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
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2272 lines
61KB

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