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