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                 if (ticket != null) {
348                 FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
349         } else {
350                 FileUtils.remove(this.gitdir + "/.gitlive-active-ticket" );
351         }
352         this.activeTicket = ticket;
353         return true;
354     }
355     
356     public bool createBranchNamed(string branchname)
357     {   
358                 
359                         var stash = false;
360                      if (this.branches.has_key(branchname)) {
361                         // this is where it get's tricky...
362                                 try {                   
363                                                 string[] cmd = { "ls-files" ,  "-m" };                   // list the modified files..
364                                             var ret = this.git(cmd);
365                                             stash = ret.length> 1 ;
366                                             
367                                                 
368                                             cmd = { "stash" };                  
369                                             if (stash) { this.git(cmd); }
370                                             
371                                             cmd = { "checkout", branchname  };
372                                             this.git(cmd);
373                                   } catch(Error e) {
374                                                 GitMonitor.gitmonitor.pauseError(e.message);
375                                                 return false;           
376                                   }
377                                   try {
378                                            if (branchname != "master") {
379                                                string[] cmd = { "merge", "master"  };
380                                                     this.git(cmd);
381                                                     this.push();
382                                                //cmd = { "commit",   "-a" , "-m",  "merge master changes" };
383                                        //git chethis.git( cmd );
384                                             }
385                                             
386                                    } catch(Error e) {
387                                             string[] cmd = { "checkout", "master"  };
388                                             this.git(cmd);
389                                                 GitMonitor.gitmonitor.pauseError(
390                                                         "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(
391                                                                 branchname)
392                                                          + e.message
393                                                 );
394                                                 return false;           
395                                          
396                                         }
397                                    try {                                        
398                                            string[]  cmd = { "stash", "pop"  };
399                                             if (stash) { this.git(cmd); }
400                                         } catch(Error ee) {
401                                                 GitMonitor.gitmonitor.pauseError(ee.message);
402                                                 return false;           
403                                         }
404                    this.push();
405                     
406                     } else {
407                                     try {                                       
408                                            
409                                         string[] cmd = { "checkout", "-b" , branchname  };
410                                         this.git(cmd);
411                        this.push();     
412                        cmd = { "branch", "--set-upstream-to=origin/"+branchname , branchname  };
413                                         this.git(cmd);
414                        
415                                         } catch(Error ee) {
416                                                 GitMonitor.gitmonitor.pauseError(ee.message);
417                                                 return false;           
418                                         }
419                             
420                     }
421                        var notification = new Notify.Notification(
422                        "Changed to branch %s".printf(branchname),
423                        "",
424                         "dialog-information"
425                        
426                );
427
428                notification.set_timeout(5);
429                notification.show();   
430        
431          
432          this.loadBranches(); // update branch list...
433          //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
434          return true;
435     }
436     
437     
438     /**
439      * add:
440      * add files to track.
441      *
442      * @argument {Array} files the files to add.
443      */
444     public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
445     {
446         // should really find out if these are untracked files each..
447         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
448         // not sure if that is how git works.. but just be certian.
449         var ret = "";
450         for (var i = 0; i < files.size;i++) {
451             var f = files.get(i).vname;
452             try {
453                 string[] cmd = { "add",    f  };
454                 this.git( cmd );
455             } catch (Error e) {
456                 ret += e.message  + "\n";
457             }        
458
459         }
460         return ret;
461     }
462         
463     public bool is_ignore(string fname) throws Error, SpawnError
464     {
465                 if (fname == ".gitignore") {
466                         this.ignore_files.clear();
467                 }
468                 
469                 if (this.ignore_files.has_key(fname)) {
470                         return this.ignore_files.get(fname);
471                 }
472                 
473                 try {
474                         var ret = this.git( { "check-ignore" , fname } );
475                         this.ignore_files.set(fname, ret.length >  0);
476                         return ret.length > 0;
477                 } catch (SpawnError e) {
478                         this.ignore_files.set(fname, false);
479                         return false;
480                 }
481                  
482     } 
483     
484     
485       /**
486      * remove:
487      * remove files to track.
488      *
489      * @argument {Array} files the files to add.
490      */
491     public string remove  ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
492     {
493         // this may fail if files do not exist..
494         // should really find out if these are untracked files each..
495         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
496         // not sure if that is how git works.. but just be certian.
497         var ret = "";
498
499         for (var i = 0; i < files.size;i++) {
500             var f = files.get(i).vname;
501             try {
502                 string[] cmd = { "rm",  "-f" ,  f  };
503                 this.git( cmd );
504             } catch (Error e) {
505                 ret += e.message  + "\n";
506             }        
507         }
508
509         return ret;
510
511     }
512     
513     
514     /**
515      * commit:
516      * perform a commit.
517      *
518      * @argument {Object} cfg commit configuration
519      * 
520      * @property {String} name (optional)
521      * @property {String} email (optional)
522      * @property {String} changed (date) (optional)
523      * @property {String} reason (optional)
524      * @property {Array} files - the files that have changed. 
525      * 
526      */
527      
528     public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files  ) throws Error, SpawnError
529     {
530         
531
532         /*
533         var env = [];
534
535         if (typeof(cfg.name) != 'undefined') {
536             args.push( {
537                 'author' : cfg.name + ' <' + cfg.email + '>'
538             });
539             env.push(
540                 "GIT_COMMITTER_NAME" + cfg.name,
541                 "GIT_COMMITTER_EMAIL" + cfg.email
542             );
543         }
544
545         if (typeof(cfg.changed) != 'undefined') {
546             env.push("GIT_AUTHOR_DATE= " + cfg.changed )
547             
548         }
549         */
550         string[] args = { "commit", "-m" };
551         args +=  (message.length > 0  ? message : "Changed" );
552         for (var i = 0; i< files.size ; i++ ) {
553             args += files.get(i).vname; // full path?
554         }
555          
556         return this.git(args);
557     }
558     
559     /**
560      * pull:
561      * Fetch and merge remote repo changes into current branch..
562      *
563      * At present we just need this to update the current working branch..
564      * -- maybe later it will have a few options and do more stuff..
565      *
566      */
567     public string pull () throws Error, SpawnError
568     {
569         // should probably hand error conditions better... 
570         string[] cmd = { "pull" , "--no-edit" };
571         return this.git( cmd );
572
573         
574     }
575     
576     public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
577     public void pull_async(GitAsyncCallback cb) 
578     {
579     
580         string[] cmd = { "pull" , "--no-edit" };
581          this.git_async( cmd , cb);
582          
583     
584     }
585     
586     /**
587      * push:
588      * Send local changes to remote repo(s)
589      *
590      * At present we just need this to push the current branch.
591      * -- maybe later it will have a few options and do more stuff..
592      *
593      */
594     public string push () throws Error, SpawnError
595     {
596         // should 
597         return this.git({ "push", "--all" });
598         
599     }
600     
601     
602     
603      /**
604      * git:
605      * The meaty part.. run spawn.. with git..
606      *
607      *
608      */
609     
610     public string git(string[] args_in ) throws Error, SpawnError
611     {
612         // convert arguments.
613         
614         string[]  args = { "git" };
615         //args +=  "--git-dir";
616         //args +=  this.gitdir;
617         args +=  "--no-pager";
618  
619  
620         //if (this.gitdir != this.repopath) {
621         //    args +=   "--work-tree";
622          //   args += this.repopath; 
623         //}
624         for (var i = 0; i < args_in.length;i++) {
625             args += args_in[i];
626         }            
627
628         //this.lastCmd = args.join(" ");
629         //if(this.debug) {
630             GLib.debug( "CWD=%s",  this.git_working_dir ); 
631             GLib.debug( "cmd: %s", string.joinv (" ", args)); 
632         //}
633
634         string[]   env = {};
635         string  home = "HOME=" + Environment.get_home_dir() ;
636         env +=  home ;
637         // do not need to set gitpath..
638         //if (File.exists(this.repo + '/.git/config')) {
639             //env.push("GITPATH=" + this.repo );
640         //}
641         
642
643         var cfg = new SpawnConfig(this.git_working_dir , args , env);
644         
645
646        // may throw error...
647         var sp = new Spawn(cfg);
648       
649
650         GLib.debug( "GOT: %s" , sp.output);
651         // parse output for some commands ?
652         return sp.output;
653     }
654         
655    unowned GitAsyncCallback git_async_on_callback;
656         public void  git_async( string[] args_in,   GitAsyncCallback cb ) throws Error, SpawnError
657     {
658         // convert arguments.
659        this.git_async_on_callback = cb;
660         string[]  args = { "git" };
661         //args +=  "--git-dir";
662         //args +=  this.gitdir;
663         args +=  "--no-pager";
664  
665  
666         //if (this.gitdir != this.repopath) {
667         //    args +=   "--work-tree";
668          //   args += this.repopath; 
669         //}
670         for (var i = 0; i < args_in.length;i++) {
671             args += args_in[i];
672         }            
673
674         //this.lastCmd = args.join(" ");
675         //if(this.debug) {
676             GLib.debug( "CWD=%s",  this.git_working_dir ); 
677             //print( "cmd: %s\n", string.joinv (" ", args)); 
678         //}
679
680         string[]   env = {};
681         string  home = "HOME=" + Environment.get_home_dir() ;
682         env +=  home ;
683         // do not need to set gitpath..
684         //if (File.exists(this.repo + '/.git/config')) {
685             //env.push("GITPATH=" + this.repo );
686         //}
687         
688
689         var cfg = new SpawnConfig(this.git_working_dir , args , env);
690         cfg.async = true;
691        
692
693        // may throw error...
694         var sp = new Spawn(cfg);
695                 //sp.ref();
696         //this.ref();
697         sp.run(this.git_async_on_complete); 
698          
699     }
700     
701     void git_async_on_complete(int err, string output)
702     {
703                 GLib.debug("GOT %d : %s", err, output);
704                 this.git_async_on_callback(this, err, output);
705 //              this.unref();   
706         //      sp.unref();             
707     
708     
709     }
710     
711 }