Skip to content

Commit f45af7b

Browse files
committed
Refactor with() to Process::run()
1 parent e7ee377 commit f45af7b

File tree

10 files changed

+81
-78
lines changed

10 files changed

+81
-78
lines changed

src/bin/rustup-init.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,14 @@ use rustup::cli::self_update;
2828
use rustup::cli::setup_mode;
2929
use rustup::env_var::RUST_RECURSION_COUNT_MAX;
3030
use rustup::is_proxyable_tools;
31-
use rustup::process::{with, Process};
31+
use rustup::process::Process;
3232
use rustup::utils::utils;
3333

3434
fn main() {
3535
#[cfg(windows)]
3636
pre_rustup_main_init();
3737

38-
let process = Process::os();
39-
with(process, || match maybe_trace_rustup() {
38+
Process::os().run(|| match maybe_trace_rustup() {
4039
Err(e) => {
4140
common::report_error(&e);
4241
std::process::exit(1);

src/cli/self_update.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1306,18 +1306,19 @@ mod tests {
13061306
use crate::cli::common;
13071307
use crate::dist::dist::PartialToolchainDesc;
13081308
use crate::test::{test_dir, with_rustup_home, Env};
1309-
use crate::{for_host, process};
1309+
use crate::{for_host, process::TestProcess};
13101310

13111311
#[test]
13121312
fn default_toolchain_is_stable() {
13131313
with_rustup_home(|home| {
13141314
let mut vars = HashMap::new();
13151315
home.apply(&mut vars);
1316-
let tp = process::TestProcess {
1316+
let tp = TestProcess {
13171317
vars,
13181318
..Default::default()
13191319
};
1320-
process::with(tp.clone().into(), || -> Result<()> {
1320+
1321+
tp.clone().run(|| -> Result<()> {
13211322
// TODO: we could pass in a custom cfg to get notification
13221323
// callbacks rather than output to the tp sink.
13231324
let mut cfg = common::set_globals(false, false).unwrap();
@@ -1339,8 +1340,10 @@ mod tests {
13391340
.unwrap() // result
13401341
.unwrap() // option
13411342
);
1343+
13421344
Ok(())
13431345
})?;
1346+
13441347
assert_eq!(
13451348
for_host!(
13461349
r"info: profile set to 'default'
@@ -1360,11 +1363,12 @@ info: default host triple is {0}
13601363
let cargo_home = root_dir.path().join("cargo");
13611364
let mut vars = HashMap::new();
13621365
vars.env("CARGO_HOME", cargo_home.to_string_lossy().to_string());
1363-
let tp = process::TestProcess {
1366+
let tp = TestProcess {
13641367
vars,
13651368
..Default::default()
13661369
};
1367-
process::with(tp.into(), || -> Result<()> {
1370+
1371+
tp.run(|| -> Result<()> {
13681372
super::install_bins().unwrap();
13691373
Ok(())
13701374
})

src/cli/self_update/windows.rs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use super::common;
1313
use super::{install_bins, InstallOpts};
1414
use crate::cli::download_tracker::DownloadTracker;
1515
use crate::dist::dist::TargetTriple;
16-
use crate::process::{self, Process};
16+
use crate::process::Process;
1717
use crate::utils::utils;
1818
use crate::utils::Notification;
1919

@@ -712,7 +712,8 @@ mod tests {
712712

713713
use rustup_macros::unit_test as test;
714714

715-
use crate::process;
715+
#[cfg(feature = "test")]
716+
use crate::process::TestProcess;
716717
use crate::test::with_saved_path;
717718

718719
fn wide(str: &str) -> Vec<u16> {
@@ -753,9 +754,9 @@ mod tests {
753754
#[test]
754755
fn windows_path_regkey_type() {
755756
// per issue #261, setting PATH should use REG_EXPAND_SZ.
756-
let tp = process::TestProcess::default();
757+
let tp = TestProcess::default();
757758
with_saved_path(&mut || {
758-
process::with(tp.clone().into(), || {
759+
tp.clone().run(|| {
759760
let root = RegKey::predef(HKEY_CURRENT_USER);
760761
let environment = root
761762
.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
@@ -783,9 +784,9 @@ mod tests {
783784
use std::io;
784785
// during uninstall the PATH key may end up empty; if so we should
785786
// delete it.
786-
let tp = process::TestProcess::default();
787+
let tp = TestProcess::default();
787788
with_saved_path(&mut || {
788-
process::with(tp.clone().into(), || {
789+
tp.clone().run(|| {
789790
let root = RegKey::predef(HKEY_CURRENT_USER);
790791
let environment = root
791792
.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
@@ -818,15 +819,15 @@ mod tests {
818819
#[test]
819820
fn windows_doesnt_mess_with_a_non_string_path() {
820821
// This writes an error, so we want a sink for it.
821-
let tp = process::TestProcess {
822+
let tp = TestProcess {
822823
vars: [("HOME".to_string(), "/unused".to_string())]
823824
.iter()
824825
.cloned()
825826
.collect(),
826827
..Default::default()
827828
};
828829
with_saved_path(&mut || {
829-
process::with(tp.clone().into(), || {
830+
tp.clone().run(|| {
830831
let root = RegKey::predef(HKEY_CURRENT_USER);
831832
let environment = root
832833
.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
@@ -853,9 +854,9 @@ mod tests {
853854
#[test]
854855
fn windows_treat_missing_path_as_empty() {
855856
// during install the PATH key may be missing; treat it as empty
856-
let tp = process::TestProcess::default();
857+
let tp = TestProcess::default();
857858
with_saved_path(&mut || {
858-
process::with(tp.clone().into(), || {
859+
tp.clone().run({
859860
let root = RegKey::predef(HKEY_CURRENT_USER);
860861
let environment = root
861862
.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)

src/diskio/test.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustup_macros::unit_test as test;
77
use crate::test::test_dir;
88

99
use super::{get_executor, Executor, Item, Kind};
10-
use crate::process;
10+
use crate::process::TestProcess;
1111

1212
impl Item {
1313
/// The length of the file, for files (for stats)
@@ -23,11 +23,11 @@ fn test_incremental_file(io_threads: &str) -> Result<()> {
2323
let work_dir = test_dir()?;
2424
let mut vars = HashMap::new();
2525
vars.insert("RUSTUP_IO_THREADS".to_string(), io_threads.to_string());
26-
let tp = process::TestProcess {
26+
TestProcess {
2727
vars,
2828
..Default::default()
29-
};
30-
process::with(tp.into(), || -> Result<()> {
29+
}
30+
.run(|| -> Result<()> {
3131
let mut written = 0;
3232
let mut file_finished = false;
3333
let mut io_executor: Box<dyn Executor> = get_executor(None, 32 * 1024 * 1024)?;
@@ -96,11 +96,11 @@ fn test_complete_file(io_threads: &str) -> Result<()> {
9696
let work_dir = test_dir()?;
9797
let mut vars = HashMap::new();
9898
vars.insert("RUSTUP_IO_THREADS".to_string(), io_threads.to_string());
99-
let tp = process::TestProcess {
99+
TestProcess {
100100
vars,
101101
..Default::default()
102-
};
103-
process::with(tp.into(), || -> Result<()> {
102+
}
103+
.run(|| -> Result<()> {
104104
let mut io_executor: Box<dyn Executor> = get_executor(None, 32 * 1024 * 1024)?;
105105
let mut chunk = io_executor.get_buffer(10);
106106
chunk.extend(b"0123456789");

src/dist/manifestation/tests.rs

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use crate::{
2525
temp, Notification,
2626
},
2727
errors::RustupError,
28-
process,
28+
process::TestProcess,
2929
test::mock::{dist::*, MockComponentBuilder, MockFile, MockInstallerBuilder},
3030
utils::{raw as utils_raw, utils},
3131
};
@@ -556,16 +556,13 @@ fn setup_from_dist_server(
556556
},
557557
};
558558

559-
process::with(
560-
process::TestProcess::new(
561-
env::current_dir().unwrap(),
562-
&["rustup"],
563-
HashMap::default(),
564-
"",
565-
)
566-
.into(),
567-
|| f(url, &toolchain, &prefix, &download_cfg, &tmp_cx),
568-
);
559+
TestProcess::new(
560+
env::current_dir().unwrap(),
561+
&["rustup"],
562+
HashMap::default(),
563+
"",
564+
)
565+
.run(|| f(url, &toolchain, &prefix, &download_cfg, &tmp_cx));
569566
}
570567

571568
fn initial_install(comps: Compressions) {

src/env_var.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ mod tests {
4444
use rustup_macros::unit_test as test;
4545

4646
use super::*;
47-
use crate::process;
47+
use crate::process::TestProcess;
4848
use crate::test::{with_saved_path, Env};
4949

5050
#[test]
@@ -54,12 +54,12 @@ mod tests {
5454
"PATH",
5555
env::join_paths(["/home/a/.cargo/bin", "/home/b/.cargo/bin"].iter()).unwrap(),
5656
);
57-
let tp = process::TestProcess {
57+
let tp = TestProcess {
5858
vars,
5959
..Default::default()
6060
};
6161
with_saved_path(&mut || {
62-
process::with(tp.clone().into(), || {
62+
tp.clone().run(|| {
6363
let mut path_entries = vec![];
6464
let mut cmd = Command::new("test");
6565

src/process/mod.rs

Lines changed: 32 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,30 @@ impl Process {
4646
})
4747
}
4848

49+
/// Run a function in the context of a process definition.
50+
///
51+
/// If the function panics, the process definition *in that thread* is cleared
52+
/// by an implicitly installed global panic hook.
53+
pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
54+
HOOK_INSTALLED.call_once(|| {
55+
let orig_hook = panic::take_hook();
56+
panic::set_hook(Box::new(move |info| {
57+
clear_process();
58+
orig_hook(info);
59+
}));
60+
});
61+
62+
PROCESS.with(|p| {
63+
if let Some(old_p) = &*p.borrow() {
64+
panic!("current process already set {old_p:?}");
65+
}
66+
*p.borrow_mut() = Some(self);
67+
let result = f();
68+
*p.borrow_mut() = None;
69+
result
70+
})
71+
}
72+
4973
pub fn name(&self) -> Option<String> {
5074
let arg0 = match self.var("RUSTUP_FORCE_ARG0") {
5175
Ok(v) => Some(v),
@@ -171,33 +195,6 @@ impl From<TestProcess> for Process {
171195

172196
static HOOK_INSTALLED: Once = Once::new();
173197

174-
/// Run a function in the context of a process definition.
175-
///
176-
/// If the function panics, the process definition *in that thread* is cleared
177-
/// by an implicitly installed global panic hook.
178-
pub fn with<F, R>(process: Process, f: F) -> R
179-
where
180-
F: FnOnce() -> R,
181-
{
182-
HOOK_INSTALLED.call_once(|| {
183-
let orig_hook = panic::take_hook();
184-
panic::set_hook(Box::new(move |info| {
185-
clear_process();
186-
orig_hook(info);
187-
}));
188-
});
189-
190-
PROCESS.with(|p| {
191-
if let Some(old_p) = &*p.borrow() {
192-
panic!("current process already set {old_p:?}");
193-
}
194-
*p.borrow_mut() = Some(process);
195-
let result = f();
196-
*p.borrow_mut() = None;
197-
result
198-
})
199-
}
200-
201198
/// Internal - for the panic hook only
202199
fn clear_process() {
203200
PROCESS.with(|p| p.replace(None));
@@ -246,6 +243,11 @@ impl TestProcess {
246243
stderr: Arc::new(Mutex::new(Vec::new())),
247244
}
248245
}
246+
247+
pub(crate) fn run<R>(self, f: impl FnOnce() -> R) -> R {
248+
Process::from(self).run(f)
249+
}
250+
249251
fn new_id() -> u64 {
250252
let low_bits: u64 = std::process::id() as u64;
251253
let mut rng = thread_rng();
@@ -277,7 +279,7 @@ mod tests {
277279

278280
use rustup_macros::unit_test as test;
279281

280-
use super::{with, Process, TestProcess};
282+
use super::{Process, TestProcess};
281283

282284
#[test]
283285
fn test_instance() {
@@ -287,7 +289,8 @@ mod tests {
287289
HashMap::default(),
288290
"",
289291
);
290-
with(proc.clone().into(), || {
292+
293+
proc.clone().run(|| {
291294
let cur = Process::get();
292295
assert_eq!(proc.id, cur.id(), "{:?} != {:?}", proc, cur)
293296
});

src/process/terminalsource.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -251,11 +251,11 @@ mod tests {
251251
fn assert_color_choice(env_val: &str, stream: StreamSelector, color_choice: ColorChoice) {
252252
let mut vars = HashMap::new();
253253
vars.env("RUSTUP_TERM_COLOR", env_val);
254-
let tp = process::TestProcess {
254+
process::TestProcess {
255255
vars,
256256
..Default::default()
257-
};
258-
process::with(tp.into(), || {
257+
}
258+
.run(|| {
259259
let term = ColorableTerminal::new(stream);
260260
let inner = term.inner.lock().unwrap();
261261
assert!(matches!(

src/test.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use anyhow::Result;
1717

1818
pub use crate::cli::self_update::test::{get_path, with_saved_path};
1919
use crate::dist::dist::TargetTriple;
20-
use crate::process;
20+
use crate::process::TestProcess;
2121

2222
// Things that can have environment variables applied to them.
2323
pub trait Env {
@@ -124,8 +124,7 @@ pub fn this_host_triple() -> String {
124124
// For windows, this host may be different to the target: we may be
125125
// building with i686 toolchain, but on an x86_64 host, so run the
126126
// actual detection logic and trust it.
127-
let tp = process::TestProcess::default();
128-
return process::with(tp.into(), || TargetTriple::from_host().unwrap().to_string());
127+
return TestProcess::default().run(|| TargetTriple::from_host().unwrap().to_string());
129128
}
130129
let arch = if cfg!(target_arch = "x86") {
131130
"i686"

src/test/mock/clitools.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use once_cell::sync::Lazy;
1919
use url::Url;
2020

2121
use crate::cli::rustup_mode;
22-
use crate::process;
22+
use crate::process::TestProcess;
2323
use crate::test as rustup_test;
2424
use crate::test::const_dist_dir;
2525
use crate::test::this_host_triple;
@@ -721,13 +721,13 @@ impl Config {
721721
.into_boxed_str(),
722722
);
723723
}
724-
let tp = process::TestProcess::new(&*self.workdir.borrow(), &arg_strings, vars, "");
725-
let process_res = process::with(tp.clone().into(), rustup_mode::main);
724+
let tp = TestProcess::new(&*self.workdir.borrow(), &arg_strings, vars, "");
725+
let process_res = tp.clone().run(rustup_mode::main);
726726
// convert Err's into an ec
727727
let ec = match process_res {
728728
Ok(process_res) => process_res,
729729
Err(e) => {
730-
process::with(tp.clone().into(), || crate::cli::common::report_error(&e));
730+
tp.clone().run(|| crate::cli::common::report_error(&e));
731731
utils::ExitCode(1)
732732
}
733733
};

0 commit comments

Comments
 (0)