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