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)
261 var cur = this.is_autopush();
262 GLib.debug("SET auto push : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
264 return; // no change..
267 FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autopush" , "");
270 FileUtils.remove(this.gitdir + "/.gitlive-disable-autopush" );
276 public void loadStatus()
278 var r = this.git({ "status" , "--porcelain" });
280 this.has_local_changes = r.length > 0;
282 var rs = this.git({ "status" , "-sb" });
284 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
287 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
291 public void loadBranches()
294 GitBranch.loadBranches(this);
300 public string branchesToString()
303 foreach( var br in this.branches.values) {
307 ret += ret.length > 0 ? "\n" : "";
314 public static void doMerges(string action, string ticket_id, string commit_message)
316 GitMonitor.gitmonitor.stop();
320 foreach(var repo in GitRepo.singleton().cache.values) {
321 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
322 var res = repo.doMerge(action,ticket_id, commit_message);
327 commitrevs += commitrevs.length > 0 ? " " : "";
328 commitrevs += repo.currentBranch.lastrev;
331 if (sucess && action == "CLOSE") {
332 RooTicket.singleton().getById(ticket_id).close(commitrevs);
334 GitMonitor.gitmonitor.start();
338 public bool doMerge(string action, string ticket_id, string commit_message)
340 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
341 // also need to decide which branch we will merge into?
343 if (action == "CLOSE" || action == "LEAVE") {
346 var oldbranch = this.currentBranch.name;
347 this.setActiveTicket(null, "master");
348 string [] cmd = { "merge", "--squash", oldbranch };
350 cmd = { "commit", "-a" , "-m", commit_message };
353 this.loadBranches(); // updates lastrev..
355 var notification = new Notify.Notification(
356 "Merged branch %s to master".printf(oldbranch),
362 notification.set_timeout(5);
370 GitMonitor.gitmonitor.pauseError(e.message);
373 // error~?? -- show the error dialog...
376 if (action == "MASTER") {
377 // merge master into ours..
379 string[] cmd = { "merge", "master" };
381 var notification = new Notify.Notification(
382 "Merged code from master to %s".printf(this.currentBranch.name),
387 notification.set_timeout(5);
392 GitMonitor.gitmonitor.pauseError(e.message);
396 if (action == "EXIT") {
398 var oldbranch = this.currentBranch.name;
399 this.setActiveTicket(null, "master");
401 var notification = new Notify.Notification(
402 "Left branch %s".printf(oldbranch),
407 notification.set_timeout(5);
412 GitMonitor.gitmonitor.pauseError(e.message);
416 // error~?? -- show the error dialog...
422 public void loadActiveTicket()
424 this.activeTicket = null;
425 if (!FileUtils.test(this.gitdir + "/.gitlive-active-ticket" , FileTest.EXISTS)) {
429 FileUtils.get_contents(this.gitdir + "/.gitlive-active-ticket" , out ticket_id);
430 if (ticket_id.length < 1) {
433 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
440 public bool setActiveTicket(RooTicket? ticket, string branchname)
442 if (!this.createBranchNamed(branchname)) {
445 if (ticket != null) {
446 FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
448 FileUtils.remove(this.gitdir + "/.gitlive-active-ticket" );
450 this.activeTicket = ticket;
454 public bool createBranchNamed(string branchname)
458 if (this.branches.has_key(branchname)) {
459 this.switchToExistingBranchNamed(branchname);
462 this.createNewBranchNamed(branchname);
465 var notification = new Notify.Notification(
466 "Changed to branch %s".printf(branchname),
472 notification.set_timeout(5);
476 this.loadBranches(); // update branch list...
477 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
480 bool switchToExistingBranchNamed(string branchname)
483 // this is where it get's tricky...
486 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
487 files = this.git(cmd);
488 stash = files.length> 1 ;
492 if (stash) { this.git(cmd); }
496 cmd = { "checkout", branchname };
499 GitMonitor.gitmonitor.pauseError(e.message);
503 if (branchname != "master") {
504 string[] cmd = { "merge", "master" };
511 string[] cmd = { "checkout", "master" };
513 GitMonitor.gitmonitor.pauseError(
514 "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(
522 string[] cmd = { "stash", "pop" };
525 var fl = files.split("\n");
526 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
527 foreach(var f in fl) {
528 if (f.length < 1) continue;
537 GitMonitor.gitmonitor.pauseError(ee.message);
547 bool createNewBranchNamed(string branchname)
551 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
552 var files = this.git(cmd);
553 stash = files.length> 1 ;
555 cmd = { "checkout", "-b" , branchname };
558 cmd = { "push", "-u" , "origin" ,"HEAD" };
562 var fl = files.split("\n");
563 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
564 foreach(var f in fl) {
565 if (f.length < 1) continue;
574 GitMonitor.gitmonitor.pauseError(ee.message);
585 * add files to track.
587 * @argument {Array} files the files to add.
589 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
591 // should really find out if these are untracked files each..
592 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
593 // not sure if that is how git works.. but just be certian.
595 for (var i = 0; i < files.size;i++) {
596 var f = files.get(i).vname;
598 string[] cmd = { "add", f };
601 ret += e.message + "\n";
608 public bool is_ignore(string fname) throws Error, SpawnError
610 if (fname == ".gitignore") {
611 this.ignore_files.clear();
614 if (this.ignore_files.has_key(fname)) {
615 return this.ignore_files.get(fname);
619 var ret = this.git( { "check-ignore" , fname } );
620 this.ignore_files.set(fname, ret.length > 0);
621 return ret.length > 0;
622 } catch (SpawnError e) {
623 this.ignore_files.set(fname, false);
632 * remove files to track.
634 * @argument {Array} files the files to add.
636 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
638 // this may fail if files do not exist..
639 // should really find out if these are untracked files each..
640 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
641 // not sure if that is how git works.. but just be certian.
644 for (var i = 0; i < files.size;i++) {
645 var f = files.get(i).vname;
647 string[] cmd = { "rm", "-f" , f };
650 ret += e.message + "\n";
663 * @argument {Object} cfg commit configuration
665 * @property {String} name (optional)
666 * @property {String} email (optional)
667 * @property {String} changed (date) (optional)
668 * @property {String} reason (optional)
669 * @property {Array} files - the files that have changed.
673 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
680 if (typeof(cfg.name) != 'undefined') {
682 'author' : cfg.name + ' <' + cfg.email + '>'
685 "GIT_COMMITTER_NAME" + cfg.name,
686 "GIT_COMMITTER_EMAIL" + cfg.email
690 if (typeof(cfg.changed) != 'undefined') {
691 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
695 string[] args = { "commit", "-m" };
696 args += (message.length > 0 ? message : "Changed" );
697 for (var i = 0; i< files.size ; i++ ) {
698 args += files.get(i).vname; // full path?
701 return this.git(args);
706 * Fetch and merge remote repo changes into current branch..
708 * At present we just need this to update the current working branch..
709 * -- maybe later it will have a few options and do more stuff..
712 public string pull () throws Error, SpawnError
714 // should probably hand error conditions better...
715 string[] cmd = { "pull" , "--no-edit" };
716 return this.git( cmd );
721 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
722 public void pull_async(GitAsyncCallback cb)
725 string[] cmd = { "pull" , "--no-edit" };
726 this.git_async( cmd , cb);
733 * Send local changes to remote repo(s)
735 * At present we just need this to push the current branch.
736 * -- maybe later it will have a few options and do more stuff..
739 public string push () throws Error, SpawnError
742 return this.git({ "push" });
750 * The meaty part.. run spawn.. with git..
755 public string git(string[] args_in ) throws Error, SpawnError
757 // convert arguments.
759 string[] args = { "git" };
760 //args += "--git-dir";
761 //args += this.gitdir;
762 args += "--no-pager";
765 //if (this.gitdir != this.repopath) {
766 // args += "--work-tree";
767 // args += this.repopath;
769 for (var i = 0; i < args_in.length;i++) {
773 //this.lastCmd = args.join(" ");
775 GLib.debug( "CWD=%s", this.git_working_dir );
776 GLib.debug( "cmd: %s", string.joinv (" ", args));
780 string home = "HOME=" + Environment.get_home_dir() ;
782 // do not need to set gitpath..
783 //if (File.exists(this.repo + '/.git/config')) {
784 //env.push("GITPATH=" + this.repo );
787 var cfg = new SpawnConfig(this.git_working_dir , args , env);
790 // may throw error...
791 var sp = new Spawn(cfg);
793 // diff output is a bit big..
794 if (args_in[0] != "diff") {
795 GLib.debug( "GOT: %s" , sp.output);
797 // parse output for some commands ?
801 unowned GitAsyncCallback git_async_on_callback;
802 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
804 // convert arguments.
805 this.git_async_on_callback = cb;
806 string[] args = { "git" };
807 //args += "--git-dir";
808 //args += this.gitdir;
809 args += "--no-pager";
812 //if (this.gitdir != this.repopath) {
813 // args += "--work-tree";
814 // args += this.repopath;
816 for (var i = 0; i < args_in.length;i++) {
820 //this.lastCmd = args.join(" ");
822 GLib.debug( "CWD=%s", this.git_working_dir );
823 //print( "cmd: %s\n", string.joinv (" ", args));
827 string home = "HOME=" + Environment.get_home_dir() ;
829 // do not need to set gitpath..
830 //if (File.exists(this.repo + '/.git/config')) {
831 //env.push("GITPATH=" + this.repo );
835 var cfg = new SpawnConfig(this.git_working_dir , args , env);
839 // may throw error...
840 var sp = new Spawn(cfg);
843 sp.run(this.git_async_on_complete);
847 void git_async_on_complete(int err, string output)
849 GLib.debug("GOT %d : %s", err, output);
850 this.git_async_on_callback(this, err, output);
861 public void update_async(GitAsyncCallback cb)
863 string[] cmd = { "fetch" , "--all" };
864 this.git_async( cmd , cb);
869 static uint update_all_total = 0;
870 static string update_all_after = "";
872 public static void updateAll(string after)
874 update_all_after = after;
875 var tr = GitRepo.singleton().cache;
878 update_all_total = tr.size;
879 foreach(var repo in tr.values) {
880 if (!repo.is_managed()) {
884 repo.update_async(updateAllCallback);
888 public static void updateAllCallback(GitRepo repo, int err, string res)
894 if (update_all_total > 0 ) {
897 switch (update_all_after) {
899 Clones.singleton().show();