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 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
26         public static GitRepo singleton()
27     {
28         if (_GitRepo == null) {
29             _GitRepo = new GitRepo();
30             _GitRepo.cache = new Gee.HashMap<string,GitRepo>();
31         }
32         return _GitRepo;
33     }
34
35     /**
36     * index of.. matching gitpath..
37     */
38     public static int indexOf( Array<GitRepo> repos, string gitpath) {
39         // make a fake object to compare against..
40         var test_repo = GitRepo.get(gitpath);
41         
42         for(var i =0; i < repos.length; i++) {
43             if (repos.index(i).gitdir == test_repo.gitdir) {
44                 return i;
45             }
46         }
47         return -1;
48     
49     }
50     
51     public  Gee.HashMap<string,GitRepo> cache;
52     
53     
54     
55     public static   Array<GitRepo> list()
56     {
57
58         //if (GitRepo.list_cache !=  null) {
59         //    unowned  Array<GitRepo>    ret = GitRepo.list_cache;
60          //   return ret;
61         //}
62         var cache = GitRepo.singleton().cache;
63         var list_cache = new Array<GitRepo>();
64         
65         var dir = Environment.get_home_dir() + "/gitlive";
66         
67         var f = File.new_for_path(dir);
68         FileEnumerator file_enum;
69         try {
70             file_enum = f.enumerate_children(
71                 FileAttribute.STANDARD_DISPLAY_NAME + ","+ 
72                 FileAttribute.STANDARD_TYPE,
73                 FileQueryInfoFlags.NONE,
74                 null);
75         } catch (Error e) {
76             
77             return list_cache;
78             
79         }
80         
81         FileInfo next_file; 
82         
83         while (true) {
84             
85             try {
86                 next_file = file_enum.next_file(null);
87                 if (next_file == null) {
88                     break;
89                 }
90                 
91             } catch (Error e) {
92                 GLib.debug("Error: %s",e.message);
93                 break;
94             }
95          
96             //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
97             
98             if (next_file.get_file_type() !=  FileType.DIRECTORY) {
99                 next_file = null;
100                 continue;
101             }
102             
103             if (next_file.get_file_type() ==  FileType.SYMBOLIC_LINK) {
104                 next_file = null;
105                 continue;
106             }
107             
108             if (next_file.get_display_name()[0] == '.') {
109                 next_file = null;
110                 continue;
111             }
112             var sp = dir+"/"+next_file.get_display_name();
113            
114             var gitdir = dir + "/" + next_file.get_display_name() + "/.git";
115             
116             if (!FileUtils.test(gitdir, FileTest.IS_DIR)) {
117                 continue;
118             }
119             
120                 var rep =  GitRepo.get(  sp );
121                 list_cache.append_val(rep);             
122             
123         }
124     
125         return list_cache;
126         
127          
128           
129         }
130         
131         public static GitRepo get(string path) 
132         {
133                 var cache = GitRepo.singleton().cache;
134                 if (cache.has_key(path)) {
135                         return cache.get(path);
136                 }
137                 return new GitRepo(path);
138         }
139         
140     
141  
142    
143     /**
144      * constructor:
145      * 
146      * @param {Object} cfg - Configuration
147      *     (basically repopath is currently only critical one.)
148      *
149      */
150      
151     private GitRepo(string path) {
152         // cal parent?
153         this.name =   File.new_for_path(path).get_basename();
154         this.ignore_files = new Gee.HashMap<string,bool>();
155         
156         this.git_working_dir = path;
157         this.gitdir = path + "/.git";
158         if (!FileUtils.test(this.gitdir , FileTest.IS_DIR)) {
159             this.gitdir = path; // naked...
160         }
161         this.cmds = new  Array<GitMonitorQueue> ();
162         
163                 var cache = GitRepo.singleton().cache;
164         //Repo.superclass.constructor.call(this,cfg);
165          if ( !cache.has_key(path) ) {
166                 cache.set( path, this);
167         }
168     } 
169     
170     
171     public bool is_autocommit ()
172     {
173         return !FileUtils.test(this.gitdir + "/.gitlive-disable-autocommit" , FileTest.EXISTS);
174     }
175     public bool is_autopush ()
176     {
177         return !FileUtils.test(this.gitdir + "/.gitlive-disable-autopush" , FileTest.EXISTS);
178     }
179     
180     Gee.HashMap<string,GitBranch> branches;
181     
182     public void loadBranches()
183     {
184         this.branches = new Gee.HashMap<string,GitBranch>();
185         
186         string[] cmd = { "branch",   "--no-color", "--verbose", "--no-abbrev" , "-a"  };
187         var res = this.git( cmd );
188         var lines = res.split("\n");
189         for (var i = 0; i < lines.length ; i++) {
190                 var br = new GitBranch(this);
191                 if (!br.parseBranchListItem(lines[i])) {
192                         continue;
193                 }
194                 GLib.debug("add branch %s", br.realName());
195                  
196                 branches.set(br.realName(), br);
197                 if (br.active) {
198                         this.currentBranch = br;
199                 }
200         }
201     
202     }
203     public string branchesToString()
204     {
205         var ret = "";
206                 foreach( var br in this.branches.values) {
207                         if (br.name == "") {
208                                 continue; 
209                         }
210                         ret += ret.length > 0 ? ","  : "";
211                         ret += br.name;
212                 
213                 }
214                 return ret;
215         
216     }
217     RooTicket? ticket = null;
218     
219     public void setActiveTicket(RooTicket ticket, string branchname)
220     {
221         this.createBranchNamed(branchname);
222         FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
223         this.activeTicket = ticket;
224     }
225     
226     public void createBranchNamed(string branchname)
227     {
228          string[] cmd = { "checkout", "-b" , branchname  };
229          this.git(cmd);
230          this.loadBranches(); // update branch list...
231     }
232     
233     
234     /**
235      * add:
236      * add files to track.
237      *
238      * @argument {Array} files the files to add.
239      */
240     public string add ( Array<GitMonitorQueue> files ) throws Error, SpawnError
241     {
242         // should really find out if these are untracked files each..
243         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
244         // not sure if that is how git works.. but just be certian.
245         var ret = "";
246         for (var i = 0; i < files.length;i++) {
247             var f = files.index(i).vname;
248             try {
249                 string[] cmd = { "add",    f  };
250                 this.git( cmd );
251             } catch (Error e) {
252                 ret += e.message  + "\n";
253             }        
254
255         }
256         return ret;
257     }
258         
259     public bool is_ignore(string fname) throws Error, SpawnError
260     {
261                 if (fname == ".gitignore") {
262                         this.ignore_files.clear();
263                 }
264                 
265                 if (this.ignore_files.has_key(fname)) {
266                         return this.ignore_files.get(fname);
267                 }
268                 
269                 try {
270                         var ret = this.git( { "check-ignore" , fname } );
271                         this.ignore_files.set(fname, ret.length >  0);
272                         return ret.length > 0;
273                 } catch (SpawnError e) {
274                         this.ignore_files.set(fname, false);
275                         return false;
276                 }
277                  
278     } 
279     
280     
281       /**
282      * remove:
283      * remove files to track.
284      *
285      * @argument {Array} files the files to add.
286      */
287     public string remove  ( Array<GitMonitorQueue> files ) throws Error, SpawnError
288     {
289         // this may fail if files do not exist..
290         // should really find out if these are untracked files each..
291         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
292         // not sure if that is how git works.. but just be certian.
293         var ret = "";
294
295         for (var i = 0; i < files.length;i++) {
296             var f = files.index(i).vname;
297             try {
298                 string[] cmd = { "rm",  "-f" ,  f  };
299                 this.git( cmd );
300             } catch (Error e) {
301                 ret += e.message  + "\n";
302             }        
303         }
304
305         return ret;
306
307     }
308     
309     
310     /**
311      * commit:
312      * perform a commit.
313      *
314      * @argument {Object} cfg commit configuration
315      * 
316      * @property {String} name (optional)
317      * @property {String} email (optional)
318      * @property {String} changed (date) (optional)
319      * @property {String} reason (optional)
320      * @property {Array} files - the files that have changed. 
321      * 
322      */
323      
324     public string commit ( string message, Array<GitMonitorQueue> files  ) throws Error, SpawnError
325     {
326         
327
328         /*
329         var env = [];
330
331         if (typeof(cfg.name) != 'undefined') {
332             args.push( {
333                 'author' : cfg.name + ' <' + cfg.email + '>'
334             });
335             env.push(
336                 "GIT_COMMITTER_NAME" + cfg.name,
337                 "GIT_COMMITTER_EMAIL" + cfg.email
338             );
339         }
340
341         if (typeof(cfg.changed) != 'undefined') {
342             env.push("GIT_AUTHOR_DATE= " + cfg.changed )
343             
344         }
345         */
346         string[] args = { "commit", "-m" };
347         args +=  (message.length > 0  ? message : "Changed" );
348         for (var i = 0; i< files.length ; i++ ) {
349             args += files.index(i).vname; // full path?
350         }
351          
352         return this.git(args);
353     }
354     
355     /**
356      * pull:
357      * Fetch and merge remote repo changes into current branch..
358      *
359      * At present we just need this to update the current working branch..
360      * -- maybe later it will have a few options and do more stuff..
361      *
362      */
363     public string pull () throws Error, SpawnError
364     {
365         // should probably hand error conditions better... 
366         string[] cmd = { "pull" , "--no-edit" };
367         return this.git( cmd );
368
369         
370     }
371     
372     public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
373     public void pull_async(GitAsyncCallback cb) 
374     {
375     
376         string[] cmd = { "pull" , "--no-edit" };
377          this.git_async( cmd , cb);
378          
379     
380     }
381     
382     /**
383      * push:
384      * Send local changes to remote repo(s)
385      *
386      * At present we just need this to push the current branch.
387      * -- maybe later it will have a few options and do more stuff..
388      *
389      */
390     public string push () throws Error, SpawnError
391     {
392         // should 
393         return this.git({ "push", "origin", "HEAD" });
394         
395     }
396     
397     
398     
399      /**
400      * git:
401      * The meaty part.. run spawn.. with git..
402      *
403      *
404      */
405     
406     public string git(string[] args_in ) throws Error, SpawnError
407     {
408         // convert arguments.
409         
410         string[]  args = { "git" };
411         //args +=  "--git-dir";
412         //args +=  this.gitdir;
413         args +=  "--no-pager";
414  
415  
416         //if (this.gitdir != this.repopath) {
417         //    args +=   "--work-tree";
418          //   args += this.repopath; 
419         //}
420         for (var i = 0; i < args_in.length;i++) {
421             args += args_in[i];
422         }            
423
424         //this.lastCmd = args.join(" ");
425         //if(this.debug) {
426             GLib.debug( "CWD=%s",  this.git_working_dir ); 
427             GLib.debug( "cmd: %s", string.joinv (" ", args)); 
428         //}
429
430         string[]   env = {};
431         string  home = "HOME=" + Environment.get_home_dir() ;
432         env +=  home ;
433         // do not need to set gitpath..
434         //if (File.exists(this.repo + '/.git/config')) {
435             //env.push("GITPATH=" + this.repo );
436         //}
437         
438
439         var cfg = new SpawnConfig(this.git_working_dir , args , env);
440         
441
442        // may throw error...
443         var sp = new Spawn(cfg);
444       
445
446         GLib.debug( "GOT: %s" , sp.output);
447         // parse output for some commands ?
448         return sp.output;
449     }
450         
451    unowned GitAsyncCallback git_async_on_callback;
452         public void  git_async( string[] args_in,   GitAsyncCallback cb ) throws Error, SpawnError
453     {
454         // convert arguments.
455        this.git_async_on_callback = cb;
456         string[]  args = { "git" };
457         //args +=  "--git-dir";
458         //args +=  this.gitdir;
459         args +=  "--no-pager";
460  
461  
462         //if (this.gitdir != this.repopath) {
463         //    args +=   "--work-tree";
464          //   args += this.repopath; 
465         //}
466         for (var i = 0; i < args_in.length;i++) {
467             args += args_in[i];
468         }            
469
470         //this.lastCmd = args.join(" ");
471         //if(this.debug) {
472             GLib.debug( "CWD=%s",  this.git_working_dir ); 
473             //print( "cmd: %s\n", string.joinv (" ", args)); 
474         //}
475
476         string[]   env = {};
477         string  home = "HOME=" + Environment.get_home_dir() ;
478         env +=  home ;
479         // do not need to set gitpath..
480         //if (File.exists(this.repo + '/.git/config')) {
481             //env.push("GITPATH=" + this.repo );
482         //}
483         
484
485         var cfg = new SpawnConfig(this.git_working_dir , args , env);
486         cfg.async = true;
487        
488
489        // may throw error...
490         var sp = new Spawn(cfg);
491                 //sp.ref();
492         //this.ref();
493         sp.run(this.git_async_on_complete); 
494          
495     }
496     
497     void git_async_on_complete(int err, string output)
498     {
499                 GLib.debug("GOT %d : %s", err, output);
500                 this.git_async_on_callback(this, err, output);
501 //              this.unref();   
502         //      sp.unref();             
503     
504     
505     }
506     
507 }