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