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