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