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