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