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