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