Skip to content

Commit

Permalink
Improvements & tests
Browse files Browse the repository at this point in the history
  • Loading branch information
boozook committed May 9, 2024
1 parent 3d6f831 commit 321ac6c
Show file tree
Hide file tree
Showing 27 changed files with 370 additions and 207 deletions.
298 changes: 182 additions & 116 deletions Cargo.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions cargo/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "cargo-playdate"
version = "0.4.11"
version = "0.4.12"
readme = "README.md"
description = "Build tool for neat yellow console."
keywords = ["playdate", "build", "cargo", "plugin", "cargo-subcommand"]
Expand Down Expand Up @@ -31,8 +31,8 @@ clap_lex = "0.7"
dirs.workspace = true
fs_extra.workspace = true

cargo = "0.78.1"
cargo-util = "0.2.10"
cargo = "0.78"
cargo-util = "0.2.11"
cargo-platform = "0.1.8"
cargo-util-schemas = "0.2.0"

Expand Down
4 changes: 2 additions & 2 deletions cargo/src/assets/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ pub fn build<'cfg>(config: &'cfg Config) -> CargoResult<AssetsArtifacts<'cfg>> {

config.log().error(message);
} else {
targets.insert(target.to_owned(), (package.package_id(), target_kind));
targets.insert(target, (package.package_id(), target_kind));
}
}
};
Expand Down Expand Up @@ -224,7 +224,7 @@ pub fn build<'cfg>(config: &'cfg Config) -> CargoResult<AssetsArtifacts<'cfg>> {
log.status("", dest);
let src = format!("root {}", dep_root.as_relative_to_root(config).display());
log.status("", src);
if dep_root != &plan.path {
if dep_root != plan.path {
let path = plan.plan.crate_root();
let src = format!("root (plan) {}", path.as_relative_to_root(config).display());
log.status("", src);
Expand Down
2 changes: 1 addition & 1 deletion cargo/src/assets/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl<'a, 'cfg> LazyEnvBuilder<'a, 'cfg> {
("CARGO_MANIFEST_DIR", root.to_string()),
];

let mut env = Env::from_iter(vars.into_iter()).map_err(|err| anyhow::anyhow!("{err}"))?;
let mut env = Env::try_from_iter(vars.into_iter()).map_err(|err| anyhow::anyhow!("{err}"))?;

// add global environment:
for (k, v) in std::env::vars() {
Expand Down
2 changes: 1 addition & 1 deletion cargo/src/init/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ fn add_dependencies<'cfg>(config: &'cfg Config<'_>,

let others = config.create_deps.iter().filter_map(|d| {
if let Name::Other(dep) = &d.name {
Some(dep.to_owned())
Some(dep.clone())
} else {
None
}
Expand Down
2 changes: 1 addition & 1 deletion cargo/src/package/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ fn build_manifest<Layout: playdate::layout::Layout>(config: &Config,
Manifest::try_from_source(ManifestSource { package,
metadata: metadata.as_ref() })
}.map_err(|err| anyhow!(err))?;
std::fs::write(layout.manifest(), manifest.to_string())?;
std::fs::write(layout.manifest(), manifest.to_manifest_string())?;
Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion support/bindgen-cfg/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "playdate-bindgen-cfg"
version = "0.1.5"
version = "0.1.6"
readme = "README.md"
description = "Minimal configuration for playdate-bindgen."
keywords = ["playdate", "bindings", "ffi", "code-generation"]
Expand Down
22 changes: 16 additions & 6 deletions support/bindgen-cfg/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ impl Derive {
}

pub fn to_cli_args(&self) -> Vec<String> {
let words = self.to_string();
let words = self.to_feature_list();
if words.is_empty() {
vec!["--derive=".to_string()]
} else {
Expand Down Expand Up @@ -236,9 +236,9 @@ impl FromStr for Derive {
}
}

impl ToString for Derive {
impl Derive {
#[rustfmt::skip]
fn to_string(&self) -> String {
fn to_feature_list(&self) -> String {
let mut out = Vec::new();
if self.default { out.push("default") }
if self.eq {out.push("eq")}
Expand All @@ -253,6 +253,11 @@ impl ToString for Derive {
}
}

impl std::fmt::Display for Derive {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.to_feature_list().fmt(f) }
}

impl Default for Derive {
fn default() -> Self {
Self { debug: true,
Expand All @@ -277,7 +282,7 @@ impl Features {
pub const fn empty() -> Self { Self { documentation: false } }

pub fn to_cli_args(&self) -> Vec<String> {
let words = self.to_string();
let words = self.to_feature_list();
if words.is_empty() {
vec!["--features=".to_string()]
} else {
Expand Down Expand Up @@ -308,15 +313,20 @@ impl FromStr for Features {
}
}

impl ToString for Features {
impl Features {
#[rustfmt::skip]
fn to_string(&self) -> String {
fn to_feature_list(&self) -> String {
let mut out = Vec::new();
if self.documentation { out.push("documentation") }
out.join(",")
}
}

impl std::fmt::Display for Features {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.to_feature_list().fmt(f) }
}

impl Default for Features {
fn default() -> Self { Self { documentation: true } }
}
Expand Down
2 changes: 1 addition & 1 deletion support/build/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "playdate-build"
version = "0.2.8"
version = "0.2.9"
readme = "README.md"
description = "Utils that help to build package for Playdate"
keywords = ["playdate", "package", "encoding", "manifest", "assets"]
Expand Down
6 changes: 3 additions & 3 deletions support/build/src/assets/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,16 +125,16 @@ pub fn apply_build_plan<'l, 'r, P: AsRef<Path>>(plan: BuildPlan<'l, 'r>,
for entry in plan.drain(..) {
let current: Vec<_> = match &entry {
Mapping::AsIs(inc, ..) => {
let source = abs_or_rel_crate_any(inc.source(), crate_root);
let source = abs_if_existing_any(inc.source(), crate_root);
vec![method(&source, &inc.target(), false)]
},
Mapping::Into(inc, ..) => {
let source = abs_or_rel_crate_any(inc.source(), crate_root);
let source = abs_if_existing_any(inc.source(), crate_root);
vec![method(&source, &inc.target(), true)]
},
Mapping::ManyInto { sources, target, .. } => {
sources.iter()
.map(|inc| (abs_or_rel_crate_any(inc.source(), crate_root), target.join(inc.target())))
.map(|inc| (abs_if_existing_any(inc.source(), crate_root), target.join(inc.target())))
.map(|(ref source, ref target)| method(source, target, false))
.collect()
},
Expand Down
19 changes: 10 additions & 9 deletions support/build/src/assets/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub fn build_plan<'l, 'r, 'c: 'l, V>(env: &'c Env,
if trailing_sep && !s.ends_with(PATH_SEPARATOR) {
s.push(MAIN_SEPARATOR);
}
unixish_path_pattern(&s).into_owned()
sanitize_path_pattern(&s).into_owned()
} else {
s.to_owned()
}
Expand Down Expand Up @@ -97,7 +97,7 @@ pub fn build_plan<'l, 'r, 'c: 'l, V>(env: &'c Env,
let key = PathBuf::from(k.as_str());
let value = Cow::Borrowed(v.as_str());
let into_dir = k.as_str().ends_with(PATH_SEPARATOR);
let source_exists = abs_or_rel_crate_existing(Path::new(value.as_ref()), crate_root)?.is_some();
let source_exists = abs_if_existing(Path::new(value.as_ref()), crate_root)?.is_some();

let mapping = match (source_exists, into_dir) {
(true, true) => Mapping::Into(Match::new(value.as_ref(), key), (k, v)),
Expand Down Expand Up @@ -200,10 +200,11 @@ pub fn build_plan<'l, 'r, 'c: 'l, V>(env: &'c Env,
}


// TODO: tests for `abs_or_rel_crate_existing`
/// Make path relative to `crate_root` if it isn't absolute, checking existence.
/// Returns `None` if path doesn't exist.
pub fn abs_or_rel_crate_existing<'t, P1, P2>(path: P1, root: P2) -> std::io::Result<Option<Cow<'t, Path>>>
///
/// Input `path` must be absolute or relative to the `root`.
pub fn abs_if_existing<'t, P1, P2>(path: P1, root: P2) -> std::io::Result<Option<Cow<'t, Path>>>
where P1: 't + AsRef<Path> + Into<Cow<'t, Path>>,
P2: AsRef<Path> {
let p = if path.as_ref().is_absolute() && path.as_ref().try_exists()? {
Expand All @@ -221,12 +222,12 @@ pub fn abs_or_rel_crate_existing<'t, P1, P2>(path: P1, root: P2) -> std::io::Res

/// Same as [`abs_or_rel_crate_existing`], but returns given `path` as fallback.
#[inline]
pub fn abs_or_rel_crate_any<'t, P1, P2>(path: P1, root: P2) -> Cow<'t, Path>
pub fn abs_if_existing_any<'t, P1, P2>(path: P1, root: P2) -> Cow<'t, Path>
where P1: 't + AsRef<Path> + Into<Cow<'t, Path>> + Clone,
P2: AsRef<Path> {
abs_or_rel_crate_existing(path.clone(), root).ok()
.flatten()
.unwrap_or(path.into())
abs_if_existing(path.clone(), root).ok()
.flatten()
.unwrap_or(path.into())
}


Expand Down Expand Up @@ -342,7 +343,7 @@ impl BuildPlan<'_, '_> {
&self)
-> impl Iterator<Item = (MappingKind, PathBuf, (PathBuf, Option<std::time::SystemTime>))> + '_ {
let pair = |inc: &Match| {
(inc.target().to_path_buf(), abs_or_rel_crate_any(inc.source(), self.crate_root).to_path_buf())
(inc.target().to_path_buf(), abs_if_existing_any(inc.source(), self.crate_root).to_path_buf())
};

self.as_inner()
Expand Down
14 changes: 9 additions & 5 deletions support/build/src/assets/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub fn resolve_includes<S: AsRef<str>, Excl: AsRef<str>>(expr: S,
exclude: &[Excl],
links: LinkBehavior)
-> Result<Vec<Match>, Error> {
let expr = unixish_path_pattern(expr.as_ref());
let expr = sanitize_path_pattern(expr.as_ref());

// let crate_root = crate_root.to_string_lossy();
// #[cfg(windows)]
Expand Down Expand Up @@ -86,6 +86,9 @@ pub fn resolve_includes<S: AsRef<str>, Excl: AsRef<str>>(expr: S,
}


// TODO: Tests for `sanitize_path_pattern`
/// Adapt path to wax walker, so kind of "patternize" or "unixish".
///
/// On Windows makes given absolute path to look like POSIX or UNC:
/// `C:/foo/bar/**` or `//./C:/foo/bar/**`.
///
Expand All @@ -94,7 +97,8 @@ pub fn resolve_includes<S: AsRef<str>, Excl: AsRef<str>>(expr: S,
/// - if pattern starts with `<driveletter>:`, escape it as `<driveletter>\`:
///
/// On unix does nothing.
pub fn unixish_path_pattern(path: &str) -> Cow<'_, str> {
pub fn sanitize_path_pattern(path: &str) -> Cow<'_, str> {
// TODO: Before patternize use normalize/canonicalize, crates: dunce, normpath, or path-slash
if cfg!(windows) {
path.replace('\\', "/")
.replace(':', "\\:")
Expand Down Expand Up @@ -167,7 +171,7 @@ impl EnvResolver {
pub fn expr<'a, 'e, 'c: 'e, Ex: AsMut<Expr<'e>>>(&self, mut expr: Ex, env: &'c Env) -> Ex {
let editable = expr.as_mut();
let replaced = self.str(editable.actual(), env);
if &replaced != editable.actual() {
if replaced != editable.actual() {
editable.set(replaced);
}
expr
Expand Down Expand Up @@ -509,7 +513,7 @@ mod tests {
let resolver = EnvResolver::new();

let env = {
let mut env = Env::default().unwrap();
let mut env = Env::try_default().unwrap();
env.vars.insert("FOO".into(), "foo".into());
env.vars.insert("BAR".into(), "bar".into());
env
Expand All @@ -534,7 +538,7 @@ mod tests {
#[should_panic]
fn resolver_missed() {
let resolver = EnvResolver::new();
let env = Env::default().unwrap();
let env = Env::try_default().unwrap();
let expr = Expr::from("${MISSED}/file.txt");
resolver.expr(expr, &env);
}
Expand Down
Loading

0 comments on commit 321ac6c

Please sign in to comment.