72959547b31ccf0239a146b91a06d92332b901f6
[git/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 "strbuf.h"
9
10 static const char builtin_check_ref_format_usage[] =
11 "git check-ref-format [--print] [options] <refname>\n"
12 " or: git check-ref-format --branch <branchname-shorthand>";
13
14 /*
15 * Remove leading slashes and replace each run of adjacent slashes in
16 * src with a single slash, and write the result to dst.
17 *
18 * This function is similar to normalize_path_copy(), but stripped down
19 * to meet check_ref_format's simpler needs.
20 */
21 static void collapse_slashes(char *dst, const char *src)
22 {
23 char ch;
24 char prev = '/';
25
26 while ((ch = *src++) != '\0') {
27 if (prev == '/' && ch == prev)
28 continue;
29
30 *dst++ = ch;
31 prev = ch;
32 }
33 *dst = '\0';
34 }
35
36 static int check_ref_format_branch(const char *arg)
37 {
38 struct strbuf sb = STRBUF_INIT;
39 int nongit;
40
41 setup_git_directory_gently(&nongit);
42 if (strbuf_check_branch_ref(&sb, arg))
43 die("'%s' is not a valid branch name", arg);
44 printf("%s\n", sb.buf + 11);
45 return 0;
46 }
47
48 static void refname_format_print(const char *arg)
49 {
50 char *refname = xmalloc(strlen(arg) + 1);
51
52 collapse_slashes(refname, arg);
53 printf("%s\n", refname);
54 }
55
56 #define REFNAME_ALLOW_ONELEVEL 1
57 #define REFNAME_REFSPEC_PATTERN 2
58
59 int cmd_check_ref_format(int argc, const char **argv, const char *prefix)
60 {
61 int i;
62 int print = 0;
63 int flags = 0;
64
65 if (argc == 2 && !strcmp(argv[1], "-h"))
66 usage(builtin_check_ref_format_usage);
67
68 if (argc == 3 && !strcmp(argv[1], "--branch"))
69 return check_ref_format_branch(argv[2]);
70
71 for (i = 1; i < argc && argv[i][0] == '-'; i++) {
72 if (!strcmp(argv[i], "--print"))
73 print = 1;
74 else if (!strcmp(argv[i], "--allow-onelevel"))
75 flags |= REFNAME_ALLOW_ONELEVEL;
76 else if (!strcmp(argv[i], "--no-allow-onelevel"))
77 flags &= ~REFNAME_ALLOW_ONELEVEL;
78 else if (!strcmp(argv[i], "--refspec-pattern"))
79 flags |= REFNAME_REFSPEC_PATTERN;
80 else
81 usage(builtin_check_ref_format_usage);
82 }
83 if (! (i == argc - 1))
84 usage(builtin_check_ref_format_usage);
85
86 switch (check_ref_format(argv[i])) {
87 case CHECK_REF_FORMAT_OK:
88 break;
89 case CHECK_REF_FORMAT_ERROR:
90 return 1;
91 case CHECK_REF_FORMAT_ONELEVEL:
92 if (!(flags & REFNAME_ALLOW_ONELEVEL))
93 return 1;
94 else
95 break;
96 case CHECK_REF_FORMAT_WILDCARD:
97 if (!(flags & REFNAME_REFSPEC_PATTERN))
98 return 1;
99 else
100 break;
101 default:
102 die("internal error: unexpected value from check_ref_format()");
103 }
104
105 if (print)
106 refname_format_print(argv[i]);
107
108 return 0;
109 }