Skip to content

Commit 4ae79d2

Browse files
committed
Use fs helpers instead of File functions.
1 parent 4367ec4 commit 4ae79d2

35 files changed

+639
-1069
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: 22 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -165,33 +165,34 @@ pub fn init() {
165165
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/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/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/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/paths.rs

Lines changed: 6 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::env;
22
use std::ffi::{OsStr, OsString};
3-
use std::fs::{self, File, OpenOptions};
3+
use std::fs::{self, OpenOptions};
44
use std::io;
55
use std::io::prelude::*;
66
use std::iter;
@@ -118,27 +118,12 @@ pub fn read(path: &Path) -> CargoResult<String> {
118118
}
119119

120120
pub fn read_bytes(path: &Path) -> CargoResult<Vec<u8>> {
121-
let res = (|| -> CargoResult<_> {
122-
let mut ret = Vec::new();
123-
let mut f = File::open(path)?;
124-
if let Ok(m) = f.metadata() {
125-
ret.reserve(m.len() as usize + 1);
126-
}
127-
f.read_to_end(&mut ret)?;
128-
Ok(ret)
129-
})()
130-
.chain_err(|| format!("failed to read `{}`", path.display()))?;
131-
Ok(res)
121+
fs::read(path).chain_err(|| format!("failed to read `{}`", path.display()))
132122
}
133123

134-
pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> {
135-
(|| -> CargoResult<()> {
136-
let mut f = File::create(path)?;
137-
f.write_all(contents)?;
138-
Ok(())
139-
})()
140-
.chain_err(|| format!("failed to write `{}`", path.display()))?;
141-
Ok(())
124+
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> CargoResult<()> {
125+
let path = path.as_ref();
126+
fs::write(path, contents.as_ref()).chain_err(|| format!("failed to write `{}`", path.display()))
142127
}
143128

144129
pub fn write_if_changed<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> CargoResult<()> {
@@ -190,7 +175,7 @@ pub fn set_invocation_time(path: &Path) -> CargoResult<FileTime> {
190175
let timestamp = path.join("invoked.timestamp");
191176
write(
192177
&timestamp,
193-
b"This file has an mtime of when this was started.",
178+
"This file has an mtime of when this was started.",
194179
)?;
195180
let ft = mtime(&timestamp)?;
196181
log::debug!("invocation time for {:?} is {}", path, ft);

tests/testsuite/alt_registry.rs

Lines changed: 26 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ use cargo::util::IntoUrl;
44
use cargo_test_support::publish::validate_alt_upload;
55
use cargo_test_support::registry::{self, Package};
66
use cargo_test_support::{basic_manifest, git, paths, project};
7-
use std::fs::{self, File};
8-
use std::io::Write;
7+
use std::fs;
98

109
#[cargo_test]
1110
fn depend_on_alt_registry() {
@@ -534,16 +533,14 @@ fn passwords_in_registry_index_url_forbidden() {
534533
registry::init();
535534

536535
let config = paths::home().join(".cargo/config");
537-
538-
File::create(config)
539-
.unwrap()
540-
.write_all(
541-
br#"
536+
fs::write(
537+
config,
538+
r#"
542539
[registry]
543540
index = "ssh://git:[email protected]"
544541
"#,
545-
)
546-
.unwrap();
542+
)
543+
.unwrap();
547544

548545
let p = project().file("src/main.rs", "fn main() {}").build();
549546

@@ -559,15 +556,14 @@ fn passwords_in_registries_index_url_forbidden() {
559556

560557
let config = paths::home().join(".cargo/config");
561558

562-
File::create(config)
563-
.unwrap()
564-
.write_all(
565-
br#"
559+
fs::write(
560+
config,
561+
r#"
566562
[registries.alternative]
567563
index = "ssh://git:[email protected]"
568564
"#,
569-
)
570-
.unwrap();
565+
)
566+
.unwrap();
571567

572568
let p = project().file("src/main.rs", "fn main() {}").build();
573569

@@ -1181,15 +1177,14 @@ fn unknown_registry() {
11811177
fn registries_index_relative_url() {
11821178
let config = paths::root().join(".cargo/config");
11831179
fs::create_dir_all(config.parent().unwrap()).unwrap();
1184-
File::create(&config)
1185-
.unwrap()
1186-
.write_all(
1187-
br#"
1180+
fs::write(
1181+
&config,
1182+
r#"
11881183
[registries.relative]
11891184
index = "file:alternative-registry"
11901185
"#,
1191-
)
1192-
.unwrap();
1186+
)
1187+
.unwrap();
11931188

11941189
registry::init();
11951190

@@ -1231,15 +1226,14 @@ fn registries_index_relative_url() {
12311226
fn registry_index_relative_url() {
12321227
let config = paths::root().join(".cargo/config");
12331228
fs::create_dir_all(config.parent().unwrap()).unwrap();
1234-
File::create(&config)
1235-
.unwrap()
1236-
.write_all(
1237-
br#"
1229+
fs::write(
1230+
&config,
1231+
r#"
12381232
[registry]
12391233
index = "file:alternative-registry"
12401234
"#,
1241-
)
1242-
.unwrap();
1235+
)
1236+
.unwrap();
12431237

12441238
registry::init();
12451239

@@ -1283,15 +1277,14 @@ warning: custom registry support via the `registry.index` configuration is being
12831277
fn registries_index_relative_path_not_allowed() {
12841278
let config = paths::root().join(".cargo/config");
12851279
fs::create_dir_all(config.parent().unwrap()).unwrap();
1286-
File::create(&config)
1287-
.unwrap()
1288-
.write_all(
1289-
br#"
1280+
fs::write(
1281+
&config,
1282+
r#"
12901283
[registries.relative]
12911284
index = "alternative-registry"
12921285
"#,
1293-
)
1294-
.unwrap();
1286+
)
1287+
.unwrap();
12951288

12961289
registry::init();
12971290

0 commit comments

Comments
 (0)