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;
35 public static GitRepo singleton()
37 if (_GitRepo == null) {
38 _GitRepo = new GitRepo.single();
39 _GitRepo.cache = new Gee.HashMap<string,GitRepo>();
45 * index of.. matching gitpath..
47 public static int indexOf( Array<GitRepo> repos, string gitpath) {
48 // make a fake object to compare against..
49 var test_repo = GitRepo.get(gitpath);
51 for(var i =0; i < repos.length; i++) {
52 if (repos.index(i).gitdir == test_repo.gitdir) {
64 public static Array<GitRepo> list()
67 //if (GitRepo.list_cache != null) {
68 // unowned Array<GitRepo> ret = GitRepo.list_cache;
71 var cache = GitRepo.singleton().cache;
72 var list_cache = new Array<GitRepo>();
74 var dir = Environment.get_home_dir() + "/gitlive";
76 var f = File.new_for_path(dir);
77 FileEnumerator file_enum;
79 file_enum = f.enumerate_children(
80 FileAttribute.STANDARD_DISPLAY_NAME + ","+
81 FileAttribute.STANDARD_TYPE,
82 FileQueryInfoFlags.NONE,
95 next_file = file_enum.next_file(null);
96 if (next_file == null) {
101 GLib.debug("Error: %s",e.message);
105 //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
107 if (next_file.get_file_type() != FileType.DIRECTORY) {
112 if (next_file.get_file_type() == FileType.SYMBOLIC_LINK) {
117 if (next_file.get_display_name()[0] == '.') {
121 var sp = dir+"/"+next_file.get_display_name();
123 var gitdir = dir + "/" + next_file.get_display_name() + "/.git";
125 if (!FileUtils.test(gitdir, FileTest.IS_DIR)) {
129 var rep = GitRepo.get( sp );
130 list_cache.append_val(rep);
138 public static GitRepo get(string path)
140 var cache = GitRepo.singleton().cache;
141 if (cache.has_key(path)) {
142 return cache.get(path);
144 return new GitRepo(path);
147 private GitRepo.single() {
148 // used to create the signleton
153 * @param {Object} cfg - Configuration
154 * (basically repopath is currently only critical one.)
158 private GitRepo(string path) {
160 this.name = File.new_for_path(path).get_basename();
161 this.ignore_files = new Gee.HashMap<string,bool>();
163 this.git_working_dir = path;
164 this.gitdir = path + "/.git";
165 if (!FileUtils.test(this.gitdir , FileTest.IS_DIR)) {
166 this.gitdir = path; // naked...
168 this.cmds = new Gee.ArrayList<GitMonitorQueue> ();
170 var cache = GitRepo.singleton().cache;
171 //Repo.superclass.constructor.call(this,cfg);
172 if ( !cache.has_key(path) ) {
173 cache.set( path, this);
176 var r = this.git({ "remote" , "get-url" , "--push" , "origin"});
177 var uri = new Soup.URI(r);
178 this.host = uri.get_host();
182 this.loadActiveTicket();
186 public bool is_master_branch()
188 // special branches that do not allow autopushing now...
189 return this.currentBranch.name == "master" || this.currentBranch.name == "roojs";
192 public void init_config()
195 if (this.get_config("managed") == "") {
196 this.set_config("managed", this.host == "git.roojs.com" ? "1" : "0");
198 if (this.get_config("autocommit") == "") {
199 this.set_config("autocommit", this.host == "git.roojs.com" ? "1" : "0");
201 if (this.get_config("autopush") == "") {
202 this.set_config("autopush", this.host == "git.roojs.com" ? "1" : "0");
208 public string get_config(string key) {
210 return this.git({ "config" , "gitlive." + key });
212 return ""; // happens when there is nothing set...
216 public void set_config(string key, string value) {
217 this.git({ "config" , "gitlive." + key, value });
220 public bool is_managed()
222 return this.get_config("managed") == "1";
226 public bool is_autocommit ()
228 return this.get_config("autocommit") == "1";
231 public void set_autocommit(bool val)
233 this.set_config("autocommit", val ? "1" : "0");
237 public bool is_auto_branch ()
239 if (this.name == "gitlog") {
243 if (this.is_managed()) {
251 public void set_auto_branch(bool val)
253 if (this.name == "gitlog") {
256 this.set_config("managed", val ? "1" : "0");
259 public bool is_autopush ()
261 return this.get_config("autopush") == "1";
263 public void set_autopush(bool val)
265 this.set_config("autopush", val ? "1" : "0");
269 public void loadStatus()
271 var r = this.git({ "status" , "--porcelain" });
273 this.has_local_changes = r.length > 0;
275 var rs = this.git({ "status" , "-sb" });
277 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
280 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
284 public void loadBranches()
287 GitBranch.loadBranches(this);
293 public string branchesToString()
296 foreach( var br in this.branches.values) {
300 ret += ret.length > 0 ? "\n" : "";
307 public static void doMerges(string action, string ticket_id, string commit_message)
309 GitMonitor.gitmonitor.stop();
313 foreach(var repo in GitRepo.singleton().cache.values) {
314 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
315 var res = repo.doMerge(action,ticket_id, commit_message);
320 commitrevs += commitrevs.length > 0 ? " " : "";
321 commitrevs += repo.currentBranch.lastrev;
324 if (sucess && action == "CLOSE") {
325 RooTicket.singleton().getById(ticket_id).close(commitrevs);
327 GitMonitor.gitmonitor.start();
331 public bool doMerge(string action, string ticket_id, string commit_message)
333 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
334 // also need to decide which branch we will merge into?
336 if (action == "CLOSE" || action == "LEAVE") {
339 var oldbranch = this.currentBranch.name;
340 this.setActiveTicket(null, "master");
341 string [] cmd = { "merge", "--squash", oldbranch };
343 cmd = { "commit", "-a" , "-m", commit_message };
346 this.loadBranches(); // updates lastrev..
348 var notification = new Notify.Notification(
349 "Merged branch %s to master".printf(oldbranch),
355 notification.set_timeout(5);
363 GitMonitor.gitmonitor.pauseError(e.message);
366 // error~?? -- show the error dialog...
369 if (action == "MASTER") {
370 // merge master into ours..
372 string[] cmd = { "merge", "master" };
374 var notification = new Notify.Notification(
375 "Merged code from master to %s".printf(this.currentBranch.name),
380 notification.set_timeout(5);
385 GitMonitor.gitmonitor.pauseError(e.message);
389 if (action == "EXIT") {
391 var oldbranch = this.currentBranch.name;
392 this.setActiveTicket(null, "master");
394 var notification = new Notify.Notification(
395 "Left branch %s".printf(oldbranch),
400 notification.set_timeout(5);
405 GitMonitor.gitmonitor.pauseError(e.message);
409 // error~?? -- show the error dialog...
415 public void loadActiveTicket()
417 this.activeTicket = null;
418 var ticket_id = this.get_config("ticket");
420 if (ticket_id.length < 1) {
423 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
430 public bool setActiveTicket(RooTicket? ticket, string branchname)
432 this.set_config("ticket", "");
433 if (!this.createBranchNamed(branchname)) {
436 this.set_config("ticket", ticket == null ? "": ticket.id);
437 this.activeTicket = ticket;
441 public bool createBranchNamed(string branchname)
445 if (this.branches.has_key(branchname)) {
446 this.switchToExistingBranchNamed(branchname);
449 this.createNewBranchNamed(branchname);
452 var notification = new Notify.Notification(
453 "Changed to branch %s".printf(branchname),
459 notification.set_timeout(5);
463 this.loadBranches(); // update branch list...
464 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
467 bool switchToExistingBranchNamed(string branchname)
470 // this is where it get's tricky...
473 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
474 files = this.git(cmd);
475 stash = files.length> 1 ;
479 if (stash) { this.git(cmd); }
483 cmd = { "checkout", branchname };
486 GitMonitor.gitmonitor.pauseError(e.message);
490 if (branchname != "master") {
491 string[] cmd = { "merge", "master" };
498 string[] cmd = { "checkout", "master" };
500 GitMonitor.gitmonitor.pauseError(
501 "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(
509 string[] cmd = { "stash", "pop" };
512 var fl = files.split("\n");
513 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
514 foreach(var f in fl) {
515 if (f.length < 1) continue;
524 GitMonitor.gitmonitor.pauseError(ee.message);
534 bool createNewBranchNamed(string branchname)
538 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
539 var files = this.git(cmd);
540 stash = files.length> 1 ;
542 cmd = { "checkout", "-b" , branchname };
545 cmd = { "push", "-u" , "origin" ,"HEAD" };
549 var fl = files.split("\n");
550 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
551 foreach(var f in fl) {
552 if (f.length < 1) continue;
561 GitMonitor.gitmonitor.pauseError(ee.message);
572 * add files to track.
574 * @argument {Array} files the files to add.
576 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
578 // should really find out if these are untracked files each..
579 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
580 // not sure if that is how git works.. but just be certian.
582 for (var i = 0; i < files.size;i++) {
583 var f = files.get(i).vname;
585 string[] cmd = { "add", f };
588 ret += e.message + "\n";
595 public bool is_ignore(string fname) throws Error, SpawnError
597 if (fname == ".gitignore") {
598 this.ignore_files.clear();
601 if (this.ignore_files.has_key(fname)) {
602 return this.ignore_files.get(fname);
606 var ret = this.git( { "check-ignore" , fname } );
607 this.ignore_files.set(fname, ret.length > 0);
608 return ret.length > 0;
609 } catch (SpawnError e) {
610 this.ignore_files.set(fname, false);
619 * remove files to track.
621 * @argument {Array} files the files to add.
623 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
625 // this may fail if files do not exist..
626 // should really find out if these are untracked files each..
627 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
628 // not sure if that is how git works.. but just be certian.
631 for (var i = 0; i < files.size;i++) {
632 var f = files.get(i).vname;
634 string[] cmd = { "rm", "-f" , f };
637 ret += e.message + "\n";
650 * @argument {Object} cfg commit configuration
652 * @property {String} name (optional)
653 * @property {String} email (optional)
654 * @property {String} changed (date) (optional)
655 * @property {String} reason (optional)
656 * @property {Array} files - the files that have changed.
660 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
667 if (typeof(cfg.name) != 'undefined') {
669 'author' : cfg.name + ' <' + cfg.email + '>'
672 "GIT_COMMITTER_NAME" + cfg.name,
673 "GIT_COMMITTER_EMAIL" + cfg.email
677 if (typeof(cfg.changed) != 'undefined') {
678 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
682 string[] args = { "commit", "-m" };
683 args += (message.length > 0 ? message : "Changed" );
684 for (var i = 0; i< files.size ; i++ ) {
685 args += files.get(i).vname; // full path?
688 return this.git(args);
693 * Fetch and merge remote repo changes into current branch..
695 * At present we just need this to update the current working branch..
696 * -- maybe later it will have a few options and do more stuff..
699 public string pull () throws Error, SpawnError
701 // should probably hand error conditions better...
702 string[] cmd = { "pull" , "--no-edit" };
703 return this.git( cmd );
708 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
709 public void pull_async(GitAsyncCallback cb)
712 string[] cmd = { "pull" , "--no-edit" };
713 this.git_async( cmd , cb);
720 * Send local changes to remote repo(s)
722 * At present we just need this to push the current branch.
723 * -- maybe later it will have a few options and do more stuff..
726 public string push () throws Error, SpawnError
729 return this.git({ "push" });
737 * The meaty part.. run spawn.. with git..
742 public string git(string[] args_in ) throws Error, SpawnError
744 // convert arguments.
746 string[] args = { "git" };
747 //args += "--git-dir";
748 //args += this.gitdir;
749 args += "--no-pager";
752 //if (this.gitdir != this.repopath) {
753 // args += "--work-tree";
754 // args += this.repopath;
756 for (var i = 0; i < args_in.length;i++) {
760 //this.lastCmd = args.join(" ");
762 GLib.debug( "CWD=%s", this.git_working_dir );
763 GLib.debug( "cmd: %s", string.joinv (" ", args));
767 string home = "HOME=" + Environment.get_home_dir() ;
769 // do not need to set gitpath..
770 //if (File.exists(this.repo + '/.git/config')) {
771 //env.push("GITPATH=" + this.repo );
774 var cfg = new SpawnConfig(this.git_working_dir , args , env);
777 // may throw error...
778 var sp = new Spawn(cfg);
780 //GLib.debug( "GOT result: %d" , sp.result);
782 // diff output is a bit big..
783 if (args_in[0] != "diff") {
784 GLib.debug( "GOT: %s" , sp.output);
786 // parse output for some commands ?
790 unowned GitAsyncCallback git_async_on_callback;
791 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
793 // convert arguments.
794 this.git_async_on_callback = cb;
795 string[] args = { "git" };
796 //args += "--git-dir";
797 //args += this.gitdir;
798 args += "--no-pager";
801 //if (this.gitdir != this.repopath) {
802 // args += "--work-tree";
803 // args += this.repopath;
805 for (var i = 0; i < args_in.length;i++) {
809 //this.lastCmd = args.join(" ");
811 GLib.debug( "CWD=%s", this.git_working_dir );
812 //print( "cmd: %s\n", string.joinv (" ", args));
816 string home = "HOME=" + Environment.get_home_dir() ;
818 // do not need to set gitpath..
819 //if (File.exists(this.repo + '/.git/config')) {
820 //env.push("GITPATH=" + this.repo );
824 var cfg = new SpawnConfig(this.git_working_dir , args , env);
828 // may throw error...
829 var sp = new Spawn(cfg);
832 sp.run(this.git_async_on_complete);
836 void git_async_on_complete(int err, string output)
838 GLib.debug("GOT %d : %s", err, output);
839 this.git_async_on_callback(this, err, output);
850 public void update_async(GitAsyncCallback cb)
852 string[] cmd = { "fetch" , "--all" };
853 this.git_async( cmd , cb);
858 static uint update_all_total = 0;
859 static string update_all_after = "";
861 public static void updateAll(string after)
863 update_all_after = after;
864 var tr = GitRepo.singleton().cache;
867 update_all_total = tr.size;
868 foreach(var repo in tr.values) {
869 if (!repo.is_managed()) {
873 repo.update_async(updateAllCallback);
877 public static void updateAllCallback(GitRepo repo, int err, string res)
883 GLib.debug("calls remaining = %d", update_all_total);
884 if (update_all_total > 0 ) {
888 switch (update_all_after) {
890 Clones.singleton().show();