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