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         public Array<GitMonitorQueue> queue ;
17         public bool queueRunning = false;
18         
19         public DateTime lastAdd;
20
21  
22
23         public GitMonitor ()
24         {
25         
26                 this.queue = new Array<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.length < 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 Array<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 Array<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 new void monitor (string path,  int depth = 0)
174         {
175                 
176                 //var depth = typeof(depth) == 'number'  ? depth *1 : 0;
177                 
178                  
179                 // if we are not at top level.. and there is a .git directory  (it's a submodule .. ignore) 
180                 if (depth > 1 && FileUtils.test(path + "/.git" , FileTest.IS_DIR)) {
181                         return;
182                 }
183                 
184                 if (depth == 1) {
185                         // FIXME - check if repo is flagged as not autocommit..
186                         //var repo = imports.Scm.Repo.Repo.get(path);
187                         //if (!repo || !repo.autocommit()) {
188                         //    return;
189                         //} 
190                 }
191                 
192                 
193                 // check if the repo is to be monitored.
194                 //print("PATH : " + path);
195                 
196                 
197                 base.monitor(path, depth);
198         }
199
200         
201
202         /**
203          * run the queue.
204          * - pulls the items off the queue 
205          *    (as commands run concurrently and new items may get added while it's running)
206          * - runs the queue items
207          * - pushes upstream.
208          * 
209          */
210         public void runQueue()
211         {
212                 
213                 if (this.paused) {
214                         return;
215                 }
216                 GLib.debug("GitMonitor.runQueue\n");
217
218                 this.queueRunning = true;
219
220                 var cmds = new Array<GitMonitorQueue>();
221
222                 for(var i = 0; i < this.queue.length; i++) {
223                         cmds.append_val(this.queue.index(i));
224                 }
225
226                 this.queue = new Array<GitMonitorQueue>();// empty queue!
227
228                 
229                 string[] success = {};
230                 string[] failure = {};
231            //var repos = new Array<GitRepo>(); //??
232                 //var done = new Array<GitMonitorQueue>();
233                 
234                 // first build a array of repo's to work with
235                 var repo_list = new Array<GitRepo>();
236                 
237                 // pull and group.
238                 
239                 //print(JSON.stringify(cmds));
240                 // make sure nothing get's added to the queue where we are doing this..
241
242                 this.paused = true;
243
244                 GLib.debug("GitMonitor.runQueue - creating repos");
245                 
246                 for(var i = 0; i < cmds.length; i++) {
247                    
248                         var cmd = cmds.index(i);
249                 
250                         var gitpath = cmd.gitpath; 
251                         GLib.debug("GitMonitor.runQueue - finding %s", cmd.gitpath);
252                 
253                         var ix  = GitRepo.indexOf(repo_list,  cmd.gitpath);
254                         if (ix < 0) {
255                                 repo_list.append_val( GitRepo.get( gitpath ));
256                                 ix = GitRepo.indexOf(repo_list,  cmd.gitpath);
257                         }
258                         GLib.debug("GitMonitor.runQueue - adding to repolist %d", ix);
259
260                         //if (typeof(repo_list[gitpath]) == 'undefined') {
261                         //    repo_list[gitpath] = new imports.Scm.Git.Repo.Repo( { repopath : gitpath });
262                         //    repo_list[gitpath].cmds = [];
263                          //   repo_list[gitpath].pull();
264                         //}
265                         repo_list.index(ix).cmds.append_val(cmd);
266
267                 }
268                 this.paused = false;
269                 // build add, remove and commit message list..
270
271                 GLib.debug("GitMonitor.runQueue - creating actions");
272                 
273                 for(var i = 0;i < repo_list.length;i++) {
274          
275                         var repo = repo_list.index(i);
276
277                         var add_files = new Array<GitMonitorQueue>();
278                         var add_files_f = new Array<GitMonitorQueue>();
279                         var remove_files = new Array<GitMonitorQueue>();
280                         var messages = new Array<GitMonitorQueue>();
281                         //print(JSON.stringify(repo.cmds,null,4));
282                         
283                         for(var ii = 0;ii < repo.cmds.length;ii++) {
284                                 var cmd = repo.cmds.index(ii);
285         
286                                 if (repo.is_ignore(cmd.vname)) {
287                                         continue;
288                                 }
289         
290                                 
291                                 switch(cmd.action) {
292                                         case "add" :
293                                                 
294                                                 if (GitMonitorQueue.indexOfAdd(add_files, cmd.vname) > -1) {
295                                                    break;
296                                                 }
297                                                 
298                                                 add_files.append_val(cmd);
299                                                 break;
300                                         
301                                         case "rm":
302                                                 if (GitMonitorQueue.indexOfAdd(remove_files, cmd.vname) > -1 ) {
303                                                    break;
304                                                 }
305                                                 
306                                                 // if file exists, do not try and delete it.
307                                                 if (FileUtils.test(cmd.fullpath(), FileTest.EXISTS)) {
308                                                         break;
309                                                 }
310                                                 
311                                                 remove_files.append_val(cmd);
312                                                 break;
313                                         
314                                         case "commit" :
315                                                 if (GitMonitorQueue.indexOfMessage(messages, cmd.message) > -1 ) {
316                                                    break;
317                                                 }
318                                                 messages.append_val(cmd);
319                                                 
320                                                 break;
321                                         default:
322                                                 stdout.printf("Opps unmatched action %s\n", cmd.action);
323                                                 break;
324                                 } 
325                         }
326                         GLib.debug( "ADD : %s", GitMonitorQueue.queueArrayToString(add_files));
327                         GLib.debug( "REMOVE FILES: %s", GitMonitorQueue.queueArrayToString(remove_files));
328                         
329                         //repo.debug = 1;
330                         // these can fail... at present... as we wildcard stuff.
331                    
332                         // make sure added files do not get removed.. ?? 
333                         /*
334                         var remove_files_f = new Array<GitMonitorQueue>();
335                         for(var ii = 0;ii < remove_files.length;ii++) {
336                                 if (GitMonitorQueue.indexOfAdd(add_files,  remove_files.index(ii).vname) > -1 ) {
337                                          continue;
338                                 }
339                                 remove_files_f.append_val(remove_files.index(ii));
340                         };
341                         stdout.printf("REMOVE : %u files\n"  , remove_files_f.length);
342                         */
343                         
344                         // if file was added, then removed, 
345                         var remove_files_f = new Array<GitMonitorQueue>();
346                         for(var ii = 0;ii < remove_files.length;ii++) {
347                                 
348                                 
349                                 
350                                 if (GitMonitorQueue.indexOfAdd(add_files,  remove_files.index(ii).vname) > -1 ) {
351                                         // in add and remove - do not remvove
352                                         continue;
353                                 }
354                                 remove_files_f.append_val(remove_files.index(ii));
355                         };
356                         for(var ii = 0;ii < add_files.length;ii++) {
357                                 if (GitMonitorQueue.indexOfAdd(remove_files,  add_files.index(ii).vname) > -1 ) {
358                                         // the add file is in the remove list, and it does not exist - do not add it..
359                                         print("check exists ? %s\n",add_files.index(ii).fullpath());
360                                         
361                                         if (!FileUtils.test(add_files.index(ii).fullpath(), FileTest.EXISTS)) {
362                                                         continue;
363                                         }
364                                          
365                                 }
366                                 
367                                 
368                                 
369                                 add_files_f.append_val(add_files.index(ii));
370                         };
371                         
372                         GLib.debug( "ADD : %s", GitMonitorQueue.queueArrayToString(add_files_f));
373                         GLib.debug( "REMOVE FILES: %s", GitMonitorQueue.queueArrayToString(remove_files_f));
374                     
375                     if (add_files_f.length < 1 && remove_files_f.length < 1) {
376                                 continue;
377                     }
378                     
379                         // make sure monitoring is paused so it does not recursively pick up
380                         // deletions
381                         this.paused = true; 
382                           
383                           
384                         try {
385                                 
386                                 repo.pull();
387                         } catch(Error e) {
388                                 this.pauseError(e.message);
389                                 //failure +=  e.message;
390                                 //print("Pull failed:\n");
391                                 return;
392                         }
393                                                                         
394                         // -- DO STUFF..            
395                         try {
396                                 repo.add(add_files_f);
397                         } catch(Error e) {
398                                 this.pauseError(e.message);
399                                 return;
400                                 failure +=  e.message;
401                                 GLib.debug("Add failed:");
402                         }  
403                         try {
404                                  repo.remove(remove_files_f);
405                         } catch(Error e) {
406                                 this.pauseError(e.message);
407                                 return;
408                                 failure +=  e.message;
409                                 GLib.debug("Remove failed:");
410                         }  
411
412
413                         try { 
414                                 success += repo.commit(
415                                         GitMonitorQueue.messageToString(messages),
416                                         add_files_f
417                                 );
418                                 success += repo.push();
419
420                         } catch(Error e) {
421                         
422                                 // if the error is 'nothing to commit, working tree clean'
423                                 // then it's not an error, - just continue;
424                                 if (/nothing to commit, working tree clean/.match(e.message)) {
425                                         GLib.debug("%s",e.message);
426                                         success += e.message;
427                                         this.paused = false; 
428                                         continue;
429                                 }
430                                 
431                         
432                         
433                                 this.paused = false;                    
434                                 this.pauseError(e.message);
435                                 
436                                 return;
437                                 //failure += e.message;
438                                 //print("Push failed:\n");
439                                 
440                         }   
441                         this.paused = false;                                            
442                 }
443                 
444                 
445                 // finally merge all the commit messages.
446                  
447                 try {
448                         // catch notification failures.. so we can carry on..
449                         if (success.length > 0) {
450
451                                 
452                                 var notification = new Notify.Notification(
453                                         "Git Live Commited",
454                                         string.joinv("\n",success),
455                                          "dialog-information"
456                                         
457                                 );
458         
459                                 notification.set_timeout(5);
460                                 notification.show();   
461                         }
462                         
463                         //if (failure.length > 0) {
464
465                                 // should never get this far...
466                         //      this.pauseError();   
467                         //}
468                 } catch(Error e) {
469                         GLib.debug(e.message);
470                         
471                 }
472                 this.queueRunning = false;
473         }
474         
475
476
477         
478
479         //string[] just_created;
480  
481  
482
483
484
485    
486
487
488         public override  void onChanged(MonitorNamePathDir src) 
489         { 
490                 //print("GitMonitor.onChanged\n");        
491                 return; // always ignore this..?
492                 //this.parsePath(src);
493         }
494         
495
496  
497         /**
498          *  results in  git add  + git commit..
499          *
500          */
501         public override void onChangesDoneHint(MonitorNamePathDir src)  
502         { 
503
504                 if (this.paused) {
505                         return;
506                 }
507                 GLib.debug("GitMonitor.onChangedHint");                         
508
509                 this.lastAdd = new DateTime.now(new TimeZone.local()); 
510                 var cmd = new GitMonitorQueue(src);
511                 if (cmd.shouldIgnore()) {
512                         GLib.debug("GitMonitor.onChangedHint - ignored");
513                         return;
514                 }
515                 
516                 //var add_it = false;
517                 /*
518                 if (this.is_just_created(cmd.path)) {
519                         
520                 if (typeof(this.just_created[src.path]) !='undefined') {
521                         delete this.just_created[src.path];
522                         
523                         this.queue.push( 
524                                 [ src.gitpath,  'add', src.vpath ],
525                                 [ src.gitpath,  'commit',    { message: src.vpath} ] 
526                                 
527                         );
528                  
529                         return;
530                 }
531                 */
532                 cmd.action = "add";
533                 this.queue.append_val(cmd);
534
535                 cmd = new GitMonitorQueue(src);
536                 cmd.action = "commit";
537                 cmd.message = cmd.vname;
538                 this.queue.append_val(cmd);
539  
540                  
541         }
542         public override  void onDeleted(MonitorNamePathDir src) 
543    { 
544
545                 if (this.paused) {
546                         return;
547                 }
548                 GLib.debug("GitMonitor.onDeleted");                     
549                 this.lastAdd = new DateTime.now(new TimeZone.local()); 
550                 var cmd = new GitMonitorQueue(src);
551                 if (cmd.shouldIgnore()) {
552                         return;
553                 }
554                 // should check if monitor needs removing..
555                 // it should also check if it was a directory.. - so we dont have to commit all..
556                 cmd.action = "rm";
557                 this.queue.append_val(cmd);
558
559                 cmd = new GitMonitorQueue(src);
560                 cmd.action = "commit";
561                 cmd.message = cmd.vname;
562                 cmd.commit_all = true;
563
564                 this.queue.append_val(cmd);
565  
566         }
567         public override  void onCreated(MonitorNamePathDir src) {
568
569                 if (this.paused) {
570                         return;
571                 }
572                 GLib.debug("GitMonitor.onCreated");                     
573                 this.lastAdd = new DateTime.now(new TimeZone.local()); 
574                 var cmd = new GitMonitorQueue(src);
575                 if (cmd.shouldIgnore()) {
576                         return;
577                 }
578
579                 if (!FileUtils.test(src.path, GLib.FileTest.IS_DIR)) {
580                    // this.just_created[src.path] = true;
581                         return; // we do not handle file create flags... - use done hint.
582                 }
583                 // directory has bee created
584                 this.monitor(src.path);
585                 //this.top.append_val(src.path);
586                 //this.monitor(src.path );
587
588
589 // -- no point in adding a dir.. as git does not handle them...
590 //        this.queue.push( 
591   //          [ src.gitpath, 'add' , src.vpath,  { all: true } ],
592  //           [ src.gitpath, 'commit' , { all: true, message: src.vpath} ]
593   //          
594    //     );
595
596         }
597
598         public  override void onAttributeChanged(MonitorNamePathDir src) { 
599
600                 if (this.paused) {
601                         return;
602                 }
603                 GLib.debug("GitMonitor.onAttributeChanged %s", src.name);                       
604                 if (src.dir == GitMonitor.gitlive) {
605                    return; // attribute on top level..
606                 }
607                 
608                 this.lastAdd = new DateTime.now(new TimeZone.local()); 
609                 var cmd = new GitMonitorQueue(src);
610                 if (cmd.shouldIgnore()) {
611                         return;
612                 }
613                 cmd.action = "add";
614                 this.queue.append_val(cmd);
615
616                 cmd = new GitMonitorQueue(src);
617                 cmd.action = "commit";
618                 cmd.message = "Attribute changed " + cmd.vname;
619                 this.queue.append_val(cmd);
620         }
621  
622    public  override void onMoved(MonitorNamePathDir src,MonitorNamePathDir dest)  
623         { 
624
625                 if (this.paused) {
626                         return;
627                 }
628                 GLib.debug("GitMonitor.onMoved");                       
629                 this.lastAdd = new DateTime.now(new TimeZone.local()); 
630                 var cmd_s = new GitMonitorQueue(src);
631
632                 var cmd_d = new GitMonitorQueue(dest);
633    
634                 
635                 if (cmd_d.gitpath != cmd_s.gitpath) {
636                         this.onDeleted(src);
637                         this.onCreated(dest);
638                         this.onChangesDoneHint(dest);
639                         return;
640                 }
641                 // needs to handle move to/from unsupported types..
642                 
643                 if (cmd_s.shouldIgnore()) {
644                         this.onCreated(dest);
645                         this.onChangesDoneHint(dest);
646                         return;
647
648                 }
649                 if (cmd_d.shouldIgnore()) {
650                         
651                         this.onDeleted(src);
652  
653
654                         return;
655                 }
656                 
657                 
658                 GLib.debug("RM: %s", cmd_s.vname);
659                 cmd_s.action = "rm";
660                 this.queue.append_val(cmd_s);
661
662                 
663                 
664                 GLib.debug("ADD: %s", cmd_d.vname);
665                 cmd_d.action = "add";
666                 this.queue.append_val(cmd_d);
667
668
669                 var cmd = new GitMonitorQueue(dest);
670                 cmd.action = "commit";
671                 cmd.message = "MOVED " + cmd_s.vname + " to " + cmd_d.vname;
672                 if (GitMonitorQueue.queueHas(this.queue, cmd_s, "add")) {
673                         cmd.message = cmd_d.vname;
674                 }
675                 
676                 this.queue.append_val(cmd);
677
678
679                  
680         }
681            
682 }