Skip to content

Commit

Permalink
Use fs helpers instead of File functions.
Browse files Browse the repository at this point in the history
  • Loading branch information
ehuss committed Apr 17, 2020
1 parent 4367ec4 commit 4ae79d2
Show file tree
Hide file tree
Showing 35 changed files with 639 additions and 1,069 deletions.
5 changes: 2 additions & 3 deletions crates/cargo-test-support/src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@ use some of the helper functions in this file to interact with the repository.
*/

use crate::{path2url, project, Project, ProjectBuilder};
use std::fs::{self, File};
use std::io::prelude::*;
use std::fs;
use std::path::{Path, PathBuf};
use url::Url;

Expand Down Expand Up @@ -81,7 +80,7 @@ impl RepoBuilder {
pub fn nocommit_file(self, path: &str, contents: &str) -> RepoBuilder {
let dst = self.repo.workdir().unwrap().join(path);
t!(fs::create_dir_all(dst.parent().unwrap()));
t!(t!(File::create(&dst)).write_all(contents.as_bytes()));
t!(fs::write(&dst, contents));
self
}

Expand Down
26 changes: 6 additions & 20 deletions crates/cargo-test-support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,6 @@ use std::env;
use std::ffi::OsStr;
use std::fmt;
use std::fs;
use std::io::prelude::*;
use std::os;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
Expand Down Expand Up @@ -166,11 +165,8 @@ impl FileBuilder {

fn mk(&self) {
self.dirname().mkdir_p();

let mut file = fs::File::create(&self.path)
fs::write(&self.path, &self.body)
.unwrap_or_else(|e| panic!("could not create file {}: {}", self.path.display(), e));

t!(file.write_all(self.body.as_bytes()));
}

fn dirname(&self) -> &Path {
Expand Down Expand Up @@ -458,25 +454,15 @@ impl Project {

/// Returns the contents of a path in the project root
pub fn read_file(&self, path: &str) -> String {
let mut buffer = String::new();
fs::File::open(self.root().join(path))
.unwrap()
.read_to_string(&mut buffer)
.unwrap();
buffer
let full = self.root().join(path);
fs::read_to_string(&full)
.unwrap_or_else(|e| panic!("could not read file {}: {}", full.display(), e))
}

/// Modifies `Cargo.toml` to remove all commented lines.
pub fn uncomment_root_manifest(&self) {
let mut contents = String::new();
fs::File::open(self.root().join("Cargo.toml"))
.unwrap()
.read_to_string(&mut contents)
.unwrap();
fs::File::create(self.root().join("Cargo.toml"))
.unwrap()
.write_all(contents.replace("#", "").as_bytes())
.unwrap();
let contents = self.read_file("Cargo.toml").replace("#", "");
fs::write(self.root().join("Cargo.toml"), contents).unwrap();
}

pub fn symlink(&self, src: impl AsRef<Path>, dst: impl AsRef<Path>) {
Expand Down
45 changes: 22 additions & 23 deletions crates/cargo-test-support/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,33 +165,34 @@ pub fn init() {
if config.exists() {
return;
}
t!(t!(File::create(&config)).write_all(
t!(fs::write(
&config,
format!(
r#"
[source.crates-io]
registry = 'https://wut'
replace-with = 'dummy-registry'
[source.crates-io]
registry = 'https://wut'
replace-with = 'dummy-registry'
[source.dummy-registry]
registry = '{reg}'
[source.dummy-registry]
registry = '{reg}'
[registries.alternative]
index = '{alt}'
"#,
[registries.alternative]
index = '{alt}'
"#,
reg = registry_url(),
alt = alt_registry_url()
)
.as_bytes()
));
let credentials = paths::home().join(".cargo/credentials");
t!(t!(File::create(&credentials)).write_all(
br#"
[registry]
token = "api-token"
[registries.alternative]
token = "api-token"
"#
t!(fs::write(
&credentials,
r#"
[registry]
token = "api-token"
[registries.alternative]
token = "api-token"
"#
));

// Initialize a new registry.
Expand Down Expand Up @@ -404,8 +405,7 @@ impl Package {
})
.collect::<Vec<_>>();
let cksum = {
let mut c = Vec::new();
t!(t!(File::open(&self.archive_dst())).read_to_end(&mut c));
let c = t!(fs::read(&self.archive_dst()));
cksum(&c)
};
let name = if self.invalid_json {
Expand Down Expand Up @@ -442,10 +442,9 @@ impl Package {
} else {
registry_path.join(&file)
};
let mut prev = String::new();
let _ = File::open(&dst).and_then(|mut f| f.read_to_string(&mut prev));
let prev = fs::read_to_string(&dst).unwrap_or(String::new());
t!(fs::create_dir_all(dst.parent().unwrap()));
t!(t!(File::create(&dst)).write_all((prev + &line[..] + "\n").as_bytes()));
t!(fs::write(&dst, prev + &line[..] + "\n"));

// Add the new file to the index.
if !self.local {
Expand Down
5 changes: 2 additions & 3 deletions src/cargo/ops/vendor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ use anyhow::bail;
use serde::Serialize;
use std::collections::HashSet;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs::{self, File};
use std::io::Write;
use std::fs;
use std::path::{Path, PathBuf};

pub struct VendorOptions<'a> {
Expand Down Expand Up @@ -223,7 +222,7 @@ fn sync(
"files": map,
});

File::create(&cksum)?.write_all(json.to_string().as_bytes())?;
paths::write(&cksum, json.to_string())?;
}

for path in to_remove {
Expand Down
8 changes: 3 additions & 5 deletions src/cargo/sources/registry/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use lazycell::LazyCell;
use log::{debug, trace};
use std::cell::{Cell, Ref, RefCell};
use std::fmt::Write as FmtWrite;
use std::fs::{File, OpenOptions};
use std::fs::{self, File, OpenOptions};
use std::io::prelude::*;
use std::io::SeekFrom;
use std::mem;
Expand Down Expand Up @@ -300,10 +300,8 @@ impl<'cfg> RegistryData for RemoteRegistry<'cfg> {

let path = self.cache_path.join(path);
let path = self.config.assert_package_cache_locked(&path);
if let Ok(dst) = File::open(path) {
if let Ok(meta) = dst.metadata() {
return meta.len() > 0;
}
if let Ok(meta) = fs::metadata(path) {
return meta.len() > 0;
}
false
}
Expand Down
6 changes: 2 additions & 4 deletions src/cargo/util/cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ impl State {

#[cfg(target_os = "linux")]
mod imp {
use std::fs::File;
use std::io::{self, Read};
use std::{fs, io};

pub struct State {
user: u64,
Expand All @@ -43,8 +42,7 @@ mod imp {
}

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

(|| {
let mut parts = state.lines().next()?.split_whitespace();
Expand Down
27 changes: 6 additions & 21 deletions src/cargo/util/paths.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::fs::{self, OpenOptions};
use std::io;
use std::io::prelude::*;
use std::iter;
Expand Down Expand Up @@ -118,27 +118,12 @@ pub fn read(path: &Path) -> CargoResult<String> {
}

pub fn read_bytes(path: &Path) -> CargoResult<Vec<u8>> {
let res = (|| -> CargoResult<_> {
let mut ret = Vec::new();
let mut f = File::open(path)?;
if let Ok(m) = f.metadata() {
ret.reserve(m.len() as usize + 1);
}
f.read_to_end(&mut ret)?;
Ok(ret)
})()
.chain_err(|| format!("failed to read `{}`", path.display()))?;
Ok(res)
fs::read(path).chain_err(|| format!("failed to read `{}`", path.display()))
}

pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
let mut f = File::create(path)?;
f.write_all(contents)?;
Ok(())
})()
.chain_err(|| format!("failed to write `{}`", path.display()))?;
Ok(())
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> CargoResult<()> {
let path = path.as_ref();
fs::write(path, contents.as_ref()).chain_err(|| format!("failed to write `{}`", path.display()))
}

pub fn write_if_changed<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> CargoResult<()> {
Expand Down Expand Up @@ -190,7 +175,7 @@ pub fn set_invocation_time(path: &Path) -> CargoResult<FileTime> {
let timestamp = path.join("invoked.timestamp");
write(
&timestamp,
b"This file has an mtime of when this was started.",
"This file has an mtime of when this was started.",
)?;
let ft = mtime(&timestamp)?;
log::debug!("invocation time for {:?} is {}", path, ft);
Expand Down
59 changes: 26 additions & 33 deletions tests/testsuite/alt_registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use cargo::util::IntoUrl;
use cargo_test_support::publish::validate_alt_upload;
use cargo_test_support::registry::{self, Package};
use cargo_test_support::{basic_manifest, git, paths, project};
use std::fs::{self, File};
use std::io::Write;
use std::fs;

#[cargo_test]
fn depend_on_alt_registry() {
Expand Down Expand Up @@ -534,16 +533,14 @@ fn passwords_in_registry_index_url_forbidden() {
registry::init();

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

File::create(config)
.unwrap()
.write_all(
br#"
fs::write(
config,
r#"
[registry]
index = "ssh://git:secret@foobar.com"
"#,
)
.unwrap();
)
.unwrap();

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

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

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

File::create(config)
.unwrap()
.write_all(
br#"
fs::write(
config,
r#"
[registries.alternative]
index = "ssh://git:secret@foobar.com"
"#,
)
.unwrap();
)
.unwrap();

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

Expand Down Expand Up @@ -1181,15 +1177,14 @@ fn unknown_registry() {
fn registries_index_relative_url() {
let config = paths::root().join(".cargo/config");
fs::create_dir_all(config.parent().unwrap()).unwrap();
File::create(&config)
.unwrap()
.write_all(
br#"
fs::write(
&config,
r#"
[registries.relative]
index = "file:alternative-registry"
"#,
)
.unwrap();
)
.unwrap();

registry::init();

Expand Down Expand Up @@ -1231,15 +1226,14 @@ fn registries_index_relative_url() {
fn registry_index_relative_url() {
let config = paths::root().join(".cargo/config");
fs::create_dir_all(config.parent().unwrap()).unwrap();
File::create(&config)
.unwrap()
.write_all(
br#"
fs::write(
&config,
r#"
[registry]
index = "file:alternative-registry"
"#,
)
.unwrap();
)
.unwrap();

registry::init();

Expand Down Expand Up @@ -1283,15 +1277,14 @@ warning: custom registry support via the `registry.index` configuration is being
fn registries_index_relative_path_not_allowed() {
let config = paths::root().join(".cargo/config");
fs::create_dir_all(config.parent().unwrap()).unwrap();
File::create(&config)
.unwrap()
.write_all(
br#"
fs::write(
&config,
r#"
[registries.relative]
index = "alternative-registry"
"#,
)
.unwrap();
)
.unwrap();

registry::init();

Expand Down
Loading

0 comments on commit 4ae79d2

Please sign in to comment.