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) {
34 if (this._currentBranch == null) {
35 GLib.error("could not work out current branch?");
37 return this._currentBranch;
41 public Gee.HashMap<string,GitBranch> branches; // accessed in GitBranch..
42 public RooTicket? activeTicket;
43 public Gee.HashMap<string,GitRepo> cache;
44 public Gee.HashMap<string,string> config_cache;
46 public Ggit.Repository repo;
47 public Ggit.RemoteHead[] remote_heads = null;
49 public static GitRepo singleton()
51 if (_GitRepo == null) {
52 _GitRepo = new GitRepo.single();
53 _GitRepo.cache = new Gee.HashMap<string,GitRepo>();
59 * index of.. matching gitpath..
61 public static int indexOf( Array<GitRepo> repos, string gitpath) {
62 // make a fake object to compare against..
63 var test_repo = GitRepo.get_sync(gitpath);
65 for(var i =0; i < repos.length; i++) {
66 if (repos.index(i).gitdir == test_repo.gitdir) {
78 public static Array<GitRepo> list()
81 //if (GitRepo.list_cache != null) {
82 // unowned Array<GitRepo> ret = GitRepo.list_cache;
85 var cache = GitRepo.singleton().cache;
86 var list_cache = new Array<GitRepo>();
88 var dir = Environment.get_home_dir() + "/gitlive";
90 var f = File.new_for_path(dir);
91 FileEnumerator file_enum;
93 file_enum = f.enumerate_children(
94 FileAttribute.STANDARD_DISPLAY_NAME + ","+
95 FileAttribute.STANDARD_TYPE,
96 FileQueryInfoFlags.NONE,
109 next_file = file_enum.next_file(null);
110 if (next_file == null) {
115 GLib.debug("Error: %s",e.message);
119 //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
121 if (next_file.get_file_type() != FileType.DIRECTORY) {
126 if (next_file.get_file_type() == FileType.SYMBOLIC_LINK) {
131 if (next_file.get_display_name()[0] == '.') {
135 var sp = dir+"/"+next_file.get_display_name();
137 var gitdir = dir + "/" + next_file.get_display_name() + "/.git";
139 if (!FileUtils.test(gitdir, FileTest.IS_DIR)) {
143 var rep = GitRepo.get_sync( sp );
144 list_cache.append_val(rep);
152 public static GitRepo get_sync(string path)
155 var cache = GitRepo.singleton().cache;
156 if (cache.has_key(path)) {
157 ret = cache.get(path);
159 ret = new GitRepo(path);
164 public static async GitRepo? get(string path)
167 SourceFunc callback = GitRepo.get.callback;
169 ThreadFunc<bool> run = () => {
171 var cache = GitRepo.singleton().cache;
172 if (cache.has_key(path)) {
173 ret = cache.get(path);
175 ret = new GitRepo(path);
177 Idle.add((owned) callback);
181 new Thread<bool>("thread-new-gitrepo-" + path, run);
187 private GitRepo.single() {
188 // used to create the signleton
193 * @param {Object} cfg - Configuration
194 * (basically repopath is currently only critical one.)
198 private GitRepo(string path)
201 this.name = File.new_for_path(path).get_basename();
202 this.ignore_files = new Gee.HashMap<string,bool>();
204 this.git_working_dir = path;
205 this.gitdir = path + "/.git";
206 if (!FileUtils.test(this.gitdir , FileTest.IS_DIR)) {
207 this.gitdir = path; // naked...
209 this.cmds = new Gee.ArrayList<GitMonitorQueue> ();
211 var cache = GitRepo.singleton().cache;
212 //Repo.superclass.constructor.call(this,cfg);
213 if ( !cache.has_key(path) ) {
214 cache.set( path, this);
217 this.repo = Ggit.Repository.open(GLib.File.new_for_path(path));
219 var r = this.repo.lookup_remote("origin");
222 //var r = this.git({ "remote" , "get-url" , "--push" , "origin"});
223 var uri = new Soup.URI(r.get_url());
224 this.host = uri.get_host();
228 this.loadActiveTicket();
232 public bool is_master_branch()
234 // special branches that do not allow autopushing now...
235 return this.getCurrentBranch().name == "master" || this.getCurrentBranch().name == "roojs";
238 public void init_config()
240 this.config_cache = new Gee.HashMap<string,string>();
242 if (this.get_config("managed") == "") {
243 this.set_config("managed", this.host == "git.roojs.com" ? "1" : "0");
245 if (this.get_config("autocommit") == "") {
246 this.set_config("autocommit", this.host == "git.roojs.com" ? "1" : "0");
248 if (this.get_config("autopush") == "") {
249 this.set_config("autopush", this.host == "git.roojs.com" ? "1" : "0");
256 public string get_config(string key)
259 if (this.config_cache.has_key(key)) {
260 //GLib.debug("get_config %s = '%s'", key, this.config_cache.get(key));
261 return this.config_cache.get(key);
264 var cfg = this.repo.get_config().snapshot();
265 var ret = cfg.get_string("gitlive." + key).strip();
268 this.repo.get_config().set_string("gitlive." + key, "");
269 //this.config_cache.set(key, "");
270 //GLib.debug("get_config (fail) %s = '%s'", key, "");
271 return ""; // happens when there is nothing set...
275 public void set_config(string key, string value)
277 this.repo.get_config().set_string("gitlive." + key, value);
278 //this.git({ "config" , "gitlive." + key, value });
279 //this.config_cache.set(key,value);
282 public bool is_managed()
284 return this.get_config("managed") == "1";
288 public bool is_autocommit ()
290 return this.get_config("autocommit") == "1";
293 public void set_autocommit(bool val)
295 this.set_config("autocommit", val ? "1" : "0");
299 public bool is_auto_branch ()
301 if (this.name == "gitlog") {
305 if (this.is_managed()) {
313 public void set_auto_branch(bool val)
315 if (this.name == "gitlog") {
318 this.set_config("managed", val ? "1" : "0");
321 public bool is_autopush ()
323 return this.get_config("autopush") == "1";
325 public void set_autopush(bool val)
327 this.set_config("autopush", val ? "1" : "0");
331 public void loadStatus()
334 var r = this.git({ "status" , "--porcelain" });
336 this.has_local_changes = r.length > 0;
338 var rs = this.git({ "status" , "-sb" });
341 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
344 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
348 public void loadBranches()
351 GitBranch.loadBranches(this);
355 public bool hasBranchCalled(string name)
357 foreach( var br in this.branches.values) {
358 if (br.name == name) {
366 public string branchesToString()
369 foreach( var br in this.branches.values) {
373 var col = /hours/.match(br.age) ? "#ff851b" : "#ffdc00"; // orange or yellow
374 ret += ret.length > 0 ? "\n" : "";
375 ret += br.name + " <span background=\"" + col + "\">" + br.age + "</span>";
381 public static void doMerges(string action, string ticket_id, string commit_message)
383 GitMonitor.gitmonitor.stop();
387 foreach(var repo in GitRepo.singleton().cache.values) {
388 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
389 var res = repo.doMerge(action,ticket_id, commit_message);
394 commitrevs += commitrevs.length > 0 ? " " : "";
395 commitrevs += repo.getCurrentBranch().lastrev;
398 if (sucess && action == "CLOSE") {
399 RooTicket.singleton().getById(ticket_id).close(commitrevs);
401 GitMonitor.gitmonitor.start();
405 public bool doMerge(string action, string ticket_id, string commit_message)
407 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
408 // also need to decide which branch we will merge into?
409 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
412 if (action == "CLOSE" || action == "LEAVE") {
415 var oldbranch = this.getCurrentBranch().name;
416 this.setActiveTicket(null, master);
417 string [] cmd = { "merge", "--squash", oldbranch };
419 cmd = { "commit", "-a" , "-m", commit_message };
422 this.loadBranches(); // updates lastrev..
424 var notification = new Notify.Notification(
425 "Merged branch %s to %s".printf(oldbranch, master),
431 notification.set_timeout(5);
439 GitMonitor.gitmonitor.pauseError(e.message);
442 // error~?? -- show the error dialog...
445 if (action == "MASTER") {
446 // merge master into ours..
448 string[] cmd = { "merge", master};
450 var notification = new Notify.Notification(
451 "Merged code from %s to %s".printf(master,this.getCurrentBranch().name),
456 notification.set_timeout(5);
461 GitMonitor.gitmonitor.pauseError(e.message);
465 if (action == "EXIT") {
467 var oldbranch = this.getCurrentBranch().name;
468 this.setActiveTicket(null, master);
470 var notification = new Notify.Notification(
471 "Left branch %s".printf(oldbranch),
476 notification.set_timeout(5);
481 GitMonitor.gitmonitor.pauseError(e.message);
485 // error~?? -- show the error dialog...
491 public void loadActiveTicket()
493 this.activeTicket = null;
494 var ticket_id = this.get_config("ticket");
496 if (ticket_id.length < 1) {
499 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
506 public bool setActiveTicket(RooTicket? ticket, string branchname)
508 this.set_config("ticket", "");
509 if (!this.createBranchNamed(branchname)) {
512 this.set_config("ticket", ticket == null ? "": ticket.id);
513 this.activeTicket = ticket;
517 public bool createBranchNamed(string branchname)
521 if (this.branches.has_key(branchname)) {
522 this.switchToExistingBranchNamed(branchname);
525 this.createNewBranchNamed(branchname);
528 var notification = new Notify.Notification(
529 "Changed to branch %s".printf(branchname),
535 notification.set_timeout(5);
539 this.loadBranches(); // update branch list...
540 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
543 bool switchToExistingBranchNamed(string branchname)
545 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
547 // this is where it get's tricky...
550 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
551 files = this.git(cmd);
552 stash = files.length> 1 ;
556 if (stash) { this.git(cmd); }
560 cmd = { "checkout", branchname };
563 GitMonitor.gitmonitor.pauseError(e.message);
567 if (branchname != master) {
568 string[] cmd = { "merge", master };
575 string[] cmd = { "checkout", master };
577 GitMonitor.gitmonitor.pauseError(
578 "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(
586 string[] cmd = { "stash", "pop" };
589 var fl = files.split("\n");
590 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
591 foreach(var f in fl) {
592 if (f.length < 1) continue;
601 GitMonitor.gitmonitor.pauseError(ee.message);
611 bool createNewBranchNamed(string branchname)
615 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
616 var files = this.git(cmd);
617 stash = files.length> 1 ;
619 cmd = { "checkout", "-b" , branchname };
622 cmd = { "push", "-u" , "origin" ,"HEAD" };
626 var fl = files.split("\n");
627 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
628 foreach(var f in fl) {
629 if (f.length < 1) continue;
638 GitMonitor.gitmonitor.pauseError(ee.message);
645 public static string previewMerges(string ticket_id)
648 foreach(var repo in GitRepo.singleton().cache.values) {
649 if (repo.activeTicket == null || repo.activeTicket.id != ticket_id) {
652 ret += repo.previewMerge() + "\n\n";
661 public string previewMerge()
664 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
665 var lines = this.git({"log", master + "...", "--pretty=format:%H %P" }).split("\n");;
666 var head = this.git({"log", "-1", "--pretty=format:%H %P" });
667 var start = head.split(" ")[0];
669 for (var i = 0; i < lines.length; i++) {
670 var cols = lines[i].split(" ");
671 if (cols.length > 2) {
677 var last = lines[lines.length-1];
678 end = last.split(" ")[1];
681 return this.git({ "diff" , (end+".."+start), "--no-color" });
683 GitMonitor.gitmonitor.pauseError(ee.message);
684 return "Error getting diff";
694 * add files to track.
696 * @argument {Array} files the files to add.
698 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
700 // should really find out if these are untracked files each..
701 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
702 // not sure if that is how git works.. but just be certian.
704 for (var i = 0; i < files.size;i++) {
705 var f = files.get(i).vname;
707 string[] cmd = { "add", f };
710 ret += e.message + "\n";
717 public bool is_ignore(string fname) throws Error, SpawnError
719 if (fname == ".gitignore") {
720 this.ignore_files.clear();
723 if (this.ignore_files.has_key(fname)) {
724 return this.ignore_files.get(fname);
728 var ret = this.git( { "check-ignore" , fname } );
729 this.ignore_files.set(fname, ret.length > 0);
730 return ret.length > 0;
731 } catch (SpawnError e) {
732 this.ignore_files.set(fname, false);
741 * remove files to track.
743 * @argument {Array} files the files to add.
745 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
747 // this may fail if files do not exist..
748 // should really find out if these are untracked files each..
749 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
750 // not sure if that is how git works.. but just be certian.
753 for (var i = 0; i < files.size;i++) {
754 var f = files.get(i).vname;
756 string[] cmd = { "rm", "-f" , f };
759 ret += e.message + "\n";
772 * @argument {Object} cfg commit configuration
774 * @property {String} name (optional)
775 * @property {String} email (optional)
776 * @property {String} changed (date) (optional)
777 * @property {String} reason (optional)
778 * @property {Array} files - the files that have changed.
782 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
789 if (typeof(cfg.name) != 'undefined') {
791 'author' : cfg.name + ' <' + cfg.email + '>'
794 "GIT_COMMITTER_NAME" + cfg.name,
795 "GIT_COMMITTER_EMAIL" + cfg.email
799 if (typeof(cfg.changed) != 'undefined') {
800 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
804 string[] args = { "commit", "-m" };
805 args += (message.length > 0 ? message : "Changed" );
806 for (var i = 0; i< files.size ; i++ ) {
807 args += files.get(i).vname; // full path?
810 return this.git(args);
815 * Fetch and merge remote repo changes into current branch..
817 * At present we just need this to update the current working branch..
818 * -- maybe later it will have a few options and do more stuff..
821 public string pull () throws Error, SpawnError
823 // should probably hand error conditions better...
824 string[] cmd = { "pull" , "--no-edit" };
825 return this.git( cmd );
830 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
831 public void pull_async(GitAsyncCallback cb)
834 string[] cmd = { "pull" , "--no-edit" };
835 this.git_async( cmd , cb);
842 * Send local changes to remote repo(s)
844 * At present we just need this to push the current branch.
845 * -- maybe later it will have a few options and do more stuff..
848 public string push () throws Error, SpawnError
851 return this.git({ "push" });
859 * The meaty part.. run spawn.. with git..
864 public string git(string[] args_in ) throws Error, SpawnError
866 // convert arguments.
868 string[] args = { "git" };
869 //args += "--git-dir";
870 //args += this.gitdir;
871 args += "--no-pager";
874 //if (this.gitdir != this.repopath) {
875 // args += "--work-tree";
876 // args += this.repopath;
878 for (var i = 0; i < args_in.length;i++) {
882 //this.lastCmd = args.join(" ");
884 GLib.debug( "CWD=%s", this.git_working_dir );
885 GLib.debug( "cmd: %s", string.joinv (" ", args));
889 string home = "HOME=" + Environment.get_home_dir() ;
891 // do not need to set gitpath..
892 //if (File.exists(this.repo + '/.git/config')) {
893 //env.push("GITPATH=" + this.repo );
896 var cfg = new SpawnConfig(this.git_working_dir , args , env);
899 // may throw error...
900 var sp = new Spawn(cfg);
902 //GLib.debug( "GOT result: %d" , sp.result);
904 // diff output is a bit big..
905 if (args_in[0] != "diff") {
906 GLib.debug( "GOT: %s" , sp.output);
908 // parse output for some commands ?
912 unowned GitAsyncCallback git_async_on_callback;
913 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
915 // convert arguments.
916 this.git_async_on_callback = cb;
917 string[] args = { "git" };
918 //args += "--git-dir";
919 //args += this.gitdir;
920 args += "--no-pager";
923 //if (this.gitdir != this.repopath) {
924 // args += "--work-tree";
925 // args += this.repopath;
927 for (var i = 0; i < args_in.length;i++) {
931 //this.lastCmd = args.join(" ");
933 GLib.debug( "CWD=%s", this.git_working_dir );
934 //print( "cmd: %s\n", string.joinv (" ", args));
938 string home = "HOME=" + Environment.get_home_dir() ;
940 // do not need to set gitpath..
941 //if (File.exists(this.repo + '/.git/config')) {
942 //env.push("GITPATH=" + this.repo );
946 var cfg = new SpawnConfig(this.git_working_dir , args , env);
950 // may throw error...
951 var sp = new Spawn(cfg);
954 sp.run(this.git_async_on_complete);
958 void git_async_on_complete(int err, string output)
960 GLib.debug("GOT %d : %s", err, output);
961 this.git_async_on_callback(this, err, output);
969 public async void doUpdate()
971 SourceFunc callback = this.doUpdate.callback;
973 ThreadFunc<bool> run = () => {
976 // update the branches..
979 //GLib.debug("connecting '%s'", r.get_url());
981 foreach(var br in this.branches.values) {
982 if (br.remote == "" || br.remoterev == br.lastrev) {
985 far += ("+refs/heads/" + br.name + ":refs/remotes/" + br.remote);
987 if (far.length > 0) {
988 GLib.debug("PUlling %s", this.name);
989 var r = this.repo.lookup_remote("origin");
990 r.connect(Ggit.Direction.FETCH, new GitCallbacks(this), null, null);
991 var options = new Ggit.FetchOptions();
992 options.set_remote_callbacks( new GitCallbacks(this));
993 r.download(far, options);
998 Idle.add((owned) callback);
1002 new Thread<bool>("thread-new-gitpull-" + this.name, run);
1009 public static void updateAllAsync(string after)
1013 var doing = new Gee.HashMap<string,bool>();;
1015 var tr = GitRepo.singleton().cache;
1017 var update_all_total = tr.size;
1018 foreach(var repo in tr.values) {
1019 if (!repo.is_managed()) {
1023 doing.set(repo.name, true);
1024 repo.doUpdate.begin((obj, res) => {
1025 repo.doUpdate.end(res);
1026 doing.set(repo.name, false);
1028 foreach(var b in doing.keys) {
1030 GLib.debug("pending: %s", b);
1038 Clones.singleton().show();
1041 GLib.debug("Unkown call after load = %s", update_all_after);
1053 public void update_async(GitAsyncCallback cb)
1055 string[] cmd = { "fetch" , "--all" };
1056 this.git_async( cmd , cb);
1061 static uint update_all_total = 0;
1062 static string update_all_after = "";
1064 public static void updateAll(string after)
1066 update_all_after = after;
1067 var tr = GitRepo.singleton().cache;
1070 update_all_total = tr.size;
1071 foreach(var repo in tr.values) {
1072 if (!repo.is_managed()) {
1076 repo.update_async(updateAllCallback);
1078 GLib.debug("calls total = %d", (int) update_all_total);
1083 public static void updateAllCallback(GitRepo repo, int err, string res)
1085 repo.loadBranches();
1089 GLib.debug("calls remaining = %d", (int)update_all_total);
1090 if (update_all_total > 0 ) {
1094 GLib.debug("call after load = %s", update_all_after);
1096 switch (update_all_after) {
1098 Clones.singleton().show();
1101 GLib.debug("Unkown call after load = %s", update_all_after);
1107 public void loadRemoteHeads(bool force = false)
1110 if (!force && this.remote_heads != null) {
1113 var r = this.repo.lookup_remote("origin");
1114 var cb = new GitCallbacks(this);
1115 r.connect(Ggit.Direction.FETCH, cb, null, null);
1116 this.remote_heads = r.list();