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;
28 public GitBranch currentBranch;
29 public Gee.HashMap<string,GitBranch> branches; // accessed in GitBranch..
30 public RooTicket? activeTicket;
31 public Gee.HashMap<string,GitRepo> cache;
32 public Gee.HashMap<string,string> config_cache;
36 public static GitRepo singleton()
38 if (_GitRepo == null) {
39 _GitRepo = new GitRepo.single();
40 _GitRepo.cache = new Gee.HashMap<string,GitRepo>();
46 * index of.. matching gitpath..
48 public static int indexOf( Array<GitRepo> repos, string gitpath) {
49 // make a fake object to compare against..
50 var test_repo = GitRepo.get(gitpath);
52 for(var i =0; i < repos.length; i++) {
53 if (repos.index(i).gitdir == test_repo.gitdir) {
65 public static Array<GitRepo> list()
68 //if (GitRepo.list_cache != null) {
69 // unowned Array<GitRepo> ret = GitRepo.list_cache;
72 var cache = GitRepo.singleton().cache;
73 var list_cache = new Array<GitRepo>();
75 var dir = Environment.get_home_dir() + "/gitlive";
77 var f = File.new_for_path(dir);
78 FileEnumerator file_enum;
80 file_enum = f.enumerate_children(
81 FileAttribute.STANDARD_DISPLAY_NAME + ","+
82 FileAttribute.STANDARD_TYPE,
83 FileQueryInfoFlags.NONE,
96 next_file = file_enum.next_file(null);
97 if (next_file == null) {
102 GLib.debug("Error: %s",e.message);
106 //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
108 if (next_file.get_file_type() != FileType.DIRECTORY) {
113 if (next_file.get_file_type() == FileType.SYMBOLIC_LINK) {
118 if (next_file.get_display_name()[0] == '.') {
122 var sp = dir+"/"+next_file.get_display_name();
124 var gitdir = dir + "/" + next_file.get_display_name() + "/.git";
126 if (!FileUtils.test(gitdir, FileTest.IS_DIR)) {
130 var rep = GitRepo.get( sp );
131 list_cache.append_val(rep);
139 public static GitRepo get(string path)
141 var cache = GitRepo.singleton().cache;
142 if (cache.has_key(path)) {
143 return cache.get(path);
145 return new GitRepo(path);
148 private GitRepo.single() {
149 // used to create the signleton
154 * @param {Object} cfg - Configuration
155 * (basically repopath is currently only critical one.)
159 private GitRepo(string path)
162 this.name = File.new_for_path(path).get_basename();
163 this.ignore_files = new Gee.HashMap<string,bool>();
165 this.git_working_dir = path;
166 this.gitdir = path + "/.git";
167 if (!FileUtils.test(this.gitdir , FileTest.IS_DIR)) {
168 this.gitdir = path; // naked...
170 this.cmds = new Gee.ArrayList<GitMonitorQueue> ();
172 var cache = GitRepo.singleton().cache;
173 //Repo.superclass.constructor.call(this,cfg);
174 if ( !cache.has_key(path) ) {
175 cache.set( path, this);
178 var r = this.git({ "remote" , "get-url" , "--push" , "origin"});
179 var uri = new Soup.URI(r);
180 this.host = uri.get_host();
184 this.loadActiveTicket();
188 public bool is_master_branch()
190 // special branches that do not allow autopushing now...
191 return this.currentBranch.name == "master" || this.currentBranch.name == "roojs";
194 public void init_config()
196 this.config_cache = new Gee.HashMap<string,string>();
198 if (this.get_config("managed") == "") {
199 this.set_config("managed", this.host == "git.roojs.com" ? "1" : "0");
201 if (this.get_config("autocommit") == "") {
202 this.set_config("autocommit", this.host == "git.roojs.com" ? "1" : "0");
204 if (this.get_config("autopush") == "") {
205 this.set_config("autopush", this.host == "git.roojs.com" ? "1" : "0");
212 public string get_config(string key) {
214 if (this.config_cache.has_key(key)) {
215 //GLib.debug("get_config %s = '%s'", key, this.config_cache.get(key));
216 return this.config_cache.get(key);
219 var ret = this.git({ "config" , "gitlive." + key }).strip();
220 this.config_cache.set(key, ret);
221 //GLib.debug("get_config %s = '%s'", key, ret);
224 this.config_cache.set(key, "");
225 //GLib.debug("get_config (fail) %s = '%s'", key, "");
226 return ""; // happens when there is nothing set...
230 public void set_config(string key, string value) {
231 this.git({ "config" , "gitlive." + key, value });
232 this.config_cache.set(key,value);
235 public bool is_managed()
237 return this.get_config("managed") == "1";
241 public bool is_autocommit ()
243 return this.get_config("autocommit") == "1";
246 public void set_autocommit(bool val)
248 this.set_config("autocommit", val ? "1" : "0");
252 public bool is_auto_branch ()
254 if (this.name == "gitlog") {
258 if (this.is_managed()) {
266 public void set_auto_branch(bool val)
268 if (this.name == "gitlog") {
271 this.set_config("managed", val ? "1" : "0");
274 public bool is_autopush ()
276 return this.get_config("autopush") == "1";
278 public void set_autopush(bool val)
280 this.set_config("autopush", val ? "1" : "0");
284 public void loadStatus()
286 var r = this.git({ "status" , "--porcelain" });
288 this.has_local_changes = r.length > 0;
290 var rs = this.git({ "status" , "-sb" });
292 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
295 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
299 public void loadBranches()
302 GitBranch.loadBranches(this);
306 public bool hasBranchCalled(string name)
308 foreach( var br in this.branches.values) {
309 if (br.name == name) {
317 public string branchesToString()
320 foreach( var br in this.branches.values) {
324 var col = /hours/.match(br.age) ? "#ff851b" : "#ffdc00"; // orange or yellow
325 ret += ret.length > 0 ? "\n" : "";
326 ret += br.name + " <span background=\"" + col + "\">" + br.age + "</span>";
332 public static void doMerges(string action, string ticket_id, string commit_message)
334 GitMonitor.gitmonitor.stop();
338 foreach(var repo in GitRepo.singleton().cache.values) {
339 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
340 var res = repo.doMerge(action,ticket_id, commit_message);
345 commitrevs += commitrevs.length > 0 ? " " : "";
346 commitrevs += repo.currentBranch.lastrev;
349 if (sucess && action == "CLOSE") {
350 RooTicket.singleton().getById(ticket_id).close(commitrevs);
352 GitMonitor.gitmonitor.start();
356 public bool doMerge(string action, string ticket_id, string commit_message)
358 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
359 // also need to decide which branch we will merge into?
360 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
363 if (action == "CLOSE" || action == "LEAVE") {
366 var oldbranch = this.currentBranch.name;
367 this.setActiveTicket(null, master);
368 string [] cmd = { "merge", "--squash", oldbranch };
370 cmd = { "commit", "-a" , "-m", commit_message };
373 this.loadBranches(); // updates lastrev..
375 var notification = new Notify.Notification(
376 "Merged branch %s to %s".printf(oldbranch, master),
382 notification.set_timeout(5);
390 GitMonitor.gitmonitor.pauseError(e.message);
393 // error~?? -- show the error dialog...
396 if (action == "MASTER") {
397 // merge master into ours..
399 string[] cmd = { "merge", master};
401 var notification = new Notify.Notification(
402 "Merged code from %s to %s".printf(master,this.currentBranch.name),
407 notification.set_timeout(5);
412 GitMonitor.gitmonitor.pauseError(e.message);
416 if (action == "EXIT") {
418 var oldbranch = this.currentBranch.name;
419 this.setActiveTicket(null, master);
421 var notification = new Notify.Notification(
422 "Left branch %s".printf(oldbranch),
427 notification.set_timeout(5);
432 GitMonitor.gitmonitor.pauseError(e.message);
436 // error~?? -- show the error dialog...
442 public void loadActiveTicket()
444 this.activeTicket = null;
445 var ticket_id = this.get_config("ticket");
447 if (ticket_id.length < 1) {
450 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
457 public bool setActiveTicket(RooTicket? ticket, string branchname)
459 this.set_config("ticket", "");
460 if (!this.createBranchNamed(branchname)) {
463 this.set_config("ticket", ticket == null ? "": ticket.id);
464 this.activeTicket = ticket;
468 public bool createBranchNamed(string branchname)
472 if (this.branches.has_key(branchname)) {
473 this.switchToExistingBranchNamed(branchname);
476 this.createNewBranchNamed(branchname);
479 var notification = new Notify.Notification(
480 "Changed to branch %s".printf(branchname),
486 notification.set_timeout(5);
490 this.loadBranches(); // update branch list...
491 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
494 bool switchToExistingBranchNamed(string branchname)
496 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
498 // this is where it get's tricky...
501 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
502 files = this.git(cmd);
503 stash = files.length> 1 ;
507 if (stash) { this.git(cmd); }
511 cmd = { "checkout", branchname };
514 GitMonitor.gitmonitor.pauseError(e.message);
518 if (branchname != master) {
519 string[] cmd = { "merge", master };
526 string[] cmd = { "checkout", master };
528 GitMonitor.gitmonitor.pauseError(
529 "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(
537 string[] cmd = { "stash", "pop" };
540 var fl = files.split("\n");
541 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
542 foreach(var f in fl) {
543 if (f.length < 1) continue;
552 GitMonitor.gitmonitor.pauseError(ee.message);
562 bool createNewBranchNamed(string branchname)
566 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
567 var files = this.git(cmd);
568 stash = files.length> 1 ;
570 cmd = { "checkout", "-b" , branchname };
573 cmd = { "push", "-u" , "origin" ,"HEAD" };
577 var fl = files.split("\n");
578 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
579 foreach(var f in fl) {
580 if (f.length < 1) continue;
589 GitMonitor.gitmonitor.pauseError(ee.message);
596 public static string previewMerges(string ticket_id)
599 foreach(var repo in GitRepo.singleton().cache.values) {
600 if (repo.activeTicket == null || repo.activeTicket.id != ticket_id) {
603 ret += repo.previewMerge() + "\n\n";
612 public string previewMerge()
615 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
616 var lines = this.git({"log", master + "...", "--pretty=format:%H %P" }).split("\n");;
617 var head = this.git({"log", "-1", "--pretty=format:%H %P" });
618 var start = head.split(" ")[0];
620 for (var i = 0; i < lines.length; i++) {
621 var cols = lines[i].split(" ");
622 if (cols.length > 2) {
628 var last = lines[lines.length-1];
629 end = last.split(" ")[1];
632 return this.git({ "diff" , (end+".."+start), "--no-color" });
634 GitMonitor.gitmonitor.pauseError(ee.message);
635 return "Error getting diff";
645 * add files to track.
647 * @argument {Array} files the files to add.
649 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
651 // should really find out if these are untracked files each..
652 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
653 // not sure if that is how git works.. but just be certian.
655 for (var i = 0; i < files.size;i++) {
656 var f = files.get(i).vname;
658 string[] cmd = { "add", f };
661 ret += e.message + "\n";
668 public bool is_ignore(string fname) throws Error, SpawnError
670 if (fname == ".gitignore") {
671 this.ignore_files.clear();
674 if (this.ignore_files.has_key(fname)) {
675 return this.ignore_files.get(fname);
679 var ret = this.git( { "check-ignore" , fname } );
680 this.ignore_files.set(fname, ret.length > 0);
681 return ret.length > 0;
682 } catch (SpawnError e) {
683 this.ignore_files.set(fname, false);
692 * remove files to track.
694 * @argument {Array} files the files to add.
696 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
698 // this may fail if files do not exist..
699 // should really find out if these are untracked files each..
700 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
701 // 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 = { "rm", "-f" , f };
710 ret += e.message + "\n";
723 * @argument {Object} cfg commit configuration
725 * @property {String} name (optional)
726 * @property {String} email (optional)
727 * @property {String} changed (date) (optional)
728 * @property {String} reason (optional)
729 * @property {Array} files - the files that have changed.
733 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
740 if (typeof(cfg.name) != 'undefined') {
742 'author' : cfg.name + ' <' + cfg.email + '>'
745 "GIT_COMMITTER_NAME" + cfg.name,
746 "GIT_COMMITTER_EMAIL" + cfg.email
750 if (typeof(cfg.changed) != 'undefined') {
751 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
755 string[] args = { "commit", "-m" };
756 args += (message.length > 0 ? message : "Changed" );
757 for (var i = 0; i< files.size ; i++ ) {
758 args += files.get(i).vname; // full path?
761 return this.git(args);
766 * Fetch and merge remote repo changes into current branch..
768 * At present we just need this to update the current working branch..
769 * -- maybe later it will have a few options and do more stuff..
772 public string pull () throws Error, SpawnError
774 // should probably hand error conditions better...
775 string[] cmd = { "pull" , "--no-edit" };
776 return this.git( cmd );
781 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
782 public void pull_async(GitAsyncCallback cb)
785 string[] cmd = { "pull" , "--no-edit" };
786 this.git_async( cmd , cb);
793 * Send local changes to remote repo(s)
795 * At present we just need this to push the current branch.
796 * -- maybe later it will have a few options and do more stuff..
799 public string push () throws Error, SpawnError
802 return this.git({ "push" });
810 * The meaty part.. run spawn.. with git..
815 public string git(string[] args_in ) throws Error, SpawnError
817 // convert arguments.
819 string[] args = { "git" };
820 //args += "--git-dir";
821 //args += this.gitdir;
822 args += "--no-pager";
825 //if (this.gitdir != this.repopath) {
826 // args += "--work-tree";
827 // args += this.repopath;
829 for (var i = 0; i < args_in.length;i++) {
833 //this.lastCmd = args.join(" ");
835 GLib.debug( "CWD=%s", this.git_working_dir );
836 GLib.debug( "cmd: %s", string.joinv (" ", args));
840 string home = "HOME=" + Environment.get_home_dir() ;
842 // do not need to set gitpath..
843 //if (File.exists(this.repo + '/.git/config')) {
844 //env.push("GITPATH=" + this.repo );
847 var cfg = new SpawnConfig(this.git_working_dir , args , env);
850 // may throw error...
851 var sp = new Spawn(cfg);
853 //GLib.debug( "GOT result: %d" , sp.result);
855 // diff output is a bit big..
856 if (args_in[0] != "diff") {
857 GLib.debug( "GOT: %s" , sp.output);
859 // parse output for some commands ?
863 unowned GitAsyncCallback git_async_on_callback;
864 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
866 // convert arguments.
867 this.git_async_on_callback = cb;
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 //print( "cmd: %s\n", 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 );
897 var cfg = new SpawnConfig(this.git_working_dir , args , env);
901 // may throw error...
902 var sp = new Spawn(cfg);
905 sp.run(this.git_async_on_complete);
909 void git_async_on_complete(int err, string output)
911 GLib.debug("GOT %d : %s", err, output);
912 this.git_async_on_callback(this, err, output);
923 public void update_async(GitAsyncCallback cb)
925 string[] cmd = { "fetch" , "--all" };
926 this.git_async( cmd , cb);
931 static uint update_all_total = 0;
932 static string update_all_after = "";
934 public static void updateAll(string after)
936 update_all_after = after;
937 var tr = GitRepo.singleton().cache;
940 update_all_total = tr.size;
941 foreach(var repo in tr.values) {
942 if (!repo.is_managed()) {
946 repo.update_async(updateAllCallback);
948 GLib.debug("calls total = %d", (int) update_all_total);
950 public static void updateAllCallback(GitRepo repo, int err, string res)
956 GLib.debug("calls remaining = %d", (int)update_all_total);
957 if (update_all_total > 0 ) {
961 GLib.debug("call after load = %s", update_all_after);
963 switch (update_all_after) {
965 Clones.singleton().show();
968 GLib.debug("Unkown call after load = %s", update_all_after);