1use crate::{Span, Spanned, Url};
4use std::{
5 fmt::{Display, Formatter},
6 str::FromStr,
7};
8
9#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
11pub struct Remote {
12 pub package: Option<String>,
14 pub host: Option<String>,
16 pub source: RemoteSource,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
22pub enum RemoteSource {
23 Unspecified(String),
25 Cran(CranRemote),
27 GitHub(HostedGitRemote),
29 GitLab(HostedGitRemote),
31 Bitbucket(HostedGitRemote),
33 Git(GenericGitRemote),
35 Url(UrlRemote),
37 Local(LocalRemote),
39 Svn(SvnRemote),
41 Bioconductor(BioconductorRemote),
43 Unknown(UnknownRemote),
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
49pub struct CranRemote {
50 pub package: String,
52}
53#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
55pub struct HostedGitRemote {
56 pub owner: String,
58 pub repository: String,
60 pub subdirectory: Option<String>,
62 pub reference: Option<String>,
64}
65#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
67pub struct GenericGitRemote {
68 pub url: String,
70 pub reference: Option<String>,
72}
73#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
75pub struct UrlRemote {
76 pub url: Url,
78}
79#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
81pub struct LocalRemote {
82 pub path: String,
84}
85#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
87pub struct SvnRemote {
88 pub url: Url,
90}
91#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
93pub struct BioconductorCredentials {
94 pub username: String,
96 pub password: String,
98}
99#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
101pub struct BioconductorRemote {
102 pub credentials: Option<BioconductorCredentials>,
104 pub release: Option<String>,
106 pub package: String,
108 pub reference: Option<String>,
110}
111#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
113pub struct UnknownRemote {
114 pub kind: String,
116 pub payload: String,
118}
119
120impl std::fmt::Debug for GenericGitRemote {
121 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
122 f.debug_struct("GenericGitRemote")
123 .field("url", &RedactedText(&self.url))
124 .field("reference", &self.reference)
125 .finish()
126 }
127}
128impl std::fmt::Debug for UrlRemote {
129 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
130 f.debug_struct("UrlRemote")
131 .field("url", &RedactedUrl(&self.url))
132 .finish()
133 }
134}
135impl std::fmt::Debug for SvnRemote {
136 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
137 f.debug_struct("SvnRemote")
138 .field("url", &RedactedUrl(&self.url))
139 .finish()
140 }
141}
142impl std::fmt::Debug for BioconductorCredentials {
143 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
144 f.debug_struct("BioconductorCredentials")
145 .field("username", &"[REDACTED]")
146 .field("password", &"[REDACTED]")
147 .finish()
148 }
149}
150struct RedactedUrl<'a>(&'a Url);
151impl std::fmt::Debug for RedactedUrl<'_> {
152 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
153 let mut url = self.0.clone();
154 if !url.username().is_empty() || url.password().is_some() {
155 let _ = url.set_username("[REDACTED]");
156 let _ = url.set_password(Some("[REDACTED]"));
157 }
158 std::fmt::Debug::fmt(url.as_str(), f)
159 }
160}
161struct RedactedText<'a>(&'a str);
162impl std::fmt::Debug for RedactedText<'_> {
163 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
164 if let Ok(url) = Url::parse(self.0) {
165 return std::fmt::Debug::fmt(&RedactedUrl(&url), f);
166 }
167 if let Some((credentials, remote)) = self
168 .0
169 .split_once('@')
170 .filter(|(left, _)| left.contains(':'))
171 {
172 let _ = credentials;
173 return std::fmt::Debug::fmt(&format!("[REDACTED]@{remote}"), f);
174 }
175 std::fmt::Debug::fmt(self.0, f)
176 }
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
181pub enum RemoteParseError {
182 #[error("empty remote specification")]
184 EmptySpecification,
185 #[error("whitespace is not allowed in a remote specification")]
187 Whitespace,
188 #[error("multiple remote specifications found")]
190 MultipleSpecifications,
191 #[error("remote specification contains a control character")]
193 ControlCharacter,
194 #[error("malformed remote prefix")]
196 MalformedPrefix,
197 #[error("remote prefix is missing a source kind")]
199 MissingKind,
200 #[error("remote prefix is missing a host")]
202 MissingHost,
203 #[error("remote specification is missing its payload")]
205 MissingPayload,
206 #[error("invalid remote package alias")]
208 InvalidAlias,
209 #[error("remote is missing a repository owner or name")]
211 MissingRepository,
212 #[error("remote repository path contains an empty component")]
214 MissingPathComponent,
215 #[error("remote reference is missing")]
217 MissingReference,
218 #[error("Git remote is missing its URL")]
220 MissingGitUrl,
221 #[error("invalid remote URL: {0}")]
223 InvalidUrl(#[source] url::ParseError),
224 #[error("malformed Bioconductor reference")]
226 MalformedBioconductorReference,
227 #[error("malformed Bioconductor credentials")]
229 MalformedBioconductorCredentials,
230 #[error("malformed Bioconductor source")]
232 MalformedBioconductorSource,
233 #[error("malformed Bioconductor package")]
235 MalformedBioconductorPackage,
236}
237
238#[derive(Debug, Clone, PartialEq, Eq)]
240pub struct PositionedRemoteParseError {
241 error: RemoteParseError,
242 span: Span,
243}
244impl PositionedRemoteParseError {
245 pub const fn error(&self) -> &RemoteParseError {
247 &self.error
248 }
249 pub const fn span(&self) -> Span {
251 self.span
252 }
253 pub const fn range(&self) -> Span {
255 self.span
256 }
257}
258impl Display for PositionedRemoteParseError {
259 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
260 self.error.fmt(f)
261 }
262}
263impl std::error::Error for PositionedRemoteParseError {
264 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
265 Some(&self.error)
266 }
267}
268
269#[derive(Debug, Clone, PartialEq, Eq, Default)]
271pub struct RemoteList {
272 entries: Vec<Spanned<Remote>>,
273 issues: Vec<PositionedRemoteParseError>,
274}
275impl RemoteList {
276 pub fn parse(input: &str) -> Self {
278 if input.trim().is_empty() {
279 return Self::default();
280 }
281 let mut result = Self::default();
282 let mut start = 0;
283 for end in input
284 .match_indices(',')
285 .map(|(i, _)| i)
286 .chain(std::iter::once(input.len()))
287 {
288 let segment = &input[start..end];
289 let left = start + segment.len() - segment.trim_start().len();
290 let right = end - (segment.len() - segment.trim_end().len());
291 if left == right {
292 result.issues.push(remote_issue(
293 RemoteParseError::EmptySpecification,
294 left,
295 left,
296 ));
297 } else {
298 match parse_remote(&input[left..right]) {
299 Ok(value) => result.entries.push(Spanned {
300 value,
301 span: Span::new(left, right),
302 }),
303 Err(error) => result.issues.push(PositionedRemoteParseError {
304 error: error.error,
305 span: Span::new(left + error.span.start(), left + error.span.end()),
306 }),
307 }
308 }
309 start = end.saturating_add(1);
310 }
311 result
312 }
313 pub fn entries(&self) -> &[Spanned<Remote>] {
315 &self.entries
316 }
317 pub fn issues(&self) -> &[PositionedRemoteParseError] {
319 &self.issues
320 }
321 pub fn into_parts(self) -> (Vec<Spanned<Remote>>, Vec<PositionedRemoteParseError>) {
323 (self.entries, self.issues)
324 }
325}
326
327impl FromStr for Remote {
328 type Err = PositionedRemoteParseError;
329 fn from_str(input: &str) -> Result<Self, Self::Err> {
330 parse_remote(input)
331 }
332}
333
334fn parse_remote(input: &str) -> Result<Remote, PositionedRemoteParseError> {
335 if input.is_empty() {
336 return Err(remote_issue(RemoteParseError::EmptySpecification, 0, 0));
337 }
338 if let Some((i, c)) = input.char_indices().find(|(_, c)| c.is_whitespace()) {
339 return Err(remote_issue(
340 RemoteParseError::Whitespace,
341 i,
342 i + c.len_utf8(),
343 ));
344 }
345 if let Some(i) = input.find(',') {
346 return Err(remote_issue(
347 RemoteParseError::MultipleSpecifications,
348 i,
349 i + 1,
350 ));
351 }
352 if let Some((i, c)) = input.char_indices().find(|(_, c)| c.is_control()) {
353 return Err(remote_issue(
354 RemoteParseError::ControlCharacter,
355 i,
356 i + c.len_utf8(),
357 ));
358 }
359 let (package, source_start) = parse_alias(input)?;
360 let (kind, host, payload, payload_start) = parse_explicit(input, source_start)?;
361 let source = match kind.map(str::to_ascii_lowercase).as_deref() {
362 None if payload.contains('/') => {
363 RemoteSource::GitHub(parse_hosted(payload, payload_start, Hosted::GitHub)?)
364 }
365 None => RemoteSource::Unspecified(payload.into()),
366 Some("cran") => RemoteSource::Cran(CranRemote {
367 package: payload.into(),
368 }),
369 Some("github") => {
370 RemoteSource::GitHub(parse_hosted(payload, payload_start, Hosted::GitHub)?)
371 }
372 Some("gitlab") => {
373 RemoteSource::GitLab(parse_hosted(payload, payload_start, Hosted::GitLab)?)
374 }
375 Some("bitbucket") => {
376 RemoteSource::Bitbucket(parse_hosted(payload, payload_start, Hosted::Bitbucket)?)
377 }
378 Some("git") => RemoteSource::Git(parse_git(payload, payload_start)?),
379 Some("url") => RemoteSource::Url(UrlRemote {
380 url: parse_url(payload, payload_start)?,
381 }),
382 Some("local") => RemoteSource::Local(LocalRemote {
383 path: payload.into(),
384 }),
385 Some("svn") => RemoteSource::Svn(SvnRemote {
386 url: parse_url(payload, payload_start)?,
387 }),
388 Some("bioc") => RemoteSource::Bioconductor(parse_bioc(payload, payload_start)?),
389 Some(_) => RemoteSource::Unknown(UnknownRemote {
390 kind: kind.unwrap_or_default().into(),
391 payload: payload.into(),
392 }),
393 };
394 Ok(Remote {
395 package,
396 host,
397 source,
398 })
399}
400
401fn parse_alias(input: &str) -> Result<(Option<String>, usize), PositionedRemoteParseError> {
402 let Some(equal) = input.find('=') else {
403 return Ok((None, 0));
404 };
405 let syntax = input
406 .char_indices()
407 .find_map(|(i, c)| matches!(c, '/' | ':' | '@' | '#').then_some(i))
408 .unwrap_or(input.len());
409 if equal > syntax {
410 return Ok((None, 0));
411 }
412 let alias = &input[..equal];
413 let mut chars = alias.chars();
414 if !chars.next().is_some_and(|c| c.is_ascii_alphabetic())
415 || !chars.all(|c| c.is_ascii_alphanumeric() || c == '.')
416 {
417 return Err(remote_issue(RemoteParseError::InvalidAlias, 0, equal));
418 }
419 Ok((Some(alias.into()), equal + 1))
420}
421
422type Explicit<'a> = (Option<&'a str>, Option<String>, &'a str, usize);
423fn parse_explicit(input: &str, start: usize) -> Result<Explicit<'_>, PositionedRemoteParseError> {
424 let source = &input[start..];
425 let Some(relative) = source.find("::") else {
426 if source.is_empty() {
427 return Err(remote_issue(RemoteParseError::MissingPayload, start, start));
428 }
429 return Ok((None, None, source, start));
430 };
431 let separator = start + relative;
432 let prefix = &input[start..separator];
433 let payload_start = separator + 2;
434 let payload = &input[payload_start..];
435 if prefix.is_empty() {
436 return Err(remote_issue(RemoteParseError::MissingKind, start, start));
437 }
438 if payload.is_empty() {
439 return Err(remote_issue(
440 RemoteParseError::MissingPayload,
441 payload_start,
442 payload_start,
443 ));
444 }
445 let mut parts = prefix.split('@');
446 let kind = parts.next().unwrap_or_default();
447 let host = parts.next();
448 if parts.next().is_some() {
449 return Err(remote_issue(
450 RemoteParseError::MalformedPrefix,
451 start,
452 separator,
453 ));
454 }
455 if kind.is_empty() {
456 return Err(remote_issue(RemoteParseError::MissingKind, start, start));
457 }
458 let host = match host {
459 Some("") => {
460 return Err(remote_issue(
461 RemoteParseError::MissingHost,
462 separator,
463 separator,
464 ));
465 }
466 Some(value) => Some(value.into()),
467 None => None,
468 };
469 Ok((Some(kind), host, payload, payload_start))
470}
471
472#[derive(Clone, Copy)]
473enum Hosted {
474 GitHub,
475 GitLab,
476 Bitbucket,
477}
478fn parse_hosted(
479 payload: &str,
480 start: usize,
481 kind: Hosted,
482) -> Result<HostedGitRemote, PositionedRemoteParseError> {
483 let delimiter = payload.char_indices().find(|(_, c)| matches!(c, '@' | '#'));
484 let (path, reference) = match delimiter {
485 Some((i, _)) if i + 1 < payload.len() => (&payload[..i], Some(payload[i + 1..].into())),
486 Some((i, _)) => {
487 return Err(remote_issue(
488 RemoteParseError::MissingReference,
489 start + i + 1,
490 start + i + 1,
491 ));
492 }
493 None => (payload, None),
494 };
495 let path = path.trim_end_matches('/');
496 let parts: Vec<_> = path.split('/').collect();
497 if parts.len() < 2 {
498 return Err(remote_issue(
499 RemoteParseError::MissingRepository,
500 start,
501 start + path.len(),
502 ));
503 }
504 if let Some((index, _)) = parts.iter().enumerate().find(|(_, part)| part.is_empty()) {
505 let offset = parts[..index]
506 .iter()
507 .map(|part| part.len() + 1)
508 .sum::<usize>();
509 return Err(remote_issue(
510 RemoteParseError::MissingPathComponent,
511 start + offset,
512 start + offset,
513 ));
514 }
515 let (repository, subdirectory) = match kind {
516 Hosted::GitLab => (parts[1..].join("/"), None),
517 Hosted::GitHub | Hosted::Bitbucket => (
518 parts[1].into(),
519 (parts.len() > 2).then(|| parts[2..].join("/")),
520 ),
521 };
522 Ok(HostedGitRemote {
523 owner: parts[0].into(),
524 repository,
525 subdirectory,
526 reference,
527 })
528}
529
530fn parse_git(payload: &str, start: usize) -> Result<GenericGitRemote, PositionedRemoteParseError> {
531 if payload.is_empty() {
532 return Err(remote_issue(RemoteParseError::MissingGitUrl, start, start));
533 }
534 let path_start = if let Some(scheme) = payload.find("://") {
535 payload[scheme + 3..]
536 .find('/')
537 .map_or(payload.len(), |i| scheme + 3 + i)
538 } else if let Some(auth) = payload.find('@') {
539 payload[auth + 1..].find(':').map_or(0, |i| auth + 2 + i)
540 } else {
541 0
542 };
543 let split = payload[path_start..].find('@').map(|i| path_start + i);
544 if split == Some(0) {
545 return Err(remote_issue(RemoteParseError::MissingGitUrl, start, start));
546 }
547 if split == Some(payload.len() - 1) {
548 return Err(remote_issue(
549 RemoteParseError::MissingReference,
550 start + payload.len(),
551 start + payload.len(),
552 ));
553 }
554 let (url, reference) = split.map_or_else(
555 || (payload.into(), None),
556 |i| (payload[..i].into(), Some(payload[i + 1..].into())),
557 );
558 Ok(GenericGitRemote { url, reference })
559}
560fn parse_url(payload: &str, start: usize) -> Result<Url, PositionedRemoteParseError> {
561 Url::parse(payload).map_err(|error| {
562 remote_issue(
563 RemoteParseError::InvalidUrl(error),
564 start,
565 start + payload.len(),
566 )
567 })
568}
569
570fn parse_bioc(
571 payload: &str,
572 start: usize,
573) -> Result<BioconductorRemote, PositionedRemoteParseError> {
574 let (source, reference) = match payload.split_once('#') {
575 Some((source, reference)) if !source.is_empty() && !reference.is_empty() => {
576 (source, Some(reference.into()))
577 }
578 Some((source, _)) => {
579 return Err(remote_issue(
580 RemoteParseError::MalformedBioconductorReference,
581 start + source.len(),
582 start + payload.len(),
583 ));
584 }
585 None => (payload, None),
586 };
587 let (credentials, source) = match source.find('@') {
588 Some(at) if source[..at].contains(':') => {
589 let (username, password) = source[..at].split_once(':').expect("colon was found");
590 if username.is_empty() || password.is_empty() {
591 return Err(remote_issue(
592 RemoteParseError::MalformedBioconductorCredentials,
593 start,
594 start + at,
595 ));
596 }
597 (
598 Some(BioconductorCredentials {
599 username: username.into(),
600 password: password.into(),
601 }),
602 &source[at + 1..],
603 )
604 }
605 _ => (None, source),
606 };
607 let source_start = start + payload.len()
608 - reference
609 .as_ref()
610 .map_or(0, |value: &String| value.len() + 1)
611 - source.len();
612 let (release, package) = match source.split_once('/') {
613 Some((release, package)) if !release.is_empty() && !package.is_empty() => {
614 (Some(release.into()), package)
615 }
616 Some(_) => {
617 return Err(remote_issue(
618 RemoteParseError::MalformedBioconductorSource,
619 source_start,
620 source_start + source.len(),
621 ));
622 }
623 None => (None, source),
624 };
625 if package.is_empty() || package.contains('/') {
626 let at = source_start + release.as_ref().map_or(0, |value: &String| value.len() + 1);
627 return Err(remote_issue(
628 RemoteParseError::MalformedBioconductorPackage,
629 at,
630 at + package.len(),
631 ));
632 }
633 Ok(BioconductorRemote {
634 credentials,
635 release,
636 package: package.into(),
637 reference,
638 })
639}
640
641impl Display for Remote {
642 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
643 if let Some(package) = &self.package {
644 write!(f, "{package}=")?;
645 }
646 match &self.source {
647 RemoteSource::Unspecified(value) => f.write_str(value),
648 RemoteSource::Cran(value) => {
649 prefix(f, "cran", self.host.as_deref())?;
650 f.write_str(&value.package)
651 }
652 RemoteSource::GitHub(value) => {
653 prefix(f, "github", self.host.as_deref())?;
654 hosted(f, value)
655 }
656 RemoteSource::GitLab(value) => {
657 prefix(f, "gitlab", self.host.as_deref())?;
658 hosted(f, value)
659 }
660 RemoteSource::Bitbucket(value) => {
661 prefix(f, "bitbucket", self.host.as_deref())?;
662 hosted(f, value)
663 }
664 RemoteSource::Git(value) => {
665 prefix(f, "git", self.host.as_deref())?;
666 f.write_str(&value.url)?;
667 reference(f, value.reference.as_deref(), '@')
668 }
669 RemoteSource::Url(value) => {
670 prefix(f, "url", self.host.as_deref())?;
671 value.url.fmt(f)
672 }
673 RemoteSource::Local(value) => {
674 prefix(f, "local", self.host.as_deref())?;
675 f.write_str(&value.path)
676 }
677 RemoteSource::Svn(value) => {
678 prefix(f, "svn", self.host.as_deref())?;
679 value.url.fmt(f)
680 }
681 RemoteSource::Bioconductor(value) => {
682 prefix(f, "bioc", self.host.as_deref())?;
683 if let Some(credentials) = &value.credentials {
684 write!(f, "{}:{}@", credentials.username, credentials.password)?;
685 }
686 if let Some(release) = &value.release {
687 write!(f, "{release}/")?;
688 }
689 f.write_str(&value.package)?;
690 reference(f, value.reference.as_deref(), '#')
691 }
692 RemoteSource::Unknown(value) => {
693 f.write_str(&value.kind)?;
694 if let Some(host) = &self.host {
695 write!(f, "@{host}")?;
696 }
697 write!(f, "::{}", value.payload)
698 }
699 }
700 }
701}
702fn prefix(f: &mut Formatter<'_>, kind: &str, host: Option<&str>) -> std::fmt::Result {
703 f.write_str(kind)?;
704 if let Some(host) = host {
705 write!(f, "@{host}")?;
706 }
707 f.write_str("::")
708}
709fn hosted(f: &mut Formatter<'_>, value: &HostedGitRemote) -> std::fmt::Result {
710 write!(f, "{}/{}", value.owner, value.repository)?;
711 if let Some(subdirectory) = &value.subdirectory {
712 write!(f, "/{subdirectory}")?;
713 }
714 reference(f, value.reference.as_deref(), '@')
715}
716fn reference(f: &mut Formatter<'_>, value: Option<&str>, delimiter: char) -> std::fmt::Result {
717 if let Some(value) = value {
718 write!(f, "{delimiter}{value}")?;
719 }
720 Ok(())
721}
722fn remote_issue(error: RemoteParseError, start: usize, end: usize) -> PositionedRemoteParseError {
723 PositionedRemoteParseError {
724 error,
725 span: Span::new(start, end),
726 }
727}