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