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