Skip to content

Commit

Permalink
Use camino to simplify path handling
Browse files Browse the repository at this point in the history
  • Loading branch information
TheSignPainter98 committed Dec 7, 2023
1 parent 19b9ff6 commit a3c7ffc
Show file tree
Hide file tree
Showing 8 changed files with 48 additions and 57 deletions.
8 changes: 8 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions crates/arg_parser/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ version = "0.0.0"
edition = "2021"

[dependencies]
camino = "1.1.6"
clap = { version = "4.0.12", features = ["derive", "env", "wrap_help"] }
clap-verbosity-flag = "2.0.0"
emblem_core = { path = "../emblem_core" }
Expand Down
23 changes: 10 additions & 13 deletions crates/arg_parser/src/arg_path.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
use crate::RawArgs;
use camino::Utf8PathBuf;
use clap::{
builder::{OsStr, StringValueParser, TypedValueParser},
error::{Error as ClapError, ErrorKind as ClapErrorKind},
CommandFactory,
};
use std::{fmt::Display, path::PathBuf};
use std::fmt::Display;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ArgPath {
Stdio,
Path(PathBuf),
Path(Utf8PathBuf),
}

impl ArgPath {
Expand All @@ -26,14 +27,10 @@ impl Default for ArgPath {

impl Display for ArgPath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::Stdio => "-",
Self::Path(s) => s.to_str().unwrap_or("(invalid path)"),
}
)
match self {
Self::Stdio => write!(f, "-"),
Self::Path(p) => write!(f, "{p}"),
}
}
}

Expand Down Expand Up @@ -78,7 +75,7 @@ impl TryFrom<&str> for ArgPath {
.error(ClapErrorKind::InvalidValue, FILE_PATH_CANNOT_BE_EMPTY))
}
"-" => Ok(Self::Stdio),
raw => Ok(Self::Path(PathBuf::from(raw))),
raw => Ok(Self::Path(Utf8PathBuf::from(raw))),
}
}
}
Expand All @@ -88,7 +85,7 @@ pub enum UninferredArgPath {
#[default]
Infer,
Stdio,
Path(PathBuf),
Path(Utf8PathBuf),
}

impl UninferredArgPath {
Expand All @@ -113,7 +110,7 @@ impl Display for UninferredArgPath {
let repr = match self {
Self::Infer => "??",
Self::Stdio => "stdio",
Self::Path(p) => p.to_str().unwrap(),
Self::Path(p) => p.as_str(),
};
repr.fmt(f)
}
Expand Down
1 change: 1 addition & 0 deletions crates/emblem_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ default = ["git2"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
camino = "1.1.6"
derive-new = "0.5.9"
derive_more = "0.99.17"
git2 = { version = "0.16.1", optional = true }
Expand Down
23 changes: 12 additions & 11 deletions crates/emblem_core/src/args.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
use std::{fmt, path};
use std::fmt;

use camino::Utf8PathBuf;

#[cfg(test)]
use camino::Utf8Path;

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum ArgPath {
Stdio,
Path(path::PathBuf),
Path(Utf8PathBuf),
}

impl AsRef<ArgPath> for ArgPath {
Expand All @@ -14,20 +19,16 @@ impl AsRef<ArgPath> for ArgPath {

impl fmt::Display for ArgPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
Self::Stdio => "-",
Self::Path(s) => s.to_str().unwrap_or("(invalid path)"),
}
)
match self {
Self::Stdio => write!(f, "-"),
Self::Path(p) => write!(f, "{p}"),
}
}
}

#[cfg(test)]
impl ArgPath {
pub fn path(&self) -> Option<&path::Path> {
pub fn path(&self) -> Option<&Utf8Path> {
match self {
Self::Stdio => None,
Self::Path(p) => Some(p),
Expand Down
15 changes: 1 addition & 14 deletions crates/emblem_core/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{borrow::Cow, error::Error as StdError, ffi::OsString, fmt::Display, io};
use std::{borrow::Cow, error::Error as StdError, fmt::Display, io};

use crate::{log::LogId, parser::error::ParseError, FileName, Log};

Expand Down Expand Up @@ -26,10 +26,6 @@ impl Error {
Self::new(ErrorImpl::ParseError { file_name, cause })
}

pub fn string_conversion(culprit: OsString) -> Self {
Self::new(ErrorImpl::StringConversion { culprit })
}

pub fn too_many_errors(tot_errors: i32) -> Self {
Self::new(ErrorImpl::TooManyErrors { tot_errors })
}
Expand Down Expand Up @@ -78,9 +74,6 @@ enum ErrorImpl {
cause: ParseError,
},

#[error("cannot convert string to utf8: {}", culprit.to_string_lossy())]
StringConversion { culprit: OsString },

#[error("run aborted after {tot_errors}")]
TooManyErrors { tot_errors: i32 },

Expand Down Expand Up @@ -127,12 +120,6 @@ mod test {
)
}

#[test]
fn string_conversion() {
let err = Error::string_conversion(OsString::from("wassup"));
assert_eq!(err.to_string(), "cannot convert string to utf8: wassup")
}

#[test]
fn uncallable_listener() {
let err = Error::uncallable_listener("string");
Expand Down
13 changes: 4 additions & 9 deletions crates/emblem_core/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,10 @@ lalrpop_mod!(
/// Parse an emblem source file at the given location.
pub fn parse_file<L: Logger>(ctx: &Context<L>, mut to_parse: SearchResult) -> Result<ParsedFile> {
let file = {
let raw = to_parse.path().as_os_str();
let mut path: &str = to_parse
.path()
.as_os_str()
.to_str()
.ok_or_else(|| Error::string_conversion(raw.to_owned()))?;
if path == "-" {
path = "(stdin)";
}
let path = match to_parse.path().as_str() {
"-" => "(stdin)",
x => x,
};
ctx.alloc_file_name(path)
};

Expand Down
21 changes: 11 additions & 10 deletions crates/emblem_core/src/path.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use camino::{Utf8Path, Utf8PathBuf};

use crate::{args::ArgPath, Error, Result};
use std::{
fs,
io::{self, Read},
path,
};

#[cfg(test)]
Expand Down Expand Up @@ -98,12 +99,12 @@ use std::{

#[derive(Debug)]
pub struct SearchResult {
path: path::PathBuf,
path: Utf8PathBuf,
file: InputFile,
}

impl SearchResult {
pub fn path(&self) -> &path::Path {
pub fn path(&self) -> &Utf8Path {
&self.path
}

Expand All @@ -117,7 +118,7 @@ impl TryFrom<&str> for SearchResult {

fn try_from(value: &str) -> Result<Self> {
Ok(Self {
path: path::PathBuf::from(value),
path: Utf8PathBuf::from(value),
file: InputFile::from(fs::File::open(value)?),
})
}
Expand All @@ -129,11 +130,11 @@ impl TryFrom<&ArgPath> for SearchResult {
fn try_from(value: &ArgPath) -> Result<Self> {
Ok(match value {
ArgPath::Path(p) => Self {
path: path::PathBuf::from(p),
path: Utf8PathBuf::from(p),
file: InputFile::from(fs::File::open(p)?),
},
ArgPath::Stdio => Self {
path: path::PathBuf::from("-"),
path: Utf8PathBuf::from("-"),
file: InputFile::from(io::stdin()), // TODO(kcza): lock this!
},
})
Expand Down Expand Up @@ -395,9 +396,9 @@ mod test {
use io::Write;

#[test]
fn fields() -> io::Result<()> {
fn fields() -> Result<()> {
let tmpdir = tempfile::tempdir()?;
let path = tmpdir.path().join("fields.txt");
let path = Utf8PathBuf::try_from(tmpdir.path().join("fields.txt")).unwrap();
let mut file = fs::File::create(&path)?;
file.write_all(b"file-content")?;

Expand Down Expand Up @@ -448,7 +449,7 @@ mod test {
let src = "from.txt";

let tmpdir = tempfile::tempdir()?;
let path = tmpdir.path().join(src);
let path = Utf8PathBuf::try_from(tmpdir.path().join(src)).unwrap();
let mut file = fs::File::create(&path)?;
file.write_all(b"file-content")?;

Expand All @@ -469,7 +470,7 @@ mod test {
{
let a = ArgPath::Stdio;
let s: SearchResult = a.as_ref().try_into()?;
assert_eq!(s.path, path::PathBuf::from("-"));
assert_eq!(s.path, Utf8PathBuf::from("-"));
assert!(s.file.stdin().is_some());
}

Expand Down

0 comments on commit a3c7ffc

Please sign in to comment.