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