1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
use lazy_static::lazy_static;
use regex::Regex;
use thiserror::Error;

struct SanitizeOptions {
    allow_onelevel: bool,
}

#[derive(Error, Debug)]
pub enum SanitizeGitRefError {
    #[error(
        "Ref must contain at least one '/'. Did you mean to call `sanitize_git_ref_onelevel`?"
    )]
    DoesNotContainForwardSlash,
}

/// Rules obtained from [git-check-ref-format].
///
/// This function sanitizes git refs with the assumption that `--allow-onelevel` is true.
///
/// [git-check-ref-format]: https://git-scm.com/docs/git-check-ref-format
pub fn sanitize_git_ref_onelevel(text: &str) -> String {
    let sanitized = sanitize(
        text,
        SanitizeOptions {
            allow_onelevel: true,
        },
    );
    sanitized.expect("Sanitization should always suceed when allow_onelevel is true")
}

fn sanitize(text: &str, options: SanitizeOptions) -> Result<String, Box<SanitizeGitRefError>> {
    let SanitizeOptions { allow_onelevel } = options;
    let mut result = text.to_owned();

    // They must contain at least one /. This enforces the presence of a category like heads/, tags/ etc. but the actual names are not restricted. If the --allow-onelevel option is used, this rule is waived.
    if !allow_onelevel {
        if !result.contains('/') {
            return Err(Box::new(SanitizeGitRefError::DoesNotContainForwardSlash));
        }
    }

    // They can include slash / for hierarchical (directory) grouping, but no slash-separated component can begin with a dot . or end with the sequence .lock.
    if result.starts_with('.') {
        result = result.replacen('.', "-", 1);
    }
    result = result.replace("/.", "/-");
    // FIXME: this is overly cautious
    result = result.replace(".lock", "-");

    // They cannot have ASCII control characters (i.e. bytes whose values are lower than \040, or \177 DEL).
    lazy_static! {
        static ref RE_CONTROL_CHARACTER: Regex = Regex::new("[[:cntrl:]]+")
            .expect("Expected control-character regular expression to compile");
    }
    result = RE_CONTROL_CHARACTER.replace_all(&result, "-").into();

    // They cannot have space anywhere.
    lazy_static! {
        static ref RE_WHITESPACE_CHARACTER: Regex = Regex::new("[[:space:]]+")
            .expect("Expected whitespace-character regular expression to compile");
    }
    result = RE_WHITESPACE_CHARACTER.replace_all(&result, "-").into();
    // Property testing has identified characters that are not detected by the
    // above regex, so we'll use this stronger test to remove all spaces.
    result.retain(|char| !char.is_whitespace());

    // They cannot have tilde ~ anywhere.
    result = result.replace('~', "-");

    // They cannot have caret ^ anywhere.
    result = result.replace('^', "-");

    // They cannot have colon : anywhere.
    result = result.replace(':', "-");

    // They cannot have question-mark ?, asterisk *, or open bracket [ anywhere. See the --refspec-pattern option below for an exception to this rule.
    result = result.replace('?', "-");
    result = result.replace('*', "-");
    result = result.replace('[', "-");

    // They cannot contain a sequence @{.
    result = result.replace("@{", "-");

    // They cannot be the single character @.
    // FIXME: this implementation is too restrictive but I'm not exactly sure of the rules right now.
    // Happy to widen this up if I get more clarity and feel confident we'll avoid false-positives.
    result = result.replace('@', "-");

    // They cannot contain a \.
    result = result.replace('\\', "-");

    // They cannot contain multiple consecutive slashes (see the --normalize option below for an exception to this rule)
    lazy_static! {
        static ref RE_MULTIPLE_FORWARD_SLASHES: Regex = Regex::new("/{2,}")
            .expect("Expected multiple-forward-slashes regular expression to compile");
    }
    result = RE_MULTIPLE_FORWARD_SLASHES.replace_all(&result, "-").into();

    // They cannot have two consecutive dots .. anywhere.
    lazy_static! {
        static ref RE_MULTIPLE_DOTS: Regex =
            Regex::new("[.]{2,}").expect("Expected multiple-dots regular expression to compile");
    }
    result = RE_MULTIPLE_DOTS.replace_all(&result, "-").into();

    // They cannot begin with a slash / (see the --normalize option below for an exception to this rule)
    // FIXME: this has a bug, property-testing is finding it consistently
    while result.starts_with('/') {
        result = result.replacen('/', "-", 1);
    }

    // They cannot end with a dot .
    // They cannot end with a slash / (see the --normalize option below for an exception to this rule)
    while result.ends_with('/') || result.ends_with('.') {
        result.pop();
    }

    if result.ends_with('/') {
        result.pop();
    }

    // Convert any sequence of multiple hyphens into a single hyphen.
    // We convert invalid characters into hyphens to prevent shrinking the input into an empty string.
    lazy_static! {
        static ref RE_MULTIPLE_HYPHENS: Regex =
            Regex::new("-{2,}").expect("Expected multiple-hyphens regular expression to compile");
    }
    result = RE_MULTIPLE_HYPHENS.replace_all(&result, "-").into();

    Ok(result)
}

#[cfg(test)]
mod test {
    use crate::sanitize_git_ref_onelevel;

    use proptest::prelude::*;

    macro_rules! test_does_not_violate_branch_naming_rule {
        ($unit_test:ident, $property_test:ident, $test_of_inclusion:expr, $unsanitized_branch_name:expr) => {
            #[test]
            fn $unit_test() {
                let sanitized_branch_name = sanitize_git_ref_onelevel(&$unsanitized_branch_name);
                assert!(
                    !$test_of_inclusion(&sanitized_branch_name),
                    "Expected unsanitized string {:?} to sanitize to a valid branch name, but {:?} is not a valid branch name",
                    &$unsanitized_branch_name,
                    &sanitized_branch_name
                );
            }

            proptest! {
                #[test]
                fn $property_test(unsanitized_branch_name in any::<String>()) {
                    let sanitized_branch_name = sanitize_git_ref_onelevel(&unsanitized_branch_name);
                    assert!(
                        !$test_of_inclusion(&sanitized_branch_name),
                        "Expected unsanitized string {:?} to sanitize to a valid branch name, but {:?} is not a valid branch name",
                        &unsanitized_branch_name,
                        &sanitized_branch_name
                    );
                }
            }
        };
    }

    // They can include slash / for hierarchical (directory) grouping, but no slash-separated component can begin with a dot.
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_a_slash_separated_component_beginning_with_a_dot,
        proptest_branch_name_does_not_contain_a_slash_separated_component_beginning_with_a_dot,
        |branch_name: &str| -> bool {
            for slash_separated_sequence in branch_name.split("/") {
                if slash_separated_sequence.starts_with(".") {
                    return true;
                }
            }
            false
        },
        "refs/heads/.master"
    );

    // Branch names can include slash / for hierarchical (directory) grouping, but no slash-separated component can end with the sequence .lock.
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_a_slash_separated_component_ending_with_dot_lock,
        proptest_branch_name_does_not_contain_a_slash_separated_component_ending_with_dot_lock,
        |branch_name: &str| -> bool {
            for slash_separated_sequence in branch_name.split("/") {
                if slash_separated_sequence.ends_with(".lock") {
                    return true;
                }
            }
            false
        },
        "refs/heads/master.lock"
    );

    // They must contain at least one /. This enforces the presence of a category like heads/, tags/ etc. but the actual names are not restricted.
    // If the --allow-onelevel option is used, this rule is waived.
    // FIXME: Turn on this test when we implement sanitize_git_ref (sans allow-onelevel)
    // fn has_at_least_one_slash<S: AsRef<str>>(branch_name: S) -> bool {
    //     branch_name.as_ref().contains("/")
    // }

    // #[test]
    // fn branch_name_has_at_least_one_slash() {
    //     assert!(has_at_least_one_slash(sanitize_git_ref_onelevel(
    //         "refs/heads/master"
    //     )))
    // }

    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_two_consecutive_dots,
        proptest_branch_name_does_not_contain_two_consecutive_dots,
        |branch_name: &str| -> bool { branch_name.contains("..") },
        "refs/heads/master..foo"
    );

    // They cannot have ASCII control characters (i.e. bytes whose values are lower than \040, or \177 DEL).
    // FIXME: Maintainer's note: not sure how to test "bytes whose values are lower than \040, or \177 DEL" yet

    // They cannot have space anywhere.
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_a_space,
        proptest_branch_name_does_not_contain_a_space,
        |branch_name: &str| -> bool { branch_name.contains(char::is_whitespace) },
        "/refs/heads/master foo"
    );

    // They cannot have tilde ~ anywhere.
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_a_tilde,
        proptest_branch_name_does_not_contain_a_tilde,
        |branch_name: &str| -> bool { branch_name.contains("?") },
        "/refs/heads/master~foo"
    );

    // They cannot have caret ^ anywhere.
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_a_carat,
        proptest_branch_name_does_not_contain_a_carat,
        |branch_name: &str| -> bool { branch_name.contains("^") },
        "/refs/heads/master^foo"
    );

    // They cannot have colon : anywhere.
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_a_colon,
        proptest_branch_name_does_not_contain_a_colon,
        |branch_name: &str| -> bool { branch_name.contains(":") },
        "/refs/heads/master:foo"
    );

    // They cannot have question-mark ? anywhere. See the --refspec-pattern option below for an exception to this rule.
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_a_question_mark,
        proptest_branch_name_does_not_contain_a_question_mark,
        |branch_name: &str| -> bool { branch_name.starts_with("?") },
        "/refs/heads/master?foo"
    );

    // They cannot have asterisk * anywhere. See the --refspec-pattern option below for an exception to this rule.
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_an_asterisk,
        proptest_branch_name_does_not_contain_an_asterisk,
        |branch_name: &str| -> bool { branch_name.starts_with("*") },
        "/refs/heads/master*foo"
    );

    // They cannot have open bracket [ anywhere. See the --refspec-pattern option below for an exception to this rule.
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_an_open_bracket,
        proptest_branch_name_does_not_contain_an_open_bracket,
        |branch_name: &str| -> bool { branch_name.starts_with("[") },
        "/refs/heads/master[foo"
    );

    // They cannot begin with a slash (/) (see the --normalize option for an exception to this rule)
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_begin_with_a_forward_slash,
        proptest_branch_name_does_not_begin_with_a_forward_slash,
        |branch_name: &str| -> bool { branch_name.starts_with("/") },
        "/refs/heads/master"
    );

    // They cannot begin with a slash (/) (see the --normalize option for an exception to this rule)
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_end_with_a_forward_slash,
        proptest_branch_name_does_not_end_with_a_forward_slash,
        |branch_name: &str| -> bool { branch_name.ends_with("/") },
        "refs/heads/master/"
    );

    // They cannot contain multiple consecutive slashes (see the --normalize option for an exception to this rule)
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_multiple_consecutive_forward_slashes,
        proptest_branch_name_does_not_contain_multiple_consecutive_forward_slashes,
        |branch_name: &str| -> bool { branch_name.contains("//") },
        "refs/heads/master//all-right"
    );

    // They cannot end with a dot .
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_end_with_dot,
        proptest_branch_name_does_not_end_with_dot,
        |branch_name: &str| -> bool { branch_name.ends_with(".") },
        "refs/heads/master."
    );

    // They cannot contain a sequence @{.
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_ampersand_open_brace,
        proptest_branch_name_does_not_contain_ampersand_open_brace,
        |branch_name: &str| -> bool { branch_name.contains("@{") },
        "refs/heads/master-@{-branch"
    );

    // FIXME: this implementation is too restrictive but I'm not exactly sure of the rules right now.
    // Happy to widen this up if I get more clarity and feel confident we'll avoid false-positives.
    // They cannot be the single character @.
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_ampersand,
        proptest_branch_name_does_not_contain_ampersand,
        |branch_name: &str| -> bool { branch_name.contains("@") },
        "refs/heads/master-@-branch"
    );

    // They cannot contain a \.
    test_does_not_violate_branch_naming_rule!(
        branch_name_does_not_contain_backslash,
        proptest_branch_name_does_not_contain_backslash,
        |branch_name: &str| -> bool { branch_name.contains(r"\") },
        r"refs/heads/master-\-branch"
    );
}