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_master_branch()
181 // special branches that do not allow autopushing now...
182 return this.currentBranch.name == "master" || this.currentBranch.name == "roojs";
186 public bool is_managed()
188 // is it a roojs origin?
189 var r = this.git({ "remote" , "get-url" , "--push" , "origin"});
190 var uri = new Soup.URI(r);
191 if (uri.get_host() != "git.roojs.com") { // we can only push to this url. -- unless we have forced it to be managed.
192 return FileUtils.test(this.gitdir + "/.gitlive-managed" , FileTest.EXISTS);
194 // otherwise see if unmanaged is set to disable it..
195 return !FileUtils.test(this.gitdir + "/.gitlive-unmanaged" , FileTest.EXISTS);
200 public bool is_autocommit ()
202 return !FileUtils.test(this.gitdir + "/.gitlive-disable-autocommit" , FileTest.EXISTS);
204 public void set_autocommit(bool val)
207 var cur = this.is_autocommit();
208 GLib.debug("SET auto commit : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
210 return; // no change..
213 FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autocommit" , "x");
216 FileUtils.remove(this.gitdir + "/.gitlive-disable-autocommit" );
221 public bool is_auto_branch ()
223 return FileUtils.test(this.gitdir + "/.gitlive-enable-auto-branch" , FileTest.EXISTS);
226 public void set_auto_branch(bool val)
229 var cur = this.is_auto_branch();
230 GLib.debug("SET auto branch : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
233 return; // no change..
236 FileUtils.set_contents(this.gitdir + "/.gitlive-enable-auto-branch" , "x");
239 FileUtils.remove(this.gitdir + "/.gitlive-enable-auto-branch" );
243 public bool is_autopush ()
245 return !FileUtils.test(this.gitdir + "/.gitlive-disable-autopush" , FileTest.EXISTS);
247 public void set_autopush(bool val)
250 var cur = this.is_autopush();
251 GLib.debug("SET auto push : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
253 return; // no change..
256 FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autopush" , "");
259 FileUtils.remove(this.gitdir + "/.gitlive-disable-autopush" );
265 public void loadStatus()
267 var r = this.git({ "status" , "--porcelain" });
269 this.has_local_changes = r.length > 0;
271 var rs = this.git({ "status" , "-sb" });
273 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
276 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
280 public void loadBranches()
283 GitBranch.loadBranches(this);
289 public string branchesToString()
292 foreach( var br in this.branches.values) {
296 ret += ret.length > 0 ? "\n" : "";
303 public static void doMerges(string action, string ticket_id, string commit_message)
305 GitMonitor.gitmonitor.stop();
309 foreach(var repo in GitRepo.singleton().cache.values) {
310 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
311 var res = repo.doMerge(action,ticket_id, commit_message);
316 commitrevs += commitrevs.length > 0 ? " " : "";
317 commitrevs += repo.currentBranch.lastrev;
320 if (sucess && action == "CLOSE") {
321 RooTicket.singleton().getById(ticket_id).close(commitrevs);
323 GitMonitor.gitmonitor.start();
327 public bool doMerge(string action, string ticket_id, string commit_message)
329 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
330 // also need to decide which branch we will merge into?
332 if (action == "CLOSE" || action == "LEAVE") {
335 var oldbranch = this.currentBranch.name;
336 this.setActiveTicket(null, "master");
337 string [] cmd = { "merge", "--squash", oldbranch };
339 cmd = { "commit", "-a" , "-m", commit_message };
342 this.loadBranches(); // updates lastrev..
344 var notification = new Notify.Notification(
345 "Merged branch %s to master".printf(oldbranch),
351 notification.set_timeout(5);
359 GitMonitor.gitmonitor.pauseError(e.message);
362 // error~?? -- show the error dialog...
365 if (action == "MASTER") {
366 // merge master into ours..
368 string[] cmd = { "merge", "master" };
370 var notification = new Notify.Notification(
371 "Merged code from master to %s".printf(this.currentBranch.name),
376 notification.set_timeout(5);
381 GitMonitor.gitmonitor.pauseError(e.message);
385 if (action == "EXIT") {
387 var oldbranch = this.currentBranch.name;
388 this.setActiveTicket(null, "master");
390 var notification = new Notify.Notification(
391 "Left branch %s".printf(oldbranch),
396 notification.set_timeout(5);
401 GitMonitor.gitmonitor.pauseError(e.message);
405 // error~?? -- show the error dialog...
411 public void loadActiveTicket()
413 this.activeTicket = null;
414 if (!FileUtils.test(this.gitdir + "/.gitlive-active-ticket" , FileTest.EXISTS)) {
418 FileUtils.get_contents(this.gitdir + "/.gitlive-active-ticket" , out ticket_id);
419 if (ticket_id.length < 1) {
422 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
429 public bool setActiveTicket(RooTicket? ticket, string branchname)
431 if (!this.createBranchNamed(branchname)) {
434 if (ticket != null) {
435 FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
437 FileUtils.remove(this.gitdir + "/.gitlive-active-ticket" );
439 this.activeTicket = ticket;
443 public bool createBranchNamed(string branchname)
447 if (this.branches.has_key(branchname)) {
448 this.switchToExistingBranchNamed(branchname);
451 this.createNewBranchNamed(branchname);
454 var notification = new Notify.Notification(
455 "Changed to branch %s".printf(branchname),
461 notification.set_timeout(5);
465 this.loadBranches(); // update branch list...
466 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
469 bool switchToExistingBranchNamed(string branchname)
472 // this is where it get's tricky...
475 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
476 files = this.git(cmd);
477 stash = files.length> 1 ;
481 if (stash) { this.git(cmd); }
485 cmd = { "checkout", branchname };
488 GitMonitor.gitmonitor.pauseError(e.message);
492 if (branchname != "master") {
493 string[] cmd = { "merge", "master" };
500 string[] cmd = { "checkout", "master" };
502 GitMonitor.gitmonitor.pauseError(
503 "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(
511 string[] cmd = { "stash", "pop" };
514 var fl = files.split("\n");
515 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
516 foreach(var f in fl) {
517 if (f.length < 1) continue;
526 GitMonitor.gitmonitor.pauseError(ee.message);
536 bool createNewBranchNamed(string branchname)
540 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
541 var files = this.git(cmd);
542 stash = files.length> 1 ;
544 cmd = { "checkout", "-b" , branchname };
547 cmd = { "push", "-u" , "origin" ,"HEAD" };
551 var fl = files.split("\n");
552 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
553 foreach(var f in fl) {
554 if (f.length < 1) continue;
563 GitMonitor.gitmonitor.pauseError(ee.message);
574 * add files to track.
576 * @argument {Array} files the files to add.
578 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
580 // should really find out if these are untracked files each..
581 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
582 // not sure if that is how git works.. but just be certian.
584 for (var i = 0; i < files.size;i++) {
585 var f = files.get(i).vname;
587 string[] cmd = { "add", f };
590 ret += e.message + "\n";
597 public bool is_ignore(string fname) throws Error, SpawnError
599 if (fname == ".gitignore") {
600 this.ignore_files.clear();
603 if (this.ignore_files.has_key(fname)) {
604 return this.ignore_files.get(fname);
608 var ret = this.git( { "check-ignore" , fname } );
609 this.ignore_files.set(fname, ret.length > 0);
610 return ret.length > 0;
611 } catch (SpawnError e) {
612 this.ignore_files.set(fname, false);
621 * remove files to track.
623 * @argument {Array} files the files to add.
625 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
627 // this may fail if files do not exist..
628 // should really find out if these are untracked files each..
629 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
630 // not sure if that is how git works.. but just be certian.
633 for (var i = 0; i < files.size;i++) {
634 var f = files.get(i).vname;
636 string[] cmd = { "rm", "-f" , f };
639 ret += e.message + "\n";
652 * @argument {Object} cfg commit configuration
654 * @property {String} name (optional)
655 * @property {String} email (optional)
656 * @property {String} changed (date) (optional)
657 * @property {String} reason (optional)
658 * @property {Array} files - the files that have changed.
662 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
669 if (typeof(cfg.name) != 'undefined') {
671 'author' : cfg.name + ' <' + cfg.email + '>'
674 "GIT_COMMITTER_NAME" + cfg.name,
675 "GIT_COMMITTER_EMAIL" + cfg.email
679 if (typeof(cfg.changed) != 'undefined') {
680 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
684 string[] args = { "commit", "-m" };
685 args += (message.length > 0 ? message : "Changed" );
686 for (var i = 0; i< files.size ; i++ ) {
687 args += files.get(i).vname; // full path?
690 return this.git(args);
695 * Fetch and merge remote repo changes into current branch..
697 * At present we just need this to update the current working branch..
698 * -- maybe later it will have a few options and do more stuff..
701 public string pull () throws Error, SpawnError
703 // should probably hand error conditions better...
704 string[] cmd = { "pull" , "--no-edit" };
705 return this.git( cmd );
710 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
711 public void pull_async(GitAsyncCallback cb)
714 string[] cmd = { "pull" , "--no-edit" };
715 this.git_async( cmd , cb);
722 * Send local changes to remote repo(s)
724 * At present we just need this to push the current branch.
725 * -- maybe later it will have a few options and do more stuff..
728 public string push () throws Error, SpawnError
731 return this.git({ "push" });
739 * The meaty part.. run spawn.. with git..
744 public string git(string[] args_in ) throws Error, SpawnError
746 // convert arguments.
748 string[] args = { "git" };
749 //args += "--git-dir";
750 //args += this.gitdir;
751 args += "--no-pager";
754 //if (this.gitdir != this.repopath) {
755 // args += "--work-tree";
756 // args += this.repopath;
758 for (var i = 0; i < args_in.length;i++) {
762 //this.lastCmd = args.join(" ");
764 GLib.debug( "CWD=%s", this.git_working_dir );
765 GLib.debug( "cmd: %s", string.joinv (" ", args));
769 string home = "HOME=" + Environment.get_home_dir() ;
771 // do not need to set gitpath..
772 //if (File.exists(this.repo + '/.git/config')) {
773 //env.push("GITPATH=" + this.repo );
776 var cfg = new SpawnConfig(this.git_working_dir , args , env);
779 // may throw error...
780 var sp = new Spawn(cfg);
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 if (update_all_total > 0 ) {
886 switch (update_all_after) {
888 Clones.singleton().show();