Skip to content

Commit

Permalink
chore(all): Move utilities to stdx sub-crate
Browse files Browse the repository at this point in the history
This adds a new sub crate called `stdx`, which contains the items previously
contained in `lib::util`, as well as some additional helpers.
  • Loading branch information
tingerrr committed Aug 9, 2024
1 parent f89bb66 commit 62a6805
Show file tree
Hide file tree
Showing 19 changed files with 918 additions and 225 deletions.
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ readme = "README.md"
[workspace.dependencies]
typst-project = { git = "https://github.com/tingerrr/typst-project", rev = "a71db5451ebdca2174adc0a323c71ba5ab2f8120" }

typst-test-lib = { path = "crates/typst-test-lib" }
typst-test-stdx = { path = "crates/typst-test-stdx" }

anyhow = "1.0.78"
clap = "4.4.12"
bitflags = "2.4.2"
Expand Down
3 changes: 2 additions & 1 deletion crates/typst-test-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ path = "src/main.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
typst-test-lib = { path = "../typst-test-lib" }
typst-test-lib.workspace = true
typst-test-stdx.workspace = true

anyhow = { workspace = true, features = ["backtrace"] }
bitflags.workspace = true
Expand Down
5 changes: 3 additions & 2 deletions crates/typst-test-cli/src/cli/uninit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use std::io;

use serde::Serialize;
use termcolor::{Color, WriteColor};
use typst_test_lib::{test_set, util};
use typst_test_lib::test_set;
use typst_test_stdx::fmt::Term;

use super::Context;
use crate::report::reports::ProjectJson;
Expand All @@ -28,7 +29,7 @@ impl Report for InitReport<'_> {
writer,
", removed {} {}",
count,
util::fmt::plural(count, "test"),
Term::simple("test").with(count),
)?;

Ok(())
Expand Down
12 changes: 5 additions & 7 deletions crates/typst-test-cli/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use typst_test_lib::store::Document;
use typst_test_lib::test::id::Identifier;
use typst_test_lib::test::ReferenceKind;
use typst_test_lib::test_set::TestSet;
use typst_test_lib::util;
use typst_test_stdx::result::ResultEx;

use crate::cli;

Expand Down Expand Up @@ -182,7 +182,7 @@ impl Project {
let _span = tracing::debug_span!("initalizing project", root = ?tests_root_dir);

tracing::debug!(path = ?tests_root_dir, "creating tests root");
util::fs::create_dir(tests_root_dir, false)?;
typst_test_stdx::fs::create_dir(tests_root_dir, false)?;

if vcs == cli::init::Vcs::Git {
tracing::debug!("writing vcs config");
Expand All @@ -208,7 +208,7 @@ impl Project {
let _span = tracing::debug_span!("initalizing project", root = ?tests_root_dir);

tracing::trace!(path = ?tests_root_dir, "removing");
util::fs::remove_dir(tests_root_dir, true)?;
typst_test_stdx::fs::remove_dir(tests_root_dir, true)?;
Ok(())
}

Expand Down Expand Up @@ -303,10 +303,8 @@ impl Project {
pub fn write_config(&self) -> anyhow::Result<()> {
let path = self.root().join(typst_project::heuristics::MANIFEST_FILE);

let content =
typst_test_lib::util::result::ignore_default(std::fs::read_to_string(&path), |err| {
err.kind() == io::ErrorKind::NotFound
})?;
let content = std::fs::read_to_string(&path)
.ignore_default(|err| err.kind() == io::ErrorKind::NotFound)?;

let mut doc = DocumentMut::from_str(&content)?;
self.config.write_into(&mut doc)?;
Expand Down
15 changes: 8 additions & 7 deletions crates/typst-test-cli/src/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ use termcolor::{Color, WriteColor};
use typst::diag::{Severity, SourceDiagnostic};
use typst::syntax::{FileId, Source, Span};
use typst::WorldExt;
use typst_test_lib::compare;
use typst_test_lib::store::test::Test;
use typst_test_lib::test::id::Identifier;
use typst_test_lib::test::ReferenceKind;
use typst_test_lib::{compare, util};
use typst_test_stdx::fmt::Term;

use crate::project::Project;
use crate::test::runner::{Event, EventPayload, Summary};
Expand Down Expand Up @@ -273,12 +274,12 @@ pub mod reports {
let secs = self.time.seconds;
match (secs / 60, secs) {
(0, 0) => writeln!(w),
(0, s) => writeln!(w, " took {s} {}", util::fmt::plural(s as usize, "second")),
(0, s) => writeln!(w, " took {s} {}", Term::simple("second").with(s as usize),),
(m, s) => writeln!(
w,
" took {m} {} {s} {}",
util::fmt::plural(m as usize, "minute"),
util::fmt::plural(s as usize, "second")
Term::simple("minute").with(m as usize),
Term::simple("second").with(s as usize)
),
}
}
Expand Down Expand Up @@ -347,8 +348,8 @@ fn test_failure<W: WriteColor + ?Sized>(
writeln!(
w,
"Expected {reference} {}, got {output} {}",
util::fmt::plural(reference, "page"),
util::fmt::plural(output, "page"),
Term::simple("page").with(reference),
Term::simple("page").with(output),
)?;
}

Expand All @@ -366,7 +367,7 @@ fn test_failure<W: WriteColor + ?Sized>(
writeln!(
w,
"Page {p} had {deviations} {}",
util::fmt::plural(deviations, "deviation",)
Term::simple("deviation").with(deviations),
)?;
}
}
Expand Down
2 changes: 2 additions & 0 deletions crates/typst-test-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ readme.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
typst-test-stdx.workspace = true

bitflags.workspace = true
bytemuck.workspace = true
comemo.workspace = true
Expand Down
8 changes: 3 additions & 5 deletions crates/typst-test-lib/src/_dev/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ use std::path::{Path, PathBuf};

use tempdir::TempDir;

use crate::util;

pub struct TempEnv {
root: TempDir,
found: BTreeMap<PathBuf, Option<Vec<u8>>>,
Expand All @@ -18,15 +16,15 @@ pub struct Setup(TempEnv);
impl Setup {
pub fn setup_dir<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
let abs_path = self.0.root.path().join(path.as_ref());
util::fs::create_dir(abs_path, true).unwrap();
typst_test_stdx::fs::create_dir(abs_path, true).unwrap();
self
}

pub fn setup_file<P: AsRef<Path>>(&mut self, path: P, content: impl AsRef<[u8]>) -> &mut Self {
let abs_path = self.0.root.path().join(path.as_ref());
let parent = abs_path.parent().unwrap();
if parent != self.0.root.path() {
util::fs::create_dir(parent, true).unwrap();
typst_test_stdx::fs::create_dir(parent, true).unwrap();
}

let content = content.as_ref();
Expand All @@ -38,7 +36,7 @@ impl Setup {
let abs_path = self.0.root.path().join(path.as_ref());
let parent = abs_path.parent().unwrap();
if parent != self.0.root.path() {
util::fs::create_dir(parent, true).unwrap();
typst_test_stdx::fs::create_dir(parent, true).unwrap();
}

std::fs::write(&abs_path, "").unwrap();
Expand Down
7 changes: 3 additions & 4 deletions crates/typst-test-lib/src/compare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
use std::fmt::{Debug, Display};

use thiserror::Error;

use crate::util;
use typst_test_stdx::fmt::Term;

pub mod visual;

Expand Down Expand Up @@ -57,7 +56,7 @@ impl Display for Error {
f,
"{} {} differed {:?}",
self.pages.len(),
util::fmt::plural(self.pages.len(), "page"),
typst_test_stdx::fmt::Term::simple("page").with(self.pages.len()),
self.pages.iter().map(|(n, _)| n).collect::<Vec<_>>()
)?;
}
Expand All @@ -83,7 +82,7 @@ pub enum PageError {
#[error(
"content differed in at least {} {}",
deviations,
util::fmt::plural(*deviations, "pixel")
Term::simple("pixel").with(*deviations)
)]
SimpleDeviations {
/// The amount of visual deviations, i.e. the amount of pixels which did
Expand Down
4 changes: 1 addition & 3 deletions crates/typst-test-lib/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,10 @@ use typst::syntax::{FileId, Source};
use typst::text::{Font, FontBook};
use typst::{Library, World};

use crate::util;

/// An error which may occur during compilation. This struct only exists to
/// implement [`Error`][trait@std::error::Error].
#[derive(Debug, Clone, Error)]
#[error("compilation failed with {} {}", .0.len(), util::fmt::plural(.0.len(), "error"))]
#[error("compilation failed with {} {}", .0.len(), typst_test_stdx::fmt::Term::simple("error").with(.0.len()))]
pub struct Error(pub EcoVec<SourceDiagnostic>);

/// Compiles a source with the given global world.
Expand Down
3 changes: 0 additions & 3 deletions crates/typst-test-lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ pub mod store;
pub mod test;
pub mod test_set;

#[doc(hidden)]
pub mod util;

#[cfg(test)]
pub mod _dev;

Expand Down
25 changes: 12 additions & 13 deletions crates/typst-test-lib/src/store/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use crate::store::project::{Resolver, TestTarget};
use crate::store::{Document, LoadError, SaveError};
use crate::test::id::Identifier;
use crate::test::{Annotation, ReferenceKind};
use crate::util;

pub mod collector;

Expand Down Expand Up @@ -110,7 +109,7 @@ impl Test {
references: Option<References>,
) -> Result<Self, SaveError> {
let test_dir = resolver.resolve(&id, TestTarget::TestDir);
util::fs::create_dir(test_dir, true)?;
typst_test_stdx::fs::create_dir(test_dir, true)?;

let mut file = File::options()
.write(true)
Expand Down Expand Up @@ -156,11 +155,11 @@ impl Test {
/// Creates this test's temporary directories, if they don't exist yet.
pub fn create_temporary_directories(&self, resolver: &dyn Resolver) -> io::Result<()> {
if self.is_ephemeral() {
util::fs::create_dir(resolver.resolve(&self.id, TestTarget::RefDir), true)?;
typst_test_stdx::fs::create_dir(resolver.resolve(&self.id, TestTarget::RefDir), true)?;
}

util::fs::create_dir(resolver.resolve(&self.id, TestTarget::OutDir), true)?;
util::fs::create_dir(resolver.resolve(&self.id, TestTarget::DiffDir), true)?;
typst_test_stdx::fs::create_dir(resolver.resolve(&self.id, TestTarget::OutDir), true)?;
typst_test_stdx::fs::create_dir(resolver.resolve(&self.id, TestTarget::DiffDir), true)?;
Ok(())
}

Expand All @@ -183,7 +182,7 @@ impl Test {
reference: &Document,
) -> Result<(), SaveError> {
let ref_dir = resolver.resolve(&self.id, TestTarget::RefDir);
util::fs::create_dir(ref_dir, true)?;
typst_test_stdx::fs::create_dir(ref_dir, true)?;
reference.save(ref_dir)?;
Ok(())
}
Expand All @@ -194,32 +193,32 @@ impl Test {
self.delete_reference_script(resolver)?;
self.delete_temporary_directories(resolver)?;

util::fs::remove_file(resolver.resolve(&self.id, TestTarget::TestScript))?;
util::fs::remove_dir(resolver.resolve(&self.id, TestTarget::TestDir), true)?;
typst_test_stdx::fs::remove_file(resolver.resolve(&self.id, TestTarget::TestScript))?;
typst_test_stdx::fs::remove_dir(resolver.resolve(&self.id, TestTarget::TestDir), true)?;

Ok(())
}

/// Deletes this test's temporary directories, if they exist.
pub fn delete_temporary_directories(&self, resolver: &dyn Resolver) -> io::Result<()> {
if self.is_ephemeral() {
util::fs::remove_dir(resolver.resolve(&self.id, TestTarget::RefDir), true)?;
typst_test_stdx::fs::remove_dir(resolver.resolve(&self.id, TestTarget::RefDir), true)?;
}

util::fs::remove_dir(resolver.resolve(&self.id, TestTarget::OutDir), true)?;
util::fs::remove_dir(resolver.resolve(&self.id, TestTarget::DiffDir), true)?;
typst_test_stdx::fs::remove_dir(resolver.resolve(&self.id, TestTarget::OutDir), true)?;
typst_test_stdx::fs::remove_dir(resolver.resolve(&self.id, TestTarget::DiffDir), true)?;
Ok(())
}

/// Deletes this test's reference script, if it exists.
pub fn delete_reference_script(&self, resolver: &dyn Resolver) -> io::Result<()> {
util::fs::remove_file(resolver.resolve(&self.id, TestTarget::RefScript))?;
typst_test_stdx::fs::remove_file(resolver.resolve(&self.id, TestTarget::RefScript))?;
Ok(())
}

/// Deletes this test's persistent reference documents, if they exist.
pub fn delete_reference_documents(&self, resolver: &dyn Resolver) -> io::Result<()> {
util::fs::remove_dir(resolver.resolve(&self.id, TestTarget::RefDir), true)?;
typst_test_stdx::fs::remove_dir(resolver.resolve(&self.id, TestTarget::RefDir), true)?;
Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion crates/typst-test-lib/src/store/vcs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,7 @@ mod tests {
)
.unwrap();
},
|root| root.expect_dir("tests/fancy/ref.typ"),
|root| root.expect_file_empty("tests/fancy/ref.typ"),
);
}
}
Loading

0 comments on commit 62a6805

Please sign in to comment.