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