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 Array<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  Array<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     } 
170     
171     
172     public bool is_autocommit ()
173     {
174         return !FileUtils.test(this.gitdir + "/.gitlive-disable-autocommit" , FileTest.EXISTS);
175     }
176     public bool is_autopush ()
177     {
178         return !FileUtils.test(this.gitdir + "/.gitlive-disable-autopush" , FileTest.EXISTS);
179     }
180     
181     Gee.HashMap<string,GitBranch> branches;
182     
183     public void loadBranches()
184     {
185         this.branches = new Gee.HashMap<string,GitBranch>();
186         
187         string[] cmd = { "branch",   "--no-color", "--verbose", "--no-abbrev" , "-a"  };
188         var res = this.git( cmd );
189         var lines = res.split("\n");
190         for (var i = 0; i < lines.length ; i++) {
191                 var br = new GitBranch(this);
192                 if (!br.parseBranchListItem(lines[i])) {
193                         continue;
194                 }
195                 GLib.debug("add branch %s", br.realName());
196                  
197                 branches.set(br.realName(), br);
198                 if (br.active) {
199                         this.currentBranch = br;
200                 }
201         }
202     
203     }
204      
205     
206     
207     
208     public string branchesToString()
209     {
210         var ret = "";
211                 foreach( var br in this.branches.values) {
212                         if (br.name == "") {
213                                 continue; 
214                         }
215                         ret += ret.length > 0 ? ","  : "";
216                         ret += br.name;
217                 
218                 }
219                 return ret;
220         
221     }
222     RooTicket? ticket = null;
223     
224     public void setActiveTicket(RooTicket ticket, string branchname)
225     {
226         this.createBranchNamed(branchname);
227         FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
228         this.activeTicket = ticket;
229     }
230     
231     public void createBranchNamed(string branchname)
232     {
233          string[] cmd = { "checkout", "-b" , branchname  };
234          this.git(cmd);
235          this.loadBranches(); // update branch list...
236     }
237     
238     
239     /**
240      * add:
241      * add files to track.
242      *
243      * @argument {Array} files the files to add.
244      */
245     public string add ( Array<GitMonitorQueue> files ) throws Error, SpawnError
246     {
247         // should really find out if these are untracked files each..
248         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
249         // not sure if that is how git works.. but just be certian.
250         var ret = "";
251         for (var i = 0; i < files.length;i++) {
252             var f = files.index(i).vname;
253             try {
254                 string[] cmd = { "add",    f  };
255                 this.git( cmd );
256             } catch (Error e) {
257                 ret += e.message  + "\n";
258             }        
259
260         }
261         return ret;
262     }
263         
264     public bool is_ignore(string fname) throws Error, SpawnError
265     {
266                 if (fname == ".gitignore") {
267                         this.ignore_files.clear();
268                 }
269                 
270                 if (this.ignore_files.has_key(fname)) {
271                         return this.ignore_files.get(fname);
272                 }
273                 
274                 try {
275                         var ret = this.git( { "check-ignore" , fname } );
276                         this.ignore_files.set(fname, ret.length >  0);
277                         return ret.length > 0;
278                 } catch (SpawnError e) {
279                         this.ignore_files.set(fname, false);
280                         return false;
281                 }
282                  
283     } 
284     
285     
286       /**
287      * remove:
288      * remove files to track.
289      *
290      * @argument {Array} files the files to add.
291      */
292     public string remove  ( Array<GitMonitorQueue> files ) throws Error, SpawnError
293     {
294         // this may fail if files do not exist..
295         // should really find out if these are untracked files each..
296         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
297         // not sure if that is how git works.. but just be certian.
298         var ret = "";
299
300         for (var i = 0; i < files.length;i++) {
301             var f = files.index(i).vname;
302             try {
303                 string[] cmd = { "rm",  "-f" ,  f  };
304                 this.git( cmd );
305             } catch (Error e) {
306                 ret += e.message  + "\n";
307             }        
308         }
309
310         return ret;
311
312     }
313     
314     
315     /**
316      * commit:
317      * perform a commit.
318      *
319      * @argument {Object} cfg commit configuration
320      * 
321      * @property {String} name (optional)
322      * @property {String} email (optional)
323      * @property {String} changed (date) (optional)
324      * @property {String} reason (optional)
325      * @property {Array} files - the files that have changed. 
326      * 
327      */
328      
329     public string commit ( string message, Array<GitMonitorQueue> files  ) throws Error, SpawnError
330     {
331         
332
333         /*
334         var env = [];
335
336         if (typeof(cfg.name) != 'undefined') {
337             args.push( {
338                 'author' : cfg.name + ' <' + cfg.email + '>'
339             });
340             env.push(
341                 "GIT_COMMITTER_NAME" + cfg.name,
342                 "GIT_COMMITTER_EMAIL" + cfg.email
343             );
344         }
345
346         if (typeof(cfg.changed) != 'undefined') {
347             env.push("GIT_AUTHOR_DATE= " + cfg.changed )
348             
349         }
350         */
351         string[] args = { "commit", "-m" };
352         args +=  (message.length > 0  ? message : "Changed" );
353         for (var i = 0; i< files.length ; i++ ) {
354             args += files.index(i).vname; // full path?
355         }
356          
357         return this.git(args);
358     }
359     
360     /**
361      * pull:
362      * Fetch and merge remote repo changes into current branch..
363      *
364      * At present we just need this to update the current working branch..
365      * -- maybe later it will have a few options and do more stuff..
366      *
367      */
368     public string pull () throws Error, SpawnError
369     {
370         // should probably hand error conditions better... 
371         string[] cmd = { "pull" , "--no-edit" };
372         return this.git( cmd );
373
374         
375     }
376     
377     public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
378     public void pull_async(GitAsyncCallback cb) 
379     {
380     
381         string[] cmd = { "pull" , "--no-edit" };
382          this.git_async( cmd , cb);
383          
384     
385     }
386     
387     /**
388      * push:
389      * Send local changes to remote repo(s)
390      *
391      * At present we just need this to push the current branch.
392      * -- maybe later it will have a few options and do more stuff..
393      *
394      */
395     public string push () throws Error, SpawnError
396     {
397         // should 
398         return this.git({ "push", "origin", "HEAD" });
399         
400     }
401     
402     
403     
404      /**
405      * git:
406      * The meaty part.. run spawn.. with git..
407      *
408      *
409      */
410     
411     public string git(string[] args_in ) throws Error, SpawnError
412     {
413         // convert arguments.
414         
415         string[]  args = { "git" };
416         //args +=  "--git-dir";
417         //args +=  this.gitdir;
418         args +=  "--no-pager";
419  
420  
421         //if (this.gitdir != this.repopath) {
422         //    args +=   "--work-tree";
423          //   args += this.repopath; 
424         //}
425         for (var i = 0; i < args_in.length;i++) {
426             args += args_in[i];
427         }            
428
429         //this.lastCmd = args.join(" ");
430         //if(this.debug) {
431             GLib.debug( "CWD=%s",  this.git_working_dir ); 
432             GLib.debug( "cmd: %s", string.joinv (" ", args)); 
433         //}
434
435         string[]   env = {};
436         string  home = "HOME=" + Environment.get_home_dir() ;
437         env +=  home ;
438         // do not need to set gitpath..
439         //if (File.exists(this.repo + '/.git/config')) {
440             //env.push("GITPATH=" + this.repo );
441         //}
442         
443
444         var cfg = new SpawnConfig(this.git_working_dir , args , env);
445         
446
447        // may throw error...
448         var sp = new Spawn(cfg);
449       
450
451         GLib.debug( "GOT: %s" , sp.output);
452         // parse output for some commands ?
453         return sp.output;
454     }
455         
456    unowned GitAsyncCallback git_async_on_callback;
457         public void  git_async( string[] args_in,   GitAsyncCallback cb ) throws Error, SpawnError
458     {
459         // convert arguments.
460        this.git_async_on_callback = cb;
461         string[]  args = { "git" };
462         //args +=  "--git-dir";
463         //args +=  this.gitdir;
464         args +=  "--no-pager";
465  
466  
467         //if (this.gitdir != this.repopath) {
468         //    args +=   "--work-tree";
469          //   args += this.repopath; 
470         //}
471         for (var i = 0; i < args_in.length;i++) {
472             args += args_in[i];
473         }            
474
475         //this.lastCmd = args.join(" ");
476         //if(this.debug) {
477             GLib.debug( "CWD=%s",  this.git_working_dir ); 
478             //print( "cmd: %s\n", string.joinv (" ", args)); 
479         //}
480
481         string[]   env = {};
482         string  home = "HOME=" + Environment.get_home_dir() ;
483         env +=  home ;
484         // do not need to set gitpath..
485         //if (File.exists(this.repo + '/.git/config')) {
486             //env.push("GITPATH=" + this.repo );
487         //}
488         
489
490         var cfg = new SpawnConfig(this.git_working_dir , args , env);
491         cfg.async = true;
492        
493
494        // may throw error...
495         var sp = new Spawn(cfg);
496                 //sp.ref();
497         //this.ref();
498         sp.run(this.git_async_on_complete); 
499          
500     }
501     
502     void git_async_on_complete(int err, string output)
503     {
504                 GLib.debug("GOT %d : %s", err, output);
505                 this.git_async_on_callback(this, err, output);
506 //              this.unref();   
507         //      sp.unref();             
508     
509     
510     }
511     
512 }