2 // valac -o /tmp/ggit Git.vala --pkg libgit2-glib-1.0 --pkg libsoup-2.4 --pkg gee-0.8 -g
7 GLib.Log.set_handler(null,
8 GLib.LogLevelFlags.LEVEL_DEBUG | GLib.LogLevelFlags.LEVEL_WARNING | GLib.LogLevelFlags.LEVEL_INFO,
21 var a = new GitLive.Repo("/home/alan/gitlive/gitlive");
26 GLib.Timeout.add (1, () => {
27 GLib.debug("Meanwhile");
29 }, GLib.Priority.HIGH);
31 var loop = new MainLoop();
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();
42 //a.mergeMasterIntoHead();
52 var a = new GitLive.Repo("/home/alan/git/test1-clone");
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);
57 var ix = a.repo.get_index();
60 var treeoid = ix.write_tree();
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 };
68 var tree = a.repo.lookup(treeoid,typeof (Ggit.Tree)) as Ggit.Tree;// odd format..
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);
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);
84 public class Repo : Object {
87 public Ggit.Repository repo;
90 public Repo(string path)
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);
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)
102 if (!force && this.branches != null) {
106 this.branches = new Gee.ArrayList<Ggit.Branch>();
107 var r = this.repo.enumerate_branches(Ggit.BranchType.LOCAL);
109 var br = r.get() as Ggit.Branch;
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();
120 GLib.debug("got branch: N=%s", br.get_name() );
121 GLib.debug("is_head %s", br.is_head() ? "Y" : "n");
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);
127 GLib.debug("HEAD= %s", br.get_name());
131 GLib.debug("Skip branch");
138 public bool is_managed()
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;
145 public bool is_autocommit ()
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;
150 public void set_autocommit(bool val)
152 this.repo.get_config().set_int32("gitlive.autocommit", val ? 1 : 0);
156 public void walkDiff()
158 this.loadLocalBranches();
162 var oid = this.repo.revparse(this.head.get_name() ).get_id() ;
163 var moid = this.repo.revparse("refs/heads/master" ).get_id() ;
165 var a = new Ggit.RevisionWalker(this.repo);
166 a.set_sort_mode(Ggit.SortMode.TOPOLOGICAL);
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",
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);;
183 var head_commit = this.repo.lookup_commit(oid);
185 var master_tree = master_commit.get_tree();
186 var head_tree = head_commit.get_tree();
188 var diff = new Ggit.Diff.tree_to_tree(this.repo, master_tree, head_tree, new Ggit.DiffOptions());
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());
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);
199 if (ix.has_conflicts()) {
200 GLib.debug("merge has conflicts");
203 var treeoid = ix.write_tree();
207 var parents = new Ggit.Commit[] { master_commit };
210 var new_tree = this.repo.lookup(treeoid,typeof (Ggit.Tree)) as Ggit.Tree;
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")
219 this.repo.create_commit("HEAD", sig, sig, null, "Test Merge", new_tree, parents);
225 public void diffhead()
227 var r = this.repo.enumerate_branches(Ggit.BranchType.LOCAL);
228 Ggit.Branch? head = null;
230 var gbr = r.get() as Ggit.Branch;
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());
240 var diff = new Ggit.Diff.tree_to_workdir(this.repo, commit.get_tree(), new Ggit.DiffOptions());
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;
251 ret += " " + line.get_text();
254 GLib.debug("%s", ret);
258 public void mergeMasterIntoHead()
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() ;
267 var master_commit = this.repo.lookup_commit(master_oid);;
268 var head_commit = this.repo.lookup_commit(head_oid);
271 var anc_oid = this.repo.merge_base(master_commit.get_id(), head_commit.get_id());
273 var anc_commit = this.repo.lookup_commit(anc_oid);
274 var anc_tree = anc_commit.get_tree();
276 var mo = new Ggit.MergeOptions();
277 var co = new Ggit.CheckoutOptions();
278 var the_ref = this.repo.lookup_reference_dwim("refs/heads/master");
280 var ac = new Ggit.AnnotatedCommit.from_ref(this.repo, the_ref);
282 var commits = new Ggit.AnnotatedCommit[] { ac };
284 this.repo.merge(commits, mo, co);
286 var cfg = this.repo.get_config().snapshot();
288 var sig = new Ggit.Signature.now(
289 cfg.get_string("user.name"),
290 cfg.get_string("user.email")
292 var new_head = this.repo.get_head();
293 var oid = new_head.get_target();
295 var ix = this.repo.get_index();
298 var treeoid = ix.write_tree();
300 var new_tree = this.repo.lookup(treeoid,typeof (Ggit.Tree)) as Ggit.Tree;
302 var parent = new_head.lookup() as Ggit.Commit;
303 Ggit.Commit[] parents = new Ggit.Commit[] { parent };
305 this.repo.create_commit("refs/heads/" + this.head.get_name(), sig, sig, null, "Test Merge", new_tree, parents);
314 public bool doMergeClose(string commit_message)
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 };
321 cmd = { "commit", "-a" , "-m", commit_message };
324 this.loadBranches(); // updates lastrev..
326 var notification = new Notify.Notification(
327 "Merged branch %s to %s".printf(oldbranch, master),
333 notification.set_timeout(5);
341 public bool is_auto_branch ()
343 if (this.name == "gitlog") {
347 if (this.is_managed()) {
355 public async void loadRemoteHeads(bool force = false)
357 SourceFunc callback = loadRemoteHeads.callback;
359 ThreadFunc<bool> run = () => {
361 if (!force && this.remote_heads != null) {
364 var r = this.repo.lookup_remote("origin");
365 r.connect(Ggit.Direction.FETCH, this.callbacks, null, null);
367 this.remote_heads = r.list();
369 foreach(var br in this.remote_heads) {
370 if (!br.get_name().has_prefix("refs/heads/")) {
374 GLib.debug("Remote: name=%s oid=%s local_oid=%s is_local=%s",
376 br.get_oid().to_string(),
377 br.get_local_oid().to_string(),
378 br.is_local() ? "Y" : "n"
381 Idle.add((owned) callback);
384 new Thread<bool>("loadRemoteHeads-" , run);
391 Ggit.Branch? getBranch(string remote_name, string remote_branch_name)
393 //GLib.debug("bn=%s",remote_branch_name);
394 if (remote_branch_name.has_prefix("refs/remotes/")) {
398 var target = remote_branch_name.replace("refs/heads/", remote_name+"/") .replace("refs/remotes/", "");
399 if (target == "HEAD") {
400 target = remote_name +"/master";
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) {
410 //GLib.debug("missing %s", remote_branch_name);
416 public void fetchAll()
418 this.loadLocalBranches();
419 this.loadRemoteHeads();
421 // remotes probably will not work with http auth..
422 //var ar = this.repo.list_remotes();
423 //foreach(var n in ar) {
426 GLib.debug("got remote '%s'", n);
427 var r = this.repo.lookup_remote(n);
428 GLib.debug("connecting '%s'", r.get_url());
431 string[] h = { "a = 1" };
432 r.connect(Ggit.Direction.FETCH, this.callbacks, null, null);
435 GLib.debug("Got Error Message: %s", e.message);
440 foreach(var rh in this.remote_heads) {
441 if (rh.get_name().has_prefix("refs/remotes/")) {
445 var br = this.getBranch(n, rh.get_name());
447 /*GLib.debug("got heads: name=%s rev=%s localrev=%s",
449 rh.get_oid().to_string(),
450 br == null ? "?": this.repo.revparse(br.get_name() ).get_id().to_string()
453 //var loc_oid = this.repo.revparse(br.get_name() ).get_id();
455 var loc_oid = br.get_target();
457 size_t ahead, behind;
458 this.repo.get_ahead_behind(
465 if (rh.get_oid().to_string() == this.repo.revparse(br.get_name() ).get_id().to_string()) {
471 far += ("+refs/heads/" + br.get_name()) + ":refs/remotes/" + n + "/" + rh.get_name().replace("refs/heads/","");
474 if (far.length < 1) {
475 GLib.debug("no fetch required.. it's uptodate");
480 GLib.debug("getting remote specs '%s', %d", n, far.length);
483 var far = r.get_fetch_specs();
485 foreach(var rs in far) {
486 GLib.debug("got remote spec: %s", rs);
490 var options = new Ggit.FetchOptions();
491 options.set_remote_callbacks(this.callbacks);
492 //yield Async.thread(() => {
494 r.download(far, options);
505 public void pushAll()
508 this.loadLocalBranches();
509 this.loadRemoteHeads();
510 // remotes probably will not work with http auth..
511 //var ar = this.repo.list_remotes();
514 GLib.debug("got remote '%s'", n);
515 var r = this.repo.lookup_remote(n);
516 GLib.debug("connecting '%s'", r.get_url());
518 r.connect(Ggit.Direction.PUSH, this.callbacks, null, null);
520 //GLib.debug("getting specs '%s'", n);
523 this.repo.add_remote_push(
525 "+%s:%s".printf(head.get_shorthand(),head.get_name())
530 var heads = r.list();
531 foreach(var rh in heads) {
532 if (rh.get_name().has_prefix("refs/remotes/")) {
536 var br = this.getBranch(n, rh.get_name());
538 GLib.debug("got heads: name=%s rev=%s localrev=%s",
540 rh.get_oid().to_string(),
541 br == null ? "?": this.repo.revparse(br.get_name() ).get_id().to_string()
543 var loc_oid = this.repo.revparse(br.get_name() ).get_id();
544 size_t ahead, behind;
545 this.repo.get_ahead_behind(
552 if (rh.get_oid().to_string() == this.repo.revparse(br.get_name() ).get_id().to_string()) {
558 far += ("+refs/heads/" + br.get_name()) + ":"+ rh.get_name();
561 if (far.length < 1) {
562 GLib.debug("no push required.. it's uptodate");
567 /*var head = this.repo.get_head();
569 far += "+%s:%s".printf(head.get_name(),head.get_name());
571 foreach(var rs in far) {
572 GLib.debug("got remote spec: %s", rs);
576 var popts = new Ggit.PushOptions();
577 popts.callbacks = this.callbacks;
580 GLib.debug("Push done?");
593 private class Callbacks : Ggit.RemoteCallbacks
595 //private Remote d_remote;
596 private Ggit.RemoteCallbacks? d_proxy = null;
598 public delegate void TransferProgress(Ggit.TransferProgress stats);
599 //private TransferProgress? d_transfer_progress;
601 public Callbacks( Repo repo) //, Ggit.RemoteCallbacks? proxy) //,Remote remote, owned TransferProgress? transfer_progress)
605 //d_transfer_progress = (owned)transfer_progress;
608 protected override void progress(string message)
610 GLib.debug("progress: %s", message);
613 d_proxy.progress(message);
617 protected override void transfer_progress(Ggit.TransferProgress stats)
619 GLib.debug("transfer_progress");
621 if (d_transfer_progress != null)
623 d_transfer_progress(stats);
628 d_proxy.transfer_progress(stats);
633 protected override void update_tips(string refname, Ggit.OId a, Ggit.OId b)
635 GLib.debug("update_tips");
636 //d_remote.tip_updated(refname, a, b);
640 d_proxy.update_tips(refname, a, b);
644 protected override void completion(Ggit.RemoteCompletionType type)
646 GLib.debug("completion");
649 d_proxy.completion(type);
653 protected override Ggit.Cred? credentials(string url, string? username_from_url, Ggit.Credtype allowed_types) throws Error
656 GLib.debug("get credentials %s UN=%s", url, username_from_url);
657 var uri = new Soup.URI(url);
660 var ret = this.netrc(uri.get_host());
665 //return new Ggit.CredPlaintext(username_from_url, "test");
668 /*var provider = d_remote.credentials_provider;
670 if (provider != null)
672 ret = provider.credentials(url, username_from_url, allowed_types);
675 if (ret == null && d_proxy != null)
677 ret = d_proxy.credentials(url, username_from_url, allowed_types);
683 public Ggit.Cred netrc(string domain)
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]);
692 var bits = Regex.split_simple ("[ \t]+", lines[i].strip());
693 if (bits.length < 6 || bits[0] != "machine" || bits[1] != domain) {
696 GLib.debug("found password?");
697 // we are gussing....
698 return new Ggit.CredPlaintext(bits[3], bits[5]);