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