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     
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 void set_auto_branch(bool val)
189     {
190                 var cur = this.is_auto_branch();
191                 if (cur == val) {
192                         return; // no change..
193                 }
194                 if (cur) {
195                         FileUtils.set_contents(this.gitdir + "/.gitlive-enable-auto-branch" , "");
196                 } else {
197                         // it exists...
198                         FileUtils.remove(this.gitdir + "/.gitlive-enable-auto-branch" ); 
199                 }
200     
201     }
202     public bool is_autopush ()
203     {
204         return !FileUtils.test(this.gitdir + "/.gitlive-disable-autopush" , FileTest.EXISTS);
205     }
206     
207     Gee.HashMap<string,GitBranch> branches;
208     
209     public void loadBranches()
210     {
211         this.branches = new Gee.HashMap<string,GitBranch>();
212         
213         string[] cmd = { "branch",   "--no-color", "--verbose", "--no-abbrev" , "-a"  };
214         var res = this.git( cmd );
215         var lines = res.split("\n");
216         for (var i = 0; i < lines.length ; i++) {
217                 var br = new GitBranch(this);
218                 if (!br.parseBranchListItem(lines[i])) {
219                         continue;
220                 }
221                 GLib.debug("add branch %s", br.realName());
222                  
223                 branches.set(br.realName(), br);
224                 if (br.active) {
225                         this.currentBranch = br;
226                 }
227         }
228     
229     }
230      
231     
232     
233     
234     public string branchesToString()
235     {
236         var ret = "";
237                 foreach( var br in this.branches.values) {
238                         if (br.name == "") {
239                                 continue; 
240                         }
241                         ret += ret.length > 0 ? ","  : "";
242                         ret += br.name;
243                 
244                 }
245                 return ret;
246         
247     }
248      public static void doMerges(string action, string ticket_id, string commit_message)
249     {
250        GitMonitor.gitmonitor.stop();
251        
252        var commitrevs = "";
253        var sucess = true;
254        foreach(var  repo in GitRepo.singleton().cache.values) {
255                if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
256                        var res = repo.doMerge(action,ticket_id, commit_message);
257                        if (!res) {
258                                sucess = false;
259                                continue;
260                        }
261                        commitrevs += commitrevs.length > 0 ? " " : "";
262                        commitrevs += repo.currentBranch.lastrev;
263                }
264        }
265        if (sucess && action == "CLOSE") {
266                RooTicket.singleton().getById(ticket_id).close(commitrevs);
267        }
268        GitMonitor.gitmonitor.start();
269     }
270      
271
272     public bool doMerge(string action, string ticket_id, string commit_message)
273     {
274        // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
275        // also need to decide which branch we will merge into?
276                    var ret = "";
277                    if (action == "CLOSE" || action == "LEAVE") {
278                                    
279                try {
280                    var oldbranch = this.currentBranch.name;
281                    this.setActiveTicket(null, "master");
282                            string [] cmd = { "merge",   "--squash",  oldbranch };
283                            this.git( cmd );
284                            cmd = { "commit",   "-a" , "-m",  commit_message };
285                            this.git( cmd );
286                            this.push();
287                            this.loadBranches(); // updates lastrev..
288                
289                        var notification = new Notify.Notification(
290                                "Merged branch %s to master".printf(oldbranch),
291                                "",
292                                 "dialog-information"
293                                
294                        );
295
296                        notification.set_timeout(5);
297                        notification.show();   
298                
299                // close ticket..
300                return true; 
301                
302            } catch (Error e) {
303
304                GitMonitor.gitmonitor.pauseError(e.message);
305                return false;
306            }
307            // error~?? -- show the error dialog...
308                    return false;
309        }
310        if (action == "MASTER") {
311                // merge master into ours..
312                        try {
313                        string[] cmd = { "merge",  "master" };
314                        this.git( cmd );
315                        var notification = new Notify.Notification(
316                                        "Merged code from master to %s".printf(this.currentBranch.name),
317                                        "",
318                                         "dialog-information"
319                                        
320                                );
321                                notification.set_timeout(5);
322                                notification.show();   
323                       
324                        return true;
325                        } catch (Error e) {
326                        GitMonitor.gitmonitor.pauseError(e.message);
327                        return false;
328                    }
329            }
330        if (action == "EXIT") {
331                        try {
332                        var oldbranch  = this.currentBranch.name;
333                          this.setActiveTicket(null, "master");
334                        this.loadBranches();
335                        var notification = new Notify.Notification(
336                                        "Left branch %s".printf(oldbranch),
337                                        "",
338                                         "dialog-information"
339                                        
340                                );
341                                notification.set_timeout(5);
342                                notification.show();   
343                        
344                        return true;
345                    } catch (Error e) {
346                        GitMonitor.gitmonitor.pauseError(e.message);
347
348                        return false;                   
349                    }
350                    // error~?? -- show the error dialog...
351
352        }
353        return false;
354     }
355         
356     public void loadActiveTicket()
357     {
358         this.activeTicket = null;
359         if (!FileUtils.test(this.gitdir + "/.gitlive-active-ticket" , FileTest.EXISTS)) {
360                 return;
361         }
362         string ticket_id;
363         FileUtils.get_contents(this.gitdir + "/.gitlive-active-ticket" , out ticket_id);  
364         if (ticket_id.length < 1) {
365                 return;
366                 }
367                 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
368         
369         
370     }
371     
372     
373     
374     public bool setActiveTicket(RooTicket? ticket, string branchname)
375     {
376         if (!this.createBranchNamed(branchname)) {
377                 return false;
378                 }
379                 if (ticket != null) {
380                 FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
381         } else {
382                 FileUtils.remove(this.gitdir + "/.gitlive-active-ticket" );
383         }
384         this.activeTicket = ticket;
385         return true;
386     }
387     
388     public bool createBranchNamed(string branchname)
389     {   
390                 
391                         var stash = false;
392                      if (this.branches.has_key(branchname)) {
393                         // this is where it get's tricky...
394                                 try {                   
395                                                 string[] cmd = { "ls-files" ,  "-m" };                   // list the modified files..
396                                             var ret = this.git(cmd);
397                                             stash = ret.length> 1 ;
398                                             
399                                                 
400                                             cmd = { "stash" };                  
401                                             if (stash) { this.git(cmd); }
402                                             
403                                             cmd = { "checkout", branchname  };
404                                             this.git(cmd);
405                                   } catch(Error e) {
406                                                 GitMonitor.gitmonitor.pauseError(e.message);
407                                                 return false;           
408                                   }
409                                   try {
410                                            if (branchname != "master") {
411                                                string[] cmd = { "merge", "master"  };
412                                                     this.git(cmd);
413                                                     this.push();
414                                                //cmd = { "commit",   "-a" , "-m",  "merge master changes" };
415                                        //git chethis.git( cmd );
416                                             }
417                                             
418                                    } catch(Error e) {
419                                             string[] cmd = { "checkout", "master"  };
420                                             this.git(cmd);
421                                                 GitMonitor.gitmonitor.pauseError(
422                                                         "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(
423                                                                 branchname)
424                                                          + e.message
425                                                 );
426                                                 return false;           
427                                          
428                                         }
429                                    try {                                        
430                                            string[]  cmd = { "stash", "pop"  };
431                                             if (stash) { this.git(cmd); }
432                                         } catch(Error ee) {
433                                                 GitMonitor.gitmonitor.pauseError(ee.message);
434                                                 return false;           
435                                         }
436                    this.push();
437                     
438                     } else {
439                                     try {                                       
440                                            
441                                         string[] cmd = { "checkout", "-b" , branchname  };
442                                         this.git(cmd);
443
444                        cmd = { "branch", "--set-upstream-to=origin/"+branchname , branchname  };
445                                         this.git(cmd);
446                        this.push();                            
447                                         } catch(Error ee) {
448                                                 GitMonitor.gitmonitor.pauseError(ee.message);
449                                                 return false;           
450                                         }
451                             
452                     }
453                        var notification = new Notify.Notification(
454                        "Changed to branch %s".printf(branchname),
455                        "",
456                         "dialog-information"
457                        
458                );
459
460                notification.set_timeout(5);
461                notification.show();   
462        
463          
464          this.loadBranches(); // update branch list...
465          //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
466          return true;
467     }
468     
469     
470     /**
471      * add:
472      * add files to track.
473      *
474      * @argument {Array} files the files to add.
475      */
476     public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
477     {
478         // should really find out if these are untracked files each..
479         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
480         // not sure if that is how git works.. but just be certian.
481         var ret = "";
482         for (var i = 0; i < files.size;i++) {
483             var f = files.get(i).vname;
484             try {
485                 string[] cmd = { "add",    f  };
486                 this.git( cmd );
487             } catch (Error e) {
488                 ret += e.message  + "\n";
489             }        
490
491         }
492         return ret;
493     }
494         
495     public bool is_ignore(string fname) throws Error, SpawnError
496     {
497                 if (fname == ".gitignore") {
498                         this.ignore_files.clear();
499                 }
500                 
501                 if (this.ignore_files.has_key(fname)) {
502                         return this.ignore_files.get(fname);
503                 }
504                 
505                 try {
506                         var ret = this.git( { "check-ignore" , fname } );
507                         this.ignore_files.set(fname, ret.length >  0);
508                         return ret.length > 0;
509                 } catch (SpawnError e) {
510                         this.ignore_files.set(fname, false);
511                         return false;
512                 }
513                  
514     } 
515     
516     
517       /**
518      * remove:
519      * remove files to track.
520      *
521      * @argument {Array} files the files to add.
522      */
523     public string remove  ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
524     {
525         // this may fail if files do not exist..
526         // should really find out if these are untracked files each..
527         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
528         // not sure if that is how git works.. but just be certian.
529         var ret = "";
530
531         for (var i = 0; i < files.size;i++) {
532             var f = files.get(i).vname;
533             try {
534                 string[] cmd = { "rm",  "-f" ,  f  };
535                 this.git( cmd );
536             } catch (Error e) {
537                 ret += e.message  + "\n";
538             }        
539         }
540
541         return ret;
542
543     }
544     
545     
546     /**
547      * commit:
548      * perform a commit.
549      *
550      * @argument {Object} cfg commit configuration
551      * 
552      * @property {String} name (optional)
553      * @property {String} email (optional)
554      * @property {String} changed (date) (optional)
555      * @property {String} reason (optional)
556      * @property {Array} files - the files that have changed. 
557      * 
558      */
559      
560     public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files  ) throws Error, SpawnError
561     {
562         
563
564         /*
565         var env = [];
566
567         if (typeof(cfg.name) != 'undefined') {
568             args.push( {
569                 'author' : cfg.name + ' <' + cfg.email + '>'
570             });
571             env.push(
572                 "GIT_COMMITTER_NAME" + cfg.name,
573                 "GIT_COMMITTER_EMAIL" + cfg.email
574             );
575         }
576
577         if (typeof(cfg.changed) != 'undefined') {
578             env.push("GIT_AUTHOR_DATE= " + cfg.changed )
579             
580         }
581         */
582         string[] args = { "commit", "-m" };
583         args +=  (message.length > 0  ? message : "Changed" );
584         for (var i = 0; i< files.size ; i++ ) {
585             args += files.get(i).vname; // full path?
586         }
587          
588         return this.git(args);
589     }
590     
591     /**
592      * pull:
593      * Fetch and merge remote repo changes into current branch..
594      *
595      * At present we just need this to update the current working branch..
596      * -- maybe later it will have a few options and do more stuff..
597      *
598      */
599     public string pull () throws Error, SpawnError
600     {
601         // should probably hand error conditions better... 
602         string[] cmd = { "pull" , "--no-edit" };
603         return this.git( cmd );
604
605         
606     }
607     
608     public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
609     public void pull_async(GitAsyncCallback cb) 
610     {
611     
612         string[] cmd = { "pull" , "--no-edit" };
613          this.git_async( cmd , cb);
614          
615     
616     }
617     
618     /**
619      * push:
620      * Send local changes to remote repo(s)
621      *
622      * At present we just need this to push the current branch.
623      * -- maybe later it will have a few options and do more stuff..
624      *
625      */
626     public string push () throws Error, SpawnError
627     {
628         // should 
629         return this.git({ "push"  });
630         
631     }
632     
633     
634     
635      /**
636      * git:
637      * The meaty part.. run spawn.. with git..
638      *
639      *
640      */
641     
642     public string git(string[] args_in ) throws Error, SpawnError
643     {
644         // convert arguments.
645         
646         string[]  args = { "git" };
647         //args +=  "--git-dir";
648         //args +=  this.gitdir;
649         args +=  "--no-pager";
650  
651  
652         //if (this.gitdir != this.repopath) {
653         //    args +=   "--work-tree";
654          //   args += this.repopath; 
655         //}
656         for (var i = 0; i < args_in.length;i++) {
657             args += args_in[i];
658         }            
659
660         //this.lastCmd = args.join(" ");
661         //if(this.debug) {
662             GLib.debug( "CWD=%s",  this.git_working_dir ); 
663             GLib.debug( "cmd: %s", string.joinv (" ", args)); 
664         //}
665
666         string[]   env = {};
667         string  home = "HOME=" + Environment.get_home_dir() ;
668         env +=  home ;
669         // do not need to set gitpath..
670         //if (File.exists(this.repo + '/.git/config')) {
671             //env.push("GITPATH=" + this.repo );
672         //}
673         
674
675         var cfg = new SpawnConfig(this.git_working_dir , args , env);
676         
677
678        // may throw error...
679         var sp = new Spawn(cfg);
680       
681
682         GLib.debug( "GOT: %s" , sp.output);
683         // parse output for some commands ?
684         return sp.output;
685     }
686         
687    unowned GitAsyncCallback git_async_on_callback;
688         public void  git_async( string[] args_in,   GitAsyncCallback cb ) throws Error, SpawnError
689     {
690         // convert arguments.
691        this.git_async_on_callback = cb;
692         string[]  args = { "git" };
693         //args +=  "--git-dir";
694         //args +=  this.gitdir;
695         args +=  "--no-pager";
696  
697  
698         //if (this.gitdir != this.repopath) {
699         //    args +=   "--work-tree";
700          //   args += this.repopath; 
701         //}
702         for (var i = 0; i < args_in.length;i++) {
703             args += args_in[i];
704         }            
705
706         //this.lastCmd = args.join(" ");
707         //if(this.debug) {
708             GLib.debug( "CWD=%s",  this.git_working_dir ); 
709             //print( "cmd: %s\n", string.joinv (" ", args)); 
710         //}
711
712         string[]   env = {};
713         string  home = "HOME=" + Environment.get_home_dir() ;
714         env +=  home ;
715         // do not need to set gitpath..
716         //if (File.exists(this.repo + '/.git/config')) {
717             //env.push("GITPATH=" + this.repo );
718         //}
719         
720
721         var cfg = new SpawnConfig(this.git_working_dir , args , env);
722         cfg.async = true;
723        
724
725        // may throw error...
726         var sp = new Spawn(cfg);
727                 //sp.ref();
728         //this.ref();
729         sp.run(this.git_async_on_complete); 
730          
731     }
732     
733     void git_async_on_complete(int err, string output)
734     {
735                 GLib.debug("GOT %d : %s", err, output);
736                 this.git_async_on_callback(this, err, output);
737 //              this.unref();   
738         //      sp.unref();             
739     
740     
741     }
742     
743 }