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