1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
use std::{
borrow::Cow,
env, fs,
path::{Path, PathBuf},
str::FromStr,
};
use anyhow::{Context, Error, Result};
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Source {
String(String),
Local(PathBuf),
}
impl Source {
pub fn parse<S>(source: S) -> Result<Self, Error>
where
S: AsRef<str>,
{
let source = source.as_ref().trim();
if source.starts_with('{') || source.starts_with('[') || source.starts_with('\n') {
return Ok(Source::String(source.to_owned()));
}
let root = env::current_dir()?.canonicalize()?;
Ok(Source::with_root(root, source))
}
fn with_root<P, S>(root: P, source: S) -> Self
where
P: AsRef<Path>,
S: AsRef<str>,
{
Source::local(root.as_ref().join(source.as_ref()))
}
fn local<P>(path: P) -> Self
where
P: AsRef<Path>,
{
Source::Local(path.as_ref().into())
}
pub fn get(&self) -> Result<String> {
match self {
Source::Local(path) => get_local_contract(path),
Source::String(abi) => Ok(abi.clone()),
}
}
}
fn get_local_contract(path: &Path) -> Result<String> {
let path = if path.is_relative() {
let absolute_path = path.canonicalize().with_context(|| {
format!(
"unable to canonicalize file from working dir {} with path {}",
env::current_dir()
.map(|cwd| cwd.display().to_string())
.unwrap_or_else(|err| format!("??? ({})", err)),
path.display(),
)
})?;
Cow::Owned(absolute_path)
} else {
Cow::Borrowed(path)
};
let json = fs::read_to_string(&path).context(format!(
"failed to read artifact JSON file with path {}",
&path.display()
))?;
Ok(json)
}
impl FromStr for Source {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
Source::parse(s)
}
}