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" });
302 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
305 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
309 public void loadBranches()
312 GitBranch.loadBranches(this);
316 public bool hasBranchCalled(string name)
318 foreach( var br in this.branches.values) {
319 if (br.name == name) {
327 public string branchesToString()
330 foreach( var br in this.branches.values) {
334 var col = /hours/.match(br.age) ? "#ff851b" : "#ffdc00"; // orange or yellow
335 ret += ret.length > 0 ? "\n" : "";
336 ret += br.name + " <span background=\"" + col + "\">" + br.age + "</span>";
342 public static void doMerges(string action, string ticket_id, string commit_message)
344 GitMonitor.gitmonitor.stop();
348 foreach(var repo in GitRepo.singleton().cache.values) {
349 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
350 var res = repo.doMerge(action,ticket_id, commit_message);
355 commitrevs += commitrevs.length > 0 ? " " : "";
356 commitrevs += repo.currentBranch.lastrev;
359 if (sucess && action == "CLOSE") {
360 RooTicket.singleton().getById(ticket_id).close(commitrevs);
362 GitMonitor.gitmonitor.start();
366 public bool doMerge(string action, string ticket_id, string commit_message)
368 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
369 // also need to decide which branch we will merge into?
370 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
373 if (action == "CLOSE" || action == "LEAVE") {
376 var oldbranch = this.currentBranch.name;
377 this.setActiveTicket(null, master);
378 string [] cmd = { "merge", "--squash", oldbranch };
380 cmd = { "commit", "-a" , "-m", commit_message };
383 this.loadBranches(); // updates lastrev..
385 var notification = new Notify.Notification(
386 "Merged branch %s to %s".printf(oldbranch, master),
392 notification.set_timeout(5);
400 GitMonitor.gitmonitor.pauseError(e.message);
403 // error~?? -- show the error dialog...
406 if (action == "MASTER") {
407 // merge master into ours..
409 string[] cmd = { "merge", master};
411 var notification = new Notify.Notification(
412 "Merged code from %s to %s".printf(master,this.currentBranch.name),
417 notification.set_timeout(5);
422 GitMonitor.gitmonitor.pauseError(e.message);
426 if (action == "EXIT") {
428 var oldbranch = this.currentBranch.name;
429 this.setActiveTicket(null, master);
431 var notification = new Notify.Notification(
432 "Left branch %s".printf(oldbranch),
437 notification.set_timeout(5);
442 GitMonitor.gitmonitor.pauseError(e.message);
446 // error~?? -- show the error dialog...
452 public void loadActiveTicket()
454 this.activeTicket = null;
455 var ticket_id = this.get_config("ticket");
457 if (ticket_id.length < 1) {
460 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
467 public bool setActiveTicket(RooTicket? ticket, string branchname)
469 this.set_config("ticket", "");
470 if (!this.createBranchNamed(branchname)) {
473 this.set_config("ticket", ticket == null ? "": ticket.id);
474 this.activeTicket = ticket;
478 public bool createBranchNamed(string branchname)
482 if (this.branches.has_key(branchname)) {
483 this.switchToExistingBranchNamed(branchname);
486 this.createNewBranchNamed(branchname);
489 var notification = new Notify.Notification(
490 "Changed to branch %s".printf(branchname),
496 notification.set_timeout(5);
500 this.loadBranches(); // update branch list...
501 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
504 bool switchToExistingBranchNamed(string branchname)
506 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
508 // this is where it get's tricky...
511 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
512 files = this.git(cmd);
513 stash = files.length> 1 ;
517 if (stash) { this.git(cmd); }
521 cmd = { "checkout", branchname };
524 GitMonitor.gitmonitor.pauseError(e.message);
528 if (branchname != master) {
529 string[] cmd = { "merge", master };
536 string[] cmd = { "checkout", master };
538 GitMonitor.gitmonitor.pauseError(
539 "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(
547 string[] cmd = { "stash", "pop" };
550 var fl = files.split("\n");
551 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
552 foreach(var f in fl) {
553 if (f.length < 1) continue;
562 GitMonitor.gitmonitor.pauseError(ee.message);
572 bool createNewBranchNamed(string branchname)
576 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
577 var files = this.git(cmd);
578 stash = files.length> 1 ;
580 cmd = { "checkout", "-b" , branchname };
583 cmd = { "push", "-u" , "origin" ,"HEAD" };
587 var fl = files.split("\n");
588 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
589 foreach(var f in fl) {
590 if (f.length < 1) continue;
599 GitMonitor.gitmonitor.pauseError(ee.message);
606 public static string previewMerges(string ticket_id)
609 foreach(var repo in GitRepo.singleton().cache.values) {
610 if (repo.activeTicket == null || repo.activeTicket.id != ticket_id) {
613 ret += repo.previewMerge() + "\n\n";
622 public string previewMerge()
625 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
626 var lines = this.git({"log", master + "...", "--pretty=format:%H %P" }).split("\n");;
627 var head = this.git({"log", "-1", "--pretty=format:%H %P" });
628 var start = head.split(" ")[0];
630 for (var i = 0; i < lines.length; i++) {
631 var cols = lines[i].split(" ");
632 if (cols.length > 2) {
638 var last = lines[lines.length-1];
639 end = last.split(" ")[1];
642 return this.git({ "diff" , (end+".."+start), "--no-color" });
644 GitMonitor.gitmonitor.pauseError(ee.message);
645 return "Error getting diff";
655 * add files to track.
657 * @argument {Array} files the files to add.
659 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
661 // should really find out if these are untracked files each..
662 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
663 // not sure if that is how git works.. but just be certian.
665 for (var i = 0; i < files.size;i++) {
666 var f = files.get(i).vname;
668 string[] cmd = { "add", f };
671 ret += e.message + "\n";
678 public bool is_ignore(string fname) throws Error, SpawnError
680 if (fname == ".gitignore") {
681 this.ignore_files.clear();
684 if (this.ignore_files.has_key(fname)) {
685 return this.ignore_files.get(fname);
689 var ret = this.git( { "check-ignore" , fname } );
690 this.ignore_files.set(fname, ret.length > 0);
691 return ret.length > 0;
692 } catch (SpawnError e) {
693 this.ignore_files.set(fname, false);
702 * remove files to track.
704 * @argument {Array} files the files to add.
706 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
708 // this may fail if files do not exist..
709 // should really find out if these are untracked files each..
710 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
711 // not sure if that is how git works.. but just be certian.
714 for (var i = 0; i < files.size;i++) {
715 var f = files.get(i).vname;
717 string[] cmd = { "rm", "-f" , f };
720 ret += e.message + "\n";
733 * @argument {Object} cfg commit configuration
735 * @property {String} name (optional)
736 * @property {String} email (optional)
737 * @property {String} changed (date) (optional)
738 * @property {String} reason (optional)
739 * @property {Array} files - the files that have changed.
743 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
750 if (typeof(cfg.name) != 'undefined') {
752 'author' : cfg.name + ' <' + cfg.email + '>'
755 "GIT_COMMITTER_NAME" + cfg.name,
756 "GIT_COMMITTER_EMAIL" + cfg.email
760 if (typeof(cfg.changed) != 'undefined') {
761 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
765 string[] args = { "commit", "-m" };
766 args += (message.length > 0 ? message : "Changed" );
767 for (var i = 0; i< files.size ; i++ ) {
768 args += files.get(i).vname; // full path?
771 return this.git(args);
776 * Fetch and merge remote repo changes into current branch..
778 * At present we just need this to update the current working branch..
779 * -- maybe later it will have a few options and do more stuff..
782 public string pull () throws Error, SpawnError
784 // should probably hand error conditions better...
785 string[] cmd = { "pull" , "--no-edit" };
786 return this.git( cmd );
791 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
792 public void pull_async(GitAsyncCallback cb)
795 string[] cmd = { "pull" , "--no-edit" };
796 this.git_async( cmd , cb);
803 * Send local changes to remote repo(s)
805 * At present we just need this to push the current branch.
806 * -- maybe later it will have a few options and do more stuff..
809 public string push () throws Error, SpawnError
812 return this.git({ "push" });
820 * The meaty part.. run spawn.. with git..
825 public string git(string[] args_in ) throws Error, SpawnError
827 // convert arguments.
829 string[] args = { "git" };
830 //args += "--git-dir";
831 //args += this.gitdir;
832 args += "--no-pager";
835 //if (this.gitdir != this.repopath) {
836 // args += "--work-tree";
837 // args += this.repopath;
839 for (var i = 0; i < args_in.length;i++) {
843 //this.lastCmd = args.join(" ");
845 GLib.debug( "CWD=%s", this.git_working_dir );
846 GLib.debug( "cmd: %s", string.joinv (" ", args));
850 string home = "HOME=" + Environment.get_home_dir() ;
852 // do not need to set gitpath..
853 //if (File.exists(this.repo + '/.git/config')) {
854 //env.push("GITPATH=" + this.repo );
857 var cfg = new SpawnConfig(this.git_working_dir , args , env);
860 // may throw error...
861 var sp = new Spawn(cfg);
863 //GLib.debug( "GOT result: %d" , sp.result);
865 // diff output is a bit big..
866 if (args_in[0] != "diff") {
867 GLib.debug( "GOT: %s" , sp.output);
869 // parse output for some commands ?
873 unowned GitAsyncCallback git_async_on_callback;
874 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
876 // convert arguments.
877 this.git_async_on_callback = cb;
878 string[] args = { "git" };
879 //args += "--git-dir";
880 //args += this.gitdir;
881 args += "--no-pager";
884 //if (this.gitdir != this.repopath) {
885 // args += "--work-tree";
886 // args += this.repopath;
888 for (var i = 0; i < args_in.length;i++) {
892 //this.lastCmd = args.join(" ");
894 GLib.debug( "CWD=%s", this.git_working_dir );
895 //print( "cmd: %s\n", string.joinv (" ", args));
899 string home = "HOME=" + Environment.get_home_dir() ;
901 // do not need to set gitpath..
902 //if (File.exists(this.repo + '/.git/config')) {
903 //env.push("GITPATH=" + this.repo );
907 var cfg = new SpawnConfig(this.git_working_dir , args , env);
911 // may throw error...
912 var sp = new Spawn(cfg);
915 sp.run(this.git_async_on_complete);
919 void git_async_on_complete(int err, string output)
921 GLib.debug("GOT %d : %s", err, output);
922 this.git_async_on_callback(this, err, output);
933 public void update_async(GitAsyncCallback cb)
935 string[] cmd = { "fetch" , "--all" };
936 this.git_async( cmd , cb);
941 static uint update_all_total = 0;
942 static string update_all_after = "";
944 public static void updateAll(string after)
946 update_all_after = after;
947 var tr = GitRepo.singleton().cache;
950 update_all_total = tr.size;
951 foreach(var repo in tr.values) {
952 if (!repo.is_managed()) {
956 repo.update_async(updateAllCallback);
958 GLib.debug("calls total = %d", (int) update_all_total);
960 public static void updateAllCallback(GitRepo repo, int err, string res)
966 GLib.debug("calls remaining = %d", (int)update_all_total);
967 if (update_all_total > 0 ) {
971 GLib.debug("call after load = %s", update_all_after);
973 switch (update_all_after) {
975 Clones.singleton().show();
978 GLib.debug("Unkown call after load = %s", update_all_after);