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 return this.config_cache.get(key);
218 var ret = this.git({ "config" , "gitlive." + key });
219 this.config_cache.set(key, ret);
222 this.config_cache.set(key, "");
223 return ""; // happens when there is nothing set...
227 public void set_config(string key, string value) {
228 this.git({ "config" , "gitlive." + key, value });
229 this.config_cache.set(key,value);
232 public bool is_managed()
234 return this.get_config("managed") == "1";
238 public bool is_autocommit ()
240 return this.get_config("autocommit") == "1";
243 public void set_autocommit(bool val)
245 this.set_config("autocommit", val ? "1" : "0");
249 public bool is_auto_branch ()
251 if (this.name == "gitlog") {
255 if (this.is_managed()) {
263 public void set_auto_branch(bool val)
265 if (this.name == "gitlog") {
268 this.set_config("managed", val ? "1" : "0");
271 public bool is_autopush ()
273 return this.get_config("autopush") == "1";
275 public void set_autopush(bool val)
277 this.set_config("autopush", val ? "1" : "0");
281 public void loadStatus()
283 var r = this.git({ "status" , "--porcelain" });
285 this.has_local_changes = r.length > 0;
287 var rs = this.git({ "status" , "-sb" });
289 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
292 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
296 public void loadBranches()
299 GitBranch.loadBranches(this);
305 public string branchesToString()
308 foreach( var br in this.branches.values) {
312 ret += ret.length > 0 ? "\n" : "";
319 public static void doMerges(string action, string ticket_id, string commit_message)
321 GitMonitor.gitmonitor.stop();
325 foreach(var repo in GitRepo.singleton().cache.values) {
326 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
327 var res = repo.doMerge(action,ticket_id, commit_message);
332 commitrevs += commitrevs.length > 0 ? " " : "";
333 commitrevs += repo.currentBranch.lastrev;
336 if (sucess && action == "CLOSE") {
337 RooTicket.singleton().getById(ticket_id).close(commitrevs);
339 GitMonitor.gitmonitor.start();
343 public bool doMerge(string action, string ticket_id, string commit_message)
345 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
346 // also need to decide which branch we will merge into?
348 if (action == "CLOSE" || action == "LEAVE") {
351 var oldbranch = this.currentBranch.name;
352 this.setActiveTicket(null, "master");
353 string [] cmd = { "merge", "--squash", oldbranch };
355 cmd = { "commit", "-a" , "-m", commit_message };
358 this.loadBranches(); // updates lastrev..
360 var notification = new Notify.Notification(
361 "Merged branch %s to master".printf(oldbranch),
367 notification.set_timeout(5);
375 GitMonitor.gitmonitor.pauseError(e.message);
378 // error~?? -- show the error dialog...
381 if (action == "MASTER") {
382 // merge master into ours..
384 string[] cmd = { "merge", "master" };
386 var notification = new Notify.Notification(
387 "Merged code from master to %s".printf(this.currentBranch.name),
392 notification.set_timeout(5);
397 GitMonitor.gitmonitor.pauseError(e.message);
401 if (action == "EXIT") {
403 var oldbranch = this.currentBranch.name;
404 this.setActiveTicket(null, "master");
406 var notification = new Notify.Notification(
407 "Left branch %s".printf(oldbranch),
412 notification.set_timeout(5);
417 GitMonitor.gitmonitor.pauseError(e.message);
421 // error~?? -- show the error dialog...
427 public void loadActiveTicket()
429 this.activeTicket = null;
430 var ticket_id = this.get_config("ticket");
432 if (ticket_id.length < 1) {
435 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
442 public bool setActiveTicket(RooTicket? ticket, string branchname)
444 this.set_config("ticket", "");
445 if (!this.createBranchNamed(branchname)) {
448 this.set_config("ticket", ticket == null ? "": ticket.id);
449 this.activeTicket = ticket;
453 public bool createBranchNamed(string branchname)
457 if (this.branches.has_key(branchname)) {
458 this.switchToExistingBranchNamed(branchname);
461 this.createNewBranchNamed(branchname);
464 var notification = new Notify.Notification(
465 "Changed to branch %s".printf(branchname),
471 notification.set_timeout(5);
475 this.loadBranches(); // update branch list...
476 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
479 bool switchToExistingBranchNamed(string branchname)
482 // this is where it get's tricky...
485 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
486 files = this.git(cmd);
487 stash = files.length> 1 ;
491 if (stash) { this.git(cmd); }
495 cmd = { "checkout", branchname };
498 GitMonitor.gitmonitor.pauseError(e.message);
502 if (branchname != "master") {
503 string[] cmd = { "merge", "master" };
510 string[] cmd = { "checkout", "master" };
512 GitMonitor.gitmonitor.pauseError(
513 "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(
521 string[] cmd = { "stash", "pop" };
524 var fl = files.split("\n");
525 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
526 foreach(var f in fl) {
527 if (f.length < 1) continue;
536 GitMonitor.gitmonitor.pauseError(ee.message);
546 bool createNewBranchNamed(string branchname)
550 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
551 var files = this.git(cmd);
552 stash = files.length> 1 ;
554 cmd = { "checkout", "-b" , branchname };
557 cmd = { "push", "-u" , "origin" ,"HEAD" };
561 var fl = files.split("\n");
562 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
563 foreach(var f in fl) {
564 if (f.length < 1) continue;
573 GitMonitor.gitmonitor.pauseError(ee.message);
584 * add files to track.
586 * @argument {Array} files the files to add.
588 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
590 // should really find out if these are untracked files each..
591 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
592 // not sure if that is how git works.. but just be certian.
594 for (var i = 0; i < files.size;i++) {
595 var f = files.get(i).vname;
597 string[] cmd = { "add", f };
600 ret += e.message + "\n";
607 public bool is_ignore(string fname) throws Error, SpawnError
609 if (fname == ".gitignore") {
610 this.ignore_files.clear();
613 if (this.ignore_files.has_key(fname)) {
614 return this.ignore_files.get(fname);
618 var ret = this.git( { "check-ignore" , fname } );
619 this.ignore_files.set(fname, ret.length > 0);
620 return ret.length > 0;
621 } catch (SpawnError e) {
622 this.ignore_files.set(fname, false);
631 * remove files to track.
633 * @argument {Array} files the files to add.
635 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
637 // this may fail if files do not exist..
638 // should really find out if these are untracked files each..
639 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
640 // not sure if that is how git works.. but just be certian.
643 for (var i = 0; i < files.size;i++) {
644 var f = files.get(i).vname;
646 string[] cmd = { "rm", "-f" , f };
649 ret += e.message + "\n";
662 * @argument {Object} cfg commit configuration
664 * @property {String} name (optional)
665 * @property {String} email (optional)
666 * @property {String} changed (date) (optional)
667 * @property {String} reason (optional)
668 * @property {Array} files - the files that have changed.
672 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
679 if (typeof(cfg.name) != 'undefined') {
681 'author' : cfg.name + ' <' + cfg.email + '>'
684 "GIT_COMMITTER_NAME" + cfg.name,
685 "GIT_COMMITTER_EMAIL" + cfg.email
689 if (typeof(cfg.changed) != 'undefined') {
690 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
694 string[] args = { "commit", "-m" };
695 args += (message.length > 0 ? message : "Changed" );
696 for (var i = 0; i< files.size ; i++ ) {
697 args += files.get(i).vname; // full path?
700 return this.git(args);
705 * Fetch and merge remote repo changes into current branch..
707 * At present we just need this to update the current working branch..
708 * -- maybe later it will have a few options and do more stuff..
711 public string pull () throws Error, SpawnError
713 // should probably hand error conditions better...
714 string[] cmd = { "pull" , "--no-edit" };
715 return this.git( cmd );
720 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
721 public void pull_async(GitAsyncCallback cb)
724 string[] cmd = { "pull" , "--no-edit" };
725 this.git_async( cmd , cb);
732 * Send local changes to remote repo(s)
734 * At present we just need this to push the current branch.
735 * -- maybe later it will have a few options and do more stuff..
738 public string push () throws Error, SpawnError
741 return this.git({ "push" });
749 * The meaty part.. run spawn.. with git..
754 public string git(string[] args_in ) throws Error, SpawnError
756 // convert arguments.
758 string[] args = { "git" };
759 //args += "--git-dir";
760 //args += this.gitdir;
761 args += "--no-pager";
764 //if (this.gitdir != this.repopath) {
765 // args += "--work-tree";
766 // args += this.repopath;
768 for (var i = 0; i < args_in.length;i++) {
772 //this.lastCmd = args.join(" ");
774 GLib.debug( "CWD=%s", this.git_working_dir );
775 GLib.debug( "cmd: %s", string.joinv (" ", args));
779 string home = "HOME=" + Environment.get_home_dir() ;
781 // do not need to set gitpath..
782 //if (File.exists(this.repo + '/.git/config')) {
783 //env.push("GITPATH=" + this.repo );
786 var cfg = new SpawnConfig(this.git_working_dir , args , env);
789 // may throw error...
790 var sp = new Spawn(cfg);
792 //GLib.debug( "GOT result: %d" , sp.result);
794 // diff output is a bit big..
795 if (args_in[0] != "diff") {
796 GLib.debug( "GOT: %s" , sp.output);
798 // parse output for some commands ?
802 unowned GitAsyncCallback git_async_on_callback;
803 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
805 // convert arguments.
806 this.git_async_on_callback = cb;
807 string[] args = { "git" };
808 //args += "--git-dir";
809 //args += this.gitdir;
810 args += "--no-pager";
813 //if (this.gitdir != this.repopath) {
814 // args += "--work-tree";
815 // args += this.repopath;
817 for (var i = 0; i < args_in.length;i++) {
821 //this.lastCmd = args.join(" ");
823 GLib.debug( "CWD=%s", this.git_working_dir );
824 //print( "cmd: %s\n", string.joinv (" ", args));
828 string home = "HOME=" + Environment.get_home_dir() ;
830 // do not need to set gitpath..
831 //if (File.exists(this.repo + '/.git/config')) {
832 //env.push("GITPATH=" + this.repo );
836 var cfg = new SpawnConfig(this.git_working_dir , args , env);
840 // may throw error...
841 var sp = new Spawn(cfg);
844 sp.run(this.git_async_on_complete);
848 void git_async_on_complete(int err, string output)
850 GLib.debug("GOT %d : %s", err, output);
851 this.git_async_on_callback(this, err, output);
862 public void update_async(GitAsyncCallback cb)
864 string[] cmd = { "fetch" , "--all" };
865 this.git_async( cmd , cb);
870 static uint update_all_total = 0;
871 static string update_all_after = "";
873 public static void updateAll(string after)
875 update_all_after = after;
876 var tr = GitRepo.singleton().cache;
879 update_all_total = tr.size;
880 foreach(var repo in tr.values) {
881 if (!repo.is_managed()) {
885 repo.update_async(updateAllCallback);
887 GLib.debug("calls total = %d", (int) update_all_total);
889 public static void updateAllCallback(GitRepo repo, int err, string res)
895 GLib.debug("calls remaining = %d", (int)update_all_total);
896 if (update_all_total > 0 ) {
902 switch (update_all_after) {
904 Clones.singleton().show();
907 GLib.debug("Unkown call after load = %s", update_after_all);