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 return this.git({ "config" , "gitlive." + key });
216 return ""; // happens when there is nothing set...
220 public void set_config(string key, string value) {
221 this.git({ "config" , "gitlive." + key, value });
224 public bool is_managed()
226 return this.get_config("managed") == "1";
230 public bool is_autocommit ()
232 return this.get_config("autocommit") == "1";
235 public void set_autocommit(bool val)
237 this.set_config("autocommit", val ? "1" : "0");
241 public bool is_auto_branch ()
243 if (this.name == "gitlog") {
247 if (this.is_managed()) {
255 public void set_auto_branch(bool val)
257 if (this.name == "gitlog") {
260 this.set_config("managed", val ? "1" : "0");
263 public bool is_autopush ()
265 return this.get_config("autopush") == "1";
267 public void set_autopush(bool val)
269 this.set_config("autopush", val ? "1" : "0");
273 public void loadStatus()
275 var r = this.git({ "status" , "--porcelain" });
277 this.has_local_changes = r.length > 0;
279 var rs = this.git({ "status" , "-sb" });
281 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
284 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
288 public void loadBranches()
291 GitBranch.loadBranches(this);
297 public string branchesToString()
300 foreach( var br in this.branches.values) {
304 ret += ret.length > 0 ? "\n" : "";
311 public static void doMerges(string action, string ticket_id, string commit_message)
313 GitMonitor.gitmonitor.stop();
317 foreach(var repo in GitRepo.singleton().cache.values) {
318 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
319 var res = repo.doMerge(action,ticket_id, commit_message);
324 commitrevs += commitrevs.length > 0 ? " " : "";
325 commitrevs += repo.currentBranch.lastrev;
328 if (sucess && action == "CLOSE") {
329 RooTicket.singleton().getById(ticket_id).close(commitrevs);
331 GitMonitor.gitmonitor.start();
335 public bool doMerge(string action, string ticket_id, string commit_message)
337 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
338 // also need to decide which branch we will merge into?
340 if (action == "CLOSE" || action == "LEAVE") {
343 var oldbranch = this.currentBranch.name;
344 this.setActiveTicket(null, "master");
345 string [] cmd = { "merge", "--squash", oldbranch };
347 cmd = { "commit", "-a" , "-m", commit_message };
350 this.loadBranches(); // updates lastrev..
352 var notification = new Notify.Notification(
353 "Merged branch %s to master".printf(oldbranch),
359 notification.set_timeout(5);
367 GitMonitor.gitmonitor.pauseError(e.message);
370 // error~?? -- show the error dialog...
373 if (action == "MASTER") {
374 // merge master into ours..
376 string[] cmd = { "merge", "master" };
378 var notification = new Notify.Notification(
379 "Merged code from master to %s".printf(this.currentBranch.name),
384 notification.set_timeout(5);
389 GitMonitor.gitmonitor.pauseError(e.message);
393 if (action == "EXIT") {
395 var oldbranch = this.currentBranch.name;
396 this.setActiveTicket(null, "master");
398 var notification = new Notify.Notification(
399 "Left branch %s".printf(oldbranch),
404 notification.set_timeout(5);
409 GitMonitor.gitmonitor.pauseError(e.message);
413 // error~?? -- show the error dialog...
419 public void loadActiveTicket()
421 this.activeTicket = null;
422 var ticket_id = this.get_config("ticket");
424 if (ticket_id.length < 1) {
427 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
434 public bool setActiveTicket(RooTicket? ticket, string branchname)
436 this.set_config("ticket", "");
437 if (!this.createBranchNamed(branchname)) {
440 this.set_config("ticket", ticket == null ? "": ticket.id);
441 this.activeTicket = ticket;
445 public bool createBranchNamed(string branchname)
449 if (this.branches.has_key(branchname)) {
450 this.switchToExistingBranchNamed(branchname);
453 this.createNewBranchNamed(branchname);
456 var notification = new Notify.Notification(
457 "Changed to branch %s".printf(branchname),
463 notification.set_timeout(5);
467 this.loadBranches(); // update branch list...
468 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
471 bool switchToExistingBranchNamed(string branchname)
474 // this is where it get's tricky...
477 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
478 files = this.git(cmd);
479 stash = files.length> 1 ;
483 if (stash) { this.git(cmd); }
487 cmd = { "checkout", branchname };
490 GitMonitor.gitmonitor.pauseError(e.message);
494 if (branchname != "master") {
495 string[] cmd = { "merge", "master" };
502 string[] cmd = { "checkout", "master" };
504 GitMonitor.gitmonitor.pauseError(
505 "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(
513 string[] cmd = { "stash", "pop" };
516 var fl = files.split("\n");
517 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
518 foreach(var f in fl) {
519 if (f.length < 1) continue;
528 GitMonitor.gitmonitor.pauseError(ee.message);
538 bool createNewBranchNamed(string branchname)
542 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
543 var files = this.git(cmd);
544 stash = files.length> 1 ;
546 cmd = { "checkout", "-b" , branchname };
549 cmd = { "push", "-u" , "origin" ,"HEAD" };
553 var fl = files.split("\n");
554 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
555 foreach(var f in fl) {
556 if (f.length < 1) continue;
565 GitMonitor.gitmonitor.pauseError(ee.message);
576 * add files to track.
578 * @argument {Array} files the files to add.
580 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
582 // should really find out if these are untracked files each..
583 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
584 // not sure if that is how git works.. but just be certian.
586 for (var i = 0; i < files.size;i++) {
587 var f = files.get(i).vname;
589 string[] cmd = { "add", f };
592 ret += e.message + "\n";
599 public bool is_ignore(string fname) throws Error, SpawnError
601 if (fname == ".gitignore") {
602 this.ignore_files.clear();
605 if (this.ignore_files.has_key(fname)) {
606 return this.ignore_files.get(fname);
610 var ret = this.git( { "check-ignore" , fname } );
611 this.ignore_files.set(fname, ret.length > 0);
612 return ret.length > 0;
613 } catch (SpawnError e) {
614 this.ignore_files.set(fname, false);
623 * remove files to track.
625 * @argument {Array} files the files to add.
627 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
629 // this may fail if files do not exist..
630 // should really find out if these are untracked files each..
631 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
632 // not sure if that is how git works.. but just be certian.
635 for (var i = 0; i < files.size;i++) {
636 var f = files.get(i).vname;
638 string[] cmd = { "rm", "-f" , f };
641 ret += e.message + "\n";
654 * @argument {Object} cfg commit configuration
656 * @property {String} name (optional)
657 * @property {String} email (optional)
658 * @property {String} changed (date) (optional)
659 * @property {String} reason (optional)
660 * @property {Array} files - the files that have changed.
664 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
671 if (typeof(cfg.name) != 'undefined') {
673 'author' : cfg.name + ' <' + cfg.email + '>'
676 "GIT_COMMITTER_NAME" + cfg.name,
677 "GIT_COMMITTER_EMAIL" + cfg.email
681 if (typeof(cfg.changed) != 'undefined') {
682 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
686 string[] args = { "commit", "-m" };
687 args += (message.length > 0 ? message : "Changed" );
688 for (var i = 0; i< files.size ; i++ ) {
689 args += files.get(i).vname; // full path?
692 return this.git(args);
697 * Fetch and merge remote repo changes into current branch..
699 * At present we just need this to update the current working branch..
700 * -- maybe later it will have a few options and do more stuff..
703 public string pull () throws Error, SpawnError
705 // should probably hand error conditions better...
706 string[] cmd = { "pull" , "--no-edit" };
707 return this.git( cmd );
712 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
713 public void pull_async(GitAsyncCallback cb)
716 string[] cmd = { "pull" , "--no-edit" };
717 this.git_async( cmd , cb);
724 * Send local changes to remote repo(s)
726 * At present we just need this to push the current branch.
727 * -- maybe later it will have a few options and do more stuff..
730 public string push () throws Error, SpawnError
733 return this.git({ "push" });
741 * The meaty part.. run spawn.. with git..
746 public string git(string[] args_in ) throws Error, SpawnError
748 // convert arguments.
750 string[] args = { "git" };
751 //args += "--git-dir";
752 //args += this.gitdir;
753 args += "--no-pager";
756 //if (this.gitdir != this.repopath) {
757 // args += "--work-tree";
758 // args += this.repopath;
760 for (var i = 0; i < args_in.length;i++) {
764 //this.lastCmd = args.join(" ");
766 GLib.debug( "CWD=%s", this.git_working_dir );
767 GLib.debug( "cmd: %s", string.joinv (" ", args));
771 string home = "HOME=" + Environment.get_home_dir() ;
773 // do not need to set gitpath..
774 //if (File.exists(this.repo + '/.git/config')) {
775 //env.push("GITPATH=" + this.repo );
778 var cfg = new SpawnConfig(this.git_working_dir , args , env);
781 // may throw error...
782 var sp = new Spawn(cfg);
784 //GLib.debug( "GOT result: %d" , sp.result);
786 // diff output is a bit big..
787 if (args_in[0] != "diff") {
788 GLib.debug( "GOT: %s" , sp.output);
790 // parse output for some commands ?
794 unowned GitAsyncCallback git_async_on_callback;
795 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
797 // convert arguments.
798 this.git_async_on_callback = cb;
799 string[] args = { "git" };
800 //args += "--git-dir";
801 //args += this.gitdir;
802 args += "--no-pager";
805 //if (this.gitdir != this.repopath) {
806 // args += "--work-tree";
807 // args += this.repopath;
809 for (var i = 0; i < args_in.length;i++) {
813 //this.lastCmd = args.join(" ");
815 GLib.debug( "CWD=%s", this.git_working_dir );
816 //print( "cmd: %s\n", string.joinv (" ", args));
820 string home = "HOME=" + Environment.get_home_dir() ;
822 // do not need to set gitpath..
823 //if (File.exists(this.repo + '/.git/config')) {
824 //env.push("GITPATH=" + this.repo );
828 var cfg = new SpawnConfig(this.git_working_dir , args , env);
832 // may throw error...
833 var sp = new Spawn(cfg);
836 sp.run(this.git_async_on_complete);
840 void git_async_on_complete(int err, string output)
842 GLib.debug("GOT %d : %s", err, output);
843 this.git_async_on_callback(this, err, output);
854 public void update_async(GitAsyncCallback cb)
856 string[] cmd = { "fetch" , "--all" };
857 this.git_async( cmd , cb);
862 static uint update_all_total = 0;
863 static string update_all_after = "";
865 public static void updateAll(string after)
867 update_all_after = after;
868 var tr = GitRepo.singleton().cache;
871 update_all_total = tr.size;
872 foreach(var repo in tr.values) {
873 if (!repo.is_managed()) {
877 repo.update_async(updateAllCallback);
879 GLib.debug("calls total = %d", (int) update_all_total);
881 public static void updateAllCallback(GitRepo repo, int err, string res)
887 GLib.debug("calls remaining = %d", (int)update_all_total);
888 if (update_all_total > 0 ) {
892 switch (update_all_after) {
894 Clones.singleton().show();