|
| 1 | +using System; |
| 2 | + |
| 3 | +namespace SourceGit.Models |
| 4 | +{ |
| 5 | + /// <summary> |
| 6 | + /// Validates branch and tag names using the same rules that git itself enforces, |
| 7 | + /// mirroring `git check-ref-format --allow-onelevel`. Rules are taken from the git-check-ref-format documentation. |
| 8 | + /// Rule 2 (a refname must contain at least one slash) is intentionally waived, matching `--allow-onelevel`. |
| 9 | + /// </summary> |
| 10 | + public static class RefName |
| 11 | + { |
| 12 | + public static bool IsValidBranchName(string name) |
| 13 | + { |
| 14 | + if (string.Equals(name, "HEAD", StringComparison.Ordinal)) |
| 15 | + return false; |
| 16 | + |
| 17 | + return IsValidRefName(name); |
| 18 | + } |
| 19 | + |
| 20 | + public static bool IsValidTagName(string name) => IsValidRefName(name); |
| 21 | + |
| 22 | + private static bool IsValidRefName(string name) |
| 23 | + { |
| 24 | + if (string.IsNullOrEmpty(name)) |
| 25 | + return false; |
| 26 | + |
| 27 | + // Anything starting with '-' is treated as a CLI option. |
| 28 | + if (name.StartsWith('-')) |
| 29 | + return false; |
| 30 | + |
| 31 | + // Rule 9: cannot be the single character '@'. |
| 32 | + if (name.Equals("@", StringComparison.Ordinal)) |
| 33 | + return false; |
| 34 | + |
| 35 | + // Rule 6: cannot begin or end with '/', or contain consecutive slashes. |
| 36 | + if (name[0] == '/' || name[^1] == '/' || name.Contains("//", StringComparison.Ordinal)) |
| 37 | + return false; |
| 38 | + |
| 39 | + // Rule 7: cannot end with a dot. |
| 40 | + if (name[^1] == '.') |
| 41 | + return false; |
| 42 | + |
| 43 | + // Rule 3: cannot contain two consecutive dots. |
| 44 | + if (name.Contains("..", StringComparison.Ordinal)) |
| 45 | + return false; |
| 46 | + |
| 47 | + // Rule 8: cannot contain the sequence '@{'. |
| 48 | + if (name.Contains("@{", StringComparison.Ordinal)) |
| 49 | + return false; |
| 50 | + |
| 51 | + // Rules 4, 5 & 10: no control chars, DEL, space, or ~ ^ : ? * [ \. |
| 52 | + foreach (var ch in name) |
| 53 | + { |
| 54 | + if (ch is < ' ' or '\x7f') |
| 55 | + return false; |
| 56 | + |
| 57 | + switch (ch) |
| 58 | + { |
| 59 | + case ' ': |
| 60 | + case '~': |
| 61 | + case '^': |
| 62 | + case ':': |
| 63 | + case '?': |
| 64 | + case '*': |
| 65 | + case '[': |
| 66 | + case '\\': |
| 67 | + return false; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + // Rule 1: no slash-separated component may begin with a dot or end with ".lock". |
| 72 | + foreach (var component in name.Split('/')) |
| 73 | + { |
| 74 | + if (component[0] == '.') |
| 75 | + return false; |
| 76 | + |
| 77 | + if (component.EndsWith(".lock", StringComparison.Ordinal)) |
| 78 | + return false; |
| 79 | + } |
| 80 | + |
| 81 | + return true; |
| 82 | + } |
| 83 | + } |
| 84 | +} |
0 commit comments