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