gitbooleanposixgit-pathspec

How to check if literal pathspecs are set in git?


Is there any reliable way to check if Git literal pathspecs are enabled in a shell script?

This option can be set either by assigning a boolean value to the variable GIT_LITERAL_PATHSPECS or by passing a flag --literal-pathspecs to git, which also seems to set this variable.

However, parsing the variable seems pretty hard. This is what the documentation says about it:

The environment variables marked as "Boolean" take their values the same way as Boolean valued configuration variables, i.e., "true", "yes", "on" and positive numbers are taken as "yes", while "false", "no", "off", and "0" are taken as "no".

This seems to be enough information to implement it but I'm afraid that the documentation may be outdated or incomplete. There may be more valid keywords like "yeah" and "nah" (or they may be added in the future).

I tried to write a script that checks those values, but I don't know how reliable it would be:

if printf '%s' "$GIT_LITERAL_PATHSPECS" | grep -Eqxi 'true|yes|on' || [ "$GIT_LITERAL_PATHSPECS" -ge 1 ] 2>/dev/null
then
    echo 'literal pathspecs are ON'
else
    echo 'literal pathspecs are OFF'
fi

Even if it is reliable, I would prefer for some simpler method that won't require me to reimplement the whole boolean parser.

Is there some Git built-in method to check either this specific value, or at least to parse a boolean environment variable?


Solution

  • This is the same concept as the other answer but I fixed it, simplified it and made sure it actually follows POSIX.

    parse_git_bool() {
         test "$(git -c 'foo.bar'="$1" config --get --type=bool 'foo.bar' 2>/dev/null)" = 'true'
    }
    
    if parse_git_bool "$GIT_LITERAL_PATHSPECS"
    then
        echo 'literal pathspecs are ON'
    else
        echo 'literal pathspecs are OFF'
    fi
    

    Explanation:

    We run git with the option -c which sets a temporary configuration value. From docs:

    Pass a configuration parameter to the command. The value given will override values from configuration files. The is expected in the same format as listed by git config (subkeys separated by dots).

    Note that omitting the = in git -c foo.bar ... is allowed and sets foo.bar to the boolean true value (just like [foo]bar would in a config file). Including the equals but with an empty value (like git -c foo.bar= ...) sets foo.bar to the empty string which git config --type=bool will convert to false.

    Then we call config --get --type=bool which returns this value back but converted to boolean. (Only 2 values are possible true and false.) We use test to check if the returned value is true.

    In case the input value was illegal, git config will silently fail (2>/dev/null) and the function will still return 1 just as if the parsed value was a correct false value. If you interested in having a different value for a failed parsing, you would need to check the exit code of git config.