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