10 static GitRepo _GitRepo;
12 public class GitRepo : Object
15 public Gee.ArrayList<GitMonitorQueue> cmds;
19 public string git_working_dir;
20 public bool debug = false;
21 public bool has_local_changes = false;
22 public string host = "";
23 public string git_status;
24 public string git_diff;
25 public string ahead_or_behind = "";
27 public Gee.HashMap<string,bool> ignore_files;
29 public GitBranch _currentBranch;
30 public GitBranch getCurrentBranch() {
31 if (this._currentBranch == null) {
32 Posix.usleep(100); // try and slow down branch loading
36 if (this._currentBranch == null) {
37 GLib.error("could not work out current branch? : %s ",this.git_working_dir );
39 return this._currentBranch;
43 public Gee.HashMap<string,GitBranch> branches; // accessed in GitBranch..
44 public RooTicket? activeTicket;
45 public Gee.HashMap<string,GitRepo> cache;
46 public Gee.HashMap<string,string> config_cache;
48 public Ggit.Repository repo;
49 public Ggit.RemoteHead[] remote_heads = null;
51 public static GitRepo singleton()
53 if (_GitRepo == null) {
54 _GitRepo = new GitRepo.single();
55 _GitRepo.cache = new Gee.HashMap<string,GitRepo>();
61 * index of.. matching gitpath..
63 public static int indexOf( Array<GitRepo> repos, string gitpath) {
64 // make a fake object to compare against..
65 var test_repo = GitRepo.get_sync(gitpath);
67 for(var i =0; i < repos.length; i++) {
68 if (repos.index(i).gitdir == test_repo.gitdir) {
80 public static Array<GitRepo> list()
83 //if (GitRepo.list_cache != null) {
84 // unowned Array<GitRepo> ret = GitRepo.list_cache;
87 var cache = GitRepo.singleton().cache;
88 var list_cache = new Array<GitRepo>();
90 var dir = Environment.get_home_dir() + "/gitlive";
92 var f = File.new_for_path(dir);
93 FileEnumerator file_enum;
95 file_enum = f.enumerate_children(
96 FileAttribute.STANDARD_DISPLAY_NAME + ","+
97 FileAttribute.STANDARD_TYPE,
98 FileQueryInfoFlags.NONE,
111 next_file = file_enum.next_file(null);
112 if (next_file == null) {
117 GLib.debug("Error: %s",e.message);
121 //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
123 if (next_file.get_file_type() != FileType.DIRECTORY) {
128 if (next_file.get_file_type() == FileType.SYMBOLIC_LINK) {
133 if (next_file.get_display_name()[0] == '.') {
137 var sp = dir+"/"+next_file.get_display_name();
139 var gitdir = dir + "/" + next_file.get_display_name() + "/.git";
141 if (!FileUtils.test(gitdir, FileTest.IS_DIR)) {
145 var rep = GitRepo.get_sync( sp );
146 list_cache.append_val(rep);
154 public static GitRepo get_sync(string path)
157 var cache = GitRepo.singleton().cache;
158 if (cache.has_key(path)) {
159 ret = cache.get(path);
161 ret = new GitRepo(path);
166 public static async GitRepo? get(string path)
169 SourceFunc callback = GitRepo.get.callback;
171 ThreadFunc<bool> run = () => {
173 var cache = GitRepo.singleton().cache;
174 if (cache.has_key(path)) {
175 ret = cache.get(path);
177 ret = new GitRepo(path);
179 Idle.add((owned) callback);
183 new Thread<bool>("thread-new-gitrepo-" + path, run);
189 private GitRepo.single() {
190 // used to create the signleton
195 * @param {Object} cfg - Configuration
196 * (basically repopath is currently only critical one.)
200 private GitRepo(string path)
203 this.name = File.new_for_path(path).get_basename();
204 this.ignore_files = new Gee.HashMap<string,bool>();
206 this.git_working_dir = path;
207 this.gitdir = path + "/.git";
208 if (!FileUtils.test(this.gitdir , FileTest.IS_DIR)) {
209 this.gitdir = path; // naked...
211 this.cmds = new Gee.ArrayList<GitMonitorQueue> ();
213 var cache = GitRepo.singleton().cache;
214 //Repo.superclass.constructor.call(this,cfg);
215 if ( !cache.has_key(path) ) {
216 cache.set( path, this);
219 this.repo = Ggit.Repository.open(GLib.File.new_for_path(path));
221 //var r = this.repo.lookup_remote("origin");
224 //var r = this.git({ "remote" , "get-url" , "--push" , "origin"});
225 //var uri = new Soup.URI(r.get_url());
226 //this.host = uri.get_host();
230 this.loadActiveTicket();
234 public bool is_master_branch()
236 // special branches that do not allow autopushing now...
237 return this.getCurrentBranch().name == "master" || this.getCurrentBranch().name == "roojs";
240 public void init_config()
242 this.config_cache = new Gee.HashMap<string,string>();
244 if (this.get_config("managed") == "") {
245 this.set_config("managed", this.host == "git.roojs.com" ? "1" : "0");
247 if (this.get_config("autocommit") == "") {
248 this.set_config("autocommit", this.host == "git.roojs.com" ? "1" : "0");
250 if (this.get_config("autopush") == "") {
251 this.set_config("autopush", this.host == "git.roojs.com" ? "1" : "0");
258 public string get_config(string key)
261 if (this.config_cache.has_key(key)) {
262 //GLib.debug("get_config %s = '%s'", key, this.config_cache.get(key));
263 return this.config_cache.get(key);
266 var cfg = this.repo.get_config().snapshot();
267 var ret = cfg.get_string("gitlive." + key).strip();
270 this.repo.get_config().set_string("gitlive." + key, "");
271 //this.config_cache.set(key, "");
272 //GLib.debug("get_config (fail) %s = '%s'", key, "");
273 return ""; // happens when there is nothing set...
277 public void set_config(string key, string value)
279 this.repo.get_config().set_string("gitlive." + key, value);
280 //this.git({ "config" , "gitlive." + key, value });
281 //this.config_cache.set(key,value);
284 public bool is_managed()
286 return this.get_config("managed") == "1";
290 public bool is_autocommit ()
292 return this.get_config("autocommit") == "1";
295 public void set_autocommit(bool val)
297 this.set_config("autocommit", val ? "1" : "0");
301 public bool is_auto_branch ()
303 if (this.name == "gitlog") {
307 if (this.is_managed()) {
315 public void set_auto_branch(bool val)
317 if (this.name == "gitlog") {
320 this.set_config("managed", val ? "1" : "0");
323 public bool is_autopush ()
325 return this.get_config("autopush") == "1";
327 public void set_autopush(bool val)
329 this.set_config("autopush", val ? "1" : "0");
333 public void loadStatus()
336 var r = this.git({ "status" , "--porcelain" });
338 this.has_local_changes = r.length > 0;
340 //var rs = this.git({ "status" , "-sb" });
341 var cb = this.getCurrentBranch();
343 this.ahead_or_behind = cb.ahead > 0 ? "A" : (cb.behind > 0 ? "B" : "");
346 this.git_diff = this.diffWorking();
350 public void loadBranches()
353 GitBranch.loadBranches(this);
357 public bool hasBranchCalled(string name)
359 foreach( var br in this.branches.values) {
360 if (br.name == name) {
368 public string branchesToString()
371 foreach( var br in this.branches.values) {
375 var col = /hours/.match(br.age) ? "#ff851b" : "#ffdc00"; // orange or yellow
376 ret += ret.length > 0 ? "\n" : "";
377 ret += br.name + " <span background=\"" + col + "\">" + br.age + "</span>";
383 public static void doMerges(string action, string ticket_id, string commit_message)
385 GitMonitor.gitmonitor.stop();
389 foreach(var repo in GitRepo.singleton().cache.values) {
390 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
391 var res = repo.doMerge(action,ticket_id, commit_message);
396 commitrevs += commitrevs.length > 0 ? " " : "";
397 commitrevs += repo.getCurrentBranch().lastrev;
400 if (sucess && action == "CLOSE") {
401 RooTicket.singleton().getById(ticket_id).close(commitrevs);
403 GitMonitor.gitmonitor.start();
407 public bool doMerge(string action, string ticket_id, string commit_message)
409 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
410 // also need to decide which branch we will merge into?
411 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
414 if (action == "CLOSE" || action == "LEAVE") {
417 var oldbranch = this.getCurrentBranch().name;
418 this.setActiveTicket(null, master);
419 string [] cmd = { "merge", "--squash", oldbranch };
421 cmd = { "commit", "-a" , "-m", commit_message };
424 this.loadBranches(); // updates lastrev..
426 var notification = new Notify.Notification(
427 "Merged branch %s to %s".printf(oldbranch, master),
433 notification.set_timeout(5);
441 GitMonitor.gitmonitor.pauseError(e.message);
444 // error~?? -- show the error dialog...
447 if (action == "MASTER") {
448 // merge master into ours..
450 string[] cmd = { "merge", master};
452 var notification = new Notify.Notification(
453 "Merged code from %s to %s".printf(master,this.getCurrentBranch().name),
458 notification.set_timeout(5);
463 GitMonitor.gitmonitor.pauseError(e.message);
467 if (action == "EXIT") {
469 var oldbranch = this.getCurrentBranch().name;
470 this.setActiveTicket(null, master);
472 var notification = new Notify.Notification(
473 "Left branch %s".printf(oldbranch),
478 notification.set_timeout(5);
483 GitMonitor.gitmonitor.pauseError(e.message);
487 // error~?? -- show the error dialog...
493 public void loadActiveTicket()
495 this.activeTicket = null;
496 var ticket_id = this.get_config("ticket");
498 if (ticket_id.length < 1) {
501 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
508 public bool setActiveTicket(RooTicket? ticket, string branchname)
510 this.set_config("ticket", "");
511 if (!this.createBranchNamed(branchname)) {
514 this.set_config("ticket", ticket == null ? "": ticket.id);
515 this.activeTicket = ticket;
519 public bool createBranchNamed(string branchname)
523 if (this.branches.has_key(branchname)) {
524 this.switchToExistingBranchNamed(branchname);
527 this.createNewBranchNamed(branchname);
530 var notification = new Notify.Notification(
531 "Changed to branch %s".printf(branchname),
537 notification.set_timeout(5);
541 this.loadBranches(); // update branch list...
542 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
545 bool switchToExistingBranchNamed(string branchname)
547 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
549 // this is where it get's tricky...
552 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
553 files = this.git(cmd);
554 stash = files.length> 1 ;
558 if (stash) { this.git(cmd); }
562 cmd = { "checkout", branchname };
565 GitMonitor.gitmonitor.pauseError(e.message);
569 if (branchname != master) {
570 string[] cmd = { "merge", master };
577 string[] cmd = { "checkout", master };
579 GitMonitor.gitmonitor.pauseError(
580 "Use\n\na) git checkout %s\nb) git mergetool\nc) git commit\nd) git push\n d) stash pop \ne) start gitlive again\n".printf(
588 string[] cmd = { "stash", "pop" };
591 var fl = files.split("\n");
592 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
593 foreach(var f in fl) {
594 if (f.length < 1) continue;
603 GitMonitor.gitmonitor.pauseError(ee.message);
613 bool createNewBranchNamed(string branchname)
617 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
618 var files = this.git(cmd);
619 stash = files.length> 1 ;
621 cmd = { "checkout", "-b" , branchname };
624 cmd = { "push", "-u" , "origin" ,"HEAD" };
628 var fl = files.split("\n");
629 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
630 foreach(var f in fl) {
631 if (f.length < 1) continue;
640 GitMonitor.gitmonitor.pauseError(ee.message);
647 public static string previewMerges(string ticket_id)
650 foreach(var repo in GitRepo.singleton().cache.values) {
651 if (repo.activeTicket == null || repo.activeTicket.id != ticket_id) {
654 ret += repo.previewMerge() + "\n\n";
663 public string previewMerge()
666 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
667 var lines = this.git({"log", master + "...", "--pretty=format:%H %P" }).split("\n");;
668 var head = this.git({"log", "-1", "--pretty=format:%H %P" });
669 var start = head.split(" ")[0];
671 for (var i = 0; i < lines.length; i++) {
672 var cols = lines[i].split(" ");
673 if (cols.length > 2) {
679 var last = lines.length > 0 ? lines[lines.length-1] : "";
680 end = last.split(" ")[1];
683 return this.git({ "diff" , (end+".."+start), "--no-color" });
685 GitMonitor.gitmonitor.pauseError(ee.message);
686 return "Error getting diff";
692 public string diffWorking()
694 var cb = this.getCurrentBranch();
695 GLib.debug("Calling diff working");
696 var diff = new Ggit.Diff.tree_to_workdir(this.repo, cb.getTree(), new Ggit.DiffOptions());
698 diff.print(Ggit.DiffFormatType.PATCH, (delta, hunk, line) => {
699 switch(line.get_origin()) {
700 case Ggit.DiffLineType.ADDITION: ret+="+"; break;
701 case Ggit.DiffLineType.DELETION: ret+="-";break;
702 case Ggit.DiffLineType.CONTEXT: ret+=" ";break;
703 case Ggit.DiffLineType.HUNK_HDR: break;
704 case Ggit.DiffLineType.FILE_HDR: break;
705 default: ret+=" ";break;
707 ret += " " + line.get_text() ;
710 //GLib.debug("returning %s", ret);
717 * add files to track.
719 * @argument {Array} files the files to add.
721 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
723 // should really find out if these are untracked files each..
724 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
725 // not sure if that is how git works.. but just be certian.
727 for (var i = 0; i < files.size;i++) {
728 var f = files.get(i).vname;
730 string[] cmd = { "add", f };
733 ret += e.message + "\n";
740 public bool is_ignore(string fname) throws Error, SpawnError
742 if (fname == ".gitignore") {
743 this.ignore_files.clear();
746 if (this.ignore_files.has_key(fname)) {
747 return this.ignore_files.get(fname);
751 var ret = this.git( { "check-ignore" , fname } );
752 this.ignore_files.set(fname, ret.length > 0);
753 return ret.length > 0;
754 } catch (SpawnError e) {
755 this.ignore_files.set(fname, false);
764 * remove files to track.
766 * @argument {Array} files the files to add.
768 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
770 // this may fail if files do not exist..
771 // should really find out if these are untracked files each..
772 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
773 // not sure if that is how git works.. but just be certian.
776 for (var i = 0; i < files.size;i++) {
777 var f = files.get(i).vname;
779 string[] cmd = { "rm", "-f" , f };
782 ret += e.message + "\n";
795 * @argument {Object} cfg commit configuration
797 * @property {String} name (optional)
798 * @property {String} email (optional)
799 * @property {String} changed (date) (optional)
800 * @property {String} reason (optional)
801 * @property {Array} files - the files that have changed.
805 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
812 if (typeof(cfg.name) != 'undefined') {
814 'author' : cfg.name + ' <' + cfg.email + '>'
817 "GIT_COMMITTER_NAME" + cfg.name,
818 "GIT_COMMITTER_EMAIL" + cfg.email
822 if (typeof(cfg.changed) != 'undefined') {
823 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
827 string[] args = { "commit", "-m" };
828 args += (message.length > 0 ? message : "Changed" );
829 for (var i = 0; i< files.size ; i++ ) {
830 args += files.get(i).vname; // full path?
833 return this.git(args);
838 * Fetch and merge remote repo changes into current branch..
840 * At present we just need this to update the current working branch..
841 * -- maybe later it will have a few options and do more stuff..
844 public string pull () throws Error, SpawnError
846 // should probably hand error conditions better...
847 string[] cmd = { "pull" , "--no-edit" };
848 return this.git( cmd );
853 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
854 public void pull_async(GitAsyncCallback cb)
857 string[] cmd = { "pull" , "--no-edit" };
858 this.git_async( cmd , cb);
865 * Send local changes to remote repo(s)
867 * At present we just need this to push the current branch.
868 * -- maybe later it will have a few options and do more stuff..
871 public string push () throws Error, SpawnError
874 return this.git({ "push" });
882 * The meaty part.. run spawn.. with git..
887 public string git(string[] args_in ) throws Error, SpawnError
889 // convert arguments.
891 string[] args = { "git" };
892 //args += "--git-dir";
893 //args += this.gitdir;
894 args += "--no-pager";
897 //if (this.gitdir != this.repopath) {
898 // args += "--work-tree";
899 // args += this.repopath;
901 for (var i = 0; i < args_in.length;i++) {
905 //this.lastCmd = args.join(" ");
907 GLib.debug( "CWD=%s", this.git_working_dir );
908 GLib.debug( "cmd: %s", string.joinv (" ", args));
912 string home = "HOME=" + Environment.get_home_dir() ;
914 // do not need to set gitpath..
915 //if (File.exists(this.repo + '/.git/config')) {
916 //env.push("GITPATH=" + this.repo );
919 var cfg = new SpawnConfig(this.git_working_dir , args , env);
922 // may throw error...
923 var sp = new Spawn(cfg);
925 //GLib.debug( "GOT result: %d" , sp.result);
927 // diff output is a bit big..
928 if (args_in[0] != "diff") {
929 GLib.debug( "GOT: %s" , sp.output);
931 // parse output for some commands ?
935 unowned GitAsyncCallback git_async_on_callback;
936 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
938 // convert arguments.
939 this.git_async_on_callback = cb;
940 string[] args = { "git" };
941 //args += "--git-dir";
942 //args += this.gitdir;
943 args += "--no-pager";
946 //if (this.gitdir != this.repopath) {
947 // args += "--work-tree";
948 // args += this.repopath;
950 for (var i = 0; i < args_in.length;i++) {
954 //this.lastCmd = args.join(" ");
956 GLib.debug( "CWD=%s", this.git_working_dir );
957 //print( "cmd: %s\n", string.joinv (" ", args));
961 string home = "HOME=" + Environment.get_home_dir() ;
963 // do not need to set gitpath..
964 //if (File.exists(this.repo + '/.git/config')) {
965 //env.push("GITPATH=" + this.repo );
969 var cfg = new SpawnConfig(this.git_working_dir , args , env);
973 // may throw error...
974 var sp = new Spawn(cfg);
977 sp.run(this.git_async_on_complete);
981 void git_async_on_complete(int err, string output)
983 GLib.debug("GOT %d : %s", err, output);
984 this.git_async_on_callback(this, err, output);
992 public async void doUpdate()
994 SourceFunc callback = this.doUpdate.callback;
996 ThreadFunc<bool> run = () => {
999 // update the branches..
1000 this.loadBranches();
1002 //GLib.debug("connecting '%s'", r.get_url());
1004 foreach(var br in this.branches.values) {
1005 if (br.remote == "" || br.remoterev == br.lastrev) {
1008 far += ("+refs/heads/" + br.name + ":refs/remotes/" + br.remote);
1010 if (far.length > 0) {
1011 GLib.debug("PUlling %s", this.name);
1012 var r = this.repo.lookup_remote("origin");
1013 r.connect(Ggit.Direction.FETCH, new GitCallbacks(this), null, null);
1014 var options = new Ggit.FetchOptions();
1015 options.set_remote_callbacks( new GitCallbacks(this));
1016 r.download(far, options);
1022 Idle.add((owned) callback);
1026 new Thread<bool>("thread-new-gitpull-" + this.name, run);
1033 public static void updateAllAsync(string after)
1037 var doing = new Gee.HashMap<string,bool>();;
1039 var tr = GitRepo.singleton().cache;
1041 var update_all_total = tr.size;
1042 foreach(var repo in tr.values) {
1043 if (!repo.is_managed()) {
1047 doing.set(repo.name, true);
1048 repo.doUpdate.begin((obj, res) => {
1049 repo.doUpdate.end(res);
1050 doing.set(repo.name, false);
1052 foreach(var b in doing.keys) {
1054 GLib.debug("pending: %s", b);
1062 Clones.singleton().show();
1065 GLib.debug("Unkown call after load = %s", update_all_after);
1077 public void update_async(GitAsyncCallback cb)
1079 string[] cmd = { "fetch" , "--all" };
1080 this.git_async( cmd , cb);
1085 static uint update_all_total = 0;
1086 static string update_all_after = "";
1088 public static void updateAll(string after)
1090 update_all_after = after;
1091 var tr = GitRepo.singleton().cache;
1094 update_all_total = tr.size;
1095 foreach(var repo in tr.values) {
1096 if (!repo.is_managed()) {
1100 repo.update_async(updateAllCallback);
1102 GLib.debug("calls total = %d", (int) update_all_total);
1107 public static void updateAllCallback(GitRepo repo, int err, string res)
1109 repo.loadBranches();
1113 GLib.debug("calls remaining = %d", (int)update_all_total);
1114 if (update_all_total > 0 ) {
1118 GLib.debug("call after load = %s", update_all_after);
1120 switch (update_all_after) {
1122 Clones.singleton().show();
1125 GLib.debug("Unkown call after load = %s", update_all_after);
1131 public void loadRemoteHeads(bool force = false)
1134 if (!force && this.remote_heads != null) {
1137 var r = this.repo.lookup_remote("origin");
1138 var cb = new GitCallbacks(this);
1139 r.connect(Ggit.Direction.FETCH, cb, null, null);
1140 this.remote_heads = r.list();