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