Git.vala
[gitlive] / Git.vala
1
2 // valac -o /tmp/ggit Git.vala --pkg libgit2-glib-1.0 --pkg libsoup-2.4 -pkg gee-0.8 -g
3
4
5
6 void main()
7 {
8          GLib.Log.set_handler(null, 
9             GLib.LogLevelFlags.LEVEL_DEBUG | GLib.LogLevelFlags.LEVEL_WARNING | GLib.LogLevelFlags.LEVEL_INFO, 
10             (dom, lvl, msg) => {
11                                         
12                                         
13                // should we debug..
14                                         
15                         
16                print("%s\n", msg);
17             }
18          ); 
19
20         Ggit.init();
21         
22         var a = new GitLive.Repo("/home/alan/gitlive/gitlive");
23         a.is_managed();
24         a.is_autocommit();
25         a.loadLocalBranches();
26         a.loadRemoteHeads();
27         a.fetchAll();
28         //
29         /*
30         var a = new GitLive.Repo("/home/alan/git/test1-clone");
31         //a.fetchAll();
32         var str = (new GLib.DateTime.now_utc()).format("%Y-%m-%d %H:%M:%S");
33         GLib.FileUtils.set_contents("/home/alan/git/test1-clone/test1",  str); 
34         
35         var ix = a.repo.get_index();
36         ix.add_path("test1");
37         ix.write();
38         var treeoid = ix.write_tree();
39
40         var head = a.repo.get_head();
41         var parent = head.lookup() as Ggit.Commit;
42         Ggit.Commit[] parents = (parent == null) ? 
43                 new Ggit.Commit[] {} :
44                 new Ggit.Commit[] { parent };
45
46         var tree = a.repo.lookup(treeoid,typeof (Ggit.Tree))  as   Ggit.Tree;// odd format.. 
47         
48         var sig = new Ggit.Signature.now("Alan Knowles", "alan@roojs.com");
49         a.repo.create_commit("HEAD", sig, sig, null, "test commit " + str, tree, parents);
50         */
51         // mmh.. no git add/commit in library...
52 //      string[] spawn_args = {"git", "commit", "-m", "test", "-a"};
53         //string[] spawn_env = Environ.get ();
54 //      Process.spawn_sync ("/home/alan/git/test1-clone", spawn_args, spawn_env, SpawnFlags.SEARCH_PATH, null);
55  
56         a.pushAll();
57 }
58  
59
60 namespace  GitLive {
61
62         public class Repo : Object {
63
64                 public Ggit.Repository  repo;
65                 Callbacks callbacks;
66
67                 public Repo(string path)
68                 {
69                         this.name = GLib.Path.get_basename(path);
70                         this.repo = Ggit.Repository.open(GLib.File.new_for_path(path));
71                         this.callbacks = new Callbacks(this);
72                 
73                 }
74                 Ggit.Branch                                             head = null;
75             Gee.ArrayList<Ggit.Branch>          branches = null;
76             Ggit.RemoteHead[]                           remote_heads = null;
77                 public void loadLocalBranches(bool force = false)
78                 {
79                         if (!force && this.branches != null) {
80                                 return;
81                         }
82                         
83                         this.branches =  new Gee.ArrayList<Ggit.Branch>();
84                         var r = this.repo.enumerate_branches(Ggit.BranchType.LOCAL);
85                         while (r.next()) {
86                                 var br = r.get() as Ggit.Branch;
87                                 //var head = this.repo.revparse("refs/heads/" + br.get_name() ).get_id();
88                                 //var rhead = this.repo.revparse(br.get_upstream().get_name() ).get_id();
89                                 //GLib.debug("got branch: name = %s upstream = %s oid = %s ", 
90                                 //              br.get_name(), br.get_upstream().get_name(), 
91                                 //              head.to_string());
92                                 this.branches.add(br);
93                                 if (br.is_head()) {
94                                         GLib.debug("HEAD= %s", br.get_name());
95                                         this.head = br;
96                                 }
97                                 
98                         }
99                         
100                         
101                 }
102                  
103                 public bool is_managed()
104                 {
105                         GLib.debug("is_managed: %d", this.repo.get_config().get_int32("gitlive.managed"));
106                         return this.repo.get_config().get_int32("gitlive.managed") == 1;
107                 }
108                 
109                 
110                 public bool is_autocommit ()
111                 {       
112                         GLib.debug("is_autocommit: %d", this.repo.get_config().get_int32("gitlive.autocommit"));
113                         return this.repo.get_config().get_int32("gitlive.autocommit") == 1;
114                 }
115                 public void set_autocommit(bool val)
116                 {
117                         this.repo.get_config().set_int32("gitlive.autocommit", val ? "1" : "0");
118                 
119                 }
120                  
121                 public bool doMergeClose(string commit_message)
122                 {
123                         this.loadLocalBranches(true);
124                         var oldbranch = this.head.get_name();
125             
126                            string [] cmd = { "merge",   "--squash",  oldbranch };
127                            this.git( cmd );
128                            cmd = { "commit",   "-a" , "-m",  commit_message };
129                            this.git( cmd );
130                            this.push();
131                            this.loadBranches(); // updates lastrev..
132                
133                        var notification = new Notify.Notification(
134                                "Merged branch %s to %s".printf(oldbranch, master),
135                                "",
136                                 "dialog-information"
137                                
138                        );
139
140                        notification.set_timeout(5);
141                        notification.show();   
142                
143                 
144                 
145                 
146                 public bool is_auto_branch ()
147                 {
148                         if (this.name == "gitlog") {
149                                 return false;
150                         }
151                         // check remote...
152                         if (this.is_managed()) {
153                                 return true;
154                         }
155                         return false;
156                         
157          
158                 }
159                 
160                 public void loadRemoteHeads(bool force = false)
161                 {
162                         
163                         if (!force && this.remote_heads != null) {
164                                 return;
165                         }
166                         var r = this.repo.lookup_remote("origin");
167                         r.connect(Ggit.Direction.FETCH, this.callbacks, null, null);
168                         this.remote_heads = r.list();
169                 
170                 }
171                 
172                 
173                 
174                 Ggit.Branch? getBranch(string remote_name, string remote_branch_name)
175                 {
176                          //GLib.debug("bn=%s",remote_branch_name);
177                          if (remote_branch_name.has_prefix("refs/remotes/")) {
178                                  return null;
179                          }
180
181                          var target = remote_branch_name.replace("refs/heads/", remote_name+"/") .replace("refs/remotes/", "");
182                         if (target == "HEAD") {
183                                 target = remote_name +"/master";
184                         }
185                          
186                         foreach(var br in this.branches) {
187                         //      GLib.debug("test:%s=%s", br.get_upstream().get_shorthand() , target);
188                                 if ( br.get_upstream().get_shorthand() == target) {
189                                         return br;
190                                 }
191                                 
192                         }
193                         //GLib.debug("missing %s", remote_branch_name);                 
194                         return null;
195                 
196                 }
197                  
198                 
199                 public void fetchAll()
200                 {
201                         this.loadLocalBranches();
202                         this.loadRemoteHeads();
203                         
204                         // remotes probably will not work with http auth..
205                         //var ar = this.repo.list_remotes();
206                         //foreach(var n in ar) {
207                         var n = "origin"; 
208                         
209                                 GLib.debug("got remote '%s'", n);
210                                 var r = this.repo.lookup_remote(n);
211                                 GLib.debug("connecting '%s'", r.get_url());
212                                  
213                                 try {
214                                         string[] h = { "a = 1" };
215                                         r.connect(Ggit.Direction.FETCH, this.callbacks, null, null);
216                                         
217                                 } catch (Error e) {
218                                         GLib.debug("Got Error Message: %s", e.message);
219                                         return;
220                                 }
221                                 string[] far = {};
222
223                                 foreach(var rh in this.remote_heads) {
224                                         if (rh.get_name().has_prefix("refs/remotes/")) {
225                                                    continue;
226                                          }
227                                 
228                                         var br = this.getBranch(n, rh.get_name());
229                                  
230                                         /*GLib.debug("got heads: name=%s   rev=%s  localrev=%s",
231                                                 rh.get_name(), 
232                                                 rh.get_oid().to_string(),
233                                                 br == null ? "?": this.repo.revparse(br.get_name() ).get_id().to_string()
234                                         );
235                                         */
236                                         var loc_oid = this.repo.revparse(br.get_name() ).get_id();
237                                         size_t ahead, behind;
238                                         this.repo.get_ahead_behind(
239                                                 loc_oid,
240                                                 rh.get_oid(),
241                                                 out ahead,
242                                                 out behind
243                                         );
244                                         
245                                         if (rh.get_oid().to_string() == this.repo.revparse(br.get_name() ).get_id().to_string()) {
246                                                 continue;
247                                         }
248                                         if (ahead > 0) {
249                                                 continue;
250                                         }
251                                         far += ("+refs/heads/" + br.get_name()) + ":refs/remotes/" + n + "/" + rh.get_name().replace("refs/heads/","");
252                                 } 
253                                 
254                                 if (far.length < 1) {
255                                         GLib.debug("no fetch required.. it's uptodate");
256                                         r.disconnect();
257                                         return;
258                                 }
259                                 
260                                 GLib.debug("getting remote specs '%s', %d", n, far.length);
261                                 
262 /*
263                                 var far = r.get_fetch_specs();
264                                 */
265                                 foreach(var rs in far) {
266                                         GLib.debug("got remote spec: %s", rs);
267                                         
268                                 }
269
270                                 var options = new Ggit.FetchOptions();
271                                 options.set_remote_callbacks(this.callbacks);
272                                 //yield Async.thread(() => {
273         
274                                         r.download(far, options);
275                                 //});
276                                 r.disconnect();
277                                 
278                                 //r.download(
279                          
280                 
281                 }
282                 
283                 
284                 
285                 public void pushAll()
286                 {
287                         
288                         this.loadLocalBranches();
289                         this.loadRemoteHeads();
290                         // remotes probably will not work with http auth..
291                         //var ar = this.repo.list_remotes();
292                         var n = "origin";
293                         
294                                 GLib.debug("got remote '%s'", n);
295                                 var r = this.repo.lookup_remote(n);
296                                 GLib.debug("connecting '%s'", r.get_url());
297                                  
298                                 r.connect(Ggit.Direction.PUSH, this.callbacks, null, null);
299                                 
300                                 //GLib.debug("getting specs '%s'", n);
301                                 /* 
302                                 
303                                 this.repo.add_remote_push(
304                                         "origin",
305                                         "+%s:%s".printf(head.get_shorthand(),head.get_name())
306                                 );
307  */
308  
309                                 string[] far = {};
310                                 var heads = r.list();
311                                 foreach(var rh in heads) {
312                                         if (rh.get_name().has_prefix("refs/remotes/")) {
313                                                    continue;
314                                          }
315                                 
316                                         var br = this.getBranch(n, rh.get_name());
317                                         /*
318                                         GLib.debug("got heads: name=%s   rev=%s  localrev=%s",
319                                                 rh.get_name(), 
320                                                 rh.get_oid().to_string(),
321                                                 br == null ? "?": this.repo.revparse(br.get_name() ).get_id().to_string()
322                                         );*/
323                                         var loc_oid = this.repo.revparse(br.get_name() ).get_id();
324                                         size_t ahead, behind;
325                                         this.repo.get_ahead_behind(
326                                                 loc_oid,
327                                                 rh.get_oid(),
328                                                 out ahead,
329                                                 out behind
330                                         );
331                                         
332                                         if (rh.get_oid().to_string() == this.repo.revparse(br.get_name() ).get_id().to_string()) {
333                                                 continue;
334                                         }
335                                         if (behind > 0) {
336                                                 continue;
337                                         }
338                                         far += ("+refs/heads/" + br.get_name()) + ":"+ rh.get_name();
339                                 }  
340                                 
341                                 if (far.length < 1) {
342                                         GLib.debug("no push required.. it's uptodate");
343                                         r.disconnect();
344                                         return;
345                                 }
346  
347                                 /*var head = this.repo.get_head();
348                                 string[] far = {};
349                                 far += "+%s:%s".printf(head.get_name(),head.get_name());
350                                 */
351                                 foreach(var rs in far) {
352                                         GLib.debug("got remote spec: %s", rs);
353                                         
354                                 }
355                                         
356                                 var popts = new Ggit.PushOptions();
357                                  popts.callbacks = this.callbacks;
358                                 GLib.debug("Push?");
359                                 r.upload(far,popts);
360                                 GLib.debug("Push done?");
361                                 r.disconnect();
362                                 
363                                 
364                                 //r.download(
365                          
366                 
367                 }
368                 
369                  
370
371         }
372         
373         private class Callbacks : Ggit.RemoteCallbacks
374         {
375                 //private Remote d_remote;
376                 private Ggit.RemoteCallbacks? d_proxy = null;
377
378                 public delegate void TransferProgress(Ggit.TransferProgress stats);
379                 //private TransferProgress? d_transfer_progress;
380
381                 public Callbacks( Repo repo)  //, Ggit.RemoteCallbacks? proxy) //,Remote remote, owned TransferProgress? transfer_progress)
382                 {
383                         //d_remote = remote;
384                         //d_proxy = proxy;
385                         //d_transfer_progress = (owned)transfer_progress;
386                 }
387
388                 protected override void progress(string message)
389                 {
390                         GLib.debug("progress: %s", message);
391                         if (d_proxy != null)
392                         {
393                                 d_proxy.progress(message);
394                         }
395                 }
396
397                 protected override void transfer_progress(Ggit.TransferProgress stats)
398                 {
399                         GLib.debug("transfer_progress");
400                         /*
401                         if (d_transfer_progress != null)
402                         {
403                                 d_transfer_progress(stats);
404                         }
405
406                         if (d_proxy != null)
407                         {
408                                 d_proxy.transfer_progress(stats);
409                         }
410                         */
411                 }
412
413                 protected override void update_tips(string refname, Ggit.OId a, Ggit.OId b)
414                 {
415                         GLib.debug("update_tips");
416                         //d_remote.tip_updated(refname, a, b);
417
418                         if (d_proxy != null)
419                         {
420                                 d_proxy.update_tips(refname, a, b);
421                         }
422                 }
423
424                 protected override void completion(Ggit.RemoteCompletionType type)
425                 {
426                         GLib.debug("completion");
427                         if (d_proxy != null)
428                         {
429                                 d_proxy.completion(type);
430                         }
431                 }
432
433                 protected override Ggit.Cred? credentials(string url, string? username_from_url, Ggit.Credtype allowed_types) throws Error
434                 {
435  
436                         GLib.debug("get credentials %s  UN=%s", url, username_from_url);
437                         var uri = new Soup.URI(url);
438
439                         if (uri != null) {
440                                 var ret = this.netrc(uri.get_host());
441                                 if (ret != null) {
442                                         return ret;
443                                 }
444                                 
445                                 //return new Ggit.CredPlaintext(username_from_url, "test");
446                         }
447                         return null;
448                         /*var provider = d_remote.credentials_provider;
449
450                         if (provider != null)
451                         {
452                                 ret = provider.credentials(url, username_from_url, allowed_types);
453                         }
454
455                         if (ret == null && d_proxy != null)
456                         {
457                                 ret = d_proxy.credentials(url, username_from_url, allowed_types);
458                         }
459                         
460                         return ret;
461                         */
462                 }
463                 public  Ggit.Cred netrc(string domain) 
464                 {
465                         string str;
466                         GLib.FileUtils.get_contents(GLib.Environment.get_home_dir() + "/.netrc", out str);
467                         var lines = str.split("\n");
468                         for(var i=0; i< lines.length; i++) {
469                                 // assumes one line per entry.. if not we are buggered...
470                                 //GLib.debug("got %s" , lines[i]);
471                         
472                                 var bits =  Regex.split_simple ("[ \t]+", lines[i].strip());
473                                 if (bits.length < 6 || bits[0] != "machine" || bits[1] != domain) {
474                                         continue;
475                                 }
476                                 GLib.debug("found password?");
477                                 // we are gussing.... 
478                                 return new Ggit.CredPlaintext(bits[3], bits[5]);
479
480                         }
481                         return null;
482
483
484                 
485                 
486                 }
487                 
488         }
489         
490         
491
492 }