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");
206 public string get_config(string key) {
207 return this.git({ "config" , "gitlive." + key });
209 public string set_config(string key, string value) {
210 return this.git({ "config" , "gitlive." + key, value });
213 public bool is_managed()
215 return this.get_config("managed") == "1";
220 public bool is_autocommit ()
223 return !FileUtils.test(this.gitdir + "/.gitlive-disable-autocommit" , FileTest.EXISTS);
225 public void set_autocommit(bool val)
228 var cur = this.is_autocommit();
229 GLib.debug("SET auto commit : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
231 return; // no change..
234 FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autocommit" , "x");
237 FileUtils.remove(this.gitdir + "/.gitlive-disable-autocommit" );
242 public bool is_auto_branch ()
244 if (this.name == "gitlog") {
248 if (this.is_managed()) {
256 public void set_auto_branch(bool val)
259 var cur = this.is_auto_branch();
260 GLib.debug("SET auto branch : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
263 return; // no change..
265 if (this.host != "git.roojs.com") { // we can only push to this url. -- unless we have forced it to be managed.
266 // remote is not our server..
268 FileUtils.set_contents(this.gitdir + "/.gitlive-managed" , "x");
270 FileUtils.remove(this.gitdir + "/.gitlive-managed" );
277 FileUtils.remove(this.gitdir + "/.gitlive-unmanaged" );
279 FileUtils.set_contents(this.gitdir + "/.gitlive-unmanaged" , "x");
285 public bool is_autopush ()
287 return !FileUtils.test(this.gitdir + "/.gitlive-disable-autopush" , FileTest.EXISTS);
289 public void set_autopush(bool val)
292 var cur = this.is_autopush();
293 GLib.debug("SET auto push : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
295 return; // no change..
298 FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autopush" , "");
301 FileUtils.remove(this.gitdir + "/.gitlive-disable-autopush" );
307 public void loadStatus()
309 var r = this.git({ "status" , "--porcelain" });
311 this.has_local_changes = r.length > 0;
313 var rs = this.git({ "status" , "-sb" });
315 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
318 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
322 public void loadBranches()
325 GitBranch.loadBranches(this);
331 public string branchesToString()
334 foreach( var br in this.branches.values) {
338 ret += ret.length > 0 ? "\n" : "";
345 public static void doMerges(string action, string ticket_id, string commit_message)
347 GitMonitor.gitmonitor.stop();
351 foreach(var repo in GitRepo.singleton().cache.values) {
352 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
353 var res = repo.doMerge(action,ticket_id, commit_message);
358 commitrevs += commitrevs.length > 0 ? " " : "";
359 commitrevs += repo.currentBranch.lastrev;
362 if (sucess && action == "CLOSE") {
363 RooTicket.singleton().getById(ticket_id).close(commitrevs);
365 GitMonitor.gitmonitor.start();
369 public bool doMerge(string action, string ticket_id, string commit_message)
371 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
372 // also need to decide which branch we will merge into?
374 if (action == "CLOSE" || action == "LEAVE") {
377 var oldbranch = this.currentBranch.name;
378 this.setActiveTicket(null, "master");
379 string [] cmd = { "merge", "--squash", oldbranch };
381 cmd = { "commit", "-a" , "-m", commit_message };
384 this.loadBranches(); // updates lastrev..
386 var notification = new Notify.Notification(
387 "Merged branch %s to master".printf(oldbranch),
393 notification.set_timeout(5);
401 GitMonitor.gitmonitor.pauseError(e.message);
404 // error~?? -- show the error dialog...
407 if (action == "MASTER") {
408 // merge master into ours..
410 string[] cmd = { "merge", "master" };
412 var notification = new Notify.Notification(
413 "Merged code from master to %s".printf(this.currentBranch.name),
418 notification.set_timeout(5);
423 GitMonitor.gitmonitor.pauseError(e.message);
427 if (action == "EXIT") {
429 var oldbranch = this.currentBranch.name;
430 this.setActiveTicket(null, "master");
432 var notification = new Notify.Notification(
433 "Left branch %s".printf(oldbranch),
438 notification.set_timeout(5);
443 GitMonitor.gitmonitor.pauseError(e.message);
447 // error~?? -- show the error dialog...
453 public void loadActiveTicket()
455 this.activeTicket = null;
456 if (!FileUtils.test(this.gitdir + "/.gitlive-active-ticket" , FileTest.EXISTS)) {
460 FileUtils.get_contents(this.gitdir + "/.gitlive-active-ticket" , out ticket_id);
461 if (ticket_id.length < 1) {
464 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
471 public bool setActiveTicket(RooTicket? ticket, string branchname)
473 if (!this.createBranchNamed(branchname)) {
476 if (ticket != null) {
477 FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
479 FileUtils.remove(this.gitdir + "/.gitlive-active-ticket" );
481 this.activeTicket = ticket;
485 public bool createBranchNamed(string branchname)
489 if (this.branches.has_key(branchname)) {
490 this.switchToExistingBranchNamed(branchname);
493 this.createNewBranchNamed(branchname);
496 var notification = new Notify.Notification(
497 "Changed to branch %s".printf(branchname),
503 notification.set_timeout(5);
507 this.loadBranches(); // update branch list...
508 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
511 bool switchToExistingBranchNamed(string branchname)
514 // this is where it get's tricky...
517 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
518 files = this.git(cmd);
519 stash = files.length> 1 ;
523 if (stash) { this.git(cmd); }
527 cmd = { "checkout", branchname };
530 GitMonitor.gitmonitor.pauseError(e.message);
534 if (branchname != "master") {
535 string[] cmd = { "merge", "master" };
542 string[] cmd = { "checkout", "master" };
544 GitMonitor.gitmonitor.pauseError(
545 "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(
553 string[] cmd = { "stash", "pop" };
556 var fl = files.split("\n");
557 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
558 foreach(var f in fl) {
559 if (f.length < 1) continue;
568 GitMonitor.gitmonitor.pauseError(ee.message);
578 bool createNewBranchNamed(string branchname)
582 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
583 var files = this.git(cmd);
584 stash = files.length> 1 ;
586 cmd = { "checkout", "-b" , branchname };
589 cmd = { "push", "-u" , "origin" ,"HEAD" };
593 var fl = files.split("\n");
594 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
595 foreach(var f in fl) {
596 if (f.length < 1) continue;
605 GitMonitor.gitmonitor.pauseError(ee.message);
616 * add files to track.
618 * @argument {Array} files the files to add.
620 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
622 // should really find out if these are untracked files each..
623 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
624 // not sure if that is how git works.. but just be certian.
626 for (var i = 0; i < files.size;i++) {
627 var f = files.get(i).vname;
629 string[] cmd = { "add", f };
632 ret += e.message + "\n";
639 public bool is_ignore(string fname) throws Error, SpawnError
641 if (fname == ".gitignore") {
642 this.ignore_files.clear();
645 if (this.ignore_files.has_key(fname)) {
646 return this.ignore_files.get(fname);
650 var ret = this.git( { "check-ignore" , fname } );
651 this.ignore_files.set(fname, ret.length > 0);
652 return ret.length > 0;
653 } catch (SpawnError e) {
654 this.ignore_files.set(fname, false);
663 * remove files to track.
665 * @argument {Array} files the files to add.
667 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
669 // this may fail if files do not exist..
670 // should really find out if these are untracked files each..
671 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
672 // not sure if that is how git works.. but just be certian.
675 for (var i = 0; i < files.size;i++) {
676 var f = files.get(i).vname;
678 string[] cmd = { "rm", "-f" , f };
681 ret += e.message + "\n";
694 * @argument {Object} cfg commit configuration
696 * @property {String} name (optional)
697 * @property {String} email (optional)
698 * @property {String} changed (date) (optional)
699 * @property {String} reason (optional)
700 * @property {Array} files - the files that have changed.
704 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
711 if (typeof(cfg.name) != 'undefined') {
713 'author' : cfg.name + ' <' + cfg.email + '>'
716 "GIT_COMMITTER_NAME" + cfg.name,
717 "GIT_COMMITTER_EMAIL" + cfg.email
721 if (typeof(cfg.changed) != 'undefined') {
722 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
726 string[] args = { "commit", "-m" };
727 args += (message.length > 0 ? message : "Changed" );
728 for (var i = 0; i< files.size ; i++ ) {
729 args += files.get(i).vname; // full path?
732 return this.git(args);
737 * Fetch and merge remote repo changes into current branch..
739 * At present we just need this to update the current working branch..
740 * -- maybe later it will have a few options and do more stuff..
743 public string pull () throws Error, SpawnError
745 // should probably hand error conditions better...
746 string[] cmd = { "pull" , "--no-edit" };
747 return this.git( cmd );
752 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
753 public void pull_async(GitAsyncCallback cb)
756 string[] cmd = { "pull" , "--no-edit" };
757 this.git_async( cmd , cb);
764 * Send local changes to remote repo(s)
766 * At present we just need this to push the current branch.
767 * -- maybe later it will have a few options and do more stuff..
770 public string push () throws Error, SpawnError
773 return this.git({ "push" });
781 * The meaty part.. run spawn.. with git..
786 public string git(string[] args_in ) throws Error, SpawnError
788 // convert arguments.
790 string[] args = { "git" };
791 //args += "--git-dir";
792 //args += this.gitdir;
793 args += "--no-pager";
796 //if (this.gitdir != this.repopath) {
797 // args += "--work-tree";
798 // args += this.repopath;
800 for (var i = 0; i < args_in.length;i++) {
804 //this.lastCmd = args.join(" ");
806 GLib.debug( "CWD=%s", this.git_working_dir );
807 GLib.debug( "cmd: %s", string.joinv (" ", args));
811 string home = "HOME=" + Environment.get_home_dir() ;
813 // do not need to set gitpath..
814 //if (File.exists(this.repo + '/.git/config')) {
815 //env.push("GITPATH=" + this.repo );
818 var cfg = new SpawnConfig(this.git_working_dir , args , env);
821 // may throw error...
822 var sp = new Spawn(cfg);
824 // diff output is a bit big..
825 if (args_in[0] != "diff") {
826 GLib.debug( "GOT: %s" , sp.output);
828 // parse output for some commands ?
832 unowned GitAsyncCallback git_async_on_callback;
833 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
835 // convert arguments.
836 this.git_async_on_callback = cb;
837 string[] args = { "git" };
838 //args += "--git-dir";
839 //args += this.gitdir;
840 args += "--no-pager";
843 //if (this.gitdir != this.repopath) {
844 // args += "--work-tree";
845 // args += this.repopath;
847 for (var i = 0; i < args_in.length;i++) {
851 //this.lastCmd = args.join(" ");
853 GLib.debug( "CWD=%s", this.git_working_dir );
854 //print( "cmd: %s\n", string.joinv (" ", args));
858 string home = "HOME=" + Environment.get_home_dir() ;
860 // do not need to set gitpath..
861 //if (File.exists(this.repo + '/.git/config')) {
862 //env.push("GITPATH=" + this.repo );
866 var cfg = new SpawnConfig(this.git_working_dir , args , env);
870 // may throw error...
871 var sp = new Spawn(cfg);
874 sp.run(this.git_async_on_complete);
878 void git_async_on_complete(int err, string output)
880 GLib.debug("GOT %d : %s", err, output);
881 this.git_async_on_callback(this, err, output);
892 public void update_async(GitAsyncCallback cb)
894 string[] cmd = { "fetch" , "--all" };
895 this.git_async( cmd , cb);
900 static uint update_all_total = 0;
901 static string update_all_after = "";
903 public static void updateAll(string after)
905 update_all_after = after;
906 var tr = GitRepo.singleton().cache;
909 update_all_total = tr.size;
910 foreach(var repo in tr.values) {
911 if (!repo.is_managed()) {
915 repo.update_async(updateAllCallback);
919 public static void updateAllCallback(GitRepo repo, int err, string res)
925 if (update_all_total > 0 ) {
928 switch (update_all_after) {
930 Clones.singleton().show();