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