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 git_status;
23 public string git_diff;
24 public string ahead_or_behind = "";
26 public Gee.HashMap<string,bool> ignore_files;
27 public GitBranch currentBranch;
28 public Gee.HashMap<string,GitBranch> branches; // accessed in GitBranch..
29 public RooTicket? activeTicket;
30 public Gee.HashMap<string,GitRepo> cache;
34 public static GitRepo singleton()
36 if (_GitRepo == null) {
37 _GitRepo = new GitRepo.single();
38 _GitRepo.cache = new Gee.HashMap<string,GitRepo>();
44 * index of.. matching gitpath..
46 public static int indexOf( Array<GitRepo> repos, string gitpath) {
47 // make a fake object to compare against..
48 var test_repo = GitRepo.get(gitpath);
50 for(var i =0; i < repos.length; i++) {
51 if (repos.index(i).gitdir == test_repo.gitdir) {
63 public static Array<GitRepo> list()
66 //if (GitRepo.list_cache != null) {
67 // unowned Array<GitRepo> ret = GitRepo.list_cache;
70 var cache = GitRepo.singleton().cache;
71 var list_cache = new Array<GitRepo>();
73 var dir = Environment.get_home_dir() + "/gitlive";
75 var f = File.new_for_path(dir);
76 FileEnumerator file_enum;
78 file_enum = f.enumerate_children(
79 FileAttribute.STANDARD_DISPLAY_NAME + ","+
80 FileAttribute.STANDARD_TYPE,
81 FileQueryInfoFlags.NONE,
94 next_file = file_enum.next_file(null);
95 if (next_file == null) {
100 GLib.debug("Error: %s",e.message);
104 //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
106 if (next_file.get_file_type() != FileType.DIRECTORY) {
111 if (next_file.get_file_type() == FileType.SYMBOLIC_LINK) {
116 if (next_file.get_display_name()[0] == '.') {
120 var sp = dir+"/"+next_file.get_display_name();
122 var gitdir = dir + "/" + next_file.get_display_name() + "/.git";
124 if (!FileUtils.test(gitdir, FileTest.IS_DIR)) {
128 var rep = GitRepo.get( sp );
129 list_cache.append_val(rep);
137 public static GitRepo get(string path)
139 var cache = GitRepo.singleton().cache;
140 if (cache.has_key(path)) {
141 return cache.get(path);
143 return new GitRepo(path);
146 private GitRepo.single() {
147 // used to create the signleton
152 * @param {Object} cfg - Configuration
153 * (basically repopath is currently only critical one.)
157 private GitRepo(string path) {
159 this.name = File.new_for_path(path).get_basename();
160 this.ignore_files = new Gee.HashMap<string,bool>();
162 this.git_working_dir = path;
163 this.gitdir = path + "/.git";
164 if (!FileUtils.test(this.gitdir , FileTest.IS_DIR)) {
165 this.gitdir = path; // naked...
167 this.cmds = new Gee.ArrayList<GitMonitorQueue> ();
169 var cache = GitRepo.singleton().cache;
170 //Repo.superclass.constructor.call(this,cfg);
171 if ( !cache.has_key(path) ) {
172 cache.set( path, this);
175 this.loadActiveTicket();
179 public bool is_wip_branch()
181 return this.currentBranch.name.has_prefix("wip_");
185 public bool is_managed()
187 // is it a roojs origin?
188 var r = this.git({ "remote" , "get-url" , "--push" , "origin"});
189 var uri = new Soup.URI(r);
190 if (uri.get_host() != "git.roojs.com") { // we can only push to this url. -- unless we have forced it to be managed.
191 return FileUtils.test(this.gitdir + "/.gitlive-managed" , FileTest.EXISTS);
193 // otherwise see if unmanaged is set to disable it..
194 return !FileUtils.test(this.gitdir + "/.gitlive-unmanaged" , FileTest.EXISTS);
199 public bool is_autocommit ()
201 return !FileUtils.test(this.gitdir + "/.gitlive-disable-autocommit" , FileTest.EXISTS);
203 public void set_autocommit(bool val)
206 var cur = this.is_autocommit();
207 GLib.debug("SET auto commit : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
209 return; // no change..
212 FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autocommit" , "x");
215 FileUtils.remove(this.gitdir + "/.gitlive-disable-autocommit" );
220 public bool is_auto_branch ()
222 return FileUtils.test(this.gitdir + "/.gitlive-enable-auto-branch" , FileTest.EXISTS);
225 public void set_auto_branch(bool val)
228 var cur = this.is_auto_branch();
229 GLib.debug("SET auto branch : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
232 return; // no change..
235 FileUtils.set_contents(this.gitdir + "/.gitlive-enable-auto-branch" , "x");
238 FileUtils.remove(this.gitdir + "/.gitlive-enable-auto-branch" );
242 public bool is_autopush ()
244 return !FileUtils.test(this.gitdir + "/.gitlive-disable-autopush" , FileTest.EXISTS);
246 public void set_autopush(bool val)
249 var cur = this.is_autopush();
250 GLib.debug("SET auto push : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
252 return; // no change..
255 FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autopush" , "");
258 FileUtils.remove(this.gitdir + "/.gitlive-disable-autopush" );
264 public void loadStatus()
266 var r = this.git({ "status" , "--porcelain" });
268 this.has_local_changes = r.length > 0;
270 var rs = this.git({ "status" , "-sb" });
272 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
275 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
279 public void loadBranches()
282 GitBranch.loadBranches(this);
288 public string branchesToString()
291 foreach( var br in this.branches.values) {
295 ret += ret.length > 0 ? "\n" : "";
302 public static void doMerges(string action, string ticket_id, string commit_message)
304 GitMonitor.gitmonitor.stop();
308 foreach(var repo in GitRepo.singleton().cache.values) {
309 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
310 var res = repo.doMerge(action,ticket_id, commit_message);
315 commitrevs += commitrevs.length > 0 ? " " : "";
316 commitrevs += repo.currentBranch.lastrev;
319 if (sucess && action == "CLOSE") {
320 RooTicket.singleton().getById(ticket_id).close(commitrevs);
322 GitMonitor.gitmonitor.start();
326 public bool doMerge(string action, string ticket_id, string commit_message)
328 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
329 // also need to decide which branch we will merge into?
331 if (action == "CLOSE" || action == "LEAVE") {
334 var oldbranch = this.currentBranch.name;
335 this.setActiveTicket(null, "master");
336 string [] cmd = { "merge", "--squash", oldbranch };
338 cmd = { "commit", "-a" , "-m", commit_message };
341 this.loadBranches(); // updates lastrev..
343 var notification = new Notify.Notification(
344 "Merged branch %s to master".printf(oldbranch),
350 notification.set_timeout(5);
358 GitMonitor.gitmonitor.pauseError(e.message);
361 // error~?? -- show the error dialog...
364 if (action == "MASTER") {
365 // merge master into ours..
367 string[] cmd = { "merge", "master" };
369 var notification = new Notify.Notification(
370 "Merged code from master to %s".printf(this.currentBranch.name),
375 notification.set_timeout(5);
380 GitMonitor.gitmonitor.pauseError(e.message);
384 if (action == "EXIT") {
386 var oldbranch = this.currentBranch.name;
387 this.setActiveTicket(null, "master");
389 var notification = new Notify.Notification(
390 "Left branch %s".printf(oldbranch),
395 notification.set_timeout(5);
400 GitMonitor.gitmonitor.pauseError(e.message);
404 // error~?? -- show the error dialog...
410 public void loadActiveTicket()
412 this.activeTicket = null;
413 if (!FileUtils.test(this.gitdir + "/.gitlive-active-ticket" , FileTest.EXISTS)) {
417 FileUtils.get_contents(this.gitdir + "/.gitlive-active-ticket" , out ticket_id);
418 if (ticket_id.length < 1) {
421 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
428 public bool setActiveTicket(RooTicket? ticket, string branchname)
430 if (!this.createBranchNamed(branchname)) {
433 if (ticket != null) {
434 FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
436 FileUtils.remove(this.gitdir + "/.gitlive-active-ticket" );
438 this.activeTicket = ticket;
442 public bool createBranchNamed(string branchname)
446 if (this.branches.has_key(branchname)) {
447 this.switchToExistingBranchNamed(branchname);
450 this.createNewBranchNamed(branchname);
453 var notification = new Notify.Notification(
454 "Changed to branch %s".printf(branchname),
460 notification.set_timeout(5);
464 this.loadBranches(); // update branch list...
465 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
468 bool switchToExistingBranchNamed(string branchname)
471 // this is where it get's tricky...
474 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
475 files = this.git(cmd);
476 stash = files.length> 1 ;
480 if (stash) { this.git(cmd); }
484 cmd = { "checkout", branchname };
487 GitMonitor.gitmonitor.pauseError(e.message);
491 if (branchname != "master") {
492 string[] cmd = { "merge", "master" };
499 string[] cmd = { "checkout", "master" };
501 GitMonitor.gitmonitor.pauseError(
502 "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(
510 string[] cmd = { "stash", "pop" };
513 var fl = files.split("\n");
514 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
515 foreach(var f in fl) {
516 if (f.length < 1) continue;
525 GitMonitor.gitmonitor.pauseError(ee.message);
535 bool createNewBranchNamed(string branchname)
539 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
540 var files = this.git(cmd);
541 stash = files.length> 1 ;
543 cmd = { "checkout", "-b" , branchname };
546 cmd = { "push", "-u" , "origin" ,"HEAD" };
550 var fl = files.split("\n");
551 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
552 foreach(var f in fl) {
553 if (f.length < 1) continue;
562 GitMonitor.gitmonitor.pauseError(ee.message);
573 * add files to track.
575 * @argument {Array} files the files to add.
577 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
579 // should really find out if these are untracked files each..
580 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
581 // not sure if that is how git works.. but just be certian.
583 for (var i = 0; i < files.size;i++) {
584 var f = files.get(i).vname;
586 string[] cmd = { "add", f };
589 ret += e.message + "\n";
596 public bool is_ignore(string fname) throws Error, SpawnError
598 if (fname == ".gitignore") {
599 this.ignore_files.clear();
602 if (this.ignore_files.has_key(fname)) {
603 return this.ignore_files.get(fname);
607 var ret = this.git( { "check-ignore" , fname } );
608 this.ignore_files.set(fname, ret.length > 0);
609 return ret.length > 0;
610 } catch (SpawnError e) {
611 this.ignore_files.set(fname, false);
620 * remove files to track.
622 * @argument {Array} files the files to add.
624 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
626 // this may fail if files do not exist..
627 // should really find out if these are untracked files each..
628 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
629 // not sure if that is how git works.. but just be certian.
632 for (var i = 0; i < files.size;i++) {
633 var f = files.get(i).vname;
635 string[] cmd = { "rm", "-f" , f };
638 ret += e.message + "\n";
651 * @argument {Object} cfg commit configuration
653 * @property {String} name (optional)
654 * @property {String} email (optional)
655 * @property {String} changed (date) (optional)
656 * @property {String} reason (optional)
657 * @property {Array} files - the files that have changed.
661 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
668 if (typeof(cfg.name) != 'undefined') {
670 'author' : cfg.name + ' <' + cfg.email + '>'
673 "GIT_COMMITTER_NAME" + cfg.name,
674 "GIT_COMMITTER_EMAIL" + cfg.email
678 if (typeof(cfg.changed) != 'undefined') {
679 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
683 string[] args = { "commit", "-m" };
684 args += (message.length > 0 ? message : "Changed" );
685 for (var i = 0; i< files.size ; i++ ) {
686 args += files.get(i).vname; // full path?
689 return this.git(args);
694 * Fetch and merge remote repo changes into current branch..
696 * At present we just need this to update the current working branch..
697 * -- maybe later it will have a few options and do more stuff..
700 public string pull () throws Error, SpawnError
702 // should probably hand error conditions better...
703 string[] cmd = { "pull" , "--no-edit" };
704 return this.git( cmd );
709 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
710 public void pull_async(GitAsyncCallback cb)
713 string[] cmd = { "pull" , "--no-edit" };
714 this.git_async( cmd , cb);
721 * Send local changes to remote repo(s)
723 * At present we just need this to push the current branch.
724 * -- maybe later it will have a few options and do more stuff..
727 public string push () throws Error, SpawnError
730 return this.git({ "push" });
738 * The meaty part.. run spawn.. with git..
743 public string git(string[] args_in ) throws Error, SpawnError
745 // convert arguments.
747 string[] args = { "git" };
748 //args += "--git-dir";
749 //args += this.gitdir;
750 args += "--no-pager";
753 //if (this.gitdir != this.repopath) {
754 // args += "--work-tree";
755 // args += this.repopath;
757 for (var i = 0; i < args_in.length;i++) {
761 //this.lastCmd = args.join(" ");
763 GLib.debug( "CWD=%s", this.git_working_dir );
764 GLib.debug( "cmd: %s", string.joinv (" ", args));
768 string home = "HOME=" + Environment.get_home_dir() ;
770 // do not need to set gitpath..
771 //if (File.exists(this.repo + '/.git/config')) {
772 //env.push("GITPATH=" + this.repo );
775 var cfg = new SpawnConfig(this.git_working_dir , args , env);
778 // may throw error...
779 var sp = new Spawn(cfg);
781 // diff output is a bit big..
782 if (args_in[0] != "diff") {
783 GLib.debug( "GOT: %s" , sp.output);
785 // parse output for some commands ?
789 unowned GitAsyncCallback git_async_on_callback;
790 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
792 // convert arguments.
793 this.git_async_on_callback = cb;
794 string[] args = { "git" };
795 //args += "--git-dir";
796 //args += this.gitdir;
797 args += "--no-pager";
800 //if (this.gitdir != this.repopath) {
801 // args += "--work-tree";
802 // args += this.repopath;
804 for (var i = 0; i < args_in.length;i++) {
808 //this.lastCmd = args.join(" ");
810 GLib.debug( "CWD=%s", this.git_working_dir );
811 //print( "cmd: %s\n", string.joinv (" ", args));
815 string home = "HOME=" + Environment.get_home_dir() ;
817 // do not need to set gitpath..
818 //if (File.exists(this.repo + '/.git/config')) {
819 //env.push("GITPATH=" + this.repo );
823 var cfg = new SpawnConfig(this.git_working_dir , args , env);
827 // may throw error...
828 var sp = new Spawn(cfg);
831 sp.run(this.git_async_on_complete);
835 void git_async_on_complete(int err, string output)
837 GLib.debug("GOT %d : %s", err, output);
838 this.git_async_on_callback(this, err, output);
849 public void update_async(GitAsyncCallback cb)
851 string[] cmd = { "fetch" , "--all" };
852 this.git_async( cmd , cb);
857 static uint update_all_total = 0;
858 static string update_all_after = "";
860 public static void updateAll(string after)
862 update_all_after = after;
863 var tr = GitRepo.singleton().cache;
866 update_all_total = tr.size;
867 foreach(var repo in tr.values) {
868 if (!repo.is_managed()) {
872 repo.update_async(updateAllCallback);
876 public static void updateAllCallback(GitRepo repo, int err, string res)
882 if (update_all_total > 0 ) {
885 switch (update_all_after) {
887 Clones.singleton().show();