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