GitMonitor.vala
[gitlive] / GitMonitor.vala
1
2  
3
4 public class GitMonitorQueue : MonitorNamePathDir {
5         // name = basename
6         // path = full path..
7         // dir = dir path
8     
9         public string gitpath;
10         public string vpath;  // relative path (within git)
11         public string vname;  // relative filename (within git)
12         public string message ; // for commit
13         public bool commit_all;
14         
15
16
17
18
19         public GitMonitorQueue(MonitorNamePathDir f) {
20
21             base(f.name, f.path, f.dir);
22
23
24             this.message = "";
25             this.commit_all = false;
26  
27            
28             var vpath_ar = this.path.substring(GitMonitor.gitlive.length +1).split("/", 0);
29             
30             this.gitpath = GitMonitor.gitlive + "/" + vpath_ar[0];
31             
32             string[]  vpath = {};
33             for (var i = 1; i< vpath_ar.length; i++) {
34                 vpath += vpath_ar[i];
35             }
36
37             this.vpath =  string.joinv("/", vpath);
38
39             this.vname =  this.vpath + (this.vpath.length > 0 ? "/" : "") + this.name;
40             //f.repo = new imports.Scm.Git.Repo({ repopath: f.gitpath })
41         
42         
43         }
44
45         public bool shouldIgnore(GitMonitor gm)
46         {
47             
48             
49             
50             // vim.. what a seriously brain dead program..
51             if (this.name == "4913") {
52                 return true;
53             }
54             
55             if (this.name[0] == '.') {
56                 // except!
57                 if (this.name == ".htaccess") {
58                     return false;
59                 }
60                 
61                 return true;
62             }
63             //if (f.name.match(/~$/)) {
64             //    return true;
65             //}
66             //if (f.name.match(/^nbproject/)) {
67             //    return true;
68             //}
69             // ignore anything in top level!!!!
70             if (this.vpath.length < 1) {
71                 return true;
72             }
73             
74             return false;
75         }
76         
77         /** -- statics --*/
78         
79         public static int indexOfAdd( Array<GitMonitorQueue> add_files, string add) {
80             for(var i =0; i < add_files.length; i++) {
81                 if (add_files.index(i).vname == add) {
82                     return i;
83                 }
84             }
85             return -1;
86         }
87         public static  int indexOfMessage(Array<GitMonitorQueue> messages, string message)  {
88             for(var i =0; i < messages.length; i++) {
89                 if (messages.index(i).message == message) {
90                     return i;
91                 }
92             }
93             return -1;
94         }
95         public static string messageToString(Array<GitMonitorQueue> messages ) {
96             string[] ret = {};
97             for(var i =0; i < messages.length; i++) {
98                 ret+= messages.index(i).message;
99             }
100             return string.joinv("\n",ret);
101         }
102
103 }
104
105
106
107 public class GitMonitor : Monitor
108 {
109
110  
111     /**
112      * @property {String} the "gitlive" directory, normally ~/gitlive
113      *  dset by OWNER... - we should do this as a CTOR.
114      *  
115      */
116     public static string gitlive = "";
117     
118     
119     public Array<GitMonitorQueue> queue ;
120     public bool queueRunning = false;
121     
122     public DateTime lastAdd;
123      
124      
125     public new void pause() {
126         this.paused = true;
127         // what does this do to the old one...
128         this.queue = new Array<GitMonitorQueue> ();
129         StatusIconA.statusicon.set_from_stock( Gtk.Stock.MEDIA_PAUSE );
130
131     }
132     
133     public new void resume () {
134         this.paused = false;
135         this.queue = new Array<GitMonitorQueue> ();
136         StatusIconA.statusicon.set_from_stock( Gtk.Stock.MEDIA_PLAY );
137         
138         
139     }
140     /**
141      * Start the monitoring
142      * and run the queue every 500 milliseconds..
143      *
144      */
145     public new void start() {
146         StatusIconA.statusicon.set_from_stock( Gtk.Stock.REFRESH );
147         
148          
149         this.lastAdd = new DateTime.now(new TimeZone.local()); 
150         
151         Timeout.add_full(Priority.LOW, 500, () => {
152
153             // call this.monitor on each of 'top'
154             for(int i = 0; i < this.top.length ; i++) {
155                 this.monitor(this.top.index(i) );
156             }
157             StatusIconA.statusicon.set_from_stock( Gtk.Stock.MEDIA_PLAY );
158              
159            
160             
161             try {
162
163               
164                 var notification = new Notify.Notification(
165                     "Git Live",
166                     "%s\nMonitoring %d Directories".printf(GitMonitor.gitlive, this.monitors.length), 
167                      "dialog-information"
168                 );
169         
170                 notification.set_timeout(5);
171                 notification.show();
172             } catch(Error e) {
173                 print(e.message);
174             }
175
176         });
177         
178         Timeout.add_full(Priority.LOW, 1000, () => {
179             //TIMEOUT", _this.queue.length , _this.queueRunning].join(', '));
180             if (this.queue.length < 1  || this.queueRunning) {
181                 return true;
182             }
183
184             var last = this.lastAdd.difference(new DateTime.now(new TimeZone.local()));
185
186             
187             //print("LAST RUN?" + last);
188             
189             if (last < 5 * TimeSpan.SECOND) { // wait 5 seconds before running. ????
190                 return true;
191             }
192             //_this.lastAdd = new Date();
193             //return 1;
194         
195             this.runQueue();
196             return true;
197         },null,null);
198         
199       
200     }
201
202
203     public new void stop() {
204         StatusIconA.statusicon.set_from_stock( Gtk.Stock.MEDIA_PAUSE );;
205         base.stop();
206     }
207     
208     
209     public new void monitor (string path,  int depth = 0)
210     {
211         
212         //var depth = typeof(depth) == 'number'  ? depth *1 : 0;
213         
214          
215         // if we are not at top level.. and there is a .git directory  (it's a submodule .. ignore) 
216         if (depth > 1 && FileUtils.test(path + "/.git" , FileTest.IS_DIR)) {
217             return;
218         }
219         
220         if (depth == 1) {
221             // FIXME - check if repo is flagged as not autocommit..
222             //var repo = imports.Scm.Repo.Repo.get(path);
223             //if (!repo || !repo.autocommit()) {
224             //    return;
225             //} 
226         }
227         
228         
229         // check if the repo is to be monitored.
230         //print("PATH : " + path);
231         
232         
233         base.monitor(path, depth);
234     }
235
236     
237
238     /**
239      * run the queue.
240      * - pulls the items off the queue 
241      *    (as commands run concurrently and new items may get added while it's running)
242      * - runs the queue items
243      * - pushes upstream.
244      * 
245      */
246     public void runQueue()
247     {
248         
249         if (this.paused) {
250             return;
251         }
252         this.queueRunning = true;
253
254         var cmds = new Array<GitMonitorQueue>();
255         for(var i = 0; i < this.queue.length; i++) {
256             cmds.append_val(this.queue.index(i));
257         }
258
259         this.queue = new Array<GitMonitorQueue>();// empty queue!
260
261         
262         string[] success = {};
263         string[] failure = {};
264         var repos = new Array<GitRepo>(); //??
265         var done = new Array<GitMonitorQueue>();
266         
267         // first build a array of repo's to work with
268         var repo_list = new Array<GitRepo>();
269         
270         // pull and group.
271         
272         //print(JSON.stringify(cmds));
273         this.paused = true;
274         
275         for(var i = 0; i < cmds.length; i++) {
276            
277         
278             var gitpath = cmd.gitpath; 
279             var ix  = GitRepo.indexOf(this.repos,  cmd.gitpath);
280             if (ix < 0) {
281                 repo_list.append_val(new GitRepo( gitpath ));
282                 ix = GitRepo.indexOf(this.repos,  cmd.gitpath);
283             }
284             
285
286             //if (typeof(repo_list[gitpath]) == 'undefined') {
287             //    repo_list[gitpath] = new imports.Scm.Git.Repo.Repo( { repopath : gitpath });
288             //    repo_list[gitpath].cmds = [];
289              //   repo_list[gitpath].pull();
290             //}
291             repo_list.index(ix).cmds.append_val(cmd);
292
293         }
294         this.paused = false;
295         // build add, remove and commit message list..
296         
297         for(var i = 0;i < repo_list.length;i++) {
298     
299
300             var repo = repo_list.index(i);
301
302             var add_files = new Array<GitMonitorQueue>();
303             var remove_files = new Array<GitMonitorQueue>();
304             var messages = new Array<GitMonitorQueue>();
305             //print(JSON.stringify(repo.cmds,null,4));
306             
307             for(var ii = 0;ii < repo.cmds.length;ii++) {
308                 var cmd = repo.cmds.index(ii);
309     
310                 
311                 switch(cmd.action) {
312                     case "add" :
313                         
314                         if (GitMonitorQueue.indexOfAdd(add_files, cmd.vname) > -1) {
315                            break;
316                         }
317         
318                         
319                         add_files.append_val(cmd);
320                         break;
321                     
322                     case "rm":
323                         if (GitMonitorQueue.indexOfAdd(add_files, cmd.rm) > -1 ) {
324                            break;
325                         }
326                         
327                         // if file exists, do not try and delete it.
328                         if (FileUtils.test(cmd.rm, FileTest.EXISTS)) {
329                             break;
330                         }
331                         
332                         remove_files.append_val(cmd);
333                         break;
334                     
335                     case "commit" :
336                         if (GitMonitorQueue.indexOfMessage(messages, cmd.message) > -1 ) {
337                            break;
338                         }
339                          
340                         messages.append_val(cmd);
341                         
342                         break;
343                     default:
344                         print("Opps unmatched action");
345                         break;
346                 } 
347             }
348             
349             //repo.debug = 1;
350             // these can fail... at present... as we wildcard stuff.
351             stdout.printf("ADD : %d files"  , add_files.length);
352             
353             // make sure added files do not get removed..
354
355             var remove_files_f = new Array<GitMonitorQueue>();
356             for(var ii = 0;ii < remove_files.length;ii++) {
357                 if (GitMonitorQueue.indexOfAdd(add_files,  remove_files.index(ii).rm) > -1 ) {
358                      continue;
359                 }
360                 remove_files_f.append_val(remove_files.index(ii));
361             };
362             stdout.printf("REMOVE : %d files"  , remove_files.length);
363              
364             // make sure monitoring is paused so it does not recursively pick up
365             // deletions
366             
367             // -- DO STUFF..
368             try {
369                 repo.add(add_files);
370             } catch(Error e) {
371                 failure +=  e.message;
372                 
373             }  
374             try {
375             repo.remove(remove_files_f);
376             this.paused = false;
377             
378             
379             try { 
380                 success += repo.commit(
381                     GitMonitorQueue.messageToString(messages),
382                     add_files  
383                 );
384                 success += repo.push();
385
386             } catch(Error e) {
387                 failure += e.message;
388                 
389             }   
390         }
391         
392         // finally merge all the commit messages.
393          
394         try {
395             // catch notification failures.. so we can carry on..
396             if (success.length) {
397
398                 
399                 var notification = new Notify.Notification(
400                     "Git Live Commited",
401                     string.joinv("\n",success),
402                      "dialog-information"
403                     
404                 );
405     
406                 notification.set_timeout(5);
407                 notification.show();   
408             }
409             
410             if (failure.length) {
411
412                 var notification = new Notify.Notification({
413                     summary: "Git Live ERROR!!",
414                     string.joinv("\n",failure),
415                     "dialog-information"
416                     
417                 });
418     
419                 notification.set_timeout(5); // show errros for longer
420                 notification.show();   
421             }
422         } catch(Error e) {
423             print(e.message);
424             
425         }
426         this.queueRunning = false;
427     }
428     
429
430
431     
432
433     //string[] just_created;
434  
435  
436
437
438
439    
440
441
442     public void onChanged(MonitorNamePathDir src) 
443     { 
444         return; // always ignore this..?
445         //this.parsePath(src);
446     }
447     
448
449  
450     /**
451      *  results in  git add  + git commit..
452      *
453      */
454     public void onChangesDoneHint(MonitorNamePathDir src)  
455     { 
456         
457         if (this.paused) {
458             return true;
459         }
460             
461
462         this.lastAdd = new DateTime.now(new TimeZone.local()); 
463         var cmd = new GitMonitorQueue(src);
464         if (cmd.shouldIgnore()) {
465             return;
466         }
467         
468        
469         var add_it = false;
470         /*
471         if (this.is_just_created(cmd.path)) {
472             
473         if (typeof(this.just_created[src.path]) !='undefined') {
474             delete this.just_created[src.path];
475             
476             this.queue.push( 
477                 [ src.gitpath,  'add', src.vpath ],
478                 [ src.gitpath,  'commit',    { message: src.vpath} ] 
479                 
480             );
481          
482             return;
483         }
484         */
485
486         this.queue.append_val(cmd);
487
488         var cmd = new GitMonitorQueue(src);
489         cmd.action = "commit";
490         cmd.message = src.vpath;
491         this.queue.append_val(cmd);
492  
493          
494     }
495     public void onDeleted(MonitorNamePathDir src) 
496    { 
497         if (this.paused) {
498             return true;
499         }
500         this.lastAdd = new DateTime.now(new TimeZone.local()); 
501         var cmd = new GitMonitorQueue(src);
502         if (cmd.shouldIgnore()) {
503             return;
504         }
505         // should check if monitor needs removing..
506         // it should also check if it was a directory.. - so we dont have to commit all..
507         cmd.action = "rm";
508         cmd.rm = src.vpath;
509         this.queue.append_val(cmd);
510
511         var cmd = new GitMonitorQueue(src);
512         cmd.action = "commit";
513         cmd.message = src.vpath;
514         cmd.commit_all = true;
515
516         this.queue.append_val(cmd);
517  
518     }
519     public void onCreated(MonitorNamePathDir src) {
520
521         if (this.paused) {
522             return true;
523         }
524         this.lastAdd = new DateTime.now(new TimeZone.local()); 
525         var cmd = new GitMonitorQueue(src);
526         if (cmd.shouldIgnore()) {
527             return;
528         }
529
530         if (!FileUtils.test(src.path, GLib.FileTest.IS_DIR)) {
531            // this.just_created[src.path] = true;
532             return; // we do not handle file create flags... - use done hint.
533         }
534         // directory has bee created
535         this.monitor(src.path);
536         this.top.append_val(src.path);
537         this.monitor(src.path );
538
539
540 // -- no point in adding a dir.. as git does not handle them...
541 //        this.queue.push( 
542   //          [ src.gitpath, 'add' , src.vpath,  { all: true } ],
543  //           [ src.gitpath, 'commit' , { all: true, message: src.vpath} ]
544   //          
545    //     );
546
547     }
548
549     public void onAttributeChanged(MonitorNamePathDir src) { 
550
551         if (this.paused) {
552             return true;
553         }
554         this.lastAdd = new DateTime.now(new TimeZone.local()); 
555         var cmd = new GitMonitorQueue(src);
556         if (cmd.shouldIgnore()) {
557             return;
558         }
559         cmd.action = "add";
560         this.queue.append_val(cmd);
561
562         var cmd = new GitMonitorQueue(src);
563         cmd.action = "commit";
564         cmd.message = "Attribute changed " + cmd.vpath;
565         this.queue.append_val(cmd);
566     }
567
568
569    public void onMoved(MonitorNamePathDir src,MonitorNamePathDir dest)  
570     { 
571         this.lastAdd = new DateTime.now(new TimeZone.local()); 
572         var cmd_s = new GitMonitorQueue(src);
573
574         var cmd_d = new GitMonitorQueue(src);
575    
576         
577         if (cmd_d.gitpath != cmd_s.gitpath) {
578             this.onDeleted(src);
579             this.onCreated(dest);
580             this.onChangedDoneHint(dest);
581             return;
582         }
583         // needs to handle move to/from unsupported types..
584         
585         if (this.shouldIgnore(src)) {
586             this.onCreated(dest);
587             this.onChangedDoneHint(dest);
588             return;
589
590         }
591         if (this.shouldIgnore(dest)) {
592             
593             this.onDeleted(src);
594  
595
596             return;
597         }
598         
599         cmd_s.action = "rm";
600         this.queue.append_val(cmd_s);
601
602
603
604
605         cmd_d.action = "add";
606         this.queue.append_val(cmd_d);
607
608
609         var cmd = new GitMonitorQueue(dest);
610         cmd.action = "commit";
611         cmd.message = "MOVED " + cmd_s.vpath + " to " + cmd_d.vpath;
612         this.queue.append_val(cmd);
613
614
615          
616     }
617        
618 }