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;
34 public Ggit.Repository repo;
35 public Ggit.RemoteHead[] remote_heads = null;
37 public static GitRepo singleton()
39 if (_GitRepo == null) {
40 _GitRepo = new GitRepo.single();
41 _GitRepo.cache = new Gee.HashMap<string,GitRepo>();
47 * index of.. matching gitpath..
49 public static int indexOf( Array<GitRepo> repos, string gitpath) {
50 // make a fake object to compare against..
51 var test_repo = GitRepo.get(gitpath);
53 for(var i =0; i < repos.length; i++) {
54 if (repos.index(i).gitdir == test_repo.gitdir) {
66 public static Array<GitRepo> list()
69 //if (GitRepo.list_cache != null) {
70 // unowned Array<GitRepo> ret = GitRepo.list_cache;
73 var cache = GitRepo.singleton().cache;
74 var list_cache = new Array<GitRepo>();
76 var dir = Environment.get_home_dir() + "/gitlive";
78 var f = File.new_for_path(dir);
79 FileEnumerator file_enum;
81 file_enum = f.enumerate_children(
82 FileAttribute.STANDARD_DISPLAY_NAME + ","+
83 FileAttribute.STANDARD_TYPE,
84 FileQueryInfoFlags.NONE,
97 next_file = file_enum.next_file(null);
98 if (next_file == null) {
103 GLib.debug("Error: %s",e.message);
107 //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
109 if (next_file.get_file_type() != FileType.DIRECTORY) {
114 if (next_file.get_file_type() == FileType.SYMBOLIC_LINK) {
119 if (next_file.get_display_name()[0] == '.') {
123 var sp = dir+"/"+next_file.get_display_name();
125 var gitdir = dir + "/" + next_file.get_display_name() + "/.git";
127 if (!FileUtils.test(gitdir, FileTest.IS_DIR)) {
131 var rep = GitRepo.get( sp );
132 list_cache.append_val(rep);
140 public static GitRepo get(string path)
142 var cache = GitRepo.singleton().cache;
143 if (cache.has_key(path)) {
144 return cache.get(path);
146 return new GitRepo(path);
149 private GitRepo.single() {
150 // used to create the signleton
155 * @param {Object} cfg - Configuration
156 * (basically repopath is currently only critical one.)
160 private GitRepo(string path)
163 this.name = File.new_for_path(path).get_basename();
164 this.ignore_files = new Gee.HashMap<string,bool>();
166 this.git_working_dir = path;
167 this.gitdir = path + "/.git";
168 if (!FileUtils.test(this.gitdir , FileTest.IS_DIR)) {
169 this.gitdir = path; // naked...
171 this.cmds = new Gee.ArrayList<GitMonitorQueue> ();
173 var cache = GitRepo.singleton().cache;
174 //Repo.superclass.constructor.call(this,cfg);
175 if ( !cache.has_key(path) ) {
176 cache.set( path, this);
179 this.repo = Ggit.Repository.open(GLib.File.new_for_path(path));
181 var r = this.repo.lookup_remote("origin");
184 //var r = this.git({ "remote" , "get-url" , "--push" , "origin"});
185 var uri = new Soup.URI(r.get_url());
186 this.host = uri.get_host();
190 this.loadActiveTicket();
194 public bool is_master_branch()
196 // special branches that do not allow autopushing now...
197 return this.currentBranch.name == "master" || this.currentBranch.name == "roojs";
200 public void init_config()
202 this.config_cache = new Gee.HashMap<string,string>();
204 if (this.get_config("managed") == "") {
205 this.set_config("managed", this.host == "git.roojs.com" ? "1" : "0");
207 if (this.get_config("autocommit") == "") {
208 this.set_config("autocommit", this.host == "git.roojs.com" ? "1" : "0");
210 if (this.get_config("autopush") == "") {
211 this.set_config("autopush", this.host == "git.roojs.com" ? "1" : "0");
218 public string get_config(string key)
221 if (this.config_cache.has_key(key)) {
222 //GLib.debug("get_config %s = '%s'", key, this.config_cache.get(key));
223 return this.config_cache.get(key);
226 var cfg = this.repo.get_config().snapshot();
227 var ret = cfg.get_string("gitlive." + key).strip();
230 this.repo.get_config().set_string("gitlive." + key, "");
231 //this.config_cache.set(key, "");
232 //GLib.debug("get_config (fail) %s = '%s'", key, "");
233 return ""; // happens when there is nothing set...
237 public void set_config(string key, string value)
239 this.repo.get_config().set_string("gitlive." + key, value);
240 //this.git({ "config" , "gitlive." + key, value });
241 //this.config_cache.set(key,value);
244 public bool is_managed()
246 return this.get_config("managed") == "1";
250 public bool is_autocommit ()
252 return this.get_config("autocommit") == "1";
255 public void set_autocommit(bool val)
257 this.set_config("autocommit", val ? "1" : "0");
261 public bool is_auto_branch ()
263 if (this.name == "gitlog") {
267 if (this.is_managed()) {
275 public void set_auto_branch(bool val)
277 if (this.name == "gitlog") {
280 this.set_config("managed", val ? "1" : "0");
283 public bool is_autopush ()
285 return this.get_config("autopush") == "1";
287 public void set_autopush(bool val)
289 this.set_config("autopush", val ? "1" : "0");
293 public void loadStatus()
296 var r = this.git({ "status" , "--porcelain" });
298 this.has_local_changes = r.length > 0;
300 var rs = this.git({ "status" , "-sb" });
303 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
306 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
310 public void loadBranches()
313 GitBranch.loadBranches(this);
317 public bool hasBranchCalled(string name)
319 foreach( var br in this.branches.values) {
320 if (br.name == name) {
328 public string branchesToString()
331 foreach( var br in this.branches.values) {
335 var col = /hours/.match(br.age) ? "#ff851b" : "#ffdc00"; // orange or yellow
336 ret += ret.length > 0 ? "\n" : "";
337 ret += br.name + " <span background=\"" + col + "\">" + br.age + "</span>";
343 public static void doMerges(string action, string ticket_id, string commit_message)
345 GitMonitor.gitmonitor.stop();
349 foreach(var repo in GitRepo.singleton().cache.values) {
350 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
351 var res = repo.doMerge(action,ticket_id, commit_message);
356 commitrevs += commitrevs.length > 0 ? " " : "";
357 commitrevs += repo.currentBranch.lastrev;
360 if (sucess && action == "CLOSE") {
361 RooTicket.singleton().getById(ticket_id).close(commitrevs);
363 GitMonitor.gitmonitor.start();
367 public bool doMerge(string action, string ticket_id, string commit_message)
369 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
370 // also need to decide which branch we will merge into?
371 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
374 if (action == "CLOSE" || action == "LEAVE") {
377 var oldbranch = this.currentBranch.name;
378 this.setActiveTicket(null, master);
379 string [] cmd = { "merge", "--squash", oldbranch };
381 cmd = { "commit", "-a" , "-m", commit_message };
384 this.loadBranches(); // updates lastrev..
386 var notification = new Notify.Notification(
387 "Merged branch %s to %s".printf(oldbranch, master),
393 notification.set_timeout(5);
401 GitMonitor.gitmonitor.pauseError(e.message);
404 // error~?? -- show the error dialog...
407 if (action == "MASTER") {
408 // merge master into ours..
410 string[] cmd = { "merge", master};
412 var notification = new Notify.Notification(
413 "Merged code from %s to %s".printf(master,this.currentBranch.name),
418 notification.set_timeout(5);
423 GitMonitor.gitmonitor.pauseError(e.message);
427 if (action == "EXIT") {
429 var oldbranch = this.currentBranch.name;
430 this.setActiveTicket(null, master);
432 var notification = new Notify.Notification(
433 "Left branch %s".printf(oldbranch),
438 notification.set_timeout(5);
443 GitMonitor.gitmonitor.pauseError(e.message);
447 // error~?? -- show the error dialog...
453 public void loadActiveTicket()
455 this.activeTicket = null;
456 var ticket_id = this.get_config("ticket");
458 if (ticket_id.length < 1) {
461 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
468 public bool setActiveTicket(RooTicket? ticket, string branchname)
470 this.set_config("ticket", "");
471 if (!this.createBranchNamed(branchname)) {
474 this.set_config("ticket", ticket == null ? "": ticket.id);
475 this.activeTicket = ticket;
479 public bool createBranchNamed(string branchname)
483 if (this.branches.has_key(branchname)) {
484 this.switchToExistingBranchNamed(branchname);
487 this.createNewBranchNamed(branchname);
490 var notification = new Notify.Notification(
491 "Changed to branch %s".printf(branchname),
497 notification.set_timeout(5);
501 this.loadBranches(); // update branch list...
502 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
505 bool switchToExistingBranchNamed(string branchname)
507 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
509 // this is where it get's tricky...
512 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
513 files = this.git(cmd);
514 stash = files.length> 1 ;
518 if (stash) { this.git(cmd); }
522 cmd = { "checkout", branchname };
525 GitMonitor.gitmonitor.pauseError(e.message);
529 if (branchname != master) {
530 string[] cmd = { "merge", master };
537 string[] cmd = { "checkout", master };
539 GitMonitor.gitmonitor.pauseError(
540 "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(
548 string[] cmd = { "stash", "pop" };
551 var fl = files.split("\n");
552 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
553 foreach(var f in fl) {
554 if (f.length < 1) continue;
563 GitMonitor.gitmonitor.pauseError(ee.message);
573 bool createNewBranchNamed(string branchname)
577 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
578 var files = this.git(cmd);
579 stash = files.length> 1 ;
581 cmd = { "checkout", "-b" , branchname };
584 cmd = { "push", "-u" , "origin" ,"HEAD" };
588 var fl = files.split("\n");
589 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
590 foreach(var f in fl) {
591 if (f.length < 1) continue;
600 GitMonitor.gitmonitor.pauseError(ee.message);
607 public static string previewMerges(string ticket_id)
610 foreach(var repo in GitRepo.singleton().cache.values) {
611 if (repo.activeTicket == null || repo.activeTicket.id != ticket_id) {
614 ret += repo.previewMerge() + "\n\n";
623 public string previewMerge()
626 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
627 var lines = this.git({"log", master + "...", "--pretty=format:%H %P" }).split("\n");;
628 var head = this.git({"log", "-1", "--pretty=format:%H %P" });
629 var start = head.split(" ")[0];
631 for (var i = 0; i < lines.length; i++) {
632 var cols = lines[i].split(" ");
633 if (cols.length > 2) {
639 var last = lines[lines.length-1];
640 end = last.split(" ")[1];
643 return this.git({ "diff" , (end+".."+start), "--no-color" });
645 GitMonitor.gitmonitor.pauseError(ee.message);
646 return "Error getting diff";
656 * add files to track.
658 * @argument {Array} files the files to add.
660 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
662 // should really find out if these are untracked files each..
663 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
664 // not sure if that is how git works.. but just be certian.
666 for (var i = 0; i < files.size;i++) {
667 var f = files.get(i).vname;
669 string[] cmd = { "add", f };
672 ret += e.message + "\n";
679 public bool is_ignore(string fname) throws Error, SpawnError
681 if (fname == ".gitignore") {
682 this.ignore_files.clear();
685 if (this.ignore_files.has_key(fname)) {
686 return this.ignore_files.get(fname);
690 var ret = this.git( { "check-ignore" , fname } );
691 this.ignore_files.set(fname, ret.length > 0);
692 return ret.length > 0;
693 } catch (SpawnError e) {
694 this.ignore_files.set(fname, false);
703 * remove files to track.
705 * @argument {Array} files the files to add.
707 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
709 // this may fail if files do not exist..
710 // should really find out if these are untracked files each..
711 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
712 // not sure if that is how git works.. but just be certian.
715 for (var i = 0; i < files.size;i++) {
716 var f = files.get(i).vname;
718 string[] cmd = { "rm", "-f" , f };
721 ret += e.message + "\n";
734 * @argument {Object} cfg commit configuration
736 * @property {String} name (optional)
737 * @property {String} email (optional)
738 * @property {String} changed (date) (optional)
739 * @property {String} reason (optional)
740 * @property {Array} files - the files that have changed.
744 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
751 if (typeof(cfg.name) != 'undefined') {
753 'author' : cfg.name + ' <' + cfg.email + '>'
756 "GIT_COMMITTER_NAME" + cfg.name,
757 "GIT_COMMITTER_EMAIL" + cfg.email
761 if (typeof(cfg.changed) != 'undefined') {
762 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
766 string[] args = { "commit", "-m" };
767 args += (message.length > 0 ? message : "Changed" );
768 for (var i = 0; i< files.size ; i++ ) {
769 args += files.get(i).vname; // full path?
772 return this.git(args);
777 * Fetch and merge remote repo changes into current branch..
779 * At present we just need this to update the current working branch..
780 * -- maybe later it will have a few options and do more stuff..
783 public string pull () throws Error, SpawnError
785 // should probably hand error conditions better...
786 string[] cmd = { "pull" , "--no-edit" };
787 return this.git( cmd );
792 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
793 public void pull_async(GitAsyncCallback cb)
796 string[] cmd = { "pull" , "--no-edit" };
797 this.git_async( cmd , cb);
804 * Send local changes to remote repo(s)
806 * At present we just need this to push the current branch.
807 * -- maybe later it will have a few options and do more stuff..
810 public string push () throws Error, SpawnError
813 return this.git({ "push" });
821 * The meaty part.. run spawn.. with git..
826 public string git(string[] args_in ) throws Error, SpawnError
828 // convert arguments.
830 string[] args = { "git" };
831 //args += "--git-dir";
832 //args += this.gitdir;
833 args += "--no-pager";
836 //if (this.gitdir != this.repopath) {
837 // args += "--work-tree";
838 // args += this.repopath;
840 for (var i = 0; i < args_in.length;i++) {
844 //this.lastCmd = args.join(" ");
846 GLib.debug( "CWD=%s", this.git_working_dir );
847 GLib.debug( "cmd: %s", string.joinv (" ", args));
851 string home = "HOME=" + Environment.get_home_dir() ;
853 // do not need to set gitpath..
854 //if (File.exists(this.repo + '/.git/config')) {
855 //env.push("GITPATH=" + this.repo );
858 var cfg = new SpawnConfig(this.git_working_dir , args , env);
861 // may throw error...
862 var sp = new Spawn(cfg);
864 //GLib.debug( "GOT result: %d" , sp.result);
866 // diff output is a bit big..
867 if (args_in[0] != "diff") {
868 GLib.debug( "GOT: %s" , sp.output);
870 // parse output for some commands ?
874 unowned GitAsyncCallback git_async_on_callback;
875 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
877 // convert arguments.
878 this.git_async_on_callback = cb;
879 string[] args = { "git" };
880 //args += "--git-dir";
881 //args += this.gitdir;
882 args += "--no-pager";
885 //if (this.gitdir != this.repopath) {
886 // args += "--work-tree";
887 // args += this.repopath;
889 for (var i = 0; i < args_in.length;i++) {
893 //this.lastCmd = args.join(" ");
895 GLib.debug( "CWD=%s", this.git_working_dir );
896 //print( "cmd: %s\n", string.joinv (" ", args));
900 string home = "HOME=" + Environment.get_home_dir() ;
902 // do not need to set gitpath..
903 //if (File.exists(this.repo + '/.git/config')) {
904 //env.push("GITPATH=" + this.repo );
908 var cfg = new SpawnConfig(this.git_working_dir , args , env);
912 // may throw error...
913 var sp = new Spawn(cfg);
916 sp.run(this.git_async_on_complete);
920 void git_async_on_complete(int err, string output)
922 GLib.debug("GOT %d : %s", err, output);
923 this.git_async_on_callback(this, err, output);
934 public void update_async(GitAsyncCallback cb)
936 string[] cmd = { "fetch" , "--all" };
937 this.git_async( cmd , cb);
942 static uint update_all_total = 0;
943 static string update_all_after = "";
945 public static void updateAll(string after)
947 update_all_after = after;
948 var tr = GitRepo.singleton().cache;
951 update_all_total = tr.size;
952 foreach(var repo in tr.values) {
953 if (!repo.is_managed()) {
957 repo.update_async(updateAllCallback);
959 GLib.debug("calls total = %d", (int) update_all_total);
961 public static void updateAllCallback(GitRepo repo, int err, string res)
967 GLib.debug("calls remaining = %d", (int)update_all_total);
968 if (update_all_total > 0 ) {
972 GLib.debug("call after load = %s", update_all_after);
974 switch (update_all_after) {
976 Clones.singleton().show();
979 GLib.debug("Unkown call after load = %s", update_all_after);
985 public void loadRemoteHeads(bool force = false)
988 if (!force && this.remote_heads != null) {
991 var r = this.repo.lookup_remote("origin");
992 r.connect(Ggit.Direction.FETCH, this.callbacks, null, null);
993 this.remote_heads = r.list();