Skip to content

Commit 85fd286

Browse files
committed
Auto merge of #8124 - ehuss:fs-cleanup, r=Eh2406
Use some fs shorthand functions. This is just some cleanup, using some fs convenience functions that I think make the code more readable. Note: While going through these, I found the `out_dir_is_preserved` test was broken and not doing what it was supposed to.
2 parents f9047dc + 4ae79d2 commit 85fd286

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+668
-1109
lines changed

crates/cargo-test-support/src/git.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,7 @@ use some of the helper functions in this file to interact with the repository.
3939
*/
4040

4141
use crate::{path2url, project, Project, ProjectBuilder};
42-
use std::fs::{self, File};
43-
use std::io::prelude::*;
42+
use std::fs;
4443
use std::path::{Path, PathBuf};
4544
use url::Url;
4645

@@ -81,7 +80,7 @@ impl RepoBuilder {
8180
pub fn nocommit_file(self, path: &str, contents: &str) -> RepoBuilder {
8281
let dst = self.repo.workdir().unwrap().join(path);
8382
t!(fs::create_dir_all(dst.parent().unwrap()));
84-
t!(t!(File::create(&dst)).write_all(contents.as_bytes()));
83+
t!(fs::write(&dst, contents));
8584
self
8685
}
8786

crates/cargo-test-support/src/lib.rs

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,6 @@ use std::env;
112112
use std::ffi::OsStr;
113113
use std::fmt;
114114
use std::fs;
115-
use std::io::prelude::*;
116115
use std::os;
117116
use std::path::{Path, PathBuf};
118117
use std::process::{Command, Output};
@@ -166,11 +165,8 @@ impl FileBuilder {
166165

167166
fn mk(&self) {
168167
self.dirname().mkdir_p();
169-
170-
let mut file = fs::File::create(&self.path)
168+
fs::write(&self.path, &self.body)
171169
.unwrap_or_else(|e| panic!("could not create file {}: {}", self.path.display(), e));
172-
173-
t!(file.write_all(self.body.as_bytes()));
174170
}
175171

176172
fn dirname(&self) -> &Path {
@@ -458,25 +454,15 @@ impl Project {
458454

459455
/// Returns the contents of a path in the project root
460456
pub fn read_file(&self, path: &str) -> String {
461-
let mut buffer = String::new();
462-
fs::File::open(self.root().join(path))
463-
.unwrap()
464-
.read_to_string(&mut buffer)
465-
.unwrap();
466-
buffer
457+
let full = self.root().join(path);
458+
fs::read_to_string(&full)
459+
.unwrap_or_else(|e| panic!("could not read file {}: {}", full.display(), e))
467460
}
468461

469462
/// Modifies `Cargo.toml` to remove all commented lines.
470463
pub fn uncomment_root_manifest(&self) {
471-
let mut contents = String::new();
472-
fs::File::open(self.root().join("Cargo.toml"))
473-
.unwrap()
474-
.read_to_string(&mut contents)
475-
.unwrap();
476-
fs::File::create(self.root().join("Cargo.toml"))
477-
.unwrap()
478-
.write_all(contents.replace("#", "").as_bytes())
479-
.unwrap();
464+
let contents = self.read_file("Cargo.toml").replace("#", "");
465+
fs::write(self.root().join("Cargo.toml"), contents).unwrap();
480466
}
481467

482468
pub fn symlink(&self, src: impl AsRef<Path>, dst: impl AsRef<Path>) {

crates/cargo-test-support/src/registry.rs

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -162,36 +162,37 @@ pub struct Dependency {
162162
pub fn init() {
163163
let config = paths::home().join(".cargo/config");
164164
t!(fs::create_dir_all(config.parent().unwrap()));
165-
if fs::metadata(&config).is_ok() {
165+
if config.exists() {
166166
return;
167167
}
168-
t!(t!(File::create(&config)).write_all(
168+
t!(fs::write(
169+
&config,
169170
format!(
170171
r#"
171-
[source.crates-io]
172-
registry = 'https://wut'
173-
replace-with = 'dummy-registry'
172+
[source.crates-io]
173+
registry = 'https://wut'
174+
replace-with = 'dummy-registry'
174175
175-
[source.dummy-registry]
176-
registry = '{reg}'
176+
[source.dummy-registry]
177+
registry = '{reg}'
177178
178-
[registries.alternative]
179-
index = '{alt}'
180-
"#,
179+
[registries.alternative]
180+
index = '{alt}'
181+
"#,
181182
reg = registry_url(),
182183
alt = alt_registry_url()
183184
)
184-
.as_bytes()
185185
));
186186
let credentials = paths::home().join(".cargo/credentials");
187-
t!(t!(File::create(&credentials)).write_all(
188-
br#"
189-
[registry]
190-
token = "api-token"
191-
192-
[registries.alternative]
193-
token = "api-token"
194-
"#
187+
t!(fs::write(
188+
&credentials,
189+
r#"
190+
[registry]
191+
token = "api-token"
192+
193+
[registries.alternative]
194+
token = "api-token"
195+
"#
195196
));
196197

197198
// Initialize a new registry.
@@ -404,8 +405,7 @@ impl Package {
404405
})
405406
.collect::<Vec<_>>();
406407
let cksum = {
407-
let mut c = Vec::new();
408-
t!(t!(File::open(&self.archive_dst())).read_to_end(&mut c));
408+
let c = t!(fs::read(&self.archive_dst()));
409409
cksum(&c)
410410
};
411411
let name = if self.invalid_json {
@@ -442,10 +442,9 @@ impl Package {
442442
} else {
443443
registry_path.join(&file)
444444
};
445-
let mut prev = String::new();
446-
let _ = File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev));
445+
let prev = fs::read_to_string(&dst).unwrap_or(String::new());
447446
t!(fs::create_dir_all(dst.parent().unwrap()));
448-
t!(t!(File::create(&dst)).write_all((prev + &line[..] + "\n").as_bytes()));
447+
t!(fs::write(&dst, prev + &line[..] + "\n"));
449448

450449
// Add the new file to the index.
451450
if !self.local {

src/bin/cargo/main.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -165,9 +165,7 @@ fn is_executable<P: AsRef<Path>>(path: P) -> bool {
165165
}
166166
#[cfg(windows)]
167167
fn is_executable<P: AsRef<Path>>(path: P) -> bool {
168-
fs::metadata(path)
169-
.map(|metadata| metadata.is_file())
170-
.unwrap_or(false)
168+
path.as_ref().is_file()
171169
}
172170

173171
fn search_directories(config: &Config) -> Vec<PathBuf> {

src/cargo/ops/cargo_new.rs

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -273,10 +273,7 @@ fn detect_source_paths_and_types(
273273
let pp = i.proposed_path;
274274

275275
// path/pp does not exist or is not a file
276-
if !fs::metadata(&path.join(&pp))
277-
.map(|x| x.is_file())
278-
.unwrap_or(false)
279-
{
276+
if !path.join(&pp).is_file() {
280277
continue;
281278
}
282279

@@ -358,7 +355,7 @@ fn plan_new_source_file(bin: bool, package_name: String) -> SourceFileInformatio
358355

359356
pub fn new(opts: &NewOptions, config: &Config) -> CargoResult<()> {
360357
let path = &opts.path;
361-
if fs::metadata(path).is_ok() {
358+
if path.exists() {
362359
anyhow::bail!(
363360
"destination `{}` already exists\n\n\
364361
Use `cargo init` to initialize the directory",
@@ -397,7 +394,7 @@ pub fn init(opts: &NewOptions, config: &Config) -> CargoResult<()> {
397394

398395
let path = &opts.path;
399396

400-
if fs::metadata(&path.join("Cargo.toml")).is_ok() {
397+
if path.join("Cargo.toml").exists() {
401398
anyhow::bail!("`cargo init` cannot be run on existing Cargo packages")
402399
}
403400

@@ -428,22 +425,22 @@ pub fn init(opts: &NewOptions, config: &Config) -> CargoResult<()> {
428425
if version_control == None {
429426
let mut num_detected_vsces = 0;
430427

431-
if fs::metadata(&path.join(".git")).is_ok() {
428+
if path.join(".git").exists() {
432429
version_control = Some(VersionControl::Git);
433430
num_detected_vsces += 1;
434431
}
435432

436-
if fs::metadata(&path.join(".hg")).is_ok() {
433+
if path.join(".hg").exists() {
437434
version_control = Some(VersionControl::Hg);
438435
num_detected_vsces += 1;
439436
}
440437

441-
if fs::metadata(&path.join(".pijul")).is_ok() {
438+
if path.join(".pijul").exists() {
442439
version_control = Some(VersionControl::Pijul);
443440
num_detected_vsces += 1;
444441
}
445442

446-
if fs::metadata(&path.join(".fossil")).is_ok() {
443+
if path.join(".fossil").exists() {
447444
version_control = Some(VersionControl::Fossil);
448445
num_detected_vsces += 1;
449446
}
@@ -743,10 +740,7 @@ mod tests {
743740
"
744741
};
745742

746-
if !fs::metadata(&path_of_source_file)
747-
.map(|x| x.is_file())
748-
.unwrap_or(false)
749-
{
743+
if !path_of_source_file.is_file() {
750744
paths::write(&path_of_source_file, default_file_content)?;
751745

752746
// Format the newly created source file

src/cargo/ops/cargo_read_manifest.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ pub fn read_packages(
6060
}
6161

6262
// Don't automatically discover packages across git submodules
63-
if fs::metadata(&dir.join(".git")).is_ok() {
63+
if dir.join(".git").exists() {
6464
return Ok(false);
6565
}
6666
}

src/cargo/ops/registry.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::collections::{BTreeMap, HashSet};
2-
use std::fs::{self, File};
2+
use std::fs::File;
33
use std::io::{self, BufRead};
44
use std::iter::repeat;
55
use std::str;
@@ -233,7 +233,7 @@ fn transmit(
233233
None => None,
234234
};
235235
if let Some(ref file) = *license_file {
236-
if fs::metadata(&pkg.root().join(file)).is_err() {
236+
if !pkg.root().join(file).exists() {
237237
bail!("the license file `{}` does not exist", file)
238238
}
239239
}

src/cargo/ops/vendor.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@ use anyhow::bail;
88
use serde::Serialize;
99
use std::collections::HashSet;
1010
use std::collections::{BTreeMap, BTreeSet, HashMap};
11-
use std::fs::{self, File};
12-
use std::io::Write;
11+
use std::fs;
1312
use std::path::{Path, PathBuf};
1413

1514
pub struct VendorOptions<'a> {
@@ -223,7 +222,7 @@ fn sync(
223222
"files": map,
224223
});
225224

226-
File::create(&cksum)?.write_all(json.to_string().as_bytes())?;
225+
paths::write(&cksum, json.to_string())?;
227226
}
228227

229228
for path in to_remove {

src/cargo/sources/path.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -373,14 +373,14 @@ impl<'cfg> PathSource<'cfg> {
373373
is_root: bool,
374374
filter: &mut dyn FnMut(&Path) -> CargoResult<bool>,
375375
) -> CargoResult<()> {
376-
if !fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false) {
376+
if !path.is_dir() {
377377
if (*filter)(path)? {
378378
ret.push(path.to_path_buf());
379379
}
380380
return Ok(());
381381
}
382382
// Don't recurse into any sub-packages that we have.
383-
if !is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() {
383+
if !is_root && path.join("Cargo.toml").exists() {
384384
return Ok(());
385385
}
386386

src/cargo/sources/registry/remote.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use lazycell::LazyCell;
99
use log::{debug, trace};
1010
use std::cell::{Cell, Ref, RefCell};
1111
use std::fmt::Write as FmtWrite;
12-
use std::fs::{File, OpenOptions};
12+
use std::fs::{self, File, OpenOptions};
1313
use std::io::prelude::*;
1414
use std::io::SeekFrom;
1515
use std::mem;
@@ -300,10 +300,8 @@ impl<'cfg> RegistryData for RemoteRegistry<'cfg> {
300300

301301
let path = self.cache_path.join(path);
302302
let path = self.config.assert_package_cache_locked(&path);
303-
if let Ok(dst) = File::open(path) {
304-
if let Ok(meta) = dst.metadata() {
305-
return meta.len() > 0;
306-
}
303+
if let Ok(meta) = fs::metadata(path) {
304+
return meta.len() > 0;
307305
}
308306
false
309307
}

src/cargo/util/command_prelude.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ use crate::CargoResult;
1313
use anyhow::bail;
1414
use clap::{self, SubCommand};
1515
use std::ffi::{OsStr, OsString};
16-
use std::fs;
1716
use std::path::PathBuf;
1817

1918
pub use crate::core::compiler::CompileMode;
@@ -285,7 +284,7 @@ pub trait ArgMatchesExt {
285284
if !path.ends_with("Cargo.toml") {
286285
anyhow::bail!("the manifest-path must be a path to a Cargo.toml file")
287286
}
288-
if fs::metadata(&path).is_err() {
287+
if !path.exists() {
289288
anyhow::bail!(
290289
"manifest path `{}` does not exist",
291290
self._value_of("manifest-path").unwrap()

src/cargo/util/config/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -949,8 +949,8 @@ impl Config {
949949
let possible = dir.join(filename_without_extension);
950950
let possible_with_extension = dir.join(format!("{}.toml", filename_without_extension));
951951

952-
if fs::metadata(&possible).is_ok() {
953-
if warn && fs::metadata(&possible_with_extension).is_ok() {
952+
if possible.exists() {
953+
if warn && possible_with_extension.exists() {
954954
// We don't want to print a warning if the version
955955
// without the extension is just a symlink to the version
956956
// WITH an extension, which people may want to do to
@@ -973,7 +973,7 @@ impl Config {
973973
}
974974

975975
Ok(Some(possible))
976-
} else if fs::metadata(&possible_with_extension).is_ok() {
976+
} else if possible_with_extension.exists() {
977977
Ok(Some(possible_with_extension))
978978
} else {
979979
Ok(None)

src/cargo/util/cpu.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@ impl State {
2626

2727
#[cfg(target_os = "linux")]
2828
mod imp {
29-
use std::fs::File;
30-
use std::io::{self, Read};
29+
use std::{fs, io};
3130

3231
pub struct State {
3332
user: u64,
@@ -43,8 +42,7 @@ mod imp {
4342
}
4443

4544
pub fn current() -> io::Result<State> {
46-
let mut state = String::new();
47-
File::open("/proc/stat")?.read_to_string(&mut state)?;
45+
let state = fs::read_to_string("/proc/stat")?;
4846

4947
(|| {
5048
let mut parts = state.lines().next()?.split_whitespace();

src/cargo/util/important_paths.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
use crate::util::errors::CargoResult;
22
use crate::util::paths;
3-
use std::fs;
43
use std::path::{Path, PathBuf};
54

65
/// Finds the root `Cargo.toml`.
76
pub fn find_root_manifest_for_wd(cwd: &Path) -> CargoResult<PathBuf> {
87
let file = "Cargo.toml";
98
for current in paths::ancestors(cwd) {
109
let manifest = current.join(file);
11-
if fs::metadata(&manifest).is_ok() {
10+
if manifest.exists() {
1211
return Ok(manifest);
1312
}
1413
}

0 commit comments

Comments
 (0)