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