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";
193 public bool is_managed()
195 // is it a roojs origin?
196 var r = this.git({ "remote" , "get-url" , "--push" , "origin"});
197 var uri = new Soup.URI(r);
198 if (uri.get_host() != "git.roojs.com") { // we can only push to this url. -- unless we have forced it to be managed.
199 return FileUtils.test(this.gitdir + "/.gitlive-managed" , FileTest.EXISTS);
201 // otherwise see if unmanaged is set to disable it..
202 return !FileUtils.test(this.gitdir + "/.gitlive-unmanaged" , FileTest.EXISTS);
207 public bool is_autocommit ()
209 return !FileUtils.test(this.gitdir + "/.gitlive-disable-autocommit" , FileTest.EXISTS);
211 public void set_autocommit(bool val)
214 var cur = this.is_autocommit();
215 GLib.debug("SET auto commit : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
217 return; // no change..
220 FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autocommit" , "x");
223 FileUtils.remove(this.gitdir + "/.gitlive-disable-autocommit" );
228 public bool is_auto_branch ()
230 if (this.name == "gitlog") {
234 if (this.is_managed()) {
242 public void set_auto_branch(bool val)
245 var cur = this.is_auto_branch();
246 GLib.debug("SET auto branch : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
249 return; // no change..
252 FileUtils.set_contents(this.gitdir + "/.gitlive-enable-auto-branch" , "x");
255 FileUtils.remove(this.gitdir + "/.gitlive-enable-auto-branch" );
259 public bool is_autopush ()
261 return !FileUtils.test(this.gitdir + "/.gitlive-disable-autopush" , FileTest.EXISTS);
263 public void set_autopush(bool val)
266 var cur = this.is_autopush();
267 GLib.debug("SET auto push : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
269 return; // no change..
272 FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autopush" , "");
275 FileUtils.remove(this.gitdir + "/.gitlive-disable-autopush" );
281 public void loadStatus()
283 var r = this.git({ "status" , "--porcelain" });
285 this.has_local_changes = r.length > 0;
287 var rs = this.git({ "status" , "-sb" });
289 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
292 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
296 public void loadBranches()
299 GitBranch.loadBranches(this);
305 public string branchesToString()
308 foreach( var br in this.branches.values) {
312 ret += ret.length > 0 ? "\n" : "";
319 public static void doMerges(string action, string ticket_id, string commit_message)
321 GitMonitor.gitmonitor.stop();
325 foreach(var repo in GitRepo.singleton().cache.values) {
326 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
327 var res = repo.doMerge(action,ticket_id, commit_message);
332 commitrevs += commitrevs.length > 0 ? " " : "";
333 commitrevs += repo.currentBranch.lastrev;
336 if (sucess && action == "CLOSE") {
337 RooTicket.singleton().getById(ticket_id).close(commitrevs);
339 GitMonitor.gitmonitor.start();
343 public bool doMerge(string action, string ticket_id, string commit_message)
345 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
346 // also need to decide which branch we will merge into?
348 if (action == "CLOSE" || action == "LEAVE") {
351 var oldbranch = this.currentBranch.name;
352 this.setActiveTicket(null, "master");
353 string [] cmd = { "merge", "--squash", oldbranch };
355 cmd = { "commit", "-a" , "-m", commit_message };
358 this.loadBranches(); // updates lastrev..
360 var notification = new Notify.Notification(
361 "Merged branch %s to master".printf(oldbranch),
367 notification.set_timeout(5);
375 GitMonitor.gitmonitor.pauseError(e.message);
378 // error~?? -- show the error dialog...
381 if (action == "MASTER") {
382 // merge master into ours..
384 string[] cmd = { "merge", "master" };
386 var notification = new Notify.Notification(
387 "Merged code from master to %s".printf(this.currentBranch.name),
392 notification.set_timeout(5);
397 GitMonitor.gitmonitor.pauseError(e.message);
401 if (action == "EXIT") {
403 var oldbranch = this.currentBranch.name;
404 this.setActiveTicket(null, "master");
406 var notification = new Notify.Notification(
407 "Left branch %s".printf(oldbranch),
412 notification.set_timeout(5);
417 GitMonitor.gitmonitor.pauseError(e.message);
421 // error~?? -- show the error dialog...
427 public void loadActiveTicket()
429 this.activeTicket = null;
430 if (!FileUtils.test(this.gitdir + "/.gitlive-active-ticket" , FileTest.EXISTS)) {
434 FileUtils.get_contents(this.gitdir + "/.gitlive-active-ticket" , out ticket_id);
435 if (ticket_id.length < 1) {
438 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
445 public bool setActiveTicket(RooTicket? ticket, string branchname)
447 if (!this.createBranchNamed(branchname)) {
450 if (ticket != null) {
451 FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
453 FileUtils.remove(this.gitdir + "/.gitlive-active-ticket" );
455 this.activeTicket = ticket;
459 public bool createBranchNamed(string branchname)
463 if (this.branches.has_key(branchname)) {
464 this.switchToExistingBranchNamed(branchname);
467 this.createNewBranchNamed(branchname);
470 var notification = new Notify.Notification(
471 "Changed to branch %s".printf(branchname),
477 notification.set_timeout(5);
481 this.loadBranches(); // update branch list...
482 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
485 bool switchToExistingBranchNamed(string branchname)
488 // this is where it get's tricky...
491 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
492 files = this.git(cmd);
493 stash = files.length> 1 ;
497 if (stash) { this.git(cmd); }
501 cmd = { "checkout", branchname };
504 GitMonitor.gitmonitor.pauseError(e.message);
508 if (branchname != "master") {
509 string[] cmd = { "merge", "master" };
516 string[] cmd = { "checkout", "master" };
518 GitMonitor.gitmonitor.pauseError(
519 "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(
527 string[] cmd = { "stash", "pop" };
530 var fl = files.split("\n");
531 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
532 foreach(var f in fl) {
533 if (f.length < 1) continue;
542 GitMonitor.gitmonitor.pauseError(ee.message);
552 bool createNewBranchNamed(string branchname)
556 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
557 var files = this.git(cmd);
558 stash = files.length> 1 ;
560 cmd = { "checkout", "-b" , branchname };
563 cmd = { "push", "-u" , "origin" ,"HEAD" };
567 var fl = files.split("\n");
568 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
569 foreach(var f in fl) {
570 if (f.length < 1) continue;
579 GitMonitor.gitmonitor.pauseError(ee.message);
590 * add files to track.
592 * @argument {Array} files the files to add.
594 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
596 // should really find out if these are untracked files each..
597 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
598 // not sure if that is how git works.. but just be certian.
600 for (var i = 0; i < files.size;i++) {
601 var f = files.get(i).vname;
603 string[] cmd = { "add", f };
606 ret += e.message + "\n";
613 public bool is_ignore(string fname) throws Error, SpawnError
615 if (fname == ".gitignore") {
616 this.ignore_files.clear();
619 if (this.ignore_files.has_key(fname)) {
620 return this.ignore_files.get(fname);
624 var ret = this.git( { "check-ignore" , fname } );
625 this.ignore_files.set(fname, ret.length > 0);
626 return ret.length > 0;
627 } catch (SpawnError e) {
628 this.ignore_files.set(fname, false);
637 * remove files to track.
639 * @argument {Array} files the files to add.
641 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
643 // this may fail if files do not exist..
644 // should really find out if these are untracked files each..
645 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
646 // not sure if that is how git works.. but just be certian.
649 for (var i = 0; i < files.size;i++) {
650 var f = files.get(i).vname;
652 string[] cmd = { "rm", "-f" , f };
655 ret += e.message + "\n";
668 * @argument {Object} cfg commit configuration
670 * @property {String} name (optional)
671 * @property {String} email (optional)
672 * @property {String} changed (date) (optional)
673 * @property {String} reason (optional)
674 * @property {Array} files - the files that have changed.
678 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
685 if (typeof(cfg.name) != 'undefined') {
687 'author' : cfg.name + ' <' + cfg.email + '>'
690 "GIT_COMMITTER_NAME" + cfg.name,
691 "GIT_COMMITTER_EMAIL" + cfg.email
695 if (typeof(cfg.changed) != 'undefined') {
696 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
700 string[] args = { "commit", "-m" };
701 args += (message.length > 0 ? message : "Changed" );
702 for (var i = 0; i< files.size ; i++ ) {
703 args += files.get(i).vname; // full path?
706 return this.git(args);
711 * Fetch and merge remote repo changes into current branch..
713 * At present we just need this to update the current working branch..
714 * -- maybe later it will have a few options and do more stuff..
717 public string pull () throws Error, SpawnError
719 // should probably hand error conditions better...
720 string[] cmd = { "pull" , "--no-edit" };
721 return this.git( cmd );
726 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
727 public void pull_async(GitAsyncCallback cb)
730 string[] cmd = { "pull" , "--no-edit" };
731 this.git_async( cmd , cb);
738 * Send local changes to remote repo(s)
740 * At present we just need this to push the current branch.
741 * -- maybe later it will have a few options and do more stuff..
744 public string push () throws Error, SpawnError
747 return this.git({ "push" });
755 * The meaty part.. run spawn.. with git..
760 public string git(string[] args_in ) throws Error, SpawnError
762 // convert arguments.
764 string[] args = { "git" };
765 //args += "--git-dir";
766 //args += this.gitdir;
767 args += "--no-pager";
770 //if (this.gitdir != this.repopath) {
771 // args += "--work-tree";
772 // args += this.repopath;
774 for (var i = 0; i < args_in.length;i++) {
778 //this.lastCmd = args.join(" ");
780 GLib.debug( "CWD=%s", this.git_working_dir );
781 GLib.debug( "cmd: %s", string.joinv (" ", args));
785 string home = "HOME=" + Environment.get_home_dir() ;
787 // do not need to set gitpath..
788 //if (File.exists(this.repo + '/.git/config')) {
789 //env.push("GITPATH=" + this.repo );
792 var cfg = new SpawnConfig(this.git_working_dir , args , env);
795 // may throw error...
796 var sp = new Spawn(cfg);
798 // diff output is a bit big..
799 if (args_in[0] != "diff") {
800 GLib.debug( "GOT: %s" , sp.output);
802 // parse output for some commands ?
806 unowned GitAsyncCallback git_async_on_callback;
807 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
809 // convert arguments.
810 this.git_async_on_callback = cb;
811 string[] args = { "git" };
812 //args += "--git-dir";
813 //args += this.gitdir;
814 args += "--no-pager";
817 //if (this.gitdir != this.repopath) {
818 // args += "--work-tree";
819 // args += this.repopath;
821 for (var i = 0; i < args_in.length;i++) {
825 //this.lastCmd = args.join(" ");
827 GLib.debug( "CWD=%s", this.git_working_dir );
828 //print( "cmd: %s\n", string.joinv (" ", args));
832 string home = "HOME=" + Environment.get_home_dir() ;
834 // do not need to set gitpath..
835 //if (File.exists(this.repo + '/.git/config')) {
836 //env.push("GITPATH=" + this.repo );
840 var cfg = new SpawnConfig(this.git_working_dir , args , env);
844 // may throw error...
845 var sp = new Spawn(cfg);
848 sp.run(this.git_async_on_complete);
852 void git_async_on_complete(int err, string output)
854 GLib.debug("GOT %d : %s", err, output);
855 this.git_async_on_callback(this, err, output);
866 public void update_async(GitAsyncCallback cb)
868 string[] cmd = { "fetch" , "--all" };
869 this.git_async( cmd , cb);
874 static uint update_all_total = 0;
875 static string update_all_after = "";
877 public static void updateAll(string after)
879 update_all_after = after;
880 var tr = GitRepo.singleton().cache;
883 update_all_total = tr.size;
884 foreach(var repo in tr.values) {
885 if (!repo.is_managed()) {
889 repo.update_async(updateAllCallback);
893 public static void updateAllCallback(GitRepo repo, int err, string res)
899 if (update_all_total > 0 ) {
902 switch (update_all_after) {
904 Clones.singleton().show();