Skip to content

Commit b11a124

Browse files
Fix clippy warnings and cargo fmt formatting
- Fix dead_code warnings: allow unused Warn variant and warn() method - Fix useless .into() conversion in logging JSON output - Fix manual Range::contains in fetch status check - Fix unit let-binding in command execution - Fix lines().flatten() -> lines().map_while(Result::ok) - Apply cargo fmt to all source files
1 parent fa6bc6b commit b11a124

11 files changed

Lines changed: 293 additions & 97 deletions

File tree

src/cmd/exec.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@ pub fn run(log: &Logger, args: &[String], workdir: &str) -> Result<(), String> {
44
return Err("command is required after \"--\"".into());
55
}
66
log.info("executing command", &[("command", &args[0])]);
7-
let dir = if workdir.is_empty() { None } else { Some(workdir) };
7+
let dir = if workdir.is_empty() {
8+
None
9+
} else {
10+
Some(workdir)
11+
};
812
let exit_code = super::run_command_in_dir(log, args, dir)?;
913
if exit_code != 0 {
1014
return Err(format!("command exited with code {}", exit_code));

src/cmd/fetch.rs

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,12 @@ pub struct Config {
1616
}
1717
impl Config {
1818
pub fn validate(&self) -> Result<(), String> {
19-
if self.url.is_empty() { return Err("--url is required".into()); }
20-
if self.output.is_empty() { return Err("--output is required".into()); }
19+
if self.url.is_empty() {
20+
return Err("--url is required".into());
21+
}
22+
if self.output.is_empty() {
23+
return Err("--output is required".into());
24+
}
2125
if self.allow_cross_site_redirects && !self.follow_redirects {
2226
return Err("--allow-cross-site-redirects requires --follow-redirects".into());
2327
}
@@ -36,7 +40,14 @@ pub fn run(log: &Logger, cfg: &Config, retry_cfg: &retry::Config) -> Result<(),
3640
log.error("fetch failed", &[("url", &cfg.url), ("error", &e)]);
3741
return Err(format!("fetch {} failed: {}", cfg.url, e));
3842
}
39-
log.info("fetch completed", &[("url", &cfg.url), ("output", &cfg.output), ("attempts", &format!("{}", result.attempt + 1))]);
43+
log.info(
44+
"fetch completed",
45+
&[
46+
("url", &cfg.url),
47+
("output", &cfg.output),
48+
("attempts", &format!("{}", result.attempt + 1)),
49+
],
50+
);
4051
Ok(())
4152
}
4253
fn do_fetch(cfg: &Config) -> Result<(), String> {
@@ -45,7 +56,8 @@ fn do_fetch(cfg: &Config) -> Result<(), String> {
4556
use std::sync::Arc;
4657
let crypto_provider = rustls::crypto::ring::default_provider();
4758
let tls_config = rustls::ClientConfig::builder_with_provider(Arc::new(crypto_provider))
48-
.with_safe_default_protocol_versions().unwrap()
59+
.with_safe_default_protocol_versions()
60+
.unwrap()
4961
.dangerous()
5062
.with_custom_certificate_verifier(Arc::new(super::wait_for::NoVerifier))
5163
.with_no_client_auth();
@@ -65,17 +77,23 @@ fn do_fetch(cfg: &Config) -> Result<(), String> {
6577
let auth_val = std::env::var(&cfg.auth_env)
6678
.map_err(|_| format!("auth env var {:?} is empty or not set", cfg.auth_env))?;
6779
if auth_val.is_empty() {
68-
return Err(format!("auth env var {:?} is empty or not set", cfg.auth_env));
80+
return Err(format!(
81+
"auth env var {:?} is empty or not set",
82+
cfg.auth_env
83+
));
6984
}
7085
req = req.set("Authorization", &auth_val);
7186
}
72-
let resp = req.call().map_err(|e| format!("HTTP request to {}: {}", cfg.url, e))?;
87+
let resp = req
88+
.call()
89+
.map_err(|e| format!("HTTP request to {}: {}", cfg.url, e))?;
7390
let status = resp.status();
74-
if status < 200 || status >= 300 {
91+
if !(200..300).contains(&status) {
7592
return Err(format!("HTTP {} returned status {}", cfg.url, status));
7693
}
7794
let mut body = Vec::new();
78-
resp.into_reader().read_to_end(&mut body)
95+
resp.into_reader()
96+
.read_to_end(&mut body)
7997
.map_err(|e| format!("reading response body: {}", e))?;
8098
if let Some(parent) = out_path.parent() {
8199
fs::create_dir_all(parent).map_err(|e| format!("creating output directory: {}", e))?;

src/cmd/migrate.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@ pub fn run(log: &Logger, args: &[String], workdir: &str, lock_file: &str) -> Res
88
if !lock_file.is_empty() {
99
let lock_path = safety::validate_file_path(workdir, lock_file)?;
1010
if lock_path.exists() {
11-
log.info("lock file exists, skipping migration", &[("lock-file", lock_path.to_str().unwrap_or(""))]);
11+
log.info(
12+
"lock file exists, skipping migration",
13+
&[("lock-file", lock_path.to_str().unwrap_or(""))],
14+
);
1215
return Ok(());
1316
}
1417
}
@@ -20,8 +23,12 @@ pub fn run(log: &Logger, args: &[String], workdir: &str, lock_file: &str) -> Res
2023
if !lock_file.is_empty() {
2124
let lock_path = safety::validate_file_path(workdir, lock_file)?;
2225
fs::create_dir_all(workdir).map_err(|e| format!("creating workdir {}: {}", workdir, e))?;
23-
fs::write(&lock_path, "migrated\n").map_err(|e| format!("writing lock file {:?}: {}", lock_path, e))?;
24-
log.info("lock file created", &[("lock-file", lock_path.to_str().unwrap_or(""))]);
26+
fs::write(&lock_path, "migrated\n")
27+
.map_err(|e| format!("writing lock file {:?}: {}", lock_path, e))?;
28+
log.info(
29+
"lock file created",
30+
&[("lock-file", lock_path.to_str().unwrap_or(""))],
31+
);
2532
}
2633
log.info("migration completed successfully", &[]);
2734
Ok(())

src/cmd/mod.rs

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
pub mod wait_for;
1+
pub mod exec;
2+
pub mod fetch;
23
pub mod migrate;
3-
pub mod seed;
44
pub mod render;
5-
pub mod fetch;
6-
pub mod exec;
5+
pub mod seed;
6+
pub mod wait_for;
7+
use crate::logging::Logger;
78
use std::io::{BufRead, BufReader, Read};
89
use std::process::Command;
9-
use crate::logging::Logger;
1010
pub fn run_command(log: &Logger, args: &[String]) -> Result<i32, String> {
1111
run_command_in_dir(log, args, None)
1212
}
@@ -19,28 +19,33 @@ pub fn run_command_in_dir(log: &Logger, args: &[String], dir: Option<&str>) -> R
1919
cmd.stdin(std::process::Stdio::null());
2020
cmd.stdout(std::process::Stdio::piped());
2121
cmd.stderr(std::process::Stdio::piped());
22-
let mut child = cmd.spawn().map_err(|e| format!("starting command {:?}: {}", args[0], e))?;
22+
let mut child = cmd
23+
.spawn()
24+
.map_err(|e| format!("starting command {:?}: {}", args[0], e))?;
2325
let stdout = child.stdout.take();
2426
let stderr = child.stderr.take();
25-
let log_stdout = std::thread::scope(|s| {
27+
std::thread::scope(|s| {
2628
let h1 = s.spawn(|| {
27-
if let Some(r) = stdout { stream_lines(log, r, "stdout"); }
29+
if let Some(r) = stdout {
30+
stream_lines(log, r, "stdout");
31+
}
2832
});
2933
let h2 = s.spawn(|| {
30-
if let Some(r) = stderr { stream_lines(log, r, "stderr"); }
34+
if let Some(r) = stderr {
35+
stream_lines(log, r, "stderr");
36+
}
3137
});
3238
h1.join().ok();
3339
h2.join().ok();
3440
});
35-
let _ = log_stdout;
36-
let status = child.wait().map_err(|e| format!("waiting for command: {}", e))?;
41+
let status = child
42+
.wait()
43+
.map_err(|e| format!("waiting for command: {}", e))?;
3744
Ok(status.code().unwrap_or(-1))
3845
}
3946
fn stream_lines<R: Read>(log: &Logger, reader: R, stream: &str) {
4047
let buf = BufReader::new(reader);
41-
for line in buf.lines() {
42-
if let Ok(l) = line {
43-
log.info(&l, &[("stream", stream)]);
44-
}
48+
for l in buf.lines().map_while(Result::ok) {
49+
log.info(&l, &[("stream", stream)]);
4550
}
4651
}

src/cmd/render.rs

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,40 @@
11
use crate::logging::Logger;
2-
use crate::safety;
32
use crate::render as render_lib;
3+
use crate::safety;
44
use std::fs;
55

6-
pub fn run(log: &Logger, template: &str, output: &str, workdir: &str, mode: &str) -> Result<(), String> {
6+
pub fn run(
7+
log: &Logger,
8+
template: &str,
9+
output: &str,
10+
workdir: &str,
11+
mode: &str,
12+
) -> Result<(), String> {
713
if template.is_empty() {
814
return Err("--template is required".into());
915
}
1016
if output.is_empty() {
1117
return Err("--output is required".into());
1218
}
1319
if mode != "envsubst" && mode != "gotemplate" {
14-
return Err(format!("--mode must be envsubst or gotemplate, got {:?}", mode));
20+
return Err(format!(
21+
"--mode must be envsubst or gotemplate, got {:?}",
22+
mode
23+
));
1524
}
1625

1726
let out_path = safety::validate_file_path(workdir, output)?;
18-
let data = fs::read_to_string(template).map_err(|e| format!("reading template {}: {}", template, e))?;
27+
let data = fs::read_to_string(template)
28+
.map_err(|e| format!("reading template {}: {}", template, e))?;
1929

20-
log.info("rendering template", &[("template", template), ("output", out_path.to_str().unwrap_or("")), ("mode", mode)]);
30+
log.info(
31+
"rendering template",
32+
&[
33+
("template", template),
34+
("output", out_path.to_str().unwrap_or("")),
35+
("mode", mode),
36+
],
37+
);
2138

2239
let result = match mode {
2340
"envsubst" => render_lib::envsubst(&data),
@@ -29,6 +46,9 @@ pub fn run(log: &Logger, template: &str, output: &str, workdir: &str, mode: &str
2946
fs::create_dir_all(parent).map_err(|e| format!("creating output directory: {}", e))?;
3047
}
3148
fs::write(&out_path, result).map_err(|e| format!("writing output {:?}: {}", out_path, e))?;
32-
log.info("render completed", &[("output", out_path.to_str().unwrap_or(""))]);
49+
log.info(
50+
"render completed",
51+
&[("output", out_path.to_str().unwrap_or(""))],
52+
);
3353
Ok(())
3454
}

src/cmd/wait_for.rs

Lines changed: 60 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,39 +2,63 @@ use crate::logging::Logger;
22
use crate::retry;
33
use std::net::TcpStream;
44
use std::time::{Duration, Instant};
5-
pub fn run(log: &Logger, targets: &[String], cfg: &retry::Config, timeout: Duration,
6-
http_status: u16, insecure_tls: bool) -> Result<(), String> {
5+
pub fn run(
6+
log: &Logger,
7+
targets: &[String],
8+
cfg: &retry::Config,
9+
timeout: Duration,
10+
http_status: u16,
11+
insecure_tls: bool,
12+
) -> Result<(), String> {
713
if targets.is_empty() {
814
return Err("at least one --target is required".into());
915
}
1016
let deadline = Instant::now() + timeout;
1117
for target in targets {
1218
log.info("waiting for target", &[("target", target)]);
1319
let result = retry::do_retry(cfg, Some(deadline), |attempt| {
14-
log.debug("attempt", &[("target", target), ("attempt", &format!("{}", attempt + 1))]);
20+
log.debug(
21+
"attempt",
22+
&[("target", target), ("attempt", &format!("{}", attempt + 1))],
23+
);
1524
check_target(target, http_status, insecure_tls, timeout)
1625
});
1726
if let Some(e) = result.err {
1827
log.error("target not reachable", &[("target", target), ("error", &e)]);
1928
return Err(format!("target {} not reachable: {}", target, e));
2029
}
21-
log.info("target is reachable", &[("target", target), ("attempts", &format!("{}", result.attempt + 1))]);
30+
log.info(
31+
"target is reachable",
32+
&[
33+
("target", target),
34+
("attempts", &format!("{}", result.attempt + 1)),
35+
],
36+
);
2237
}
2338
log.info("all targets reachable", &[]);
2439
Ok(())
2540
}
26-
fn check_target(target: &str, expected_status: u16, insecure_tls: bool, timeout: Duration) -> Result<(), String> {
41+
fn check_target(
42+
target: &str,
43+
expected_status: u16,
44+
insecure_tls: bool,
45+
timeout: Duration,
46+
) -> Result<(), String> {
2747
if let Some(addr) = target.strip_prefix("tcp://") {
2848
check_tcp(addr, timeout)
2949
} else if target.starts_with("http://") || target.starts_with("https://") {
3050
check_http(target, expected_status, insecure_tls, timeout)
3151
} else {
32-
Err(format!("unsupported target scheme in {:?}; use tcp://, http://, or https://", target))
52+
Err(format!(
53+
"unsupported target scheme in {:?}; use tcp://, http://, or https://",
54+
target
55+
))
3356
}
3457
}
3558
fn check_tcp(addr: &str, timeout: Duration) -> Result<(), String> {
3659
let per_req = timeout.min(Duration::from_secs(5));
37-
let addrs: Vec<std::net::SocketAddr> = addr.to_socket_addrs_safe()
60+
let addrs: Vec<std::net::SocketAddr> = addr
61+
.to_socket_addrs_safe()
3862
.map_err(|e| format!("resolving {}: {}", addr, e))?;
3963
if addrs.is_empty() {
4064
return Err(format!("could not resolve {}", addr));
@@ -43,13 +67,19 @@ fn check_tcp(addr: &str, timeout: Duration) -> Result<(), String> {
4367
.map_err(|e| format!("tcp dial {}: {}", addr, e))?;
4468
Ok(())
4569
}
46-
fn check_http(url: &str, expected_status: u16, insecure_tls: bool, timeout: Duration) -> Result<(), String> {
70+
fn check_http(
71+
url: &str,
72+
expected_status: u16,
73+
insecure_tls: bool,
74+
timeout: Duration,
75+
) -> Result<(), String> {
4776
let per_req = timeout.min(Duration::from_secs(5));
4877
let agent = if insecure_tls {
4978
use std::sync::Arc;
5079
let crypto_provider = rustls::crypto::ring::default_provider();
5180
let tls_config = rustls::ClientConfig::builder_with_provider(Arc::new(crypto_provider))
52-
.with_safe_default_protocol_versions().unwrap()
81+
.with_safe_default_protocol_versions()
82+
.unwrap()
5383
.dangerous()
5484
.with_custom_certificate_verifier(Arc::new(NoVerifier))
5585
.with_no_client_auth();
@@ -60,11 +90,16 @@ fn check_http(url: &str, expected_status: u16, insecure_tls: bool, timeout: Dura
6090
} else {
6191
ureq::AgentBuilder::new().timeout(per_req).build()
6292
};
63-
let resp = agent.get(url).call()
93+
let resp = agent
94+
.get(url)
95+
.call()
6496
.map_err(|e| format!("http request to {}: {}", url, e))?;
6597
let status = resp.status();
6698
if status != expected_status {
67-
return Err(format!("http {} returned status {}, expected {}", url, status, expected_status));
99+
return Err(format!(
100+
"http {} returned status {}, expected {}",
101+
url, status, expected_status
102+
));
68103
}
69104
Ok(())
70105
}
@@ -81,25 +116,34 @@ impl ToSocketAddrs for str {
81116
pub struct NoVerifier;
82117
impl rustls::client::danger::ServerCertVerifier for NoVerifier {
83118
fn verify_server_cert(
84-
&self, _: &rustls::pki_types::CertificateDer<'_>, _: &[rustls::pki_types::CertificateDer<'_>],
85-
_: &rustls::pki_types::ServerName<'_>, _: &[u8], _: rustls::pki_types::UnixTime,
119+
&self,
120+
_: &rustls::pki_types::CertificateDer<'_>,
121+
_: &[rustls::pki_types::CertificateDer<'_>],
122+
_: &rustls::pki_types::ServerName<'_>,
123+
_: &[u8],
124+
_: rustls::pki_types::UnixTime,
86125
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
87126
Ok(rustls::client::danger::ServerCertVerified::assertion())
88127
}
89128
fn verify_tls12_signature(
90-
&self, _: &[u8], _: &rustls::pki_types::CertificateDer<'_>,
129+
&self,
130+
_: &[u8],
131+
_: &rustls::pki_types::CertificateDer<'_>,
91132
_: &rustls::DigitallySignedStruct,
92133
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
93134
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
94135
}
95136
fn verify_tls13_signature(
96-
&self, _: &[u8], _: &rustls::pki_types::CertificateDer<'_>,
137+
&self,
138+
_: &[u8],
139+
_: &rustls::pki_types::CertificateDer<'_>,
97140
_: &rustls::DigitallySignedStruct,
98141
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
99142
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
100143
}
101144
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
102145
rustls::crypto::ring::default_provider()
103-
.signature_verification_algorithms.supported_schemes()
146+
.signature_verification_algorithms
147+
.supported_schemes()
104148
}
105149
}

0 commit comments

Comments
 (0)