check-ref-format doc: --branch validates and expands <branch>
[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 [--normalize] [<options>] <refname>\n"
12 " or: git check-ref-format --branch <branchname-shorthand>";
13
14 /*
15 * Return a copy of refname but with leading slashes removed and runs
16 * of adjacent slashes replaced with single slashes.
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 char *collapse_slashes(const char *refname)
22 {
23 char *ret = xmallocz(strlen(refname));
24 char ch;
25 char prev = '/';
26 char *cp = ret;
27
28 while ((ch = *refname++) != '\0') {
29 if (prev == '/' && ch == prev)
30 continue;
31
32 *cp++ = ch;
33 prev = ch;
34 }
35 *cp = '\0';
36 return ret;
37 }
38
39 static int check_ref_format_branch(const char *arg)
40 {
41 struct strbuf sb = STRBUF_INIT;
42 const char *name;
43 int nongit;
44
45 setup_git_directory_gently(&nongit);
46 if (strbuf_check_branch_ref(&sb, arg) ||
47 !skip_prefix(sb.buf, "refs/heads/", &name))
48 die("'%s' is not a valid branch name", arg);
49 printf("%s\n", name);
50 return 0;
51 }
52
53 int cmd_check_ref_format(int argc, const char **argv, const char *prefix)
54 {
55 int i;
56 int normalize = 0;
57 int flags = 0;
58 const char *refname;
59
60 if (argc == 2 && !strcmp(argv[1], "-h"))
61 usage(builtin_check_ref_format_usage);
62
63 if (argc == 3 && !strcmp(argv[1], "--branch"))
64 return check_ref_format_branch(argv[2]);
65
66 for (i = 1; i < argc && argv[i][0] == '-'; i++) {
67 if (!strcmp(argv[i], "--normalize") || !strcmp(argv[i], "--print"))
68 normalize = 1;
69 else if (!strcmp(argv[i], "--allow-onelevel"))
70 flags |= REFNAME_ALLOW_ONELEVEL;
71 else if (!strcmp(argv[i], "--no-allow-onelevel"))
72 flags &= ~REFNAME_ALLOW_ONELEVEL;
73 else if (!strcmp(argv[i], "--refspec-pattern"))
74 flags |= REFNAME_REFSPEC_PATTERN;
75 else
76 usage(builtin_check_ref_format_usage);
77 }
78 if (! (i == argc - 1))
79 usage(builtin_check_ref_format_usage);
80
81 refname = argv[i];
82 if (normalize)
83 refname = collapse_slashes(refname);
84 if (check_refname_format(refname, flags))
85 return 1;
86 if (normalize)
87 printf("%s\n", refname);
88
89 return 0;
90 }