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