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