1use std::fmt::{self, Display, Formatter};
2use std::path::PathBuf;
3
4use serde::Deserialize;
5use toml_edit::{Array, Item, Table, Value, value};
6
7use uv_configuration::ExcludeDependency;
8use uv_distribution_types::{NameRequirementSpecification, Requirement};
9use uv_fs::{PortablePath, Simplified};
10use uv_macros::DeserializeUntagged;
11use uv_pypi_types::VerbatimParsedUrl;
12use uv_python_types::PythonRequest;
13use uv_settings::{ToolOptions, ToolOptionsWire};
14
15#[derive(Debug, Clone, Deserialize)]
17#[serde(try_from = "ToolWire", into = "ToolWire")]
18pub struct Tool {
19 requirements: Vec<Requirement>,
24 constraints: Vec<Requirement>,
26 overrides: Vec<Requirement>,
28 excludes: Vec<ExcludeDependency>,
30 build_constraints: Vec<NameRequirementSpecification>,
32 python: Option<PythonRequest>,
34 entrypoints: Vec<ToolEntrypoint>,
36 options: ToolOptions,
38}
39
40#[derive(Debug, Clone, Deserialize)]
41#[serde(rename_all = "kebab-case")]
42struct ToolWire {
43 #[serde(default)]
44 requirements: Vec<RequirementWire>,
45 #[serde(default)]
46 constraints: Vec<Requirement>,
47 #[serde(default)]
48 overrides: Vec<Requirement>,
49 #[serde(default)]
50 excludes: Vec<ExcludeDependency>,
51 #[serde(default)]
52 build_constraint_dependencies: Vec<NameRequirementSpecification>,
53 python: Option<PythonRequest>,
54 entrypoints: Vec<ToolEntrypoint>,
55 #[serde(default)]
56 options: ToolOptionsWire,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, DeserializeUntagged)]
60enum RequirementWire {
61 #[untagged(map)]
63 Requirement(Requirement),
64 #[untagged(string)]
67 Deprecated(uv_pep508::Requirement<VerbatimParsedUrl>),
68}
69
70impl From<Tool> for ToolWire {
71 fn from(tool: Tool) -> Self {
72 Self {
73 requirements: tool
74 .requirements
75 .into_iter()
76 .map(RequirementWire::Requirement)
77 .collect(),
78 constraints: tool.constraints,
79 overrides: tool.overrides,
80 excludes: tool.excludes,
81 build_constraint_dependencies: tool.build_constraints,
82 python: tool.python,
83 entrypoints: tool.entrypoints,
84 options: tool.options.into(),
85 }
86 }
87}
88
89impl TryFrom<ToolWire> for Tool {
90 type Error = serde::de::value::Error;
91
92 fn try_from(tool: ToolWire) -> Result<Self, Self::Error> {
93 Ok(Self {
94 requirements: tool
95 .requirements
96 .into_iter()
97 .map(|req| match req {
98 RequirementWire::Requirement(requirements) => requirements,
99 RequirementWire::Deprecated(requirement) => Requirement::from(requirement),
100 })
101 .collect(),
102 constraints: tool.constraints,
103 overrides: tool.overrides,
104 excludes: tool.excludes,
105 build_constraints: tool.build_constraint_dependencies,
106 python: tool.python,
107 entrypoints: tool.entrypoints,
108 options: tool.options.into(),
109 })
110 }
111}
112
113#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Deserialize)]
114#[serde(rename_all = "kebab-case")]
115pub struct ToolEntrypoint {
116 pub name: String,
117 pub install_path: PathBuf,
118 pub from: Option<String>,
119}
120
121impl Display for ToolEntrypoint {
122 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
123 cfg_select! {
124 windows => {
125 write!(
126 f,
127 "{} ({})",
128 self.name,
129 self.install_path
130 .simplified_display()
131 .to_string()
132 .replace('/', "\\")
133 )
134 },
135 unix => {
136 write!(
137 f,
138 "{} ({})",
139 self.name,
140 self.install_path.simplified_display()
141 )
142 },
143 }
144 }
145}
146
147fn each_element_on_its_line_array(elements: impl Iterator<Item = impl Into<Value>>) -> Array {
158 let mut array = elements
159 .map(Into::into)
160 .map(|mut value| {
161 value.decor_mut().set_prefix("\n ");
163 value
164 })
165 .collect::<Array>();
166 array.set_trailing_comma(true);
169 array.set_trailing("\n");
171 array
172}
173
174impl Tool {
175 pub fn new(
177 requirements: Vec<Requirement>,
178 constraints: Vec<Requirement>,
179 overrides: Vec<Requirement>,
180 excludes: Vec<ExcludeDependency>,
181 build_constraints: Vec<NameRequirementSpecification>,
182 python: Option<PythonRequest>,
183 entrypoints: impl IntoIterator<Item = ToolEntrypoint>,
184 options: ToolOptions,
185 ) -> Self {
186 let mut entrypoints: Vec<_> = entrypoints.into_iter().collect();
187 entrypoints.sort();
188 Self {
189 requirements,
190 constraints,
191 overrides,
192 excludes,
193 build_constraints,
194 python,
195 entrypoints,
196 options,
197 }
198 }
199
200 #[must_use]
202 pub fn with_options(self, options: ToolOptions) -> Self {
203 Self { options, ..self }
204 }
205
206 pub(crate) fn to_toml(&self) -> Result<Table, toml_edit::ser::Error> {
208 let mut table = Table::new();
209
210 if !self.requirements.is_empty() {
211 table.insert("requirements", {
212 let requirements = self
213 .requirements
214 .iter()
215 .map(|requirement| {
216 serde::Serialize::serialize(
217 &requirement,
218 toml_edit::ser::ValueSerializer::new(),
219 )
220 })
221 .collect::<Result<Vec<_>, _>>()?;
222
223 let requirements = match requirements.as_slice() {
224 [] => Array::new(),
225 [requirement] => Array::from_iter([requirement]),
226 requirements => each_element_on_its_line_array(requirements.iter()),
227 };
228 value(requirements)
229 });
230 }
231
232 if !self.constraints.is_empty() {
233 table.insert("constraints", {
234 let constraints = self
235 .constraints
236 .iter()
237 .map(|constraint| {
238 serde::Serialize::serialize(
239 &constraint,
240 toml_edit::ser::ValueSerializer::new(),
241 )
242 })
243 .collect::<Result<Vec<_>, _>>()?;
244
245 let constraints = match constraints.as_slice() {
246 [] => Array::new(),
247 [constraint] => Array::from_iter([constraint]),
248 constraints => each_element_on_its_line_array(constraints.iter()),
249 };
250 value(constraints)
251 });
252 }
253
254 if !self.overrides.is_empty() {
255 table.insert("overrides", {
256 let overrides = self
257 .overrides
258 .iter()
259 .map(|r#override| {
260 serde::Serialize::serialize(
261 &r#override,
262 toml_edit::ser::ValueSerializer::new(),
263 )
264 })
265 .collect::<Result<Vec<_>, _>>()?;
266
267 let overrides = match overrides.as_slice() {
268 [] => Array::new(),
269 [r#override] => Array::from_iter([r#override]),
270 overrides => each_element_on_its_line_array(overrides.iter()),
271 };
272 value(overrides)
273 });
274 }
275
276 if !self.excludes.is_empty() {
277 table.insert("excludes", {
278 let excludes = self
279 .excludes
280 .iter()
281 .map(|r#exclude| {
282 serde::Serialize::serialize(
283 &r#exclude,
284 toml_edit::ser::ValueSerializer::new(),
285 )
286 })
287 .collect::<Result<Vec<_>, _>>()?;
288
289 let excludes = match excludes.as_slice() {
290 [] => Array::new(),
291 [r#exclude] => Array::from_iter([r#exclude]),
292 excludes => each_element_on_its_line_array(excludes.iter()),
293 };
294 value(excludes)
295 });
296 }
297
298 if !self.build_constraints.is_empty() {
299 table.insert("build-constraint-dependencies", {
300 let build_constraints = self
301 .build_constraints
302 .iter()
303 .map(|r#build_constraint| {
304 serde::Serialize::serialize(
305 &r#build_constraint,
306 toml_edit::ser::ValueSerializer::new(),
307 )
308 })
309 .collect::<Result<Vec<_>, _>>()?;
310
311 let build_constraints = match build_constraints.as_slice() {
312 [] => Array::new(),
313 [r#build_constraint] => Array::from_iter([r#build_constraint]),
314 build_constraints => each_element_on_its_line_array(build_constraints.iter()),
315 };
316 value(build_constraints)
317 });
318 }
319
320 if let Some(ref python) = self.python {
321 table.insert(
322 "python",
323 value(serde::Serialize::serialize(
324 &python,
325 toml_edit::ser::ValueSerializer::new(),
326 )?),
327 );
328 }
329
330 table.insert("entrypoints", {
331 let entrypoints = each_element_on_its_line_array(
332 self.entrypoints
333 .iter()
334 .map(ToolEntrypoint::to_toml)
335 .map(Table::into_inline_table),
336 );
337 value(entrypoints)
338 });
339
340 if self.options != ToolOptions::default() {
341 let serialized = serde::Serialize::serialize(
342 &ToolOptionsWire::from(self.options.clone()),
343 toml_edit::ser::ValueSerializer::new(),
344 )?;
345 let Value::InlineTable(serialized) = serialized else {
346 return Err(toml_edit::ser::Error::Custom(
347 "Expected an inline table".to_string(),
348 ));
349 };
350 table.insert("options", Item::Table(serialized.into_table()));
351 }
352
353 Ok(table)
354 }
355
356 pub fn entrypoints(&self) -> &[ToolEntrypoint] {
357 &self.entrypoints
358 }
359
360 pub fn requirements(&self) -> &[Requirement] {
361 &self.requirements
362 }
363
364 pub fn constraints(&self) -> &[Requirement] {
365 &self.constraints
366 }
367
368 pub fn overrides(&self) -> &[Requirement] {
369 &self.overrides
370 }
371
372 pub fn excludes(&self) -> &[ExcludeDependency] {
373 &self.excludes
374 }
375
376 pub fn build_constraints(&self) -> &[NameRequirementSpecification] {
377 &self.build_constraints
378 }
379
380 pub fn python(&self) -> &Option<PythonRequest> {
381 &self.python
382 }
383
384 pub fn options(&self) -> &ToolOptions {
385 &self.options
386 }
387}
388
389impl ToolEntrypoint {
390 pub fn new(name: &str, install_path: PathBuf, from: String) -> Self {
392 let name = name
393 .trim_end_matches(std::env::consts::EXE_SUFFIX)
394 .to_string();
395 Self {
396 name,
397 install_path,
398 from: Some(from),
399 }
400 }
401
402 fn to_toml(&self) -> Table {
404 let mut table = Table::new();
405 table.insert("name", value(&self.name));
406 table.insert(
407 "install-path",
408 value(PortablePath::from(&self.install_path).to_string()),
410 );
411 if let Some(from) = &self.from {
412 table.insert("from", value(from));
413 }
414 table
415 }
416}