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