Compare commits

..

9 Commits

Author SHA1 Message Date
Neven Villani
ed8aeecbc4
Merge 143732d2a82c057f9efe48895fc798e422894fec into 7278d887cf05fadc9a96478830e5876739b78f53 2025-07-24 10:18:23 +09:00
Neven Villani
143732d2a8 One comment out of date 2025-06-24 14:42:23 +02:00
Neven Villani
efe81a1aae
Merge branch 'main' into main 2025-06-12 16:06:33 +02:00
Neven Villani
3b5ee3c488 Update in tests/ too the PathBuf in FileError 2025-06-12 15:54:09 +02:00
Neven Villani
f3d5cdc6a5 Report path on a FileError 2025-06-12 15:47:47 +02:00
Neven Villani
85e03abe45 Improve messages
- restore ability to override a package locally
- cut down on some repeated logic
- more detailed errors
2025-06-12 13:36:13 +02:00
Neven Villani
c354369b05 What's with the namespacing on the unit tests ? 2025-06-11 22:43:14 +02:00
Neven Villani
91ec946283 first attempt 2025-06-11 22:32:10 +02:00
Neven Villani
a5ef75a9c2 I want to get all of this working 2025-06-11 22:31:56 +02:00
7 changed files with 69 additions and 114 deletions

View File

@ -159,7 +159,6 @@ strip = true
[workspace.lints.clippy]
blocks_in_conditions = "allow"
comparison_chain = "allow"
iter_over_hash_type = "warn"
manual_range_contains = "allow"
mutable_key_type = "allow"
uninlined_format_args = "warn"

View File

@ -29,9 +29,8 @@ pub fn init(command: &InitCommand) -> StrResult<()> {
})?;
// Find or download the package.
let package_path = package_storage
.prepare_package(&spec, &mut PrintDownload(&spec))
.map_err(|e| eco_format!("{e}"))?;
let package_path =
package_storage.prepare_package(&spec, &mut PrintDownload(&spec))?;
// Parse the manifest.
let manifest = parse_manifest(&package_path)?;

View File

@ -139,7 +139,6 @@ impl Watcher {
fn update(&mut self, iter: impl IntoIterator<Item = PathBuf>) -> StrResult<()> {
// Mark all files as not "seen" so that we may unwatch them if they
// aren't in the dependency list.
#[allow(clippy::iter_over_hash_type, reason = "order does not matter")]
for seen in self.watched.values_mut() {
*seen = false;
}

View File

@ -173,7 +173,6 @@ impl SystemWorld {
/// Reset the compilation state in preparation of a new compilation.
pub fn reset(&mut self) {
#[allow(clippy::iter_over_hash_type, reason = "order does not matter")]
for slot in self.slots.get_mut().values_mut() {
slot.reset();
}

View File

@ -121,7 +121,7 @@ impl PackageStorage {
let namespace_dir = packages_dir.join(format!("{}", spec.namespace));
if !namespace_dir.exists() {
return not_found(eco_format!(
"the namespace @{} should be located at {}",
"namespace @{} should be located at {}",
spec.namespace,
namespace_dir.display()
));
@ -129,7 +129,7 @@ impl PackageStorage {
let package_dir = namespace_dir.join(format!("{}", spec.name));
if !package_dir.exists() {
return not_found(eco_format!(
"the registry at {} does not have package '{}'",
"{} does not have package '{}'",
namespace_dir.display(),
spec.name
));
@ -220,7 +220,7 @@ impl PackageStorage {
return Err(PackageError::NotFound(
spec.clone(),
eco_format!(
"the registry at {namespace_url} does not have package '{}'",
"{namespace_url} does not have package '{}'",
spec.name
),
));

View File

@ -314,24 +314,6 @@ impl<T> Trace<T> for SourceResult<T> {
/// A result type with a string error message.
pub type StrResult<T> = Result<T, EcoString>;
/// A common trait to add a span to any error
pub trait ErrAt {
/// Attach a span to a more specialized error and turn it into
/// a generic error, optionally with hints.
fn err_at(self, span: Span) -> SourceDiagnostic;
}
/// Blanket implementation for anything that doesn't implement its own
/// convertion to a SourceDiagnostic.
impl<S> ErrAt for S
where
S: Into<EcoString>,
{
fn err_at(self, span: Span) -> SourceDiagnostic {
SourceDiagnostic::error(span, self)
}
}
/// Convert a [`StrResult`] or [`HintedStrResult`] to a [`SourceResult`] by
/// adding span information.
pub trait At<T> {
@ -341,10 +323,18 @@ pub trait At<T> {
impl<T, S> At<T> for Result<T, S>
where
S: ErrAt,
S: Into<EcoString>,
{
fn at(self, span: Span) -> SourceResult<T> {
self.map_err(|e| eco_vec![e.err_at(span)])
self.map_err(|message| {
let mut diagnostic = SourceDiagnostic::error(span, message);
if diagnostic.message.contains("(access denied)") {
diagnostic.hint("cannot read file outside of project root");
diagnostic
.hint("you can adjust the project root with the --root argument");
}
eco_vec![diagnostic]
})
}
}
@ -478,29 +468,6 @@ impl FileError {
_ => Self::Other(Some(eco_format!("{err}"))),
}
}
fn write_hints(&self) -> EcoVec<EcoString> {
match self {
Self::NotFound(_) => eco_vec![],
Self::AccessDenied(_) => {
eco_vec![
eco_format!("cannot read file outside of project root"),
eco_format!(
"you can adjust the project root with the --root argument"
),
]
}
Self::IsDirectory(_) => eco_vec![],
Self::NotSource(_) => eco_vec![],
Self::InvalidUtf8(Some(path)) => {
eco_vec![eco_format!("tried to read {}", path.display())]
}
Self::InvalidUtf8(None) => eco_vec![],
Self::Package(error) => error.write_hints(),
Self::Other(Some(err)) => eco_vec![eco_format!("{err}")],
Self::Other(None) => eco_vec![],
}
}
}
impl std::error::Error for FileError {}
@ -511,31 +478,26 @@ impl Display for FileError {
Self::NotFound(path) => {
write!(f, "file not found (searched at {})", path.display())
}
Self::NotSource(path) => {
write!(f, "{} is not a typst source file", path.display())
}
Self::InvalidUtf8(_) => write!(f, "file is not valid utf-8"),
Self::IsDirectory(path) => {
write!(f, "failed to load file {} (is a directory)", path.display())
}
Self::AccessDenied(path) => {
write!(f, "failed to load file {} (access denied)", path.display())
}
Self::Other(_) => {
write!(f, "failed to load file")
Self::IsDirectory(path) => {
write!(f, "failed to load file {} (is a directory)", path.display())
}
Self::Package(error) => write!(f, "{error}"),
Self::NotSource(path) => {
write!(f, "{} is not a typst source file", path.display())
}
Self::InvalidUtf8(Some(path)) => {
write!(f, "file {} is not valid utf-8", path.display())
}
Self::InvalidUtf8(None) => f.pad("file is not valid utf-8"),
Self::Package(error) => error.fmt(f),
Self::Other(Some(err)) => write!(f, "failed to load file ({err})"),
Self::Other(None) => f.pad("failed to load file"),
}
}
}
impl ErrAt for FileError {
fn err_at(self, span: Span) -> SourceDiagnostic {
let hints = self.write_hints();
SourceDiagnostic::error(span, eco_format!("{}", self)).with_hints(hints)
}
}
impl From<Utf8Error> for FileError {
fn from(_: Utf8Error) -> Self {
Self::InvalidUtf8(None)
@ -554,6 +516,12 @@ impl From<PackageError> for FileError {
}
}
impl From<FileError> for EcoString {
fn from(err: FileError) -> Self {
eco_format!("{err}")
}
}
/// A result type with a package-related error.
pub type PackageResult<T> = Result<T, PackageError>;
@ -576,58 +544,48 @@ pub enum PackageError {
Other(Option<EcoString>),
}
impl PackageError {
fn write_hints(&self) -> EcoVec<EcoString> {
match self {
Self::NotFound(_, detail) => {
eco_vec![eco_format!("{detail}")]
}
Self::VersionNotFound(spec, latest, registry) => {
if let Some(version) = latest {
eco_vec![
eco_format!(
"the package {} exists, but not with version {}",
spec.name,
spec.version
),
eco_format!(
"the registry at {registry} provides up to version {version}"
),
]
} else {
eco_vec![eco_format!(
"the registry at {registry} contains no versions for this package"
)]
}
}
Self::NetworkFailed(Some(err)) => eco_vec![eco_format!("{err}")],
Self::NetworkFailed(None) => eco_vec![],
Self::MalformedArchive(Some(err)) => eco_vec![eco_format!("{err}")],
Self::MalformedArchive(None) => {
eco_vec![eco_format!("the archive is malformed")]
}
Self::Other(Some(err)) => eco_vec![eco_format!("{err}")],
Self::Other(None) => eco_vec![],
}
}
}
impl std::error::Error for PackageError {}
impl Display for PackageError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::NotFound(spec, _) => write!(f, "package {spec} not found"),
Self::VersionNotFound(spec, _, _) => {
write!(f, "package version {spec} not found")
Self::NotFound(spec, detail) => {
write!(f, "package not found: {detail} (searching for {spec})",)
}
Self::NetworkFailed(_) => write!(f, "failed to download package"),
Self::MalformedArchive(_) => write!(f, "failed to decompress package"),
Self::Other(_) => f.pad("failed to load package"),
Self::VersionNotFound(spec, latest, registry) => {
write!(
f,
"package '{}' found, but version {} does not exist",
spec.name, spec.version
)?;
if let Some(version) = latest {
write!(f, " (latest version provided by {registry} is {version})")
} else {
write!(f, " ({registry} contains no versions for this package)")
}
}
Self::NetworkFailed(Some(err)) => {
write!(f, "failed to download package ({err})")
}
Self::NetworkFailed(None) => f.pad("failed to download package"),
Self::MalformedArchive(Some(err)) => {
write!(f, "failed to decompress package ({err})")
}
Self::MalformedArchive(None) => {
f.pad("failed to decompress package (archive malformed)")
}
Self::Other(Some(err)) => write!(f, "failed to load package ({err})"),
Self::Other(None) => f.pad("failed to load package"),
}
}
}
impl From<PackageError> for EcoString {
fn from(err: PackageError) -> Self {
eco_format!("{err}")
}
}
/// A result type with a data-loading-related error.
pub type LoadResult<T> = Result<T, LoadError>;

View File

@ -42,10 +42,10 @@ use std::collections::HashSet;
use std::sync::LazyLock;
use comemo::{Track, Tracked, Validate};
use ecow::{EcoVec, eco_format, eco_vec};
use ecow::{EcoString, EcoVec, eco_format, eco_vec};
use typst_html::HtmlDocument;
use typst_library::diag::{
ErrAt, FileError, SourceDiagnostic, SourceResult, Warned, bail, warning,
FileError, SourceDiagnostic, SourceResult, Warned, bail, warning,
};
use typst_library::engine::{Engine, Route, Sink, Traced};
use typst_library::foundations::{NativeRuleMap, StyleChain, Styles, Value};
@ -192,7 +192,8 @@ fn hint_invalid_main_file(
input: FileId,
) -> EcoVec<SourceDiagnostic> {
let is_utf8_error = matches!(file_error, FileError::InvalidUtf8(_));
let mut diagnostic = file_error.err_at(Span::detached());
let mut diagnostic =
SourceDiagnostic::error(Span::detached(), EcoString::from(file_error));
// Attempt to provide helpful hints for UTF-8 errors. Perhaps the user
// mistyped the filename. For example, they could have written "file.pdf"