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