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 private Ggit.Repository repo;
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 this.repo = Ggit.Repository.open(GLib.File.new_for_path(path));
180 var r = this.repo.lookup_remote("origin");
183 //var r = this.git({ "remote" , "get-url" , "--push" , "origin"});
184 var uri = new Soup.URI(r.get_url());
185 this.host = uri.get_host();
189 this.loadActiveTicket();
193 public bool is_master_branch()
195 // special branches that do not allow autopushing now...
196 return this.currentBranch.name == "master" || this.currentBranch.name == "roojs";
199 public void init_config()
201 this.config_cache = new Gee.HashMap<string,string>();
203 if (this.get_config("managed") == "") {
204 this.set_config("managed", this.host == "git.roojs.com" ? "1" : "0");
206 if (this.get_config("autocommit") == "") {
207 this.set_config("autocommit", this.host == "git.roojs.com" ? "1" : "0");
209 if (this.get_config("autopush") == "") {
210 this.set_config("autopush", this.host == "git.roojs.com" ? "1" : "0");
217 public string get_config(string key)
220 if (this.config_cache.has_key(key)) {
221 //GLib.debug("get_config %s = '%s'", key, this.config_cache.get(key));
222 return this.config_cache.get(key);
225 var cfg = this.repo.get_config().snapshot();
226 var ret = cfg.get_string("gitlive." + key).strip();
229 this.repo.get_config().set_string("gitlive." + key, "");
230 //this.config_cache.set(key, "");
231 //GLib.debug("get_config (fail) %s = '%s'", key, "");
232 return ""; // happens when there is nothing set...
236 public void set_config(string key, string value)
238 this.repo.get_config().set_string("gitlive." + key, value);
239 //this.git({ "config" , "gitlive." + key, value });
240 //this.config_cache.set(key,value);
243 public bool is_managed()
245 return this.get_config("managed") == "1";
249 public bool is_autocommit ()
251 return this.get_config("autocommit") == "1";
254 public void set_autocommit(bool val)
256 this.set_config("autocommit", val ? "1" : "0");
260 public bool is_auto_branch ()
262 if (this.name == "gitlog") {
266 if (this.is_managed()) {
274 public void set_auto_branch(bool val)
276 if (this.name == "gitlog") {
279 this.set_config("managed", val ? "1" : "0");
282 public bool is_autopush ()
284 return this.get_config("autopush") == "1";
286 public void set_autopush(bool val)
288 this.set_config("autopush", val ? "1" : "0");
292 public void loadStatus()
295 var r = this.git({ "status" , "--porcelain" });
297 this.has_local_changes = r.length > 0;
299 var rs = this.git({ "status" , "-sb" });
301 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
304 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
308 public void loadBranches()
311 GitBranch.loadBranches(this);
315 public bool hasBranchCalled(string name)
317 foreach( var br in this.branches.values) {
318 if (br.name == name) {
326 public string branchesToString()
329 foreach( var br in this.branches.values) {
333 var col = /hours/.match(br.age) ? "#ff851b" : "#ffdc00"; // orange or yellow
334 ret += ret.length > 0 ? "\n" : "";
335 ret += br.name + " <span background=\"" + col + "\">" + br.age + "</span>";
341 public static void doMerges(string action, string ticket_id, string commit_message)
343 GitMonitor.gitmonitor.stop();
347 foreach(var repo in GitRepo.singleton().cache.values) {
348 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
349 var res = repo.doMerge(action,ticket_id, commit_message);
354 commitrevs += commitrevs.length > 0 ? " " : "";
355 commitrevs += repo.currentBranch.lastrev;
358 if (sucess && action == "CLOSE") {
359 RooTicket.singleton().getById(ticket_id).close(commitrevs);
361 GitMonitor.gitmonitor.start();
365 public bool doMerge(string action, string ticket_id, string commit_message)
367 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
368 // also need to decide which branch we will merge into?
369 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
372 if (action == "CLOSE" || action == "LEAVE") {
375 var oldbranch = this.currentBranch.name;
376 this.setActiveTicket(null, master);
377 string [] cmd = { "merge", "--squash", oldbranch };
379 cmd = { "commit", "-a" , "-m", commit_message };
382 this.loadBranches(); // updates lastrev..
384 var notification = new Notify.Notification(
385 "Merged branch %s to %s".printf(oldbranch, master),
391 notification.set_timeout(5);
399 GitMonitor.gitmonitor.pauseError(e.message);
402 // error~?? -- show the error dialog...
405 if (action == "MASTER") {
406 // merge master into ours..
408 string[] cmd = { "merge", master};
410 var notification = new Notify.Notification(
411 "Merged code from %s to %s".printf(master,this.currentBranch.name),
416 notification.set_timeout(5);
421 GitMonitor.gitmonitor.pauseError(e.message);
425 if (action == "EXIT") {
427 var oldbranch = this.currentBranch.name;
428 this.setActiveTicket(null, master);
430 var notification = new Notify.Notification(
431 "Left branch %s".printf(oldbranch),
436 notification.set_timeout(5);
441 GitMonitor.gitmonitor.pauseError(e.message);
445 // error~?? -- show the error dialog...
451 public void loadActiveTicket()
453 this.activeTicket = null;
454 var ticket_id = this.get_config("ticket");
456 if (ticket_id.length < 1) {
459 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
466 public bool setActiveTicket(RooTicket? ticket, string branchname)
468 this.set_config("ticket", "");
469 if (!this.createBranchNamed(branchname)) {
472 this.set_config("ticket", ticket == null ? "": ticket.id);
473 this.activeTicket = ticket;
477 public bool createBranchNamed(string branchname)
481 if (this.branches.has_key(branchname)) {
482 this.switchToExistingBranchNamed(branchname);
485 this.createNewBranchNamed(branchname);
488 var notification = new Notify.Notification(
489 "Changed to branch %s".printf(branchname),
495 notification.set_timeout(5);
499 this.loadBranches(); // update branch list...
500 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
503 bool switchToExistingBranchNamed(string branchname)
505 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
507 // this is where it get's tricky...
510 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
511 files = this.git(cmd);
512 stash = files.length> 1 ;
516 if (stash) { this.git(cmd); }
520 cmd = { "checkout", branchname };
523 GitMonitor.gitmonitor.pauseError(e.message);
527 if (branchname != master) {
528 string[] cmd = { "merge", master };
535 string[] cmd = { "checkout", master };
537 GitMonitor.gitmonitor.pauseError(
538 "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(
546 string[] cmd = { "stash", "pop" };
549 var fl = files.split("\n");
550 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
551 foreach(var f in fl) {
552 if (f.length < 1) continue;
561 GitMonitor.gitmonitor.pauseError(ee.message);
571 bool createNewBranchNamed(string branchname)
575 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
576 var files = this.git(cmd);
577 stash = files.length> 1 ;
579 cmd = { "checkout", "-b" , branchname };
582 cmd = { "push", "-u" , "origin" ,"HEAD" };
586 var fl = files.split("\n");
587 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
588 foreach(var f in fl) {
589 if (f.length < 1) continue;
598 GitMonitor.gitmonitor.pauseError(ee.message);
605 public static string previewMerges(string ticket_id)
608 foreach(var repo in GitRepo.singleton().cache.values) {
609 if (repo.activeTicket == null || repo.activeTicket.id != ticket_id) {
612 ret += repo.previewMerge() + "\n\n";
621 public string previewMerge()
624 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
625 var lines = this.git({"log", master + "...", "--pretty=format:%H %P" }).split("\n");;
626 var head = this.git({"log", "-1", "--pretty=format:%H %P" });
627 var start = head.split(" ")[0];
629 for (var i = 0; i < lines.length; i++) {
630 var cols = lines[i].split(" ");
631 if (cols.length > 2) {
637 var last = lines[lines.length-1];
638 end = last.split(" ")[1];
641 return this.git({ "diff" , (end+".."+start), "--no-color" });
643 GitMonitor.gitmonitor.pauseError(ee.message);
644 return "Error getting diff";
654 * add files to track.
656 * @argument {Array} files the files to add.
658 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
660 // should really find out if these are untracked files each..
661 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
662 // not sure if that is how git works.. but just be certian.
664 for (var i = 0; i < files.size;i++) {
665 var f = files.get(i).vname;
667 string[] cmd = { "add", f };
670 ret += e.message + "\n";
677 public bool is_ignore(string fname) throws Error, SpawnError
679 if (fname == ".gitignore") {
680 this.ignore_files.clear();
683 if (this.ignore_files.has_key(fname)) {
684 return this.ignore_files.get(fname);
688 var ret = this.git( { "check-ignore" , fname } );
689 this.ignore_files.set(fname, ret.length > 0);
690 return ret.length > 0;
691 } catch (SpawnError e) {
692 this.ignore_files.set(fname, false);
701 * remove files to track.
703 * @argument {Array} files the files to add.
705 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
707 // this may fail if files do not exist..
708 // should really find out if these are untracked files each..
709 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
710 // not sure if that is how git works.. but just be certian.
713 for (var i = 0; i < files.size;i++) {
714 var f = files.get(i).vname;
716 string[] cmd = { "rm", "-f" , f };
719 ret += e.message + "\n";
732 * @argument {Object} cfg commit configuration
734 * @property {String} name (optional)
735 * @property {String} email (optional)
736 * @property {String} changed (date) (optional)
737 * @property {String} reason (optional)
738 * @property {Array} files - the files that have changed.
742 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
749 if (typeof(cfg.name) != 'undefined') {
751 'author' : cfg.name + ' <' + cfg.email + '>'
754 "GIT_COMMITTER_NAME" + cfg.name,
755 "GIT_COMMITTER_EMAIL" + cfg.email
759 if (typeof(cfg.changed) != 'undefined') {
760 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
764 string[] args = { "commit", "-m" };
765 args += (message.length > 0 ? message : "Changed" );
766 for (var i = 0; i< files.size ; i++ ) {
767 args += files.get(i).vname; // full path?
770 return this.git(args);
775 * Fetch and merge remote repo changes into current branch..
777 * At present we just need this to update the current working branch..
778 * -- maybe later it will have a few options and do more stuff..
781 public string pull () throws Error, SpawnError
783 // should probably hand error conditions better...
784 string[] cmd = { "pull" , "--no-edit" };
785 return this.git( cmd );
790 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
791 public void pull_async(GitAsyncCallback cb)
794 string[] cmd = { "pull" , "--no-edit" };
795 this.git_async( cmd , cb);
802 * Send local changes to remote repo(s)
804 * At present we just need this to push the current branch.
805 * -- maybe later it will have a few options and do more stuff..
808 public string push () throws Error, SpawnError
811 return this.git({ "push" });
819 * The meaty part.. run spawn.. with git..
824 public string git(string[] args_in ) throws Error, SpawnError
826 // convert arguments.
828 string[] args = { "git" };
829 //args += "--git-dir";
830 //args += this.gitdir;
831 args += "--no-pager";
834 //if (this.gitdir != this.repopath) {
835 // args += "--work-tree";
836 // args += this.repopath;
838 for (var i = 0; i < args_in.length;i++) {
842 //this.lastCmd = args.join(" ");
844 GLib.debug( "CWD=%s", this.git_working_dir );
845 GLib.debug( "cmd: %s", string.joinv (" ", args));
849 string home = "HOME=" + Environment.get_home_dir() ;
851 // do not need to set gitpath..
852 //if (File.exists(this.repo + '/.git/config')) {
853 //env.push("GITPATH=" + this.repo );
856 var cfg = new SpawnConfig(this.git_working_dir , args , env);
859 // may throw error...
860 var sp = new Spawn(cfg);
862 //GLib.debug( "GOT result: %d" , sp.result);
864 // diff output is a bit big..
865 if (args_in[0] != "diff") {
866 GLib.debug( "GOT: %s" , sp.output);
868 // parse output for some commands ?
872 unowned GitAsyncCallback git_async_on_callback;
873 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
875 // convert arguments.
876 this.git_async_on_callback = cb;
877 string[] args = { "git" };
878 //args += "--git-dir";
879 //args += this.gitdir;
880 args += "--no-pager";
883 //if (this.gitdir != this.repopath) {
884 // args += "--work-tree";
885 // args += this.repopath;
887 for (var i = 0; i < args_in.length;i++) {
891 //this.lastCmd = args.join(" ");
893 GLib.debug( "CWD=%s", this.git_working_dir );
894 //print( "cmd: %s\n", string.joinv (" ", args));
898 string home = "HOME=" + Environment.get_home_dir() ;
900 // do not need to set gitpath..
901 //if (File.exists(this.repo + '/.git/config')) {
902 //env.push("GITPATH=" + this.repo );
906 var cfg = new SpawnConfig(this.git_working_dir , args , env);
910 // may throw error...
911 var sp = new Spawn(cfg);
914 sp.run(this.git_async_on_complete);
918 void git_async_on_complete(int err, string output)
920 GLib.debug("GOT %d : %s", err, output);
921 this.git_async_on_callback(this, err, output);
932 public void update_async(GitAsyncCallback cb)
934 string[] cmd = { "fetch" , "--all" };
935 this.git_async( cmd , cb);
940 static uint update_all_total = 0;
941 static string update_all_after = "";
943 public static void updateAll(string after)
945 update_all_after = after;
946 var tr = GitRepo.singleton().cache;
949 update_all_total = tr.size;
950 foreach(var repo in tr.values) {
951 if (!repo.is_managed()) {
955 repo.update_async(updateAllCallback);
957 GLib.debug("calls total = %d", (int) update_all_total);
959 public static void updateAllCallback(GitRepo repo, int err, string res)
965 GLib.debug("calls remaining = %d", (int)update_all_total);
966 if (update_all_total > 0 ) {
970 GLib.debug("call after load = %s", update_all_after);
972 switch (update_all_after) {
974 Clones.singleton().show();
977 GLib.debug("Unkown call after load = %s", update_all_after);