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