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