-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathlib.rs
66 lines (56 loc) · 1.85 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//! Core library of `cargo-component`.
#![deny(missing_docs)]
use std::path::PathBuf;
use std::str::FromStr;
use anyhow::Context;
use semver::VersionReq;
use wasm_pkg_client::PackageRef;
pub mod command;
pub mod lock;
pub mod progress;
pub mod registry;
pub mod terminal;
/// The root directory name used for default cargo component directories
pub const CARGO_COMPONENT_DIR: &str = "cargo-component";
/// The cache directory name used by default
pub const CACHE_DIR: &str = "cache";
/// Returns the path to the default cache directory, returning an error if a cache directory cannot be found.
pub fn default_cache_dir() -> anyhow::Result<PathBuf> {
dirs::cache_dir()
.map(|p| p.join(CARGO_COMPONENT_DIR).join(CACHE_DIR))
.ok_or_else(|| anyhow::anyhow!("failed to find cache directory"))
}
/// A helper that fetches the default directory if the given directory is `None`.
pub fn cache_dir(dir: Option<PathBuf>) -> anyhow::Result<PathBuf> {
match dir {
Some(dir) => Ok(dir),
None => default_cache_dir(),
}
}
/// Represents a versioned component package name.
#[derive(Clone)]
pub struct VersionedPackageName {
/// The package name.
pub name: PackageRef,
/// The optional package version.
pub version: Option<VersionReq>,
}
impl FromStr for VersionedPackageName {
type Err = anyhow::Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s.split_once('@') {
Some((name, version)) => Ok(Self {
name: name.parse()?,
version: Some(
version
.parse()
.with_context(|| format!("invalid package version `{version}`"))?,
),
}),
None => Ok(Self {
name: s.parse()?,
version: None,
}),
}
}
}