GitRepo.vala
[gitlive] / GitRepo.vala
1
2 /**
3  * @class Scm.Git.Repo
4  *
5  * @extends Scm.Repo
6  * 
7  *
8  *
9  */
10 static GitRepo  _GitRepo; 
11  
12 public class GitRepo : Object
13 {
14      
15     public Gee.ArrayList<GitMonitorQueue> cmds;
16
17     public string name;
18     public string gitdir;
19     public string git_working_dir;
20     public bool debug = false;
21     
22     public Gee.HashMap<string,bool> ignore_files;
23     public GitBranch currentBranch;
24
25         public RooTicket? activeTicket;
26
27         public static GitRepo singleton()
28     {
29         if (_GitRepo == null) {
30             _GitRepo = new GitRepo.single();
31             _GitRepo.cache = new Gee.HashMap<string,GitRepo>();
32         }
33         return _GitRepo;
34     }
35  
36     /**
37     * index of.. matching gitpath..
38     */
39     public static int indexOf( Array<GitRepo> repos, string gitpath) {
40         // make a fake object to compare against..
41         var test_repo = GitRepo.get(gitpath);
42         
43         for(var i =0; i < repos.length; i++) {
44             if (repos.index(i).gitdir == test_repo.gitdir) {
45                 return i;
46             }
47         }
48         return -1;
49     
50     }
51     
52     public  Gee.HashMap<string,GitRepo> cache;
53     
54     
55     
56     public static   Array<GitRepo> list()
57     {
58
59         //if (GitRepo.list_cache !=  null) {
60         //    unowned  Array<GitRepo>    ret = GitRepo.list_cache;
61          //   return ret;
62         //}
63         var cache = GitRepo.singleton().cache;
64         var list_cache = new Array<GitRepo>();
65         
66         var dir = Environment.get_home_dir() + "/gitlive";
67         
68         var f = File.new_for_path(dir);
69         FileEnumerator file_enum;
70         try {
71             file_enum = f.enumerate_children(
72                 FileAttribute.STANDARD_DISPLAY_NAME + ","+ 
73                 FileAttribute.STANDARD_TYPE,
74                 FileQueryInfoFlags.NONE,
75                 null);
76         } catch (Error e) {
77             
78             return list_cache;
79             
80         }
81         
82         FileInfo next_file; 
83         
84         while (true) {
85             
86             try {
87                 next_file = file_enum.next_file(null);
88                 if (next_file == null) {
89                     break;
90                 }
91                 
92             } catch (Error e) {
93                 GLib.debug("Error: %s",e.message);
94                 break;
95             }
96          
97             //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
98             
99             if (next_file.get_file_type() !=  FileType.DIRECTORY) {
100                 next_file = null;
101                 continue;
102             }
103             
104             if (next_file.get_file_type() ==  FileType.SYMBOLIC_LINK) {
105                 next_file = null;
106                 continue;
107             }
108             
109             if (next_file.get_display_name()[0] == '.') {
110                 next_file = null;
111                 continue;
112             }
113             var sp = dir+"/"+next_file.get_display_name();
114            
115             var gitdir = dir + "/" + next_file.get_display_name() + "/.git";
116             
117             if (!FileUtils.test(gitdir, FileTest.IS_DIR)) {
118                 continue;
119             }
120             
121                 var rep =  GitRepo.get(  sp );
122                 list_cache.append_val(rep);             
123             
124         }
125     
126         return list_cache;
127         
128          
129           
130         }
131         
132         public static GitRepo get(string path) 
133         {
134                 var cache = GitRepo.singleton().cache;
135                 if (cache.has_key(path)) {
136                         return cache.get(path);
137                 }
138                 return new GitRepo(path);
139         }
140         
141     private GitRepo.single() {
142                 // used to create the signleton
143         }
144     /**
145      * constructor:
146      * 
147      * @param {Object} cfg - Configuration
148      *     (basically repopath is currently only critical one.)
149      *
150      */
151      
152     private GitRepo(string path) {
153         // cal parent?
154         this.name =   File.new_for_path(path).get_basename();
155         this.ignore_files = new Gee.HashMap<string,bool>();
156         
157         this.git_working_dir = path;
158         this.gitdir = path + "/.git";
159         if (!FileUtils.test(this.gitdir , FileTest.IS_DIR)) {
160             this.gitdir = path; // naked...
161         }
162         this.cmds = new  Gee.ArrayList<GitMonitorQueue> ();
163         
164                 var cache = GitRepo.singleton().cache;
165         //Repo.superclass.constructor.call(this,cfg);
166                 if ( !cache.has_key(path) ) {
167                         cache.set( path, this);
168         }
169         this.loadBranches();
170         this.loadActiveTicket();
171     } 
172     
173     public bool is_wip_branch()
174     {
175         return this.currentBranch.name.has_prefix("wip_");
176                 
177     }
178     
179     public bool is_autocommit ()
180     {
181         return !FileUtils.test(this.gitdir + "/.gitlive-disable-autocommit" , FileTest.EXISTS);
182     }
183     public void set_autocommit(bool val)
184     {
185                 GLib.debug("SET auto commit : %s => %s", val ? "ON" : "OFF",  cur  ? "ON" : "OFF");
186                 var cur = this.is_autocommit();
187                 if (cur == val) {
188                         return; // no change..
189                 }
190                 if (!cur) {
191                         FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autocommit" , "x");
192                 } else {
193                         // it exists...
194                         FileUtils.remove(this.gitdir + "/.gitlive-disable-autocommit" ); 
195                 }
196     
197     }
198     
199     public bool is_auto_branch ()
200     {
201         return FileUtils.test(this.gitdir + "/.gitlive-enable-auto-branch" , FileTest.EXISTS);
202     }
203     
204     public void set_auto_branch(bool val)
205     {
206
207                 var cur = this.is_auto_branch();
208                 GLib.debug("SET auto branch : %s => %s", val ? "ON" : "OFF",  cur  ? "ON" : "OFF");
209                 
210                 if (cur == val) {
211                         return; // no change..
212                 }
213                 if (cur) {
214                         FileUtils.set_contents(this.gitdir + "/.gitlive-enable-auto-branch" , "x");
215                 } else {
216                         // it exists...
217                         FileUtils.remove(this.gitdir + "/.gitlive-enable-auto-branch" ); 
218                 }
219     
220     }
221     public bool is_autopush ()
222     {
223         return !FileUtils.test(this.gitdir + "/.gitlive-disable-autopush" , FileTest.EXISTS);
224     }
225     public void set_autopush(bool val)
226     {
227                 GLib.debug("SET auto push : %s", val ? "ON" : "OFF");
228                 var cur = this.is_autopush();
229                 if (cur == val) {
230                         return; // no change..
231                 }
232                 if (!cur) {
233                         FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autopush" , "");
234                 } else {
235                         // it exists...
236                         FileUtils.remove(this.gitdir + "/.gitlive-disable-autopush" ); 
237                 }
238     
239     }
240     
241     
242     
243     Gee.HashMap<string,GitBranch> branches;
244     
245     public void loadBranches()
246     {
247         this.branches = new Gee.HashMap<string,GitBranch>();
248         
249         string[] cmd = { "branch",   "--no-color", "--verbose", "--no-abbrev" , "-a"  };
250         var res = this.git( cmd );
251         var lines = res.split("\n");
252         for (var i = 0; i < lines.length ; i++) {
253                 var br = new GitBranch(this);
254                 if (!br.parseBranchListItem(lines[i])) {
255                         continue;
256                 }
257                 GLib.debug("add branch %s", br.realName());
258                  
259                 branches.set(br.realName(), br);
260                 if (br.active) {
261                         this.currentBranch = br;
262                 }
263         }
264     
265     }
266      
267     
268     
269     
270     public string branchesToString()
271     {
272         var ret = "";
273                 foreach( var br in this.branches.values) {
274                         if (br.name == "") {
275                                 continue; 
276                         }
277                         ret += ret.length > 0 ? ","  : "";
278                         ret += br.name;
279                 
280                 }
281                 return ret;
282         
283     }
284      public static void doMerges(string action, string ticket_id, string commit_message)
285     {
286        GitMonitor.gitmonitor.stop();
287        
288        var commitrevs = "";
289        var sucess = true;
290        foreach(var  repo in GitRepo.singleton().cache.values) {
291                if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
292                        var res = repo.doMerge(action,ticket_id, commit_message);
293                        if (!res) {
294                                sucess = false;
295                                continue;
296                        }
297                        commitrevs += commitrevs.length > 0 ? " " : "";
298                        commitrevs += repo.currentBranch.lastrev;
299                }
300        }
301        if (sucess && action == "CLOSE") {
302                RooTicket.singleton().getById(ticket_id).close(commitrevs);
303        }
304        GitMonitor.gitmonitor.start();
305     }
306      
307
308     public bool doMerge(string action, string ticket_id, string commit_message)
309     {
310        // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
311        // also need to decide which branch we will merge into?
312                    var ret = "";
313                    if (action == "CLOSE" || action == "LEAVE") {
314                                    
315                try {
316                    var oldbranch = this.currentBranch.name;
317                    this.setActiveTicket(null, "master");
318                            string [] cmd = { "merge",   "--squash",  oldbranch };
319                            this.git( cmd );
320                            cmd = { "commit",   "-a" , "-m",  commit_message };
321                            this.git( cmd );
322                            this.push();
323                            this.loadBranches(); // updates lastrev..
324                
325                        var notification = new Notify.Notification(
326                                "Merged branch %s to master".printf(oldbranch),
327                                "",
328                                 "dialog-information"
329                                
330                        );
331
332                        notification.set_timeout(5);
333                        notification.show();   
334                
335                // close ticket..
336                return true; 
337                
338            } catch (Error e) {
339
340                GitMonitor.gitmonitor.pauseError(e.message);
341                return false;
342            }
343            // error~?? -- show the error dialog...
344                    return false;
345        }
346        if (action == "MASTER") {
347                // merge master into ours..
348                        try {
349                        string[] cmd = { "merge",  "master" };
350                        this.git( cmd );
351                        var notification = new Notify.Notification(
352                                        "Merged code from master to %s".printf(this.currentBranch.name),
353                                        "",
354                                         "dialog-information"
355                                        
356                                );
357                                notification.set_timeout(5);
358                                notification.show();   
359                       
360                        return true;
361                        } catch (Error e) {
362                        GitMonitor.gitmonitor.pauseError(e.message);
363                        return false;
364                    }
365            }
366        if (action == "EXIT") {
367                        try {
368                        var oldbranch  = this.currentBranch.name;
369                          this.setActiveTicket(null, "master");
370                        this.loadBranches();
371                        var notification = new Notify.Notification(
372                                        "Left branch %s".printf(oldbranch),
373                                        "",
374                                         "dialog-information"
375                                        
376                                );
377                                notification.set_timeout(5);
378                                notification.show();   
379                        
380                        return true;
381                    } catch (Error e) {
382                        GitMonitor.gitmonitor.pauseError(e.message);
383
384                        return false;                   
385                    }
386                    // error~?? -- show the error dialog...
387
388        }
389        return false;
390     }
391         
392     public void loadActiveTicket()
393     {
394         this.activeTicket = null;
395         if (!FileUtils.test(this.gitdir + "/.gitlive-active-ticket" , FileTest.EXISTS)) {
396                 return;
397         }
398         string ticket_id;
399         FileUtils.get_contents(this.gitdir + "/.gitlive-active-ticket" , out ticket_id);  
400         if (ticket_id.length < 1) {
401                 return;
402                 }
403                 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
404         
405         
406     }
407     
408     
409     
410     public bool setActiveTicket(RooTicket? ticket, string branchname)
411     {
412         if (!this.createBranchNamed(branchname)) {
413                 return false;
414                 }
415                 if (ticket != null) {
416                 FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
417         } else {
418                 FileUtils.remove(this.gitdir + "/.gitlive-active-ticket" );
419         }
420         this.activeTicket = ticket;
421         return true;
422     }
423     
424     public bool createBranchNamed(string branchname)
425     {   
426                 
427                         var stash = false;
428                      if (this.branches.has_key(branchname)) {
429                         // this is where it get's tricky...
430                                 try {                   
431                                                 string[] cmd = { "ls-files" ,  "-m" };                   // list the modified files..
432                                             var ret = this.git(cmd);
433                                             stash = ret.length> 1 ;
434                                             
435                                                 
436                                             cmd = { "stash" };                  
437                                             if (stash) { this.git(cmd); }
438                                             
439                                             cmd = { "checkout", branchname  };
440                                             this.git(cmd);
441                                   } catch(Error e) {
442                                                 GitMonitor.gitmonitor.pauseError(e.message);
443                                                 return false;           
444                                   }
445                                   try {
446                                            if (branchname != "master") {
447                                                string[] cmd = { "merge", "master"  };
448                                                     this.git(cmd);
449                                                     this.push();
450                                                //cmd = { "commit",   "-a" , "-m",  "merge master changes" };
451                                        //git chethis.git( cmd );
452                                             }
453                                             
454                                    } catch(Error e) {
455                                             string[] cmd = { "checkout", "master"  };
456                                             this.git(cmd);
457                                                 GitMonitor.gitmonitor.pauseError(
458                                                         "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(
459                                                                 branchname)
460                                                          + e.message
461                                                 );
462                                                 return false;           
463                                          
464                                         }
465                                    try {                                        
466                                            string[]  cmd = { "stash", "pop"  };
467                                             if (stash) { this.git(cmd); }
468                                         } catch(Error ee) {
469                                                 GitMonitor.gitmonitor.pauseError(ee.message);
470                                                 return false;           
471                                         }
472                    this.push();
473                     
474                     } else {
475                                     try {                                       
476                                            
477                                         string[] cmd = { "checkout", "-b" , branchname  };
478                                         this.git(cmd);
479
480                        cmd = { "branch", "--set-upstream-to=origin/"+branchname , branchname  };
481                                         this.git(cmd);
482                        this.push();                            
483                                         } catch(Error ee) {
484                                                 GitMonitor.gitmonitor.pauseError(ee.message);
485                                                 return false;           
486                                         }
487                             
488                     }
489                        var notification = new Notify.Notification(
490                        "Changed to branch %s".printf(branchname),
491                        "",
492                         "dialog-information"
493                        
494                );
495
496                notification.set_timeout(5);
497                notification.show();   
498        
499          
500          this.loadBranches(); // update branch list...
501          //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
502          return true;
503     }
504     
505     
506     /**
507      * add:
508      * add files to track.
509      *
510      * @argument {Array} files the files to add.
511      */
512     public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
513     {
514         // should really find out if these are untracked files each..
515         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
516         // not sure if that is how git works.. but just be certian.
517         var ret = "";
518         for (var i = 0; i < files.size;i++) {
519             var f = files.get(i).vname;
520             try {
521                 string[] cmd = { "add",    f  };
522                 this.git( cmd );
523             } catch (Error e) {
524                 ret += e.message  + "\n";
525             }        
526
527         }
528         return ret;
529     }
530         
531     public bool is_ignore(string fname) throws Error, SpawnError
532     {
533                 if (fname == ".gitignore") {
534                         this.ignore_files.clear();
535                 }
536                 
537                 if (this.ignore_files.has_key(fname)) {
538                         return this.ignore_files.get(fname);
539                 }
540                 
541                 try {
542                         var ret = this.git( { "check-ignore" , fname } );
543                         this.ignore_files.set(fname, ret.length >  0);
544                         return ret.length > 0;
545                 } catch (SpawnError e) {
546                         this.ignore_files.set(fname, false);
547                         return false;
548                 }
549                  
550     } 
551     
552     
553       /**
554      * remove:
555      * remove files to track.
556      *
557      * @argument {Array} files the files to add.
558      */
559     public string remove  ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
560     {
561         // this may fail if files do not exist..
562         // should really find out if these are untracked files each..
563         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
564         // not sure if that is how git works.. but just be certian.
565         var ret = "";
566
567         for (var i = 0; i < files.size;i++) {
568             var f = files.get(i).vname;
569             try {
570                 string[] cmd = { "rm",  "-f" ,  f  };
571                 this.git( cmd );
572             } catch (Error e) {
573                 ret += e.message  + "\n";
574             }        
575         }
576
577         return ret;
578
579     }
580     
581     
582     /**
583      * commit:
584      * perform a commit.
585      *
586      * @argument {Object} cfg commit configuration
587      * 
588      * @property {String} name (optional)
589      * @property {String} email (optional)
590      * @property {String} changed (date) (optional)
591      * @property {String} reason (optional)
592      * @property {Array} files - the files that have changed. 
593      * 
594      */
595      
596     public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files  ) throws Error, SpawnError
597     {
598         
599
600         /*
601         var env = [];
602
603         if (typeof(cfg.name) != 'undefined') {
604             args.push( {
605                 'author' : cfg.name + ' <' + cfg.email + '>'
606             });
607             env.push(
608                 "GIT_COMMITTER_NAME" + cfg.name,
609                 "GIT_COMMITTER_EMAIL" + cfg.email
610             );
611         }
612
613         if (typeof(cfg.changed) != 'undefined') {
614             env.push("GIT_AUTHOR_DATE= " + cfg.changed )
615             
616         }
617         */
618         string[] args = { "commit", "-m" };
619         args +=  (message.length > 0  ? message : "Changed" );
620         for (var i = 0; i< files.size ; i++ ) {
621             args += files.get(i).vname; // full path?
622         }
623          
624         return this.git(args);
625     }
626     
627     /**
628      * pull:
629      * Fetch and merge remote repo changes into current branch..
630      *
631      * At present we just need this to update the current working branch..
632      * -- maybe later it will have a few options and do more stuff..
633      *
634      */
635     public string pull () throws Error, SpawnError
636     {
637         // should probably hand error conditions better... 
638         string[] cmd = { "pull" , "--no-edit" };
639         return this.git( cmd );
640
641         
642     }
643     
644     public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
645     public void pull_async(GitAsyncCallback cb) 
646     {
647     
648         string[] cmd = { "pull" , "--no-edit" };
649          this.git_async( cmd , cb);
650          
651     
652     }
653     
654     /**
655      * push:
656      * Send local changes to remote repo(s)
657      *
658      * At present we just need this to push the current branch.
659      * -- maybe later it will have a few options and do more stuff..
660      *
661      */
662     public string push () throws Error, SpawnError
663     {
664         // should 
665         return this.git({ "push"  });
666         
667     }
668     
669     
670     
671      /**
672      * git:
673      * The meaty part.. run spawn.. with git..
674      *
675      *
676      */
677     
678     public string git(string[] args_in ) throws Error, SpawnError
679     {
680         // convert arguments.
681         
682         string[]  args = { "git" };
683         //args +=  "--git-dir";
684         //args +=  this.gitdir;
685         args +=  "--no-pager";
686  
687  
688         //if (this.gitdir != this.repopath) {
689         //    args +=   "--work-tree";
690          //   args += this.repopath; 
691         //}
692         for (var i = 0; i < args_in.length;i++) {
693             args += args_in[i];
694         }            
695
696         //this.lastCmd = args.join(" ");
697         //if(this.debug) {
698             GLib.debug( "CWD=%s",  this.git_working_dir ); 
699             GLib.debug( "cmd: %s", string.joinv (" ", args)); 
700         //}
701
702         string[]   env = {};
703         string  home = "HOME=" + Environment.get_home_dir() ;
704         env +=  home ;
705         // do not need to set gitpath..
706         //if (File.exists(this.repo + '/.git/config')) {
707             //env.push("GITPATH=" + this.repo );
708         //}
709         
710
711         var cfg = new SpawnConfig(this.git_working_dir , args , env);
712         
713
714        // may throw error...
715         var sp = new Spawn(cfg);
716       
717
718         GLib.debug( "GOT: %s" , sp.output);
719         // parse output for some commands ?
720         return sp.output;
721     }
722         
723    unowned GitAsyncCallback git_async_on_callback;
724         public void  git_async( string[] args_in,   GitAsyncCallback cb ) throws Error, SpawnError
725     {
726         // convert arguments.
727        this.git_async_on_callback = cb;
728         string[]  args = { "git" };
729         //args +=  "--git-dir";
730         //args +=  this.gitdir;
731         args +=  "--no-pager";
732  
733  
734         //if (this.gitdir != this.repopath) {
735         //    args +=   "--work-tree";
736          //   args += this.repopath; 
737         //}
738         for (var i = 0; i < args_in.length;i++) {
739             args += args_in[i];
740         }            
741
742         //this.lastCmd = args.join(" ");
743         //if(this.debug) {
744             GLib.debug( "CWD=%s",  this.git_working_dir ); 
745             //print( "cmd: %s\n", string.joinv (" ", args)); 
746         //}
747
748         string[]   env = {};
749         string  home = "HOME=" + Environment.get_home_dir() ;
750         env +=  home ;
751         // do not need to set gitpath..
752         //if (File.exists(this.repo + '/.git/config')) {
753             //env.push("GITPATH=" + this.repo );
754         //}
755         
756
757         var cfg = new SpawnConfig(this.git_working_dir , args , env);
758         cfg.async = true;
759        
760
761        // may throw error...
762         var sp = new Spawn(cfg);
763                 //sp.ref();
764         //this.ref();
765         sp.run(this.git_async_on_complete); 
766          
767     }
768     
769     void git_async_on_complete(int err, string output)
770     {
771                 GLib.debug("GOT %d : %s", err, output);
772                 this.git_async_on_callback(this, err, output);
773 //              this.unref();   
774         //      sp.unref();             
775     
776     
777     }
778     
779 }