1use crate::description::map_entry_value_range;
4use crate::{RDescription, TextRange};
5use rowan::TextSize;
6use std::fmt::{Display, Formatter};
7use std::str::FromStr;
8use url::Url;
9
10#[derive(Debug, Clone, PartialEq, Eq, Hash)]
25pub struct Remote {
26 pub package: Option<String>,
28 pub host: Option<String>,
30 pub source: RemoteSource,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Hash)]
36pub enum RemoteSource {
37 Unspecified(String),
39 Cran(CranRemote),
41 GitHub(HostedGitRemote),
43 GitLab(HostedGitRemote),
45 Bitbucket(HostedGitRemote),
47 Git(GenericGitRemote),
49 Url(UrlRemote),
51 Local(LocalRemote),
53 Svn(SvnRemote),
55 Bioconductor(BioconductorRemote),
57 Unknown(UnknownRemote),
59}
60
61#[derive(Debug, Clone, PartialEq, Eq, Hash)]
63pub struct CranRemote {
64 pub package: String,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Hash)]
70pub struct HostedGitRemote {
71 pub owner: String,
73 pub repository: String,
75 pub subdirectory: Option<String>,
77 pub reference: Option<String>,
79}
80
81#[derive(Clone, PartialEq, Eq, Hash)]
83pub struct GenericGitRemote {
84 pub url: String,
86 pub reference: Option<String>,
88}
89
90#[derive(Clone, PartialEq, Eq, Hash)]
92pub struct UrlRemote {
93 pub url: Url,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Hash)]
99pub struct LocalRemote {
100 pub path: String,
102}
103
104#[derive(Clone, PartialEq, Eq, Hash)]
106pub struct SvnRemote {
107 pub url: Url,
109}
110
111#[derive(Clone, PartialEq, Eq, Hash)]
113pub struct BioconductorCredentials {
114 pub username: String,
116 pub password: String,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Hash)]
122pub struct BioconductorRemote {
123 pub credentials: Option<BioconductorCredentials>,
125 pub release: Option<String>,
127 pub package: String,
129 pub reference: Option<String>,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq, Hash)]
135pub struct UnknownRemote {
136 pub kind: String,
138 pub payload: String,
140}
141
142impl std::fmt::Debug for GenericGitRemote {
143 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
144 formatter
145 .debug_struct("GenericGitRemote")
146 .field("url", &RedactedUrlText(&self.url))
147 .field("reference", &self.reference)
148 .finish()
149 }
150}
151
152impl std::fmt::Debug for UrlRemote {
153 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
154 formatter
155 .debug_struct("UrlRemote")
156 .field("url", &RedactedUrl(&self.url))
157 .finish()
158 }
159}
160
161impl std::fmt::Debug for SvnRemote {
162 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
163 formatter
164 .debug_struct("SvnRemote")
165 .field("url", &RedactedUrl(&self.url))
166 .finish()
167 }
168}
169
170impl std::fmt::Debug for BioconductorCredentials {
171 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
172 formatter
173 .debug_struct("BioconductorCredentials")
174 .field("username", &"[REDACTED]")
175 .field("password", &"[REDACTED]")
176 .finish()
177 }
178}
179
180struct RedactedUrl<'a>(&'a Url);
181
182impl std::fmt::Debug for RedactedUrl<'_> {
183 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
184 let mut url = self.0.clone();
185 if !url.username().is_empty() || url.password().is_some() {
186 let _ = url.set_username("[REDACTED]");
187 let _ = url.set_password(Some("[REDACTED]"));
188 }
189 std::fmt::Debug::fmt(url.as_str(), formatter)
190 }
191}
192
193struct RedactedUrlText<'a>(&'a str);
194
195impl std::fmt::Debug for RedactedUrlText<'_> {
196 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
197 match Url::parse(self.0) {
198 Ok(url) if !url.username().is_empty() || url.password().is_some() => {
199 std::fmt::Debug::fmt(&RedactedUrl(&url), formatter)
200 }
201 _ => match self.0.split_once('@') {
202 Some((credentials, remote)) if credentials.contains(':') => {
203 std::fmt::Debug::fmt(&format!("[REDACTED]@{remote}"), formatter)
204 }
205 _ => std::fmt::Debug::fmt(self.0, formatter),
206 },
207 }
208 }
209}
210
211#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
217pub enum RemoteParseError {
218 #[error("remote input exceeds the supported text size")]
220 InputTooLong,
221 #[error("empty remote specification")]
223 EmptySpecification,
224 #[error("whitespace is not allowed in a remote specification")]
226 Whitespace,
227 #[error("multiple remote specifications found")]
229 MultipleSpecifications,
230 #[error("remote specification contains a control character")]
232 ControlCharacter,
233 #[error("malformed remote specification")]
235 MalformedSpecification,
236 #[error("malformed remote prefix")]
238 MalformedPrefix,
239 #[error("remote prefix is missing a source kind")]
241 MissingKind,
242 #[error("remote prefix is missing a host")]
244 MissingHost,
245 #[error("remote specification is missing its payload")]
247 MissingPayload,
248 #[error("invalid remote package alias")]
250 InvalidAlias,
251 #[error("remote is missing a repository owner or name")]
253 MissingRepository,
254 #[error("remote repository path contains an empty component")]
256 MissingPathComponent,
257 #[error("remote reference is missing")]
259 MissingReference,
260 #[error("Git remote is missing its URL")]
262 MissingGitUrl,
263 #[error("invalid remote URL: {0}")]
265 InvalidUrl(#[source] url::ParseError),
266 #[error("malformed Bioconductor reference")]
268 MalformedBioconductorReference,
269 #[error("malformed Bioconductor credentials")]
271 MalformedBioconductorCredentials,
272 #[error("malformed Bioconductor source")]
274 MalformedBioconductorSource,
275 #[error("malformed Bioconductor package")]
277 MalformedBioconductorPackage,
278}
279
280#[derive(Debug, Clone, PartialEq, Eq)]
282pub struct PositionedRemoteParseError {
283 error: RemoteParseError,
284 range: TextRange,
285}
286
287impl PositionedRemoteParseError {
288 fn new(error: RemoteParseError, range: TextRange) -> Self {
289 Self { error, range }
290 }
291
292 pub fn error(&self) -> &RemoteParseError {
294 &self.error
295 }
296
297 pub fn range(&self) -> TextRange {
302 self.range
303 }
304}
305
306impl Display for PositionedRemoteParseError {
307 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
308 self.error.fmt(formatter)
309 }
310}
311
312impl std::error::Error for PositionedRemoteParseError {
313 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
314 Some(&self.error)
315 }
316}
317
318#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
320pub enum RemotesError {
321 #[error("Remotes field contains invalid remote specifications")]
323 Invalid(Vec<PositionedRemoteParseError>),
324}
325
326impl RemotesError {
327 pub fn issues(&self) -> &[PositionedRemoteParseError] {
329 match self {
330 Self::Invalid(issues) => issues,
331 }
332 }
333}
334
335#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
337pub enum RemoteMutationError {
338 #[error("remote at index {index} cannot be represented: {source}")]
340 Invalid {
341 index: usize,
343 #[source]
345 source: PositionedRemoteParseError,
346 },
347 #[error("remote at index {index} does not round-trip semantically")]
349 SemanticMismatch {
350 index: usize,
352 },
353}
354
355impl RemoteMutationError {
356 pub fn index(&self) -> usize {
358 match self {
359 Self::Invalid { index, .. } | Self::SemanticMismatch { index } => *index,
360 }
361 }
362
363 pub fn source_error(&self) -> Option<&PositionedRemoteParseError> {
365 match self {
366 Self::Invalid { source, .. } => Some(source),
367 Self::SemanticMismatch { .. } => None,
368 }
369 }
370}
371
372impl FromStr for Remote {
373 type Err = PositionedRemoteParseError;
374
375 fn from_str(input: &str) -> Result<Self, Self::Err> {
376 if TextSize::try_from(input.len()).is_err() {
377 return Err(PositionedRemoteParseError::new(
378 RemoteParseError::InputTooLong,
379 TextRange::empty(TextSize::from(0)),
380 ));
381 }
382 parse_remote(input)
383 }
384}
385
386fn parse_remote(input: &str) -> Result<Remote, PositionedRemoteParseError> {
387 if input.is_empty() {
388 return Err(issue(RemoteParseError::EmptySpecification, 0, 0));
389 }
390 if let Some((offset, character)) = input
391 .char_indices()
392 .find(|(_, character)| character.is_whitespace())
393 {
394 return Err(issue(
395 RemoteParseError::Whitespace,
396 offset,
397 offset + character.len_utf8(),
398 ));
399 }
400 if let Some(offset) = input.find(',') {
401 return Err(issue(
402 RemoteParseError::MultipleSpecifications,
403 offset,
404 offset + 1,
405 ));
406 }
407 if let Some((offset, character)) = input
408 .char_indices()
409 .find(|(_, character)| character.is_control())
410 {
411 return Err(issue(
412 RemoteParseError::ControlCharacter,
413 offset,
414 offset + character.len_utf8(),
415 ));
416 }
417
418 let (package, source_start) = parse_alias(input)?;
419 let source_text = &input[source_start..];
420 if source_text.is_empty() {
421 return Err(issue(
422 RemoteParseError::MissingPayload,
423 source_start,
424 source_start,
425 ));
426 }
427
428 let (kind, host, payload, payload_start) = parse_explicit_source(input, source_start)?;
429 let source = match kind.map(str::to_ascii_lowercase).as_deref() {
430 None if payload.contains('/') => {
431 RemoteSource::GitHub(parse_hosted(payload, payload_start, HostedKind::GitHub)?)
432 }
433 None => RemoteSource::Unspecified(payload.to_string()),
434 Some("cran") => RemoteSource::Cran(CranRemote {
435 package: payload.to_string(),
436 }),
437 Some("github") => {
438 RemoteSource::GitHub(parse_hosted(payload, payload_start, HostedKind::GitHub)?)
439 }
440 Some("gitlab") => {
441 RemoteSource::GitLab(parse_hosted(payload, payload_start, HostedKind::GitLab)?)
442 }
443 Some("bitbucket") => {
444 RemoteSource::Bitbucket(parse_hosted(payload, payload_start, HostedKind::Bitbucket)?)
445 }
446 Some("git") => RemoteSource::Git(parse_generic_git(payload, payload_start)?),
447 Some("url") => RemoteSource::Url(UrlRemote {
448 url: parse_url(payload, payload_start)?,
449 }),
450 Some("local") => RemoteSource::Local(LocalRemote {
451 path: payload.to_string(),
452 }),
453 Some("svn") => RemoteSource::Svn(SvnRemote {
454 url: parse_url(payload, payload_start)?,
455 }),
456 Some("bioc") => RemoteSource::Bioconductor(parse_bioconductor(payload, payload_start)?),
457 Some(_) => RemoteSource::Unknown(UnknownRemote {
458 kind: kind.unwrap_or_default().to_string(),
459 payload: payload.to_string(),
460 }),
461 };
462
463 Ok(Remote {
464 package,
465 host,
466 source,
467 })
468}
469
470fn parse_alias(input: &str) -> Result<(Option<String>, usize), PositionedRemoteParseError> {
471 let Some(equal) = input.find('=') else {
472 return Ok((None, 0));
473 };
474 let first_source_syntax = input
475 .char_indices()
476 .find_map(|(offset, character)| {
477 matches!(character, '/' | ':' | '@' | '#').then_some(offset)
478 })
479 .unwrap_or(input.len());
480 if equal > first_source_syntax {
481 return Ok((None, 0));
482 }
483
484 let candidate = &input[..equal];
485 if !valid_package_alias(candidate) {
486 return Err(issue(RemoteParseError::InvalidAlias, 0, equal));
487 }
488 Ok((Some(candidate.to_string()), equal + 1))
489}
490
491fn valid_package_alias(value: &str) -> bool {
492 let mut chars = value.chars();
493 chars
494 .next()
495 .is_some_and(|character| character.is_ascii_alphabetic())
496 && chars.all(|character| character.is_ascii_alphanumeric() || character == '.')
497}
498
499type ExplicitSource<'a> = (Option<&'a str>, Option<String>, &'a str, usize);
500
501fn parse_explicit_source(
502 input: &str,
503 source_start: usize,
504) -> Result<ExplicitSource<'_>, PositionedRemoteParseError> {
505 let source = &input[source_start..];
506 let Some(relative_separator) = source.find("::") else {
507 return Ok((None, None, source, source_start));
508 };
509 let separator = source_start + relative_separator;
510 let prefix = &input[source_start..separator];
511 let payload_start = separator + 2;
512 let payload = &input[payload_start..];
513 if prefix.is_empty() {
514 return Err(issue(
515 RemoteParseError::MissingKind,
516 source_start,
517 source_start,
518 ));
519 }
520 if payload.is_empty() {
521 return Err(issue(
522 RemoteParseError::MissingPayload,
523 payload_start,
524 payload_start,
525 ));
526 }
527
528 let mut components = prefix.split('@');
529 let kind = components.next().unwrap_or_default();
530 let host = components.next();
531 if components.next().is_some() {
532 return Err(issue(
533 RemoteParseError::MalformedPrefix,
534 source_start,
535 separator,
536 ));
537 }
538 if kind.is_empty() {
539 return Err(issue(
540 RemoteParseError::MissingKind,
541 source_start,
542 source_start,
543 ));
544 }
545 let host = match host {
546 Some("") => {
547 return Err(issue(RemoteParseError::MissingHost, separator, separator));
548 }
549 Some(host) => Some(host.to_string()),
550 None => None,
551 };
552
553 Ok((Some(kind), host, payload, payload_start))
554}
555
556#[derive(Clone, Copy)]
557enum HostedKind {
558 GitHub,
559 GitLab,
560 Bitbucket,
561}
562
563fn parse_hosted(
564 payload: &str,
565 payload_start: usize,
566 kind: HostedKind,
567) -> Result<HostedGitRemote, PositionedRemoteParseError> {
568 let delimiter = payload
569 .char_indices()
570 .find(|(_, character)| matches!(character, '@' | '#'));
571 let (path, reference) = match delimiter {
572 Some((offset, _)) if offset + 1 < payload.len() => {
573 (&payload[..offset], Some(payload[offset + 1..].to_string()))
574 }
575 Some((offset, _)) => {
576 return Err(issue(
577 RemoteParseError::MissingReference,
578 payload_start + offset + 1,
579 payload_start + offset + 1,
580 ));
581 }
582 None => (payload, None),
583 };
584
585 let path = path.trim_end_matches('/');
586 let parts = path.split('/').collect::<Vec<_>>();
587 if parts.len() < 2 {
588 return Err(issue(
589 RemoteParseError::MissingRepository,
590 payload_start,
591 payload_start + path.len(),
592 ));
593 }
594 if let Some((index, _)) = parts.iter().enumerate().find(|(_, part)| part.is_empty()) {
595 let offset = parts[..index]
596 .iter()
597 .map(|part| part.len() + 1)
598 .sum::<usize>();
599 return Err(issue(
600 RemoteParseError::MissingPathComponent,
601 payload_start + offset,
602 payload_start + offset,
603 ));
604 }
605
606 let (repository, subdirectory) = match kind {
607 HostedKind::GitLab => (parts[1..].join("/"), None),
608 HostedKind::GitHub | HostedKind::Bitbucket => (
609 parts[1].to_string(),
610 (parts.len() > 2).then(|| parts[2..].join("/")),
611 ),
612 };
613 Ok(HostedGitRemote {
614 owner: parts[0].to_string(),
615 repository,
616 subdirectory,
617 reference,
618 })
619}
620
621fn parse_generic_git(
622 payload: &str,
623 payload_start: usize,
624) -> Result<GenericGitRemote, PositionedRemoteParseError> {
625 if payload.is_empty() {
626 return Err(issue(
627 RemoteParseError::MissingGitUrl,
628 payload_start,
629 payload_start,
630 ));
631 }
632
633 let path_start = if let Some(scheme) = payload.find("://") {
634 payload[scheme + 3..]
635 .find('/')
636 .map(|offset| scheme + 3 + offset)
637 .unwrap_or(payload.len())
638 } else if let Some(authentication) = payload.find('@') {
639 payload[authentication + 1..]
640 .find(':')
641 .map(|offset| authentication + 1 + offset + 1)
642 .unwrap_or(0)
643 } else {
644 0
645 };
646 let split = payload[path_start..]
647 .find('@')
648 .map(|offset| path_start + offset);
649 if split == Some(0) {
650 return Err(issue(
651 RemoteParseError::MissingGitUrl,
652 payload_start,
653 payload_start,
654 ));
655 }
656 if split == Some(payload.len().saturating_sub(1)) {
657 return Err(issue(
658 RemoteParseError::MissingReference,
659 payload_start + payload.len(),
660 payload_start + payload.len(),
661 ));
662 }
663 let (url, reference) = match split {
664 Some(index) => (
665 payload[..index].to_string(),
666 Some(payload[index + 1..].to_string()),
667 ),
668 None => (payload.to_string(), None),
669 };
670 if url.is_empty() {
671 return Err(issue(
672 RemoteParseError::MissingGitUrl,
673 payload_start,
674 payload_start,
675 ));
676 }
677 Ok(GenericGitRemote { url, reference })
678}
679
680fn parse_url(payload: &str, payload_start: usize) -> Result<Url, PositionedRemoteParseError> {
681 Url::parse(payload).map_err(|source| {
682 issue(
683 RemoteParseError::InvalidUrl(source),
684 payload_start,
685 payload_start + payload.len(),
686 )
687 })
688}
689
690fn parse_bioconductor(
691 payload: &str,
692 payload_start: usize,
693) -> Result<BioconductorRemote, PositionedRemoteParseError> {
694 let (source, reference) = match payload.split_once('#') {
695 Some((source, reference)) if !source.is_empty() && !reference.is_empty() => {
696 (source, Some(reference.to_string()))
697 }
698 Some((source, _)) => {
699 let start = payload_start + source.len();
700 return Err(issue(
701 RemoteParseError::MalformedBioconductorReference,
702 start,
703 payload_start + payload.len(),
704 ));
705 }
706 None => (payload, None),
707 };
708
709 let (credentials, source) = match source.find('@') {
710 Some(at) if source[..at].contains(':') => {
711 let Some((username, password)) = source[..at].split_once(':') else {
712 return Err(issue(
713 RemoteParseError::MalformedBioconductorCredentials,
714 payload_start,
715 payload_start + at,
716 ));
717 };
718 if username.is_empty() || password.is_empty() {
719 return Err(issue(
720 RemoteParseError::MalformedBioconductorCredentials,
721 payload_start,
722 payload_start + at,
723 ));
724 }
725 (
726 Some(BioconductorCredentials {
727 username: username.to_string(),
728 password: password.to_string(),
729 }),
730 &source[at + 1..],
731 )
732 }
733 _ => (None, source),
734 };
735 let source_offset = payload_start + payload.len()
736 - reference.as_ref().map_or(0, |value| value.len() + 1)
737 - source.len();
738
739 let (release, package) = match source.split_once('/') {
740 Some((release, package)) if !release.is_empty() && !package.is_empty() => {
741 (Some(release.to_string()), package)
742 }
743 Some(_) => {
744 return Err(issue(
745 RemoteParseError::MalformedBioconductorSource,
746 source_offset,
747 source_offset + source.len(),
748 ));
749 }
750 None => (None, source),
751 };
752 if package.is_empty() || package.contains('/') {
753 let package_start = source_offset + release.as_ref().map_or(0, |value| value.len() + 1);
754 return Err(issue(
755 RemoteParseError::MalformedBioconductorPackage,
756 package_start,
757 package_start + package.len(),
758 ));
759 }
760
761 Ok(BioconductorRemote {
762 credentials,
763 release,
764 package: package.to_string(),
765 reference,
766 })
767}
768
769impl Display for Remote {
770 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
771 if let Some(package) = &self.package {
772 write!(formatter, "{package}=")?;
773 }
774 match &self.source {
775 RemoteSource::Unspecified(payload) => formatter.write_str(payload),
776 RemoteSource::Cran(remote) => {
777 write_explicit_host(formatter, "cran", self.host.as_deref())?;
778 formatter.write_str(&remote.package)
779 }
780 RemoteSource::GitHub(remote) => {
781 write_explicit_host(formatter, "github", self.host.as_deref())?;
782 write_hosted(formatter, remote)
783 }
784 RemoteSource::GitLab(remote) => {
785 write_explicit_host(formatter, "gitlab", self.host.as_deref())?;
786 write_hosted(formatter, remote)
787 }
788 RemoteSource::Bitbucket(remote) => {
789 write_explicit_host(formatter, "bitbucket", self.host.as_deref())?;
790 write_hosted(formatter, remote)
791 }
792 RemoteSource::Git(remote) => {
793 write_explicit_host(formatter, "git", self.host.as_deref())?;
794 formatter.write_str(&remote.url)?;
795 write_reference(formatter, remote.reference.as_deref(), '@')
796 }
797 RemoteSource::Url(remote) => {
798 write_explicit_host(formatter, "url", self.host.as_deref())?;
799 Display::fmt(&remote.url, formatter)
800 }
801 RemoteSource::Local(remote) => {
802 write_explicit_host(formatter, "local", self.host.as_deref())?;
803 formatter.write_str(&remote.path)
804 }
805 RemoteSource::Svn(remote) => {
806 write_explicit_host(formatter, "svn", self.host.as_deref())?;
807 Display::fmt(&remote.url, formatter)
808 }
809 RemoteSource::Bioconductor(remote) => {
810 write_explicit_host(formatter, "bioc", self.host.as_deref())?;
811 if let Some(credentials) = &remote.credentials {
812 write!(
813 formatter,
814 "{}:{}@",
815 credentials.username, credentials.password
816 )?;
817 }
818 if let Some(release) = &remote.release {
819 write!(formatter, "{release}/")?;
820 }
821 formatter.write_str(&remote.package)?;
822 write_reference(formatter, remote.reference.as_deref(), '#')
823 }
824 RemoteSource::Unknown(remote) => {
825 formatter.write_str(&remote.kind)?;
826 if let Some(host) = &self.host {
827 write!(formatter, "@{host}")?;
828 }
829 write!(formatter, "::{}", remote.payload)
830 }
831 }
832 }
833}
834
835fn write_explicit_host(
836 formatter: &mut Formatter<'_>,
837 kind: &str,
838 host: Option<&str>,
839) -> std::fmt::Result {
840 formatter.write_str(kind)?;
841 if let Some(host) = host {
842 write!(formatter, "@{host}")?;
843 }
844 formatter.write_str("::")
845}
846
847fn write_hosted(formatter: &mut Formatter<'_>, remote: &HostedGitRemote) -> std::fmt::Result {
848 write!(formatter, "{}/{}", remote.owner, remote.repository)?;
849 if let Some(subdirectory) = &remote.subdirectory {
850 write!(formatter, "/{subdirectory}")?;
851 }
852 write_reference(formatter, remote.reference.as_deref(), '@')
853}
854
855fn write_reference(
856 formatter: &mut Formatter<'_>,
857 reference: Option<&str>,
858 delimiter: char,
859) -> std::fmt::Result {
860 if let Some(reference) = reference {
861 write!(formatter, "{delimiter}{reference}")?;
862 }
863 Ok(())
864}
865
866fn parse_remotes(input: &str) -> (Vec<Remote>, Vec<PositionedRemoteParseError>) {
867 if TextSize::try_from(input.len()).is_err() {
868 return (
869 Vec::new(),
870 vec![PositionedRemoteParseError::new(
871 RemoteParseError::InputTooLong,
872 TextRange::empty(TextSize::from(0)),
873 )],
874 );
875 }
876 if input.trim().is_empty() {
877 return (Vec::new(), Vec::new());
878 }
879
880 let mut remotes = Vec::new();
881 let mut issues = Vec::new();
882 let mut start = 0;
883 for end in input
884 .match_indices(',')
885 .map(|(offset, _)| offset)
886 .chain(std::iter::once(input.len()))
887 {
888 let segment = &input[start..end];
889 let trimmed_start = start + (segment.len() - segment.trim_start().len());
890 let trimmed_end = end - (segment.len() - segment.trim_end().len());
891 if trimmed_start == trimmed_end {
892 issues.push(issue(
893 RemoteParseError::EmptySpecification,
894 trimmed_start,
895 trimmed_start,
896 ));
897 } else {
898 match parse_remote(&input[trimmed_start..trimmed_end]) {
899 Ok(remote) => remotes.push(remote),
900 Err(relative) => issues.push(PositionedRemoteParseError::new(
901 relative.error,
902 TextRange::new(
903 TextSize::from(trimmed_start as u32) + relative.range.start(),
904 TextSize::from(trimmed_start as u32) + relative.range.end(),
905 ),
906 )),
907 }
908 }
909 start = end.saturating_add(1);
910 }
911 (remotes, issues)
912}
913
914fn issue(error: RemoteParseError, start: usize, end: usize) -> PositionedRemoteParseError {
915 PositionedRemoteParseError::new(
916 error,
917 TextRange::new(TextSize::from(start as u32), TextSize::from(end as u32)),
918 )
919}
920
921impl RDescription {
922 pub fn remotes(&self) -> Result<std::vec::IntoIter<Remote>, RemotesError> {
929 let tree = self.tree();
930 let mut remotes = Vec::new();
931 let mut issues = Vec::new();
932 for paragraph in tree.paragraphs() {
933 for entry in paragraph.entries() {
934 if !entry
935 .key()
936 .is_some_and(|key| key.eq_ignore_ascii_case("Remotes"))
937 {
938 continue;
939 }
940 let value = entry.value();
941 let (parsed, relative_issues) = parse_remotes(&value);
942 remotes.extend(parsed);
943 issues.extend(relative_issues.into_iter().map(|issue| {
944 PositionedRemoteParseError::new(
945 issue.error,
946 map_entry_value_range(&entry, &value, issue.range),
947 )
948 }));
949 }
950 }
951 if issues.is_empty() {
952 Ok(remotes.into_iter())
953 } else {
954 Err(RemotesError::Invalid(issues))
955 }
956 }
957
958 pub fn set_remotes<I>(&mut self, remotes: I) -> Result<(), RemoteMutationError>
970 where
971 I: IntoIterator<Item = Remote>,
972 {
973 let remotes = remotes.into_iter().collect::<Vec<_>>();
974 let mut rendered = Vec::with_capacity(remotes.len());
975 for (index, remote) in remotes.iter().enumerate() {
976 let value = remote.to_string();
977 let reparsed = value
978 .parse::<Remote>()
979 .map_err(|source| RemoteMutationError::Invalid { index, source })?;
980 if reparsed != *remote {
981 return Err(RemoteMutationError::SemanticMismatch { index });
982 }
983 rendered.push(value);
984 }
985
986 if rendered.is_empty() {
987 self.replace_field_rendered("Remotes", None);
988 return Ok(());
989 }
990 let canonical = if let [remote] = rendered.as_slice() {
991 format!("Remotes: {remote}\n")
992 } else {
993 let mut field = String::from("Remotes:\n");
994 for (index, remote) in rendered.iter().enumerate() {
995 field.push_str(" ");
996 field.push_str(remote);
997 if index + 1 < rendered.len() {
998 field.push(',');
999 }
1000 field.push('\n');
1001 }
1002 field
1003 };
1004 self.replace_field_rendered("Remotes", Some(&canonical));
1005 Ok(())
1006 }
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011 use super::*;
1012
1013 fn parse(input: &str) -> Remote {
1014 input.parse().unwrap()
1015 }
1016
1017 fn slice<'a>(input: &'a str, issue: &PositionedRemoteParseError) -> &'a str {
1018 &input[usize::from(issue.range().start())..usize::from(issue.range().end())]
1019 }
1020
1021 #[test]
1022 fn parses_all_source_variants_and_legacy_semantics() {
1023 let cases = [
1024 "untyped",
1025 "alias=organization/repository/packages/alias@feature/branch",
1026 "github@api.github.example.com::organization/repository#123",
1027 "gitlab::group/subgroup/repository@main",
1028 "bitbucket::organization/repository/package@stable",
1029 "git::ssh://git@git.example.com:7999/team/package.git@v1.2.0",
1030 "url::https://example.com/package.tar.gz",
1031 "local::../package",
1032 "svn::https://svn.example.com/package/trunk",
1033 "bioc::user:password@3.19/SummarizedExperiment#abc123",
1034 "forge@packages.example.com::team/package@edge",
1035 "cran::dplyr",
1036 ];
1037 for case in cases {
1038 let remote = parse(case);
1039 assert_eq!(parse(&remote.to_string()), remote, "{case}");
1040 }
1041 assert!(matches!(
1042 parse("dplyr").source,
1043 RemoteSource::Unspecified(_)
1044 ));
1045 assert!(matches!(
1046 parse("owner/repo").source,
1047 RemoteSource::GitHub(_)
1048 ));
1049 assert!(matches!(parse("CRAN::dplyr").source, RemoteSource::Cran(_)));
1050 }
1051
1052 #[test]
1053 fn hosted_and_generic_git_references_are_opaque() {
1054 let hosted = parse("github::organization/repository#142");
1055 assert_eq!(hosted.to_string(), "github::organization/repository@142");
1056
1057 for (input, expected_url, expected_reference) in [
1058 (
1059 "git::git@git.example.com:team/package.git@main",
1060 "git@git.example.com:team/package.git",
1061 "main",
1062 ),
1063 (
1064 "git::ssh://git@git.example.com/team/package.git@feature@candidate",
1065 "ssh://git@git.example.com/team/package.git",
1066 "feature@candidate",
1067 ),
1068 ] {
1069 let RemoteSource::Git(git) = parse(input).source else {
1070 panic!("expected Git remote");
1071 };
1072 assert_eq!(git.url, expected_url);
1073 assert_eq!(git.reference.as_deref(), Some(expected_reference));
1074 }
1075 }
1076
1077 #[test]
1078 fn custom_hosts_with_ports_and_hosted_trailing_slashes_remain_supported() {
1079 let hosted = parse("github@ghe.example.com:8443::owner/repository/");
1080 assert_eq!(hosted.host.as_deref(), Some("ghe.example.com:8443"));
1081 assert_eq!(
1082 hosted.to_string(),
1083 "github@ghe.example.com:8443::owner/repository"
1084 );
1085 assert_eq!(parse(&hosted.to_string()), hosted);
1086 }
1087
1088 #[test]
1089 fn typed_url_and_svn_payloads_are_urls() {
1090 let RemoteSource::Url(url) = parse("url::HTTPS://EXAMPLE.COM/archive.tar.gz").source else {
1091 panic!("expected URL remote");
1092 };
1093 assert_eq!(url.url.as_str(), "https://example.com/archive.tar.gz");
1094 let RemoteSource::Svn(svn) = parse("svn::https://svn.example.com/trunk").source else {
1095 panic!("expected SVN remote");
1096 };
1097 assert_eq!(svn.url.scheme(), "https");
1098 assert!(matches!(
1099 "url::relative/path".parse::<Remote>().unwrap_err().error(),
1100 RemoteParseError::InvalidUrl(_)
1101 ));
1102 }
1103
1104 #[test]
1105 fn malformed_errors_have_small_relative_ranges() {
1106 for (input, expected, kind) in [
1107 ("bad-alias=owner/repo", "bad-alias", "alias"),
1108 ("github::owner//repo", "", "path"),
1109 ("github::owner/repo@", "", "reference"),
1110 ("git::host/path@", "", "reference"),
1111 ("kind@host@again::payload", "kind@host@again", "prefix"),
1112 ("one/repo two/repo", " ", "whitespace"),
1113 ] {
1114 let error = input.parse::<Remote>().unwrap_err();
1115 assert_eq!(slice(input, &error), expected, "{kind}");
1116 }
1117 }
1118
1119 #[test]
1120 fn collection_collects_every_error_and_returns_no_partial_value() {
1121 let input = "Remotes:\n good/repo,\n bad alias/repo,\n github::owner/repo@,\n ok/repo,\n";
1122 let error = RDescription::parse(input).remotes().unwrap_err();
1123 assert_eq!(error.issues().len(), 3);
1124 assert_eq!(slice(input, &error.issues()[0]), " ");
1125 assert_eq!(slice(input, &error.issues()[1]), "");
1126 assert_eq!(slice(input, &error.issues()[2]), "");
1127 }
1128
1129 #[test]
1130 fn getter_merges_repeated_fields_paragraphs_and_duplicates() {
1131 let description = RDescription::parse(
1132 "Remotes: one/repo, one/repo\n\nremotes:\n gitlab::group/nested/repo,\n cran::dplyr\n",
1133 );
1134 let remotes = description.remotes().unwrap().collect::<Vec<_>>();
1135 assert_eq!(remotes.len(), 4);
1136 assert_eq!(remotes[0], remotes[1]);
1137 let RemoteSource::GitLab(gitlab) = &remotes[2].source else {
1138 panic!("expected GitLab remote");
1139 };
1140 assert_eq!(gitlab.repository, "nested/repo");
1141 }
1142
1143 #[test]
1144 fn entirely_blank_field_is_empty_but_empty_segments_are_errors() {
1145 assert_eq!(
1146 RDescription::parse("Remotes:\n").remotes().unwrap().len(),
1147 0
1148 );
1149 let error = RDescription::parse("Remotes: one/repo,,two/repo,\n")
1150 .remotes()
1151 .unwrap_err();
1152 assert_eq!(error.issues().len(), 2);
1153 assert!(error
1154 .issues()
1155 .iter()
1156 .all(|issue| matches!(issue.error(), RemoteParseError::EmptySpecification)));
1157 }
1158
1159 #[test]
1160 fn fixture_documents_cover_hosted_and_vcs_sources() {
1161 let hosted = RDescription::parse(include_str!("../testdata/remotes-hosted.desc"))
1162 .remotes()
1163 .unwrap()
1164 .collect::<Vec<_>>();
1165 assert_eq!(hosted.len(), 2);
1166 assert!(matches!(hosted[0].source, RemoteSource::GitHub(_)));
1167 assert!(matches!(hosted[1].source, RemoteSource::GitLab(_)));
1168
1169 let vcs = RDescription::parse(include_str!("../testdata/remotes-vcs.desc"))
1170 .remotes()
1171 .unwrap()
1172 .collect::<Vec<_>>();
1173 assert_eq!(vcs.len(), 3);
1174 assert!(matches!(vcs[0].source, RemoteSource::Git(_)));
1175 assert!(matches!(vcs[1].source, RemoteSource::Svn(_)));
1176 assert!(matches!(vcs[2].source, RemoteSource::Bioconductor(_)));
1177 }
1178
1179 #[test]
1180 fn malformed_credentials_are_not_exposed_by_errors() {
1181 let secret = "very-secret-password";
1182 let input = format!("bioc:::{secret}@package");
1183 let error = input.parse::<Remote>().unwrap_err();
1184 assert!(matches!(
1185 error.error(),
1186 RemoteParseError::MalformedBioconductorCredentials
1187 ));
1188 assert!(!error.to_string().contains(secret));
1189 assert!(!format!("{error:?}").contains(secret));
1190 }
1191
1192 #[test]
1193 fn semantic_debug_redacts_embedded_credentials() {
1194 for remote in [
1195 parse("bioc::sensitive-user:very-secret@release/Package"),
1196 parse("url::https://sensitive-user:very-secret@example.com/archive.tar.gz"),
1197 parse("git::https://sensitive-user:very-secret@example.com/repository.git@main"),
1198 parse("git::sensitive-user:very-secret@example.com:team/repository.git@main"),
1199 ] {
1200 let debug = format!("{remote:?}");
1201 assert!(!debug.contains("sensitive-user"));
1202 assert!(!debug.contains("very-secret"));
1203 assert!(debug.contains("REDACTED"));
1204 }
1205 }
1206
1207 #[test]
1208 fn setters_are_canonical_and_coalesce_duplicates() {
1209 let mut description =
1210 RDescription::parse("Package: example\nRemotes: old/repo\n\nremotes: duplicate/repo\n");
1211 let remotes = vec![parse("owner/repo#main"), parse("cran::dplyr")];
1212 description.set_remotes(remotes.clone()).unwrap();
1213 assert_eq!(
1214 description.to_string(),
1215 "Package: example\nRemotes:\n github::owner/repo@main,\n cran::dplyr\n\n"
1216 );
1217 assert_eq!(description.remotes().unwrap().collect::<Vec<_>>(), remotes);
1218 description.set_remotes([]).unwrap();
1219 assert!(!description
1220 .to_string()
1221 .to_ascii_lowercase()
1222 .contains("remotes:"));
1223 }
1224
1225 #[test]
1226 fn setter_rejects_invalid_public_values_transactionally() {
1227 let input = "Remotes: original/repo\n";
1228 let mut description = RDescription::parse(input);
1229 let comma_url = Remote {
1230 package: None,
1231 host: None,
1232 source: RemoteSource::Url(UrlRemote {
1233 url: Url::parse("https://example.com/a,b").unwrap(),
1234 }),
1235 };
1236 let error = description.set_remotes([comma_url]).unwrap_err();
1237 assert_eq!(error.index(), 0);
1238 assert_eq!(description.to_string(), input);
1239
1240 let invalid_combination = Remote {
1241 package: None,
1242 host: Some("ignored.example".to_string()),
1243 source: RemoteSource::Unspecified("package".to_string()),
1244 };
1245 assert!(matches!(
1246 description.set_remotes([invalid_combination]),
1247 Err(RemoteMutationError::SemanticMismatch { index: 0 })
1248 ));
1249 assert_eq!(description.to_string(), input);
1250 }
1251
1252 #[test]
1253 fn setter_reparses_and_preserves_unrelated_diagnostics() {
1254 let mut description = RDescription::parse("Remotes: old/repo\nBroken field\nKeep: exact\n");
1255 let old_range = description.syntax_issues()[0].range;
1256 description
1257 .set_remotes([parse("owner/repository"), parse("cran::dplyr")])
1258 .unwrap();
1259
1260 let rendered = description.to_string();
1261 let new_range = description.syntax_issues()[0].range;
1262 assert_ne!(new_range, old_range);
1263 assert_eq!(
1264 &rendered[usize::from(new_range.start())..usize::from(new_range.end())],
1265 "field"
1266 );
1267 assert!(rendered.contains("Keep: exact\n"));
1268 }
1269
1270 #[test]
1271 fn semantic_values_are_send_and_sync() {
1272 fn assert_send_sync<T: Send + Sync>() {}
1273 assert_send_sync::<Remote>();
1274 assert_send_sync::<RemoteSource>();
1275 assert_send_sync::<PositionedRemoteParseError>();
1276 assert_send_sync::<RemotesError>();
1277 assert_send_sync::<RemoteMutationError>();
1278 }
1279}