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);
308 public string branchesToString()
311 foreach( var br in this.branches.values) {
315 ret += ret.length > 0 ? "\n" : "";
322 public static void doMerges(string action, string ticket_id, string commit_message)
324 GitMonitor.gitmonitor.stop();
328 foreach(var repo in GitRepo.singleton().cache.values) {
329 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
330 var res = repo.doMerge(action,ticket_id, commit_message);
335 commitrevs += commitrevs.length > 0 ? " " : "";
336 commitrevs += repo.currentBranch.lastrev;
339 if (sucess && action == "CLOSE") {
340 RooTicket.singleton().getById(ticket_id).close(commitrevs);
342 GitMonitor.gitmonitor.start();
346 public bool doMerge(string action, string ticket_id, string commit_message)
348 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
349 // also need to decide which branch we will merge into?
351 if (action == "CLOSE" || action == "LEAVE") {
354 var oldbranch = this.currentBranch.name;
355 this.setActiveTicket(null, "master");
356 string [] cmd = { "merge", "--squash", oldbranch };
358 cmd = { "commit", "-a" , "-m", commit_message };
361 this.loadBranches(); // updates lastrev..
363 var notification = new Notify.Notification(
364 "Merged branch %s to master".printf(oldbranch),
370 notification.set_timeout(5);
378 GitMonitor.gitmonitor.pauseError(e.message);
381 // error~?? -- show the error dialog...
384 if (action == "MASTER") {
385 // merge master into ours..
387 string[] cmd = { "merge", "master" };
389 var notification = new Notify.Notification(
390 "Merged code from master to %s".printf(this.currentBranch.name),
395 notification.set_timeout(5);
400 GitMonitor.gitmonitor.pauseError(e.message);
404 if (action == "EXIT") {
406 var oldbranch = this.currentBranch.name;
407 this.setActiveTicket(null, "master");
409 var notification = new Notify.Notification(
410 "Left branch %s".printf(oldbranch),
415 notification.set_timeout(5);
420 GitMonitor.gitmonitor.pauseError(e.message);
424 // error~?? -- show the error dialog...
430 public void loadActiveTicket()
432 this.activeTicket = null;
433 var ticket_id = this.get_config("ticket");
435 if (ticket_id.length < 1) {
438 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
445 public bool setActiveTicket(RooTicket? ticket, string branchname)
447 this.set_config("ticket", "");
448 if (!this.createBranchNamed(branchname)) {
451 this.set_config("ticket", ticket == null ? "": ticket.id);
452 this.activeTicket = ticket;
456 public bool createBranchNamed(string branchname)
460 if (this.branches.has_key(branchname)) {
461 this.switchToExistingBranchNamed(branchname);
464 this.createNewBranchNamed(branchname);
467 var notification = new Notify.Notification(
468 "Changed to branch %s".printf(branchname),
474 notification.set_timeout(5);
478 this.loadBranches(); // update branch list...
479 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
482 bool switchToExistingBranchNamed(string branchname)
485 // this is where it get's tricky...
488 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
489 files = this.git(cmd);
490 stash = files.length> 1 ;
494 if (stash) { this.git(cmd); }
498 cmd = { "checkout", branchname };
501 GitMonitor.gitmonitor.pauseError(e.message);
505 if (branchname != "master") {
506 string[] cmd = { "merge", "master" };
513 string[] cmd = { "checkout", "master" };
515 GitMonitor.gitmonitor.pauseError(
516 "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(
524 string[] cmd = { "stash", "pop" };
527 var fl = files.split("\n");
528 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
529 foreach(var f in fl) {
530 if (f.length < 1) continue;
539 GitMonitor.gitmonitor.pauseError(ee.message);
549 bool createNewBranchNamed(string branchname)
553 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
554 var files = this.git(cmd);
555 stash = files.length> 1 ;
557 cmd = { "checkout", "-b" , branchname };
560 cmd = { "push", "-u" , "origin" ,"HEAD" };
564 var fl = files.split("\n");
565 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
566 foreach(var f in fl) {
567 if (f.length < 1) continue;
576 GitMonitor.gitmonitor.pauseError(ee.message);
583 public static string previewMerges(string ticket_id)
586 foreach(var repo in GitRepo.singleton().cache.values) {
587 if (repo.activeTicket == null || repo.activeTicket.id != ticket_id) {
590 ret += repo.previewMerge() + "\n\n";
599 public string previewMerge()
602 var lines = this.git({"log", "master...", "--pretty=format:\"%H %P\"" }).split("\n");;
603 var head = this.git({"log", "-1", "--pretty=format:\"%H %P\"" });
604 start = head.split(" ")[0];
606 for (var i = 0; i < lines.length; i++) {
607 var cols = lines[i].split(" ");
608 if (cols.length > 2) {
614 var last = lines[lines.length-1];
615 var end = last.split(" ")[1];
618 return this.git({ "diff" , start+".."+end, "--no-color" });
620 GitMonitor.gitmonitor.pauseError(ee.message);
621 return "Error getting diff";
631 * add files to track.
633 * @argument {Array} files the files to add.
635 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
637 // should really find out if these are untracked files each..
638 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
639 // not sure if that is how git works.. but just be certian.
641 for (var i = 0; i < files.size;i++) {
642 var f = files.get(i).vname;
644 string[] cmd = { "add", f };
647 ret += e.message + "\n";
654 public bool is_ignore(string fname) throws Error, SpawnError
656 if (fname == ".gitignore") {
657 this.ignore_files.clear();
660 if (this.ignore_files.has_key(fname)) {
661 return this.ignore_files.get(fname);
665 var ret = this.git( { "check-ignore" , fname } );
666 this.ignore_files.set(fname, ret.length > 0);
667 return ret.length > 0;
668 } catch (SpawnError e) {
669 this.ignore_files.set(fname, false);
678 * remove files to track.
680 * @argument {Array} files the files to add.
682 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
684 // this may fail if files do not exist..
685 // should really find out if these are untracked files each..
686 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
687 // not sure if that is how git works.. but just be certian.
690 for (var i = 0; i < files.size;i++) {
691 var f = files.get(i).vname;
693 string[] cmd = { "rm", "-f" , f };
696 ret += e.message + "\n";
709 * @argument {Object} cfg commit configuration
711 * @property {String} name (optional)
712 * @property {String} email (optional)
713 * @property {String} changed (date) (optional)
714 * @property {String} reason (optional)
715 * @property {Array} files - the files that have changed.
719 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
726 if (typeof(cfg.name) != 'undefined') {
728 'author' : cfg.name + ' <' + cfg.email + '>'
731 "GIT_COMMITTER_NAME" + cfg.name,
732 "GIT_COMMITTER_EMAIL" + cfg.email
736 if (typeof(cfg.changed) != 'undefined') {
737 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
741 string[] args = { "commit", "-m" };
742 args += (message.length > 0 ? message : "Changed" );
743 for (var i = 0; i< files.size ; i++ ) {
744 args += files.get(i).vname; // full path?
747 return this.git(args);
752 * Fetch and merge remote repo changes into current branch..
754 * At present we just need this to update the current working branch..
755 * -- maybe later it will have a few options and do more stuff..
758 public string pull () throws Error, SpawnError
760 // should probably hand error conditions better...
761 string[] cmd = { "pull" , "--no-edit" };
762 return this.git( cmd );
767 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
768 public void pull_async(GitAsyncCallback cb)
771 string[] cmd = { "pull" , "--no-edit" };
772 this.git_async( cmd , cb);
779 * Send local changes to remote repo(s)
781 * At present we just need this to push the current branch.
782 * -- maybe later it will have a few options and do more stuff..
785 public string push () throws Error, SpawnError
788 return this.git({ "push" });
796 * The meaty part.. run spawn.. with git..
801 public string git(string[] args_in ) throws Error, SpawnError
803 // convert arguments.
805 string[] args = { "git" };
806 //args += "--git-dir";
807 //args += this.gitdir;
808 args += "--no-pager";
811 //if (this.gitdir != this.repopath) {
812 // args += "--work-tree";
813 // args += this.repopath;
815 for (var i = 0; i < args_in.length;i++) {
819 //this.lastCmd = args.join(" ");
821 GLib.debug( "CWD=%s", this.git_working_dir );
822 GLib.debug( "cmd: %s", string.joinv (" ", args));
826 string home = "HOME=" + Environment.get_home_dir() ;
828 // do not need to set gitpath..
829 //if (File.exists(this.repo + '/.git/config')) {
830 //env.push("GITPATH=" + this.repo );
833 var cfg = new SpawnConfig(this.git_working_dir , args , env);
836 // may throw error...
837 var sp = new Spawn(cfg);
839 //GLib.debug( "GOT result: %d" , sp.result);
841 // diff output is a bit big..
842 if (args_in[0] != "diff") {
843 GLib.debug( "GOT: %s" , sp.output);
845 // parse output for some commands ?
849 unowned GitAsyncCallback git_async_on_callback;
850 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
852 // convert arguments.
853 this.git_async_on_callback = cb;
854 string[] args = { "git" };
855 //args += "--git-dir";
856 //args += this.gitdir;
857 args += "--no-pager";
860 //if (this.gitdir != this.repopath) {
861 // args += "--work-tree";
862 // args += this.repopath;
864 for (var i = 0; i < args_in.length;i++) {
868 //this.lastCmd = args.join(" ");
870 GLib.debug( "CWD=%s", this.git_working_dir );
871 //print( "cmd: %s\n", string.joinv (" ", args));
875 string home = "HOME=" + Environment.get_home_dir() ;
877 // do not need to set gitpath..
878 //if (File.exists(this.repo + '/.git/config')) {
879 //env.push("GITPATH=" + this.repo );
883 var cfg = new SpawnConfig(this.git_working_dir , args , env);
887 // may throw error...
888 var sp = new Spawn(cfg);
891 sp.run(this.git_async_on_complete);
895 void git_async_on_complete(int err, string output)
897 GLib.debug("GOT %d : %s", err, output);
898 this.git_async_on_callback(this, err, output);
909 public void update_async(GitAsyncCallback cb)
911 string[] cmd = { "fetch" , "--all" };
912 this.git_async( cmd , cb);
917 static uint update_all_total = 0;
918 static string update_all_after = "";
920 public static void updateAll(string after)
922 update_all_after = after;
923 var tr = GitRepo.singleton().cache;
926 update_all_total = tr.size;
927 foreach(var repo in tr.values) {
928 if (!repo.is_managed()) {
932 repo.update_async(updateAllCallback);
934 GLib.debug("calls total = %d", (int) update_all_total);
936 public static void updateAllCallback(GitRepo repo, int err, string res)
942 GLib.debug("calls remaining = %d", (int)update_all_total);
943 if (update_all_total > 0 ) {
947 GLib.debug("call after load = %s", update_all_after);
949 switch (update_all_after) {
951 Clones.singleton().show();
954 GLib.debug("Unkown call after load = %s", update_all_after);