-
Notifications
You must be signed in to change notification settings - Fork 15
/
subcommand.rs
253 lines (212 loc) · 7.78 KB
/
subcommand.rs
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use std::env::ArgsOs;
use std::ffi::OsString;
use std::fmt;
use std::io;
use std::str::FromStr;
use anyhow::Context as _;
use digest::Digest as _;
use sha2::Sha256;
use thiserror::Error;
use crate::config::parse_file;
use crate::config::REQUIRED_HEADER;
use crate::default_provider_factory::DefaultProviderFactory;
use crate::dotslash_cache::DotslashCache;
use crate::download::download_artifact;
use crate::locate::locate_artifact;
use crate::platform::SUPPORTED_PLATFORM;
use crate::print_entry_for_url::print_entry_for_url;
use crate::util;
use crate::util::fs_ctx;
#[derive(Debug)]
pub enum Subcommand {
/// Similar to running `b3sum`, though takes exactly one argument and prints
/// only the hash
B3Sum,
/// Clean the cache directory
Clean,
/// Create a the artifact entry for DotSlash file from a URL
CreateUrlEntry,
/// Print the cache directory
CacheDir,
/// Fetch and cache an artifact but do not execute it
Fetch,
/// Parse a DotSlash file and print its data as JSON
Parse,
/// Similar to running `shasum -a 256`, though takes exactly one argument
/// and prints only the hash
Sha256,
/// Version
Version,
/// Help
Help,
}
impl fmt::Display for Subcommand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::B3Sum => "b3sum",
Self::Clean => "clean",
Self::CreateUrlEntry => "create-url-entry",
Self::CacheDir => "cache-dir",
Self::Fetch => "fetch",
Self::Parse => "parse",
Self::Sha256 => "sha256",
Self::Version => "version",
Self::Help => "help",
})
}
}
impl FromStr for Subcommand {
type Err = SubcommandError;
fn from_str(name: &str) -> Result<Self, Self::Err> {
match name {
"b3sum" => Ok(Subcommand::B3Sum),
"clean" => Ok(Subcommand::Clean),
"create-url-entry" => Ok(Subcommand::CreateUrlEntry),
"cache-dir" => Ok(Subcommand::CacheDir),
"fetch" => Ok(Subcommand::Fetch),
"parse" => Ok(Subcommand::Parse),
"sha256" => Ok(Subcommand::Sha256),
"version" => Ok(Subcommand::Version),
"help" => Ok(Subcommand::Help),
_ => Err(SubcommandError::UnknownCommand(name.to_owned())),
}
}
}
#[derive(Error, Debug)]
pub enum SubcommandError {
#[error(
"no subcommand passed to '--'
See `dotslash --help` for more information."
)]
MissingCommand,
#[error(
"unknown subcommand passed to '--': `{0}`
See `dotslash --help` for more information."
)]
UnknownCommand(String),
#[error("'{0}' command failed")]
Other(Subcommand, #[source] anyhow::Error),
}
pub fn run_subcommand(subcommand: Subcommand, args: &mut ArgsOs) -> Result<(), SubcommandError> {
_run_subcommand(&subcommand, args).map_err(|x| SubcommandError::Other(subcommand, x))
}
fn _run_subcommand(subcommand: &Subcommand, args: &mut ArgsOs) -> anyhow::Result<()> {
match subcommand {
Subcommand::B3Sum => {
let file_arg = take_exactly_one_arg(args)?;
// TODO: read from stdin if file_arg is `-`
let mut file = fs_ctx::file_open(file_arg)?;
let mut hasher = blake3::Hasher::new();
io::copy(&mut file, &mut hasher)?;
let hex_digest = format!("{:x}", hasher.finalize());
println!("{}", hex_digest);
}
Subcommand::Clean => {
if args.next().is_some() {
return Err(anyhow::format_err!(
"expected no arguments but received some",
));
}
let dotslash_cache = DotslashCache::new();
eprintln!("Cleaning `{}`", dotslash_cache.cache_dir().display());
// Make sure nothing is read-only first.
let _ = util::make_tree_entries_writable(dotslash_cache.cache_dir());
// Then delete the contents.
fs_ctx::remove_dir_all(dotslash_cache.cache_dir())?;
}
Subcommand::CreateUrlEntry => {
let url = take_exactly_one_arg(args)?;
print_entry_for_url(&url)?;
}
Subcommand::CacheDir => {
if args.next().is_some() {
return Err(anyhow::format_err!(
"expected no arguments but received some",
));
}
let dotslash_cache = DotslashCache::new();
println!("{}", dotslash_cache.cache_dir().display());
}
Subcommand::Fetch => {
let file_arg = take_exactly_one_arg(args)?;
let dotslash_data = fs_ctx::read_to_string(file_arg)?;
let dotslash_cache = DotslashCache::new();
let (artifact_entry, artifact_location) =
locate_artifact(&dotslash_data, &dotslash_cache)?;
if !artifact_location.executable.exists() {
let provider_factory = DefaultProviderFactory {};
download_artifact(&artifact_entry, &artifact_location, &provider_factory)?;
}
println!("{}", artifact_location.executable.display());
}
Subcommand::Parse => {
let file_arg = take_exactly_one_arg(args)?;
let dotslash_data = fs_ctx::read_to_string(file_arg)?;
let (original_json, _config_file) =
parse_file(&dotslash_data).context("failed to parse file")?;
let json =
serde_jsonrc::to_string(&original_json).context("failed to serialize value")?;
println!("{json}");
}
Subcommand::Version => {
if args.next().is_some() {
return Err(anyhow::format_err!(
"expected no arguments but received some",
));
}
println!("DotSlash {}", env!("CARGO_PKG_VERSION"));
}
Subcommand::Help => {
if args.next().is_some() {
return Err(anyhow::format_err!(
"expected no arguments but received some",
));
}
eprint!(
r##"usage: dotslash DOTSLASH_FILE [OPTIONS]
DOTSLASH_FILE must be a file that starts with `{}`
and contains a JSON body tells DotSlash how to fetch and run the executable
that DOTSLASH_FILE represents.
All OPTIONS will be forwarded directly to the executable identified by
DOTSLASH_FILE.
Supported platform: {}
Your DotSlash cache is: {}
Learn more at {}
"##,
REQUIRED_HEADER,
SUPPORTED_PLATFORM,
DotslashCache::new().cache_dir().display(),
env!("CARGO_PKG_HOMEPAGE"),
);
}
Subcommand::Sha256 => {
let file_arg = take_exactly_one_arg(args)?;
// TODO: read from stdin if file_arg is `-`
let mut file = fs_ctx::file_open(file_arg)?;
let mut hasher = Sha256::new();
io::copy(&mut file, &mut hasher)?;
let hex_digest = format!("{:x}", hasher.finalize());
println!("{}", hex_digest);
}
};
Ok(())
}
fn take_exactly_one_arg(args: &mut ArgsOs) -> anyhow::Result<OsString> {
match (args.next(), args.next()) {
(None, _) => Err(anyhow::format_err!(
"expected exactly one argument but received none"
)),
(Some(_), Some(_)) => Err(anyhow::format_err!(
"expected exactly one argument but received more"
)),
(Some(arg), None) => Ok(arg),
}
}