]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/check-ref-format.c
Merge branch 'fc/remove-header-workarounds-for-asciidoc'
[thirdparty/git.git] / builtin / check-ref-format.c
1 /*
2 * GIT - The information manager from hell
3 */
4
5 #include "cache.h"
6 #include "refs.h"
7 #include "builtin.h"
8 #include "setup.h"
9 #include "strbuf.h"
10
11 static const char builtin_check_ref_format_usage[] =
12 "git check-ref-format [--normalize] [<options>] <refname>\n"
13 " or: git check-ref-format --branch <branchname-shorthand>";
14
15 /*
16 * Return a copy of refname but with leading slashes removed and runs
17 * of adjacent slashes replaced with single slashes.
18 *
19 * This function is similar to normalize_path_copy(), but stripped down
20 * to meet check_ref_format's simpler needs.
21 */
22 static char *collapse_slashes(const char *refname)
23 {
24 char *ret = xmallocz(strlen(refname));
25 char ch;
26 char prev = '/';
27 char *cp = ret;
28
29 while ((ch = *refname++) != '\0') {
30 if (prev == '/' && ch == prev)
31 continue;
32
33 *cp++ = ch;
34 prev = ch;
35 }
36 *cp = '\0';
37 return ret;
38 }
39
40 static int check_ref_format_branch(const char *arg)
41 {
42 struct strbuf sb = STRBUF_INIT;
43 const char *name;
44 int nongit;
45
46 setup_git_directory_gently(&nongit);
47 if (strbuf_check_branch_ref(&sb, arg) ||
48 !skip_prefix(sb.buf, "refs/heads/", &name))
49 die("'%s' is not a valid branch name", arg);
50 printf("%s\n", name);
51 strbuf_release(&sb);
52 return 0;
53 }
54
55 int cmd_check_ref_format(int argc, const char **argv, const char *prefix)
56 {
57 int i;
58 int normalize = 0;
59 int flags = 0;
60 const char *refname;
61 char *to_free = NULL;
62 int ret = 1;
63
64 BUG_ON_NON_EMPTY_PREFIX(prefix);
65
66 if (argc == 2 && !strcmp(argv[1], "-h"))
67 usage(builtin_check_ref_format_usage);
68
69 if (argc == 3 && !strcmp(argv[1], "--branch"))
70 return check_ref_format_branch(argv[2]);
71
72 for (i = 1; i < argc && argv[i][0] == '-'; i++) {
73 if (!strcmp(argv[i], "--normalize") || !strcmp(argv[i], "--print"))
74 normalize = 1;
75 else if (!strcmp(argv[i], "--allow-onelevel"))
76 flags |= REFNAME_ALLOW_ONELEVEL;
77 else if (!strcmp(argv[i], "--no-allow-onelevel"))
78 flags &= ~REFNAME_ALLOW_ONELEVEL;
79 else if (!strcmp(argv[i], "--refspec-pattern"))
80 flags |= REFNAME_REFSPEC_PATTERN;
81 else
82 usage(builtin_check_ref_format_usage);
83 }
84 if (! (i == argc - 1))
85 usage(builtin_check_ref_format_usage);
86
87 refname = argv[i];
88 if (normalize)
89 refname = to_free = collapse_slashes(refname);
90 if (check_refname_format(refname, flags))
91 goto cleanup;
92 if (normalize)
93 printf("%s\n", refname);
94
95 ret = 0;
96 cleanup:
97 free(to_free);
98 return ret;
99 }