|
2 | 2 | // This is based on https://github.com/rust-lang/cargo/blob/489b66f2e458404a10d7824194d3ded94bc1f4e4/src/cargo/util/restricted_names.rs
|
3 | 3 |
|
4 | 4 | use anyhow::{bail, Result};
|
| 5 | +use regex::Regex; |
5 | 6 | use std::path::Path;
|
6 | 7 |
|
7 | 8 | /// Returns `true` if the name contains non-ASCII characters.
|
@@ -94,6 +95,18 @@ pub fn is_glob_pattern<T: AsRef<str>>(name: T) -> bool {
|
94 | 95 | name.as_ref().contains(&['*', '?', '[', ']'][..])
|
95 | 96 | }
|
96 | 97 |
|
| 98 | +/// Check the project name format. |
| 99 | +pub fn is_valid_project_name_format(name: &str) -> Result<()> { |
| 100 | + let re = Regex::new(r"^([a-zA-Z]([a-zA-Z0-9-_]+)|)$").unwrap(); |
| 101 | + if !re.is_match(name) { |
| 102 | + bail!( |
| 103 | + "'{name}' is not a valid name for a project. \n\ |
| 104 | + The name may use letters, numbers, hyphens, and underscores, and must start with a letter." |
| 105 | + ); |
| 106 | + } |
| 107 | + Ok(()) |
| 108 | +} |
| 109 | + |
97 | 110 | #[test]
|
98 | 111 | fn test_invalid_char() {
|
99 | 112 | assert_eq!(
|
@@ -130,3 +143,35 @@ fn test_invalid_char() {
|
130 | 143 | std::result::Result::Ok(())
|
131 | 144 | ));
|
132 | 145 | }
|
| 146 | + |
| 147 | +#[test] |
| 148 | +fn test_is_valid_project_name_format() { |
| 149 | + let assert_valid = |name: &str| { |
| 150 | + is_valid_project_name_format(name).expect("this should pass"); |
| 151 | + }; |
| 152 | + |
| 153 | + let assert_invalid = |name: &str, expected_error: &str| { |
| 154 | + assert_eq!( |
| 155 | + is_valid_project_name_format(name).map_err(|e| e.to_string()), |
| 156 | + Err(expected_error.into()) |
| 157 | + ); |
| 158 | + }; |
| 159 | + |
| 160 | + let format_error_message = |name: &str| -> String { |
| 161 | + format!( |
| 162 | + "'{}' is not a valid name for a project. \n\ |
| 163 | + The name may use letters, numbers, hyphens, and underscores, and must start with a letter.", |
| 164 | + name |
| 165 | + ) |
| 166 | + }; |
| 167 | + |
| 168 | + // Test valid project names |
| 169 | + assert_valid("mock_project_name"); |
| 170 | + assert_valid("mock_project_name123"); |
| 171 | + assert_valid("mock_project_name-123-_"); |
| 172 | + |
| 173 | + // Test invalid project names |
| 174 | + assert_invalid("1mock_project", &format_error_message("1mock_project")); |
| 175 | + assert_invalid("mock_.project", &format_error_message("mock_.project")); |
| 176 | + assert_invalid("mock_/project", &format_error_message("mock_/project")); |
| 177 | +} |
0 commit comments