git/list[1] front-page[2] threads[3] people[4] search[5] about
 

Parsing trailers

From
William Chargin <wchargin@gmail.com>
Date
Dec 23, 2018, 22:41 UTC
Message-ID
<CAFW+GMDazFSDzBrvzMqaPGwew=+CP7tw7G5FfDqcAUYd3qjPuQ@mail.gmail.com>

I'm interested in parsing the output of `git-interpret-trailers` in a script. I had hoped that the `--parse` option would make this easy, but it seems that the `trailer.separators` configuration option is used to specify both the input format (which separators may indicate a trailer) and the output format of `git interpret-trailers --parse`. Given that `trailer.separators` may contain any (non-NUL) characters, including whitespace, parsing the output is not straightforward.

Here's what I've come up with. The output format is "<tok><sep> <val>", where "<tok>" and "<val>" have been trimmed and so have no leading or trailing whitespace, but "<val>" may have internal whitespace while "<tok>" may not. Thus, the first space character in the output may correspond to either "<sep>" or the fixed space, but we should be able to determine which is the case: the first space is immediately followed by a second space if and only if the first space corresponds to "<sep>".

Assuming that the above analysis is correct, the following procedure should suffice to safely parse the output:

  - Let `i` be the index of the first space in `s`.
  - If `s[i+1]` is a space, let `sep_pos` be `i`. Otherwise, let
    `sep_pos` be `i - 1`.
  - The substring `s[:sep_pos]` is the token.
  - The character at index `sep_pos` is the separator.
  - The character at index `sep_pos + 1` is the fixed space.
  - The substring `s[sep_pos+2:nl]` is the value, where `nl` is the
    index of the first newline in `s` after `sep_pos`.

(It seems unfortunately complicated when all we want to do is parse the output of `--parse`, but I don't see a better approach!)

My questions:
  - Is this accurate?
  - Is this algorithm guaranteed to remain correct in future versions of
    Git?
  - Is there a simpler way to extract the token-value pairs from a
    commit message string?
Would appreciate any advice.

Thanks! WC

Next: Christian Couder
Message 1 of 8 in “Parsing trailers”
  1. William CharginDec 23, 2018
  2. Christian CouderDec 24, 2018
  3. William CharginDec 24, 2018
  4. Christian CouderDec 26, 2018
  5. William CharginDec 26, 2018
  6. Jeff KingJan 3, 2019
  7. William CharginJan 3, 2019
  8. Jeff KingJan 3, 2019

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.