path.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539
  1. /*
  2. * Utilities for paths and pathnames
  3. */
  4. #include "cache.h"
  5. #include "repository.h"
  6. #include "strbuf.h"
  7. #include "string-list.h"
  8. #include "dir.h"
  9. #include "worktree.h"
  10. #include "submodule-config.h"
  11. #include "path.h"
  12. #include "packfile.h"
  13. #include "object-store.h"
  14. #include "lockfile.h"
  15. static int get_st_mode_bits(const char *path, int *mode)
  16. {
  17. struct stat st;
  18. if (lstat(path, &st) < 0)
  19. return -1;
  20. *mode = st.st_mode;
  21. return 0;
  22. }
  23. static char bad_path[] = "/bad-path/";
  24. static struct strbuf *get_pathname(void)
  25. {
  26. static struct strbuf pathname_array[4] = {
  27. STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
  28. };
  29. static int index;
  30. struct strbuf *sb = &pathname_array[index];
  31. index = (index + 1) % ARRAY_SIZE(pathname_array);
  32. strbuf_reset(sb);
  33. return sb;
  34. }
  35. static const char *cleanup_path(const char *path)
  36. {
  37. /* Clean it up */
  38. if (skip_prefix(path, "./", &path)) {
  39. while (*path == '/')
  40. path++;
  41. }
  42. return path;
  43. }
  44. static void strbuf_cleanup_path(struct strbuf *sb)
  45. {
  46. const char *path = cleanup_path(sb->buf);
  47. if (path > sb->buf)
  48. strbuf_remove(sb, 0, path - sb->buf);
  49. }
  50. char *mksnpath(char *buf, size_t n, const char *fmt, ...)
  51. {
  52. va_list args;
  53. unsigned len;
  54. va_start(args, fmt);
  55. len = vsnprintf(buf, n, fmt, args);
  56. va_end(args);
  57. if (len >= n) {
  58. strlcpy(buf, bad_path, n);
  59. return buf;
  60. }
  61. return (char *)cleanup_path(buf);
  62. }
  63. static int dir_prefix(const char *buf, const char *dir)
  64. {
  65. int len = strlen(dir);
  66. return !strncmp(buf, dir, len) &&
  67. (is_dir_sep(buf[len]) || buf[len] == '\0');
  68. }
  69. /* $buf =~ m|$dir/+$file| but without regex */
  70. static int is_dir_file(const char *buf, const char *dir, const char *file)
  71. {
  72. int len = strlen(dir);
  73. if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
  74. return 0;
  75. while (is_dir_sep(buf[len]))
  76. len++;
  77. return !strcmp(buf + len, file);
  78. }
  79. static void replace_dir(struct strbuf *buf, int len, const char *newdir)
  80. {
  81. int newlen = strlen(newdir);
  82. int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
  83. !is_dir_sep(newdir[newlen - 1]);
  84. if (need_sep)
  85. len--; /* keep one char, to be replaced with '/' */
  86. strbuf_splice(buf, 0, len, newdir, newlen);
  87. if (need_sep)
  88. buf->buf[newlen] = '/';
  89. }
  90. struct common_dir {
  91. /* Not considered garbage for report_linked_checkout_garbage */
  92. unsigned ignore_garbage:1;
  93. unsigned is_dir:1;
  94. /* Belongs to the common dir, though it may contain paths that don't */
  95. unsigned is_common:1;
  96. const char *path;
  97. };
  98. static struct common_dir common_list[] = {
  99. { 0, 1, 1, "branches" },
  100. { 0, 1, 1, "common" },
  101. { 0, 1, 1, "hooks" },
  102. { 0, 1, 1, "info" },
  103. { 0, 0, 0, "info/sparse-checkout" },
  104. { 1, 1, 1, "logs" },
  105. { 1, 0, 0, "logs/HEAD" },
  106. { 0, 1, 0, "logs/refs/bisect" },
  107. { 0, 1, 0, "logs/refs/rewritten" },
  108. { 0, 1, 0, "logs/refs/worktree" },
  109. { 0, 1, 1, "lost-found" },
  110. { 0, 1, 1, "objects" },
  111. { 0, 1, 1, "refs" },
  112. { 0, 1, 0, "refs/bisect" },
  113. { 0, 1, 0, "refs/rewritten" },
  114. { 0, 1, 0, "refs/worktree" },
  115. { 0, 1, 1, "remotes" },
  116. { 0, 1, 1, "worktrees" },
  117. { 0, 1, 1, "rr-cache" },
  118. { 0, 1, 1, "svn" },
  119. { 0, 0, 1, "config" },
  120. { 1, 0, 1, "gc.pid" },
  121. { 0, 0, 1, "packed-refs" },
  122. { 0, 0, 1, "shallow" },
  123. { 0, 0, 0, NULL }
  124. };
  125. /*
  126. * A compressed trie. A trie node consists of zero or more characters that
  127. * are common to all elements with this prefix, optionally followed by some
  128. * children. If value is not NULL, the trie node is a terminal node.
  129. *
  130. * For example, consider the following set of strings:
  131. * abc
  132. * def
  133. * definite
  134. * definition
  135. *
  136. * The trie would look like:
  137. * root: len = 0, children a and d non-NULL, value = NULL.
  138. * a: len = 2, contents = bc, value = (data for "abc")
  139. * d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
  140. * i: len = 3, contents = nit, children e and i non-NULL, value = NULL
  141. * e: len = 0, children all NULL, value = (data for "definite")
  142. * i: len = 2, contents = on, children all NULL,
  143. * value = (data for "definition")
  144. */
  145. struct trie {
  146. struct trie *children[256];
  147. int len;
  148. char *contents;
  149. void *value;
  150. };
  151. static struct trie *make_trie_node(const char *key, void *value)
  152. {
  153. struct trie *new_node = xcalloc(1, sizeof(*new_node));
  154. new_node->len = strlen(key);
  155. if (new_node->len) {
  156. new_node->contents = xmalloc(new_node->len);
  157. memcpy(new_node->contents, key, new_node->len);
  158. }
  159. new_node->value = value;
  160. return new_node;
  161. }
  162. /*
  163. * Add a key/value pair to a trie. The key is assumed to be \0-terminated.
  164. * If there was an existing value for this key, return it.
  165. */
  166. static void *add_to_trie(struct trie *root, const char *key, void *value)
  167. {
  168. struct trie *child;
  169. void *old;
  170. int i;
  171. if (!*key) {
  172. /* we have reached the end of the key */
  173. old = root->value;
  174. root->value = value;
  175. return old;
  176. }
  177. for (i = 0; i < root->len; i++) {
  178. if (root->contents[i] == key[i])
  179. continue;
  180. /*
  181. * Split this node: child will contain this node's
  182. * existing children.
  183. */
  184. child = xmalloc(sizeof(*child));
  185. memcpy(child->children, root->children, sizeof(root->children));
  186. child->len = root->len - i - 1;
  187. if (child->len) {
  188. child->contents = xstrndup(root->contents + i + 1,
  189. child->len);
  190. }
  191. child->value = root->value;
  192. root->value = NULL;
  193. root->len = i;
  194. memset(root->children, 0, sizeof(root->children));
  195. root->children[(unsigned char)root->contents[i]] = child;
  196. /* This is the newly-added child. */
  197. root->children[(unsigned char)key[i]] =
  198. make_trie_node(key + i + 1, value);
  199. return NULL;
  200. }
  201. /* We have matched the entire compressed section */
  202. if (key[i]) {
  203. child = root->children[(unsigned char)key[root->len]];
  204. if (child) {
  205. return add_to_trie(child, key + root->len + 1, value);
  206. } else {
  207. child = make_trie_node(key + root->len + 1, value);
  208. root->children[(unsigned char)key[root->len]] = child;
  209. return NULL;
  210. }
  211. }
  212. old = root->value;
  213. root->value = value;
  214. return old;
  215. }
  216. typedef int (*match_fn)(const char *unmatched, void *value, void *baton);
  217. /*
  218. * Search a trie for some key. Find the longest /-or-\0-terminated
  219. * prefix of the key for which the trie contains a value. If there is
  220. * no such prefix, return -1. Otherwise call fn with the unmatched
  221. * portion of the key and the found value. If fn returns 0 or
  222. * positive, then return its return value. If fn returns negative,
  223. * then call fn with the next-longest /-terminated prefix of the key
  224. * (i.e. a parent directory) for which the trie contains a value, and
  225. * handle its return value the same way. If there is no shorter
  226. * /-terminated prefix with a value left, then return the negative
  227. * return value of the most recent fn invocation.
  228. *
  229. * The key is partially normalized: consecutive slashes are skipped.
  230. *
  231. * For example, consider the trie containing only [logs,
  232. * logs/refs/bisect], both with values, but not logs/refs.
  233. *
  234. * | key | unmatched | prefix to node | return value |
  235. * |--------------------|----------------|------------------|--------------|
  236. * | a | not called | n/a | -1 |
  237. * | logstore | not called | n/a | -1 |
  238. * | logs | \0 | logs | as per fn |
  239. * | logs/ | / | logs | as per fn |
  240. * | logs/refs | /refs | logs | as per fn |
  241. * | logs/refs/ | /refs/ | logs | as per fn |
  242. * | logs/refs/b | /refs/b | logs | as per fn |
  243. * | logs/refs/bisected | /refs/bisected | logs | as per fn |
  244. * | logs/refs/bisect | \0 | logs/refs/bisect | as per fn |
  245. * | logs/refs/bisect/ | / | logs/refs/bisect | as per fn |
  246. * | logs/refs/bisect/a | /a | logs/refs/bisect | as per fn |
  247. * | (If fn in the previous line returns -1, then fn is called once more:) |
  248. * | logs/refs/bisect/a | /refs/bisect/a | logs | as per fn |
  249. * |--------------------|----------------|------------------|--------------|
  250. */
  251. static int trie_find(struct trie *root, const char *key, match_fn fn,
  252. void *baton)
  253. {
  254. int i;
  255. int result;
  256. struct trie *child;
  257. if (!*key) {
  258. /* we have reached the end of the key */
  259. if (root->value && !root->len)
  260. return fn(key, root->value, baton);
  261. else
  262. return -1;
  263. }
  264. for (i = 0; i < root->len; i++) {
  265. /* Partial path normalization: skip consecutive slashes. */
  266. if (key[i] == '/' && key[i+1] == '/') {
  267. key++;
  268. continue;
  269. }
  270. if (root->contents[i] != key[i])
  271. return -1;
  272. }
  273. /* Matched the entire compressed section */
  274. key += i;
  275. if (!*key) {
  276. /* End of key */
  277. if (root->value)
  278. return fn(key, root->value, baton);
  279. else
  280. return -1;
  281. }
  282. /* Partial path normalization: skip consecutive slashes */
  283. while (key[0] == '/' && key[1] == '/')
  284. key++;
  285. child = root->children[(unsigned char)*key];
  286. if (child)
  287. result = trie_find(child, key + 1, fn, baton);
  288. else
  289. result = -1;
  290. if (result >= 0 || (*key != '/' && *key != 0))
  291. return result;
  292. if (root->value)
  293. return fn(key, root->value, baton);
  294. else
  295. return -1;
  296. }
  297. static struct trie common_trie;
  298. static int common_trie_done_setup;
  299. static void init_common_trie(void)
  300. {
  301. struct common_dir *p;
  302. if (common_trie_done_setup)
  303. return;
  304. for (p = common_list; p->path; p++)
  305. add_to_trie(&common_trie, p->path, p);
  306. common_trie_done_setup = 1;
  307. }
  308. /*
  309. * Helper function for update_common_dir: returns 1 if the dir
  310. * prefix is common.
  311. */
  312. static int check_common(const char *unmatched, void *value, void *baton)
  313. {
  314. struct common_dir *dir = value;
  315. if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
  316. return dir->is_common;
  317. if (!dir->is_dir && unmatched[0] == 0)
  318. return dir->is_common;
  319. return 0;
  320. }
  321. static void update_common_dir(struct strbuf *buf, int git_dir_len,
  322. const char *common_dir)
  323. {
  324. char *base = buf->buf + git_dir_len;
  325. int has_lock_suffix = strbuf_strip_suffix(buf, LOCK_SUFFIX);
  326. init_common_trie();
  327. if (trie_find(&common_trie, base, check_common, NULL) > 0)
  328. replace_dir(buf, git_dir_len, common_dir);
  329. if (has_lock_suffix)
  330. strbuf_addstr(buf, LOCK_SUFFIX);
  331. }
  332. void report_linked_checkout_garbage(void)
  333. {
  334. struct strbuf sb = STRBUF_INIT;
  335. const struct common_dir *p;
  336. int len;
  337. if (!the_repository->different_commondir)
  338. return;
  339. strbuf_addf(&sb, "%s/", get_git_dir());
  340. len = sb.len;
  341. for (p = common_list; p->path; p++) {
  342. const char *path = p->path;
  343. if (p->ignore_garbage)
  344. continue;
  345. strbuf_setlen(&sb, len);
  346. strbuf_addstr(&sb, path);
  347. if (file_exists(sb.buf))
  348. report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
  349. }
  350. strbuf_release(&sb);
  351. }
  352. static void adjust_git_path(const struct repository *repo,
  353. struct strbuf *buf, int git_dir_len)
  354. {
  355. const char *base = buf->buf + git_dir_len;
  356. if (is_dir_file(base, "info", "grafts"))
  357. strbuf_splice(buf, 0, buf->len,
  358. repo->graft_file, strlen(repo->graft_file));
  359. else if (!strcmp(base, "index"))
  360. strbuf_splice(buf, 0, buf->len,
  361. repo->index_file, strlen(repo->index_file));
  362. else if (dir_prefix(base, "objects"))
  363. replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
  364. else if (git_hooks_path && dir_prefix(base, "hooks"))
  365. replace_dir(buf, git_dir_len + 5, git_hooks_path);
  366. else if (repo->different_commondir)
  367. update_common_dir(buf, git_dir_len, repo->commondir);
  368. }
  369. static void strbuf_worktree_gitdir(struct strbuf *buf,
  370. const struct repository *repo,
  371. const struct worktree *wt)
  372. {
  373. if (!wt)
  374. strbuf_addstr(buf, repo->gitdir);
  375. else if (!wt->id)
  376. strbuf_addstr(buf, repo->commondir);
  377. else
  378. strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
  379. }
  380. static void do_git_path(const struct repository *repo,
  381. const struct worktree *wt, struct strbuf *buf,
  382. const char *fmt, va_list args)
  383. {
  384. int gitdir_len;
  385. strbuf_worktree_gitdir(buf, repo, wt);
  386. if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
  387. strbuf_addch(buf, '/');
  388. gitdir_len = buf->len;
  389. strbuf_vaddf(buf, fmt, args);
  390. if (!wt)
  391. adjust_git_path(repo, buf, gitdir_len);
  392. strbuf_cleanup_path(buf);
  393. }
  394. char *repo_git_path(const struct repository *repo,
  395. const char *fmt, ...)
  396. {
  397. struct strbuf path = STRBUF_INIT;
  398. va_list args;
  399. va_start(args, fmt);
  400. do_git_path(repo, NULL, &path, fmt, args);
  401. va_end(args);
  402. return strbuf_detach(&path, NULL);
  403. }
  404. void strbuf_repo_git_path(struct strbuf *sb,
  405. const struct repository *repo,
  406. const char *fmt, ...)
  407. {
  408. va_list args;
  409. va_start(args, fmt);
  410. do_git_path(repo, NULL, sb, fmt, args);
  411. va_end(args);
  412. }
  413. char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
  414. {
  415. va_list args;
  416. strbuf_reset(buf);
  417. va_start(args, fmt);
  418. do_git_path(the_repository, NULL, buf, fmt, args);
  419. va_end(args);
  420. return buf->buf;
  421. }
  422. void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
  423. {
  424. va_list args;
  425. va_start(args, fmt);
  426. do_git_path(the_repository, NULL, sb, fmt, args);
  427. va_end(args);
  428. }
  429. const char *git_path(const char *fmt, ...)
  430. {
  431. struct strbuf *pathname = get_pathname();
  432. va_list args;
  433. va_start(args, fmt);
  434. do_git_path(the_repository, NULL, pathname, fmt, args);
  435. va_end(args);
  436. return pathname->buf;
  437. }
  438. char *git_pathdup(const char *fmt, ...)
  439. {
  440. struct strbuf path = STRBUF_INIT;
  441. va_list args;
  442. va_start(args, fmt);
  443. do_git_path(the_repository, NULL, &path, fmt, args);
  444. va_end(args);
  445. return strbuf_detach(&path, NULL);
  446. }
  447. char *mkpathdup(const char *fmt, ...)
  448. {
  449. struct strbuf sb = STRBUF_INIT;
  450. va_list args;
  451. va_start(args, fmt);
  452. strbuf_vaddf(&sb, fmt, args);
  453. va_end(args);
  454. strbuf_cleanup_path(&sb);
  455. return strbuf_detach(&sb, NULL);
  456. }
  457. const char *mkpath(const char *fmt, ...)
  458. {
  459. va_list args;
  460. struct strbuf *pathname = get_pathname();
  461. va_start(args, fmt);
  462. strbuf_vaddf(pathname, fmt, args);
  463. va_end(args);
  464. return cleanup_path(pathname->buf);
  465. }
  466. const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
  467. {
  468. struct strbuf *pathname = get_pathname();
  469. va_list args;
  470. va_start(args, fmt);
  471. do_git_path(the_repository, wt, pathname, fmt, args);
  472. va_end(args);
  473. return pathname->buf;
  474. }
  475. static void do_worktree_path(const struct repository *repo,
  476. struct strbuf *buf,
  477. const char *fmt, va_list args)
  478. {
  479. strbuf_addstr(buf, repo->worktree);
  480. if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
  481. strbuf_addch(buf, '/');
  482. strbuf_vaddf(buf, fmt, args);
  483. strbuf_cleanup_path(buf);
  484. }
  485. char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
  486. {
  487. struct strbuf path = STRBUF_INIT;
  488. va_list args;
  489. if (!repo->worktree)
  490. return NULL;
  491. va_start(args, fmt);
  492. do_worktree_path(repo, &path, fmt, args);
  493. va_end(args);
  494. return strbuf_detach(&path, NULL);
  495. }
  496. void strbuf_repo_worktree_path(struct strbuf *sb,
  497. const struct repository *repo,
  498. const char *fmt, ...)
  499. {
  500. va_list args;
  501. if (!repo->worktree)
  502. return;
  503. va_start(args, fmt);
  504. do_worktree_path(repo, sb, fmt, args);
  505. va_end(args);
  506. }
  507. /* Returns 0 on success, negative on failure. */
  508. static int do_submodule_path(struct strbuf *buf, const char *path,
  509. const char *fmt, va_list args)
  510. {
  511. struct strbuf git_submodule_common_dir = STRBUF_INIT;
  512. struct strbuf git_submodule_dir = STRBUF_INIT;
  513. int ret;
  514. ret = submodule_to_gitdir(&git_submodule_dir, path);
  515. if (ret)
  516. goto cleanup;
  517. strbuf_complete(&git_submodule_dir, '/');
  518. strbuf_addbuf(buf, &git_submodule_dir);
  519. strbuf_vaddf(buf, fmt, args);
  520. if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
  521. update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
  522. strbuf_cleanup_path(buf);
  523. cleanup:
  524. strbuf_release(&git_submodule_dir);
  525. strbuf_release(&git_submodule_common_dir);
  526. return ret;
  527. }
  528. char *git_pathdup_submodule(const char *path, const char *fmt, ...)
  529. {
  530. int err;
  531. va_list args;
  532. struct strbuf buf = STRBUF_INIT;
  533. va_start(args, fmt);
  534. err = do_submodule_path(&buf, path, fmt, args);
  535. va_end(args);
  536. if (err) {
  537. strbuf_release(&buf);
  538. return NULL;
  539. }
  540. return strbuf_detach(&buf, NULL);
  541. }
  542. int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
  543. const char *fmt, ...)
  544. {
  545. int err;
  546. va_list args;
  547. va_start(args, fmt);
  548. err = do_submodule_path(buf, path, fmt, args);
  549. va_end(args);
  550. return err;
  551. }
  552. static void do_git_common_path(const struct repository *repo,
  553. struct strbuf *buf,
  554. const char *fmt,
  555. va_list args)
  556. {
  557. strbuf_addstr(buf, repo->commondir);
  558. if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
  559. strbuf_addch(buf, '/');
  560. strbuf_vaddf(buf, fmt, args);
  561. strbuf_cleanup_path(buf);
  562. }
  563. const char *git_common_path(const char *fmt, ...)
  564. {
  565. struct strbuf *pathname = get_pathname();
  566. va_list args;
  567. va_start(args, fmt);
  568. do_git_common_path(the_repository, pathname, fmt, args);
  569. va_end(args);
  570. return pathname->buf;
  571. }
  572. void strbuf_git_common_path(struct strbuf *sb,
  573. const struct repository *repo,
  574. const char *fmt, ...)
  575. {
  576. va_list args;
  577. va_start(args, fmt);
  578. do_git_common_path(repo, sb, fmt, args);
  579. va_end(args);
  580. }
  581. int validate_headref(const char *path)
  582. {
  583. struct stat st;
  584. char buffer[256];
  585. const char *refname;
  586. struct object_id oid;
  587. int fd;
  588. ssize_t len;
  589. if (lstat(path, &st) < 0)
  590. return -1;
  591. /* Make sure it is a "refs/.." symlink */
  592. if (S_ISLNK(st.st_mode)) {
  593. len = readlink(path, buffer, sizeof(buffer)-1);
  594. if (len >= 5 && !memcmp("refs/", buffer, 5))
  595. return 0;
  596. return -1;
  597. }
  598. /*
  599. * Anything else, just open it and try to see if it is a symbolic ref.
  600. */
  601. fd = open(path, O_RDONLY);
  602. if (fd < 0)
  603. return -1;
  604. len = read_in_full(fd, buffer, sizeof(buffer)-1);
  605. close(fd);
  606. if (len < 0)
  607. return -1;
  608. buffer[len] = '\0';
  609. /*
  610. * Is it a symbolic ref?
  611. */
  612. if (skip_prefix(buffer, "ref:", &refname)) {
  613. while (isspace(*refname))
  614. refname++;
  615. if (starts_with(refname, "refs/"))
  616. return 0;
  617. }
  618. /*
  619. * Is this a detached HEAD?
  620. */
  621. if (!get_oid_hex(buffer, &oid))
  622. return 0;
  623. return -1;
  624. }
  625. static struct passwd *getpw_str(const char *username, size_t len)
  626. {
  627. struct passwd *pw;
  628. char *username_z = xmemdupz(username, len);
  629. pw = getpwnam(username_z);
  630. free(username_z);
  631. return pw;
  632. }
  633. /*
  634. * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
  635. * then it is a newly allocated string. Returns NULL on getpw failure or
  636. * if path is NULL.
  637. *
  638. * If real_home is true, strbuf_realpath($HOME) is used in the expansion.
  639. */
  640. char *expand_user_path(const char *path, int real_home)
  641. {
  642. struct strbuf user_path = STRBUF_INIT;
  643. const char *to_copy = path;
  644. if (path == NULL)
  645. goto return_null;
  646. if (path[0] == '~') {
  647. const char *first_slash = strchrnul(path, '/');
  648. const char *username = path + 1;
  649. size_t username_len = first_slash - username;
  650. if (username_len == 0) {
  651. const char *home = getenv("HOME");
  652. if (!home)
  653. goto return_null;
  654. if (real_home)
  655. strbuf_add_real_path(&user_path, home);
  656. else
  657. strbuf_addstr(&user_path, home);
  658. #ifdef GIT_WINDOWS_NATIVE
  659. convert_slashes(user_path.buf);
  660. #endif
  661. } else {
  662. struct passwd *pw = getpw_str(username, username_len);
  663. if (!pw)
  664. goto return_null;
  665. strbuf_addstr(&user_path, pw->pw_dir);
  666. }
  667. to_copy = first_slash;
  668. }
  669. strbuf_addstr(&user_path, to_copy);
  670. return strbuf_detach(&user_path, NULL);
  671. return_null:
  672. strbuf_release(&user_path);
  673. return NULL;
  674. }
  675. /*
  676. * First, one directory to try is determined by the following algorithm.
  677. *
  678. * (0) If "strict" is given, the path is used as given and no DWIM is
  679. * done. Otherwise:
  680. * (1) "~/path" to mean path under the running user's home directory;
  681. * (2) "~user/path" to mean path under named user's home directory;
  682. * (3) "relative/path" to mean cwd relative directory; or
  683. * (4) "/absolute/path" to mean absolute directory.
  684. *
  685. * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
  686. * in this order. We select the first one that is a valid git repository, and
  687. * chdir() to it. If none match, or we fail to chdir, we return NULL.
  688. *
  689. * If all goes well, we return the directory we used to chdir() (but
  690. * before ~user is expanded), avoiding getcwd() resolving symbolic
  691. * links. User relative paths are also returned as they are given,
  692. * except DWIM suffixing.
  693. */
  694. const char *enter_repo(const char *path, int strict)
  695. {
  696. static struct strbuf validated_path = STRBUF_INIT;
  697. static struct strbuf used_path = STRBUF_INIT;
  698. if (!path)
  699. return NULL;
  700. if (!strict) {
  701. static const char *suffix[] = {
  702. "/.git", "", ".git/.git", ".git", NULL,
  703. };
  704. const char *gitfile;
  705. int len = strlen(path);
  706. int i;
  707. while ((1 < len) && (path[len-1] == '/'))
  708. len--;
  709. /*
  710. * We can handle arbitrary-sized buffers, but this remains as a
  711. * sanity check on untrusted input.
  712. */
  713. if (PATH_MAX <= len)
  714. return NULL;
  715. strbuf_reset(&used_path);
  716. strbuf_reset(&validated_path);
  717. strbuf_add(&used_path, path, len);
  718. strbuf_add(&validated_path, path, len);
  719. if (used_path.buf[0] == '~') {
  720. char *newpath = expand_user_path(used_path.buf, 0);
  721. if (!newpath)
  722. return NULL;
  723. strbuf_attach(&used_path, newpath, strlen(newpath),
  724. strlen(newpath));
  725. }
  726. for (i = 0; suffix[i]; i++) {
  727. struct stat st;
  728. size_t baselen = used_path.len;
  729. strbuf_addstr(&used_path, suffix[i]);
  730. if (!stat(used_path.buf, &st) &&
  731. (S_ISREG(st.st_mode) ||
  732. (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
  733. strbuf_addstr(&validated_path, suffix[i]);
  734. break;
  735. }
  736. strbuf_setlen(&used_path, baselen);
  737. }
  738. if (!suffix[i])
  739. return NULL;
  740. gitfile = read_gitfile(used_path.buf);
  741. if (gitfile) {
  742. strbuf_reset(&used_path);
  743. strbuf_addstr(&used_path, gitfile);
  744. }
  745. if (chdir(used_path.buf))
  746. return NULL;
  747. path = validated_path.buf;
  748. }
  749. else {
  750. const char *gitfile = read_gitfile(path);
  751. if (gitfile)
  752. path = gitfile;
  753. if (chdir(path))
  754. return NULL;
  755. }
  756. if (is_git_directory(".")) {
  757. set_git_dir(".", 0);
  758. check_repository_format(NULL);
  759. return path;
  760. }
  761. return NULL;
  762. }
  763. static int calc_shared_perm(int mode)
  764. {
  765. int tweak;
  766. if (get_shared_repository() < 0)
  767. tweak = -get_shared_repository();
  768. else
  769. tweak = get_shared_repository();
  770. if (!(mode & S_IWUSR))
  771. tweak &= ~0222;
  772. if (mode & S_IXUSR)
  773. /* Copy read bits to execute bits */
  774. tweak |= (tweak & 0444) >> 2;
  775. if (get_shared_repository() < 0)
  776. mode = (mode & ~0777) | tweak;
  777. else
  778. mode |= tweak;
  779. return mode;
  780. }
  781. int adjust_shared_perm(const char *path)
  782. {
  783. int old_mode, new_mode;
  784. if (!get_shared_repository())
  785. return 0;
  786. if (get_st_mode_bits(path, &old_mode) < 0)
  787. return -1;
  788. new_mode = calc_shared_perm(old_mode);
  789. if (S_ISDIR(old_mode)) {
  790. /* Copy read bits to execute bits */
  791. new_mode |= (new_mode & 0444) >> 2;
  792. new_mode |= FORCE_DIR_SET_GID;
  793. }
  794. if (((old_mode ^ new_mode) & ~S_IFMT) &&
  795. chmod(path, (new_mode & ~S_IFMT)) < 0)
  796. return -2;
  797. return 0;
  798. }
  799. void safe_create_dir(const char *dir, int share)
  800. {
  801. if (mkdir(dir, 0777) < 0) {
  802. if (errno != EEXIST) {
  803. perror(dir);
  804. exit(1);
  805. }
  806. }
  807. else if (share && adjust_shared_perm(dir))
  808. die(_("Could not make %s writable by group"), dir);
  809. }
  810. static int have_same_root(const char *path1, const char *path2)
  811. {
  812. int is_abs1, is_abs2;
  813. is_abs1 = is_absolute_path(path1);
  814. is_abs2 = is_absolute_path(path2);
  815. return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
  816. (!is_abs1 && !is_abs2);
  817. }
  818. /*
  819. * Give path as relative to prefix.
  820. *
  821. * The strbuf may or may not be used, so do not assume it contains the
  822. * returned path.
  823. */
  824. const char *relative_path(const char *in, const char *prefix,
  825. struct strbuf *sb)
  826. {
  827. int in_len = in ? strlen(in) : 0;
  828. int prefix_len = prefix ? strlen(prefix) : 0;
  829. int in_off = 0;
  830. int prefix_off = 0;
  831. int i = 0, j = 0;
  832. if (!in_len)
  833. return "./";
  834. else if (!prefix_len)
  835. return in;
  836. if (have_same_root(in, prefix))
  837. /* bypass dos_drive, for "c:" is identical to "C:" */
  838. i = j = has_dos_drive_prefix(in);
  839. else {
  840. return in;
  841. }
  842. while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
  843. if (is_dir_sep(prefix[i])) {
  844. while (is_dir_sep(prefix[i]))
  845. i++;
  846. while (is_dir_sep(in[j]))
  847. j++;
  848. prefix_off = i;
  849. in_off = j;
  850. } else {
  851. i++;
  852. j++;
  853. }
  854. }
  855. if (
  856. /* "prefix" seems like prefix of "in" */
  857. i >= prefix_len &&
  858. /*
  859. * but "/foo" is not a prefix of "/foobar"
  860. * (i.e. prefix not end with '/')
  861. */
  862. prefix_off < prefix_len) {
  863. if (j >= in_len) {
  864. /* in="/a/b", prefix="/a/b" */
  865. in_off = in_len;
  866. } else if (is_dir_sep(in[j])) {
  867. /* in="/a/b/c", prefix="/a/b" */
  868. while (is_dir_sep(in[j]))
  869. j++;
  870. in_off = j;
  871. } else {
  872. /* in="/a/bbb/c", prefix="/a/b" */
  873. i = prefix_off;
  874. }
  875. } else if (
  876. /* "in" is short than "prefix" */
  877. j >= in_len &&
  878. /* "in" not end with '/' */
  879. in_off < in_len) {
  880. if (is_dir_sep(prefix[i])) {
  881. /* in="/a/b", prefix="/a/b/c/" */
  882. while (is_dir_sep(prefix[i]))
  883. i++;
  884. in_off = in_len;
  885. }
  886. }
  887. in += in_off;
  888. in_len -= in_off;
  889. if (i >= prefix_len) {
  890. if (!in_len)
  891. return "./";
  892. else
  893. return in;
  894. }
  895. strbuf_reset(sb);
  896. strbuf_grow(sb, in_len);
  897. while (i < prefix_len) {
  898. if (is_dir_sep(prefix[i])) {
  899. strbuf_addstr(sb, "../");
  900. while (is_dir_sep(prefix[i]))
  901. i++;
  902. continue;
  903. }
  904. i++;
  905. }
  906. if (!is_dir_sep(prefix[prefix_len - 1]))
  907. strbuf_addstr(sb, "../");
  908. strbuf_addstr(sb, in);
  909. return sb->buf;
  910. }
  911. /*
  912. * A simpler implementation of relative_path
  913. *
  914. * Get relative path by removing "prefix" from "in". This function
  915. * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
  916. * to increase performance when traversing the path to work_tree.
  917. */
  918. const char *remove_leading_path(const char *in, const char *prefix)
  919. {
  920. static struct strbuf buf = STRBUF_INIT;
  921. int i = 0, j = 0;
  922. if (!prefix || !prefix[0])
  923. return in;
  924. while (prefix[i]) {
  925. if (is_dir_sep(prefix[i])) {
  926. if (!is_dir_sep(in[j]))
  927. return in;
  928. while (is_dir_sep(prefix[i]))
  929. i++;
  930. while (is_dir_sep(in[j]))
  931. j++;
  932. continue;
  933. } else if (in[j] != prefix[i]) {
  934. return in;
  935. }
  936. i++;
  937. j++;
  938. }
  939. if (
  940. /* "/foo" is a prefix of "/foo" */
  941. in[j] &&
  942. /* "/foo" is not a prefix of "/foobar" */
  943. !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
  944. )
  945. return in;
  946. while (is_dir_sep(in[j]))
  947. j++;
  948. strbuf_reset(&buf);
  949. if (!in[j])
  950. strbuf_addstr(&buf, ".");
  951. else
  952. strbuf_addstr(&buf, in + j);
  953. return buf.buf;
  954. }
  955. /*
  956. * It is okay if dst == src, but they should not overlap otherwise.
  957. * The "dst" buffer must be at least as long as "src"; normalizing may shrink
  958. * the size of the path, but will never grow it.
  959. *
  960. * Performs the following normalizations on src, storing the result in dst:
  961. * - Ensures that components are separated by '/' (Windows only)
  962. * - Squashes sequences of '/' except "//server/share" on Windows
  963. * - Removes "." components.
  964. * - Removes ".." components, and the components the precede them.
  965. * Returns failure (non-zero) if a ".." component appears as first path
  966. * component anytime during the normalization. Otherwise, returns success (0).
  967. *
  968. * Note that this function is purely textual. It does not follow symlinks,
  969. * verify the existence of the path, or make any system calls.
  970. *
  971. * prefix_len != NULL is for a specific case of prefix_pathspec():
  972. * assume that src == dst and src[0..prefix_len-1] is already
  973. * normalized, any time "../" eats up to the prefix_len part,
  974. * prefix_len is reduced. In the end prefix_len is the remaining
  975. * prefix that has not been overridden by user pathspec.
  976. *
  977. * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
  978. * For everything but the root folder itself, the normalized path should not
  979. * end with a '/', then the callers need to be fixed up accordingly.
  980. *
  981. */
  982. int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
  983. {
  984. char *dst0;
  985. const char *end;
  986. /*
  987. * Copy initial part of absolute path: "/", "C:/", "//server/share/".
  988. */
  989. end = src + offset_1st_component(src);
  990. while (src < end) {
  991. char c = *src++;
  992. if (is_dir_sep(c))
  993. c = '/';
  994. *dst++ = c;
  995. }
  996. dst0 = dst;
  997. while (is_dir_sep(*src))
  998. src++;
  999. for (;;) {
  1000. char c = *src;
  1001. /*
  1002. * A path component that begins with . could be
  1003. * special:
  1004. * (1) "." and ends -- ignore and terminate.
  1005. * (2) "./" -- ignore them, eat slash and continue.
  1006. * (3) ".." and ends -- strip one and terminate.
  1007. * (4) "../" -- strip one, eat slash and continue.
  1008. */
  1009. if (c == '.') {
  1010. if (!src[1]) {
  1011. /* (1) */
  1012. src++;
  1013. } else if (is_dir_sep(src[1])) {
  1014. /* (2) */
  1015. src += 2;
  1016. while (is_dir_sep(*src))
  1017. src++;
  1018. continue;
  1019. } else if (src[1] == '.') {
  1020. if (!src[2]) {
  1021. /* (3) */
  1022. src += 2;
  1023. goto up_one;
  1024. } else if (is_dir_sep(src[2])) {
  1025. /* (4) */
  1026. src += 3;
  1027. while (is_dir_sep(*src))
  1028. src++;
  1029. goto up_one;
  1030. }
  1031. }
  1032. }
  1033. /* copy up to the next '/', and eat all '/' */
  1034. while ((c = *src++) != '\0' && !is_dir_sep(c))
  1035. *dst++ = c;
  1036. if (is_dir_sep(c)) {
  1037. *dst++ = '/';
  1038. while (is_dir_sep(c))
  1039. c = *src++;
  1040. src--;
  1041. } else if (!c)
  1042. break;
  1043. continue;
  1044. up_one:
  1045. /*
  1046. * dst0..dst is prefix portion, and dst[-1] is '/';
  1047. * go up one level.
  1048. */
  1049. dst--; /* go to trailing '/' */
  1050. if (dst <= dst0)
  1051. return -1;
  1052. /* Windows: dst[-1] cannot be backslash anymore */
  1053. while (dst0 < dst && dst[-1] != '/')
  1054. dst--;
  1055. if (prefix_len && *prefix_len > dst - dst0)
  1056. *prefix_len = dst - dst0;
  1057. }
  1058. *dst = '\0';
  1059. return 0;
  1060. }
  1061. int normalize_path_copy(char *dst, const char *src)
  1062. {
  1063. return normalize_path_copy_len(dst, src, NULL);
  1064. }
  1065. /*
  1066. * path = Canonical absolute path
  1067. * prefixes = string_list containing normalized, absolute paths without
  1068. * trailing slashes (except for the root directory, which is denoted by "/").
  1069. *
  1070. * Determines, for each path in prefixes, whether the "prefix"
  1071. * is an ancestor directory of path. Returns the length of the longest
  1072. * ancestor directory, excluding any trailing slashes, or -1 if no prefix
  1073. * is an ancestor. (Note that this means 0 is returned if prefixes is
  1074. * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
  1075. * are not considered to be their own ancestors. path must be in a
  1076. * canonical form: empty components, or "." or ".." components are not
  1077. * allowed.
  1078. */
  1079. int longest_ancestor_length(const char *path, struct string_list *prefixes)
  1080. {
  1081. int i, max_len = -1;
  1082. if (!strcmp(path, "/"))
  1083. return -1;
  1084. for (i = 0; i < prefixes->nr; i++) {
  1085. const char *ceil = prefixes->items[i].string;
  1086. int len = strlen(ceil);
  1087. if (len == 1 && ceil[0] == '/')
  1088. len = 0; /* root matches anything, with length 0 */
  1089. else if (!strncmp(path, ceil, len) && path[len] == '/')
  1090. ; /* match of length len */
  1091. else
  1092. continue; /* no match */
  1093. if (len > max_len)
  1094. max_len = len;
  1095. }
  1096. return max_len;
  1097. }
  1098. /* strip arbitrary amount of directory separators at end of path */
  1099. static inline int chomp_trailing_dir_sep(const char *path, int len)
  1100. {
  1101. while (len && is_dir_sep(path[len - 1]))
  1102. len--;
  1103. return len;
  1104. }
  1105. /*
  1106. * If path ends with suffix (complete path components), returns the offset of
  1107. * the last character in the path before the suffix (sans trailing directory
  1108. * separators), and -1 otherwise.
  1109. */
  1110. static ssize_t stripped_path_suffix_offset(const char *path, const char *suffix)
  1111. {
  1112. int path_len = strlen(path), suffix_len = strlen(suffix);
  1113. while (suffix_len) {
  1114. if (!path_len)
  1115. return -1;
  1116. if (is_dir_sep(path[path_len - 1])) {
  1117. if (!is_dir_sep(suffix[suffix_len - 1]))
  1118. return -1;
  1119. path_len = chomp_trailing_dir_sep(path, path_len);
  1120. suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
  1121. }
  1122. else if (path[--path_len] != suffix[--suffix_len])
  1123. return -1;
  1124. }
  1125. if (path_len && !is_dir_sep(path[path_len - 1]))
  1126. return -1;
  1127. return chomp_trailing_dir_sep(path, path_len);
  1128. }
  1129. /*
  1130. * Returns true if the path ends with components, considering only complete path
  1131. * components, and false otherwise.
  1132. */
  1133. int ends_with_path_components(const char *path, const char *components)
  1134. {
  1135. return stripped_path_suffix_offset(path, components) != -1;
  1136. }
  1137. /*
  1138. * If path ends with suffix (complete path components), returns the
  1139. * part before suffix (sans trailing directory separators).
  1140. * Otherwise returns NULL.
  1141. */
  1142. char *strip_path_suffix(const char *path, const char *suffix)
  1143. {
  1144. ssize_t offset = stripped_path_suffix_offset(path, suffix);
  1145. return offset == -1 ? NULL : xstrndup(path, offset);
  1146. }
  1147. int daemon_avoid_alias(const char *p)
  1148. {
  1149. int sl, ndot;
  1150. /*
  1151. * This resurrects the belts and suspenders paranoia check by HPA
  1152. * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
  1153. * does not do getcwd() based path canonicalization.
  1154. *
  1155. * sl becomes true immediately after seeing '/' and continues to
  1156. * be true as long as dots continue after that without intervening
  1157. * non-dot character.
  1158. */
  1159. if (!p || (*p != '/' && *p != '~'))
  1160. return -1;
  1161. sl = 1; ndot = 0;
  1162. p++;
  1163. while (1) {
  1164. char ch = *p++;
  1165. if (sl) {
  1166. if (ch == '.')
  1167. ndot++;
  1168. else if (ch == '/') {
  1169. if (ndot < 3)
  1170. /* reject //, /./ and /../ */
  1171. return -1;
  1172. ndot = 0;
  1173. }
  1174. else if (ch == 0) {
  1175. if (0 < ndot && ndot < 3)
  1176. /* reject /.$ and /..$ */
  1177. return -1;
  1178. return 0;
  1179. }
  1180. else
  1181. sl = ndot = 0;
  1182. }
  1183. else if (ch == 0)
  1184. return 0;
  1185. else if (ch == '/') {
  1186. sl = 1;
  1187. ndot = 0;
  1188. }
  1189. }
  1190. }
  1191. /*
  1192. * On NTFS, we need to be careful to disallow certain synonyms of the `.git/`
  1193. * directory:
  1194. *
  1195. * - For historical reasons, file names that end in spaces or periods are
  1196. * automatically trimmed. Therefore, `.git . . ./` is a valid way to refer
  1197. * to `.git/`.
  1198. *
  1199. * - For other historical reasons, file names that do not conform to the 8.3
  1200. * format (up to eight characters for the basename, three for the file
  1201. * extension, certain characters not allowed such as `+`, etc) are associated
  1202. * with a so-called "short name", at least on the `C:` drive by default.
  1203. * Which means that `git~1/` is a valid way to refer to `.git/`.
  1204. *
  1205. * Note: Technically, `.git/` could receive the short name `git~2` if the
  1206. * short name `git~1` were already used. In Git, however, we guarantee that
  1207. * `.git` is the first item in a directory, therefore it will be associated
  1208. * with the short name `git~1` (unless short names are disabled).
  1209. *
  1210. * - For yet other historical reasons, NTFS supports so-called "Alternate Data
  1211. * Streams", i.e. metadata associated with a given file, referred to via
  1212. * `<filename>:<stream-name>:<stream-type>`. There exists a default stream
  1213. * type for directories, allowing `.git/` to be accessed via
  1214. * `.git::$INDEX_ALLOCATION/`.
  1215. *
  1216. * When this function returns 1, it indicates that the specified file/directory
  1217. * name refers to a `.git` file or directory, or to any of these synonyms, and
  1218. * Git should therefore not track it.
  1219. *
  1220. * For performance reasons, _all_ Alternate Data Streams of `.git/` are
  1221. * forbidden, not just `::$INDEX_ALLOCATION`.
  1222. *
  1223. * This function is intended to be used by `git fsck` even on platforms where
  1224. * the backslash is a regular filename character, therefore it needs to handle
  1225. * backlash characters in the provided `name` specially: they are interpreted
  1226. * as directory separators.
  1227. */
  1228. int is_ntfs_dotgit(const char *name)
  1229. {
  1230. char c;
  1231. /*
  1232. * Note that when we don't find `.git` or `git~1` we end up with `name`
  1233. * advanced partway through the string. That's okay, though, as we
  1234. * return immediately in those cases, without looking at `name` any
  1235. * further.
  1236. */
  1237. c = *(name++);
  1238. if (c == '.') {
  1239. /* .git */
  1240. if (((c = *(name++)) != 'g' && c != 'G') ||
  1241. ((c = *(name++)) != 'i' && c != 'I') ||
  1242. ((c = *(name++)) != 't' && c != 'T'))
  1243. return 0;
  1244. } else if (c == 'g' || c == 'G') {
  1245. /* git ~1 */
  1246. if (((c = *(name++)) != 'i' && c != 'I') ||
  1247. ((c = *(name++)) != 't' && c != 'T') ||
  1248. *(name++) != '~' ||
  1249. *(name++) != '1')
  1250. return 0;
  1251. } else
  1252. return 0;
  1253. for (;;) {
  1254. c = *(name++);
  1255. if (!c || c == '\\' || c == '/' || c == ':')
  1256. return 1;
  1257. if (c != '.' && c != ' ')
  1258. return 0;
  1259. }
  1260. }
  1261. static int is_ntfs_dot_generic(const char *name,
  1262. const char *dotgit_name,
  1263. size_t len,
  1264. const char *dotgit_ntfs_shortname_prefix)
  1265. {
  1266. int saw_tilde;
  1267. size_t i;
  1268. if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
  1269. i = len + 1;
  1270. only_spaces_and_periods:
  1271. for (;;) {
  1272. char c = name[i++];
  1273. if (!c || c == ':')
  1274. return 1;
  1275. if (c != ' ' && c != '.')
  1276. return 0;
  1277. }
  1278. }
  1279. /*
  1280. * Is it a regular NTFS short name, i.e. shortened to 6 characters,
  1281. * followed by ~1, ... ~4?
  1282. */
  1283. if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
  1284. name[7] >= '1' && name[7] <= '4') {
  1285. i = 8;
  1286. goto only_spaces_and_periods;
  1287. }
  1288. /*
  1289. * Is it a fall-back NTFS short name (for details, see
  1290. * https://en.wikipedia.org/wiki/8.3_filename?
  1291. */
  1292. for (i = 0, saw_tilde = 0; i < 8; i++)
  1293. if (name[i] == '\0')
  1294. return 0;
  1295. else if (saw_tilde) {
  1296. if (name[i] < '0' || name[i] > '9')
  1297. return 0;
  1298. } else if (name[i] == '~') {
  1299. if (name[++i] < '1' || name[i] > '9')
  1300. return 0;
  1301. saw_tilde = 1;
  1302. } else if (i >= 6)
  1303. return 0;
  1304. else if (name[i] & 0x80) {
  1305. /*
  1306. * We know our needles contain only ASCII, so we clamp
  1307. * here to make the results of tolower() sane.
  1308. */
  1309. return 0;
  1310. } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
  1311. return 0;
  1312. goto only_spaces_and_periods;
  1313. }
  1314. /*
  1315. * Inline helper to make sure compiler resolves strlen() on literals at
  1316. * compile time.
  1317. */
  1318. static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
  1319. const char *dotgit_ntfs_shortname_prefix)
  1320. {
  1321. return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
  1322. dotgit_ntfs_shortname_prefix);
  1323. }
  1324. int is_ntfs_dotgitmodules(const char *name)
  1325. {
  1326. return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
  1327. }
  1328. int is_ntfs_dotgitignore(const char *name)
  1329. {
  1330. return is_ntfs_dot_str(name, "gitignore", "gi250a");
  1331. }
  1332. int is_ntfs_dotgitattributes(const char *name)
  1333. {
  1334. return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
  1335. }
  1336. int looks_like_command_line_option(const char *str)
  1337. {
  1338. return str && str[0] == '-';
  1339. }
  1340. char *xdg_config_home(const char *filename)
  1341. {
  1342. const char *home, *config_home;
  1343. assert(filename);
  1344. config_home = getenv("XDG_CONFIG_HOME");
  1345. if (config_home && *config_home)
  1346. return mkpathdup("%s/git/%s", config_home, filename);
  1347. home = getenv("HOME");
  1348. if (home)
  1349. return mkpathdup("%s/.config/git/%s", home, filename);
  1350. return NULL;
  1351. }
  1352. char *xdg_cache_home(const char *filename)
  1353. {
  1354. const char *home, *cache_home;
  1355. assert(filename);
  1356. cache_home = getenv("XDG_CACHE_HOME");
  1357. if (cache_home && *cache_home)
  1358. return mkpathdup("%s/git/%s", cache_home, filename);
  1359. home = getenv("HOME");
  1360. if (home)
  1361. return mkpathdup("%s/.cache/git/%s", home, filename);
  1362. return NULL;
  1363. }
  1364. REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
  1365. REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
  1366. REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
  1367. REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
  1368. REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
  1369. REPO_GIT_PATH_FUNC(merge_autostash, "MERGE_AUTOSTASH")
  1370. REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
  1371. REPO_GIT_PATH_FUNC(shallow, "shallow")