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