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