THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

2511 lines
68KB

  1. #include "builtin.h"
  2. #include "cache.h"
  3. #include "parse-options.h"
  4. #include "refs.h"
  5. #include "wildmatch.h"
  6. #include "object-store.h"
  7. #include "repository.h"
  8. #include "commit.h"
  9. #include "remote.h"
  10. #include "color.h"
  11. #include "tag.h"
  12. #include "quote.h"
  13. #include "ref-filter.h"
  14. #include "revision.h"
  15. #include "utf8.h"
  16. #include "git-compat-util.h"
  17. #include "version.h"
  18. #include "trailer.h"
  19. #include "wt-status.h"
  20. #include "commit-slab.h"
  21. #include "commit-graph.h"
  22. #include "commit-reach.h"
  23. #include "worktree.h"
  24. #include "hashmap.h"
  25. #include "argv-array.h"
  26. static struct ref_msg {
  27. const char *gone;
  28. const char *ahead;
  29. const char *behind;
  30. const char *ahead_behind;
  31. } msgs = {
  32. /* Untranslated plumbing messages: */
  33. "gone",
  34. "ahead %d",
  35. "behind %d",
  36. "ahead %d, behind %d"
  37. };
  38. void setup_ref_filter_porcelain_msg(void)
  39. {
  40. msgs.gone = _("gone");
  41. msgs.ahead = _("ahead %d");
  42. msgs.behind = _("behind %d");
  43. msgs.ahead_behind = _("ahead %d, behind %d");
  44. }
  45. typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
  46. typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
  47. typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
  48. struct align {
  49. align_type position;
  50. unsigned int width;
  51. };
  52. struct if_then_else {
  53. cmp_status cmp_status;
  54. const char *str;
  55. unsigned int then_atom_seen : 1,
  56. else_atom_seen : 1,
  57. condition_satisfied : 1;
  58. };
  59. struct refname_atom {
  60. enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
  61. int lstrip, rstrip;
  62. };
  63. static struct expand_data {
  64. struct object_id oid;
  65. enum object_type type;
  66. unsigned long size;
  67. off_t disk_size;
  68. struct object_id delta_base_oid;
  69. void *content;
  70. struct object_info info;
  71. } oi, oi_deref;
  72. struct ref_to_worktree_entry {
  73. struct hashmap_entry ent;
  74. struct worktree *wt; /* key is wt->head_ref */
  75. };
  76. static int ref_to_worktree_map_cmpfnc(const void *unused_lookupdata,
  77. const struct hashmap_entry *eptr,
  78. const struct hashmap_entry *kptr,
  79. const void *keydata_aka_refname)
  80. {
  81. const struct ref_to_worktree_entry *e, *k;
  82. e = container_of(eptr, const struct ref_to_worktree_entry, ent);
  83. k = container_of(kptr, const struct ref_to_worktree_entry, ent);
  84. return strcmp(e->wt->head_ref,
  85. keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
  86. }
  87. static struct ref_to_worktree_map {
  88. struct hashmap map;
  89. struct worktree **worktrees;
  90. } ref_to_worktree_map;
  91. /*
  92. * An atom is a valid field atom listed below, possibly prefixed with
  93. * a "*" to denote deref_tag().
  94. *
  95. * We parse given format string and sort specifiers, and make a list
  96. * of properties that we need to extract out of objects. ref_array_item
  97. * structure will hold an array of values extracted that can be
  98. * indexed with the "atom number", which is an index into this
  99. * array.
  100. */
  101. static struct used_atom {
  102. const char *name;
  103. cmp_type type;
  104. info_source source;
  105. union {
  106. char color[COLOR_MAXLEN];
  107. struct align align;
  108. struct {
  109. enum {
  110. RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
  111. } option;
  112. struct refname_atom refname;
  113. unsigned int nobracket : 1, push : 1, push_remote : 1;
  114. } remote_ref;
  115. struct {
  116. enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
  117. struct process_trailer_options trailer_opts;
  118. unsigned int nlines;
  119. } contents;
  120. struct {
  121. cmp_status cmp_status;
  122. const char *str;
  123. } if_then_else;
  124. struct {
  125. enum { O_FULL, O_LENGTH, O_SHORT } option;
  126. unsigned int length;
  127. } objectname;
  128. struct refname_atom refname;
  129. char *head;
  130. } u;
  131. } *used_atom;
  132. static int used_atom_cnt, need_tagged, need_symref;
  133. /*
  134. * Expand string, append it to strbuf *sb, then return error code ret.
  135. * Allow to save few lines of code.
  136. */
  137. static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
  138. {
  139. va_list ap;
  140. va_start(ap, fmt);
  141. strbuf_vaddf(sb, fmt, ap);
  142. va_end(ap);
  143. return ret;
  144. }
  145. static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
  146. const char *color_value, struct strbuf *err)
  147. {
  148. if (!color_value)
  149. return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
  150. if (color_parse(color_value, atom->u.color) < 0)
  151. return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
  152. color_value);
  153. /*
  154. * We check this after we've parsed the color, which lets us complain
  155. * about syntactically bogus color names even if they won't be used.
  156. */
  157. if (!want_color(format->use_color))
  158. color_parse("", atom->u.color);
  159. return 0;
  160. }
  161. static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
  162. const char *name, struct strbuf *err)
  163. {
  164. if (!arg)
  165. atom->option = R_NORMAL;
  166. else if (!strcmp(arg, "short"))
  167. atom->option = R_SHORT;
  168. else if (skip_prefix(arg, "lstrip=", &arg) ||
  169. skip_prefix(arg, "strip=", &arg)) {
  170. atom->option = R_LSTRIP;
  171. if (strtol_i(arg, 10, &atom->lstrip))
  172. return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
  173. } else if (skip_prefix(arg, "rstrip=", &arg)) {
  174. atom->option = R_RSTRIP;
  175. if (strtol_i(arg, 10, &atom->rstrip))
  176. return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
  177. } else
  178. return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
  179. return 0;
  180. }
  181. static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
  182. const char *arg, struct strbuf *err)
  183. {
  184. struct string_list params = STRING_LIST_INIT_DUP;
  185. int i;
  186. if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
  187. atom->u.remote_ref.push = 1;
  188. if (!arg) {
  189. atom->u.remote_ref.option = RR_REF;
  190. return refname_atom_parser_internal(&atom->u.remote_ref.refname,
  191. arg, atom->name, err);
  192. }
  193. atom->u.remote_ref.nobracket = 0;
  194. string_list_split(&params, arg, ',', -1);
  195. for (i = 0; i < params.nr; i++) {
  196. const char *s = params.items[i].string;
  197. if (!strcmp(s, "track"))
  198. atom->u.remote_ref.option = RR_TRACK;
  199. else if (!strcmp(s, "trackshort"))
  200. atom->u.remote_ref.option = RR_TRACKSHORT;
  201. else if (!strcmp(s, "nobracket"))
  202. atom->u.remote_ref.nobracket = 1;
  203. else if (!strcmp(s, "remotename")) {
  204. atom->u.remote_ref.option = RR_REMOTE_NAME;
  205. atom->u.remote_ref.push_remote = 1;
  206. } else if (!strcmp(s, "remoteref")) {
  207. atom->u.remote_ref.option = RR_REMOTE_REF;
  208. atom->u.remote_ref.push_remote = 1;
  209. } else {
  210. atom->u.remote_ref.option = RR_REF;
  211. if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
  212. arg, atom->name, err)) {
  213. string_list_clear(&params, 0);
  214. return -1;
  215. }
  216. }
  217. }
  218. string_list_clear(&params, 0);
  219. return 0;
  220. }
  221. static int objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom,
  222. const char *arg, struct strbuf *err)
  223. {
  224. if (arg)
  225. return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
  226. if (*atom->name == '*')
  227. oi_deref.info.typep = &oi_deref.type;
  228. else
  229. oi.info.typep = &oi.type;
  230. return 0;
  231. }
  232. static int objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom,
  233. const char *arg, struct strbuf *err)
  234. {
  235. if (!arg) {
  236. if (*atom->name == '*')
  237. oi_deref.info.sizep = &oi_deref.size;
  238. else
  239. oi.info.sizep = &oi.size;
  240. } else if (!strcmp(arg, "disk")) {
  241. if (*atom->name == '*')
  242. oi_deref.info.disk_sizep = &oi_deref.disk_size;
  243. else
  244. oi.info.disk_sizep = &oi.disk_size;
  245. } else
  246. return strbuf_addf_ret(err, -1, _("unrecognized %%(objectsize) argument: %s"), arg);
  247. return 0;
  248. }
  249. static int deltabase_atom_parser(const struct ref_format *format, struct used_atom *atom,
  250. const char *arg, struct strbuf *err)
  251. {
  252. if (arg)
  253. return strbuf_addf_ret(err, -1, _("%%(deltabase) does not take arguments"));
  254. if (*atom->name == '*')
  255. oi_deref.info.delta_base_sha1 = oi_deref.delta_base_oid.hash;
  256. else
  257. oi.info.delta_base_sha1 = oi.delta_base_oid.hash;
  258. return 0;
  259. }
  260. static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
  261. const char *arg, struct strbuf *err)
  262. {
  263. if (arg)
  264. return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
  265. atom->u.contents.option = C_BODY_DEP;
  266. return 0;
  267. }
  268. static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
  269. const char *arg, struct strbuf *err)
  270. {
  271. if (arg)
  272. return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
  273. atom->u.contents.option = C_SUB;
  274. return 0;
  275. }
  276. static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
  277. const char *arg, struct strbuf *err)
  278. {
  279. struct string_list params = STRING_LIST_INIT_DUP;
  280. int i;
  281. atom->u.contents.trailer_opts.no_divider = 1;
  282. if (arg) {
  283. string_list_split(&params, arg, ',', -1);
  284. for (i = 0; i < params.nr; i++) {
  285. const char *s = params.items[i].string;
  286. if (!strcmp(s, "unfold"))
  287. atom->u.contents.trailer_opts.unfold = 1;
  288. else if (!strcmp(s, "only"))
  289. atom->u.contents.trailer_opts.only_trailers = 1;
  290. else {
  291. strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
  292. string_list_clear(&params, 0);
  293. return -1;
  294. }
  295. }
  296. }
  297. atom->u.contents.option = C_TRAILERS;
  298. string_list_clear(&params, 0);
  299. return 0;
  300. }
  301. static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
  302. const char *arg, struct strbuf *err)
  303. {
  304. if (!arg)
  305. atom->u.contents.option = C_BARE;
  306. else if (!strcmp(arg, "body"))
  307. atom->u.contents.option = C_BODY;
  308. else if (!strcmp(arg, "signature"))
  309. atom->u.contents.option = C_SIG;
  310. else if (!strcmp(arg, "subject"))
  311. atom->u.contents.option = C_SUB;
  312. else if (skip_prefix(arg, "trailers", &arg)) {
  313. skip_prefix(arg, ":", &arg);
  314. if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
  315. return -1;
  316. } else if (skip_prefix(arg, "lines=", &arg)) {
  317. atom->u.contents.option = C_LINES;
  318. if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
  319. return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
  320. } else
  321. return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
  322. return 0;
  323. }
  324. static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
  325. const char *arg, struct strbuf *err)
  326. {
  327. if (!arg)
  328. atom->u.objectname.option = O_FULL;
  329. else if (!strcmp(arg, "short"))
  330. atom->u.objectname.option = O_SHORT;
  331. else if (skip_prefix(arg, "short=", &arg)) {
  332. atom->u.objectname.option = O_LENGTH;
  333. if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
  334. atom->u.objectname.length == 0)
  335. return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
  336. if (atom->u.objectname.length < MINIMUM_ABBREV)
  337. atom->u.objectname.length = MINIMUM_ABBREV;
  338. } else
  339. return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
  340. return 0;
  341. }
  342. static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
  343. const char *arg, struct strbuf *err)
  344. {
  345. return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
  346. }
  347. static align_type parse_align_position(const char *s)
  348. {
  349. if (!strcmp(s, "right"))
  350. return ALIGN_RIGHT;
  351. else if (!strcmp(s, "middle"))
  352. return ALIGN_MIDDLE;
  353. else if (!strcmp(s, "left"))
  354. return ALIGN_LEFT;
  355. return -1;
  356. }
  357. static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
  358. const char *arg, struct strbuf *err)
  359. {
  360. struct align *align = &atom->u.align;
  361. struct string_list params = STRING_LIST_INIT_DUP;
  362. int i;
  363. unsigned int width = ~0U;
  364. if (!arg)
  365. return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
  366. align->position = ALIGN_LEFT;
  367. string_list_split(&params, arg, ',', -1);
  368. for (i = 0; i < params.nr; i++) {
  369. const char *s = params.items[i].string;
  370. int position;
  371. if (skip_prefix(s, "position=", &s)) {
  372. position = parse_align_position(s);
  373. if (position < 0) {
  374. strbuf_addf(err, _("unrecognized position:%s"), s);
  375. string_list_clear(&params, 0);
  376. return -1;
  377. }
  378. align->position = position;
  379. } else if (skip_prefix(s, "width=", &s)) {
  380. if (strtoul_ui(s, 10, &width)) {
  381. strbuf_addf(err, _("unrecognized width:%s"), s);
  382. string_list_clear(&params, 0);
  383. return -1;
  384. }
  385. } else if (!strtoul_ui(s, 10, &width))
  386. ;
  387. else if ((position = parse_align_position(s)) >= 0)
  388. align->position = position;
  389. else {
  390. strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
  391. string_list_clear(&params, 0);
  392. return -1;
  393. }
  394. }
  395. if (width == ~0U) {
  396. string_list_clear(&params, 0);
  397. return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
  398. }
  399. align->width = width;
  400. string_list_clear(&params, 0);
  401. return 0;
  402. }
  403. static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
  404. const char *arg, struct strbuf *err)
  405. {
  406. if (!arg) {
  407. atom->u.if_then_else.cmp_status = COMPARE_NONE;
  408. return 0;
  409. } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
  410. atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
  411. } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
  412. atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
  413. } else
  414. return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
  415. return 0;
  416. }
  417. static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
  418. const char *arg, struct strbuf *unused_err)
  419. {
  420. atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
  421. return 0;
  422. }
  423. static struct {
  424. const char *name;
  425. info_source source;
  426. cmp_type cmp_type;
  427. int (*parser)(const struct ref_format *format, struct used_atom *atom,
  428. const char *arg, struct strbuf *err);
  429. } valid_atom[] = {
  430. { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
  431. { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
  432. { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
  433. { "objectname", SOURCE_OTHER, FIELD_STR, objectname_atom_parser },
  434. { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
  435. { "tree", SOURCE_OBJ },
  436. { "parent", SOURCE_OBJ },
  437. { "numparent", SOURCE_OBJ, FIELD_ULONG },
  438. { "object", SOURCE_OBJ },
  439. { "type", SOURCE_OBJ },
  440. { "tag", SOURCE_OBJ },
  441. { "author", SOURCE_OBJ },
  442. { "authorname", SOURCE_OBJ },
  443. { "authoremail", SOURCE_OBJ },
  444. { "authordate", SOURCE_OBJ, FIELD_TIME },
  445. { "committer", SOURCE_OBJ },
  446. { "committername", SOURCE_OBJ },
  447. { "committeremail", SOURCE_OBJ },
  448. { "committerdate", SOURCE_OBJ, FIELD_TIME },
  449. { "tagger", SOURCE_OBJ },
  450. { "taggername", SOURCE_OBJ },
  451. { "taggeremail", SOURCE_OBJ },
  452. { "taggerdate", SOURCE_OBJ, FIELD_TIME },
  453. { "creator", SOURCE_OBJ },
  454. { "creatordate", SOURCE_OBJ, FIELD_TIME },
  455. { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
  456. { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
  457. { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
  458. { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
  459. { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
  460. { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
  461. { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
  462. { "flag", SOURCE_NONE },
  463. { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
  464. { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
  465. { "worktreepath", SOURCE_NONE },
  466. { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
  467. { "end", SOURCE_NONE },
  468. { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
  469. { "then", SOURCE_NONE },
  470. { "else", SOURCE_NONE },
  471. /*
  472. * Please update $__git_ref_fieldlist in git-completion.bash
  473. * when you add new atoms
  474. */
  475. };
  476. #define REF_FORMATTING_STATE_INIT { 0, NULL }
  477. struct ref_formatting_stack {
  478. struct ref_formatting_stack *prev;
  479. struct strbuf output;
  480. void (*at_end)(struct ref_formatting_stack **stack);
  481. void *at_end_data;
  482. };
  483. struct ref_formatting_state {
  484. int quote_style;
  485. struct ref_formatting_stack *stack;
  486. };
  487. struct atom_value {
  488. const char *s;
  489. int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
  490. struct strbuf *err);
  491. uintmax_t value; /* used for sorting when not FIELD_STR */
  492. struct used_atom *atom;
  493. };
  494. /*
  495. * Used to parse format string and sort specifiers
  496. */
  497. static int parse_ref_filter_atom(const struct ref_format *format,
  498. const char *atom, const char *ep,
  499. struct strbuf *err)
  500. {
  501. const char *sp;
  502. const char *arg;
  503. int i, at, atom_len;
  504. sp = atom;
  505. if (*sp == '*' && sp < ep)
  506. sp++; /* deref */
  507. if (ep <= sp)
  508. return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
  509. (int)(ep-atom), atom);
  510. /* Do we have the atom already used elsewhere? */
  511. for (i = 0; i < used_atom_cnt; i++) {
  512. int len = strlen(used_atom[i].name);
  513. if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
  514. return i;
  515. }
  516. /*
  517. * If the atom name has a colon, strip it and everything after
  518. * it off - it specifies the format for this entry, and
  519. * shouldn't be used for checking against the valid_atom
  520. * table.
  521. */
  522. arg = memchr(sp, ':', ep - sp);
  523. atom_len = (arg ? arg : ep) - sp;
  524. /* Is the atom a valid one? */
  525. for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
  526. int len = strlen(valid_atom[i].name);
  527. if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
  528. break;
  529. }
  530. if (ARRAY_SIZE(valid_atom) <= i)
  531. return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
  532. (int)(ep-atom), atom);
  533. if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
  534. return strbuf_addf_ret(err, -1,
  535. _("not a git repository, but the field '%.*s' requires access to object data"),
  536. (int)(ep-atom), atom);
  537. /* Add it in, including the deref prefix */
  538. at = used_atom_cnt;
  539. used_atom_cnt++;
  540. REALLOC_ARRAY(used_atom, used_atom_cnt);
  541. used_atom[at].name = xmemdupz(atom, ep - atom);
  542. used_atom[at].type = valid_atom[i].cmp_type;
  543. used_atom[at].source = valid_atom[i].source;
  544. if (used_atom[at].source == SOURCE_OBJ) {
  545. if (*atom == '*')
  546. oi_deref.info.contentp = &oi_deref.content;
  547. else
  548. oi.info.contentp = &oi.content;
  549. }
  550. if (arg) {
  551. arg = used_atom[at].name + (arg - atom) + 1;
  552. if (!*arg) {
  553. /*
  554. * Treat empty sub-arguments list as NULL (i.e.,
  555. * "%(atom:)" is equivalent to "%(atom)").
  556. */
  557. arg = NULL;
  558. }
  559. }
  560. memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
  561. if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
  562. return -1;
  563. if (*atom == '*')
  564. need_tagged = 1;
  565. if (!strcmp(valid_atom[i].name, "symref"))
  566. need_symref = 1;
  567. return at;
  568. }
  569. static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
  570. {
  571. switch (quote_style) {
  572. case QUOTE_NONE:
  573. strbuf_addstr(s, str);
  574. break;
  575. case QUOTE_SHELL:
  576. sq_quote_buf(s, str);
  577. break;
  578. case QUOTE_PERL:
  579. perl_quote_buf(s, str);
  580. break;
  581. case QUOTE_PYTHON:
  582. python_quote_buf(s, str);
  583. break;
  584. case QUOTE_TCL:
  585. tcl_quote_buf(s, str);
  586. break;
  587. }
  588. }
  589. static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
  590. struct strbuf *unused_err)
  591. {
  592. /*
  593. * Quote formatting is only done when the stack has a single
  594. * element. Otherwise quote formatting is done on the
  595. * element's entire output strbuf when the %(end) atom is
  596. * encountered.
  597. */
  598. if (!state->stack->prev)
  599. quote_formatting(&state->stack->output, v->s, state->quote_style);
  600. else
  601. strbuf_addstr(&state->stack->output, v->s);
  602. return 0;
  603. }
  604. static void push_stack_element(struct ref_formatting_stack **stack)
  605. {
  606. struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
  607. strbuf_init(&s->output, 0);
  608. s->prev = *stack;
  609. *stack = s;
  610. }
  611. static void pop_stack_element(struct ref_formatting_stack **stack)
  612. {
  613. struct ref_formatting_stack *current = *stack;
  614. struct ref_formatting_stack *prev = current->prev;
  615. if (prev)
  616. strbuf_addbuf(&prev->output, &current->output);
  617. strbuf_release(&current->output);
  618. free(current);
  619. *stack = prev;
  620. }
  621. static void end_align_handler(struct ref_formatting_stack **stack)
  622. {
  623. struct ref_formatting_stack *cur = *stack;
  624. struct align *align = (struct align *)cur->at_end_data;
  625. struct strbuf s = STRBUF_INIT;
  626. strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
  627. strbuf_swap(&cur->output, &s);
  628. strbuf_release(&s);
  629. }
  630. static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
  631. struct strbuf *unused_err)
  632. {
  633. struct ref_formatting_stack *new_stack;
  634. push_stack_element(&state->stack);
  635. new_stack = state->stack;
  636. new_stack->at_end = end_align_handler;
  637. new_stack->at_end_data = &atomv->atom->u.align;
  638. return 0;
  639. }
  640. static void if_then_else_handler(struct ref_formatting_stack **stack)
  641. {
  642. struct ref_formatting_stack *cur = *stack;
  643. struct ref_formatting_stack *prev = cur->prev;
  644. struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
  645. if (!if_then_else->then_atom_seen)
  646. die(_("format: %%(if) atom used without a %%(then) atom"));
  647. if (if_then_else->else_atom_seen) {
  648. /*
  649. * There is an %(else) atom: we need to drop one state from the
  650. * stack, either the %(else) branch if the condition is satisfied, or
  651. * the %(then) branch if it isn't.
  652. */
  653. if (if_then_else->condition_satisfied) {
  654. strbuf_reset(&cur->output);
  655. pop_stack_element(&cur);
  656. } else {
  657. strbuf_swap(&cur->output, &prev->output);
  658. strbuf_reset(&cur->output);
  659. pop_stack_element(&cur);
  660. }
  661. } else if (!if_then_else->condition_satisfied) {
  662. /*
  663. * No %(else) atom: just drop the %(then) branch if the
  664. * condition is not satisfied.
  665. */
  666. strbuf_reset(&cur->output);
  667. }
  668. *stack = cur;
  669. free(if_then_else);
  670. }
  671. static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
  672. struct strbuf *unused_err)
  673. {
  674. struct ref_formatting_stack *new_stack;
  675. struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
  676. if_then_else->str = atomv->atom->u.if_then_else.str;
  677. if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
  678. push_stack_element(&state->stack);
  679. new_stack = state->stack;
  680. new_stack->at_end = if_then_else_handler;
  681. new_stack->at_end_data = if_then_else;
  682. return 0;
  683. }
  684. static int is_empty(const char *s)
  685. {
  686. while (*s != '\0') {
  687. if (!isspace(*s))
  688. return 0;
  689. s++;
  690. }
  691. return 1;
  692. }
  693. static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
  694. struct strbuf *err)
  695. {
  696. struct ref_formatting_stack *cur = state->stack;
  697. struct if_then_else *if_then_else = NULL;
  698. if (cur->at_end == if_then_else_handler)
  699. if_then_else = (struct if_then_else *)cur->at_end_data;
  700. if (!if_then_else)
  701. return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
  702. if (if_then_else->then_atom_seen)
  703. return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
  704. if (if_then_else->else_atom_seen)
  705. return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
  706. if_then_else->then_atom_seen = 1;
  707. /*
  708. * If the 'equals' or 'notequals' attribute is used then
  709. * perform the required comparison. If not, only non-empty
  710. * strings satisfy the 'if' condition.
  711. */
  712. if (if_then_else->cmp_status == COMPARE_EQUAL) {
  713. if (!strcmp(if_then_else->str, cur->output.buf))
  714. if_then_else->condition_satisfied = 1;
  715. } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
  716. if (strcmp(if_then_else->str, cur->output.buf))
  717. if_then_else->condition_satisfied = 1;
  718. } else if (cur->output.len && !is_empty(cur->output.buf))
  719. if_then_else->condition_satisfied = 1;
  720. strbuf_reset(&cur->output);
  721. return 0;
  722. }
  723. static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
  724. struct strbuf *err)
  725. {
  726. struct ref_formatting_stack *prev = state->stack;
  727. struct if_then_else *if_then_else = NULL;
  728. if (prev->at_end == if_then_else_handler)
  729. if_then_else = (struct if_then_else *)prev->at_end_data;
  730. if (!if_then_else)
  731. return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
  732. if (!if_then_else->then_atom_seen)
  733. return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
  734. if (if_then_else->else_atom_seen)
  735. return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
  736. if_then_else->else_atom_seen = 1;
  737. push_stack_element(&state->stack);
  738. state->stack->at_end_data = prev->at_end_data;
  739. state->stack->at_end = prev->at_end;
  740. return 0;
  741. }
  742. static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
  743. struct strbuf *err)
  744. {
  745. struct ref_formatting_stack *current = state->stack;
  746. struct strbuf s = STRBUF_INIT;
  747. if (!current->at_end)
  748. return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
  749. current->at_end(&state->stack);
  750. /* Stack may have been popped within at_end(), hence reset the current pointer */
  751. current = state->stack;
  752. /*
  753. * Perform quote formatting when the stack element is that of
  754. * a supporting atom. If nested then perform quote formatting
  755. * only on the topmost supporting atom.
  756. */
  757. if (!current->prev->prev) {
  758. quote_formatting(&s, current->output.buf, state->quote_style);
  759. strbuf_swap(&current->output, &s);
  760. }
  761. strbuf_release(&s);
  762. pop_stack_element(&state->stack);
  763. return 0;
  764. }
  765. /*
  766. * In a format string, find the next occurrence of %(atom).
  767. */
  768. static const char *find_next(const char *cp)
  769. {
  770. while (*cp) {
  771. if (*cp == '%') {
  772. /*
  773. * %( is the start of an atom;
  774. * %% is a quoted per-cent.
  775. */
  776. if (cp[1] == '(')
  777. return cp;
  778. else if (cp[1] == '%')
  779. cp++; /* skip over two % */
  780. /* otherwise this is a singleton, literal % */
  781. }
  782. cp++;
  783. }
  784. return NULL;
  785. }
  786. /*
  787. * Make sure the format string is well formed, and parse out
  788. * the used atoms.
  789. */
  790. int verify_ref_format(struct ref_format *format)
  791. {
  792. const char *cp, *sp;
  793. format->need_color_reset_at_eol = 0;
  794. for (cp = format->format; *cp && (sp = find_next(cp)); ) {
  795. struct strbuf err = STRBUF_INIT;
  796. const char *color, *ep = strchr(sp, ')');
  797. int at;
  798. if (!ep)
  799. return error(_("malformed format string %s"), sp);
  800. /* sp points at "%(" and ep points at the closing ")" */
  801. at = parse_ref_filter_atom(format, sp + 2, ep, &err);
  802. if (at < 0)
  803. die("%s", err.buf);
  804. cp = ep + 1;
  805. if (skip_prefix(used_atom[at].name, "color:", &color))
  806. format->need_color_reset_at_eol = !!strcmp(color, "reset");
  807. strbuf_release(&err);
  808. }
  809. if (format->need_color_reset_at_eol && !want_color(format->use_color))
  810. format->need_color_reset_at_eol = 0;
  811. return 0;
  812. }
  813. static int grab_objectname(const char *name, const struct object_id *oid,
  814. struct atom_value *v, struct used_atom *atom)
  815. {
  816. if (starts_with(name, "objectname")) {
  817. if (atom->u.objectname.option == O_SHORT) {
  818. v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
  819. return 1;
  820. } else if (atom->u.objectname.option == O_FULL) {
  821. v->s = xstrdup(oid_to_hex(oid));
  822. return 1;
  823. } else if (atom->u.objectname.option == O_LENGTH) {
  824. v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
  825. return 1;
  826. } else
  827. BUG("unknown %%(objectname) option");
  828. }
  829. return 0;
  830. }
  831. /* See grab_values */
  832. static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
  833. {
  834. int i;
  835. for (i = 0; i < used_atom_cnt; i++) {
  836. const char *name = used_atom[i].name;
  837. struct atom_value *v = &val[i];
  838. if (!!deref != (*name == '*'))
  839. continue;
  840. if (deref)
  841. name++;
  842. if (!strcmp(name, "objecttype"))
  843. v->s = xstrdup(type_name(oi->type));
  844. else if (!strcmp(name, "objectsize:disk")) {
  845. v->value = oi->disk_size;
  846. v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
  847. } else if (!strcmp(name, "objectsize")) {
  848. v->value = oi->size;
  849. v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
  850. } else if (!strcmp(name, "deltabase"))
  851. v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
  852. else if (deref)
  853. grab_objectname(name, &oi->oid, v, &used_atom[i]);
  854. }
  855. }
  856. /* See grab_values */
  857. static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
  858. {
  859. int i;
  860. struct tag *tag = (struct tag *) obj;
  861. for (i = 0; i < used_atom_cnt; i++) {
  862. const char *name = used_atom[i].name;
  863. struct atom_value *v = &val[i];
  864. if (!!deref != (*name == '*'))
  865. continue;
  866. if (deref)
  867. name++;
  868. if (!strcmp(name, "tag"))
  869. v->s = xstrdup(tag->tag);
  870. else if (!strcmp(name, "type") && tag->tagged)
  871. v->s = xstrdup(type_name(tag->tagged->type));
  872. else if (!strcmp(name, "object") && tag->tagged)
  873. v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
  874. }
  875. }
  876. /* See grab_values */
  877. static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
  878. {
  879. int i;
  880. struct commit *commit = (struct commit *) obj;
  881. for (i = 0; i < used_atom_cnt; i++) {
  882. const char *name = used_atom[i].name;
  883. struct atom_value *v = &val[i];
  884. if (!!deref != (*name == '*'))
  885. continue;
  886. if (deref)
  887. name++;
  888. if (!strcmp(name, "tree")) {
  889. v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
  890. }
  891. else if (!strcmp(name, "numparent")) {
  892. v->value = commit_list_count(commit->parents);
  893. v->s = xstrfmt("%lu", (unsigned long)v->value);
  894. }
  895. else if (!strcmp(name, "parent")) {
  896. struct commit_list *parents;
  897. struct strbuf s = STRBUF_INIT;
  898. for (parents = commit->parents; parents; parents = parents->next) {
  899. struct commit *parent = parents->item;
  900. if (parents != commit->parents)
  901. strbuf_addch(&s, ' ');
  902. strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
  903. }
  904. v->s = strbuf_detach(&s, NULL);
  905. }
  906. }
  907. }
  908. static const char *find_wholine(const char *who, int wholen, const char *buf)
  909. {
  910. const char *eol;
  911. while (*buf) {
  912. if (!strncmp(buf, who, wholen) &&
  913. buf[wholen] == ' ')
  914. return buf + wholen + 1;
  915. eol = strchr(buf, '\n');
  916. if (!eol)
  917. return "";
  918. eol++;
  919. if (*eol == '\n')
  920. return ""; /* end of header */
  921. buf = eol;
  922. }
  923. return "";
  924. }
  925. static const char *copy_line(const char *buf)
  926. {
  927. const char *eol = strchrnul(buf, '\n');
  928. return xmemdupz(buf, eol - buf);
  929. }
  930. static const char *copy_name(const char *buf)
  931. {
  932. const char *cp;
  933. for (cp = buf; *cp && *cp != '\n'; cp++) {
  934. if (!strncmp(cp, " <", 2))
  935. return xmemdupz(buf, cp - buf);
  936. }
  937. return xstrdup("");
  938. }
  939. static const char *copy_email(const char *buf)
  940. {
  941. const char *email = strchr(buf, '<');
  942. const char *eoemail;
  943. if (!email)
  944. return xstrdup("");
  945. eoemail = strchr(email, '>');
  946. if (!eoemail)
  947. return xstrdup("");
  948. return xmemdupz(email, eoemail + 1 - email);
  949. }
  950. static char *copy_subject(const char *buf, unsigned long len)
  951. {
  952. char *r = xmemdupz(buf, len);
  953. int i;
  954. for (i = 0; i < len; i++)
  955. if (r[i] == '\n')
  956. r[i] = ' ';
  957. return r;
  958. }
  959. static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
  960. {
  961. const char *eoemail = strstr(buf, "> ");
  962. char *zone;
  963. timestamp_t timestamp;
  964. long tz;
  965. struct date_mode date_mode = { DATE_NORMAL };
  966. const char *formatp;
  967. /*
  968. * We got here because atomname ends in "date" or "date<something>";
  969. * it's not possible that <something> is not ":<format>" because
  970. * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
  971. * ":" means no format is specified, and use the default.
  972. */
  973. formatp = strchr(atomname, ':');
  974. if (formatp != NULL) {
  975. formatp++;
  976. parse_date_format(formatp, &date_mode);
  977. }
  978. if (!eoemail)
  979. goto bad;
  980. timestamp = parse_timestamp(eoemail + 2, &zone, 10);
  981. if (timestamp == TIME_MAX)
  982. goto bad;
  983. tz = strtol(zone, NULL, 10);
  984. if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
  985. goto bad;
  986. v->s = xstrdup(show_date(timestamp, tz, &date_mode));
  987. v->value = timestamp;
  988. return;
  989. bad:
  990. v->s = xstrdup("");
  991. v->value = 0;
  992. }
  993. /* See grab_values */
  994. static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
  995. {
  996. int i;
  997. int wholen = strlen(who);
  998. const char *wholine = NULL;
  999. for (i = 0; i < used_atom_cnt; i++) {
  1000. const char *name = used_atom[i].name;
  1001. struct atom_value *v = &val[i];
  1002. if (!!deref != (*name == '*'))
  1003. continue;
  1004. if (deref)
  1005. name++;
  1006. if (strncmp(who, name, wholen))
  1007. continue;
  1008. if (name[wholen] != 0 &&
  1009. strcmp(name + wholen, "name") &&
  1010. strcmp(name + wholen, "email") &&
  1011. !starts_with(name + wholen, "date"))
  1012. continue;
  1013. if (!wholine)
  1014. wholine = find_wholine(who, wholen, buf);
  1015. if (!wholine)
  1016. return; /* no point looking for it */
  1017. if (name[wholen] == 0)
  1018. v->s = copy_line(wholine);
  1019. else if (!strcmp(name + wholen, "name"))
  1020. v->s = copy_name(wholine);
  1021. else if (!strcmp(name + wholen, "email"))
  1022. v->s = copy_email(wholine);
  1023. else if (starts_with(name + wholen, "date"))
  1024. grab_date(wholine, v, name);
  1025. }
  1026. /*
  1027. * For a tag or a commit object, if "creator" or "creatordate" is
  1028. * requested, do something special.
  1029. */
  1030. if (strcmp(who, "tagger") && strcmp(who, "committer"))
  1031. return; /* "author" for commit object is not wanted */
  1032. if (!wholine)
  1033. wholine = find_wholine(who, wholen, buf);
  1034. if (!wholine)
  1035. return;
  1036. for (i = 0; i < used_atom_cnt; i++) {
  1037. const char *name = used_atom[i].name;
  1038. struct atom_value *v = &val[i];
  1039. if (!!deref != (*name == '*'))
  1040. continue;
  1041. if (deref)
  1042. name++;
  1043. if (starts_with(name, "creatordate"))
  1044. grab_date(wholine, v, name);
  1045. else if (!strcmp(name, "creator"))
  1046. v->s = copy_line(wholine);
  1047. }
  1048. }
  1049. static void find_subpos(const char *buf,
  1050. const char **sub, unsigned long *sublen,
  1051. const char **body, unsigned long *bodylen,
  1052. unsigned long *nonsiglen,
  1053. const char **sig, unsigned long *siglen)
  1054. {
  1055. const char *eol;
  1056. /* skip past header until we hit empty line */
  1057. while (*buf && *buf != '\n') {
  1058. eol = strchrnul(buf, '\n');
  1059. if (*eol)
  1060. eol++;
  1061. buf = eol;
  1062. }
  1063. /* skip any empty lines */
  1064. while (*buf == '\n')
  1065. buf++;
  1066. /* parse signature first; we might not even have a subject line */
  1067. *sig = buf + parse_signature(buf, strlen(buf));
  1068. *siglen = strlen(*sig);
  1069. /* subject is first non-empty line */
  1070. *sub = buf;
  1071. /* subject goes to first empty line */
  1072. while (buf < *sig && *buf && *buf != '\n') {
  1073. eol = strchrnul(buf, '\n');
  1074. if (*eol)
  1075. eol++;
  1076. buf = eol;
  1077. }
  1078. *sublen = buf - *sub;
  1079. /* drop trailing newline, if present */
  1080. if (*sublen && (*sub)[*sublen - 1] == '\n')
  1081. *sublen -= 1;
  1082. /* skip any empty lines */
  1083. while (*buf == '\n')
  1084. buf++;
  1085. *body = buf;
  1086. *bodylen = strlen(buf);
  1087. *nonsiglen = *sig - buf;
  1088. }
  1089. /*
  1090. * If 'lines' is greater than 0, append that many lines from the given
  1091. * 'buf' of length 'size' to the given strbuf.
  1092. */
  1093. static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
  1094. {
  1095. int i;
  1096. const char *sp, *eol;
  1097. size_t len;
  1098. sp = buf;
  1099. for (i = 0; i < lines && sp < buf + size; i++) {
  1100. if (i)
  1101. strbuf_addstr(out, "\n ");
  1102. eol = memchr(sp, '\n', size - (sp - buf));
  1103. len = eol ? eol - sp : size - (sp - buf);
  1104. strbuf_add(out, sp, len);
  1105. if (!eol)
  1106. break;
  1107. sp = eol + 1;
  1108. }
  1109. }
  1110. /* See grab_values */
  1111. static void grab_sub_body_contents(struct atom_value *val, int deref, void *buf)
  1112. {
  1113. int i;
  1114. const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
  1115. unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
  1116. for (i = 0; i < used_atom_cnt; i++) {
  1117. struct used_atom *atom = &used_atom[i];
  1118. const char *name = atom->name;
  1119. struct atom_value *v = &val[i];
  1120. if (!!deref != (*name == '*'))
  1121. continue;
  1122. if (deref)
  1123. name++;
  1124. if (strcmp(name, "subject") &&
  1125. strcmp(name, "body") &&
  1126. !starts_with(name, "trailers") &&
  1127. !starts_with(name, "contents"))
  1128. continue;
  1129. if (!subpos)
  1130. find_subpos(buf,
  1131. &subpos, &sublen,
  1132. &bodypos, &bodylen, &nonsiglen,
  1133. &sigpos, &siglen);
  1134. if (atom->u.contents.option == C_SUB)
  1135. v->s = copy_subject(subpos, sublen);
  1136. else if (atom->u.contents.option == C_BODY_DEP)
  1137. v->s = xmemdupz(bodypos, bodylen);
  1138. else if (atom->u.contents.option == C_BODY)
  1139. v->s = xmemdupz(bodypos, nonsiglen);
  1140. else if (atom->u.contents.option == C_SIG)
  1141. v->s = xmemdupz(sigpos, siglen);
  1142. else if (atom->u.contents.option == C_LINES) {
  1143. struct strbuf s = STRBUF_INIT;
  1144. const char *contents_end = bodylen + bodypos - siglen;
  1145. /* Size is the length of the message after removing the signature */
  1146. append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
  1147. v->s = strbuf_detach(&s, NULL);
  1148. } else if (atom->u.contents.option == C_TRAILERS) {
  1149. struct strbuf s = STRBUF_INIT;
  1150. /* Format the trailer info according to the trailer_opts given */
  1151. format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
  1152. v->s = strbuf_detach(&s, NULL);
  1153. } else if (atom->u.contents.option == C_BARE)
  1154. v->s = xstrdup(subpos);
  1155. }
  1156. }
  1157. /*
  1158. * We want to have empty print-string for field requests
  1159. * that do not apply (e.g. "authordate" for a tag object)
  1160. */
  1161. static void fill_missing_values(struct atom_value *val)
  1162. {
  1163. int i;
  1164. for (i = 0; i < used_atom_cnt; i++) {
  1165. struct atom_value *v = &val[i];
  1166. if (v->s == NULL)
  1167. v->s = xstrdup("");
  1168. }
  1169. }
  1170. /*
  1171. * val is a list of atom_value to hold returned values. Extract
  1172. * the values for atoms in used_atom array out of (obj, buf, sz).
  1173. * when deref is false, (obj, buf, sz) is the object that is
  1174. * pointed at by the ref itself; otherwise it is the object the
  1175. * ref (which is a tag) refers to.
  1176. */
  1177. static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf)
  1178. {
  1179. switch (obj->type) {
  1180. case OBJ_TAG:
  1181. grab_tag_values(val, deref, obj);
  1182. grab_sub_body_contents(val, deref, buf);
  1183. grab_person("tagger", val, deref, buf);
  1184. break;
  1185. case OBJ_COMMIT:
  1186. grab_commit_values(val, deref, obj);
  1187. grab_sub_body_contents(val, deref, buf);
  1188. grab_person("author", val, deref, buf);
  1189. grab_person("committer", val, deref, buf);
  1190. break;
  1191. case OBJ_TREE:
  1192. /* grab_tree_values(val, deref, obj, buf, sz); */
  1193. break;
  1194. case OBJ_BLOB:
  1195. /* grab_blob_values(val, deref, obj, buf, sz); */
  1196. break;
  1197. default:
  1198. die("Eh? Object of type %d?", obj->type);
  1199. }
  1200. }
  1201. static inline char *copy_advance(char *dst, const char *src)
  1202. {
  1203. while (*src)
  1204. *dst++ = *src++;
  1205. return dst;
  1206. }
  1207. static const char *lstrip_ref_components(const char *refname, int len)
  1208. {
  1209. long remaining = len;
  1210. const char *start = xstrdup(refname);
  1211. const char *to_free = start;
  1212. if (len < 0) {
  1213. int i;
  1214. const char *p = refname;
  1215. /* Find total no of '/' separated path-components */
  1216. for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
  1217. ;
  1218. /*
  1219. * The number of components we need to strip is now
  1220. * the total minus the components to be left (Plus one
  1221. * because we count the number of '/', but the number
  1222. * of components is one more than the no of '/').
  1223. */
  1224. remaining = i + len + 1;
  1225. }
  1226. while (remaining > 0) {
  1227. switch (*start++) {
  1228. case '\0':
  1229. free((char *)to_free);
  1230. return xstrdup("");
  1231. case '/':
  1232. remaining--;
  1233. break;
  1234. }
  1235. }
  1236. start = xstrdup(start);
  1237. free((char *)to_free);
  1238. return start;
  1239. }
  1240. static const char *rstrip_ref_components(const char *refname, int len)
  1241. {
  1242. long remaining = len;
  1243. const char *start = xstrdup(refname);
  1244. const char *to_free = start;
  1245. if (len < 0) {
  1246. int i;
  1247. const char *p = refname;
  1248. /* Find total no of '/' separated path-components */
  1249. for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
  1250. ;
  1251. /*
  1252. * The number of components we need to strip is now
  1253. * the total minus the components to be left (Plus one
  1254. * because we count the number of '/', but the number
  1255. * of components is one more than the no of '/').
  1256. */
  1257. remaining = i + len + 1;
  1258. }
  1259. while (remaining-- > 0) {
  1260. char *p = strrchr(start, '/');
  1261. if (p == NULL) {
  1262. free((char *)to_free);
  1263. return xstrdup("");
  1264. } else
  1265. p[0] = '\0';
  1266. }
  1267. return start;
  1268. }
  1269. static const char *show_ref(struct refname_atom *atom, const char *refname)
  1270. {
  1271. if (atom->option == R_SHORT)
  1272. return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
  1273. else if (atom->option == R_LSTRIP)
  1274. return lstrip_ref_components(refname, atom->lstrip);
  1275. else if (atom->option == R_RSTRIP)
  1276. return rstrip_ref_components(refname, atom->rstrip);
  1277. else
  1278. return xstrdup(refname);
  1279. }
  1280. static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
  1281. struct branch *branch, const char **s)
  1282. {
  1283. int num_ours, num_theirs;
  1284. if (atom->u.remote_ref.option == RR_REF)
  1285. *s = show_ref(&atom->u.remote_ref.refname, refname);
  1286. else if (atom->u.remote_ref.option == RR_TRACK) {
  1287. if (stat_tracking_info(branch, &num_ours, &num_theirs,
  1288. NULL, atom->u.remote_ref.push,
  1289. AHEAD_BEHIND_FULL) < 0) {
  1290. *s = xstrdup(msgs.gone);
  1291. } else if (!num_ours && !num_theirs)
  1292. *s = xstrdup("");
  1293. else if (!num_ours)
  1294. *s = xstrfmt(msgs.behind, num_theirs);
  1295. else if (!num_theirs)
  1296. *s = xstrfmt(msgs.ahead, num_ours);
  1297. else
  1298. *s = xstrfmt(msgs.ahead_behind,
  1299. num_ours, num_theirs);
  1300. if (!atom->u.remote_ref.nobracket && *s[0]) {
  1301. const char *to_free = *s;
  1302. *s = xstrfmt("[%s]", *s);
  1303. free((void *)to_free);
  1304. }
  1305. } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
  1306. if (stat_tracking_info(branch, &num_ours, &num_theirs,
  1307. NULL, atom->u.remote_ref.push,
  1308. AHEAD_BEHIND_FULL) < 0) {
  1309. *s = xstrdup("");
  1310. return;
  1311. }
  1312. if (!num_ours && !num_theirs)
  1313. *s = xstrdup("=");
  1314. else if (!num_ours)
  1315. *s = xstrdup("<");
  1316. else if (!num_theirs)
  1317. *s = xstrdup(">");
  1318. else
  1319. *s = xstrdup("<>");
  1320. } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
  1321. int explicit;
  1322. const char *remote = atom->u.remote_ref.push ?
  1323. pushremote_for_branch(branch, &explicit) :
  1324. remote_for_branch(branch, &explicit);
  1325. *s = xstrdup(explicit ? remote : "");
  1326. } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
  1327. int explicit;
  1328. const char *merge;
  1329. merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
  1330. &explicit);
  1331. *s = xstrdup(explicit ? merge : "");
  1332. } else
  1333. BUG("unhandled RR_* enum");
  1334. }
  1335. char *get_head_description(void)
  1336. {
  1337. struct strbuf desc = STRBUF_INIT;
  1338. struct wt_status_state state;
  1339. memset(&state, 0, sizeof(state));
  1340. wt_status_get_state(the_repository, &state, 1);
  1341. /*
  1342. * The ( character must be hard-coded and not part of a localizable
  1343. * string, since the description is used as a sort key and compared
  1344. * with ref names.
  1345. */
  1346. strbuf_addch(&desc, '(');
  1347. if (state.rebase_in_progress ||
  1348. state.rebase_interactive_in_progress) {
  1349. if (state.branch)
  1350. strbuf_addf(&desc, _("no branch, rebasing %s"),
  1351. state.branch);
  1352. else
  1353. strbuf_addf(&desc, _("no branch, rebasing detached HEAD %s"),
  1354. state.detached_from);
  1355. } else if (state.bisect_in_progress)
  1356. strbuf_addf(&desc, _("no branch, bisect started on %s"),
  1357. state.branch);
  1358. else if (state.detached_from) {
  1359. if (state.detached_at)
  1360. strbuf_addstr(&desc, HEAD_DETACHED_AT);
  1361. else
  1362. strbuf_addstr(&desc, HEAD_DETACHED_FROM);
  1363. strbuf_addstr(&desc, state.detached_from);
  1364. }
  1365. else
  1366. strbuf_addstr(&desc, _("no branch"));
  1367. strbuf_addch(&desc, ')');
  1368. free(state.branch);
  1369. free(state.onto);
  1370. free(state.detached_from);
  1371. return strbuf_detach(&desc, NULL);
  1372. }
  1373. static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
  1374. {
  1375. if (!ref->symref)
  1376. return xstrdup("");
  1377. else
  1378. return show_ref(&atom->u.refname, ref->symref);
  1379. }
  1380. static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
  1381. {
  1382. if (ref->kind & FILTER_REFS_DETACHED_HEAD)
  1383. return get_head_description();
  1384. return show_ref(&atom->u.refname, ref->refname);
  1385. }
  1386. static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
  1387. struct expand_data *oi, struct strbuf *err)
  1388. {
  1389. /* parse_object_buffer() will set eaten to 0 if free() will be needed */
  1390. int eaten = 1;
  1391. if (oi->info.contentp) {
  1392. /* We need to know that to use parse_object_buffer properly */
  1393. oi->info.sizep = &oi->size;
  1394. oi->info.typep = &oi->type;
  1395. }
  1396. if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
  1397. OBJECT_INFO_LOOKUP_REPLACE))
  1398. return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
  1399. oid_to_hex(&oi->oid), ref->refname);
  1400. if (oi->info.disk_sizep && oi->disk_size < 0)
  1401. BUG("Object size is less than zero.");
  1402. if (oi->info.contentp) {
  1403. *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
  1404. if (!obj) {
  1405. if (!eaten)
  1406. free(oi->content);
  1407. return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
  1408. oid_to_hex(&oi->oid), ref->refname);
  1409. }
  1410. grab_values(ref->value, deref, *obj, oi->content);
  1411. }
  1412. grab_common_values(ref->value, deref, oi);
  1413. if (!eaten)
  1414. free(oi->content);
  1415. return 0;
  1416. }
  1417. static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
  1418. {
  1419. int i;
  1420. for (i = 0; worktrees[i]; i++) {
  1421. if (worktrees[i]->head_ref) {
  1422. struct ref_to_worktree_entry *entry;
  1423. entry = xmalloc(sizeof(*entry));
  1424. entry->wt = worktrees[i];
  1425. hashmap_entry_init(&entry->ent,
  1426. strhash(worktrees[i]->head_ref));
  1427. hashmap_add(map, &entry->ent);
  1428. }
  1429. }
  1430. }
  1431. static void lazy_init_worktree_map(void)
  1432. {
  1433. if (ref_to_worktree_map.worktrees)
  1434. return;
  1435. ref_to_worktree_map.worktrees = get_worktrees(0);
  1436. hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
  1437. populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
  1438. }
  1439. static char *get_worktree_path(const struct used_atom *atom, const struct ref_array_item *ref)
  1440. {
  1441. struct hashmap_entry entry, *e;
  1442. struct ref_to_worktree_entry *lookup_result;
  1443. lazy_init_worktree_map();
  1444. hashmap_entry_init(&entry, strhash(ref->refname));
  1445. e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
  1446. if (!e)
  1447. return xstrdup("");
  1448. lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
  1449. return xstrdup(lookup_result->wt->path);
  1450. }
  1451. /*
  1452. * Parse the object referred by ref, and grab needed value.
  1453. */
  1454. static int populate_value(struct ref_array_item *ref, struct strbuf *err)
  1455. {
  1456. struct object *obj;
  1457. int i;
  1458. struct object_info empty = OBJECT_INFO_INIT;
  1459. ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
  1460. if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
  1461. ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
  1462. NULL, NULL);
  1463. if (!ref->symref)
  1464. ref->symref = xstrdup("");
  1465. }
  1466. /* Fill in specials first */
  1467. for (i = 0; i < used_atom_cnt; i++) {
  1468. struct used_atom *atom = &used_atom[i];
  1469. const char *name = used_atom[i].name;
  1470. struct atom_value *v = &ref->value[i];
  1471. int deref = 0;
  1472. const char *refname;
  1473. struct branch *branch = NULL;
  1474. v->handler = append_atom;
  1475. v->atom = atom;
  1476. if (*name == '*') {
  1477. deref = 1;
  1478. name++;
  1479. }
  1480. if (starts_with(name, "refname"))
  1481. refname = get_refname(atom, ref);
  1482. else if (!strcmp(name, "worktreepath")) {
  1483. if (ref->kind == FILTER_REFS_BRANCHES)
  1484. v->s = get_worktree_path(atom, ref);
  1485. else
  1486. v->s = xstrdup("");
  1487. continue;
  1488. }
  1489. else if (starts_with(name, "symref"))
  1490. refname = get_symref(atom, ref);
  1491. else if (starts_with(name, "upstream")) {
  1492. const char *branch_name;
  1493. /* only local branches may have an upstream */
  1494. if (!skip_prefix(ref->refname, "refs/heads/",
  1495. &branch_name)) {
  1496. v->s = xstrdup("");
  1497. continue;
  1498. }
  1499. branch = branch_get(branch_name);
  1500. refname = branch_get_upstream(branch, NULL);
  1501. if (refname)
  1502. fill_remote_ref_details(atom, refname, branch, &v->s);
  1503. else
  1504. v->s = xstrdup("");
  1505. continue;
  1506. } else if (atom->u.remote_ref.push) {
  1507. const char *branch_name;
  1508. v->s = xstrdup("");
  1509. if (!skip_prefix(ref->refname, "refs/heads/",
  1510. &branch_name))
  1511. continue;
  1512. branch = branch_get(branch_name);
  1513. if (atom->u.remote_ref.push_remote)
  1514. refname = NULL;
  1515. else {
  1516. refname = branch_get_push(branch, NULL);
  1517. if (!refname)
  1518. continue;
  1519. }
  1520. /* We will definitely re-init v->s on the next line. */
  1521. free((char *)v->s);
  1522. fill_remote_ref_details(atom, refname, branch, &v->s);
  1523. continue;
  1524. } else if (starts_with(name, "color:")) {
  1525. v->s = xstrdup(atom->u.color);
  1526. continue;
  1527. } else if (!strcmp(name, "flag")) {
  1528. char buf[256], *cp = buf;
  1529. if (ref->flag & REF_ISSYMREF)
  1530. cp = copy_advance(cp, ",symref");
  1531. if (ref->flag & REF_ISPACKED)
  1532. cp = copy_advance(cp, ",packed");
  1533. if (cp == buf)
  1534. v->s = xstrdup("");
  1535. else {
  1536. *cp = '\0';
  1537. v->s = xstrdup(buf + 1);
  1538. }
  1539. continue;
  1540. } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
  1541. continue;
  1542. } else if (!strcmp(name, "HEAD")) {
  1543. if (atom->u.head && !strcmp(ref->refname, atom->u.head))
  1544. v->s = xstrdup("*");
  1545. else
  1546. v->s = xstrdup(" ");
  1547. continue;
  1548. } else if (starts_with(name, "align")) {
  1549. v->handler = align_atom_handler;
  1550. v->s = xstrdup("");
  1551. continue;
  1552. } else if (!strcmp(name, "end")) {
  1553. v->handler = end_atom_handler;
  1554. v->s = xstrdup("");
  1555. continue;
  1556. } else if (starts_with(name, "if")) {
  1557. const char *s;
  1558. if (skip_prefix(name, "if:", &s))
  1559. v->s = xstrdup(s);
  1560. else
  1561. v->s = xstrdup("");
  1562. v->handler = if_atom_handler;
  1563. continue;
  1564. } else if (!strcmp(name, "then")) {
  1565. v->handler = then_atom_handler;
  1566. v->s = xstrdup("");
  1567. continue;
  1568. } else if (!strcmp(name, "else")) {
  1569. v->handler = else_atom_handler;
  1570. v->s = xstrdup("");
  1571. continue;
  1572. } else
  1573. continue;
  1574. if (!deref)
  1575. v->s = xstrdup(refname);
  1576. else
  1577. v->s = xstrfmt("%s^{}", refname);
  1578. free((char *)refname);
  1579. }
  1580. for (i = 0; i < used_atom_cnt; i++) {
  1581. struct atom_value *v = &ref->value[i];
  1582. if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
  1583. return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
  1584. oid_to_hex(&ref->objectname), ref->refname);
  1585. }
  1586. if (need_tagged)
  1587. oi.info.contentp = &oi.content;
  1588. if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
  1589. !memcmp(&oi_deref.info, &empty, sizeof(empty)))
  1590. return 0;
  1591. oi.oid = ref->objectname;
  1592. if (get_object(ref, 0, &obj, &oi, err))
  1593. return -1;
  1594. /*
  1595. * If there is no atom that wants to know about tagged
  1596. * object, we are done.
  1597. */
  1598. if (!need_tagged || (obj->type != OBJ_TAG))
  1599. return 0;
  1600. /*
  1601. * If it is a tag object, see if we use a value that derefs
  1602. * the object, and if we do grab the object it refers to.
  1603. */
  1604. oi_deref.oid = *get_tagged_oid((struct tag *)obj);
  1605. /*
  1606. * NEEDSWORK: This derefs tag only once, which
  1607. * is good to deal with chains of trust, but
  1608. * is not consistent with what deref_tag() does
  1609. * which peels the onion to the core.
  1610. */
  1611. return get_object(ref, 1, &obj, &oi_deref, err);
  1612. }
  1613. /*
  1614. * Given a ref, return the value for the atom. This lazily gets value
  1615. * out of the object by calling populate value.
  1616. */
  1617. static int get_ref_atom_value(struct ref_array_item *ref, int atom,
  1618. struct atom_value **v, struct strbuf *err)
  1619. {
  1620. if (!ref->value) {
  1621. if (populate_value(ref, err))
  1622. return -1;
  1623. fill_missing_values(ref->value);
  1624. }
  1625. *v = &ref->value[atom];
  1626. return 0;
  1627. }
  1628. /*
  1629. * Return 1 if the refname matches one of the patterns, otherwise 0.
  1630. * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
  1631. * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
  1632. * matches "refs/heads/mas*", too).
  1633. */
  1634. static int match_pattern(const struct ref_filter *filter, const char *refname)
  1635. {
  1636. const char **patterns = filter->name_patterns;
  1637. unsigned flags = 0;
  1638. if (filter->ignore_case)
  1639. flags |= WM_CASEFOLD;
  1640. /*
  1641. * When no '--format' option is given we need to skip the prefix
  1642. * for matching refs of tags and branches.
  1643. */
  1644. (void)(skip_prefix(refname, "refs/tags/", &refname) ||
  1645. skip_prefix(refname, "refs/heads/", &refname) ||
  1646. skip_prefix(refname, "refs/remotes/", &refname) ||
  1647. skip_prefix(refname, "refs/", &refname));
  1648. for (; *patterns; patterns++) {
  1649. if (!wildmatch(*patterns, refname, flags))
  1650. return 1;
  1651. }
  1652. return 0;
  1653. }
  1654. /*
  1655. * Return 1 if the refname matches one of the patterns, otherwise 0.
  1656. * A pattern can be path prefix (e.g. a refname "refs/heads/master"
  1657. * matches a pattern "refs/heads/" but not "refs/heads/m") or a
  1658. * wildcard (e.g. the same ref matches "refs/heads/m*", too).
  1659. */
  1660. static int match_name_as_path(const struct ref_filter *filter, const char *refname)
  1661. {
  1662. const char **pattern = filter->name_patterns;
  1663. int namelen = strlen(refname);
  1664. unsigned flags = WM_PATHNAME;
  1665. if (filter->ignore_case)
  1666. flags |= WM_CASEFOLD;
  1667. for (; *pattern; pattern++) {
  1668. const char *p = *pattern;
  1669. int plen = strlen(p);
  1670. if ((plen <= namelen) &&
  1671. !strncmp(refname, p, plen) &&
  1672. (refname[plen] == '\0' ||
  1673. refname[plen] == '/' ||
  1674. p[plen-1] == '/'))
  1675. return 1;
  1676. if (!wildmatch(p, refname, flags))
  1677. return 1;
  1678. }
  1679. return 0;
  1680. }
  1681. /* Return 1 if the refname matches one of the patterns, otherwise 0. */
  1682. static int filter_pattern_match(struct ref_filter *filter, const char *refname)
  1683. {
  1684. if (!*filter->name_patterns)
  1685. return 1; /* No pattern always matches */
  1686. if (filter->match_as_path)
  1687. return match_name_as_path(filter, refname);
  1688. return match_pattern(filter, refname);
  1689. }
  1690. static int qsort_strcmp(const void *va, const void *vb)
  1691. {
  1692. const char *a = *(const char **)va;
  1693. const char *b = *(const char **)vb;
  1694. return strcmp(a, b);
  1695. }
  1696. static void find_longest_prefixes_1(struct string_list *out,
  1697. struct strbuf *prefix,
  1698. const char **patterns, size_t nr)
  1699. {
  1700. size_t i;
  1701. for (i = 0; i < nr; i++) {
  1702. char c = patterns[i][prefix->len];
  1703. if (!c || is_glob_special(c)) {
  1704. string_list_append(out, prefix->buf);
  1705. return;
  1706. }
  1707. }
  1708. i = 0;
  1709. while (i < nr) {
  1710. size_t end;
  1711. /*
  1712. * Set "end" to the index of the element _after_ the last one
  1713. * in our group.
  1714. */
  1715. for (end = i + 1; end < nr; end++) {
  1716. if (patterns[i][prefix->len] != patterns[end][prefix->len])
  1717. break;
  1718. }
  1719. strbuf_addch(prefix, patterns[i][prefix->len]);
  1720. find_longest_prefixes_1(out, prefix, patterns + i, end - i);
  1721. strbuf_setlen(prefix, prefix->len - 1);
  1722. i = end;
  1723. }
  1724. }
  1725. static void find_longest_prefixes(struct string_list *out,
  1726. const char **patterns)
  1727. {
  1728. struct argv_array sorted = ARGV_ARRAY_INIT;
  1729. struct strbuf prefix = STRBUF_INIT;
  1730. argv_array_pushv(&sorted, patterns);
  1731. QSORT(sorted.argv, sorted.argc, qsort_strcmp);
  1732. find_longest_prefixes_1(out, &prefix, sorted.argv, sorted.argc);
  1733. argv_array_clear(&sorted);
  1734. strbuf_release(&prefix);
  1735. }
  1736. /*
  1737. * This is the same as for_each_fullref_in(), but it tries to iterate
  1738. * only over the patterns we'll care about. Note that it _doesn't_ do a full
  1739. * pattern match, so the callback still has to match each ref individually.
  1740. */
  1741. static int for_each_fullref_in_pattern(struct ref_filter *filter,
  1742. each_ref_fn cb,
  1743. void *cb_data,
  1744. int broken)
  1745. {
  1746. struct string_list prefixes = STRING_LIST_INIT_DUP;
  1747. struct string_list_item *prefix;
  1748. int ret;
  1749. if (!filter->match_as_path) {
  1750. /*
  1751. * in this case, the patterns are applied after
  1752. * prefixes like "refs/heads/" etc. are stripped off,
  1753. * so we have to look at everything:
  1754. */
  1755. return for_each_fullref_in("", cb, cb_data, broken);
  1756. }
  1757. if (filter->ignore_case) {
  1758. /*
  1759. * we can't handle case-insensitive comparisons,
  1760. * so just return everything and let the caller
  1761. * sort it out.
  1762. */
  1763. return for_each_fullref_in("", cb, cb_data, broken);
  1764. }
  1765. if (!filter->name_patterns[0]) {
  1766. /* no patterns; we have to look at everything */
  1767. return for_each_fullref_in("", cb, cb_data, broken);
  1768. }
  1769. find_longest_prefixes(&prefixes, filter->name_patterns);
  1770. for_each_string_list_item(prefix, &prefixes) {
  1771. ret = for_each_fullref_in(prefix->string, cb, cb_data, broken);
  1772. if (ret)
  1773. break;
  1774. }
  1775. string_list_clear(&prefixes, 0);
  1776. return ret;
  1777. }
  1778. /*
  1779. * Given a ref (sha1, refname), check if the ref belongs to the array
  1780. * of sha1s. If the given ref is a tag, check if the given tag points
  1781. * at one of the sha1s in the given sha1 array.
  1782. * the given sha1_array.
  1783. * NEEDSWORK:
  1784. * 1. Only a single level of inderection is obtained, we might want to
  1785. * change this to account for multiple levels (e.g. annotated tags
  1786. * pointing to annotated tags pointing to a commit.)
  1787. * 2. As the refs are cached we might know what refname peels to without
  1788. * the need to parse the object via parse_object(). peel_ref() might be a
  1789. * more efficient alternative to obtain the pointee.
  1790. */
  1791. static const struct object_id *match_points_at(struct oid_array *points_at,
  1792. const struct object_id *oid,
  1793. const char *refname)
  1794. {
  1795. const struct object_id *tagged_oid = NULL;
  1796. struct object *obj;
  1797. if (oid_array_lookup(points_at, oid) >= 0)
  1798. return oid;
  1799. obj = parse_object(the_repository, oid);
  1800. if (!obj)
  1801. die(_("malformed object at '%s'"), refname);
  1802. if (obj->type == OBJ_TAG)
  1803. tagged_oid = get_tagged_oid((struct tag *)obj);
  1804. if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
  1805. return tagged_oid;
  1806. return NULL;
  1807. }
  1808. /*
  1809. * Allocate space for a new ref_array_item and copy the name and oid to it.
  1810. *
  1811. * Callers can then fill in other struct members at their leisure.
  1812. */
  1813. static struct ref_array_item *new_ref_array_item(const char *refname,
  1814. const struct object_id *oid)
  1815. {
  1816. struct ref_array_item *ref;
  1817. FLEX_ALLOC_STR(ref, refname, refname);
  1818. oidcpy(&ref->objectname, oid);
  1819. return ref;
  1820. }
  1821. struct ref_array_item *ref_array_push(struct ref_array *array,
  1822. const char *refname,
  1823. const struct object_id *oid)
  1824. {
  1825. struct ref_array_item *ref = new_ref_array_item(refname, oid);
  1826. ALLOC_GROW(array->items, array->nr + 1, array->alloc);
  1827. array->items[array->nr++] = ref;
  1828. return ref;
  1829. }
  1830. static int ref_kind_from_refname(const char *refname)
  1831. {
  1832. unsigned int i;
  1833. static struct {
  1834. const char *prefix;
  1835. unsigned int kind;
  1836. } ref_kind[] = {
  1837. { "refs/heads/" , FILTER_REFS_BRANCHES },
  1838. { "refs/remotes/" , FILTER_REFS_REMOTES },
  1839. { "refs/tags/", FILTER_REFS_TAGS}
  1840. };
  1841. if (!strcmp(refname, "HEAD"))
  1842. return FILTER_REFS_DETACHED_HEAD;
  1843. for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
  1844. if (starts_with(refname, ref_kind[i].prefix))
  1845. return ref_kind[i].kind;
  1846. }
  1847. return FILTER_REFS_OTHERS;
  1848. }
  1849. static int filter_ref_kind(struct ref_filter *filter, const char *refname)
  1850. {
  1851. if (filter->kind == FILTER_REFS_BRANCHES ||
  1852. filter->kind == FILTER_REFS_REMOTES ||
  1853. filter->kind == FILTER_REFS_TAGS)
  1854. return filter->kind;
  1855. return ref_kind_from_refname(refname);
  1856. }
  1857. struct ref_filter_cbdata {
  1858. struct ref_array *array;
  1859. struct ref_filter *filter;
  1860. struct contains_cache contains_cache;
  1861. struct contains_cache no_contains_cache;
  1862. };
  1863. /*
  1864. * A call-back given to for_each_ref(). Filter refs and keep them for
  1865. * later object processing.
  1866. */
  1867. static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
  1868. {
  1869. struct ref_filter_cbdata *ref_cbdata = cb_data;
  1870. struct ref_filter *filter = ref_cbdata->filter;
  1871. struct ref_array_item *ref;
  1872. struct commit *commit = NULL;
  1873. unsigned int kind;
  1874. if (flag & REF_BAD_NAME) {
  1875. warning(_("ignoring ref with broken name %s"), refname);
  1876. return 0;
  1877. }
  1878. if (flag & REF_ISBROKEN) {
  1879. warning(_("ignoring broken ref %s"), refname);
  1880. return 0;
  1881. }
  1882. /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
  1883. kind = filter_ref_kind(filter, refname);
  1884. if (!(kind & filter->kind))
  1885. return 0;
  1886. if (!filter_pattern_match(filter, refname))
  1887. return 0;
  1888. if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
  1889. return 0;
  1890. /*
  1891. * A merge filter is applied on refs pointing to commits. Hence
  1892. * obtain the commit using the 'oid' available and discard all
  1893. * non-commits early. The actual filtering is done later.
  1894. */
  1895. if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
  1896. commit = lookup_commit_reference_gently(the_repository, oid,
  1897. 1);
  1898. if (!commit)
  1899. return 0;
  1900. /* We perform the filtering for the '--contains' option... */
  1901. if (filter->with_commit &&
  1902. !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
  1903. return 0;
  1904. /* ...or for the `--no-contains' option */
  1905. if (filter->no_commit &&
  1906. commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
  1907. return 0;
  1908. }
  1909. /*
  1910. * We do not open the object yet; sort may only need refname
  1911. * to do its job and the resulting list may yet to be pruned
  1912. * by maxcount logic.
  1913. */
  1914. ref = ref_array_push(ref_cbdata->array, refname, oid);
  1915. ref->commit = commit;
  1916. ref->flag = flag;
  1917. ref->kind = kind;
  1918. return 0;
  1919. }
  1920. /* Free memory allocated for a ref_array_item */
  1921. static void free_array_item(struct ref_array_item *item)
  1922. {
  1923. free((char *)item->symref);
  1924. if (item->value) {
  1925. int i;
  1926. for (i = 0; i < used_atom_cnt; i++)
  1927. free((char *)item->value[i].s);
  1928. free(item->value);
  1929. }
  1930. free(item);
  1931. }
  1932. /* Free all memory allocated for ref_array */
  1933. void ref_array_clear(struct ref_array *array)
  1934. {
  1935. int i;
  1936. for (i = 0; i < array->nr; i++)
  1937. free_array_item(array->items[i]);
  1938. FREE_AND_NULL(array->items);
  1939. array->nr = array->alloc = 0;
  1940. for (i = 0; i < used_atom_cnt; i++)
  1941. free((char *)used_atom[i].name);
  1942. FREE_AND_NULL(used_atom);
  1943. used_atom_cnt = 0;
  1944. if (ref_to_worktree_map.worktrees) {
  1945. hashmap_free_entries(&(ref_to_worktree_map.map),
  1946. struct ref_to_worktree_entry, ent);
  1947. free_worktrees(ref_to_worktree_map.worktrees);
  1948. ref_to_worktree_map.worktrees = NULL;
  1949. }
  1950. }
  1951. static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
  1952. {
  1953. struct rev_info revs;
  1954. int i, old_nr;
  1955. struct ref_filter *filter = ref_cbdata->filter;
  1956. struct ref_array *array = ref_cbdata->array;
  1957. struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
  1958. repo_init_revisions(the_repository, &revs, NULL);
  1959. for (i = 0; i < array->nr; i++) {
  1960. struct ref_array_item *item = array->items[i];
  1961. add_pending_object(&revs, &item->commit->object, item->refname);
  1962. to_clear[i] = item->commit;
  1963. }
  1964. filter->merge_commit->object.flags |= UNINTERESTING;
  1965. add_pending_object(&revs, &filter->merge_commit->object, "");
  1966. revs.limited = 1;
  1967. if (prepare_revision_walk(&revs))
  1968. die(_("revision walk setup failed"));
  1969. old_nr = array->nr;
  1970. array->nr = 0;
  1971. for (i = 0; i < old_nr; i++) {
  1972. struct ref_array_item *item = array->items[i];
  1973. struct commit *commit = item->commit;
  1974. int is_merged = !!(commit->object.flags & UNINTERESTING);
  1975. if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
  1976. array->items[array->nr++] = array->items[i];
  1977. else
  1978. free_array_item(item);
  1979. }
  1980. clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
  1981. clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
  1982. free(to_clear);
  1983. }
  1984. /*
  1985. * API for filtering a set of refs. Based on the type of refs the user
  1986. * has requested, we iterate through those refs and apply filters
  1987. * as per the given ref_filter structure and finally store the
  1988. * filtered refs in the ref_array structure.
  1989. */
  1990. int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
  1991. {
  1992. struct ref_filter_cbdata ref_cbdata;
  1993. int ret = 0;
  1994. unsigned int broken = 0;
  1995. ref_cbdata.array = array;
  1996. ref_cbdata.filter = filter;
  1997. if (type & FILTER_REFS_INCLUDE_BROKEN)
  1998. broken = 1;
  1999. filter->kind = type & FILTER_REFS_KIND_MASK;
  2000. init_contains_cache(&ref_cbdata.contains_cache);
  2001. init_contains_cache(&ref_cbdata.no_contains_cache);
  2002. /* Simple per-ref filtering */
  2003. if (!filter->kind)
  2004. die("filter_refs: invalid type");
  2005. else {
  2006. /*
  2007. * For common cases where we need only branches or remotes or tags,
  2008. * we only iterate through those refs. If a mix of refs is needed,
  2009. * we iterate over all refs and filter out required refs with the help
  2010. * of filter_ref_kind().
  2011. */
  2012. if (filter->kind == FILTER_REFS_BRANCHES)
  2013. ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
  2014. else if (filter->kind == FILTER_REFS_REMOTES)
  2015. ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
  2016. else if (filter->kind == FILTER_REFS_TAGS)
  2017. ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
  2018. else if (filter->kind & FILTER_REFS_ALL)
  2019. ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
  2020. if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
  2021. head_ref(ref_filter_handler, &ref_cbdata);
  2022. }
  2023. clear_contains_cache(&ref_cbdata.contains_cache);
  2024. clear_contains_cache(&ref_cbdata.no_contains_cache);
  2025. /* Filters that need revision walking */
  2026. if (filter->merge_commit)
  2027. do_merge_filter(&ref_cbdata);
  2028. return ret;
  2029. }
  2030. static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
  2031. {
  2032. struct atom_value *va, *vb;
  2033. int cmp;
  2034. cmp_type cmp_type = used_atom[s->atom].type;
  2035. int (*cmp_fn)(const char *, const char *);
  2036. struct strbuf err = STRBUF_INIT;
  2037. if (get_ref_atom_value(a, s->atom, &va, &err))
  2038. die("%s", err.buf);
  2039. if (get_ref_atom_value(b, s->atom, &vb, &err))
  2040. die("%s", err.buf);
  2041. strbuf_release(&err);
  2042. cmp_fn = s->ignore_case ? strcasecmp : strcmp;
  2043. if (s->version)
  2044. cmp = versioncmp(va->s, vb->s);
  2045. else if (cmp_type == FIELD_STR)
  2046. cmp = cmp_fn(va->s, vb->s);
  2047. else {
  2048. if (va->value < vb->value)
  2049. cmp = -1;
  2050. else if (va->value == vb->value)
  2051. cmp = cmp_fn(a->refname, b->refname);
  2052. else
  2053. cmp = 1;
  2054. }
  2055. return (s->reverse) ? -cmp : cmp;
  2056. }
  2057. static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
  2058. {
  2059. struct ref_array_item *a = *((struct ref_array_item **)a_);
  2060. struct ref_array_item *b = *((struct ref_array_item **)b_);
  2061. struct ref_sorting *s;
  2062. for (s = ref_sorting; s; s = s->next) {
  2063. int cmp = cmp_ref_sorting(s, a, b);
  2064. if (cmp)
  2065. return cmp;
  2066. }
  2067. return 0;
  2068. }
  2069. void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
  2070. {
  2071. QSORT_S(array->items, array->nr, compare_refs, sorting);
  2072. }
  2073. static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
  2074. {
  2075. struct strbuf *s = &state->stack->output;
  2076. while (*cp && (!ep || cp < ep)) {
  2077. if (*cp == '%') {
  2078. if (cp[1] == '%')
  2079. cp++;
  2080. else {
  2081. int ch = hex2chr(cp + 1);
  2082. if (0 <= ch) {
  2083. strbuf_addch(s, ch);
  2084. cp += 3;
  2085. continue;
  2086. }
  2087. }
  2088. }
  2089. strbuf_addch(s, *cp);
  2090. cp++;
  2091. }
  2092. }
  2093. int format_ref_array_item(struct ref_array_item *info,
  2094. const struct ref_format *format,
  2095. struct strbuf *final_buf,
  2096. struct strbuf *error_buf)
  2097. {
  2098. const char *cp, *sp, *ep;
  2099. struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
  2100. state.quote_style = format->quote_style;
  2101. push_stack_element(&state.stack);
  2102. for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
  2103. struct atom_value *atomv;
  2104. int pos;
  2105. ep = strchr(sp, ')');
  2106. if (cp < sp)
  2107. append_literal(cp, sp, &state);
  2108. pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
  2109. if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
  2110. atomv->handler(atomv, &state, error_buf)) {
  2111. pop_stack_element(&state.stack);
  2112. return -1;
  2113. }
  2114. }
  2115. if (*cp) {
  2116. sp = cp + strlen(cp);
  2117. append_literal(cp, sp, &state);
  2118. }
  2119. if (format->need_color_reset_at_eol) {
  2120. struct atom_value resetv;
  2121. resetv.s = GIT_COLOR_RESET;
  2122. if (append_atom(&resetv, &state, error_buf)) {
  2123. pop_stack_element(&state.stack);
  2124. return -1;
  2125. }
  2126. }
  2127. if (state.stack->prev) {
  2128. pop_stack_element(&state.stack);
  2129. return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
  2130. }
  2131. strbuf_addbuf(final_buf, &state.stack->output);
  2132. pop_stack_element(&state.stack);
  2133. return 0;
  2134. }
  2135. void show_ref_array_item(struct ref_array_item *info,
  2136. const struct ref_format *format)
  2137. {
  2138. struct strbuf final_buf = STRBUF_INIT;
  2139. struct strbuf error_buf = STRBUF_INIT;
  2140. if (format_ref_array_item(info, format, &final_buf, &error_buf))
  2141. die("%s", error_buf.buf);
  2142. fwrite(final_buf.buf, 1, final_buf.len, stdout);
  2143. strbuf_release(&error_buf);
  2144. strbuf_release(&final_buf);
  2145. putchar('\n');
  2146. }
  2147. void pretty_print_ref(const char *name, const struct object_id *oid,
  2148. const struct ref_format *format)
  2149. {
  2150. struct ref_array_item *ref_item;
  2151. ref_item = new_ref_array_item(name, oid);
  2152. ref_item->kind = ref_kind_from_refname(name);
  2153. show_ref_array_item(ref_item, format);
  2154. free_array_item(ref_item);
  2155. }
  2156. static int parse_sorting_atom(const char *atom)
  2157. {
  2158. /*
  2159. * This parses an atom using a dummy ref_format, since we don't
  2160. * actually care about the formatting details.
  2161. */
  2162. struct ref_format dummy = REF_FORMAT_INIT;
  2163. const char *end = atom + strlen(atom);
  2164. struct strbuf err = STRBUF_INIT;
  2165. int res = parse_ref_filter_atom(&dummy, atom, end, &err);
  2166. if (res < 0)
  2167. die("%s", err.buf);
  2168. strbuf_release(&err);
  2169. return res;
  2170. }
  2171. /* If no sorting option is given, use refname to sort as default */
  2172. struct ref_sorting *ref_default_sorting(void)
  2173. {
  2174. static const char cstr_name[] = "refname";
  2175. struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
  2176. sorting->next = NULL;
  2177. sorting->atom = parse_sorting_atom(cstr_name);
  2178. return sorting;
  2179. }
  2180. void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
  2181. {
  2182. struct ref_sorting *s;
  2183. s = xcalloc(1, sizeof(*s));
  2184. s->next = *sorting_tail;
  2185. *sorting_tail = s;
  2186. if (*arg == '-') {
  2187. s->reverse = 1;
  2188. arg++;
  2189. }
  2190. if (skip_prefix(arg, "version:", &arg) ||
  2191. skip_prefix(arg, "v:", &arg))
  2192. s->version = 1;
  2193. s->atom = parse_sorting_atom(arg);
  2194. }
  2195. int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
  2196. {
  2197. /*
  2198. * NEEDSWORK: We should probably clear the list in this case, but we've
  2199. * already munged the global used_atoms list, which would need to be
  2200. * undone.
  2201. */
  2202. BUG_ON_OPT_NEG(unset);
  2203. parse_ref_sorting(opt->value, arg);
  2204. return 0;
  2205. }
  2206. int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
  2207. {
  2208. struct ref_filter *rf = opt->value;
  2209. struct object_id oid;
  2210. int no_merged = starts_with(opt->long_name, "no");
  2211. BUG_ON_OPT_NEG(unset);
  2212. if (rf->merge) {
  2213. if (no_merged) {
  2214. return error(_("option `%s' is incompatible with --merged"),
  2215. opt->long_name);
  2216. } else {
  2217. return error(_("option `%s' is incompatible with --no-merged"),
  2218. opt->long_name);
  2219. }
  2220. }
  2221. rf->merge = no_merged
  2222. ? REF_FILTER_MERGED_OMIT
  2223. : REF_FILTER_MERGED_INCLUDE;
  2224. if (get_oid(arg, &oid))
  2225. die(_("malformed object name %s"), arg);
  2226. rf->merge_commit = lookup_commit_reference_gently(the_repository,
  2227. &oid, 0);
  2228. if (!rf->merge_commit)
  2229. return error(_("option `%s' must point to a commit"), opt->long_name);
  2230. return 0;
  2231. }