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