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     public bool is_autopush ()
146     {
147         return !FileUtils.test(this.gitdir + "/.gitlive-disable-autopush" , FileTest.IS_DIR);
148     }    
149     /**
150      * add:
151      * add files to track.
152      *
153      * @argument {Array} files the files to add.
154      */
155     public string add ( Array<GitMonitorQueue> files ) throws Error, SpawnError
156     {
157         // should really find out if these are untracked files each..
158         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
159         // not sure if that is how git works.. but just be certian.
160         var ret = "";
161         for (var i = 0; i < files.length;i++) {
162             var f = files.index(i).vname;
163             try {
164                 string[] cmd = { "add",    f  };
165                 this.git( cmd );
166             } catch (Error e) {
167                 ret += e.message  + "\n";
168             }        
169
170         }
171         return ret;
172     }
173         
174     public bool is_ignore(string fname) throws Error, SpawnError
175     {
176                 if (fname == ".gitignore") {
177                         this.ignore_files.clear();
178                 }
179                 
180                 if (this.ignore_files.has_key(fname)) {
181                         return this.ignore_files.get(fname);
182                 }
183                 
184                 try {
185                         var ret = this.git( { "check-ignore" , fname } );
186                         this.ignore_files.set(fname, ret.length >  0);
187                         return ret.length > 0;
188                 } catch (SpawnError e) {
189                         this.ignore_files.set(fname, false);
190                         return false;
191                 }
192                  
193     } 
194     
195     
196       /**
197      * remove:
198      * remove files to track.
199      *
200      * @argument {Array} files the files to add.
201      */
202     public string remove  ( Array<GitMonitorQueue> files ) throws Error, SpawnError
203     {
204         // this may fail if files do not exist..
205         // should really find out if these are untracked files each..
206         // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
207         // not sure if that is how git works.. but just be certian.
208         var ret = "";
209
210         for (var i = 0; i < files.length;i++) {
211             var f = files.index(i).vname;
212             try {
213                 string[] cmd = { "rm",  "-f" ,  f  };
214                 this.git( cmd );
215             } catch (Error e) {
216                 ret += e.message  + "\n";
217             }        
218         }
219
220         return ret;
221
222     }
223     
224     
225     /**
226      * commit:
227      * perform a commit.
228      *
229      * @argument {Object} cfg commit configuration
230      * 
231      * @property {String} name (optional)
232      * @property {String} email (optional)
233      * @property {String} changed (date) (optional)
234      * @property {String} reason (optional)
235      * @property {Array} files - the files that have changed. 
236      * 
237      */
238      
239     public string commit ( string message, Array<GitMonitorQueue> files  ) throws Error, SpawnError
240     {
241         
242
243         /*
244         var env = [];
245
246         if (typeof(cfg.name) != 'undefined') {
247             args.push( {
248                 'author' : cfg.name + ' <' + cfg.email + '>'
249             });
250             env.push(
251                 "GIT_COMMITTER_NAME" + cfg.name,
252                 "GIT_COMMITTER_EMAIL" + cfg.email
253             );
254         }
255
256         if (typeof(cfg.changed) != 'undefined') {
257             env.push("GIT_AUTHOR_DATE= " + cfg.changed )
258             
259         }
260         */
261         string[] args = { "commit", "-m" };
262         args +=  (message.length > 0  ? message : "Changed" );
263         for (var i = 0; i< files.length ; i++ ) {
264             args += files.index(i).vname; // full path?
265         }
266          
267         return this.git(args);
268     }
269     
270     /**
271      * pull:
272      * Fetch and merge remote repo changes into current branch..
273      *
274      * At present we just need this to update the current working branch..
275      * -- maybe later it will have a few options and do more stuff..
276      *
277      */
278     public string pull () throws Error, SpawnError
279     {
280         // should probably hand error conditions better... 
281         string[] cmd = { "pull" , "--no-edit" };
282         return this.git( cmd );
283
284         
285     }
286     
287     public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
288     public void pull_async(GitAsyncCallback cb) 
289     {
290     
291         string[] cmd = { "pull" , "--no-edit" };
292          this.git_async( cmd , cb);
293          
294     
295     }
296     
297     /**
298      * push:
299      * Send local changes to remote repo(s)
300      *
301      * At present we just need this to push the current branch.
302      * -- maybe later it will have a few options and do more stuff..
303      *
304      */
305     public string push () throws Error, SpawnError
306     {
307         // should 
308         return this.git({ "push", "origin", "HEAD" });
309         
310     }
311     
312     
313     
314      /**
315      * git:
316      * The meaty part.. run spawn.. with git..
317      *
318      *
319      */
320     
321     public string git(string[] args_in ) throws Error, SpawnError
322     {
323         // convert arguments.
324         
325         string[]  args = { "git" };
326         //args +=  "--git-dir";
327         //args +=  this.gitdir;
328         args +=  "--no-pager";
329  
330  
331         //if (this.gitdir != this.repopath) {
332         //    args +=   "--work-tree";
333          //   args += this.repopath; 
334         //}
335         for (var i = 0; i < args_in.length;i++) {
336             args += args_in[i];
337         }            
338
339         //this.lastCmd = args.join(" ");
340         //if(this.debug) {
341             GLib.debug( "CWD=%s",  this.git_working_dir ); 
342             GLib.debug( "cmd: %s", string.joinv (" ", args)); 
343         //}
344
345         string[]   env = {};
346         string  home = "HOME=" + Environment.get_home_dir() ;
347         env +=  home ;
348         // do not need to set gitpath..
349         //if (File.exists(this.repo + '/.git/config')) {
350             //env.push("GITPATH=" + this.repo );
351         //}
352         
353
354         var cfg = new SpawnConfig(this.git_working_dir , args , env);
355         
356
357        // may throw error...
358         var sp = new Spawn(cfg);
359       
360
361         GLib.debug( "GOT: %s" , sp.output);
362         // parse output for some commands ?
363         return sp.output;
364     }
365         
366    unowned GitAsyncCallback git_async_on_callback;
367         public void  git_async( string[] args_in,   GitAsyncCallback cb ) throws Error, SpawnError
368     {
369         // convert arguments.
370        this.git_async_on_callback = cb;
371         string[]  args = { "git" };
372         //args +=  "--git-dir";
373         //args +=  this.gitdir;
374         args +=  "--no-pager";
375  
376  
377         //if (this.gitdir != this.repopath) {
378         //    args +=   "--work-tree";
379          //   args += this.repopath; 
380         //}
381         for (var i = 0; i < args_in.length;i++) {
382             args += args_in[i];
383         }            
384
385         //this.lastCmd = args.join(" ");
386         //if(this.debug) {
387             GLib.debug( "CWD=%s",  this.git_working_dir ); 
388             //print( "cmd: %s\n", string.joinv (" ", args)); 
389         //}
390
391         string[]   env = {};
392         string  home = "HOME=" + Environment.get_home_dir() ;
393         env +=  home ;
394         // do not need to set gitpath..
395         //if (File.exists(this.repo + '/.git/config')) {
396             //env.push("GITPATH=" + this.repo );
397         //}
398         
399
400         var cfg = new SpawnConfig(this.git_working_dir , args , env);
401         cfg.async = true;
402        
403
404        // may throw error...
405         var sp = new Spawn(cfg);
406                 //sp.ref();
407         //this.ref();
408         sp.run(this.git_async_on_complete); 
409          
410     }
411     
412     void git_async_on_complete(int err, string output)
413     {
414                 GLib.debug("GOT %d : %s", err, output);
415                 this.git_async_on_callback(this, err, output);
416 //              this.unref();   
417         //      sp.unref();             
418     
419     
420     }
421     
422 }