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