Subject: [PATCH v2 5/6] config.c: allow to un-share certain config in multi-worktree setup

From: Nguyễn Thái Ngọc Duy <[email-masked]>
Date: Sun, 27 Dec 2015 10:14:38 +0700

Repo ext worktree=1 provides a set of config vars that _must_ be
per-worktree. However, the user may want to make some more config vars
per-worktree, depending on their workflow.

include.path is extended to make this possible. If the given path is
in the form "$GIT_xyz/abc" then "$GIT_xyz" will be expanded using the
corresponding environment variable. To unshare, the user can save
config in, for example, $GIT_DIR/worktrees/<id>/config.worktree and
specify this in $GIT_DIR/config

    include.path = $GIT_DIR/config.worktree

Signed-off-by: Nguyễn Thái Ngọc Duy <[email-masked]>
---
 cache.h       |  1 +
 config.c      | 26 ++++++++++++++++++++++++++
 environment.c | 13 +++++++++++++
 3 files changed, 40 insertions(+)

diff --git a/cache.h b/cache.h
index 10f4ff8..cc00ca1 100644
--- a/cache.h
+++ b/cache.h
@@ -454,6 +454,7 @@ extern int is_bare_repository(void);
 extern int is_inside_git_dir(void);
 extern char *git_work_tree_cfg;
 extern int is_inside_work_tree(void);
+extern const char *get_git_env(const char *name);
 extern const char *get_git_dir(void);
 extern const char *get_git_common_dir(void);
 extern int is_git_directory(const char *path);
diff --git a/config.c b/config.c
index 5aa1379..eb951f5 100644
--- a/config.c
+++ b/config.c
@@ -155,6 +155,32 @@ static int handle_path_include(const char *path, struct config_include_data *inc
 	expanded = expand_user_path(path);
 	if (!expanded)
 		return error("Could not expand include path '%s'", path);
+
+	if (starts_with(expanded, "$GIT_")) {
+		char *slash = expanded;
+		const char *base = NULL;
+		struct strbuf sb = STRBUF_INIT;
+
+		while (*slash && !is_dir_sep(*slash))
+			slash++;
+
+		if (*slash) {
+			char saved_slash = *slash;
+			*slash = '\0';
+			base = get_git_env(expanded + 1);
+			*slash = saved_slash;
+		}
+
+		if (!base) {
+			free(expanded);
+			return error("Could not expand include path '%s'", path);
+		}
+
+		strbuf_addstr(&sb, real_path(base));
+		strbuf_addstr(&sb, slash);
+		free(expanded);
+		expanded = strbuf_detach(&sb, NULL);
+	}
 	path = expanded;
 
 	/*
diff --git a/environment.c b/environment.c
index a3f17ed..7a1d62e 100644
--- a/environment.c
+++ b/environment.c
@@ -321,3 +321,16 @@ const char *get_commit_output_encoding(void)
 {
 	return git_commit_encoding ? git_commit_encoding : "UTF-8";
 }
+
+const char *get_git_env(const char *name)
+{
+	if (!strcmp(name, GIT_DIR_ENVIRONMENT))
+		return get_git_dir();
+	else if (!strcmp(name, GIT_WORK_TREE_ENVIRONMENT))
+		return get_git_work_tree();
+	else if (!strcmp(name, GIT_COMMON_DIR_ENVIRONMENT))
+		return get_git_common_dir();
+	// else if ... check environment.c
+	else
+		return getenv(name);
+}
-- 
2.3.0.rc1.137.g477eb31