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