3 const char *prefix_path(const char *prefix
, int len
, const char *path
)
5 const char *orig
= path
;
31 /* Remove last component of the prefix */
34 die("'%s' is outside repository", orig
);
36 } while (len
&& prefix
[len
-1] != '/');
40 int speclen
= strlen(path
);
41 char *n
= xmalloc(speclen
+ len
+ 1);
43 memcpy(n
, prefix
, len
);
44 memcpy(n
+ len
, path
, speclen
+1);
50 const char **get_pathspec(const char *prefix
, const char **pathspec
)
52 const char *entry
= *pathspec
;
56 if (!prefix
&& !entry
)
60 static const char *spec
[2];
66 /* Otherwise we have to re-write the entries.. */
68 prefixlen
= prefix
? strlen(prefix
) : 0;
70 *p
= prefix_path(prefix
, prefixlen
, entry
);
71 } while ((entry
= *++p
) != NULL
);
72 return (const char **) pathspec
;
76 * Test if it looks like we're at the top level git directory.
79 * - either a .git/objects/ directory _or_ the proper
80 * GIT_OBJECT_DIRECTORY environment variable
81 * - a refs/ directory under ".git"
82 * - either a HEAD symlink or a HEAD file that is formatted as
85 static int is_toplevel_directory(void)
87 if (access(".git/refs/", X_OK
) ||
88 access(getenv(DB_ENVIRONMENT
) ?
89 getenv(DB_ENVIRONMENT
) : ".git/objects/", X_OK
) ||
90 validate_symref(".git/HEAD"))
95 static const char *setup_git_directory_1(void)
97 static char cwd
[PATH_MAX
+1];
101 * If GIT_DIR is set explicitly, we're not going
102 * to do any discovery, but we still do repository
105 if (getenv(GIT_DIR_ENVIRONMENT
)) {
107 int len
= strlen(getenv(GIT_DIR_ENVIRONMENT
));
108 if (sizeof(path
) - 40 < len
)
109 die("'$%s' too big", GIT_DIR_ENVIRONMENT
);
110 memcpy(path
, getenv(GIT_DIR_ENVIRONMENT
), len
);
112 strcpy(path
+ len
, "/refs");
113 if (access(path
, X_OK
))
114 goto bad_dir_environ
;
115 strcpy(path
+ len
, "/HEAD");
116 if (validate_symref(path
))
117 goto bad_dir_environ
;
118 if (getenv(DB_ENVIRONMENT
)) {
119 if (access(DB_ENVIRONMENT
, X_OK
))
120 goto bad_dir_environ
;
123 strcpy(path
+ len
, "/objects");
124 if (access(path
, X_OK
))
125 goto bad_dir_environ
;
130 die("Not a git repository: '%s'", path
);
133 if (!getcwd(cwd
, sizeof(cwd
)) || cwd
[0] != '/')
134 die("Unable to read current working directory");
136 offset
= len
= strlen(cwd
);
138 if (is_toplevel_directory())
143 die("Not a git repository");
144 } while (cwd
[--offset
] != '/');
150 /* Make "offset" point to past the '/', and add a '/' at the end */
157 int check_repository_format_version(const char *var
, const char *value
)
159 if (strcmp(var
, "core.repositoryformatversion") == 0)
160 repository_format_version
= git_config_int(var
, value
);
164 int check_repository_format(void)
166 git_config(check_repository_format_version
);
167 if (GIT_REPO_VERSION
< repository_format_version
)
168 die ("Expected git repo version <= %d, found %d",
169 GIT_REPO_VERSION
, repository_format_version
);
173 const char *setup_git_directory(void)
175 const char *retval
= setup_git_directory_1();
176 check_repository_format();