sync
[gitlive] / GitRepo.vala
1
2 /**
3  * @class Scm.Git.Repo
4  *
5  * @extends Scm.Repo
6  * 
7  *
8  *
9  */
10 static GitRepo  _GitRepo; 
11  
12 public class GitRepo : Object
13 {
14      
15     public Gee.ArrayList<GitMonitorQueue> cmds;
16
17     public string name;
18     public string gitdir;
19     public string git_working_dir;
20     public bool debug = false;
21     
22     public Gee.HashMap<string,bool> ignore_files;
23     public GitBranch currentBranch;
24
25         public RooTicket? activeTicket;
26
27         public static GitRepo singleton()
28     {
29         if (_GitRepo == null) {
30             _GitRepo = new GitRepo.single();
31             _GitRepo.cache = new Gee.HashMap<string,GitRepo>();
32         }
33         return _GitRepo;
34     }
35  
36     /**
37     * index of.. matching gitpath..
38     */
39     public static int indexOf( Array<GitRepo> repos, string gitpath) {
40         // make a fake object to compare against..
41         var test_repo = GitRepo.get(gitpath);
42         
43         for(var i =0; i < repos.length; i++) {
44             if (repos.index(i).gitdir == test_repo.gitdir) {
45                 return i;
46             }
47         }
48         return -1;
49     
50     }
51     
52     public  Gee.HashMap<string,GitRepo> cache;
53     
54     
55     
56     public static   Array<GitRepo> list()
57     {
58
59         //if (GitRepo.list_cache !=  null) {
60         //    unowned  Array<GitRepo>    ret = GitRepo.list_cache;
61          //   return ret;
62         //}
63         var cache = GitRepo.singleton().cache;
64         var list_cache = new Array<GitRepo>();
65         
66         var dir = Environment.get_home_dir() + "/gitlive";
67         
68         var f = File.new_for_path(dir);
69         FileEnumerator file_enum;
70         try {
71             file_enum = f.enumerate_children(
72                 FileAttribute.STANDARD_DISPLAY_NAME + ","+ 
73                 FileAttribute.STANDARD_TYPE,
74                 FileQueryInfoFlags.NONE,
75                 null);
76         } catch (Error e) {
77             
78             return list_cache;
79             
80         }
81         
82         FileInfo next_file; 
83         
84         while (true) {
85             
86             try {
87                 next_file = file_enum.next_file(null);
88                 if (next_file == null) {
89                     break;
90                 }
91                 
92             } catch (Error e) {
93                 GLib.debug("Error: %s",e.message);
94                 break;
95             }
96          
97             //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
98             
99             if (next_file.get_file_type() !=  FileType.DIRECTORY) {
100                 next_file = null;
101                 continue;
102             }
103             
104             if (next_file.get_file_type() ==  FileType.SYMBOLIC_LINK) {
105                 next_file = null;
106                 continue;
107             }
108             
109             if (next_file.get_display_name()[0] == '.') {
110                 next_file = null;
111                 continue;
112             }
113             var sp = dir+"/"+next_file.get_display_name();
114            
115             var gitdir = dir + "/" + next_file.get_display_name() + "/.git";
116             
117             if (!FileUtils.test(gitdir, FileTest.IS_DIR)) {
118                 continue;
119             }
120             
121                 var rep =  GitRepo.get(  sp );
122                 list_cache.append_val(rep);             
123             
124         }
125     
126         return list_cache;
127         
128          
129           
130         }
131         
132         public static GitRepo get(string path) 
133         {
134                 var cache = GitRepo.singleton().cache;
135                 if (cache.has_key(path)) {
136                         return cache.get(path);
137                 }
138                 return new GitRepo(path);
139         }
140         
141     private GitRepo.single() {
142                 // used to create the signleton
143         }
144     /**
145      * constructor:
146      * 
147      * @param {Object} cfg - Configuration
148      *     (basically repopath is currently only critical one.)
149      *
150      */
151      
152     private GitRepo(string path) {
153         // cal parent?
154         this.name =   File.new_for_path(path).get_basename();
155         this.ignore_files = new Gee.HashMap<string,bool>();
156         
157         this.git_working_dir = path;
158         this.gitdir = path + "/.git";
159         if (!FileUtils.test(this.gitdir , FileTest.IS_DIR)) {
160             this.gitdir = path; // naked...
161         }
162         this.cmds = new  Gee.ArrayList<GitMonitorQueue> ();
163         
164                 var cache = GitRepo.singleton().cache;
165         //Repo.superclass.constructor.call(this,cfg);
166                 if ( !cache.has_key(path) ) {
167                         cache.set( path, this);
168         }
169         this.loadBranches();
170         this.loadActiveTicket();
171     } 
172     
173     public bool is_wip_branch()
174     {
175         return this.currentBranch.name.has_prefix("wip_");
176                 
177     }
178     
179     public bool is_autocommit ()
180     {
181         return !FileUtils.test(this.gitdir + "/.gitlive-disable-autocommit" , FileTest.EXISTS);
182     }
183     public void set_autocommit(bool val)
184     {
185
186                 var cur = this.is_autocommit();
187                 GLib.debug("SET auto commit : %s <= %s", val ? "ON" : "OFF",  cur  ? "ON" : "OFF");
188                 if (cur == val) {
189                         return; // no change..
190                 }
191                 if (!val) {
192                         FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autocommit" , "x");
193                 } else {
194                         // it exists...
195                         FileUtils.remove(this.gitdir + "/.gitlive-disable-autocommit" ); 
196                 }
197     
198     }
199     
200     public bool is_auto_branch ()
201     {
202         return FileUtils.test(this.gitdir + "/.gitlive-enable-auto-branch" , FileTest.EXISTS);
203     }
204     
205     public void set_auto_branch(bool val)
206     {
207
208                 var cur = this.is_auto_branch();
209                 GLib.debug("SET auto branch : %s <= %s", val ? "ON" : "OFF",  cur  ? "ON" : "OFF");
210                 
211                 if (cur == val) {
212                         return; // no change..
213                 }
214                 if (val) {
215                         FileUtils.set_contents(this.gitdir + "/.gitlive-enable-auto-branch" , "x");
216                 } else {
217                         // it exists...
218                         FileUtils.remove(this.gitdir + "/.gitlive-enable-auto-branch" ); 
219                 }
220     
221     }
222     public bool is_autopush ()
223     {
224         return !FileUtils.test(this.gitdir + "/.gitlive-disable-autopush" , FileTest.EXISTS);
225     }
226     public void set_autopush(bool val)
227     {
228
229                 var cur = this.is_autopush();
230                 GLib.debug("SET auto push : %s <= %s", val ? "ON" : "OFF",  cur  ? "ON" : "OFF");
231                 if (cur == val) {
232                         return; // no change..
233                 }
234                 if (!val) {
235                         FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autopush" , "");
236                 } else {
237                         // it exists...
238                         FileUtils.remove(this.gitdir + "/.gitlive-disable-autopush" ); 
239                 }
240     
241     }
242     
243     
244     
245     Gee.HashMap<string,GitBranch> branches;
246     
247     public void loadBranches()
248     {
249         this.branches = new Gee.HashMap<string,GitBranch>();
250         
251         string[] cmd = { "branch",   "--no-color", "--verbose", "--no-abbrev" , "-a"  };
252         var res = this.git( cmd );
253         var lines = res.split("\n");
254         for (var i = 0; i < lines.length ; i++) {
255                 var br = new GitBranch(this);
256                 if (!br.parseBranchListItem(lines[i])) {
257                         continue;
258                 }
259                 GLib.debug("add branch %s", br.realName());
260                  
261                 branches.set(br.realName(), br);
262                 if (br.active) {
263                         this.currentBranch = br;
264                 }
265         }
266     
267     }
268      
269     
270     
271     
272     public string branchesToString()
273     {
274         var ret = "";
275                 foreach( var br in this.branches.values) {
276                         if (br.name == "") {
277                                 continue; 
278                         }
279                         ret += ret.length > 0 ? ","  : "";
280                         ret += br.name;
281                 
282                 }
283                 return ret;
284         
285     }
286      public static void doMerges(string action, string ticket_id, string commit_message)
287     {
288        GitMonitor.gitmonitor.stop();
289        
290        var commitrevs = "";
291        var sucess = true;
292        foreach(var  repo in GitRepo.singleton().cache.values) {
293                if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
294                        var res = repo.doMerge(action,ticket_id, commit_message);
295                        if (!res) {
296                                sucess = false;
297                                continue;
298                        }
299                        commitrevs += commitrevs.length > 0 ? " " : "";
300                        commitrevs += repo.currentBranch.lastrev;
301                }
302        }
303        if (sucess && action == "CLOSE") {
304                RooTicket.singleton().getById(ticket_id).close(commitrevs);
305        }
306        GitMonitor.gitmonitor.start();
307     }
308      
309
310     public bool doMerge(string action, string ticket_id, string commit_message)
311     {
312        // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
313        // also need to decide which branch we will merge into?
314                    var ret = "";
315                    if (action == "CLOSE" || action == "LEAVE") {
316                                    
317                try {
318                    var oldbranch = this.currentBranch.name;
319                    this.setActiveTicket(null, "master");
320                            string [] cmd = { "merge",   "--squash",  oldbranch };
321                            this.git( cmd );
322                            cmd = { "commit",   "-a" , "-m",  commit_message };
323                            this.git( cmd );
324                            this.push();
325                            this.loadBranches(); // updates lastrev..
326                
327                        var notification = new Notify.Notification(
328                                "Merged branch %s to master".printf(oldbranch),
329                                "",
330                                 "dialog-information"
331                                
332                        );
333
334                        notification.set_timeout(5);
335                        notification.show();   
336                
337                // close ticket..
338                return true; 
339                
340            } catch (Error e) {
341
342                GitMonitor.gitmonitor.pauseError(e.message);
343                return false;
344            }
345            // error~?? -- show the error dialog...
346                    return false;
347        }
348        if (action == "MASTER") {
349                // merge master into ours..
350                        try {
351                        string[] cmd = { "merge",  "master" };
352                        this.git( cmd );
353                        var notification = new Notify.Notification(
354                                        "Merged code from master to %s".printf(this.currentBranch.name),
355                                        "",
356                                         "dialog-information"
357                                        
358                                );
359                                notification.set_timeout(5);
360                                notification.show();   
361                       
362                        return true;
363                        } catch (Error e) {
364                        GitMonitor.gitmonitor.pauseError(e.message);
365                        return false;
366                    }
367            }
368        if (action == "EXIT") {
369                        try {
370                        var oldbranch  = this.currentBranch.name;
371                          this.setActiveTicket(null, "master");
372                        this.loadBranches();
373                        var notification = new Notify.Notification(
374                                        "Left branch %s".printf(oldbranch),
375                                        "",
376                                         "dialog-information"
377                                        
378                                );
379                                notification.set_timeout(5);
380                                notification.show();   
381                        
382                        return true;
383                    } catch (Error e) {
384                        GitMonitor.gitmonitor.pauseError(e.message);
385
386                        return false;                   
387                    }
388                    // error~?? -- show the error dialog...
389
390        }
391        return false;
392     }
393         
394     public void loadActiveTicket()
395     {
396         this.activeTicket = null;
397         if (!FileUtils.test(this.gitdir + "/.gitlive-active-ticket" , FileTest.EXISTS)) {
398                 return;
399         }
400         string ticket_id;
401         FileUtils.get_contents(this.gitdir + "/.gitlive-active-ticket" , out ticket_id);  
402         if (ticket_id.length < 1) {
403                 return;
404                 }
405                 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
406         
407         
408     }
409     
410     
411     
412     public bool setActiveTicket(RooTicket? ticket, string branchname)
413     {
414         if (!this.createBranchNamed(branchname)) {
415                 return false;
416                 }
417                 if (ticket != null) {
418                 FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
419         } else {
420                 FileUtils.remove(this.gitdir + "/.gitlive-active-ticket" );
421         }
422         this.activeTicket = ticket;
423         return true;
424     }
425     
426     public bool createBranchNamed(string branchname)
427     {   
428                 
429
430                      if (this.branches.has_key(branchname)) {
431                         this.switchToExistingBranchNamed(branchname);
432                     
433                     } else {
434                                  this.createNewBranchNamed(branchname); 
435                             
436                     }
437                        var notification = new Notify.Notification(
438                        "Changed to branch %s".printf(branchname),
439                        "",
440                         "dialog-information"
441                        
442                );
443
444                notification.set_timeout(5);
445                notification.show();   
446        
447          
448          this.loadBranches(); // update branch list...
449          //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
450          return true;
451     }
452      bool switchToExistingBranchNamed(string branchname)
453      {
454                 var stash = false;
455                                          // this is where it get's tricky...
456                 string files = "";
457                 try {                   
458                                 string[] cmd = { "ls-files" ,  "-m" };                   // list the modified files..
459                                 files = this.git(cmd);
460                                 stash = files.length> 1 ;
461                                 
462                                 
463                                 cmd = { "stash" };                      
464                                 if (stash) { this.git(cmd); }
465                                 
466                                 this.pull();
467                                 
468                                 cmd = { "checkout", branchname  };
469                                 this.git(cmd);
470                   } catch(Error e) {
471                                 GitMonitor.gitmonitor.pauseError(e.message);
472                                 return false;           
473                   }
474                 try {
475                    if (branchname != "master") {
476                        string[] cmd = { "merge", "master"  };
477                             this.git(cmd);
478                             this.push();
479                        
480                     }
481                     
482                 } catch(Error e) {
483                     string[] cmd = { "checkout", "master"  };
484                     this.git(cmd);
485                         GitMonitor.gitmonitor.pauseError(
486                                 "Use\n\na) git checkout %s\nb) git mergetool\nc) git commit\nd) git push\n d) stash pop \ne) start gitlive again\n".printf(
487                                         branchname)
488                                  + e.message
489                         );
490                         return false;           
491                  
492                 }
493                 try {                                   
494                     string[]  cmd = { "stash", "pop"  };
495                     if (stash) { 
496                         this.git(cmd); 
497                         var fl = files.split("\n");
498                         cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
499                         foreach(var f in fl) {
500                                 cmd += f;
501                         }
502                         this.git(cmd);                              
503                 }
504              
505
506                    
507                 } catch(Error ee) {
508                         GitMonitor.gitmonitor.pauseError(ee.message);
509                         return false;           
510                 }
511        this.push();
512        return true;                             
513                  
514      }
515     
516     
517     
518      bool createNewBranchNamed(string branchname)
519      {
520                 var stash = false;
521                  try {                                  
522                                 string[] cmd = { "ls-files" ,  "-m" };                   // list the modified files..
523                                 var files = this.git(cmd);
524                                 stash = files.length> 1 ;
525                         
526                          cmd = { "checkout", "-b" , branchname  };
527                         this.git(cmd);
528
529                cmd = { "push", "-u" , "origin" ,"HEAD"  };
530                         this.git(cmd);
531                                 if (stash) { 
532
533                                 var fl = files.split("\n");
534                                 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
535                                 foreach(var f in fl) {
536                                         cmd += f;
537                                 }
538                                 this.git(cmd);  
539                                 this.push();                        
540                         }
541
542              
543                 } catch(Error ee) {
544                                 GitMonitor.gitmonitor.pauseError(ee.message);
545                                 return false;           
546                         }
547                         return true;
548      
549      }
550     
551     
552     
553     /**
554      * add:
555      * add files to track.
556      *
557      * @argument {Array} files the files to add.
558      */
559     public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
560     {
561         // should really find out if these are untracked files each..
562         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
563         // not sure if that is how git works.. but just be certian.
564         var ret = "";
565         for (var i = 0; i < files.size;i++) {
566             var f = files.get(i).vname;
567             try {
568                 string[] cmd = { "add",    f  };
569                 this.git( cmd );
570             } catch (Error e) {
571                 ret += e.message  + "\n";
572             }        
573
574         }
575         return ret;
576     }
577         
578     public bool is_ignore(string fname) throws Error, SpawnError
579     {
580                 if (fname == ".gitignore") {
581                         this.ignore_files.clear();
582                 }
583                 
584                 if (this.ignore_files.has_key(fname)) {
585                         return this.ignore_files.get(fname);
586                 }
587                 
588                 try {
589                         var ret = this.git( { "check-ignore" , fname } );
590                         this.ignore_files.set(fname, ret.length >  0);
591                         return ret.length > 0;
592                 } catch (SpawnError e) {
593                         this.ignore_files.set(fname, false);
594                         return false;
595                 }
596                  
597     } 
598     
599     
600       /**
601      * remove:
602      * remove files to track.
603      *
604      * @argument {Array} files the files to add.
605      */
606     public string remove  ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
607     {
608         // this may fail if files do not exist..
609         // should really find out if these are untracked files each..
610         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
611         // not sure if that is how git works.. but just be certian.
612         var ret = "";
613
614         for (var i = 0; i < files.size;i++) {
615             var f = files.get(i).vname;
616             try {
617                 string[] cmd = { "rm",  "-f" ,  f  };
618                 this.git( cmd );
619             } catch (Error e) {
620                 ret += e.message  + "\n";
621             }        
622         }
623
624         return ret;
625
626     }
627     
628     
629     /**
630      * commit:
631      * perform a commit.
632      *
633      * @argument {Object} cfg commit configuration
634      * 
635      * @property {String} name (optional)
636      * @property {String} email (optional)
637      * @property {String} changed (date) (optional)
638      * @property {String} reason (optional)
639      * @property {Array} files - the files that have changed. 
640      * 
641      */
642      
643     public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files  ) throws Error, SpawnError
644     {
645         
646
647         /*
648         var env = [];
649
650         if (typeof(cfg.name) != 'undefined') {
651             args.push( {
652                 'author' : cfg.name + ' <' + cfg.email + '>'
653             });
654             env.push(
655                 "GIT_COMMITTER_NAME" + cfg.name,
656                 "GIT_COMMITTER_EMAIL" + cfg.email
657             );
658         }
659
660         if (typeof(cfg.changed) != 'undefined') {
661             env.push("GIT_AUTHOR_DATE= " + cfg.changed )
662             
663         }
664         */
665         string[] args = { "commit", "-m" };
666         args +=  (message.length > 0  ? message : "Changed" );
667         for (var i = 0; i< files.size ; i++ ) {
668             args += files.get(i).vname; // full path?
669         }
670          
671         return this.git(args);
672     }
673     
674     /**
675      * pull:
676      * Fetch and merge remote repo changes into current branch..
677      *
678      * At present we just need this to update the current working branch..
679      * -- maybe later it will have a few options and do more stuff..
680      *
681      */
682     public string pull () throws Error, SpawnError
683     {
684         // should probably hand error conditions better... 
685         string[] cmd = { "pull" , "--no-edit" };
686         return this.git( cmd );
687
688         
689     }
690     
691     public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
692     public void pull_async(GitAsyncCallback cb) 
693     {
694     
695         string[] cmd = { "pull" , "--no-edit" };
696          this.git_async( cmd , cb);
697          
698     
699     }
700     
701     /**
702      * push:
703      * Send local changes to remote repo(s)
704      *
705      * At present we just need this to push the current branch.
706      * -- maybe later it will have a few options and do more stuff..
707      *
708      */
709     public string push () throws Error, SpawnError
710     {
711         // should 
712         return this.git({ "push"  });
713         
714     }
715     
716     
717     
718      /**
719      * git:
720      * The meaty part.. run spawn.. with git..
721      *
722      *
723      */
724     
725     public string git(string[] args_in ) throws Error, SpawnError
726     {
727         // convert arguments.
728         
729         string[]  args = { "git" };
730         //args +=  "--git-dir";
731         //args +=  this.gitdir;
732         args +=  "--no-pager";
733  
734  
735         //if (this.gitdir != this.repopath) {
736         //    args +=   "--work-tree";
737          //   args += this.repopath; 
738         //}
739         for (var i = 0; i < args_in.length;i++) {
740             args += args_in[i];
741         }            
742
743         //this.lastCmd = args.join(" ");
744         //if(this.debug) {
745             GLib.debug( "CWD=%s",  this.git_working_dir ); 
746             GLib.debug( "cmd: %s", string.joinv (" ", args)); 
747         //}
748
749         string[]   env = {};
750         string  home = "HOME=" + Environment.get_home_dir() ;
751         env +=  home ;
752         // do not need to set gitpath..
753         //if (File.exists(this.repo + '/.git/config')) {
754             //env.push("GITPATH=" + this.repo );
755         //}
756         
757
758         var cfg = new SpawnConfig(this.git_working_dir , args , env);
759         
760
761        // may throw error...
762         var sp = new Spawn(cfg);
763       
764
765         GLib.debug( "GOT: %s" , sp.output);
766         // parse output for some commands ?
767         return sp.output;
768     }
769         
770    unowned GitAsyncCallback git_async_on_callback;
771         public void  git_async( string[] args_in,   GitAsyncCallback cb ) throws Error, SpawnError
772     {
773         // convert arguments.
774        this.git_async_on_callback = cb;
775         string[]  args = { "git" };
776         //args +=  "--git-dir";
777         //args +=  this.gitdir;
778         args +=  "--no-pager";
779  
780  
781         //if (this.gitdir != this.repopath) {
782         //    args +=   "--work-tree";
783          //   args += this.repopath; 
784         //}
785         for (var i = 0; i < args_in.length;i++) {
786             args += args_in[i];
787         }            
788
789         //this.lastCmd = args.join(" ");
790         //if(this.debug) {
791             GLib.debug( "CWD=%s",  this.git_working_dir ); 
792             //print( "cmd: %s\n", string.joinv (" ", args)); 
793         //}
794
795         string[]   env = {};
796         string  home = "HOME=" + Environment.get_home_dir() ;
797         env +=  home ;
798         // do not need to set gitpath..
799         //if (File.exists(this.repo + '/.git/config')) {
800             //env.push("GITPATH=" + this.repo );
801         //}
802         
803
804         var cfg = new SpawnConfig(this.git_working_dir , args , env);
805         cfg.async = true;
806        
807
808        // may throw error...
809         var sp = new Spawn(cfg);
810                 //sp.ref();
811         //this.ref();
812         sp.run(this.git_async_on_complete); 
813          
814     }
815     
816     void git_async_on_complete(int err, string output)
817     {
818                 GLib.debug("GOT %d : %s", err, output);
819                 this.git_async_on_callback(this, err, output);
820 //              this.unref();   
821         //      sp.unref();             
822     
823     
824     }
825     
826 }