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?
197 if (this.host != "git.roojs.com") { // we can only push to this url. -- unless we have forced it to be managed.
198 return FileUtils.test(this.gitdir + "/.gitlive-managed" , FileTest.EXISTS);
200 // otherwise see if unmanaged is set to disable it..
201 return !FileUtils.test(this.gitdir + "/.gitlive-unmanaged" , FileTest.EXISTS);
206 public bool is_autocommit ()
208 return !FileUtils.test(this.gitdir + "/.gitlive-disable-autocommit" , FileTest.EXISTS);
210 public void set_autocommit(bool val)
213 var cur = this.is_autocommit();
214 GLib.debug("SET auto commit : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
216 return; // no change..
219 FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autocommit" , "x");
222 FileUtils.remove(this.gitdir + "/.gitlive-disable-autocommit" );
227 public bool is_auto_branch ()
229 if (this.name == "gitlog") {
233 if (this.is_managed()) {
241 public void set_auto_branch(bool val)
244 var cur = this.is_auto_branch();
245 GLib.debug("SET auto branch : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
248 return; // no change..
251 FileUtils.set_contents(this.gitdir + "/.gitlive-enable-auto-branch" , "x");
254 FileUtils.remove(this.gitdir + "/.gitlive-enable-auto-branch" );
258 public bool is_autopush ()
260 return !FileUtils.test(this.gitdir + "/.gitlive-disable-autopush" , FileTest.EXISTS);
262 public void set_autopush(bool val)
265 var cur = this.is_autopush();
266 GLib.debug("SET auto push : %s <= %s", val ? "ON" : "OFF", cur ? "ON" : "OFF");
268 return; // no change..
271 FileUtils.set_contents(this.gitdir + "/.gitlive-disable-autopush" , "");
274 FileUtils.remove(this.gitdir + "/.gitlive-disable-autopush" );
280 public void loadStatus()
282 var r = this.git({ "status" , "--porcelain" });
284 this.has_local_changes = r.length > 0;
286 var rs = this.git({ "status" , "-sb" });
288 this.ahead_or_behind = rs.contains("[ahead") ? "A" : (rs.contains("[behind") ? "B" : "");
291 this.git_diff = this.git({ "diff" , "HEAD", "--no-color" });
295 public void loadBranches()
298 GitBranch.loadBranches(this);
304 public string branchesToString()
307 foreach( var br in this.branches.values) {
311 ret += ret.length > 0 ? "\n" : "";
318 public static void doMerges(string action, string ticket_id, string commit_message)
320 GitMonitor.gitmonitor.stop();
324 foreach(var repo in GitRepo.singleton().cache.values) {
325 if (repo.activeTicket != null && repo.activeTicket.id == ticket_id) {
326 var res = repo.doMerge(action,ticket_id, commit_message);
331 commitrevs += commitrevs.length > 0 ? " " : "";
332 commitrevs += repo.currentBranch.lastrev;
335 if (sucess && action == "CLOSE") {
336 RooTicket.singleton().getById(ticket_id).close(commitrevs);
338 GitMonitor.gitmonitor.start();
342 public bool doMerge(string action, string ticket_id, string commit_message)
344 // in theory we should check to see if other repo's have got the same branch and merge all them at the same time.
345 // also need to decide which branch we will merge into?
347 if (action == "CLOSE" || action == "LEAVE") {
350 var oldbranch = this.currentBranch.name;
351 this.setActiveTicket(null, "master");
352 string [] cmd = { "merge", "--squash", oldbranch };
354 cmd = { "commit", "-a" , "-m", commit_message };
357 this.loadBranches(); // updates lastrev..
359 var notification = new Notify.Notification(
360 "Merged branch %s to master".printf(oldbranch),
366 notification.set_timeout(5);
374 GitMonitor.gitmonitor.pauseError(e.message);
377 // error~?? -- show the error dialog...
380 if (action == "MASTER") {
381 // merge master into ours..
383 string[] cmd = { "merge", "master" };
385 var notification = new Notify.Notification(
386 "Merged code from master to %s".printf(this.currentBranch.name),
391 notification.set_timeout(5);
396 GitMonitor.gitmonitor.pauseError(e.message);
400 if (action == "EXIT") {
402 var oldbranch = this.currentBranch.name;
403 this.setActiveTicket(null, "master");
405 var notification = new Notify.Notification(
406 "Left branch %s".printf(oldbranch),
411 notification.set_timeout(5);
416 GitMonitor.gitmonitor.pauseError(e.message);
420 // error~?? -- show the error dialog...
426 public void loadActiveTicket()
428 this.activeTicket = null;
429 if (!FileUtils.test(this.gitdir + "/.gitlive-active-ticket" , FileTest.EXISTS)) {
433 FileUtils.get_contents(this.gitdir + "/.gitlive-active-ticket" , out ticket_id);
434 if (ticket_id.length < 1) {
437 this.activeTicket = RooTicket.singleton().getById(ticket_id.strip());
444 public bool setActiveTicket(RooTicket? ticket, string branchname)
446 if (!this.createBranchNamed(branchname)) {
449 if (ticket != null) {
450 FileUtils.set_contents(this.gitdir + "/.gitlive-active-ticket" , ticket.id);
452 FileUtils.remove(this.gitdir + "/.gitlive-active-ticket" );
454 this.activeTicket = ticket;
458 public bool createBranchNamed(string branchname)
462 if (this.branches.has_key(branchname)) {
463 this.switchToExistingBranchNamed(branchname);
466 this.createNewBranchNamed(branchname);
469 var notification = new Notify.Notification(
470 "Changed to branch %s".printf(branchname),
476 notification.set_timeout(5);
480 this.loadBranches(); // update branch list...
481 //GitMonitor.gitmonitor.runQueue(); // no point - we have hidden the queue..
484 bool switchToExistingBranchNamed(string branchname)
487 // this is where it get's tricky...
490 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
491 files = this.git(cmd);
492 stash = files.length> 1 ;
496 if (stash) { this.git(cmd); }
500 cmd = { "checkout", branchname };
503 GitMonitor.gitmonitor.pauseError(e.message);
507 if (branchname != "master") {
508 string[] cmd = { "merge", "master" };
515 string[] cmd = { "checkout", "master" };
517 GitMonitor.gitmonitor.pauseError(
518 "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(
526 string[] cmd = { "stash", "pop" };
529 var fl = files.split("\n");
530 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
531 foreach(var f in fl) {
532 if (f.length < 1) continue;
541 GitMonitor.gitmonitor.pauseError(ee.message);
551 bool createNewBranchNamed(string branchname)
555 string[] cmd = { "ls-files" , "-m" }; // list the modified files..
556 var files = this.git(cmd);
557 stash = files.length> 1 ;
559 cmd = { "checkout", "-b" , branchname };
562 cmd = { "push", "-u" , "origin" ,"HEAD" };
566 var fl = files.split("\n");
567 cmd = { "commit", "-m" , "Changed " + string.joinv("",fl) };
568 foreach(var f in fl) {
569 if (f.length < 1) continue;
578 GitMonitor.gitmonitor.pauseError(ee.message);
589 * add files to track.
591 * @argument {Array} files the files to add.
593 public string add ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
595 // should really find out if these are untracked files each..
596 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
597 // not sure if that is how git works.. but just be certian.
599 for (var i = 0; i < files.size;i++) {
600 var f = files.get(i).vname;
602 string[] cmd = { "add", f };
605 ret += e.message + "\n";
612 public bool is_ignore(string fname) throws Error, SpawnError
614 if (fname == ".gitignore") {
615 this.ignore_files.clear();
618 if (this.ignore_files.has_key(fname)) {
619 return this.ignore_files.get(fname);
623 var ret = this.git( { "check-ignore" , fname } );
624 this.ignore_files.set(fname, ret.length > 0);
625 return ret.length > 0;
626 } catch (SpawnError e) {
627 this.ignore_files.set(fname, false);
636 * remove files to track.
638 * @argument {Array} files the files to add.
640 public string remove ( Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
642 // this may fail if files do not exist..
643 // should really find out if these are untracked files each..
644 // we run multiple versions to make sure that if one failes, it does not ignore the whole lot..
645 // not sure if that is how git works.. but just be certian.
648 for (var i = 0; i < files.size;i++) {
649 var f = files.get(i).vname;
651 string[] cmd = { "rm", "-f" , f };
654 ret += e.message + "\n";
667 * @argument {Object} cfg commit configuration
669 * @property {String} name (optional)
670 * @property {String} email (optional)
671 * @property {String} changed (date) (optional)
672 * @property {String} reason (optional)
673 * @property {Array} files - the files that have changed.
677 public string commit ( string message, Gee.ArrayList<GitMonitorQueue> files ) throws Error, SpawnError
684 if (typeof(cfg.name) != 'undefined') {
686 'author' : cfg.name + ' <' + cfg.email + '>'
689 "GIT_COMMITTER_NAME" + cfg.name,
690 "GIT_COMMITTER_EMAIL" + cfg.email
694 if (typeof(cfg.changed) != 'undefined') {
695 env.push("GIT_AUTHOR_DATE= " + cfg.changed )
699 string[] args = { "commit", "-m" };
700 args += (message.length > 0 ? message : "Changed" );
701 for (var i = 0; i< files.size ; i++ ) {
702 args += files.get(i).vname; // full path?
705 return this.git(args);
710 * Fetch and merge remote repo changes into current branch..
712 * At present we just need this to update the current working branch..
713 * -- maybe later it will have a few options and do more stuff..
716 public string pull () throws Error, SpawnError
718 // should probably hand error conditions better...
719 string[] cmd = { "pull" , "--no-edit" };
720 return this.git( cmd );
725 public delegate void GitAsyncCallback (GitRepo repo, int err, string str);
726 public void pull_async(GitAsyncCallback cb)
729 string[] cmd = { "pull" , "--no-edit" };
730 this.git_async( cmd , cb);
737 * Send local changes to remote repo(s)
739 * At present we just need this to push the current branch.
740 * -- maybe later it will have a few options and do more stuff..
743 public string push () throws Error, SpawnError
746 return this.git({ "push" });
754 * The meaty part.. run spawn.. with git..
759 public string git(string[] args_in ) throws Error, SpawnError
761 // convert arguments.
763 string[] args = { "git" };
764 //args += "--git-dir";
765 //args += this.gitdir;
766 args += "--no-pager";
769 //if (this.gitdir != this.repopath) {
770 // args += "--work-tree";
771 // args += this.repopath;
773 for (var i = 0; i < args_in.length;i++) {
777 //this.lastCmd = args.join(" ");
779 GLib.debug( "CWD=%s", this.git_working_dir );
780 GLib.debug( "cmd: %s", string.joinv (" ", args));
784 string home = "HOME=" + Environment.get_home_dir() ;
786 // do not need to set gitpath..
787 //if (File.exists(this.repo + '/.git/config')) {
788 //env.push("GITPATH=" + this.repo );
791 var cfg = new SpawnConfig(this.git_working_dir , args , env);
794 // may throw error...
795 var sp = new Spawn(cfg);
797 // diff output is a bit big..
798 if (args_in[0] != "diff") {
799 GLib.debug( "GOT: %s" , sp.output);
801 // parse output for some commands ?
805 unowned GitAsyncCallback git_async_on_callback;
806 public void git_async( string[] args_in, GitAsyncCallback cb ) throws Error, SpawnError
808 // convert arguments.
809 this.git_async_on_callback = cb;
810 string[] args = { "git" };
811 //args += "--git-dir";
812 //args += this.gitdir;
813 args += "--no-pager";
816 //if (this.gitdir != this.repopath) {
817 // args += "--work-tree";
818 // args += this.repopath;
820 for (var i = 0; i < args_in.length;i++) {
824 //this.lastCmd = args.join(" ");
826 GLib.debug( "CWD=%s", this.git_working_dir );
827 //print( "cmd: %s\n", string.joinv (" ", args));
831 string home = "HOME=" + Environment.get_home_dir() ;
833 // do not need to set gitpath..
834 //if (File.exists(this.repo + '/.git/config')) {
835 //env.push("GITPATH=" + this.repo );
839 var cfg = new SpawnConfig(this.git_working_dir , args , env);
843 // may throw error...
844 var sp = new Spawn(cfg);
847 sp.run(this.git_async_on_complete);
851 void git_async_on_complete(int err, string output)
853 GLib.debug("GOT %d : %s", err, output);
854 this.git_async_on_callback(this, err, output);
865 public void update_async(GitAsyncCallback cb)
867 string[] cmd = { "fetch" , "--all" };
868 this.git_async( cmd , cb);
873 static uint update_all_total = 0;
874 static string update_all_after = "";
876 public static void updateAll(string after)
878 update_all_after = after;
879 var tr = GitRepo.singleton().cache;
882 update_all_total = tr.size;
883 foreach(var repo in tr.values) {
884 if (!repo.is_managed()) {
888 repo.update_async(updateAllCallback);
892 public static void updateAllCallback(GitRepo repo, int err, string res)
898 if (update_all_total > 0 ) {
901 switch (update_all_after) {
903 Clones.singleton().show();