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 return this.git({ "config" , "gitlive." + key });
220 return ""; // happens when there is nothing set...
224 public void set_config(string key, string value) {
225 this.git({ "config" , "gitlive." + key, value });
228 public bool is_managed()
230 return this.get_config("managed") == "1";
234 public bool is_autocommit ()
236 return this.get_config("autocommit") == "1";
239 public void set_autocommit(bool val)
241 this.set_config("autocommit", val ? "1" : "0");
245 public bool is_auto_branch ()
247 if (this.name == "gitlog") {
251 if (this.is_managed()) {
259 public void set_auto_branch(bool val)
261 if (this.name == "gitlog") {
264 this.set_config("managed", val ? "1" : "0");
267 public bool is_autopush ()
269 return this.get_config("autopush") == "1";
271 public void set_autopush(bool val)
273 this.set_config("autopush", val ? "1" : "0");
277 public void loadStatus()
279 var r = this.git({ "status" , "--porcelain" });
281 this.has_local_changes = r.length > 0;
283 var rs = this.git({ "status" , "-sb" });
285 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
288 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
292 public void loadBranches()
295 GitBranch.loadBranches(this);
301 public string branchesToString()
304 foreach( var br in this.branches.values) {
308 ret += ret.length > 0 ? "\n" : "";
315 public static void doMerges(string action, string ticket_id, string commit_message)
317 GitMonitor.gitmonitor.stop();
321 foreach(var repo in GitRepo.singleton().cache.values) {
322 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
323 var res = repo.doMerge(action,ticket_id, commit_message);
328 commitrevs += commitrevs.length > 0 ? " " : "";
329 commitrevs += repo.currentBranch.lastrev;
332 if (sucess && action == "CLOSE") {
333 RooTicket.singleton().getById(ticket_id).close(commitrevs);
335 GitMonitor.gitmonitor.start();
339 public bool doMerge(string action, string ticket_id, string commit_message)
341 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
342 // also need to decide which branch we will merge into?
344 if (action == "CLOSE" || action == "LEAVE") {
347 var oldbranch = this.currentBranch.name;
348 this.setActiveTicket(null, "master");
349 string [] cmd = { "merge", "--squash", oldbranch };
351 cmd = { "commit", "-a" , "-m", commit_message };
354 this.loadBranches(); // updates lastrev..
356 var notification = new Notify.Notification(
357 "Merged branch %s to master".printf(oldbranch),
363 notification.set_timeout(5);
371 GitMonitor.gitmonitor.pauseError(e.message);
374 // error~?? -- show the error dialog...
377 if (action == "MASTER") {
378 // merge master into ours..
380 string[] cmd = { "merge", "master" };
382 var notification = new Notify.Notification(
383 "Merged code from master to %s".printf(this.currentBranch.name),
388 notification.set_timeout(5);
393 GitMonitor.gitmonitor.pauseError(e.message);
397 if (action == "EXIT") {
399 var oldbranch = this.currentBranch.name;
400 this.setActiveTicket(null, "master");
402 var notification = new Notify.Notification(
403 "Left branch %s".printf(oldbranch),
408 notification.set_timeout(5);
413 GitMonitor.gitmonitor.pauseError(e.message);
417 // error~?? -- show the error dialog...
423 public void loadActiveTicket()
425 this.activeTicket = null;
426 var ticket_id = this.get_config("ticket");
428 if (ticket_id.length < 1) {
431 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
438 public bool setActiveTicket(RooTicket? ticket, string branchname)
440 this.set_config("ticket", "");
441 if (!this.createBranchNamed(branchname)) {
444 this.set_config("ticket", ticket == null ? "": ticket.id);
445 this.activeTicket = ticket;
449 public bool createBranchNamed(string branchname)
453 if (this.branches.has_key(branchname)) {
454 this.switchToExistingBranchNamed(branchname);
457 this.createNewBranchNamed(branchname);
460 var notification = new Notify.Notification(
461 "Changed to branch %s".printf(branchname),
467 notification.set_timeout(5);
471 this.loadBranches(); // update branch list...
472 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
475 bool switchToExistingBranchNamed(string branchname)
478 // this is where it get's tricky...
481 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
482 files = this.git(cmd);
483 stash = files.length> 1 ;
487 if (stash) { this.git(cmd); }
491 cmd = { "checkout", branchname };
494 GitMonitor.gitmonitor.pauseError(e.message);
498 if (branchname != "master") {
499 string[] cmd = { "merge", "master" };
506 string[] cmd = { "checkout", "master" };
508 GitMonitor.gitmonitor.pauseError(
509 "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(
517 string[] cmd = { "stash", "pop" };
520 var fl = files.split("\n");
521 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
522 foreach(var f in fl) {
523 if (f.length < 1) continue;
532 GitMonitor.gitmonitor.pauseError(ee.message);
542 bool createNewBranchNamed(string branchname)
546 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
547 var files = this.git(cmd);
548 stash = files.length> 1 ;
550 cmd = { "checkout", "-b" , branchname };
553 cmd = { "push", "-u" , "origin" ,"HEAD" };
557 var fl = files.split("\n");
558 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
559 foreach(var f in fl) {
560 if (f.length < 1) continue;
569 GitMonitor.gitmonitor.pauseError(ee.message);
580 * add files to track.
582 * @argument {Array} files the files to add.
584 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
586 // should really find out if these are untracked files each..
587 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
588 // not sure if that is how git works.. but just be certian.
590 for (var i = 0; i < files.size;i++) {
591 var f = files.get(i).vname;
593 string[] cmd = { "add", f };
596 ret += e.message + "\n";
603 public bool is_ignore(string fname) throws Error, SpawnError
605 if (fname == ".gitignore") {
606 this.ignore_files.clear();
609 if (this.ignore_files.has_key(fname)) {
610 return this.ignore_files.get(fname);
614 var ret = this.git( { "check-ignore" , fname } );
615 this.ignore_files.set(fname, ret.length > 0);
616 return ret.length > 0;
617 } catch (SpawnError e) {
618 this.ignore_files.set(fname, false);
627 * remove files to track.
629 * @argument {Array} files the files to add.
631 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
633 // this may fail if files do not exist..
634 // should really find out if these are untracked files each..
635 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
636 // not sure if that is how git works.. but just be certian.
639 for (var i = 0; i < files.size;i++) {
640 var f = files.get(i).vname;
642 string[] cmd = { "rm", "-f" , f };
645 ret += e.message + "\n";
658 * @argument {Object} cfg commit configuration
660 * @property {String} name (optional)
661 * @property {String} email (optional)
662 * @property {String} changed (date) (optional)
663 * @property {String} reason (optional)
664 * @property {Array} files - the files that have changed.
668 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
675 if (typeof(cfg.name) != 'undefined') {
677 'author' : cfg.name + ' <' + cfg.email + '>'
680 "GIT_COMMITTER_NAME" + cfg.name,
681 "GIT_COMMITTER_EMAIL" + cfg.email
685 if (typeof(cfg.changed) != 'undefined') {
686 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
690 string[] args = { "commit", "-m" };
691 args += (message.length > 0 ? message : "Changed" );
692 for (var i = 0; i< files.size ; i++ ) {
693 args += files.get(i).vname; // full path?
696 return this.git(args);
701 * Fetch and merge remote repo changes into current branch..
703 * At present we just need this to update the current working branch..
704 * -- maybe later it will have a few options and do more stuff..
707 public string pull () throws Error, SpawnError
709 // should probably hand error conditions better...
710 string[] cmd = { "pull" , "--no-edit" };
711 return this.git( cmd );
716 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
717 public void pull_async(GitAsyncCallback cb)
720 string[] cmd = { "pull" , "--no-edit" };
721 this.git_async( cmd , cb);
728 * Send local changes to remote repo(s)
730 * At present we just need this to push the current branch.
731 * -- maybe later it will have a few options and do more stuff..
734 public string push () throws Error, SpawnError
737 return this.git({ "push" });
745 * The meaty part.. run spawn.. with git..
750 public string git(string[] args_in ) throws Error, SpawnError
752 // convert arguments.
754 string[] args = { "git" };
755 //args += "--git-dir";
756 //args += this.gitdir;
757 args += "--no-pager";
760 //if (this.gitdir != this.repopath) {
761 // args += "--work-tree";
762 // args += this.repopath;
764 for (var i = 0; i < args_in.length;i++) {
768 //this.lastCmd = args.join(" ");
770 GLib.debug( "CWD=%s", this.git_working_dir );
771 GLib.debug( "cmd: %s", string.joinv (" ", args));
775 string home = "HOME=" + Environment.get_home_dir() ;
777 // do not need to set gitpath..
778 //if (File.exists(this.repo + '/.git/config')) {
779 //env.push("GITPATH=" + this.repo );
782 var cfg = new SpawnConfig(this.git_working_dir , args , env);
785 // may throw error...
786 var sp = new Spawn(cfg);
788 //GLib.debug( "GOT result: %d" , sp.result);
790 // diff output is a bit big..
791 if (args_in[0] != "diff") {
792 GLib.debug( "GOT: %s" , sp.output);
794 // parse output for some commands ?
798 unowned GitAsyncCallback git_async_on_callback;
799 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
801 // convert arguments.
802 this.git_async_on_callback = cb;
803 string[] args = { "git" };
804 //args += "--git-dir";
805 //args += this.gitdir;
806 args += "--no-pager";
809 //if (this.gitdir != this.repopath) {
810 // args += "--work-tree";
811 // args += this.repopath;
813 for (var i = 0; i < args_in.length;i++) {
817 //this.lastCmd = args.join(" ");
819 GLib.debug( "CWD=%s", this.git_working_dir );
820 //print( "cmd: %s\n", string.joinv (" ", args));
824 string home = "HOME=" + Environment.get_home_dir() ;
826 // do not need to set gitpath..
827 //if (File.exists(this.repo + '/.git/config')) {
828 //env.push("GITPATH=" + this.repo );
832 var cfg = new SpawnConfig(this.git_working_dir , args , env);
836 // may throw error...
837 var sp = new Spawn(cfg);
840 sp.run(this.git_async_on_complete);
844 void git_async_on_complete(int err, string output)
846 GLib.debug("GOT %d : %s", err, output);
847 this.git_async_on_callback(this, err, output);
858 public void update_async(GitAsyncCallback cb)
860 string[] cmd = { "fetch" , "--all" };
861 this.git_async( cmd , cb);
866 static uint update_all_total = 0;
867 static string update_all_after = "";
869 public static void updateAll(string after)
871 update_all_after = after;
872 var tr = GitRepo.singleton().cache;
875 update_all_total = tr.size;
876 foreach(var repo in tr.values) {
877 if (!repo.is_managed()) {
881 repo.update_async(updateAllCallback);
883 GLib.debug("calls total = %d", (int) update_all_total);
885 public static void updateAllCallback(GitRepo repo, int err, string res)
891 GLib.debug("calls remaining = %d", (int)update_all_total);
892 if (update_all_total > 0 ) {
896 switch (update_all_after) {
898 Clones.singleton().show();