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);
306 public bool hasBranchCalled(string name)
308 foreach( var br in this.branches.values) {
309 if (br.name == name) {
317 public string branchesToString()
320 foreach( var br in this.branches.values) {
324 ret += ret.length > 0 ? "\n" : "";
331 public static void doMerges(string action, string ticket_id, string commit_message)
333 GitMonitor.gitmonitor.stop();
337 foreach(var repo in GitRepo.singleton().cache.values) {
338 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
339 var res = repo.doMerge(action,ticket_id, commit_message);
344 commitrevs += commitrevs.length > 0 ? " " : "";
345 commitrevs += repo.currentBranch.lastrev;
348 if (sucess && action == "CLOSE") {
349 RooTicket.singleton().getById(ticket_id).close(commitrevs);
351 GitMonitor.gitmonitor.start();
355 public bool doMerge(string action, string ticket_id, string commit_message)
357 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
358 // also need to decide which branch we will merge into?
359 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
362 if (action == "CLOSE" || action == "LEAVE") {
365 var oldbranch = this.currentBranch.name;
366 this.setActiveTicket(null, master);
367 string [] cmd = { "merge", "--squash", oldbranch };
369 cmd = { "commit", "-a" , "-m", commit_message };
372 this.loadBranches(); // updates lastrev..
374 var notification = new Notify.Notification(
375 "Merged branch %s to %s".printf(oldbranch, master),
381 notification.set_timeout(5);
389 GitMonitor.gitmonitor.pauseError(e.message);
392 // error~?? -- show the error dialog...
395 if (action == "MASTER") {
396 // merge master into ours..
398 string[] cmd = { "merge", master};
400 var notification = new Notify.Notification(
401 "Merged code from %s to %s".printf(master,this.currentBranch.name),
406 notification.set_timeout(5);
411 GitMonitor.gitmonitor.pauseError(e.message);
415 if (action == "EXIT") {
417 var oldbranch = this.currentBranch.name;
418 this.setActiveTicket(null, master);
420 var notification = new Notify.Notification(
421 "Left branch %s".printf(oldbranch),
426 notification.set_timeout(5);
431 GitMonitor.gitmonitor.pauseError(e.message);
435 // error~?? -- show the error dialog...
441 public void loadActiveTicket()
443 this.activeTicket = null;
444 var ticket_id = this.get_config("ticket");
446 if (ticket_id.length < 1) {
449 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
456 public bool setActiveTicket(RooTicket? ticket, string branchname)
458 this.set_config("ticket", "");
459 if (!this.createBranchNamed(branchname)) {
462 this.set_config("ticket", ticket == null ? "": ticket.id);
463 this.activeTicket = ticket;
467 public bool createBranchNamed(string branchname)
471 if (this.branches.has_key(branchname)) {
472 this.switchToExistingBranchNamed(branchname);
475 this.createNewBranchNamed(branchname);
478 var notification = new Notify.Notification(
479 "Changed to branch %s".printf(branchname),
485 notification.set_timeout(5);
489 this.loadBranches(); // update branch list...
490 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
493 bool switchToExistingBranchNamed(string branchname)
495 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
497 // this is where it get's tricky...
500 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
501 files = this.git(cmd);
502 stash = files.length> 1 ;
506 if (stash) { this.git(cmd); }
510 cmd = { "checkout", branchname };
513 GitMonitor.gitmonitor.pauseError(e.message);
517 if (branchname != master) {
518 string[] cmd = { "merge", master };
525 string[] cmd = { "checkout", master };
527 GitMonitor.gitmonitor.pauseError(
528 "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(
536 string[] cmd = { "stash", "pop" };
539 var fl = files.split("\n");
540 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
541 foreach(var f in fl) {
542 if (f.length < 1) continue;
551 GitMonitor.gitmonitor.pauseError(ee.message);
561 bool createNewBranchNamed(string branchname)
565 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
566 var files = this.git(cmd);
567 stash = files.length> 1 ;
569 cmd = { "checkout", "-b" , branchname };
572 cmd = { "push", "-u" , "origin" ,"HEAD" };
576 var fl = files.split("\n");
577 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
578 foreach(var f in fl) {
579 if (f.length < 1) continue;
588 GitMonitor.gitmonitor.pauseError(ee.message);
595 public static string previewMerges(string ticket_id)
598 foreach(var repo in GitRepo.singleton().cache.values) {
599 if (repo.activeTicket == null || repo.activeTicket.id != ticket_id) {
602 ret += repo.previewMerge() + "\n\n";
611 public string previewMerge()
614 var master = this.hasBranchCalled("roojs") ? "roojs" : "master";
615 var lines = this.git({"log", master + "...", "--pretty=format:%H %P" }).split("\n");;
616 var head = this.git({"log", "-1", "--pretty=format:%H %P" });
617 var start = head.split(" ")[0];
619 for (var i = 0; i < lines.length; i++) {
620 var cols = lines[i].split(" ");
621 if (cols.length > 2) {
627 var last = lines[lines.length-1];
628 end = last.split(" ")[1];
631 return this.git({ "diff" , (end+".."+start), "--no-color" });
633 GitMonitor.gitmonitor.pauseError(ee.message);
634 return "Error getting diff";
644 * add files to track.
646 * @argument {Array} files the files to add.
648 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
650 // should really find out if these are untracked files each..
651 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
652 // not sure if that is how git works.. but just be certian.
654 for (var i = 0; i < files.size;i++) {
655 var f = files.get(i).vname;
657 string[] cmd = { "add", f };
660 ret += e.message + "\n";
667 public bool is_ignore(string fname) throws Error, SpawnError
669 if (fname == ".gitignore") {
670 this.ignore_files.clear();
673 if (this.ignore_files.has_key(fname)) {
674 return this.ignore_files.get(fname);
678 var ret = this.git( { "check-ignore" , fname } );
679 this.ignore_files.set(fname, ret.length > 0);
680 return ret.length > 0;
681 } catch (SpawnError e) {
682 this.ignore_files.set(fname, false);
691 * remove files to track.
693 * @argument {Array} files the files to add.
695 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
697 // this may fail if files do not exist..
698 // should really find out if these are untracked files each..
699 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
700 // not sure if that is how git works.. but just be certian.
703 for (var i = 0; i < files.size;i++) {
704 var f = files.get(i).vname;
706 string[] cmd = { "rm", "-f" , f };
709 ret += e.message + "\n";
722 * @argument {Object} cfg commit configuration
724 * @property {String} name (optional)
725 * @property {String} email (optional)
726 * @property {String} changed (date) (optional)
727 * @property {String} reason (optional)
728 * @property {Array} files - the files that have changed.
732 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
739 if (typeof(cfg.name) != 'undefined') {
741 'author' : cfg.name + ' <' + cfg.email + '>'
744 "GIT_COMMITTER_NAME" + cfg.name,
745 "GIT_COMMITTER_EMAIL" + cfg.email
749 if (typeof(cfg.changed) != 'undefined') {
750 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
754 string[] args = { "commit", "-m" };
755 args += (message.length > 0 ? message : "Changed" );
756 for (var i = 0; i< files.size ; i++ ) {
757 args += files.get(i).vname; // full path?
760 return this.git(args);
765 * Fetch and merge remote repo changes into current branch..
767 * At present we just need this to update the current working branch..
768 * -- maybe later it will have a few options and do more stuff..
771 public string pull () throws Error, SpawnError
773 // should probably hand error conditions better...
774 string[] cmd = { "pull" , "--no-edit" };
775 return this.git( cmd );
780 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
781 public void pull_async(GitAsyncCallback cb)
784 string[] cmd = { "pull" , "--no-edit" };
785 this.git_async( cmd , cb);
792 * Send local changes to remote repo(s)
794 * At present we just need this to push the current branch.
795 * -- maybe later it will have a few options and do more stuff..
798 public string push () throws Error, SpawnError
801 return this.git({ "push" });
809 * The meaty part.. run spawn.. with git..
814 public string git(string[] args_in ) throws Error, SpawnError
816 // convert arguments.
818 string[] args = { "git" };
819 //args += "--git-dir";
820 //args += this.gitdir;
821 args += "--no-pager";
824 //if (this.gitdir != this.repopath) {
825 // args += "--work-tree";
826 // args += this.repopath;
828 for (var i = 0; i < args_in.length;i++) {
832 //this.lastCmd = args.join(" ");
834 GLib.debug( "CWD=%s", this.git_working_dir );
835 GLib.debug( "cmd: %s", string.joinv (" ", args));
839 string home = "HOME=" + Environment.get_home_dir() ;
841 // do not need to set gitpath..
842 //if (File.exists(this.repo + '/.git/config')) {
843 //env.push("GITPATH=" + this.repo );
846 var cfg = new SpawnConfig(this.git_working_dir , args , env);
849 // may throw error...
850 var sp = new Spawn(cfg);
852 //GLib.debug( "GOT result: %d" , sp.result);
854 // diff output is a bit big..
855 if (args_in[0] != "diff") {
856 GLib.debug( "GOT: %s" , sp.output);
858 // parse output for some commands ?
862 unowned GitAsyncCallback git_async_on_callback;
863 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
865 // convert arguments.
866 this.git_async_on_callback = cb;
867 string[] args = { "git" };
868 //args += "--git-dir";
869 //args += this.gitdir;
870 args += "--no-pager";
873 //if (this.gitdir != this.repopath) {
874 // args += "--work-tree";
875 // args += this.repopath;
877 for (var i = 0; i < args_in.length;i++) {
881 //this.lastCmd = args.join(" ");
883 GLib.debug( "CWD=%s", this.git_working_dir );
884 //print( "cmd: %s\n", string.joinv (" ", args));
888 string home = "HOME=" + Environment.get_home_dir() ;
890 // do not need to set gitpath..
891 //if (File.exists(this.repo + '/.git/config')) {
892 //env.push("GITPATH=" + this.repo );
896 var cfg = new SpawnConfig(this.git_working_dir , args , env);
900 // may throw error...
901 var sp = new Spawn(cfg);
904 sp.run(this.git_async_on_complete);
908 void git_async_on_complete(int err, string output)
910 GLib.debug("GOT %d : %s", err, output);
911 this.git_async_on_callback(this, err, output);
922 public void update_async(GitAsyncCallback cb)
924 string[] cmd = { "fetch" , "--all" };
925 this.git_async( cmd , cb);
930 static uint update_all_total = 0;
931 static string update_all_after = "";
933 public static void updateAll(string after)
935 update_all_after = after;
936 var tr = GitRepo.singleton().cache;
939 update_all_total = tr.size;
940 foreach(var repo in tr.values) {
941 if (!repo.is_managed()) {
945 repo.update_async(updateAllCallback);
947 GLib.debug("calls total = %d", (int) update_all_total);
949 public static void updateAllCallback(GitRepo repo, int err, string res)
955 GLib.debug("calls remaining = %d", (int)update_all_total);
956 if (update_all_total > 0 ) {
960 GLib.debug("call after load = %s", update_all_after);
962 switch (update_all_after) {
964 Clones.singleton().show();
967 GLib.debug("Unkown call after load = %s", update_all_after);