Skip to content

Commit b7afb46

Browse files
pks-tgitster
authored andcommitted
parse-options-cb: only abbreviate hashes when hash algo is known
The `OPT__ABBREV()` option can be used to add an option that abbreviates object IDs. When given a length longer than `the_hash_algo->hexsz`, then it will instead set the length to that maximum length. It may not always be guaranteed that we have `the_hash_algo` initialized properly as the hash algorithm can only be set up after we have set up `the_repository`. In that case, the hash would always be truncated to the hex length of SHA1, which may not be what the user desires. In practice it's not a problem as all commands that use `OPT__ABBREV()` also have `RUN_SETUP` set and thus cannot work without a repository. Consequently, both `the_repository` and `the_hash_algo` would be properly set up. Regardless of that, harden the code to not truncate the length when we didn't set up a repository. Signed-off-by: Patrick Steinhardt <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 0c6bd2b commit b7afb46

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

parse-options-cb.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include "environment.h"
88
#include "gettext.h"
99
#include "object-name.h"
10+
#include "setup.h"
1011
#include "string-list.h"
1112
#include "strvec.h"
1213
#include "oid-array.h"
@@ -29,7 +30,7 @@ int parse_opt_abbrev_cb(const struct option *opt, const char *arg, int unset)
2930
opt->long_name);
3031
if (v && v < MINIMUM_ABBREV)
3132
v = MINIMUM_ABBREV;
32-
else if (v > the_hash_algo->hexsz)
33+
else if (startup_info->have_repository && v > the_hash_algo->hexsz)
3334
v = the_hash_algo->hexsz;
3435
}
3536
*(int *)(opt->value) = v;

t/t0040-parse-options.sh

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,23 @@ test_expect_success 'long options' '
176176
test_cmp expect output
177177
'
178178

179+
test_expect_success 'abbreviate to something longer than SHA1 length' '
180+
cat >expect <<-EOF &&
181+
boolean: 0
182+
integer: 0
183+
magnitude: 0
184+
timestamp: 0
185+
string: (not set)
186+
abbrev: 100
187+
verbose: -1
188+
quiet: 0
189+
dry run: no
190+
file: (not set)
191+
EOF
192+
test-tool parse-options --abbrev=100 >output &&
193+
test_cmp expect output
194+
'
195+
179196
test_expect_success 'missing required value' '
180197
cat >expect <<-\EOF &&
181198
error: switch `s'\'' requires a value

0 commit comments

Comments
 (0)