GitMonitor.vala
[gitlive] / GitMonitor.vala
1
2  
3
4 public class GitMonitorQueue : MonitorNamePathDir {
5                 // name = basename
6                 // path = full path..
7                 // dir = dir path
8         
9                 public string gitpath;
10                 public string vdir;  // relative path (within git)
11                 public string vname;  // relative filename (within git)
12                 public string message ; // for commit
13                 public bool commit_all;
14                  
15                 public GitMonitorQueue(MonitorNamePathDir f) {
16
17                         base(f.name, f.path, f.dir);
18  
19                         this.message = "";
20                         this.commit_all = false;
21                         
22                         var vpath_ar = this.dir.substring(GitMonitor.gitlive.length +1).split("/", 0);
23                         
24                         if (vpath_ar[0].length < 1) {
25
26                                 this.gitpath = "";
27                                 this.vdir = "";
28                                 this.vname = "";
29                         }        
30
31
32                         this.gitpath = GitMonitor.gitlive + "/" + vpath_ar[0];
33                         
34                         string[]  vpath = {};
35                         for (var i = 1; i< vpath_ar.length; i++) {
36                                 vpath += vpath_ar[i];
37                         }
38
39                         this.vdir =  string.joinv("/", vpath);
40
41                         this.vname =  this.vdir + (this.vdir.length > 0 ? "/" : "") + this.name;
42 /*
43                         stdout.printf(
44                                         "NEW GitMonitorQueue\nname: %s\npath: %s\ndir: %s\n" + 
45                                         "gitpath: %s\nvdir: %s\nvname: %s\n",
46                                         this.name, this.path, this.dir,
47                                         this.gitpath, this.vdir, this.vname
48                         );
49 */
50
51                         //f.repo = new imports.Scm.Git.Repo({ repopath: f.gitpath })
52                 
53                 
54                 }
55
56                 public bool shouldIgnore()
57                 {
58                         
59                          
60                         // vim.. what a seriously brain dead program..
61                         if (this.name == "4913") {
62                                 return true;
63                         }
64                         
65                         if (this.name[0] == '.') {
66                                 // except!
67                                 if (this.name == ".htaccess") {
68                                         return false;
69                                 }
70                                 
71                                 return true;
72                         }
73                         
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() {
183                 this.paused = true;
184                 // what does this do to the old one...
185                 this.queue = new Array<GitMonitorQueue> ();
186                 StatusIconA.statusicon.pauseError();
187
188         }
189
190  
191         public new void pause() {
192                 this.paused = true;
193                 // what does this do to the old one...
194                 this.queue = new Array<GitMonitorQueue> ();
195                 StatusIconA.statusicon.pause();
196
197         }
198         
199         public new void resume () {
200                 this.paused = false;
201                 this.queue = new Array<GitMonitorQueue> ();
202                 StatusIconA.statusicon.resume();
203                 
204                 
205         }
206         /**
207          * Start the monitoring
208          * and run the queue every 500 milliseconds..
209          *
210          */
211         public new void start() {
212                 StatusIconA.statusicon.refreshing();
213                 
214                  
215                 this.lastAdd = new DateTime.now(new TimeZone.local()); 
216                 
217                 Timeout.add_full(Priority.LOW, 500, () => {
218                         //stdout.printf("GitMonitor.start :: top.length = %u\n", this.top.length);
219                         // call this.monitor on each of 'top'
220                         for(int i = 0; i < this.top.length ; i++) {
221
222                                 this.monitor(this.top.index(i) );
223                         }
224                         StatusIconA.statusicon.resume();
225                          
226                    
227                         
228                         try {
229
230                           
231                                 var notification = new Notify.Notification(
232                                         "Git Live",
233                                         "%s\nMonitoring %u Directories".printf(GitMonitor.gitlive, this.monitors.length), 
234                                          "dialog-information"
235                                 );
236                 
237                                 notification.set_timeout(5);
238                                 notification.show();
239                         } catch(Error e) {
240                                 print("Error %s\n",e.message);
241                         }
242                         return false; // do not keep doing this..
243
244                 });
245                 
246
247                 Timeout.add_full(Priority.LOW, 1000, () => {
248                         //TIMEOUT", _this.queue.length , _this.queueRunning].join(', '));
249
250                         //stdout.printf("QL %u: QR: %d\n", this.queue.length, this.queueRunning ? 1 : 0);
251                         if (this.queue.length < 1  || this.queueRunning) {
252                                 return true;
253                         }
254                         
255                         var last = -1 * this.lastAdd.difference(new DateTime.now(new TimeZone.local()));
256  
257                         // stdout.printf("LAST RUN: %s (expect %s) \n" ,
258                         //         last.to_string(),   (5 * TimeSpan.SECOND).to_string() );
259  
260                         if (last < 5 * TimeSpan.SECOND) { // wait 5 seconds before running. ????
261                                 return true;
262                         }
263                         //_this.lastAdd = new Date();
264                         //return 1;
265                 
266                         this.runQueue();
267                         return true; //
268                 });
269                  
270         }
271
272
273         public new void stop() {
274                 StatusIconA.statusicon.pause();
275                 base.stop();
276         }
277         
278         
279         public new void monitor (string path,  int depth = 0)
280         {
281                 
282                 //var depth = typeof(depth) == 'number'  ? depth *1 : 0;
283                 
284                  
285                 // if we are not at top level.. and there is a .git directory  (it's a submodule .. ignore) 
286                 if (depth > 1 && FileUtils.test(path + "/.git" , FileTest.IS_DIR)) {
287                         return;
288                 }
289                 
290                 if (depth == 1) {
291                         // FIXME - check if repo is flagged as not autocommit..
292                         //var repo = imports.Scm.Repo.Repo.get(path);
293                         //if (!repo || !repo.autocommit()) {
294                         //    return;
295                         //} 
296                 }
297                 
298                 
299                 // check if the repo is to be monitored.
300                 //print("PATH : " + path);
301                 
302                 
303                 base.monitor(path, depth);
304         }
305
306         
307
308         /**
309          * run the queue.
310          * - pulls the items off the queue 
311          *    (as commands run concurrently and new items may get added while it's running)
312          * - runs the queue items
313          * - pushes upstream.
314          * 
315          */
316         public void runQueue()
317         {
318                 
319                 if (this.paused) {
320                         return;
321                 }
322                 print("GitMonitor.runQueue\n");
323
324                 this.queueRunning = true;
325
326                 var cmds = new Array<GitMonitorQueue>();
327
328                 for(var i = 0; i < this.queue.length; i++) {
329                         cmds.append_val(this.queue.index(i));
330                 }
331
332                 this.queue = new Array<GitMonitorQueue>();// empty queue!
333
334                 
335                 string[] success = {};
336                 string[] failure = {};
337            //var repos = new Array<GitRepo>(); //??
338                 //var done = new Array<GitMonitorQueue>();
339                 
340                 // first build a array of repo's to work with
341                 var repo_list = new Array<GitRepo>();
342                 
343                 // pull and group.
344                 
345                 //print(JSON.stringify(cmds));
346                 // make sure nothing get's added to the queue where we are doing this..
347
348                 this.paused = true;
349
350                 print("GitMonitor.runQueue - creating repos\n");
351                 
352                 for(var i = 0; i < cmds.length; i++) {
353                    
354                         var cmd = cmds.index(i);
355                 
356                         var gitpath = cmd.gitpath; 
357                         stdout.printf("GitMonitor.runQueue - finding %s\n", cmd.gitpath);
358                 
359                         var ix  = GitRepo.indexOf(repo_list,  cmd.gitpath);
360                         if (ix < 0) {
361                                 repo_list.append_val(new GitRepo( gitpath ));
362                                 ix = GitRepo.indexOf(repo_list,  cmd.gitpath);
363                         }
364                         stdout.printf("GitMonitor.runQueue - adding to repolist %d\n", ix);
365
366                         //if (typeof(repo_list[gitpath]) == 'undefined') {
367                         //    repo_list[gitpath] = new imports.Scm.Git.Repo.Repo( { repopath : gitpath });
368                         //    repo_list[gitpath].cmds = [];
369                          //   repo_list[gitpath].pull();
370                         //}
371                         repo_list.index(ix).cmds.append_val(cmd);
372
373                 }
374                 this.paused = false;
375                 // build add, remove and commit message list..
376
377                 print("GitMonitor.runQueue - creating actions\n");
378                 
379                 for(var i = 0;i < repo_list.length;i++) {
380          
381                         var repo = repo_list.index(i);
382
383                         var add_files = new Array<GitMonitorQueue>();
384                         var add_files_f = new Array<GitMonitorQueue>();
385                         var remove_files = new Array<GitMonitorQueue>();
386                         var messages = new Array<GitMonitorQueue>();
387                         //print(JSON.stringify(repo.cmds,null,4));
388                         
389                         for(var ii = 0;ii < repo.cmds.length;ii++) {
390                                 var cmd = repo.cmds.index(ii);
391         
392                                 
393                                 switch(cmd.action) {
394                                         case "add" :
395                                                 
396                                                 if (GitMonitorQueue.indexOfAdd(add_files, cmd.vname) > -1) {
397                                                    break;
398                                                 }
399                                                 
400                                                 add_files.append_val(cmd);
401                                                 break;
402                                         
403                                         case "rm":
404                                                 if (GitMonitorQueue.indexOfAdd(remove_files, cmd.vname) > -1 ) {
405                                                    break;
406                                                 }
407                                                 
408                                                 // if file exists, do not try and delete it.
409                                                 if (FileUtils.test(cmd.fullpath(), FileTest.EXISTS)) {
410                                                         break;
411                                                 }
412                                                 
413                                                 remove_files.append_val(cmd);
414                                                 break;
415                                         
416                                         case "commit" :
417                                                 if (GitMonitorQueue.indexOfMessage(messages, cmd.message) > -1 ) {
418                                                    break;
419                                                 }
420                                                 messages.append_val(cmd);
421                                                 
422                                                 break;
423                                         default:
424                                                 stdout.printf("Opps unmatched action %s\n", cmd.action);
425                                                 break;
426                                 } 
427                         }
428                         print( "ADD : %s\n", GitMonitorQueue.queueArrayToString(add_files));
429                         print( "REMOVE FILES: %s\n", GitMonitorQueue.queueArrayToString(remove_files));
430                         //repo.debug = 1;
431                         // these can fail... at present... as we wildcard stuff.
432                    
433                         // make sure added files do not get removed.. ?? 
434                         /*
435                         var remove_files_f = new Array<GitMonitorQueue>();
436                         for(var ii = 0;ii < remove_files.length;ii++) {
437                                 if (GitMonitorQueue.indexOfAdd(add_files,  remove_files.index(ii).vname) > -1 ) {
438                                          continue;
439                                 }
440                                 remove_files_f.append_val(remove_files.index(ii));
441                         };
442                         stdout.printf("REMOVE : %u files\n"  , remove_files_f.length);
443                         */
444                         
445                         // if file was added, then removed, 
446                         var remove_files_f = new Array<GitMonitorQueue>();
447                         for(var ii = 0;ii < remove_files.length;ii++) {
448                                 
449                                 
450                                 
451                                 if (GitMonitorQueue.indexOfAdd(add_files,  remove_files.index(ii).vname) > -1 ) {
452                                         // in add and remove - do not remvove
453                                         continue;
454                                 }
455                                 remove_files_f.append_val(remove_files.index(ii));
456                         };
457                         for(var ii = 0;ii < add_files.length;ii++) {
458                                 if (GitMonitorQueue.indexOfAdd(remove_files,  add_files.index(ii).vname) > -1 ) {
459                                         // the add file is in the remove list, and it does not exist - do not add it..
460                                         print("check exists ? %s\n",add_files.index(ii).fullpath());
461                                         
462                                         if (!FileUtils.test(add_files.index(ii).fullpath(), FileTest.EXISTS)) {
463                                                         continue;
464                                         }
465                                          
466                                 }
467                                 
468                                 
469                                 
470                                 add_files_f.append_val(add_files.index(ii));
471                         };
472                         
473                         print( "ADD : %s\n", GitMonitorQueue.queueArrayToString(add_files_f));
474                         print( "REMOVE FILES: %s\n", GitMonitorQueue.queueArrayToString(remove_files_f));
475                    
476                         
477                         // make sure monitoring is paused so it does not recursively pick up
478                         // deletions
479                         try {
480                                 repo.pull();
481                         } catch(Error e) {
482                                 failure +=  e.message;
483                                 print("Pull failed:\n");
484                         }
485                         
486                         
487                         // -- DO STUFF..            
488                         try {
489                                 repo.add(add_files_f);
490                         } catch(Error e) {
491                                 failure +=  e.message;
492                                 print("Add failed:\n");
493                         }  
494                         try {
495                                  repo.remove(remove_files_f);
496                         } catch(Error e) {
497                                 failure +=  e.message;
498                                 print("Remove failed:\n");
499                         }  
500
501                         this.paused = false;
502                         
503                         
504                         try { 
505                                 success += repo.commit(
506                                         GitMonitorQueue.messageToString(messages),
507                                         add_files_f
508                                 );
509                                 success += repo.push();
510
511                         } catch(Error e) {
512                                 failure += e.message;
513                                 print("Push failed:\n");
514                                 
515                         }   
516                 }
517                 
518                 
519                 // finally merge all the commit messages.
520                  
521                 try {
522                         // catch notification failures.. so we can carry on..
523                         if (success.length > 0) {
524
525                                 
526                                 var notification = new Notify.Notification(
527                                         "Git Live Commited",
528                                         string.joinv("\n",success),
529                                          "dialog-information"
530                                         
531                                 );
532         
533                                 notification.set_timeout(5);
534                                 notification.show();   
535                         }
536                         
537                         if (failure.length > 0) {
538
539                                 var notification = new Notify.Notification(
540                                           "Git Live ERROR!!",
541                                         string.joinv("\n",failure),
542                                         "dialog-information"
543                                         
544                                 );
545                                 
546         
547                                 notification.set_timeout(10); // show errros for longer
548                                 notification.show();
549                                 
550                                 this.pauseError();   
551                         }
552                 } catch(Error e) {
553                         print(e.message);
554                         
555                 }
556                 this.queueRunning = false;
557         }
558         
559
560
561         
562
563         //string[] just_created;
564  
565  
566
567
568
569    
570
571
572         public override  void onChanged(MonitorNamePathDir src) 
573         { 
574                 print("GitMonitor.onChanged\n");        
575                 return; // always ignore this..?
576                 //this.parsePath(src);
577         }
578         
579
580  
581         /**
582          *  results in  git add  + git commit..
583          *
584          */
585         public override void onChangesDoneHint(MonitorNamePathDir src)  
586         { 
587                 print("GitMonitor.onChangedHint\n");        
588                 if (this.paused) {
589                         return;
590                 }
591                         
592
593                 this.lastAdd = new DateTime.now(new TimeZone.local()); 
594                 var cmd = new GitMonitorQueue(src);
595                 if (cmd.shouldIgnore()) {
596                         return;
597                 }
598                 
599            
600                 //var add_it = false;
601                 /*
602                 if (this.is_just_created(cmd.path)) {
603                         
604                 if (typeof(this.just_created[src.path]) !='undefined') {
605                         delete this.just_created[src.path];
606                         
607                         this.queue.push( 
608                                 [ src.gitpath,  'add', src.vpath ],
609                                 [ src.gitpath,  'commit',    { message: src.vpath} ] 
610                                 
611                         );
612                  
613                         return;
614                 }
615                 */
616                 cmd.action = "add";
617                 this.queue.append_val(cmd);
618
619                 cmd = new GitMonitorQueue(src);
620                 cmd.action = "commit";
621                 cmd.message = cmd.vname;
622                 this.queue.append_val(cmd);
623  
624                  
625         }
626         public override  void onDeleted(MonitorNamePathDir src) 
627    { 
628                 print("GitMonitor.onDeleted\n");        
629                 if (this.paused) {
630                         return;
631                 }
632                 this.lastAdd = new DateTime.now(new TimeZone.local()); 
633                 var cmd = new GitMonitorQueue(src);
634                 if (cmd.shouldIgnore()) {
635                         return;
636                 }
637                 // should check if monitor needs removing..
638                 // it should also check if it was a directory.. - so we dont have to commit all..
639                 cmd.action = "rm";
640                 this.queue.append_val(cmd);
641
642                 cmd = new GitMonitorQueue(src);
643                 cmd.action = "commit";
644                 cmd.message = cmd.vname;
645                 cmd.commit_all = true;
646
647                 this.queue.append_val(cmd);
648  
649         }
650         public override  void onCreated(MonitorNamePathDir src) {
651                 print("GitMonitor.onCreated\n");        
652                 if (this.paused) {
653                         return;
654                 }
655                 this.lastAdd = new DateTime.now(new TimeZone.local()); 
656                 var cmd = new GitMonitorQueue(src);
657                 if (cmd.shouldIgnore()) {
658                         return;
659                 }
660
661                 if (!FileUtils.test(src.path, GLib.FileTest.IS_DIR)) {
662                    // this.just_created[src.path] = true;
663                         return; // we do not handle file create flags... - use done hint.
664                 }
665                 // directory has bee created
666                 this.monitor(src.path);
667                 //this.top.append_val(src.path);
668                 //this.monitor(src.path );
669
670
671 // -- no point in adding a dir.. as git does not handle them...
672 //        this.queue.push( 
673   //          [ src.gitpath, 'add' , src.vpath,  { all: true } ],
674  //           [ src.gitpath, 'commit' , { all: true, message: src.vpath} ]
675   //          
676    //     );
677
678         }
679
680         public  override void onAttributeChanged(MonitorNamePathDir src) { 
681                 print("GitMonitor.onAttributeChanged\n");        
682                 if (this.paused) {
683                         return;
684                 }
685                 if (src.dir == GitMonitor.gitlive) {
686                    return; // attribute on top level..
687                 }
688                 
689                 this.lastAdd = new DateTime.now(new TimeZone.local()); 
690                 var cmd = new GitMonitorQueue(src);
691                 if (cmd.shouldIgnore()) {
692                         return;
693                 }
694                 cmd.action = "add";
695                 this.queue.append_val(cmd);
696
697                 cmd = new GitMonitorQueue(src);
698                 cmd.action = "commit";
699                 cmd.message = "Attribute changed " + cmd.vname;
700                 this.queue.append_val(cmd);
701         }
702  
703    public  override void onMoved(MonitorNamePathDir src,MonitorNamePathDir dest)  
704         { 
705                 print("GitMonitor.onMoved\n");        
706                 if (this.paused) {
707                         return;
708                 }
709                 this.lastAdd = new DateTime.now(new TimeZone.local()); 
710                 var cmd_s = new GitMonitorQueue(src);
711
712                 var cmd_d = new GitMonitorQueue(dest);
713    
714                 
715                 if (cmd_d.gitpath != cmd_s.gitpath) {
716                         this.onDeleted(src);
717                         this.onCreated(dest);
718                         this.onChangesDoneHint(dest);
719                         return;
720                 }
721                 // needs to handle move to/from unsupported types..
722                 
723                 if (cmd_s.shouldIgnore()) {
724                         this.onCreated(dest);
725                         this.onChangesDoneHint(dest);
726                         return;
727
728                 }
729                 if (cmd_d.shouldIgnore()) {
730                         
731                         this.onDeleted(src);
732  
733
734                         return;
735                 }
736                 
737                 
738                 print("RM: %s\n", cmd_s.vname);
739                 cmd_s.action = "rm";
740                 this.queue.append_val(cmd_s);
741
742                 
743                 
744                 print("ADD: %s\n", cmd_d.vname);
745                 cmd_d.action = "add";
746                 this.queue.append_val(cmd_d);
747
748
749                 var cmd = new GitMonitorQueue(dest);
750                 cmd.action = "commit";
751                 cmd.message = "MOVED " + cmd_s.vname + " to " + cmd_d.vname;
752                 if (GitMonitorQueue.queueHas(this.queue, cmd_s, "add")) {
753                         cmd.message = cmd_d.vname;
754                 }
755                 
756                 this.queue.append_val(cmd);
757
758
759                  
760         }
761            
762 }