revert code that did not affect memory
[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      
29     public GitBranch  _currentBranch;
30     public GitBranch  getCurrentBranch() {
31         if (this._currentBranch == null) {
32                 Posix.usleep(100); // try and slow down branch loading          
33                 this.loadBranches();
34
35         }
36         if (this._currentBranch == null) {      
37                 GLib.error("could not work out current branch? : %s ",this.git_working_dir );
38                 }
39                 return this._currentBranch;
40     }
41     
42     
43     public Gee.HashMap<string,GitBranch> branches; // accessed in GitBranch..
44         public RooTicket? activeTicket;
45     public Gee.HashMap<string,GitRepo> cache;
46     public Gee.HashMap<string,string> config_cache;
47     
48     public Ggit.Repository repo;
49     public Ggit.RemoteHead[]                            remote_heads = null;
50     
51         public static GitRepo singleton()
52     {
53         if (_GitRepo == null) {
54             _GitRepo = new GitRepo.single();
55             _GitRepo.cache = new Gee.HashMap<string,GitRepo>();
56         }
57         return _GitRepo;
58     }
59  
60     /**
61     * index of.. matching gitpath..
62     */
63     public static int indexOf( Array<GitRepo> repos, string gitpath) {
64         // make a fake object to compare against..
65         var test_repo = GitRepo.get_sync(gitpath);
66         
67         for(var i =0; i < repos.length; i++) {
68             if (repos.index(i).gitdir == test_repo.gitdir) {
69                 return i;
70             }
71         }
72         return -1;
73     
74     }
75     
76
77     
78     
79     
80     public static   Array<GitRepo> list()
81     {
82
83         //if (GitRepo.list_cache !=  null) {
84         //    unowned  Array<GitRepo>    ret = GitRepo.list_cache;
85          //   return ret;
86         //}
87         var cache = GitRepo.singleton().cache;
88         var list_cache = new Array<GitRepo>();
89         
90         var dir = Environment.get_home_dir() + "/gitlive";
91         
92         var f = File.new_for_path(dir);
93         FileEnumerator file_enum;
94         try {
95             file_enum = f.enumerate_children(
96                 FileAttribute.STANDARD_DISPLAY_NAME + ","+ 
97                 FileAttribute.STANDARD_TYPE,
98                 FileQueryInfoFlags.NONE,
99                 null);
100         } catch (Error e) {
101             
102             return list_cache;
103             
104         }
105         
106         FileInfo next_file; 
107         
108         while (true) {
109             
110             try {
111                 next_file = file_enum.next_file(null);
112                 if (next_file == null) {
113                     break;
114                 }
115                 
116             } catch (Error e) {
117                 GLib.debug("Error: %s",e.message);
118                 break;
119             }
120          
121             //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
122             
123             if (next_file.get_file_type() !=  FileType.DIRECTORY) {
124                 next_file = null;
125                 continue;
126             }
127             
128             if (next_file.get_file_type() ==  FileType.SYMBOLIC_LINK) {
129                 next_file = null;
130                 continue;
131             }
132             
133             if (next_file.get_display_name()[0] == '.') {
134                 next_file = null;
135                 continue;
136             }
137             var sp = dir+"/"+next_file.get_display_name();
138            
139             var gitdir = dir + "/" + next_file.get_display_name() + "/.git";
140             
141             if (!FileUtils.test(gitdir, FileTest.IS_DIR)) {
142                 continue;
143             }
144             
145                 var rep =  GitRepo.get_sync(  sp );
146                 list_cache.append_val(rep);             
147             
148         }
149     
150         return list_cache;
151          
152         }
153         
154         public  static GitRepo get_sync(string path) 
155         {
156                 GitRepo ret;
157                 var cache = GitRepo.singleton().cache;
158                 if (cache.has_key(path)) {
159                         ret =  cache.get(path);
160                 } else {
161                         ret =  new GitRepo(path);
162                 }
163                 return ret;
164         }
165          
166         public static  async  GitRepo? get(string path) 
167         {
168                 
169                 SourceFunc callback = GitRepo.get.callback;
170                 GitRepo ret = null;
171                 ThreadFunc<bool> run = () => {
172                         
173                         var cache = GitRepo.singleton().cache;
174                         if (cache.has_key(path)) {
175                                 ret =  cache.get(path);
176                         } else {
177                                 ret =  new GitRepo(path);
178                         }
179                         Idle.add((owned) callback);
180                 return true;
181                         
182                 };
183                 new Thread<bool>("thread-new-gitrepo-" + path, run);
184                 yield;
185                 return ret;
186                 
187         }
188         
189     private GitRepo.single() {
190                 // used to create the signleton
191         }
192     /**
193      * constructor:
194      * 
195      * @param {Object} cfg - Configuration
196      *     (basically repopath is currently only critical one.)
197      *
198      */
199      
200     private GitRepo(string path) 
201     {
202         // cal parent?
203         this.name =   File.new_for_path(path).get_basename();
204         this.ignore_files = new Gee.HashMap<string,bool>();
205         
206         this.git_working_dir = path;
207         this.gitdir = path + "/.git";
208         if (!FileUtils.test(this.gitdir , FileTest.IS_DIR)) {
209             this.gitdir = path; // naked...
210         }
211         this.cmds = new  Gee.ArrayList<GitMonitorQueue> ();
212         
213                 var cache = GitRepo.singleton().cache;
214         //Repo.superclass.constructor.call(this,cfg);
215                 if ( !cache.has_key(path) ) {
216                         cache.set( path, this);
217         }
218         
219         this.repo =  Ggit.Repository.open(GLib.File.new_for_path(path));
220         
221         var r = this.repo.lookup_remote("origin");
222         
223         
224         //var r = this.git({ "remote" , "get-url" , "--push" , "origin"});
225         var uri = new Soup.URI(r.get_url());            
226         this.host = uri.get_host();
227                 this.init_config();
228         
229         this.loadBranches();
230         this.loadActiveTicket();
231         this.loadStatus();
232     } 
233     
234     public bool is_master_branch()
235     {
236         // special branches that do not allow autopushing now...
237         return this.getCurrentBranch().name == "master" || this.getCurrentBranch().name == "roojs";
238                 
239     }
240     public void init_config()
241     {
242         this.config_cache = new Gee.HashMap<string,string>();
243         // managed = 
244         if (this.get_config("managed") == "") {
245                 this.set_config("managed", this.host == "git.roojs.com" ? "1" : "0");
246                 }
247         if (this.get_config("autocommit") == "") {
248                 this.set_config("autocommit", this.host == "git.roojs.com" ? "1" : "0");
249                 }
250         if (this.get_config("autopush") == "") {
251                 this.set_config("autopush", this.host == "git.roojs.com" ? "1" : "0");
252                 }
253                 
254     }
255     
256     
257     
258     public string get_config(string key) 
259     {
260     
261         if (this.config_cache.has_key(key)) {
262                 //GLib.debug("get_config %s = '%s'", key, this.config_cache.get(key));
263                 return this.config_cache.get(key);
264                 }
265         try {
266                 var cfg = this.repo.get_config().snapshot();
267                 var ret = cfg.get_string("gitlive." + key).strip();
268                 return ret;
269         } catch (Error e) {
270                 this.repo.get_config().set_string("gitlive." + key, "");
271                 //this.config_cache.set(key, "");
272                 //GLib.debug("get_config (fail) %s = '%s'", key, "");
273                 return ""; // happens when there is nothing set...
274         }
275
276         }
277     public void set_config(string key, string value) 
278     {
279         this.repo.get_config().set_string("gitlive." + key, value);
280         //this.git({ "config" , "gitlive." + key, value });
281         //this.config_cache.set(key,value);
282         }
283     
284     public bool is_managed()
285     {
286         return this.get_config("managed") == "1";
287     }
288     
289     
290     public bool is_autocommit ()
291     {           
292         return this.get_config("autocommit") == "1";            
293     }
294     
295     public void set_autocommit(bool val)
296     {
297                 this.set_config("autocommit", val ? "1" : "0");
298     
299     }
300     
301     public bool is_auto_branch ()
302     {
303         if (this.name == "gitlog") {
304                 return false;
305                 }
306                 // check remote...
307         if (this.is_managed()) {
308                 return true;
309                 }
310         return false;
311         
312  
313     }
314     
315     public void set_auto_branch(bool val)
316     {
317                 if (this.name == "gitlog") {
318                 return;
319                 }
320                 this.set_config("managed", val ? "1" : "0");
321     
322     }
323     public bool is_autopush ()
324     {
325         return this.get_config("autopush") == "1";
326     }
327     public void set_autopush(bool val)
328     {
329                 this.set_config("autopush", val ? "1" : "0");
330     }
331     
332     
333         public void loadStatus()
334         {
335                 // status??/ 
336                 var r = this.git({ "status" , "--porcelain" });
337                 this.git_status = r;
338                 this.has_local_changes = r.length > 0;
339                 
340                 //var rs = this.git({ "status" , "-sb" });
341                 var cb = this.getCurrentBranch();
342                   
343                 this.ahead_or_behind = cb.ahead > 0 ?  "A" : (cb.behind > 0  ? "B" : "");
344                 
345                 
346                 this.git_diff  = this.diffWorking();
347         }    
348
349     
350     public void loadBranches()
351     {
352
353         GitBranch.loadBranches(this);
354     }
355      
356     
357     public bool hasBranchCalled(string name)
358     {
359         foreach( var br in this.branches.values) {
360                         if (br.name == name) {
361                                 return true;
362                         }
363
364                 }
365                 return false;
366     }
367     
368     public string branchesToString()
369     {
370         var ret = "";
371                 foreach( var br in this.branches.values) {
372                         if (br.name == "") {
373                                 continue; 
374                         }
375                         var col = /hours/.match(br.age) ? "#ff851b" : "#ffdc00"; // orange or yellow
376                         ret += ret.length > 0 ? "\n"  : "";
377                         ret += br.name + " <span background=\"" + col + "\">" + br.age + "</span>";
378                 
379                 }
380                 return ret;
381         
382     }
383      public static void doMerges(string action, string ticket_id, string commit_message)
384     {
385        GitMonitor.gitmonitor.stop();
386        
387        var commitrevs = "";
388        var sucess = true;
389        foreach(var  repo in GitRepo.singleton().cache.values) {
390                if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
391                        var res = repo.doMerge(action,ticket_id, commit_message);
392                        if (!res) {
393                                sucess = false;
394                                continue;
395                        }
396                        commitrevs += commitrevs.length > 0 ? " " : "";
397                        commitrevs += repo.getCurrentBranch().lastrev;
398                }
399        }
400        if (sucess && action == "CLOSE") {
401                RooTicket.singleton().getById(ticket_id).close(commitrevs);
402        }
403        GitMonitor.gitmonitor.start();
404     }
405       
406
407     public bool doMerge(string action, string ticket_id, string commit_message)
408     {
409        // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
410        // also need to decide which branch we will merge into?
411                 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
412        
413                    var ret = "";
414                    if (action == "CLOSE" || action == "LEAVE") {
415                                    
416                try {
417                    var oldbranch = this.getCurrentBranch().name;
418                    this.setActiveTicket(null, master);
419                            string [] cmd = { "merge",   "--squash",  oldbranch };
420                            this.git( cmd );
421                            cmd = { "commit",   "-a" , "-m",  commit_message };
422                            this.git( cmd );
423                            this.push();
424                            this.loadBranches(); // updates lastrev..
425                
426                        var notification = new Notify.Notification(
427                                "Merged branch %s to %s".printf(oldbranch, master),
428                                "",
429                                 "dialog-information"
430                                
431                        );
432
433                        notification.set_timeout(5);
434                        notification.show();   
435                
436                // close ticket..
437                return true; 
438                
439            } catch (Error e) {
440
441                GitMonitor.gitmonitor.pauseError(e.message);
442                return false;
443            }
444            // error~?? -- show the error dialog...
445                    return false;
446        }
447        if (action == "MASTER") {
448                // merge master into ours..
449                        try {
450                        string[] cmd = { "merge", master};
451                        this.git( cmd );
452                        var notification = new Notify.Notification(
453                                        "Merged code from %s to %s".printf(master,this.getCurrentBranch().name),
454                                        "",
455                                         "dialog-information"
456                                        
457                                );
458                                notification.set_timeout(5);
459                                notification.show();   
460                       
461                        return true;
462                        } catch (Error e) {
463                        GitMonitor.gitmonitor.pauseError(e.message);
464                        return false;
465                    }
466            }
467        if (action == "EXIT") {
468                        try {
469                        var oldbranch  = this.getCurrentBranch().name;
470                          this.setActiveTicket(null, master);
471                        this.loadBranches();
472                        var notification = new Notify.Notification(
473                                        "Left branch %s".printf(oldbranch),
474                                        "",
475                                         "dialog-information"
476                                        
477                                );
478                                notification.set_timeout(5);
479                                notification.show();   
480                        
481                        return true;
482                    } catch (Error e) {
483                        GitMonitor.gitmonitor.pauseError(e.message);
484
485                        return false;                   
486                    }
487                    // error~?? -- show the error dialog...
488
489        }
490        return false;
491     }
492         
493     public void loadActiveTicket()
494     {
495         this.activeTicket = null;
496                 var ticket_id = this.get_config("ticket");
497         
498         if (ticket_id.length < 1) {
499                 return;
500                 }
501                 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
502         
503         
504     }
505     
506     
507     
508     public bool setActiveTicket(RooTicket? ticket, string branchname)
509     {
510         this.set_config("ticket", "");
511         if (!this.createBranchNamed(branchname)) {
512                 return false;
513                 }
514                 this.set_config("ticket", ticket == null ? "": ticket.id);
515         this.activeTicket = ticket;
516         return true;
517     }
518     
519     public bool createBranchNamed(string branchname)
520     {   
521                 
522
523                      if (this.branches.has_key(branchname)) {
524                         this.switchToExistingBranchNamed(branchname);
525                     
526                     } else {
527                                  this.createNewBranchNamed(branchname); 
528                             
529                     }
530                        var notification = new Notify.Notification(
531                        "Changed to branch %s".printf(branchname),
532                        "",
533                         "dialog-information"
534                        
535                );
536
537                notification.set_timeout(5);
538                notification.show();   
539        
540          
541          this.loadBranches(); // update branch list...
542          //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
543          return true;
544     }
545      bool switchToExistingBranchNamed(string branchname)
546      {
547                 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
548                 var stash = false;
549                 // this is where it get's tricky...
550                 string files = "";
551                 try {                   
552                                 string[] cmd = { "ls-files" ,  "-m" };                   // list the modified files..
553                                 files = this.git(cmd);
554                                 stash = files.length> 1 ;
555                                 
556                                 
557                                 cmd = { "stash" };                      
558                                 if (stash) { this.git(cmd); }
559                                 
560                                 this.pull();
561                                 
562                                 cmd = { "checkout", branchname  };
563                                 this.git(cmd);
564                   } catch(Error e) {
565                                 GitMonitor.gitmonitor.pauseError(e.message);
566                                 return false;           
567                   }
568                 try {
569                    if (branchname != master) {
570                        string[] cmd = { "merge", master };
571                             this.git(cmd);
572                             this.push();
573                        
574                     }
575                     
576                 } catch(Error e) {
577                     string[] cmd = { "checkout", master  };
578                     this.git(cmd);
579                         GitMonitor.gitmonitor.pauseError(
580                                 "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(
581                                         branchname)
582                                  + e.message
583                         );
584                         return false;           
585                  
586                 }
587                 try {                                   
588                     string[]  cmd = { "stash", "pop"  };
589                     if (stash) { 
590                         this.git(cmd); 
591                         var fl = files.split("\n");
592                         cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
593                         foreach(var f in fl) {
594                                 if (f.length < 1) continue;
595                                 cmd += f;
596                         }
597                         this.git(cmd);                              
598                 }
599              
600
601                    
602                 } catch(Error ee) {
603                         GitMonitor.gitmonitor.pauseError(ee.message);
604                         return false;           
605                 }
606        this.push();
607        return true;                             
608                  
609      }
610     
611     
612     
613      bool createNewBranchNamed(string branchname)
614      {
615                 var stash = false;
616                  try {                                  
617                                 string[] cmd = { "ls-files" ,  "-m" };                   // list the modified files..
618                                 var files = this.git(cmd);
619                                 stash = files.length> 1 ;
620                         
621                          cmd = { "checkout", "-b" , branchname  };
622                         this.git(cmd);
623
624                cmd = { "push", "-u" , "origin" ,"HEAD"  };
625                         this.git(cmd);
626                                 if (stash) { 
627
628                                 var fl = files.split("\n");
629                                 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
630                                 foreach(var f in fl) {
631                                         if (f.length < 1) continue;
632                                         cmd += f;
633                                 }
634                                 this.git(cmd);  
635                                 this.push();                        
636                         }
637
638              
639                 } catch(Error ee) {
640                                 GitMonitor.gitmonitor.pauseError(ee.message);
641                                 return false;           
642                         }
643                         return true;
644      
645      }
646      
647      public static string previewMerges(string ticket_id)
648     {
649        var ret = "";
650        foreach(var  repo in GitRepo.singleton().cache.values) {
651            if (repo.activeTicket == null || repo.activeTicket.id != ticket_id) {
652                 continue;
653                 }
654                         ret += repo.previewMerge() + "\n\n";
655
656        }
657        return ret;
658
659     }
660      
661      
662      
663      public string previewMerge()
664      {
665          try {                                  
666                         var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
667                         var lines = this.git({"log", master + "...",  "--pretty=format:%H %P" }).split("\n");;
668                         var head = this.git({"log", "-1",  "--pretty=format:%H %P" });
669                         var start = head.split(" ")[0];
670                         var end = "";
671                         for (var i = 0; i < lines.length; i++) {
672                                 var cols = lines[i].split(" ");
673                                 if (cols.length > 2) {
674                                         end = cols[0];
675                                         break;
676                                 }
677                         }
678                         if (end == "") {
679                                 var last = lines.length > 0 ? lines[lines.length-1] : "";
680                                 end = last.split(" ")[1];                               
681                         }
682
683                         return this.git({ "diff" , (end+".."+start), "--no-color" });
684                 }  catch(Error ee) {
685                         GitMonitor.gitmonitor.pauseError(ee.message);
686                         return "Error getting diff";            
687                 }
688           
689      }
690     
691     
692     public string diffWorking()
693     {
694         var cb = this.getCurrentBranch();
695         GLib.debug("Calling diff working");
696         var diff = new Ggit.Diff.tree_to_workdir(this.repo, cb.getTree(), new Ggit.DiffOptions());
697         var ret = "";
698         diff.print(Ggit.DiffFormatType.PATCH, (delta, hunk, line) => {
699                 switch(line.get_origin()) {
700                         case Ggit.DiffLineType.ADDITION: ret+="+"; break;
701                                 case Ggit.DiffLineType.DELETION: ret+="-";break;
702                                 case Ggit.DiffLineType.CONTEXT:  ret+=" ";break;
703                                 case Ggit.DiffLineType.HUNK_HDR: break;                                 
704                                 case Ggit.DiffLineType.FILE_HDR: break;
705                                 default: ret+=" ";break;
706                         }
707                 ret += " " + line.get_text() ;
708                 return 0;
709         });
710         //GLib.debug("returning %s", ret);
711         return ret;
712     }    
713     
714     
715     /**
716      * add:
717      * add files to track.
718      *
719      * @argument {Array} files the files to add.
720      */
721     public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
722     {
723         // should really find out if these are untracked files each..
724         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
725         // not sure if that is how git works.. but just be certian.
726         var ret = "";
727         for (var i = 0; i < files.size;i++) {
728             var f = files.get(i).vname;
729             try {
730                 string[] cmd = { "add",    f  };
731                 this.git( cmd );
732             } catch (Error e) {
733                 ret += e.message  + "\n";
734             }        
735
736         }
737         return ret;
738     }
739         
740     public bool is_ignore(string fname) throws Error, SpawnError
741     {
742                 if (fname == ".gitignore") {
743                         this.ignore_files.clear();
744                 }
745                 
746                 if (this.ignore_files.has_key(fname)) {
747                         return this.ignore_files.get(fname);
748                 }
749                 
750                 try {
751                         var ret = this.git( { "check-ignore" , fname } );
752                         this.ignore_files.set(fname, ret.length >  0);
753                         return ret.length > 0;
754                 } catch (SpawnError e) {
755                         this.ignore_files.set(fname, false);
756                         return false;
757                 }
758                  
759     } 
760     
761     
762       /**
763      * remove:
764      * remove files to track.
765      *
766      * @argument {Array} files the files to add.
767      */
768     public string remove  ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
769     {
770         // this may fail if files do not exist..
771         // should really find out if these are untracked files each..
772         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
773         // not sure if that is how git works.. but just be certian.
774         var ret = "";
775
776         for (var i = 0; i < files.size;i++) {
777             var f = files.get(i).vname;
778             try {
779                 string[] cmd = { "rm",  "-f" ,  f  };
780                 this.git( cmd );
781             } catch (Error e) {
782                 ret += e.message  + "\n";
783             }        
784         }
785
786         return ret;
787
788     }
789     
790     
791     /**
792      * commit:
793      * perform a commit.
794      *
795      * @argument {Object} cfg commit configuration
796      * 
797      * @property {String} name (optional)
798      * @property {String} email (optional)
799      * @property {String} changed (date) (optional)
800      * @property {String} reason (optional)
801      * @property {Array} files - the files that have changed. 
802      * 
803      */
804      
805     public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files  ) throws Error, SpawnError
806     {
807         
808
809         /*
810         var env = [];
811
812         if (typeof(cfg.name) != 'undefined') {
813             args.push( {
814                 'author' : cfg.name + ' <' + cfg.email + '>'
815             });
816             env.push(
817                 "GIT_COMMITTER_NAME" + cfg.name,
818                 "GIT_COMMITTER_EMAIL" + cfg.email
819             );
820         }
821
822         if (typeof(cfg.changed) != 'undefined') {
823             env.push("GIT_AUTHOR_DATE= " + cfg.changed )
824             
825         }
826         */
827         string[] args = { "commit", "-m" };
828         args +=  (message.length > 0  ? message : "Changed" );
829         for (var i = 0; i< files.size ; i++ ) {
830             args += files.get(i).vname; // full path?
831         }
832          
833         return this.git(args);
834     }
835     
836     /**
837      * pull:
838      * Fetch and merge remote repo changes into current branch..
839      *
840      * At present we just need this to update the current working branch..
841      * -- maybe later it will have a few options and do more stuff..
842      *
843      */
844     public string pull () throws Error, SpawnError
845     {
846         // should probably hand error conditions better... 
847         string[] cmd = { "pull" , "--no-edit" };
848         return this.git( cmd );
849
850         
851     }
852     
853     public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
854     public void pull_async(GitAsyncCallback cb) 
855     {
856     
857          string[] cmd = { "pull" , "--no-edit" };
858          this.git_async( cmd , cb);
859          
860     
861     }
862     
863     /**
864      * push:
865      * Send local changes to remote repo(s)
866      *
867      * At present we just need this to push the current branch.
868      * -- maybe later it will have a few options and do more stuff..
869      *
870      */
871     public string push () throws Error, SpawnError
872     {
873         // should 
874         return this.git({ "push"  });
875         
876     }
877     
878     
879     
880      /**
881      * git:
882      * The meaty part.. run spawn.. with git..
883      *
884      *
885      */
886     
887     public string git(string[] args_in ) throws Error, SpawnError
888     {
889         // convert arguments.
890         
891         string[]  args = { "git" };
892         //args +=  "--git-dir";
893         //args +=  this.gitdir;
894         args +=  "--no-pager";
895  
896  
897         //if (this.gitdir != this.repopath) {
898         //    args +=   "--work-tree";
899          //   args += this.repopath; 
900         //}
901         for (var i = 0; i < args_in.length;i++) {
902             args += args_in[i];
903         }            
904
905         //this.lastCmd = args.join(" ");
906         //if(this.debug) {
907             GLib.debug( "CWD=%s",  this.git_working_dir ); 
908             GLib.debug( "cmd: %s", string.joinv (" ", args)); 
909         //}
910
911         string[]   env = {};
912         string  home = "HOME=" + Environment.get_home_dir() ;
913         env +=  home ;
914         // do not need to set gitpath..
915         //if (File.exists(this.repo + '/.git/config')) {
916             //env.push("GITPATH=" + this.repo );
917         //}
918           
919         var cfg = new SpawnConfig(this.git_working_dir , args , env);
920         //cfg.debug = true;
921
922        // may throw error...
923         var sp = new Spawn(cfg);
924       
925              //GLib.debug( "GOT result: %d" , sp.result);
926       
927         // diff output is a bit big..
928                 if (args_in[0] != "diff") {
929                 GLib.debug( "GOT: %s" , sp.output);
930         }
931         // parse output for some commands ?
932         return sp.output;
933     }
934         
935    unowned GitAsyncCallback git_async_on_callback;
936         public void  git_async( string[] args_in,   GitAsyncCallback cb ) throws Error, SpawnError
937     {
938         // convert arguments.
939        this.git_async_on_callback = cb;
940         string[]  args = { "git" };
941         //args +=  "--git-dir";
942         //args +=  this.gitdir;
943         args +=  "--no-pager";
944  
945  
946         //if (this.gitdir != this.repopath) {
947         //    args +=   "--work-tree";
948          //   args += this.repopath; 
949         //}
950         for (var i = 0; i < args_in.length;i++) {
951             args += args_in[i];
952         }            
953
954         //this.lastCmd = args.join(" ");
955         //if(this.debug) {
956             GLib.debug( "CWD=%s",  this.git_working_dir ); 
957             //print( "cmd: %s\n", string.joinv (" ", args)); 
958         //}
959
960         string[]   env = {};
961         string  home = "HOME=" + Environment.get_home_dir() ;
962         env +=  home ;
963         // do not need to set gitpath..
964         //if (File.exists(this.repo + '/.git/config')) {
965             //env.push("GITPATH=" + this.repo );
966         //}
967         
968
969         var cfg = new SpawnConfig(this.git_working_dir , args , env);
970         cfg.async = true;
971        
972
973        // may throw error...
974         var sp = new Spawn(cfg);
975                 //sp.ref();
976         //this.ref();
977         sp.run(this.git_async_on_complete); 
978          
979     }
980     
981     void git_async_on_complete(int err, string output)
982     {
983                 GLib.debug("GOT %d : %s", err, output);
984                 this.git_async_on_callback(this, err, output);
985 //              this.unref();   
986         //      sp.unref();             
987     
988     
989     }
990     
991     
992     public async void doUpdate()
993     {
994         SourceFunc callback = this.doUpdate.callback;
995                 GitRepo ret = null;
996                 ThreadFunc<bool> run = () => {
997                         
998                         
999                 // update the branches..
1000                         this.loadBranches();
1001
1002                         //GLib.debug("connecting '%s'", r.get_url());
1003                         string[] far = {};
1004                         foreach(var br in this.branches.values) {
1005                                 if (br.remote == "" || br.remoterev == br.lastrev) {
1006                                         continue;
1007                                 }
1008                                 far +=  ("+refs/heads/" + br.name + ":refs/remotes/" + br.remote);
1009                         }
1010                         if (far.length > 0) {
1011                                 GLib.debug("PUlling %s", this.name);
1012                                 var r = this.repo.lookup_remote("origin");
1013                                 r.connect(Ggit.Direction.FETCH, new GitCallbacks(this), null, null);
1014                                 var options = new Ggit.FetchOptions();
1015                                 options.set_remote_callbacks( new GitCallbacks(this));
1016                                 r.download(far, options);
1017                         }
1018                         this.loadStatus();
1019                          
1020                 
1021                         Idle.add((owned) callback);
1022                 return true;
1023                         
1024                 };
1025                 new Thread<bool>("thread-new-gitpull-" + this.name, run);
1026                 yield;
1027                    
1028         
1029     }
1030     
1031         
1032         public static void updateAllAsync(string after)
1033         {
1034  
1035                 
1036                 var doing = new  Gee.HashMap<string,bool>();;
1037                 
1038                 var tr =  GitRepo.singleton().cache;
1039         
1040        var update_all_total = tr.size;
1041        foreach(var repo  in tr.values) {
1042                 if (!repo.is_managed()) {
1043                         update_all_total--;                     
1044                         continue;
1045                 }
1046                 doing.set(repo.name, true);
1047                         repo.doUpdate.begin((obj, res) => {
1048                                 repo.doUpdate.end(res);
1049                                 doing.set(repo.name, false);
1050                                  
1051                                 foreach(var b in doing.keys) {
1052                                         if (doing.get(b)) {
1053                                                 GLib.debug("pending: %s", b);
1054                                                 return;
1055                                         }
1056                                 }
1057                         
1058                                 
1059                                 switch (after) {
1060                                         case "show_clones":
1061                                                 Clones.singleton().show();
1062                                                 break;
1063                                         default:
1064                                                 GLib.debug("Unkown call after load = %s", update_all_after);            
1065                                                 break;
1066                                 }
1067                         });
1068                 }
1069
1070         
1071         }
1072         
1073          
1074     
1075  
1076     public void update_async(GitAsyncCallback cb) 
1077     {
1078          string[] cmd = { "fetch" , "--all" };
1079          this.git_async( cmd , cb);
1080          
1081     }
1082     
1083     
1084     static uint update_all_total = 0;
1085     static string update_all_after = "";
1086      
1087     public static void updateAll(string after)
1088     {
1089                 update_all_after = after;
1090                 var tr =  GitRepo.singleton().cache;
1091             
1092         
1093        update_all_total = tr.size;
1094        foreach(var repo  in tr.values) {
1095                 if (!repo.is_managed()) {
1096                         update_all_total--;                     
1097                         continue;
1098                 }
1099            repo.update_async(updateAllCallback); 
1100         } 
1101                 GLib.debug("calls total = %d", (int) update_all_total);
1102     }
1103     
1104     
1105     
1106     public static void  updateAllCallback(GitRepo repo, int err, string res)
1107     {
1108         repo.loadBranches();
1109         repo.loadStatus();
1110         
1111         update_all_total--;
1112                 GLib.debug("calls remaining = %d", (int)update_all_total);      
1113         if (update_all_total > 0 ) {
1114
1115                 return;
1116                 }
1117                 GLib.debug("call after load = %s", update_all_after);    
1118                 
1119                 switch (update_all_after) {
1120                         case "show_clones":
1121                                 Clones.singleton().show();
1122                                 break;
1123                         default:
1124                                 GLib.debug("Unkown call after load = %s", update_all_after);            
1125                                 break;
1126                 }
1127                 return;
1128     }
1129     
1130     public void loadRemoteHeads(bool force = false)
1131         {
1132                 
1133                 if (!force && this.remote_heads != null) {
1134                         return;
1135                 }
1136                 var r = this.repo.lookup_remote("origin");
1137                 var cb = new GitCallbacks(this);
1138                 r.connect(Ggit.Direction.FETCH, cb, null, null);
1139                 this.remote_heads = r.list();
1140         
1141         }
1142     
1143 }