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