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 = null;
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         
133         
134         
135         public static GitRepo get(string path) 
136         {
137                 //GLib.debug("get Repo %s", path);
138                 var cache = GitRepo.singleton().cache;
139                 if (cache.has_key(path)) {
140                         return cache.get(path);
141                 }
142                 return new GitRepo(path);
143         }
144         
145     private GitRepo.single() {
146                 // used to create the signleton
147         }
148     /**
149      * constructor:
150      * 
151      * @param {Object} cfg - Configuration
152      *     (basically repopath is currently only critical one.)
153      *
154      */
155      
156     private GitRepo(string path) {
157         // cal parent?
158         this.name =   File.new_for_path(path).get_basename();
159         this.ignore_files = new Gee.HashMap<string,bool>();
160         
161         this.git_working_dir = path;
162         this.gitdir = path + "/.git";
163         if (!FileUtils.test(this.gitdir , FileTest.IS_DIR)) {
164             this.gitdir = path; // naked...
165         }
166         this.cmds = new  Gee.ArrayList<GitMonitorQueue> ();
167         
168                 var cache = GitRepo.singleton().cache;
169         //Repo.superclass.constructor.call(this,cfg);
170                 if ( !cache.has_key(path) ) {
171                         cache.set( path, this);
172         }
173         this.loadBranches();
174         this.loadTicket();
175     } 
176     
177     public bool is_wip_branch()
178     {
179         return this.currentBranch.name.has_prefix("wip_");
180                 
181     }
182     
183     public bool is_autocommit ()
184     {
185         return !FileUtils.test(this.gitdir + "/.gitlive-disable-autocommit" , 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     public string branchesToString()
217     {
218         var ret = "";
219                 foreach( var br in this.branches.values) {
220                         if (br.name == "") {
221                                 continue; 
222                         }
223                         ret += ret.length > 0 ? ","  : "";
224                         ret += br.name;
225                 
226                 }
227                 return ret;
228         
229     }
230     //RooTicket? ticket = null;
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  
265                         try {
266                                 var oldbranch = this.currentBranch.name;
267                                 this.setActiveTicket(null, "master");
268                         string [] cmd = { "merge",   "--squash",  oldbranch };
269                         this.git( cmd );
270                          cmd = { "commit",   "--m",  commit_message };
271                         this.git( cmd );
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     
343     
344     public void setActiveTicket(RooTicket? ticket, string branchname)
345     {
346         this.createBranchNamed(branchname);
347         if (ticket != null) {
348                 FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
349         } else {
350                 if (FileUtils.test(this.gitdir + "/.gitlive-active-ticket",FileTest.EXISTS)) {
351                         FileUtils.remove(this.gitdir + "/.gitlive-active-ticket");
352                         }
353                 }
354         
355         this.activeTicket = ticket;
356     }
357     
358     
359     
360     public void loadTicket()
361     {
362         if (this.activeTicket != null) { // assumes merge will clear this...
363                 return;
364         }
365         if (!FileUtils.test(this.gitdir + "/.gitlive-active-ticket",FileTest.EXISTS)) {
366                 return;
367                 }
368                 string ticket_id;
369                 FileUtils.get_contents(this.gitdir + "/.gitlive-active-ticket" , out  ticket_id);
370                 this.activeTicket = RooTicket.singleton().getById(ticket_id);
371     }
372     
373     
374     
375     
376     
377     public void createBranchNamed(string branchname)
378     {
379                 if (this.branches.has_key(branchname)) {
380                          string[] cmd = { "checkout", branchname  };
381                          this.git(cmd);         
382                 } else {
383                          string[] cmd = { "checkout", "-b" , branchname  };
384                          this.git(cmd);
385                  }
386          this.loadBranches(); // update branch list...
387          GitMonitor.gitmonitor.runQueue(); // commit any outstanding...
388     }
389     
390      
391     
392     
393     /**
394      * add:
395      * add files to track.
396      *
397      * @argument {Array} files the files to add.
398      */
399     public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
400     {
401         // should really find out if these are untracked files each..
402         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
403         // not sure if that is how git works.. but just be certian.
404         var ret = "";
405         for (var i = 0; i < files.size;i++) {
406             var f = files.get(i).vname;
407             try {
408                 string[] cmd = { "add",    f  };
409                 this.git( cmd );
410             } catch (Error e) {
411                 ret += e.message  + "\n";
412             }        
413
414         }
415         return ret;
416     }
417         
418     public bool is_ignore(string fname) throws Error, SpawnError
419     {
420                 if (fname == ".gitignore") {
421                         this.ignore_files.clear();
422                 }
423                 
424                 if (this.ignore_files.has_key(fname)) {
425                         return this.ignore_files.get(fname);
426                 }
427                 
428                 try {
429                         var ret = this.git( { "check-ignore" , fname } );
430                         this.ignore_files.set(fname, ret.length >  0);
431                         return ret.length > 0;
432                 } catch (SpawnError e) {
433                         this.ignore_files.set(fname, false);
434                         return false;
435                 }
436                  
437     } 
438     
439     
440       /**
441      * remove:
442      * remove files to track.
443      *
444      * @argument {Array} files the files to add.
445      */
446     public string remove  ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
447     {
448         // this may fail if files do not exist..
449         // should really find out if these are untracked files each..
450         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
451         // not sure if that is how git works.. but just be certian.
452         var ret = "";
453
454         for (var i = 0; i < files.size;i++) {
455             var f = files.get(i).vname;
456             try {
457                 string[] cmd = { "rm",  "-f" ,  f  };
458                 this.git( cmd );
459             } catch (Error e) {
460                 ret += e.message  + "\n";
461             }        
462         }
463
464         return ret;
465
466     }
467     
468     
469     /**
470      * commit:
471      * perform a commit.
472      *
473      * @argument {Object} cfg commit configuration
474      * 
475      * @property {String} name (optional)
476      * @property {String} email (optional)
477      * @property {String} changed (date) (optional)
478      * @property {String} reason (optional)
479      * @property {Array} files - the files that have changed. 
480      * 
481      */
482      
483     public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files  ) throws Error, SpawnError
484     {
485         
486
487         /*
488         var env = [];
489
490         if (typeof(cfg.name) != 'undefined') {
491             args.push( {
492                 'author' : cfg.name + ' <' + cfg.email + '>'
493             });
494             env.push(
495                 "GIT_COMMITTER_NAME" + cfg.name,
496                 "GIT_COMMITTER_EMAIL" + cfg.email
497             );
498         }
499
500         if (typeof(cfg.changed) != 'undefined') {
501             env.push("GIT_AUTHOR_DATE= " + cfg.changed )
502             
503         }
504         */
505         string[] args = { "commit", "-m" };
506         args +=  (message.length > 0  ? message : "Changed" );
507         for (var i = 0; i< files.size ; i++ ) {
508             args += files.get(i).vname; // full path?
509         }
510          
511         return this.git(args);
512     }
513     
514     /**
515      * pull:
516      * Fetch and merge remote repo changes into current branch..
517      *
518      * At present we just need this to update the current working branch..
519      * -- maybe later it will have a few options and do more stuff..
520      *
521      */
522     public string pull () throws Error, SpawnError
523     {
524         // should probably hand error conditions better... 
525         string[] cmd = { "pull" , "--no-edit" };
526         return this.git( cmd );
527
528         
529     }
530     
531     public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
532     public void pull_async(GitAsyncCallback cb) 
533     {
534     
535         string[] cmd = { "pull" , "--no-edit" };
536          this.git_async( cmd , cb);
537          
538     
539     }
540     
541     /**
542      * push:
543      * Send local changes to remote repo(s)
544      *
545      * At present we just need this to push the current branch.
546      * -- maybe later it will have a few options and do more stuff..
547      *
548      */
549     public string push () throws Error, SpawnError
550     {
551         // should 
552         return this.git({ "push", "origin", "HEAD" });
553         
554     }
555     
556     
557     
558      /**
559      * git:
560      * The meaty part.. run spawn.. with git..
561      *
562      *
563      */
564     
565     public string git(string[] args_in ) throws Error, SpawnError
566     {
567         // convert arguments.
568         
569         string[]  args = { "git" };
570         //args +=  "--git-dir";
571         //args +=  this.gitdir;
572         args +=  "--no-pager";
573  
574  
575         //if (this.gitdir != this.repopath) {
576         //    args +=   "--work-tree";
577          //   args += this.repopath; 
578         //}
579         for (var i = 0; i < args_in.length;i++) {
580             args += args_in[i];
581         }            
582
583         //this.lastCmd = args.join(" ");
584         //if(this.debug) {
585             GLib.debug( "CWD=%s",  this.git_working_dir ); 
586             GLib.debug( "cmd: %s", string.joinv (" ", args)); 
587         //}
588
589         string[]   env = {};
590         string  home = "HOME=" + Environment.get_home_dir() ;
591         env +=  home ;
592         // do not need to set gitpath..
593         //if (File.exists(this.repo + '/.git/config')) {
594             //env.push("GITPATH=" + this.repo );
595         //}
596         
597
598         var cfg = new SpawnConfig(this.git_working_dir , args , env);
599         
600
601        // may throw error...
602         var sp = new Spawn(cfg);
603       
604
605         GLib.debug( "GOT: %s" , sp.output);
606         // parse output for some commands ?
607         return sp.output;
608     }
609         
610    unowned GitAsyncCallback git_async_on_callback;
611         public void  git_async( string[] args_in,   GitAsyncCallback cb ) throws Error, SpawnError
612     {
613         // convert arguments.
614        this.git_async_on_callback = cb;
615         string[]  args = { "git" };
616         //args +=  "--git-dir";
617         //args +=  this.gitdir;
618         args +=  "--no-pager";
619  
620  
621         //if (this.gitdir != this.repopath) {
622         //    args +=   "--work-tree";
623          //   args += this.repopath; 
624         //}
625         for (var i = 0; i < args_in.length;i++) {
626             args += args_in[i];
627         }            
628
629         //this.lastCmd = args.join(" ");
630         //if(this.debug) {
631             GLib.debug( "CWD=%s",  this.git_working_dir ); 
632             //print( "cmd: %s\n", string.joinv (" ", args)); 
633         //}
634
635         string[]   env = {};
636         string  home = "HOME=" + Environment.get_home_dir() ;
637         env +=  home ;
638         // do not need to set gitpath..
639         //if (File.exists(this.repo + '/.git/config')) {
640             //env.push("GITPATH=" + this.repo );
641         //}
642         
643
644         var cfg = new SpawnConfig(this.git_working_dir , args , env);
645         cfg.async = true;
646        
647
648        // may throw error...
649         var sp = new Spawn(cfg);
650                 //sp.ref();
651         //this.ref();
652         sp.run(this.git_async_on_complete); 
653          
654     }
655     
656     void git_async_on_complete(int err, string output)
657     {
658                 GLib.debug("GOT %d : %s", err, output);
659                 this.git_async_on_callback(this, err, output);
660 //              this.unref();   
661         //      sp.unref();             
662     
663     
664     }
665     
666 }