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) {
209 return this.git({ "config" , "gitlive." + key });
211 public string set_config(string key, string value) {
212 return this.git({ "config" , "gitlive." + key, value });
215 public bool is_managed()
217 return this.get_config("managed") == "1";
221 public bool is_autocommit ()
223 return this.get_config("autocommit") == "1";
226 public void set_autocommit(bool val)
228 this.set_config("autocommit", val ? "1" : "0");
232 public bool is_auto_branch ()
234 if (this.name == "gitlog") {
238 if (this.is_managed()) {
246 public void set_auto_branch(bool val)
248 if (this.name == "gitlog") {
251 this.set_config("managed", val ? "1" : "0");
254 public bool is_autopush ()
256 return this.get_config("autopush") == "1";
258 public void set_autopush(bool val)
260 this.set_config("autopush", val ? "1" : "0");
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 var ticket_id = this.get_config("ticket");
415 if (ticket_id.length < 1) {
418 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
425 public bool setActiveTicket(RooTicket? ticket, string branchname)
427 if (!this.createBranchNamed(branchname)) {
430 if (ticket != null) {
431 FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
433 FileUtils.remove(this.gitdir + "/.gitlive-active-ticket" );
435 this.activeTicket = ticket;
439 public bool createBranchNamed(string branchname)
443 if (this.branches.has_key(branchname)) {
444 this.switchToExistingBranchNamed(branchname);
447 this.createNewBranchNamed(branchname);
450 var notification = new Notify.Notification(
451 "Changed to branch %s".printf(branchname),
457 notification.set_timeout(5);
461 this.loadBranches(); // update branch list...
462 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
465 bool switchToExistingBranchNamed(string branchname)
468 // this is where it get's tricky...
471 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
472 files = this.git(cmd);
473 stash = files.length> 1 ;
477 if (stash) { this.git(cmd); }
481 cmd = { "checkout", branchname };
484 GitMonitor.gitmonitor.pauseError(e.message);
488 if (branchname != "master") {
489 string[] cmd = { "merge", "master" };
496 string[] cmd = { "checkout", "master" };
498 GitMonitor.gitmonitor.pauseError(
499 "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(
507 string[] cmd = { "stash", "pop" };
510 var fl = files.split("\n");
511 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
512 foreach(var f in fl) {
513 if (f.length < 1) continue;
522 GitMonitor.gitmonitor.pauseError(ee.message);
532 bool createNewBranchNamed(string branchname)
536 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
537 var files = this.git(cmd);
538 stash = files.length> 1 ;
540 cmd = { "checkout", "-b" , branchname };
543 cmd = { "push", "-u" , "origin" ,"HEAD" };
547 var fl = files.split("\n");
548 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
549 foreach(var f in fl) {
550 if (f.length < 1) continue;
559 GitMonitor.gitmonitor.pauseError(ee.message);
570 * add files to track.
572 * @argument {Array} files the files to add.
574 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
576 // should really find out if these are untracked files each..
577 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
578 // not sure if that is how git works.. but just be certian.
580 for (var i = 0; i < files.size;i++) {
581 var f = files.get(i).vname;
583 string[] cmd = { "add", f };
586 ret += e.message + "\n";
593 public bool is_ignore(string fname) throws Error, SpawnError
595 if (fname == ".gitignore") {
596 this.ignore_files.clear();
599 if (this.ignore_files.has_key(fname)) {
600 return this.ignore_files.get(fname);
604 var ret = this.git( { "check-ignore" , fname } );
605 this.ignore_files.set(fname, ret.length > 0);
606 return ret.length > 0;
607 } catch (SpawnError e) {
608 this.ignore_files.set(fname, false);
617 * remove files to track.
619 * @argument {Array} files the files to add.
621 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
623 // this may fail if files do not exist..
624 // should really find out if these are untracked files each..
625 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
626 // not sure if that is how git works.. but just be certian.
629 for (var i = 0; i < files.size;i++) {
630 var f = files.get(i).vname;
632 string[] cmd = { "rm", "-f" , f };
635 ret += e.message + "\n";
648 * @argument {Object} cfg commit configuration
650 * @property {String} name (optional)
651 * @property {String} email (optional)
652 * @property {String} changed (date) (optional)
653 * @property {String} reason (optional)
654 * @property {Array} files - the files that have changed.
658 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
665 if (typeof(cfg.name) != 'undefined') {
667 'author' : cfg.name + ' <' + cfg.email + '>'
670 "GIT_COMMITTER_NAME" + cfg.name,
671 "GIT_COMMITTER_EMAIL" + cfg.email
675 if (typeof(cfg.changed) != 'undefined') {
676 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
680 string[] args = { "commit", "-m" };
681 args += (message.length > 0 ? message : "Changed" );
682 for (var i = 0; i< files.size ; i++ ) {
683 args += files.get(i).vname; // full path?
686 return this.git(args);
691 * Fetch and merge remote repo changes into current branch..
693 * At present we just need this to update the current working branch..
694 * -- maybe later it will have a few options and do more stuff..
697 public string pull () throws Error, SpawnError
699 // should probably hand error conditions better...
700 string[] cmd = { "pull" , "--no-edit" };
701 return this.git( cmd );
706 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
707 public void pull_async(GitAsyncCallback cb)
710 string[] cmd = { "pull" , "--no-edit" };
711 this.git_async( cmd , cb);
718 * Send local changes to remote repo(s)
720 * At present we just need this to push the current branch.
721 * -- maybe later it will have a few options and do more stuff..
724 public string push () throws Error, SpawnError
727 return this.git({ "push" });
735 * The meaty part.. run spawn.. with git..
740 public string git(string[] args_in ) throws Error, SpawnError
742 // convert arguments.
744 string[] args = { "git" };
745 //args += "--git-dir";
746 //args += this.gitdir;
747 args += "--no-pager";
750 //if (this.gitdir != this.repopath) {
751 // args += "--work-tree";
752 // args += this.repopath;
754 for (var i = 0; i < args_in.length;i++) {
758 //this.lastCmd = args.join(" ");
760 GLib.debug( "CWD=%s", this.git_working_dir );
761 GLib.debug( "cmd: %s", string.joinv (" ", args));
765 string home = "HOME=" + Environment.get_home_dir() ;
767 // do not need to set gitpath..
768 //if (File.exists(this.repo + '/.git/config')) {
769 //env.push("GITPATH=" + this.repo );
772 var cfg = new SpawnConfig(this.git_working_dir , args , env);
775 // may throw error...
776 var sp = new Spawn(cfg);
778 // diff output is a bit big..
779 if (args_in[0] != "diff") {
780 GLib.debug( "GOT: %s" , sp.output);
782 // parse output for some commands ?
786 unowned GitAsyncCallback git_async_on_callback;
787 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
789 // convert arguments.
790 this.git_async_on_callback = cb;
791 string[] args = { "git" };
792 //args += "--git-dir";
793 //args += this.gitdir;
794 args += "--no-pager";
797 //if (this.gitdir != this.repopath) {
798 // args += "--work-tree";
799 // args += this.repopath;
801 for (var i = 0; i < args_in.length;i++) {
805 //this.lastCmd = args.join(" ");
807 GLib.debug( "CWD=%s", this.git_working_dir );
808 //print( "cmd: %s\n", string.joinv (" ", args));
812 string home = "HOME=" + Environment.get_home_dir() ;
814 // do not need to set gitpath..
815 //if (File.exists(this.repo + '/.git/config')) {
816 //env.push("GITPATH=" + this.repo );
820 var cfg = new SpawnConfig(this.git_working_dir , args , env);
824 // may throw error...
825 var sp = new Spawn(cfg);
828 sp.run(this.git_async_on_complete);
832 void git_async_on_complete(int err, string output)
834 GLib.debug("GOT %d : %s", err, output);
835 this.git_async_on_callback(this, err, output);
846 public void update_async(GitAsyncCallback cb)
848 string[] cmd = { "fetch" , "--all" };
849 this.git_async( cmd , cb);
854 static uint update_all_total = 0;
855 static string update_all_after = "";
857 public static void updateAll(string after)
859 update_all_after = after;
860 var tr = GitRepo.singleton().cache;
863 update_all_total = tr.size;
864 foreach(var repo in tr.values) {
865 if (!repo.is_managed()) {
869 repo.update_async(updateAllCallback);
873 public static void updateAllCallback(GitRepo repo, int err, string res)
879 if (update_all_total > 0 ) {
882 switch (update_all_after) {
884 Clones.singleton().show();