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