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;
31 public Gee.HashMap<string,GitBranch> branches; // accessed in GitBranch..
32 public RooTicket? activeTicket;
33 public Gee.HashMap<string,GitRepo> cache;
34 public Gee.HashMap<string,string> config_cache;
36 public Ggit.Repository repo;
37 public Ggit.RemoteHead[] remote_heads = null;
39 public static GitRepo singleton()
41 if (_GitRepo == null) {
42 _GitRepo = new GitRepo.single();
43 _GitRepo.cache = new Gee.HashMap<string,GitRepo>();
49 * index of.. matching gitpath..
51 public static int indexOf( Array<GitRepo> repos, string gitpath) {
52 // make a fake object to compare against..
53 var test_repo = GitRepo.get_sync(gitpath);
55 for(var i =0; i < repos.length; i++) {
56 if (repos.index(i).gitdir == test_repo.gitdir) {
68 public static Array<GitRepo> list()
71 //if (GitRepo.list_cache != null) {
72 // unowned Array<GitRepo> ret = GitRepo.list_cache;
75 var cache = GitRepo.singleton().cache;
76 var list_cache = new Array<GitRepo>();
78 var dir = Environment.get_home_dir() + "/gitlive";
80 var f = File.new_for_path(dir);
81 FileEnumerator file_enum;
83 file_enum = f.enumerate_children(
84 FileAttribute.STANDARD_DISPLAY_NAME + ","+
85 FileAttribute.STANDARD_TYPE,
86 FileQueryInfoFlags.NONE,
99 next_file = file_enum.next_file(null);
100 if (next_file == null) {
105 GLib.debug("Error: %s",e.message);
109 //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
111 if (next_file.get_file_type() != FileType.DIRECTORY) {
116 if (next_file.get_file_type() == FileType.SYMBOLIC_LINK) {
121 if (next_file.get_display_name()[0] == '.') {
125 var sp = dir+"/"+next_file.get_display_name();
127 var gitdir = dir + "/" + next_file.get_display_name() + "/.git";
129 if (!FileUtils.test(gitdir, FileTest.IS_DIR)) {
133 var rep = GitRepo.get_sync( sp );
134 list_cache.append_val(rep);
142 public static GitRepo get_sync(string path)
145 var cache = GitRepo.singleton().cache;
146 if (cache.has_key(path)) {
147 ret = cache.get(path);
149 ret = new GitRepo(path);
154 public static async GitRepo? get(string path)
157 SourceFunc callback = GitRepo.get.callback;
159 ThreadFunc<bool> run = () => {
161 var cache = GitRepo.singleton().cache;
162 if (cache.has_key(path)) {
163 ret = cache.get(path);
165 ret = new GitRepo(path);
167 Idle.add((owned) callback);
171 new Thread<bool>("thread-new-gitrepo", run);
177 private GitRepo.single() {
178 // used to create the signleton
183 * @param {Object} cfg - Configuration
184 * (basically repopath is currently only critical one.)
188 private GitRepo(string path)
191 this.name = File.new_for_path(path).get_basename();
192 this.ignore_files = new Gee.HashMap<string,bool>();
194 this.git_working_dir = path;
195 this.gitdir = path + "/.git";
196 if (!FileUtils.test(this.gitdir , FileTest.IS_DIR)) {
197 this.gitdir = path; // naked...
199 this.cmds = new Gee.ArrayList<GitMonitorQueue> ();
201 var cache = GitRepo.singleton().cache;
202 //Repo.superclass.constructor.call(this,cfg);
203 if ( !cache.has_key(path) ) {
204 cache.set( path, this);
207 this.repo = Ggit.Repository.open(GLib.File.new_for_path(path));
209 var r = this.repo.lookup_remote("origin");
212 //var r = this.git({ "remote" , "get-url" , "--push" , "origin"});
213 var uri = new Soup.URI(r.get_url());
214 this.host = uri.get_host();
218 this.loadActiveTicket();
222 public bool is_master_branch()
224 // special branches that do not allow autopushing now...
225 return this.currentBranch.name == "master" || this.currentBranch.name == "roojs";
228 public void init_config()
230 this.config_cache = new Gee.HashMap<string,string>();
232 if (this.get_config("managed") == "") {
233 this.set_config("managed", this.host == "git.roojs.com" ? "1" : "0");
235 if (this.get_config("autocommit") == "") {
236 this.set_config("autocommit", this.host == "git.roojs.com" ? "1" : "0");
238 if (this.get_config("autopush") == "") {
239 this.set_config("autopush", this.host == "git.roojs.com" ? "1" : "0");
246 public string get_config(string key)
249 if (this.config_cache.has_key(key)) {
250 //GLib.debug("get_config %s = '%s'", key, this.config_cache.get(key));
251 return this.config_cache.get(key);
254 var cfg = this.repo.get_config().snapshot();
255 var ret = cfg.get_string("gitlive." + key).strip();
258 this.repo.get_config().set_string("gitlive." + key, "");
259 //this.config_cache.set(key, "");
260 //GLib.debug("get_config (fail) %s = '%s'", key, "");
261 return ""; // happens when there is nothing set...
265 public void set_config(string key, string value)
267 this.repo.get_config().set_string("gitlive." + key, value);
268 //this.git({ "config" , "gitlive." + key, value });
269 //this.config_cache.set(key,value);
272 public bool is_managed()
274 return this.get_config("managed") == "1";
278 public bool is_autocommit ()
280 return this.get_config("autocommit") == "1";
283 public void set_autocommit(bool val)
285 this.set_config("autocommit", val ? "1" : "0");
289 public bool is_auto_branch ()
291 if (this.name == "gitlog") {
295 if (this.is_managed()) {
303 public void set_auto_branch(bool val)
305 if (this.name == "gitlog") {
308 this.set_config("managed", val ? "1" : "0");
311 public bool is_autopush ()
313 return this.get_config("autopush") == "1";
315 public void set_autopush(bool val)
317 this.set_config("autopush", val ? "1" : "0");
321 public void loadStatus()
324 var r = this.git({ "status" , "--porcelain" });
326 this.has_local_changes = r.length > 0;
328 var rs = this.git({ "status" , "-sb" });
331 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
334 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
338 public void loadBranches()
341 GitBranch.loadBranches(this);
345 public bool hasBranchCalled(string name)
347 foreach( var br in this.branches.values) {
348 if (br.name == name) {
356 public string branchesToString()
359 foreach( var br in this.branches.values) {
363 var col = /hours/.match(br.age) ? "#ff851b" : "#ffdc00"; // orange or yellow
364 ret += ret.length > 0 ? "\n" : "";
365 ret += br.name + " <span background=\"" + col + "\">" + br.age + "</span>";
371 public static void doMerges(string action, string ticket_id, string commit_message)
373 GitMonitor.gitmonitor.stop();
377 foreach(var repo in GitRepo.singleton().cache.values) {
378 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
379 var res = repo.doMerge(action,ticket_id, commit_message);
384 commitrevs += commitrevs.length > 0 ? " " : "";
385 commitrevs += repo.currentBranch.lastrev;
388 if (sucess && action == "CLOSE") {
389 RooTicket.singleton().getById(ticket_id).close(commitrevs);
391 GitMonitor.gitmonitor.start();
395 public bool doMerge(string action, string ticket_id, string commit_message)
397 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
398 // also need to decide which branch we will merge into?
399 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
402 if (action == "CLOSE" || action == "LEAVE") {
405 var oldbranch = this.currentBranch.name;
406 this.setActiveTicket(null, master);
407 string [] cmd = { "merge", "--squash", oldbranch };
409 cmd = { "commit", "-a" , "-m", commit_message };
412 this.loadBranches(); // updates lastrev..
414 var notification = new Notify.Notification(
415 "Merged branch %s to %s".printf(oldbranch, master),
421 notification.set_timeout(5);
429 GitMonitor.gitmonitor.pauseError(e.message);
432 // error~?? -- show the error dialog...
435 if (action == "MASTER") {
436 // merge master into ours..
438 string[] cmd = { "merge", master};
440 var notification = new Notify.Notification(
441 "Merged code from %s to %s".printf(master,this.currentBranch.name),
446 notification.set_timeout(5);
451 GitMonitor.gitmonitor.pauseError(e.message);
455 if (action == "EXIT") {
457 var oldbranch = this.currentBranch.name;
458 this.setActiveTicket(null, master);
460 var notification = new Notify.Notification(
461 "Left branch %s".printf(oldbranch),
466 notification.set_timeout(5);
471 GitMonitor.gitmonitor.pauseError(e.message);
475 // error~?? -- show the error dialog...
481 public void loadActiveTicket()
483 this.activeTicket = null;
484 var ticket_id = this.get_config("ticket");
486 if (ticket_id.length < 1) {
489 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
496 public bool setActiveTicket(RooTicket? ticket, string branchname)
498 this.set_config("ticket", "");
499 if (!this.createBranchNamed(branchname)) {
502 this.set_config("ticket", ticket == null ? "": ticket.id);
503 this.activeTicket = ticket;
507 public bool createBranchNamed(string branchname)
511 if (this.branches.has_key(branchname)) {
512 this.switchToExistingBranchNamed(branchname);
515 this.createNewBranchNamed(branchname);
518 var notification = new Notify.Notification(
519 "Changed to branch %s".printf(branchname),
525 notification.set_timeout(5);
529 this.loadBranches(); // update branch list...
530 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
533 bool switchToExistingBranchNamed(string branchname)
535 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
537 // this is where it get's tricky...
540 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
541 files = this.git(cmd);
542 stash = files.length> 1 ;
546 if (stash) { this.git(cmd); }
550 cmd = { "checkout", branchname };
553 GitMonitor.gitmonitor.pauseError(e.message);
557 if (branchname != master) {
558 string[] cmd = { "merge", master };
565 string[] cmd = { "checkout", master };
567 GitMonitor.gitmonitor.pauseError(
568 "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(
576 string[] cmd = { "stash", "pop" };
579 var fl = files.split("\n");
580 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
581 foreach(var f in fl) {
582 if (f.length < 1) continue;
591 GitMonitor.gitmonitor.pauseError(ee.message);
601 bool createNewBranchNamed(string branchname)
605 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
606 var files = this.git(cmd);
607 stash = files.length> 1 ;
609 cmd = { "checkout", "-b" , branchname };
612 cmd = { "push", "-u" , "origin" ,"HEAD" };
616 var fl = files.split("\n");
617 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
618 foreach(var f in fl) {
619 if (f.length < 1) continue;
628 GitMonitor.gitmonitor.pauseError(ee.message);
635 public static string previewMerges(string ticket_id)
638 foreach(var repo in GitRepo.singleton().cache.values) {
639 if (repo.activeTicket == null || repo.activeTicket.id != ticket_id) {
642 ret += repo.previewMerge() + "\n\n";
651 public string previewMerge()
654 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
655 var lines = this.git({"log", master + "...", "--pretty=format:%H %P" }).split("\n");;
656 var head = this.git({"log", "-1", "--pretty=format:%H %P" });
657 var start = head.split(" ")[0];
659 for (var i = 0; i < lines.length; i++) {
660 var cols = lines[i].split(" ");
661 if (cols.length > 2) {
667 var last = lines[lines.length-1];
668 end = last.split(" ")[1];
671 return this.git({ "diff" , (end+".."+start), "--no-color" });
673 GitMonitor.gitmonitor.pauseError(ee.message);
674 return "Error getting diff";
684 * add files to track.
686 * @argument {Array} files the files to add.
688 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
690 // should really find out if these are untracked files each..
691 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
692 // not sure if that is how git works.. but just be certian.
694 for (var i = 0; i < files.size;i++) {
695 var f = files.get(i).vname;
697 string[] cmd = { "add", f };
700 ret += e.message + "\n";
707 public bool is_ignore(string fname) throws Error, SpawnError
709 if (fname == ".gitignore") {
710 this.ignore_files.clear();
713 if (this.ignore_files.has_key(fname)) {
714 return this.ignore_files.get(fname);
718 var ret = this.git( { "check-ignore" , fname } );
719 this.ignore_files.set(fname, ret.length > 0);
720 return ret.length > 0;
721 } catch (SpawnError e) {
722 this.ignore_files.set(fname, false);
731 * remove files to track.
733 * @argument {Array} files the files to add.
735 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
737 // this may fail if files do not exist..
738 // should really find out if these are untracked files each..
739 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
740 // not sure if that is how git works.. but just be certian.
743 for (var i = 0; i < files.size;i++) {
744 var f = files.get(i).vname;
746 string[] cmd = { "rm", "-f" , f };
749 ret += e.message + "\n";
762 * @argument {Object} cfg commit configuration
764 * @property {String} name (optional)
765 * @property {String} email (optional)
766 * @property {String} changed (date) (optional)
767 * @property {String} reason (optional)
768 * @property {Array} files - the files that have changed.
772 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
779 if (typeof(cfg.name) != 'undefined') {
781 'author' : cfg.name + ' <' + cfg.email + '>'
784 "GIT_COMMITTER_NAME" + cfg.name,
785 "GIT_COMMITTER_EMAIL" + cfg.email
789 if (typeof(cfg.changed) != 'undefined') {
790 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
794 string[] args = { "commit", "-m" };
795 args += (message.length > 0 ? message : "Changed" );
796 for (var i = 0; i< files.size ; i++ ) {
797 args += files.get(i).vname; // full path?
800 return this.git(args);
805 * Fetch and merge remote repo changes into current branch..
807 * At present we just need this to update the current working branch..
808 * -- maybe later it will have a few options and do more stuff..
811 public string pull () throws Error, SpawnError
813 // should probably hand error conditions better...
814 string[] cmd = { "pull" , "--no-edit" };
815 return this.git( cmd );
820 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
821 public void pull_async(GitAsyncCallback cb)
824 string[] cmd = { "pull" , "--no-edit" };
825 this.git_async( cmd , cb);
832 * Send local changes to remote repo(s)
834 * At present we just need this to push the current branch.
835 * -- maybe later it will have a few options and do more stuff..
838 public string push () throws Error, SpawnError
841 return this.git({ "push" });
849 * The meaty part.. run spawn.. with git..
854 public string git(string[] args_in ) throws Error, SpawnError
856 // convert arguments.
858 string[] args = { "git" };
859 //args += "--git-dir";
860 //args += this.gitdir;
861 args += "--no-pager";
864 //if (this.gitdir != this.repopath) {
865 // args += "--work-tree";
866 // args += this.repopath;
868 for (var i = 0; i < args_in.length;i++) {
872 //this.lastCmd = args.join(" ");
874 GLib.debug( "CWD=%s", this.git_working_dir );
875 GLib.debug( "cmd: %s", string.joinv (" ", args));
879 string home = "HOME=" + Environment.get_home_dir() ;
881 // do not need to set gitpath..
882 //if (File.exists(this.repo + '/.git/config')) {
883 //env.push("GITPATH=" + this.repo );
886 var cfg = new SpawnConfig(this.git_working_dir , args , env);
889 // may throw error...
890 var sp = new Spawn(cfg);
892 //GLib.debug( "GOT result: %d" , sp.result);
894 // diff output is a bit big..
895 if (args_in[0] != "diff") {
896 GLib.debug( "GOT: %s" , sp.output);
898 // parse output for some commands ?
902 unowned GitAsyncCallback git_async_on_callback;
903 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
905 // convert arguments.
906 this.git_async_on_callback = cb;
907 string[] args = { "git" };
908 //args += "--git-dir";
909 //args += this.gitdir;
910 args += "--no-pager";
913 //if (this.gitdir != this.repopath) {
914 // args += "--work-tree";
915 // args += this.repopath;
917 for (var i = 0; i < args_in.length;i++) {
921 //this.lastCmd = args.join(" ");
923 GLib.debug( "CWD=%s", this.git_working_dir );
924 //print( "cmd: %s\n", string.joinv (" ", args));
928 string home = "HOME=" + Environment.get_home_dir() ;
930 // do not need to set gitpath..
931 //if (File.exists(this.repo + '/.git/config')) {
932 //env.push("GITPATH=" + this.repo );
936 var cfg = new SpawnConfig(this.git_working_dir , args , env);
940 // may throw error...
941 var sp = new Spawn(cfg);
944 sp.run(this.git_async_on_complete);
948 void git_async_on_complete(int err, string output)
950 GLib.debug("GOT %d : %s", err, output);
951 this.git_async_on_callback(this, err, output);
959 public void doUpdate()
961 // update the branches..
967 public static void updateAllAsync(string after)
971 var tr = GitRepo.singleton().cache;
973 var update_all_total = tr.size;
974 foreach(var repo in tr.values) {
975 repo.doUpdate.begin((obj, res) => {
976 GitRepo.updateRepo.end(res);
978 if (update_all_total != done) {
983 Clones.singleton().show();
986 GLib.debug("Unkown call after load = %s", update_all_after);
998 public void update_async(GitAsyncCallback cb)
1000 string[] cmd = { "fetch" , "--all" };
1001 this.git_async( cmd , cb);
1006 static uint update_all_total = 0;
1007 static string update_all_after = "";
1009 public static void updateAll(string after)
1011 update_all_after = after;
1012 var tr = GitRepo.singleton().cache;
1015 update_all_total = tr.size;
1016 foreach(var repo in tr.values) {
1017 if (!repo.is_managed()) {
1021 repo.update_async(updateAllCallback);
1023 GLib.debug("calls total = %d", (int) update_all_total);
1028 public static void updateAllCallback(GitRepo repo, int err, string res)
1030 repo.loadBranches();
1034 GLib.debug("calls remaining = %d", (int)update_all_total);
1035 if (update_all_total > 0 ) {
1039 GLib.debug("call after load = %s", update_all_after);
1041 switch (update_all_after) {
1043 Clones.singleton().show();
1046 GLib.debug("Unkown call after load = %s", update_all_after);
1052 public void loadRemoteHeads(bool force = false)
1055 if (!force && this.remote_heads != null) {
1058 var r = this.repo.lookup_remote("origin");
1059 var cb = new GitCallbacks(this);
1060 r.connect(Ggit.Direction.FETCH, cb, null, null);
1061 this.remote_heads = r.list();