| 1 | use std::{fmt, str::FromStr, time::SystemTime}; |
| 2 | |
| 3 | use super::{DomainError, ImportSource, ImportState, OrgId, RepoId}; |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | const RESERVED: &[&str] = &["import", "new", "search"]; |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 23 | pub struct RepoName(String); |
| 24 | |
| 25 | impl RepoName { |
| 26 | pub const MAX_LEN: usize = 100; |
| 27 | |
| 28 | |
| 29 | pub fn new(value: impl Into<String>) -> Result<Self, DomainError> { |
| 30 | let value = value.into(); |
| 31 | let trimmed = value.trim(); |
| 32 | |
| 33 | let invalid = |reason: &str| DomainError::validation("repository name", reason); |
| 34 | |
| 35 | if trimmed.is_empty() { |
| 36 | return Err(invalid("must not be empty")); |
| 37 | } |
| 38 | if trimmed.chars().count() > Self::MAX_LEN { |
| 39 | return Err(invalid("must be at most 100 characters")); |
| 40 | } |
| 41 | if !trimmed |
| 42 | .chars() |
| 43 | .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) |
| 44 | { |
| 45 | return Err(invalid( |
| 46 | "may only contain letters, digits, hyphens, underscores, and dots", |
| 47 | )); |
| 48 | } |
| 49 | if trimmed.starts_with('-') || trimmed.ends_with('-') { |
| 50 | return Err(invalid("must not start or end with a hyphen")); |
| 51 | } |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | if trimmed.chars().all(|c| c == '.') { |
| 57 | return Err(invalid("must not consist only of dots")); |
| 58 | } |
| 59 | |
| 60 | let normalised = trimmed.to_lowercase(); |
| 61 | |
| 62 | |
| 63 | |
| 64 | if normalised.ends_with(".git") { |
| 65 | return Err(invalid("must not end with .git")); |
| 66 | } |
| 67 | if RESERVED.contains(&normalised.as_str()) { |
| 68 | return Err(invalid("is reserved")); |
| 69 | } |
| 70 | |
| 71 | Ok(Self(normalised)) |
| 72 | } |
| 73 | |
| 74 | |
| 75 | pub fn from_trusted(value: impl Into<String>) -> Self { |
| 76 | Self(value.into()) |
| 77 | } |
| 78 | |
| 79 | pub fn as_str(&self) -> &str { |
| 80 | &self.0 |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | impl fmt::Display for RepoName { |
| 85 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 86 | f.write_str(&self.0) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | |
| 91 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 92 | pub enum Visibility { |
| 93 | |
| 94 | |
| 95 | |
| 96 | #[default] |
| 97 | Public, |
| 98 | |
| 99 | Private, |
| 100 | } |
| 101 | |
| 102 | impl Visibility { |
| 103 | pub fn as_str(self) -> &'static str { |
| 104 | match self { |
| 105 | Self::Public => "public", |
| 106 | Self::Private => "private", |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | pub fn is_public(self) -> bool { |
| 111 | self == Self::Public |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | impl fmt::Display for Visibility { |
| 116 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 117 | f.write_str(self.as_str()) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | |
| 122 | |
| 123 | impl FromStr for Visibility { |
| 124 | type Err = DomainError; |
| 125 | |
| 126 | fn from_str(value: &str) -> Result<Self, Self::Err> { |
| 127 | match value { |
| 128 | "public" => Ok(Self::Public), |
| 129 | "private" => Ok(Self::Private), |
| 130 | other => Err(DomainError::validation( |
| 131 | "visibility", |
| 132 | format!("unknown visibility {other:?}"), |
| 133 | )), |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | |
| 139 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 140 | pub struct Repository { |
| 141 | pub id: RepoId, |
| 142 | pub org_id: OrgId, |
| 143 | pub name: RepoName, |
| 144 | pub description: Option<String>, |
| 145 | pub visibility: Visibility, |
| 146 | |
| 147 | |
| 148 | |
| 149 | pub updated_at: SystemTime, |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | pub pinned: bool, |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | pub archived: bool, |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | pub import_state: Option<ImportState>, |
| 170 | |
| 171 | |
| 172 | |
| 173 | pub import_source: Option<ImportSource>, |
| 174 | |
| 175 | |
| 176 | pub import_error: Option<String>, |
| 177 | } |
| 178 | |
| 179 | impl Repository { |
| 180 | |
| 181 | pub const MAX_DESCRIPTION_LEN: usize = 300; |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | pub fn new( |
| 189 | id: RepoId, |
| 190 | org_id: OrgId, |
| 191 | name: impl Into<String>, |
| 192 | description: Option<String>, |
| 193 | visibility: Visibility, |
| 194 | now: SystemTime, |
| 195 | ) -> Result<Self, DomainError> { |
| 196 | let description = normalise_optional(description); |
| 197 | |
| 198 | if let Some(description) = &description |
| 199 | && description.chars().count() > Self::MAX_DESCRIPTION_LEN |
| 200 | { |
| 201 | return Err(DomainError::validation( |
| 202 | "description", |
| 203 | format!("must be at most {} characters", Self::MAX_DESCRIPTION_LEN), |
| 204 | )); |
| 205 | } |
| 206 | |
| 207 | Ok(Self { |
| 208 | id, |
| 209 | org_id, |
| 210 | name: RepoName::new(name)?, |
| 211 | description, |
| 212 | visibility, |
| 213 | updated_at: now, |
| 214 | pinned: false, |
| 215 | archived: false, |
| 216 | import_state: None, |
| 217 | import_source: None, |
| 218 | import_error: None, |
| 219 | }) |
| 220 | } |
| 221 | |
| 222 | |
| 223 | #[allow(clippy::too_many_arguments)] |
| 224 | pub fn from_trusted( |
| 225 | id: RepoId, |
| 226 | org_id: OrgId, |
| 227 | name: RepoName, |
| 228 | description: Option<String>, |
| 229 | visibility: Visibility, |
| 230 | updated_at: SystemTime, |
| 231 | pinned: bool, |
| 232 | archived: bool, |
| 233 | ) -> Self { |
| 234 | Self { |
| 235 | id, |
| 236 | org_id, |
| 237 | name, |
| 238 | description, |
| 239 | visibility, |
| 240 | updated_at, |
| 241 | pinned, |
| 242 | archived, |
| 243 | import_state: None, |
| 244 | import_source: None, |
| 245 | import_error: None, |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 254 | #[must_use] |
| 255 | pub fn with_import( |
| 256 | mut self, |
| 257 | state: Option<ImportState>, |
| 258 | source: Option<ImportSource>, |
| 259 | error: Option<String>, |
| 260 | ) -> Self { |
| 261 | self.import_state = state; |
| 262 | self.import_source = source; |
| 263 | self.import_error = error; |
| 264 | self |
| 265 | } |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | pub fn start_import(&mut self, source: ImportSource) { |
| 272 | self.import_state = Some(ImportState::Importing); |
| 273 | self.import_source = Some(source); |
| 274 | self.import_error = None; |
| 275 | } |
| 276 | |
| 277 | |
| 278 | pub fn fail_import(&mut self, reason: impl Into<String>) { |
| 279 | self.import_state = Some(ImportState::Failed); |
| 280 | self.import_error = Some(reason.into()); |
| 281 | } |
| 282 | |
| 283 | |
| 284 | |
| 285 | pub fn finish_import(&mut self) { |
| 286 | self.import_state = None; |
| 287 | self.import_error = None; |
| 288 | } |
| 289 | |
| 290 | |
| 291 | |
| 292 | pub fn is_importing(&self) -> bool { |
| 293 | self.import_state.is_some() |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | |
| 298 | fn normalise_optional(value: Option<String>) -> Option<String> { |
| 299 | value |
| 300 | .map(|value| value.trim().to_owned()) |
| 301 | .filter(|value| !value.is_empty()) |
| 302 | } |
| 303 | |
| 304 | #[cfg(test)] |
| 305 | mod tests { |
| 306 | use super::*; |
| 307 | |
| 308 | #[test] |
| 309 | fn accepts_ordinary_repository_names() { |
| 310 | for input in [ |
| 311 | "steid", |
| 312 | "my-repo", |
| 313 | "my_repo", |
| 314 | "foo.js", |
| 315 | ".github", |
| 316 | "v2", |
| 317 | "a", |
| 318 | "dot.separated.name", |
| 319 | "trailing.", |
| 320 | ] { |
| 321 | assert!( |
| 322 | RepoName::new(input).is_ok(), |
| 323 | "expected {input:?} to be accepted" |
| 324 | ); |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | #[test] |
| 329 | fn normalises_case_and_whitespace() { |
| 330 | let name = RepoName::new(" MyRepo ").expect("should be valid"); |
| 331 | |
| 332 | assert_eq!(name.as_str(), "myrepo"); |
| 333 | } |
| 334 | |
| 335 | |
| 336 | |
| 337 | #[test] |
| 338 | fn rejects_anything_that_could_escape_the_data_directory() { |
| 339 | for input in [ |
| 340 | ".", |
| 341 | "..", |
| 342 | "...", |
| 343 | "../etc", |
| 344 | "..%2F..%2Fetc", |
| 345 | "foo/bar", |
| 346 | "foo\\bar", |
| 347 | "/absolute", |
| 348 | "~root", |
| 349 | "with space", |
| 350 | "new\nline", |
| 351 | "nul\0byte", |
| 352 | ] { |
| 353 | assert!( |
| 354 | RepoName::new(input).is_err(), |
| 355 | "expected {input:?} to be rejected: it could escape the data directory" |
| 356 | ); |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | #[test] |
| 361 | fn rejects_malformed_names() { |
| 362 | for input in [ |
| 363 | "", |
| 364 | " ", |
| 365 | "-leading", |
| 366 | "trailing-", |
| 367 | "emoji🦀", |
| 368 | &"a".repeat(101), |
| 369 | ] { |
| 370 | assert!( |
| 371 | RepoName::new(input).is_err(), |
| 372 | "expected {input:?} to be rejected" |
| 373 | ); |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | #[test] |
| 378 | fn rejects_names_ending_in_dot_git() { |
| 379 | |
| 380 | assert!(RepoName::new("foo.git").is_err()); |
| 381 | assert!(RepoName::new("FOO.GIT").is_err()); |
| 382 | |
| 383 | assert!(RepoName::new("foo.github").is_ok()); |
| 384 | } |
| 385 | |
| 386 | #[test] |
| 387 | fn rejects_reserved_names() { |
| 388 | for reserved in RESERVED { |
| 389 | assert!( |
| 390 | RepoName::new(*reserved).is_err(), |
| 391 | "expected {reserved:?} to be reserved" |
| 392 | ); |
| 393 | } |
| 394 | |
| 395 | assert!(RepoName::new("NEW").is_err()); |
| 396 | } |
| 397 | |
| 398 | #[test] |
| 399 | fn reservation_does_not_leak_into_substrings() { |
| 400 | for allowed in ["newton", "renew", "imports", "research"] { |
| 401 | assert!( |
| 402 | RepoName::new(allowed).is_ok(), |
| 403 | "expected {allowed:?} to be allowed" |
| 404 | ); |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | #[test] |
| 409 | fn the_reserved_list_is_sorted_and_unique() { |
| 410 | let mut sorted = RESERVED.to_vec(); |
| 411 | sorted.sort_unstable(); |
| 412 | sorted.dedup(); |
| 413 | |
| 414 | assert_eq!( |
| 415 | sorted.as_slice(), |
| 416 | RESERVED, |
| 417 | "keep RESERVED sorted and unique" |
| 418 | ); |
| 419 | } |
| 420 | |
| 421 | #[test] |
| 422 | fn accepts_a_name_at_the_length_limit() { |
| 423 | assert!(RepoName::new("a".repeat(RepoName::MAX_LEN)).is_ok()); |
| 424 | } |
| 425 | |
| 426 | #[test] |
| 427 | fn repositories_default_to_public() { |
| 428 | assert_eq!(Visibility::default(), Visibility::Public); |
| 429 | assert!(Visibility::default().is_public()); |
| 430 | } |
| 431 | |
| 432 | #[test] |
| 433 | fn visibility_round_trips_through_strings() { |
| 434 | for visibility in [Visibility::Public, Visibility::Private] { |
| 435 | assert_eq!( |
| 436 | visibility |
| 437 | .as_str() |
| 438 | .parse::<Visibility>() |
| 439 | .expect("round trip"), |
| 440 | visibility |
| 441 | ); |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | #[test] |
| 446 | fn unknown_visibility_is_an_error_not_a_default() { |
| 447 | |
| 448 | assert!("internal".parse::<Visibility>().is_err()); |
| 449 | assert!("Public".parse::<Visibility>().is_err()); |
| 450 | } |
| 451 | |
| 452 | fn repo(description: Option<&str>) -> Result<Repository, DomainError> { |
| 453 | Repository::new( |
| 454 | RepoId::generate(), |
| 455 | OrgId::generate(), |
| 456 | "steid", |
| 457 | description.map(str::to_owned), |
| 458 | Visibility::Public, |
| 459 | at(1_000), |
| 460 | ) |
| 461 | } |
| 462 | |
| 463 | fn at(seconds: u64) -> SystemTime { |
| 464 | SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(seconds) |
| 465 | } |
| 466 | |
| 467 | #[test] |
| 468 | fn a_new_repository_is_stamped_with_the_time_it_was_created() { |
| 469 | let repo = Repository::new( |
| 470 | RepoId::generate(), |
| 471 | OrgId::generate(), |
| 472 | "steid", |
| 473 | None, |
| 474 | Visibility::Public, |
| 475 | at(1_700), |
| 476 | ) |
| 477 | .expect("valid"); |
| 478 | |
| 479 | assert_eq!(repo.updated_at, at(1_700)); |
| 480 | } |
| 481 | |
| 482 | #[test] |
| 483 | fn a_new_repository_is_not_an_import() { |
| 484 | |
| 485 | |
| 486 | let repo = repo(None).expect("valid"); |
| 487 | |
| 488 | assert_eq!(repo.import_state, None); |
| 489 | assert_eq!(repo.import_source, None); |
| 490 | assert!(!repo.is_importing()); |
| 491 | } |
| 492 | |
| 493 | #[test] |
| 494 | fn an_import_runs_then_clears() { |
| 495 | let mut repo = repo(None).expect("valid"); |
| 496 | let source = ImportSource::new("https://example.com/thing.git").expect("valid source"); |
| 497 | |
| 498 | repo.start_import(source.clone()); |
| 499 | assert_eq!(repo.import_state, Some(ImportState::Importing)); |
| 500 | assert!(repo.is_importing()); |
| 501 | |
| 502 | repo.finish_import(); |
| 503 | assert_eq!(repo.import_state, None); |
| 504 | assert!(!repo.is_importing()); |
| 505 | |
| 506 | assert_eq!(repo.import_source, Some(source)); |
| 507 | } |
| 508 | |
| 509 | #[test] |
| 510 | fn a_failed_import_keeps_its_source_and_its_reason() { |
| 511 | let mut repo = repo(None).expect("valid"); |
| 512 | repo.start_import(ImportSource::new("https://example.com/thing.git").expect("valid")); |
| 513 | repo.fail_import("the remote hung up"); |
| 514 | |
| 515 | assert_eq!(repo.import_state, Some(ImportState::Failed)); |
| 516 | assert_eq!(repo.import_error.as_deref(), Some("the remote hung up")); |
| 517 | |
| 518 | assert!(repo.import_source.is_some()); |
| 519 | } |
| 520 | |
| 521 | #[test] |
| 522 | fn restarting_an_import_clears_the_previous_reason() { |
| 523 | let mut repo = repo(None).expect("valid"); |
| 524 | repo.start_import(ImportSource::new("https://example.com/a.git").expect("valid")); |
| 525 | repo.fail_import("the remote hung up"); |
| 526 | repo.start_import(ImportSource::new("https://example.com/b.git").expect("valid")); |
| 527 | |
| 528 | assert_eq!(repo.import_error, None); |
| 529 | } |
| 530 | |
| 531 | #[test] |
| 532 | fn a_new_repository_is_not_pinned() { |
| 533 | |
| 534 | |
| 535 | assert!(!repo(None).expect("valid").pinned); |
| 536 | } |
| 537 | |
| 538 | #[test] |
| 539 | fn a_new_repository_is_not_archived() { |
| 540 | |
| 541 | assert!(!repo(None).expect("valid").archived); |
| 542 | } |
| 543 | |
| 544 | #[test] |
| 545 | fn a_repository_keeps_its_description() { |
| 546 | let repo = repo(Some("A personal-first gitforge.")).expect("valid"); |
| 547 | |
| 548 | assert_eq!( |
| 549 | repo.description.as_deref(), |
| 550 | Some("A personal-first gitforge.") |
| 551 | ); |
| 552 | } |
| 553 | |
| 554 | #[test] |
| 555 | fn a_blank_description_is_treated_as_unset() { |
| 556 | assert_eq!(repo(Some(" ")).expect("valid").description, None); |
| 557 | } |
| 558 | |
| 559 | #[test] |
| 560 | fn rejects_an_over_long_description() { |
| 561 | let long = "a".repeat(Repository::MAX_DESCRIPTION_LEN + 1); |
| 562 | |
| 563 | let error = repo(Some(&long)).expect_err("should reject"); |
| 564 | |
| 565 | assert!(matches!(error, DomainError::Validation { .. })); |
| 566 | } |
| 567 | |
| 568 | #[test] |
| 569 | fn description_length_counts_characters_not_bytes() { |
| 570 | let accented = "é".repeat(Repository::MAX_DESCRIPTION_LEN); |
| 571 | |
| 572 | assert!(repo(Some(&accented)).is_ok()); |
| 573 | } |
| 574 | |
| 575 | #[test] |
| 576 | fn an_invalid_name_rejects_the_whole_repository() { |
| 577 | let error = Repository::new( |
| 578 | RepoId::generate(), |
| 579 | OrgId::generate(), |
| 580 | "../escape", |
| 581 | None, |
| 582 | Visibility::Public, |
| 583 | at(1_000), |
| 584 | ) |
| 585 | .expect_err("should reject"); |
| 586 | |
| 587 | assert!(matches!(error, DomainError::Validation { .. })); |
| 588 | } |
| 589 | } |