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.mergeMasterIntoHead();
24         //a.walkDiff();
25         return;
26         a.is_managed();
27         a.is_autocommit();
28         a.loadLocalBranches();
29         a.loadRemoteHeads();
30         a.fetchAll();
31         //
32         /*
33         var a = new GitLive.Repo("/home/alan/git/test1-clone");
34         //a.fetchAll();
35         var str = (new GLib.DateTime.now_utc()).format("%Y-%m-%d %H:%M:%S");
36         GLib.FileUtils.set_contents("/home/alan/git/test1-clone/test1",  str); 
37         
38         var ix = a.repo.get_index();
39         ix.add_path("test1");
40         ix.write();
41         var treeoid = ix.write_tree();
42
43         var head = a.repo.get_head();
44         var parent = head.lookup() as Ggit.Commit;
45         Ggit.Commit[] parents = (parent == null) ? 
46                 new Ggit.Commit[] {} :
47                 new Ggit.Commit[] { parent };
48
49         var tree = a.repo.lookup(treeoid,typeof (Ggit.Tree))  as   Ggit.Tree;// odd format.. 
50         
51         var sig = new Ggit.Signature.now("Alan Knowles", "alan@roojs.com");
52         a.repo.create_commit("HEAD", sig, sig, null, "test commit " + str, tree, parents);
53         */
54         // mmh.. no git add/commit in library...
55 //      string[] spawn_args = {"git", "commit", "-m", "test", "-a"};
56         //string[] spawn_env = Environ.get ();
57 //      Process.spawn_sync ("/home/alan/git/test1-clone", spawn_args, spawn_env, SpawnFlags.SEARCH_PATH, null);
58  
59         a.pushAll();
60 }
61  
62
63 namespace  GitLive {
64
65         public class Repo : Object {
66
67                 string name = "";
68                 public Ggit.Repository  repo;
69                 Callbacks callbacks;
70
71                 public Repo(string path)
72                 {
73                         this.name = GLib.Path.get_basename(path);
74                         this.repo = Ggit.Repository.open(GLib.File.new_for_path(path));
75                         this.callbacks = new Callbacks(this);
76                 
77                 }
78                 Ggit.Branch                                             head = null;
79             Gee.ArrayList<Ggit.Branch>          branches = null;
80             Ggit.RemoteHead[]                           remote_heads = null;
81                 public void loadLocalBranches(bool force = false)
82                 {
83                         if (!force && this.branches != null) {
84                                 return;
85                         }
86                         
87                         this.branches =  new Gee.ArrayList<Ggit.Branch>();
88                         var r = this.repo.enumerate_branches(Ggit.BranchType.LOCAL);
89                         while (r.next()) {
90                                 var br = r.get() as Ggit.Branch;
91                                 //var head = this.repo.revparse("refs/heads/" + br.get_name() ).get_id();
92                                 //var rhead = this.repo.revparse(br.get_upstream().get_name() ).get_id();
93                                 //GLib.debug("got branch: name = %s upstream = %s oid = %s ", 
94                                 //              br.get_name(), br.get_upstream().get_name(), 
95                                 //              head.to_string());
96                                 this.branches.add(br);
97                                 if (br.is_head()) {
98                                         GLib.debug("HEAD= %s", br.get_name());
99                                         this.head = br;
100                                 }
101                                 
102                         }
103                         
104                         
105                 }
106                  
107                 public bool is_managed()
108                 {
109                         GLib.debug("is_managed: %d", this.repo.get_config().get_int32("gitlive.managed"));
110                         return this.repo.get_config().get_int32("gitlive.managed") == 1;
111                 }
112                 
113                 
114                 public bool is_autocommit ()
115                 {       
116                         GLib.debug("is_autocommit: %d", this.repo.get_config().get_int32("gitlive.autocommit"));
117                         return this.repo.get_config().get_int32("gitlive.autocommit") == 1;
118                 }
119                 public void set_autocommit(bool val)
120                 {
121                         this.repo.get_config().set_int32("gitlive.autocommit", val ? 1 : 0);
122                 
123                 }
124                  
125                 public void walkDiff()
126                 {
127                         this.loadLocalBranches();
128                         
129                         
130                         
131                         var oid =  this.repo.revparse(this.head.get_name() ).get_id()  ;
132                         var moid =  this.repo.revparse("refs/heads/master" ).get_id()  ;
133                         
134                         var a = new Ggit.RevisionWalker(this.repo);
135                         a.set_sort_mode(Ggit.SortMode.TOPOLOGICAL);
136                         a.push(oid);
137                         a.hide(moid);
138                         var last = oid;
139                         for (var noid = a.next(); noid != null; noid= a.next()) {
140                                 //var commit = this.repo.lookup(noid, typeof(Ggit.Commit)) as Ggit.Commit;
141                                 GLib.debug("rev: %s",
142                                         noid.to_string()
143                                 );
144                                 last = noid;
145                         }
146                         var commit = this.repo.lookup(last, typeof(Ggit.Commit)) as Ggit.Commit;
147                         var parent = commit.get_parents();
148                         GLib.debug("parent = %s", parent.get_id(0).to_string());
149                         var master_rev =  parent.get_id(0);
150                         var master_commit  = this.repo.lookup_commit(master_rev);;
151                         
152                         var head_commit = this.repo.lookup_commit(oid);
153                         
154                         var master_tree = master_commit.get_tree();
155                         var head_tree = head_commit.get_tree();
156                         
157                         var diff = new Ggit.Diff.tree_to_tree(this.repo, master_tree, head_tree, new Ggit.DiffOptions());
158                         
159                         diff.print(Ggit.DiffFormatType.PATCH, ( delta,  hunk,  line) => {
160                                 GLib.debug("%d: %s, %s", line.get_new_lineno(), line.get_origin().to_string(), line.get_text());
161                                 return 0;
162                         });
163                         // let's try a merge..
164                         var mo = new Ggit.MergeOptions();
165                         mo.set_file_favor(Ggit.MergeFileFavor.THEIRS);
166                         var ix = this.repo.merge_trees(master_tree, master_tree, head_tree, mo);
167                         
168                         if (ix.has_conflicts()) {
169                                 GLib.debug("merge has conflicts");
170                                 return;
171                         }
172                          var treeoid = ix.write_tree();
173                          
174                          
175                           
176                         var parents =   new Ggit.Commit[] { master_commit };
177
178
179                         var new_tree = this.repo.lookup(treeoid,typeof (Ggit.Tree))  as   Ggit.Tree;
180                         
181                         var sig = new Ggit.Signature.now(
182                                         this.repo.get_config().get_string("user.name"),
183                                         this.repo.get_config().get_string("user.email")
184                         );
185                         this.repo.create_commit("HEAD", sig, sig, null, "Test Merge", new_tree, parents);
186         
187                         
188                         
189                         
190                         
191                 }
192                 public void mergeMasterIntoHead()
193                 {
194                         // assumes head is not master...
195                         this.loadLocalBranches();
196                         GLib.debug("head rev = %s", this.head.get_name());
197                         var head_oid =  this.repo.revparse(this.head.get_name() ).get_id()  ;
198                         var master_oid =  this.repo.revparse("refs/heads/master" ).get_id()  ;
199
200                         var master_commit  = this.repo.lookup_commit(master_oid);;
201                         var head_commit = this.repo.lookup_commit(head_oid);
202                          
203                 
204                         var anc_oid = this.repo.merge_base(master_commit.get_id(), head_commit.get_id());
205                         
206                         var anc_commit = this.repo.lookup_commit(anc_oid);
207                         var anc_tree = anc_commit.get_tree();
208                         
209                         var master_tree = master_commit.get_tree();
210                         var head_tree = head_commit.get_tree();
211                         var mo = new Ggit.MergeOptions();
212                         mo.set_file_favor(Ggit.MergeFileFavor.THEIRS);
213                         var ix  = this.repo.merge_trees(anc_tree, master_tree, head_tree, mo);
214                         
215                         // might be conflicts..
216                         if (ix.has_conflicts()) {
217                                 GLib.debug("merge has conflicts");
218                                 return;
219                         }
220                         this.repo.checkout_index(ix, new Ggit.CheckoutOptions());
221                          var treeoid = ix.write_tree();
222                          
223                           
224                         var parents =   new Ggit.Commit[] { master_commit };
225
226
227                         var new_tree = this.repo.lookup(treeoid,typeof (Ggit.Tree))  as   Ggit.Tree;
228                         
229                         var sig = new Ggit.Signature.now(
230                                         this.repo.get_config().get_string("user.name"),
231                                         this.repo.get_config().get_string("user.email")
232                         );
233                         this.repo.create_commit("HEAD", sig, sig, null, "Test Merge", new_tree, parents);
234         
235                 
236                 }
237                 
238                 
239                 /*
240                 public bool doMergeClose(string commit_message)
241                 {
242                         this.loadLocalBranches(true);
243                         var oldbranch = this.head.get_name();
244             // going to asume this is merge trees..
245                            string [] cmd = { "merge",   "--squash",  oldbranch };
246                            this.git( cmd );
247                            cmd = { "commit",   "-a" , "-m",  commit_message };
248                            this.git( cmd );
249                            this.push();
250                            this.loadBranches(); // updates lastrev..
251                
252                        var notification = new Notify.Notification(
253                                "Merged branch %s to %s".printf(oldbranch, master),
254                                "",
255                                 "dialog-information"
256                                
257                        );
258
259                        notification.set_timeout(5);
260                        notification.show();   
261                
262                 
263                 }
264                 */
265                 
266                 
267                 public bool is_auto_branch ()
268                 {
269                         if (this.name == "gitlog") {
270                                 return false;
271                         }
272                         // check remote...
273                         if (this.is_managed()) {
274                                 return true;
275                         }
276                         return false;
277                         
278          
279                 }
280                 
281                 public void loadRemoteHeads(bool force = false)
282                 {
283                         
284                         if (!force && this.remote_heads != null) {
285                                 return;
286                         }
287                         var r = this.repo.lookup_remote("origin");
288                         r.connect(Ggit.Direction.FETCH, this.callbacks, null, null);
289                         this.remote_heads = r.list();
290                 
291                 }
292                 
293                 
294                 
295                 Ggit.Branch? getBranch(string remote_name, string remote_branch_name)
296                 {
297                          //GLib.debug("bn=%s",remote_branch_name);
298                          if (remote_branch_name.has_prefix("refs/remotes/")) {
299                                  return null;
300                          }
301
302                          var target = remote_branch_name.replace("refs/heads/", remote_name+"/") .replace("refs/remotes/", "");
303                         if (target == "HEAD") {
304                                 target = remote_name +"/master";
305                         }
306                          
307                         foreach(var br in this.branches) {
308                         //      GLib.debug("test:%s=%s", br.get_upstream().get_shorthand() , target);
309                                 if ( br.get_upstream().get_shorthand() == target) {
310                                         return br;
311                                 }
312                                 
313                         }
314                         //GLib.debug("missing %s", remote_branch_name);                 
315                         return null;
316                 
317                 }
318                  
319                 
320                 public void fetchAll()
321                 {
322                         this.loadLocalBranches();
323                         this.loadRemoteHeads();
324                         
325                         // remotes probably will not work with http auth..
326                         //var ar = this.repo.list_remotes();
327                         //foreach(var n in ar) {
328                         var n = "origin"; 
329                         
330                                 GLib.debug("got remote '%s'", n);
331                                 var r = this.repo.lookup_remote(n);
332                                 GLib.debug("connecting '%s'", r.get_url());
333                                  
334                                 try {
335                                         string[] h = { "a = 1" };
336                                         r.connect(Ggit.Direction.FETCH, this.callbacks, null, null);
337                                         
338                                 } catch (Error e) {
339                                         GLib.debug("Got Error Message: %s", e.message);
340                                         return;
341                                 }
342                                 string[] far = {};
343
344                                 foreach(var rh in this.remote_heads) {
345                                         if (rh.get_name().has_prefix("refs/remotes/")) {
346                                                    continue;
347                                          }
348                                 
349                                         var br = this.getBranch(n, rh.get_name());
350                                  
351                                         /*GLib.debug("got heads: name=%s   rev=%s  localrev=%s",
352                                                 rh.get_name(), 
353                                                 rh.get_oid().to_string(),
354                                                 br == null ? "?": this.repo.revparse(br.get_name() ).get_id().to_string()
355                                         );
356                                         */
357                                         var loc_oid = this.repo.revparse(br.get_name() ).get_id();
358                                         size_t ahead, behind;
359                                         this.repo.get_ahead_behind(
360                                                 loc_oid,
361                                                 rh.get_oid(),
362                                                 out ahead,
363                                                 out behind
364                                         );
365                                         
366                                         if (rh.get_oid().to_string() == this.repo.revparse(br.get_name() ).get_id().to_string()) {
367                                                 continue;
368                                         }
369                                         if (ahead > 0) {
370                                                 continue;
371                                         }
372                                         far += ("+refs/heads/" + br.get_name()) + ":refs/remotes/" + n + "/" + rh.get_name().replace("refs/heads/","");
373                                 } 
374                                 
375                                 if (far.length < 1) {
376                                         GLib.debug("no fetch required.. it's uptodate");
377                                         r.disconnect();
378                                         return;
379                                 }
380                                 
381                                 GLib.debug("getting remote specs '%s', %d", n, far.length);
382                                 
383 /*
384                                 var far = r.get_fetch_specs();
385                                 */
386                                 foreach(var rs in far) {
387                                         GLib.debug("got remote spec: %s", rs);
388                                         
389                                 }
390
391                                 var options = new Ggit.FetchOptions();
392                                 options.set_remote_callbacks(this.callbacks);
393                                 //yield Async.thread(() => {
394         
395                                         r.download(far, options);
396                                 //});
397                                 r.disconnect();
398                                 
399                                 //r.download(
400                          
401                 
402                 }
403                 
404                 
405                 
406                 public void pushAll()
407                 {
408                         
409                         this.loadLocalBranches();
410                         this.loadRemoteHeads();
411                         // remotes probably will not work with http auth..
412                         //var ar = this.repo.list_remotes();
413                         var n = "origin";
414                         
415                                 GLib.debug("got remote '%s'", n);
416                                 var r = this.repo.lookup_remote(n);
417                                 GLib.debug("connecting '%s'", r.get_url());
418                                  
419                                 r.connect(Ggit.Direction.PUSH, this.callbacks, null, null);
420                                 
421                                 //GLib.debug("getting specs '%s'", n);
422                                 /* 
423                                 
424                                 this.repo.add_remote_push(
425                                         "origin",
426                                         "+%s:%s".printf(head.get_shorthand(),head.get_name())
427                                 );
428  */
429  
430                                 string[] far = {};
431                                 var heads = r.list();
432                                 foreach(var rh in heads) {
433                                         if (rh.get_name().has_prefix("refs/remotes/")) {
434                                                    continue;
435                                          }
436                                 
437                                         var br = this.getBranch(n, rh.get_name());
438                                         /*
439                                         GLib.debug("got heads: name=%s   rev=%s  localrev=%s",
440                                                 rh.get_name(), 
441                                                 rh.get_oid().to_string(),
442                                                 br == null ? "?": this.repo.revparse(br.get_name() ).get_id().to_string()
443                                         );*/
444                                         var loc_oid = this.repo.revparse(br.get_name() ).get_id();
445                                         size_t ahead, behind;
446                                         this.repo.get_ahead_behind(
447                                                 loc_oid,
448                                                 rh.get_oid(),
449                                                 out ahead,
450                                                 out behind
451                                         );
452                                         
453                                         if (rh.get_oid().to_string() == this.repo.revparse(br.get_name() ).get_id().to_string()) {
454                                                 continue;
455                                         }
456                                         if (behind > 0) {
457                                                 continue;
458                                         }
459                                         far += ("+refs/heads/" + br.get_name()) + ":"+ rh.get_name();
460                                 }  
461                                 
462                                 if (far.length < 1) {
463                                         GLib.debug("no push required.. it's uptodate");
464                                         r.disconnect();
465                                         return;
466                                 }
467  
468                                 /*var head = this.repo.get_head();
469                                 string[] far = {};
470                                 far += "+%s:%s".printf(head.get_name(),head.get_name());
471                                 */
472                                 foreach(var rs in far) {
473                                         GLib.debug("got remote spec: %s", rs);
474                                         
475                                 }
476                                         
477                                 var popts = new Ggit.PushOptions();
478                                  popts.callbacks = this.callbacks;
479                                 GLib.debug("Push?");
480                                 r.upload(far,popts);
481                                 GLib.debug("Push done?");
482                                 r.disconnect();
483                                 
484                                 
485                                 //r.download(
486                          
487                 
488                 }
489                 
490                  
491
492         }
493         
494         private class Callbacks : Ggit.RemoteCallbacks
495         {
496                 //private Remote d_remote;
497                 private Ggit.RemoteCallbacks? d_proxy = null;
498
499                 public delegate void TransferProgress(Ggit.TransferProgress stats);
500                 //private TransferProgress? d_transfer_progress;
501
502                 public Callbacks( Repo repo)  //, Ggit.RemoteCallbacks? proxy) //,Remote remote, owned TransferProgress? transfer_progress)
503                 {
504                         //d_remote = remote;
505                         //d_proxy = proxy;
506                         //d_transfer_progress = (owned)transfer_progress;
507                 }
508
509                 protected override void progress(string message)
510                 {
511                         GLib.debug("progress: %s", message);
512                         if (d_proxy != null)
513                         {
514                                 d_proxy.progress(message);
515                         }
516                 }
517
518                 protected override void transfer_progress(Ggit.TransferProgress stats)
519                 {
520                         GLib.debug("transfer_progress");
521                         /*
522                         if (d_transfer_progress != null)
523                         {
524                                 d_transfer_progress(stats);
525                         }
526
527                         if (d_proxy != null)
528                         {
529                                 d_proxy.transfer_progress(stats);
530                         }
531                         */
532                 }
533
534                 protected override void update_tips(string refname, Ggit.OId a, Ggit.OId b)
535                 {
536                         GLib.debug("update_tips");
537                         //d_remote.tip_updated(refname, a, b);
538
539                         if (d_proxy != null)
540                         {
541                                 d_proxy.update_tips(refname, a, b);
542                         }
543                 }
544
545                 protected override void completion(Ggit.RemoteCompletionType type)
546                 {
547                         GLib.debug("completion");
548                         if (d_proxy != null)
549                         {
550                                 d_proxy.completion(type);
551                         }
552                 }
553
554                 protected override Ggit.Cred? credentials(string url, string? username_from_url, Ggit.Credtype allowed_types) throws Error
555                 {
556  
557                         GLib.debug("get credentials %s  UN=%s", url, username_from_url);
558                         var uri = new Soup.URI(url);
559
560                         if (uri != null) {
561                                 var ret = this.netrc(uri.get_host());
562                                 if (ret != null) {
563                                         return ret;
564                                 }
565                                 
566                                 //return new Ggit.CredPlaintext(username_from_url, "test");
567                         }
568                         return null;
569                         /*var provider = d_remote.credentials_provider;
570
571                         if (provider != null)
572                         {
573                                 ret = provider.credentials(url, username_from_url, allowed_types);
574                         }
575
576                         if (ret == null && d_proxy != null)
577                         {
578                                 ret = d_proxy.credentials(url, username_from_url, allowed_types);
579                         }
580                         
581                         return ret;
582                         */
583                 }
584                 public  Ggit.Cred netrc(string domain) 
585                 {
586                         string str;
587                         GLib.FileUtils.get_contents(GLib.Environment.get_home_dir() + "/.netrc", out str);
588                         var lines = str.split("\n");
589                         for(var i=0; i< lines.length; i++) {
590                                 // assumes one line per entry.. if not we are buggered...
591                                 //GLib.debug("got %s" , lines[i]);
592                         
593                                 var bits =  Regex.split_simple ("[ \t]+", lines[i].strip());
594                                 if (bits.length < 6 || bits[0] != "machine" || bits[1] != domain) {
595                                         continue;
596                                 }
597                                 GLib.debug("found password?");
598                                 // we are gussing.... 
599                                 return new Ggit.CredPlaintext(bits[3], bits[5]);
600
601                         }
602                         return null;
603
604
605                 
606                 
607                 }
608                 
609         }
610         
611         
612
613 }