Skip to content

Commit 6766aed

Browse files
committed
Replace dist errors
Add property validation and parameter errors to the error module and replace all `Box<Error>`s in the dist module with `error:Error`s. Also, make the first word of all error messages consistently lowercase.
1 parent 3100dbd commit 6766aed

File tree

9 files changed

+126
-89
lines changed

9 files changed

+126
-89
lines changed

src/dist/mod.rs

+16-21
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ distribution `META.json` files. It supports both the [v1] and [v2] specs.
88
[v2]: https://github.com/pgxn/rfcs/pull/3
99
1010
*/
11-
use std::{borrow::Borrow, collections::HashMap, error::Error, fs::File, path::Path};
11+
use std::{borrow::Borrow, collections::HashMap, fs::File, path::Path};
1212

13-
use crate::util;
13+
use crate::{error::Error, util};
1414
use relative_path::{RelativePath, RelativePathBuf};
1515
use semver::Version;
1616
use serde::{Deserialize, Deserializer, Serialize};
@@ -828,18 +828,18 @@ where
828828
impl Distribution {
829829
/// Deserializes `meta`, which contains PGXN `version` metadata, into a
830830
/// [`Distribution`].
831-
fn from_version(version: u8, meta: Value) -> Result<Self, Box<dyn Error>> {
831+
fn from_version(version: u8, meta: Value) -> Result<Self, Error> {
832832
match version {
833833
1 => v1::from_value(meta),
834834
2 => v2::from_value(meta),
835-
_ => Err(Box::from(format!("Unknown meta version {version}"))),
835+
_ => Err(Error::UnknownSpec),
836836
}
837837
}
838838

839839
/// Loads the release `META.json` data from `file` then converts into a
840840
/// [`Distribution`]. Returns an error on file error or if the content of
841841
/// `file` is not valid PGXN `META.json` data.
842-
pub fn load<P: AsRef<Path>>(file: P) -> Result<Self, Box<dyn Error>> {
842+
pub fn load<P: AsRef<Path>>(file: P) -> Result<Self, Error> {
843843
let meta: Value = serde_json::from_reader(File::open(file)?)?;
844844
meta.try_into()
845845
}
@@ -922,7 +922,7 @@ impl Distribution {
922922
}
923923

924924
impl TryFrom<Value> for Distribution {
925-
type Error = Box<dyn Error>;
925+
type Error = Error;
926926
/// Converts the PGXN `META.json` data from `meta` into a
927927
/// [`Distribution`]. Returns an error if `meta` is invalid.
928928
///
@@ -959,16 +959,13 @@ impl TryFrom<Value> for Distribution {
959959
fn try_from(meta: Value) -> Result<Self, Self::Error> {
960960
// Make sure it's valid.
961961
let mut validator = crate::valid::Validator::new();
962-
let version = match validator.validate(&meta) {
963-
Err(e) => return Err(Box::from(e.to_string())),
964-
Ok(v) => v,
965-
};
962+
let version = validator.validate(&meta)?;
966963
Distribution::from_version(version, meta)
967964
}
968965
}
969966

970967
impl TryFrom<&[&Value]> for Distribution {
971-
type Error = Box<dyn Error>;
968+
type Error = Error;
972969
/// Merge multiple PGXN `META.json` data from `meta` into a
973970
/// [`Distribution`]. Returns an error if `meta` is invalid.
974971
///
@@ -1013,12 +1010,11 @@ impl TryFrom<&[&Value]> for Distribution {
10131010
/// [RFC 7396]: https:///www.rfc-editor.org/rfc/rfc7396.html
10141011
fn try_from(meta: &[&Value]) -> Result<Self, Self::Error> {
10151012
if meta.is_empty() {
1016-
return Err(Box::from("meta contains no values"));
1013+
return Err(Error::Param("meta contains no values"));
10171014
}
10181015

10191016
// Find the version of the first doc.
1020-
let version =
1021-
util::get_version(meta[0]).ok_or("No spec version found in first meta value")?;
1017+
let version = util::get_version(meta[0]).ok_or(Error::UnknownSpec)?;
10221018

10231019
// Convert the first doc to v2 if necessary.
10241020
let mut v2 = match version {
@@ -1034,21 +1030,20 @@ impl TryFrom<&[&Value]> for Distribution {
10341030

10351031
// Validate the patched doc and return.
10361032
let mut validator = crate::valid::Validator::new();
1037-
validator.validate(&v2).map_err(|e| e.to_string())?;
1033+
validator.validate(&v2)?;
10381034
Distribution::from_version(2, v2)
10391035
}
10401036
}
10411037

10421038
impl TryFrom<Distribution> for Value {
1043-
type Error = Box<dyn Error>;
1039+
type Error = Error;
10441040
/// Converts `meta` into a [serde_json::Value].
10451041
///
10461042
/// # Example
10471043
///
10481044
/// ``` rust
1049-
/// # use std::error::Error;
10501045
/// use serde_json::{json, Value};
1051-
/// use pgxn_meta::dist::*;
1046+
/// use pgxn_meta::{error::Error, dist::*};
10521047
///
10531048
/// let meta_json = json!({
10541049
/// "name": "pair",
@@ -1072,7 +1067,7 @@ impl TryFrom<Distribution> for Value {
10721067
///
10731068
/// let meta = Distribution::try_from(meta_json);
10741069
/// assert!(meta.is_ok());
1075-
/// let val: Result<Value, Box<dyn Error>> = meta.unwrap().try_into();
1070+
/// let val: Result<Value, Error> = meta.unwrap().try_into();
10761071
/// assert!(val.is_ok());
10771072
/// ```
10781073
fn try_from(meta: Distribution) -> Result<Self, Self::Error> {
@@ -1082,7 +1077,7 @@ impl TryFrom<Distribution> for Value {
10821077
}
10831078

10841079
impl TryFrom<&String> for Distribution {
1085-
type Error = Box<dyn Error>;
1080+
type Error = Error;
10861081
/// Converts `str` into JSON and then into a [`Distribution`]. Returns an
10871082
/// error if the content of `str` is not valid PGXN `META.json` data.
10881083
fn try_from(str: &String) -> Result<Self, Self::Error> {
@@ -1092,7 +1087,7 @@ impl TryFrom<&String> for Distribution {
10921087
}
10931088

10941089
impl TryFrom<Distribution> for String {
1095-
type Error = Box<dyn Error>;
1090+
type Error = Error;
10961091
/// Converts `meta` into a JSON String.
10971092
fn try_from(meta: Distribution) -> Result<Self, Self::Error> {
10981093
let val = serde_json::to_string(&meta)?;

src/dist/tests.rs

+16-18
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
use super::*;
22
use serde_json::{json, Value};
33
use std::{
4-
error::Error,
54
fs::{self, File},
65
path::PathBuf,
76
};
87
use wax::Glob;
98

109
#[test]
11-
fn test_corpus() -> Result<(), Box<dyn Error>> {
10+
fn test_corpus() -> Result<(), Error> {
1211
for v_dir in ["v1", "v2"] {
1312
let dir: PathBuf = [env!("CARGO_MANIFEST_DIR"), "corpus", v_dir]
1413
.iter()
@@ -32,7 +31,7 @@ fn test_corpus() -> Result<(), Box<dyn Error>> {
3231
if v_dir == "v2" {
3332
assert_eq!(contents.get("license").unwrap(), dist.license());
3433
// Make sure round-trip produces the same JSON.
35-
let output: Result<Value, Box<dyn Error>> = dist.try_into();
34+
let output: Result<Value, Error> = dist.try_into();
3635
match output {
3736
Err(e) => panic!("{v_dir}/{:?} failed: {e}", path.file_name().unwrap()),
3837
Ok(val) => {
@@ -49,11 +48,10 @@ fn test_corpus() -> Result<(), Box<dyn Error>> {
4948
Ok(dist) => {
5049
if v_dir == "v2" {
5150
// Make sure value round-trip produces the same JSON.
52-
let output: Result<String, Box<dyn Error>> = dist.try_into();
51+
let output: Result<Value, Error> = dist.try_into();
5352
match output {
5453
Err(e) => panic!("{v_dir}/{:?} failed: {e}", path.file_name().unwrap()),
5554
Ok(val) => {
56-
let val: Value = serde_json::from_str(&val)?;
5755
assert_json_diff::assert_json_eq!(&contents, &val);
5856
}
5957
};
@@ -68,7 +66,7 @@ fn test_corpus() -> Result<(), Box<dyn Error>> {
6866
}
6967

7068
#[test]
71-
fn test_bad_corpus() -> Result<(), Box<dyn Error>> {
69+
fn test_bad_corpus() -> Result<(), Error> {
7270
let file: PathBuf = [env!("CARGO_MANIFEST_DIR"), "corpus", "invalid.json"]
7371
.iter()
7472
.collect();
@@ -89,7 +87,7 @@ fn test_bad_corpus() -> Result<(), Box<dyn Error>> {
8987
"Should have failed on {:?} but did not",
9088
file.file_name().unwrap()
9189
),
92-
Err(e) => assert_eq!("Unknown meta version 99", e.to_string()),
90+
Err(e) => assert_eq!("cannot determine meta-spec version", e.to_string()),
9391
}
9492

9593
// Should fail when no meta-spec.
@@ -99,7 +97,7 @@ fn test_bad_corpus() -> Result<(), Box<dyn Error>> {
9997
"Should have failed on {:?} but did not",
10098
file.file_name().unwrap()
10199
),
102-
Err(e) => assert_eq!("Cannot determine meta-spec version", e.to_string()),
100+
Err(e) => assert_eq!("cannot determine meta-spec version", e.to_string()),
103101
}
104102

105103
// Make sure we catch a failure parsing into a Distribution struct.
@@ -112,7 +110,7 @@ fn test_bad_corpus() -> Result<(), Box<dyn Error>> {
112110
}
113111

114112
#[test]
115-
fn test_try_merge_v1() -> Result<(), Box<dyn Error>> {
113+
fn test_try_merge_v1() -> Result<(), Error> {
116114
// Load a v1 META file.
117115
let dir: PathBuf = [env!("CARGO_MANIFEST_DIR"), "corpus"].iter().collect();
118116
let widget_file = dir.join("v1").join("widget.json");
@@ -169,7 +167,7 @@ fn test_try_merge_v1() -> Result<(), Box<dyn Error>> {
169167
}
170168

171169
#[test]
172-
fn test_try_merge_v2() -> Result<(), Box<dyn Error>> {
170+
fn test_try_merge_v2() -> Result<(), Error> {
173171
// Load a v2 META file.
174172
let dir: PathBuf = [env!("CARGO_MANIFEST_DIR"), "corpus"].iter().collect();
175173
let widget_file = dir.join("v2").join("minimal.json");
@@ -214,7 +212,7 @@ fn run_merge_case(
214212
orig: &Value,
215213
patches: &[Value],
216214
expect: &Value,
217-
) -> Result<(), Box<dyn Error>> {
215+
) -> Result<(), Error> {
218216
let mut meta = vec![orig];
219217
for p in patches {
220218
meta.push(p);
@@ -223,7 +221,7 @@ fn run_merge_case(
223221
Err(e) => panic!("patching {name} failed: {e}"),
224222
Ok(dist) => {
225223
// Convert the Distribution object to JSON.
226-
let output: Result<Value, Box<dyn Error>> = dist.try_into();
224+
let output: Result<Value, Error> = dist.try_into();
227225
match output {
228226
Err(e) => panic!("{name} serialization failed: {e}"),
229227
Ok(val) => {
@@ -240,7 +238,7 @@ fn run_merge_case(
240238
}
241239

242240
#[test]
243-
fn test_try_merge_err() -> Result<(), Box<dyn Error>> {
241+
fn test_try_merge_err() -> Result<(), Error> {
244242
// Load invalid meta.
245243
let dir: PathBuf = [env!("CARGO_MANIFEST_DIR"), "corpus"].iter().collect();
246244
let widget_file = dir.join("invalid.json");
@@ -254,12 +252,12 @@ fn test_try_merge_err() -> Result<(), Box<dyn Error>> {
254252
(
255253
"no version",
256254
vec![&empty],
257-
"No spec version found in first meta value",
255+
"cannot determine meta-spec version",
258256
),
259257
(
260258
"bad version",
261259
vec![&bad_version],
262-
"No spec version found in first meta value",
260+
"cannot determine meta-spec version",
263261
),
264262
(
265263
"invalid",
@@ -277,7 +275,7 @@ fn test_try_merge_err() -> Result<(), Box<dyn Error>> {
277275
}
278276

279277
#[test]
280-
fn test_try_merge_partman() -> Result<(), Box<dyn Error>> {
278+
fn test_try_merge_partman() -> Result<(), Error> {
281279
// Test the real-world pg_partman JSON with a patch to build the expected
282280
// v2 JSON. First, load the original metadata.
283281
let original_meta = json!({
@@ -410,7 +408,7 @@ fn test_try_merge_partman() -> Result<(), Box<dyn Error>> {
410408
Err(e) => panic!("patching part man failed: {e}"),
411409
Ok(dist) => {
412410
// Convert the Distributions object to JSON.
413-
let output: Result<Value, Box<dyn Error>> = dist.try_into();
411+
let output: Result<Value, Error> = dist.try_into();
414412
match output {
415413
Err(e) => panic!("partman serialization failed: {e}"),
416414
Ok(val) => {
@@ -1336,7 +1334,7 @@ fn test_artifact() {
13361334
}
13371335

13381336
#[test]
1339-
fn test_distribution() -> Result<(), Box<dyn Error>> {
1337+
fn test_distribution() -> Result<(), Error> {
13401338
let dir: PathBuf = [env!("CARGO_MANIFEST_DIR"), "corpus", "v2"]
13411339
.iter()
13421340
.collect();

0 commit comments

Comments
 (0)