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                         var oid =  this.repo.revparse(this.head.get_name() ).get_id()  ;
130                         var moid =  this.repo.revparse("refs/heads/master" ).get_id()  ;
131                         
132                         var a = new Ggit.RevisionWalker(this.repo);
133                         a.set_sort_mode(Ggit.SortMode.TOPOLOGICAL);
134                         a.push(oid);
135                         a.hide(moid);
136                         var last = oid;
137                         for (var noid = a.next(); noid != null; noid= a.next()) {
138                                 //var commit = this.repo.lookup(noid, typeof(Ggit.Commit)) as Ggit.Commit;
139                                 GLib.debug("rev: %s",
140                                         noid.to_string()
141                                 );
142                                 last = noid;
143                         }
144                         var commit = this.repo.lookup(last, typeof(Ggit.Commit)) as Ggit.Commit;
145                         var parent = commit.get_parents();
146                         GLib.debug("parent = %s", parent.get_id(0).to_string());
147                         var master_rev =  parent.get_id(0);
148                         var master_commit  = this.repo.lookup_commit(master_rev);;
149                         
150                         var head_commit = this.repo.lookup_commit(oid);
151                         
152                         var master_tree = master_commit.get_tree();
153                         var head_tree = head_commit.get_tree();
154                         
155                         var diff = new Ggit.Diff.tree_to_tree(this.repo, master_tree, head_tree, new Ggit.DiffOptions());
156                         
157                         diff.print(Ggit.DiffFormatType.PATCH, ( delta,  hunk,  line) => {
158                                 GLib.debug("%d: %s, %s", line.get_new_lineno(), line.get_origin().to_string(), line.get_text());
159                                 return 0;
160                         });
161                         // let's try a merge..
162                         var mo = new Ggit.MergeOptions();
163                         mo.set_file_favor(Ggit.MergeFileFavor.THEIRS);
164                         var ix = this.repo.merge_trees(master_tree, master_tree, head_tree, mo);
165                         
166                         if (ix.has_conflicts()) {
167                                 GLib.debug("merge has conflicts");
168                                 return;
169                         }
170                          var treeoid = ix.write_tree();
171                          
172                          
173                           
174                         var parents =   new Ggit.Commit[] { master_commit };
175
176
177                         var new_tree = this.repo.lookup(treeoid,typeof (Ggit.Tree))  as   Ggit.Tree;
178                         
179                         var sig = new Ggit.Signature.now(
180                                         this.repo.get_config().get_string("user.name"),
181                                         this.repo.get_config().get_string("user.email")
182                         );
183                         this.repo.create_commit("HEAD", sig, sig, null, "Test Merge", new_tree, parents);
184         
185                         
186                         
187                         
188                         
189                 }
190                 public void mergeMasterIntoHead()
191                 {
192                         // assumes head is not master...
193                         var head_oid =  this.repo.revparse(this.head.get_name() ).get_id()  ;
194                         var master_oid =  this.repo.revparse("refs/heads/master" ).get_id()  ;
195
196                         var master_commit  = this.repo.lookup_commit(master_oid);;
197                         var head_commit = this.repo.lookup_commit(head_oid);
198                          
199                 
200                         var anc_oid = this.repo.merge_base(master_commit.get_id(), head_commit.get_id());
201                         
202                         var anc_commit = this.repo.lookup_commit(anc_oid);
203                         var anc_tree = anc_commit.get_tree();
204                         
205                         var master_tree = master_commit.get_tree();
206                         var head_tree = head_commit.get_tree();
207                         var mo = new Ggit.MergeOptions();
208                         mo.set_file_favor(Ggit.MergeFileFavor.THEIRS);
209                         var ix  = this.repo.merge_trees(anc_tree, master_tree, head_tree, mo);
210                          var treeoid = ix.write_tree();
211                          
212                          
213                           
214                         var parents =   new Ggit.Commit[] { master_commit };
215
216
217                         var new_tree = this.repo.lookup(treeoid,typeof (Ggit.Tree))  as   Ggit.Tree;
218                         
219                         var sig = new Ggit.Signature.now(
220                                         this.repo.get_config().get_string("user.name"),
221                                         this.repo.get_config().get_string("user.email")
222                         );
223                         this.repo.create_commit("HEAD", sig, sig, null, "Test Merge", new_tree, parents);
224         
225                 
226                 }
227                 
228                 
229                 /*
230                 public bool doMergeClose(string commit_message)
231                 {
232                         this.loadLocalBranches(true);
233                         var oldbranch = this.head.get_name();
234             // going to asume this is merge trees..
235                            string [] cmd = { "merge",   "--squash",  oldbranch };
236                            this.git( cmd );
237                            cmd = { "commit",   "-a" , "-m",  commit_message };
238                            this.git( cmd );
239                            this.push();
240                            this.loadBranches(); // updates lastrev..
241                
242                        var notification = new Notify.Notification(
243                                "Merged branch %s to %s".printf(oldbranch, master),
244                                "",
245                                 "dialog-information"
246                                
247                        );
248
249                        notification.set_timeout(5);
250                        notification.show();   
251                
252                 
253                 }
254                 */
255                 
256                 
257                 public bool is_auto_branch ()
258                 {
259                         if (this.name == "gitlog") {
260                                 return false;
261                         }
262                         // check remote...
263                         if (this.is_managed()) {
264                                 return true;
265                         }
266                         return false;
267                         
268          
269                 }
270                 
271                 public void loadRemoteHeads(bool force = false)
272                 {
273                         
274                         if (!force && this.remote_heads != null) {
275                                 return;
276                         }
277                         var r = this.repo.lookup_remote("origin");
278                         r.connect(Ggit.Direction.FETCH, this.callbacks, null, null);
279                         this.remote_heads = r.list();
280                 
281                 }
282                 
283                 
284                 
285                 Ggit.Branch? getBranch(string remote_name, string remote_branch_name)
286                 {
287                          //GLib.debug("bn=%s",remote_branch_name);
288                          if (remote_branch_name.has_prefix("refs/remotes/")) {
289                                  return null;
290                          }
291
292                          var target = remote_branch_name.replace("refs/heads/", remote_name+"/") .replace("refs/remotes/", "");
293                         if (target == "HEAD") {
294                                 target = remote_name +"/master";
295                         }
296                          
297                         foreach(var br in this.branches) {
298                         //      GLib.debug("test:%s=%s", br.get_upstream().get_shorthand() , target);
299                                 if ( br.get_upstream().get_shorthand() == target) {
300                                         return br;
301                                 }
302                                 
303                         }
304                         //GLib.debug("missing %s", remote_branch_name);                 
305                         return null;
306                 
307                 }
308                  
309                 
310                 public void fetchAll()
311                 {
312                         this.loadLocalBranches();
313                         this.loadRemoteHeads();
314                         
315                         // remotes probably will not work with http auth..
316                         //var ar = this.repo.list_remotes();
317                         //foreach(var n in ar) {
318                         var n = "origin"; 
319                         
320                                 GLib.debug("got remote '%s'", n);
321                                 var r = this.repo.lookup_remote(n);
322                                 GLib.debug("connecting '%s'", r.get_url());
323                                  
324                                 try {
325                                         string[] h = { "a = 1" };
326                                         r.connect(Ggit.Direction.FETCH, this.callbacks, null, null);
327                                         
328                                 } catch (Error e) {
329                                         GLib.debug("Got Error Message: %s", e.message);
330                                         return;
331                                 }
332                                 string[] far = {};
333
334                                 foreach(var rh in this.remote_heads) {
335                                         if (rh.get_name().has_prefix("refs/remotes/")) {
336                                                    continue;
337                                          }
338                                 
339                                         var br = this.getBranch(n, rh.get_name());
340                                  
341                                         /*GLib.debug("got heads: name=%s   rev=%s  localrev=%s",
342                                                 rh.get_name(), 
343                                                 rh.get_oid().to_string(),
344                                                 br == null ? "?": this.repo.revparse(br.get_name() ).get_id().to_string()
345                                         );
346                                         */
347                                         var loc_oid = this.repo.revparse(br.get_name() ).get_id();
348                                         size_t ahead, behind;
349                                         this.repo.get_ahead_behind(
350                                                 loc_oid,
351                                                 rh.get_oid(),
352                                                 out ahead,
353                                                 out behind
354                                         );
355                                         
356                                         if (rh.get_oid().to_string() == this.repo.revparse(br.get_name() ).get_id().to_string()) {
357                                                 continue;
358                                         }
359                                         if (ahead > 0) {
360                                                 continue;
361                                         }
362                                         far += ("+refs/heads/" + br.get_name()) + ":refs/remotes/" + n + "/" + rh.get_name().replace("refs/heads/","");
363                                 } 
364                                 
365                                 if (far.length < 1) {
366                                         GLib.debug("no fetch required.. it's uptodate");
367                                         r.disconnect();
368                                         return;
369                                 }
370                                 
371                                 GLib.debug("getting remote specs '%s', %d", n, far.length);
372                                 
373 /*
374                                 var far = r.get_fetch_specs();
375                                 */
376                                 foreach(var rs in far) {
377                                         GLib.debug("got remote spec: %s", rs);
378                                         
379                                 }
380
381                                 var options = new Ggit.FetchOptions();
382                                 options.set_remote_callbacks(this.callbacks);
383                                 //yield Async.thread(() => {
384         
385                                         r.download(far, options);
386                                 //});
387                                 r.disconnect();
388                                 
389                                 //r.download(
390                          
391                 
392                 }
393                 
394                 
395                 
396                 public void pushAll()
397                 {
398                         
399                         this.loadLocalBranches();
400                         this.loadRemoteHeads();
401                         // remotes probably will not work with http auth..
402                         //var ar = this.repo.list_remotes();
403                         var n = "origin";
404                         
405                                 GLib.debug("got remote '%s'", n);
406                                 var r = this.repo.lookup_remote(n);
407                                 GLib.debug("connecting '%s'", r.get_url());
408                                  
409                                 r.connect(Ggit.Direction.PUSH, this.callbacks, null, null);
410                                 
411                                 //GLib.debug("getting specs '%s'", n);
412                                 /* 
413                                 
414                                 this.repo.add_remote_push(
415                                         "origin",
416                                         "+%s:%s".printf(head.get_shorthand(),head.get_name())
417                                 );
418  */
419  
420                                 string[] far = {};
421                                 var heads = r.list();
422                                 foreach(var rh in heads) {
423                                         if (rh.get_name().has_prefix("refs/remotes/")) {
424                                                    continue;
425                                          }
426                                 
427                                         var br = this.getBranch(n, rh.get_name());
428                                         /*
429                                         GLib.debug("got heads: name=%s   rev=%s  localrev=%s",
430                                                 rh.get_name(), 
431                                                 rh.get_oid().to_string(),
432                                                 br == null ? "?": this.repo.revparse(br.get_name() ).get_id().to_string()
433                                         );*/
434                                         var loc_oid = this.repo.revparse(br.get_name() ).get_id();
435                                         size_t ahead, behind;
436                                         this.repo.get_ahead_behind(
437                                                 loc_oid,
438                                                 rh.get_oid(),
439                                                 out ahead,
440                                                 out behind
441                                         );
442                                         
443                                         if (rh.get_oid().to_string() == this.repo.revparse(br.get_name() ).get_id().to_string()) {
444                                                 continue;
445                                         }
446                                         if (behind > 0) {
447                                                 continue;
448                                         }
449                                         far += ("+refs/heads/" + br.get_name()) + ":"+ rh.get_name();
450                                 }  
451                                 
452                                 if (far.length < 1) {
453                                         GLib.debug("no push required.. it's uptodate");
454                                         r.disconnect();
455                                         return;
456                                 }
457  
458                                 /*var head = this.repo.get_head();
459                                 string[] far = {};
460                                 far += "+%s:%s".printf(head.get_name(),head.get_name());
461                                 */
462                                 foreach(var rs in far) {
463                                         GLib.debug("got remote spec: %s", rs);
464                                         
465                                 }
466                                         
467                                 var popts = new Ggit.PushOptions();
468                                  popts.callbacks = this.callbacks;
469                                 GLib.debug("Push?");
470                                 r.upload(far,popts);
471                                 GLib.debug("Push done?");
472                                 r.disconnect();
473                                 
474                                 
475                                 //r.download(
476                          
477                 
478                 }
479                 
480                  
481
482         }
483         
484         private class Callbacks : Ggit.RemoteCallbacks
485         {
486                 //private Remote d_remote;
487                 private Ggit.RemoteCallbacks? d_proxy = null;
488
489                 public delegate void TransferProgress(Ggit.TransferProgress stats);
490                 //private TransferProgress? d_transfer_progress;
491
492                 public Callbacks( Repo repo)  //, Ggit.RemoteCallbacks? proxy) //,Remote remote, owned TransferProgress? transfer_progress)
493                 {
494                         //d_remote = remote;
495                         //d_proxy = proxy;
496                         //d_transfer_progress = (owned)transfer_progress;
497                 }
498
499                 protected override void progress(string message)
500                 {
501                         GLib.debug("progress: %s", message);
502                         if (d_proxy != null)
503                         {
504                                 d_proxy.progress(message);
505                         }
506                 }
507
508                 protected override void transfer_progress(Ggit.TransferProgress stats)
509                 {
510                         GLib.debug("transfer_progress");
511                         /*
512                         if (d_transfer_progress != null)
513                         {
514                                 d_transfer_progress(stats);
515                         }
516
517                         if (d_proxy != null)
518                         {
519                                 d_proxy.transfer_progress(stats);
520                         }
521                         */
522                 }
523
524                 protected override void update_tips(string refname, Ggit.OId a, Ggit.OId b)
525                 {
526                         GLib.debug("update_tips");
527                         //d_remote.tip_updated(refname, a, b);
528
529                         if (d_proxy != null)
530                         {
531                                 d_proxy.update_tips(refname, a, b);
532                         }
533                 }
534
535                 protected override void completion(Ggit.RemoteCompletionType type)
536                 {
537                         GLib.debug("completion");
538                         if (d_proxy != null)
539                         {
540                                 d_proxy.completion(type);
541                         }
542                 }
543
544                 protected override Ggit.Cred? credentials(string url, string? username_from_url, Ggit.Credtype allowed_types) throws Error
545                 {
546  
547                         GLib.debug("get credentials %s  UN=%s", url, username_from_url);
548                         var uri = new Soup.URI(url);
549
550                         if (uri != null) {
551                                 var ret = this.netrc(uri.get_host());
552                                 if (ret != null) {
553                                         return ret;
554                                 }
555                                 
556                                 //return new Ggit.CredPlaintext(username_from_url, "test");
557                         }
558                         return null;
559                         /*var provider = d_remote.credentials_provider;
560
561                         if (provider != null)
562                         {
563                                 ret = provider.credentials(url, username_from_url, allowed_types);
564                         }
565
566                         if (ret == null && d_proxy != null)
567                         {
568                                 ret = d_proxy.credentials(url, username_from_url, allowed_types);
569                         }
570                         
571                         return ret;
572                         */
573                 }
574                 public  Ggit.Cred netrc(string domain) 
575                 {
576                         string str;
577                         GLib.FileUtils.get_contents(GLib.Environment.get_home_dir() + "/.netrc", out str);
578                         var lines = str.split("\n");
579                         for(var i=0; i< lines.length; i++) {
580                                 // assumes one line per entry.. if not we are buggered...
581                                 //GLib.debug("got %s" , lines[i]);
582                         
583                                 var bits =  Regex.split_simple ("[ \t]+", lines[i].strip());
584                                 if (bits.length < 6 || bits[0] != "machine" || bits[1] != domain) {
585                                         continue;
586                                 }
587                                 GLib.debug("found password?");
588                                 // we are gussing.... 
589                                 return new Ggit.CredPlaintext(bits[3], bits[5]);
590
591                         }
592                         return null;
593
594
595                 
596                 
597                 }
598                 
599         }
600         
601         
602
603 }