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