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