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