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