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