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