1use purrdf_hash::hex;
7use purrdf_iri::IriReadError;
8use purrdf_lex::allocation::{Admission, Memory, StorageError};
9use purrdf_lex::percent;
10
11use super::{BuildError, invalid};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub enum LockedSourceKind {
16 Git,
18 Registry,
20 SparseRegistry,
22 Path,
24 LocalRegistry,
26 Directory,
28}
29
30#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
32pub enum LockedGitReference {
33 DefaultBranch,
35 Branch(String),
37 Tag(String),
39 Revision(String),
41}
42
43#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
48pub struct LockedSource {
49 kind: LockedSourceKind,
50 repository: String,
51 reference: Option<LockedGitReference>,
52 revision: Option<String>,
53}
54
55impl LockedSource {
56 pub(crate) fn retained<S: Admission + ?Sized>(
57 &self,
58 memory: &mut Memory<'_, S>,
59 ) -> Result<Self, StorageError> {
60 let reference = match &self.reference {
61 None => None,
62 Some(LockedGitReference::DefaultBranch) => Some(LockedGitReference::DefaultBranch),
63 Some(LockedGitReference::Branch(text)) => {
64 Some(LockedGitReference::Branch(memory.string(text)?))
65 }
66 Some(LockedGitReference::Tag(text)) => {
67 Some(LockedGitReference::Tag(memory.string(text)?))
68 }
69 Some(LockedGitReference::Revision(text)) => {
70 Some(LockedGitReference::Revision(memory.string(text)?))
71 }
72 };
73 Ok(Self {
74 kind: self.kind,
75 repository: memory.string(&self.repository)?,
76 reference,
77 revision: self
78 .revision
79 .as_ref()
80 .map(|text| memory.string(text))
81 .transpose()?,
82 })
83 }
84 #[must_use]
86 pub const fn kind(&self) -> LockedSourceKind {
87 self.kind
88 }
89
90 #[must_use]
92 pub fn repository(&self) -> &str {
93 &self.repository
94 }
95
96 #[must_use]
98 pub const fn reference(&self) -> Option<&LockedGitReference> {
99 self.reference.as_ref()
100 }
101
102 #[must_use]
104 pub fn revision(&self) -> Option<&str> {
105 self.revision.as_deref()
106 }
107
108 pub(super) fn parse<S: Admission + ?Sized>(
109 text: &str,
110 memory: &mut Memory<'_, S>,
111 ) -> Result<Self, BuildError> {
112 let Some((family, body)) = text.split_once('+') else {
113 return Err(invalid(
114 memory,
115 "source",
116 format_args!("expected a source family followed by '+' and an absolute IRI"),
117 ));
118 };
119 let kind = match family {
120 "git" => LockedSourceKind::Git,
121 "registry" => LockedSourceKind::Registry,
122 "sparse" => LockedSourceKind::SparseRegistry,
123 "path" => LockedSourceKind::Path,
124 "local-registry" => LockedSourceKind::LocalRegistry,
125 "directory" => LockedSourceKind::Directory,
126 _ => {
127 return Err(invalid(
128 memory,
129 "source",
130 format_args!("unsupported source family {family:?}"),
131 ));
132 }
133 };
134 let iri = purrdf_iri::parse_with_memory(body, memory).map_err(|error| match error {
135 IriReadError::Storage(error) => BuildError::Storage(error),
136 IriReadError::Lexical(error) => invalid(
137 memory,
138 "source",
139 format_args!("invalid repository IRI: {error}"),
140 ),
141 })?;
142 if !iri.has_scheme() {
143 return Err(invalid(
144 memory,
145 "source",
146 format_args!("repository IRI must be absolute"),
147 ));
148 }
149 let (repository, reference, revision) = if kind == LockedSourceKind::Git {
150 let suffix = iri.query().map_or(0, |text| text.len() + 1)
151 + iri.fragment().map_or(0, |text| text.len() + 1);
152 let repository = memory.string(&body[..body.len() - suffix])?;
153 let reference = git_reference(iri.query(), memory)?;
154 let revision = iri
155 .fragment()
156 .map(|text| full_revision(text, memory))
157 .transpose()?;
158 (repository, Some(reference), revision)
159 } else {
160 if iri.fragment().is_some() {
161 return Err(invalid(
162 memory,
163 "source",
164 format_args!("a non-Git source cannot select a revision fragment"),
165 ));
166 }
167 (memory.string(body)?, None, None)
168 };
169 memory.release_string(iri.into_text())?;
170 Ok(Self {
171 kind,
172 repository,
173 reference,
174 revision,
175 })
176 }
177
178 pub(super) fn release<S: Admission + ?Sized>(
179 self,
180 memory: &mut Memory<'_, S>,
181 ) -> Result<(), BuildError> {
182 memory.release_string(self.repository)?;
183 if let Some(
184 LockedGitReference::Branch(text)
185 | LockedGitReference::Tag(text)
186 | LockedGitReference::Revision(text),
187 ) = self.reference
188 {
189 memory.release_string(text)?;
190 }
191 if let Some(revision) = self.revision {
192 memory.release_string(revision)?;
193 }
194 Ok(())
195 }
196}
197
198fn git_reference<S: Admission + ?Sized>(
199 query: Option<&str>,
200 memory: &mut Memory<'_, S>,
201) -> Result<LockedGitReference, BuildError> {
202 let Some(query) = query else {
203 return Ok(LockedGitReference::DefaultBranch);
204 };
205 let Some((key, value)) = query.split_once('=') else {
206 return Err(invalid(
207 memory,
208 "source",
209 format_args!("Git selector must name branch, tag or rev"),
210 ));
211 };
212 if query.contains('&') || !matches!(key, "branch" | "ref" | "tag" | "rev") {
213 return Err(invalid(
214 memory,
215 "source",
216 format_args!("exactly one supported Git selector is required"),
217 ));
218 }
219 let decoded = percent::decode_form(value).map_err(|error| {
220 invalid(
221 memory,
222 "source",
223 format_args!("invalid Git selector: {error}"),
224 )
225 })?;
226 if decoded.is_empty() {
227 return Err(invalid(
228 memory,
229 "source",
230 format_args!("Git selector cannot be empty"),
231 ));
232 }
233 let value = memory.string(&decoded)?;
234 Ok(match key {
235 "branch" | "ref" => LockedGitReference::Branch(value),
236 "tag" => LockedGitReference::Tag(value),
237 "rev" => LockedGitReference::Revision(value),
238 _ => unreachable!("the selector was checked before allocation"),
239 })
240}
241
242fn full_revision<S: Admission + ?Sized>(
243 text: &str,
244 memory: &mut Memory<'_, S>,
245) -> Result<String, BuildError> {
246 if !matches!(text.len(), 40 | 64) {
247 return Err(invalid(
248 memory,
249 "source",
250 format_args!("Git precision must be a full 40- or 64-digit revision"),
251 ));
252 }
253 let mut bytes = [0; 32];
254 let length = hex::decode_to_slice(text, &mut bytes).map_err(|error| {
255 invalid(
256 memory,
257 "source",
258 format_args!("invalid full Git revision: {error}"),
259 )
260 })?;
261 Ok(memory.format(&format_args!("{}", hex::Lower(&bytes[..length])))?)
262}