2

I added this npm script to my package.json file:

"gitlog" : "git log --graph --decorate -30 --all --date-order --date=format:'%Y-%m-%d %H:%M:%S' --pretty=format:'%C(cyan)%h%Creset %C(black bold)%ad%Creset%C(auto)%d %s'"

But when I type npm run gitlog, I get the error: fatal: Invalid object name '%H'.

I tried putting the command in back ticks but got another error. Is there some escaping I have to do on this command or how can I get it to work?

0

2 Answers 2

1

Replace all single quotes (') with JSON escaped double quotes (\") e.g.

"gitlog": "git log --graph --decorate -30 --all --date-order --date=format:\"%Y-%m-%d %H:%M:%S\" --pretty=format:\"%C(cyan)%h%Creset %C(black bold)%ad%Creset%C(auto)%d %s\""
                                                                           ^^                 ^^                 ^^                                                       ^^ 
1

I'm not sure how NPM is escaping the string and delivering it on the command line/terminal, but you can likely fix this with some standard tricks on double packed strings.

There are two passes of string parsing that happens here - first the JSON in the package.json file is sent to NPM, then NPM sends the string to the terminal/command line. So you need to figure out how to embed the inner quotes in a way that they will get to the command line (in a way that agrees with git).

Try the following:

  1. Reverse the single and double quotes (single quotes outside)

  2. Add backslash in front of the inner quotes

    • Backslash is typically an escape character for special characters
    • When parsing a string, quotes are special characters
  3. Add backslash in front of the inner quotes after switching them from single to double quotes

  4. Try duplicating all the interior quotes (i.e. instead of '%C(cyan)...' try ''%C(cyan)...'' or ""%C(cyan)...""). Sometime parsers will treat duplicate quotes as an escape character and put just a single quote in the final output that is passed on.


How do I know this is the root cause?

The clue here is the error output. If you find the first "%H" in your string, you see there is a space right before it. If the single quotes get stripped out, then git will see the space, and consider the text after it to be the start of a new argument.

Git doesn't recognize "%H" as valid for whatever that argument would have been, and the error message it printed was the result.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.