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 (500, () => {
24       GLib.debug("Meanwhile");
25       return false;
26     }, GLib.Priority.DEFAULT);
27         
28         var loop = new MainLoop();
29         
30         var a = new GitLive.Repo("/home/alan/gitlive/gitlive");
31         
32         a.loadRemoteHeads.begin(true, (obj,res) => {
33                 a.loadRemoteHeads.end(res);
34                 print("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                                 this.remote_heads = r.list();
317                                 
318                                 foreach(var br in this.remote_heads) {
319                                         if (!br.get_name().has_prefix("refs/heads/")) {
320                                                 continue;
321                                         }
322                                         
323                                         GLib.debug("Remote: name=%s  oid=%s local_oid=%s is_local=%s",
324                                                 br.get_name().substring(11),
325                                                 br.get_oid().to_string(),
326                                                 br.get_local_oid().to_string(),
327                                                 br.is_local() ? "Y" : "n"
328                                                 );
329                                 }
330                                 Idle.add((owned) callback);
331                                 return true;;
332                         };
333                         new Thread<bool>("thread-example", run);
334                         yield;
335                         
336
337                 }
338                  
339                 
340                 Ggit.Branch? getBranch(string remote_name, string remote_branch_name)
341                 {
342                          //GLib.debug("bn=%s",remote_branch_name);
343                          if (remote_branch_name.has_prefix("refs/remotes/")) {
344                                  return null;
345                          }
346
347                          var target = remote_branch_name.replace("refs/heads/", remote_name+"/") .replace("refs/remotes/", "");
348                         if (target == "HEAD") {
349                                 target = remote_name +"/master";
350                         }
351                          
352                         foreach(var br in this.branches) {
353                         //      GLib.debug("test:%s=%s", br.get_upstream().get_shorthand() , target);
354                                 if ( br.get_upstream().get_shorthand() == target) {
355                                         return br;
356                                 }
357                                 
358                         }
359                         //GLib.debug("missing %s", remote_branch_name);                 
360                         return null;
361                 
362                 }
363                  
364                 
365                 public void fetchAll()
366                 {
367                         this.loadLocalBranches();
368                         this.loadRemoteHeads();
369                         
370                         // remotes probably will not work with http auth..
371                         //var ar = this.repo.list_remotes();
372                         //foreach(var n in ar) {
373                         var n = "origin"; 
374                         
375                                 GLib.debug("got remote '%s'", n);
376                                 var r = this.repo.lookup_remote(n);
377                                 GLib.debug("connecting '%s'", r.get_url());
378                                  
379                                 try {
380                                         string[] h = { "a = 1" };
381                                         r.connect(Ggit.Direction.FETCH, this.callbacks, null, null);
382                                         
383                                 } catch (Error e) {
384                                         GLib.debug("Got Error Message: %s", e.message);
385                                         return;
386                                 }
387                                 string[] far = {};
388
389                                 foreach(var rh in this.remote_heads) {
390                                         if (rh.get_name().has_prefix("refs/remotes/")) {
391                                                    continue;
392                                          }
393                                 
394                                         var br = this.getBranch(n, rh.get_name());
395                                  
396                                         /*GLib.debug("got heads: name=%s   rev=%s  localrev=%s",
397                                                 rh.get_name(), 
398                                                 rh.get_oid().to_string(),
399                                                 br == null ? "?": this.repo.revparse(br.get_name() ).get_id().to_string()
400                                         );
401                                         */
402                                         //var loc_oid = this.repo.revparse(br.get_name() ).get_id();
403                                         
404                                         var loc_oid = br.get_target();
405                                         
406                                         size_t ahead, behind;
407                                         this.repo.get_ahead_behind(
408                                                 loc_oid,
409                                                 rh.get_oid(),
410                                                 out ahead,
411                                                 out behind
412                                         );
413                                         
414                                         if (rh.get_oid().to_string() == this.repo.revparse(br.get_name() ).get_id().to_string()) {
415                                                 continue;
416                                         }
417                                         if (ahead > 0) {
418                                                 continue;
419                                         }
420                                         far += ("+refs/heads/" + br.get_name()) + ":refs/remotes/" + n + "/" + rh.get_name().replace("refs/heads/","");
421                                 } 
422                                 
423                                 if (far.length < 1) {
424                                         GLib.debug("no fetch required.. it's uptodate");
425                                         r.disconnect();
426                                         return;
427                                 }
428                                 
429                                 GLib.debug("getting remote specs '%s', %d", n, far.length);
430                                 
431 /*
432                                 var far = r.get_fetch_specs();
433                                 */
434                                 foreach(var rs in far) {
435                                         GLib.debug("got remote spec: %s", rs);
436                                         
437                                 }
438
439                                 var options = new Ggit.FetchOptions();
440                                 options.set_remote_callbacks(this.callbacks);
441                                 //yield Async.thread(() => {
442         
443                                         r.download(far, options);
444                                 //});
445                                 r.disconnect();
446                                 
447                                 //r.download(
448                          
449                 
450                 }
451                 
452                 
453                 
454                 public void pushAll()
455                 {
456                         
457                         this.loadLocalBranches();
458                         this.loadRemoteHeads();
459                         // remotes probably will not work with http auth..
460                         //var ar = this.repo.list_remotes();
461                         var n = "origin";
462                         
463                                 GLib.debug("got remote '%s'", n);
464                                 var r = this.repo.lookup_remote(n);
465                                 GLib.debug("connecting '%s'", r.get_url());
466                                  
467                                 r.connect(Ggit.Direction.PUSH, this.callbacks, null, null);
468                                 
469                                 //GLib.debug("getting specs '%s'", n);
470                                 /* 
471                                 
472                                 this.repo.add_remote_push(
473                                         "origin",
474                                         "+%s:%s".printf(head.get_shorthand(),head.get_name())
475                                 );
476  */
477  
478                                 string[] far = {};
479                                 var heads = r.list();
480                                 foreach(var rh in heads) {
481                                         if (rh.get_name().has_prefix("refs/remotes/")) {
482                                                    continue;
483                                          }
484                                 
485                                         var br = this.getBranch(n, rh.get_name());
486                                         /*
487                                         GLib.debug("got heads: name=%s   rev=%s  localrev=%s",
488                                                 rh.get_name(), 
489                                                 rh.get_oid().to_string(),
490                                                 br == null ? "?": this.repo.revparse(br.get_name() ).get_id().to_string()
491                                         );*/
492                                         var loc_oid = this.repo.revparse(br.get_name() ).get_id();
493                                         size_t ahead, behind;
494                                         this.repo.get_ahead_behind(
495                                                 loc_oid,
496                                                 rh.get_oid(),
497                                                 out ahead,
498                                                 out behind
499                                         );
500                                         
501                                         if (rh.get_oid().to_string() == this.repo.revparse(br.get_name() ).get_id().to_string()) {
502                                                 continue;
503                                         }
504                                         if (behind > 0) {
505                                                 continue;
506                                         }
507                                         far += ("+refs/heads/" + br.get_name()) + ":"+ rh.get_name();
508                                 }  
509                                 
510                                 if (far.length < 1) {
511                                         GLib.debug("no push required.. it's uptodate");
512                                         r.disconnect();
513                                         return;
514                                 }
515  
516                                 /*var head = this.repo.get_head();
517                                 string[] far = {};
518                                 far += "+%s:%s".printf(head.get_name(),head.get_name());
519                                 */
520                                 foreach(var rs in far) {
521                                         GLib.debug("got remote spec: %s", rs);
522                                         
523                                 }
524                                         
525                                 var popts = new Ggit.PushOptions();
526                                  popts.callbacks = this.callbacks;
527                                 GLib.debug("Push?");
528                                 r.upload(far,popts);
529                                 GLib.debug("Push done?");
530                                 r.disconnect();
531                                 
532                                 
533                                 //r.download(
534                          
535                 
536                 }
537                 
538                  
539
540         }
541         
542         private class Callbacks : Ggit.RemoteCallbacks
543         {
544                 //private Remote d_remote;
545                 private Ggit.RemoteCallbacks? d_proxy = null;
546
547                 public delegate void TransferProgress(Ggit.TransferProgress stats);
548                 //private TransferProgress? d_transfer_progress;
549
550                 public Callbacks( Repo repo)  //, Ggit.RemoteCallbacks? proxy) //,Remote remote, owned TransferProgress? transfer_progress)
551                 {
552                         //d_remote = remote;
553                         //d_proxy = proxy;
554                         //d_transfer_progress = (owned)transfer_progress;
555                 }
556
557                 protected override void progress(string message)
558                 {
559                         GLib.debug("progress: %s", message);
560                         if (d_proxy != null)
561                         {
562                                 d_proxy.progress(message);
563                         }
564                 }
565
566                 protected override void transfer_progress(Ggit.TransferProgress stats)
567                 {
568                         GLib.debug("transfer_progress");
569                         /*
570                         if (d_transfer_progress != null)
571                         {
572                                 d_transfer_progress(stats);
573                         }
574
575                         if (d_proxy != null)
576                         {
577                                 d_proxy.transfer_progress(stats);
578                         }
579                         */
580                 }
581
582                 protected override void update_tips(string refname, Ggit.OId a, Ggit.OId b)
583                 {
584                         GLib.debug("update_tips");
585                         //d_remote.tip_updated(refname, a, b);
586
587                         if (d_proxy != null)
588                         {
589                                 d_proxy.update_tips(refname, a, b);
590                         }
591                 }
592
593                 protected override void completion(Ggit.RemoteCompletionType type)
594                 {
595                         GLib.debug("completion");
596                         if (d_proxy != null)
597                         {
598                                 d_proxy.completion(type);
599                         }
600                 }
601
602                 protected override Ggit.Cred? credentials(string url, string? username_from_url, Ggit.Credtype allowed_types) throws Error
603                 {
604  
605                         GLib.debug("get credentials %s  UN=%s", url, username_from_url);
606                         var uri = new Soup.URI(url);
607
608                         if (uri != null) {
609                                 var ret = this.netrc(uri.get_host());
610                                 if (ret != null) {
611                                         return ret;
612                                 }
613                                 
614                                 //return new Ggit.CredPlaintext(username_from_url, "test");
615                         }
616                         return null;
617                         /*var provider = d_remote.credentials_provider;
618
619                         if (provider != null)
620                         {
621                                 ret = provider.credentials(url, username_from_url, allowed_types);
622                         }
623
624                         if (ret == null && d_proxy != null)
625                         {
626                                 ret = d_proxy.credentials(url, username_from_url, allowed_types);
627                         }
628                         
629                         return ret;
630                         */
631                 }
632                 public  Ggit.Cred netrc(string domain) 
633                 {
634                         string str;
635                         GLib.FileUtils.get_contents(GLib.Environment.get_home_dir() + "/.netrc", out str);
636                         var lines = str.split("\n");
637                         for(var i=0; i< lines.length; i++) {
638                                 // assumes one line per entry.. if not we are buggered...
639                                 //GLib.debug("got %s" , lines[i]);
640                         
641                                 var bits =  Regex.split_simple ("[ \t]+", lines[i].strip());
642                                 if (bits.length < 6 || bits[0] != "machine" || bits[1] != domain) {
643                                         continue;
644                                 }
645                                 GLib.debug("found password?");
646                                 // we are gussing.... 
647                                 return new Ggit.CredPlaintext(bits[3], bits[5]);
648
649                         }
650                         return null;
651
652
653                 
654                 
655                 }
656                 
657         }
658         
659         
660
661 }