Replace OpenOptions::new with File::options to be readable (#3059)

## Issue Addressed

Closes #3049 

This PR updates widely but this replace is safe as `File::options()` is equivelent to `OpenOptions::new()`.
ref: https://doc.rust-lang.org/stable/src/std/fs.rs.html#378-380
This commit is contained in:
Akihito Nakano 2022-03-07 06:30:18 +00:00
parent cbda0a2f0a
commit 4186d117af
16 changed files with 40 additions and 41 deletions

View File

@ -3,7 +3,7 @@ use crate::{BeaconChainTypes, BeaconStore};
use ssz::{Decode, DecodeError, Encode}; use ssz::{Decode, DecodeError, Encode};
use std::collections::HashMap; use std::collections::HashMap;
use std::convert::TryInto; use std::convert::TryInto;
use std::fs::{File, OpenOptions}; use std::fs::File;
use std::io::{self, Read, Write}; use std::io::{self, Read, Write};
use std::path::Path; use std::path::Path;
use store::{DBColumn, Error as StoreError, StoreItem}; use store::{DBColumn, Error as StoreError, StoreItem};
@ -255,7 +255,7 @@ impl From<Error> for BeaconChainError {
impl ValidatorPubkeyCacheFile { impl ValidatorPubkeyCacheFile {
/// Opens an existing file for reading and writing. /// Opens an existing file for reading and writing.
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, Error> { pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
OpenOptions::new() File::options()
.read(true) .read(true)
.write(true) .write(true)
.create(false) .create(false)
@ -453,7 +453,7 @@ mod test {
let cache = ValidatorPubkeyCache::<T>::load_from_file(&path).expect("should open cache"); let cache = ValidatorPubkeyCache::<T>::load_from_file(&path).expect("should open cache");
drop(cache); drop(cache);
let mut file = OpenOptions::new() let mut file = File::options()
.write(true) .write(true)
.append(true) .append(true)
.open(&path) .open(&path)

View File

@ -10,7 +10,7 @@ use regex::Regex;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use slog::{error, Logger}; use slog::{error, Logger};
use std::collections::HashSet; use std::collections::HashSet;
use std::fs::{self, OpenOptions}; use std::fs::{self, File};
use std::io; use std::io;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use types::{graffiti::GraffitiString, Address, PublicKey}; use types::{graffiti::GraffitiString, Address, PublicKey};
@ -162,7 +162,7 @@ impl ValidatorDefinitions {
/// Open an existing file, returning an error if the file does not exist. /// Open an existing file, returning an error if the file does not exist.
pub fn open<P: AsRef<Path>>(validators_dir: P) -> Result<Self, Error> { pub fn open<P: AsRef<Path>>(validators_dir: P) -> Result<Self, Error> {
let config_path = validators_dir.as_ref().join(CONFIG_FILENAME); let config_path = validators_dir.as_ref().join(CONFIG_FILENAME);
let file = OpenOptions::new() let file = File::options()
.write(true) .write(true)
.read(true) .read(true)
.create_new(false) .create_new(false)
@ -219,7 +219,7 @@ impl ValidatorDefinitions {
return None; return None;
} }
let keystore_result = OpenOptions::new() let keystore_result = File::options()
.read(true) .read(true)
.create(false) .create(false)
.open(&voting_keystore_path) .open(&voting_keystore_path)

View File

@ -2,7 +2,7 @@
use eth2_wallet::Error as WalletError; use eth2_wallet::Error as WalletError;
use eth2_wallet::{Uuid, Wallet}; use eth2_wallet::{Uuid, Wallet};
use std::fs::{copy as copy_file, remove_file, OpenOptions}; use std::fs::{copy as copy_file, remove_file, File};
use std::io; use std::io;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -27,7 +27,7 @@ pub fn read<P: AsRef<Path>>(wallet_dir: P, uuid: &Uuid) -> Result<Wallet, Error>
if !json_path.exists() { if !json_path.exists() {
Err(Error::WalletDoesNotExist(json_path)) Err(Error::WalletDoesNotExist(json_path))
} else { } else {
OpenOptions::new() File::options()
.read(true) .read(true)
.create(false) .create(false)
.open(json_path) .open(json_path)
@ -79,7 +79,7 @@ pub fn create<P: AsRef<Path>>(wallet_dir: P, wallet: &Wallet) -> Result<(), Erro
if json_path.exists() { if json_path.exists() {
Err(Error::WalletAlreadyExists(json_path)) Err(Error::WalletAlreadyExists(json_path))
} else { } else {
OpenOptions::new() File::options()
.write(true) .write(true)
.create_new(true) .create_new(true)
.open(json_path) .open(json_path)

View File

@ -6,7 +6,7 @@ use eth2_wallet::{bip39::Mnemonic, Error as WalletError, Uuid, Wallet, WalletBui
use lockfile::LockfileError; use lockfile::LockfileError;
use std::collections::HashMap; use std::collections::HashMap;
use std::ffi::OsString; use std::ffi::OsString;
use std::fs::{create_dir_all, read_dir, OpenOptions}; use std::fs::{create_dir_all, read_dir, File};
use std::io; use std::io;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -172,7 +172,7 @@ impl WalletManager {
// Ignore any paths that don't parse as a UUID. // Ignore any paths that don't parse as a UUID.
if let Ok(uuid) = Uuid::parse_str(&file_name) { if let Ok(uuid) = Uuid::parse_str(&file_name) {
let wallet_path = f.path().join(format!("{}", uuid)); let wallet_path = f.path().join(format!("{}", uuid));
let wallet = OpenOptions::new() let wallet = File::options()
.read(true) .read(true)
.create(false) .create(false)
.open(wallet_path) .open(wallet_path)

View File

@ -1,5 +1,5 @@
use fs2::FileExt; use fs2::FileExt;
use std::fs::{self, File, OpenOptions}; use std::fs::{self, File};
use std::io::{self, ErrorKind}; use std::io::{self, ErrorKind};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -30,7 +30,7 @@ impl Lockfile {
let file = if file_existed { let file = if file_existed {
File::open(&path) File::open(&path)
} else { } else {
OpenOptions::new() File::options()
.read(true) .read(true)
.write(true) .write(true)
.create_new(true) .create_new(true)

View File

@ -4,7 +4,7 @@ use deposit_contract::{encode_eth1_tx_data, Error as DepositError};
use eth2_keystore::{Error as KeystoreError, Keystore, KeystoreBuilder, PlainText}; use eth2_keystore::{Error as KeystoreError, Keystore, KeystoreBuilder, PlainText};
use filesystem::create_with_600_perms; use filesystem::create_with_600_perms;
use rand::{distributions::Alphanumeric, Rng}; use rand::{distributions::Alphanumeric, Rng};
use std::fs::{create_dir_all, OpenOptions}; use std::fs::{create_dir_all, File};
use std::io::{self, Write}; use std::io::{self, Write};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use types::{ChainSpec, DepositData, Hash256, Keypair, Signature}; use types::{ChainSpec, DepositData, Hash256, Keypair, Signature};
@ -197,7 +197,7 @@ impl<'a> Builder<'a> {
return Err(Error::DepositDataAlreadyExists(path)); return Err(Error::DepositDataAlreadyExists(path));
} else { } else {
let hex = format!("0x{}", hex::encode(&deposit_data)); let hex = format!("0x{}", hex::encode(&deposit_data));
OpenOptions::new() File::options()
.write(true) .write(true)
.read(true) .read(true)
.create(true) .create(true)
@ -214,7 +214,7 @@ impl<'a> Builder<'a> {
if path.exists() { if path.exists() {
return Err(Error::DepositAmountAlreadyExists(path)); return Err(Error::DepositAmountAlreadyExists(path));
} else { } else {
OpenOptions::new() File::options()
.write(true) .write(true)
.read(true) .read(true)
.create(true) .create(true)
@ -267,7 +267,7 @@ fn write_keystore_to_file(path: PathBuf, keystore: &Keystore) -> Result<(), Erro
if path.exists() { if path.exists() {
Err(Error::KeystoreAlreadyExists(path)) Err(Error::KeystoreAlreadyExists(path))
} else { } else {
let file = OpenOptions::new() let file = File::options()
.write(true) .write(true)
.read(true) .read(true)
.create_new(true) .create_new(true)

View File

@ -6,7 +6,7 @@ use deposit_contract::decode_eth1_tx_data;
use derivative::Derivative; use derivative::Derivative;
use eth2_keystore::{Error as KeystoreError, Keystore, PlainText}; use eth2_keystore::{Error as KeystoreError, Keystore, PlainText};
use lockfile::{Lockfile, LockfileError}; use lockfile::{Lockfile, LockfileError};
use std::fs::{read, write, OpenOptions}; use std::fs::{read, write, File};
use std::io; use std::io;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use tree_hash::TreeHash; use tree_hash::TreeHash;
@ -211,7 +211,7 @@ pub fn unlock_keypair<P: AsRef<Path>>(
password_dir: P, password_dir: P,
) -> Result<Keypair, Error> { ) -> Result<Keypair, Error> {
let keystore = Keystore::from_json_reader( let keystore = Keystore::from_json_reader(
&mut OpenOptions::new() &mut File::options()
.read(true) .read(true)
.create(false) .create(false)
.open(keystore_path) .open(keystore_path)
@ -236,7 +236,7 @@ pub fn unlock_keypair_from_password_path(
password_path: &Path, password_path: &Path,
) -> Result<Keypair, Error> { ) -> Result<Keypair, Error> {
let keystore = Keystore::from_json_reader( let keystore = Keystore::from_json_reader(
&mut OpenOptions::new() &mut File::options()
.read(true) .read(true)
.create(false) .create(false)
.open(keystore_path) .open(keystore_path)

View File

@ -1163,14 +1163,13 @@ mod tests {
#[cfg(test)] #[cfg(test)]
mod yaml_tests { mod yaml_tests {
use super::*; use super::*;
use std::fs::OpenOptions;
use tempfile::NamedTempFile; use tempfile::NamedTempFile;
#[test] #[test]
fn minimal_round_trip() { fn minimal_round_trip() {
// create temp file // create temp file
let tmp_file = NamedTempFile::new().expect("failed to create temp file"); let tmp_file = NamedTempFile::new().expect("failed to create temp file");
let writer = OpenOptions::new() let writer = File::options()
.read(false) .read(false)
.write(true) .write(true)
.open(tmp_file.as_ref()) .open(tmp_file.as_ref())
@ -1181,7 +1180,7 @@ mod yaml_tests {
// write fresh minimal config to file // write fresh minimal config to file
serde_yaml::to_writer(writer, &yamlconfig).expect("failed to write or serialize"); serde_yaml::to_writer(writer, &yamlconfig).expect("failed to write or serialize");
let reader = OpenOptions::new() let reader = File::options()
.read(true) .read(true)
.write(false) .write(false)
.open(tmp_file.as_ref()) .open(tmp_file.as_ref())
@ -1194,7 +1193,7 @@ mod yaml_tests {
#[test] #[test]
fn mainnet_round_trip() { fn mainnet_round_trip() {
let tmp_file = NamedTempFile::new().expect("failed to create temp file"); let tmp_file = NamedTempFile::new().expect("failed to create temp file");
let writer = OpenOptions::new() let writer = File::options()
.read(false) .read(false)
.write(true) .write(true)
.open(tmp_file.as_ref()) .open(tmp_file.as_ref())
@ -1203,7 +1202,7 @@ mod yaml_tests {
let yamlconfig = Config::from_chain_spec::<MainnetEthSpec>(&mainnet_spec); let yamlconfig = Config::from_chain_spec::<MainnetEthSpec>(&mainnet_spec);
serde_yaml::to_writer(writer, &yamlconfig).expect("failed to write or serialize"); serde_yaml::to_writer(writer, &yamlconfig).expect("failed to write or serialize");
let reader = OpenOptions::new() let reader = File::options()
.read(true) .read(true)
.write(false) .write(false)
.open(tmp_file.as_ref()) .open(tmp_file.as_ref())

View File

@ -92,13 +92,13 @@ impl ConfigAndPreset {
mod test { mod test {
use super::*; use super::*;
use crate::MainnetEthSpec; use crate::MainnetEthSpec;
use std::fs::OpenOptions; use std::fs::File;
use tempfile::NamedTempFile; use tempfile::NamedTempFile;
#[test] #[test]
fn extra_fields_round_trip() { fn extra_fields_round_trip() {
let tmp_file = NamedTempFile::new().expect("failed to create temp file"); let tmp_file = NamedTempFile::new().expect("failed to create temp file");
let writer = OpenOptions::new() let writer = File::options()
.read(false) .read(false)
.write(true) .write(true)
.open(tmp_file.as_ref()) .open(tmp_file.as_ref())
@ -116,7 +116,7 @@ mod test {
serde_yaml::to_writer(writer, &yamlconfig).expect("failed to write or serialize"); serde_yaml::to_writer(writer, &yamlconfig).expect("failed to write or serialize");
let reader = OpenOptions::new() let reader = File::options()
.read(true) .read(true)
.write(false) .write(false)
.open(tmp_file.as_ref()) .open(tmp_file.as_ref())

View File

@ -21,7 +21,7 @@ use scrypt::{
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::fs::OpenOptions; use std::fs::File;
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::iter::FromIterator; use std::iter::FromIterator;
use std::path::Path; use std::path::Path;
@ -329,7 +329,7 @@ impl Keystore {
/// Instantiates `self` by reading a JSON file at `path`. /// Instantiates `self` by reading a JSON file at `path`.
pub fn from_json_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> { pub fn from_json_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
OpenOptions::new() File::options()
.read(true) .read(true)
.write(false) .write(false)
.create(false) .create(false)

View File

@ -7,7 +7,7 @@ use eth2_keystore::{
json_keystore::{Kdf, Pbkdf2, Prf, Scrypt}, json_keystore::{Kdf, Pbkdf2, Prf, Scrypt},
Error, Keystore, KeystoreBuilder, DKLEN, Error, Keystore, KeystoreBuilder, DKLEN,
}; };
use std::fs::OpenOptions; use std::fs::File;
use tempfile::tempdir; use tempfile::tempdir;
const GOOD_PASSWORD: &[u8] = &[42, 42, 42]; const GOOD_PASSWORD: &[u8] = &[42, 42, 42];
@ -55,7 +55,7 @@ fn file() {
let path = dir.path().join("keystore.json"); let path = dir.path().join("keystore.json");
let get_file = || { let get_file = || {
OpenOptions::new() File::options()
.write(true) .write(true)
.read(true) .read(true)
.create(true) .create(true)

View File

@ -4,7 +4,7 @@ use eth2_wallet::{
bip39::{Language, Mnemonic, Seed}, bip39::{Language, Mnemonic, Seed},
recover_validator_secret, DerivedKey, Error, KeyType, KeystoreError, Wallet, WalletBuilder, recover_validator_secret, DerivedKey, Error, KeyType, KeystoreError, Wallet, WalletBuilder,
}; };
use std::fs::OpenOptions; use std::fs::File;
use tempfile::tempdir; use tempfile::tempdir;
const NAME: &str = "Wallet McWalletface"; const NAME: &str = "Wallet McWalletface";
@ -133,7 +133,7 @@ fn file_round_trip() {
let path = dir.path().join("keystore.json"); let path = dir.path().join("keystore.json");
let get_file = || { let get_file = || {
OpenOptions::new() File::options()
.write(true) .write(true)
.read(true) .read(true)
.create(true) .create(true)

View File

@ -4,7 +4,7 @@ use eth2::{BeaconNodeHttpClient, Timeouts};
use log::{error, info}; use log::{error, info};
use sensitive_url::SensitiveUrl; use sensitive_url::SensitiveUrl;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::fs::OpenOptions; use std::fs::File;
use std::io::Write; use std::io::Write;
use std::path::PathBuf; use std::path::PathBuf;
use std::time::Duration; use std::time::Duration;
@ -158,7 +158,7 @@ pub async fn run<T: EthSpec>(matches: &ArgMatches<'_>) -> Result<(), String> {
let mut proposer_map: HashMap<Slot, ProposerInfo> = HashMap::new(); let mut proposer_map: HashMap<Slot, ProposerInfo> = HashMap::new();
let mut file = OpenOptions::new() let mut file = File::options()
.read(true) .read(true)
.write(true) .write(true)
.create(true) .create(true)

View File

@ -18,7 +18,7 @@ pub fn log_file_access<P: AsRef<Path>>(file_accessed: P) {
let passed_test_list_path = let passed_test_list_path =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(ACCESSED_FILE_LOG_FILENAME); PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(ACCESSED_FILE_LOG_FILENAME);
let mut file = fs::OpenOptions::new() let mut file = fs::File::options()
.append(true) .append(true)
.create(true) .create(true)
.open(passed_test_list_path) .open(passed_test_list_path)

View File

@ -8,7 +8,7 @@ use crate::{signing_root_from_row, NotSafe, Safe, SignedAttestation, SignedBlock
use filesystem::restrict_file_permissions; use filesystem::restrict_file_permissions;
use r2d2_sqlite::SqliteConnectionManager; use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::{params, OptionalExtension, Transaction, TransactionBehavior}; use rusqlite::{params, OptionalExtension, Transaction, TransactionBehavior};
use std::fs::OpenOptions; use std::fs::File;
use std::path::Path; use std::path::Path;
use std::time::Duration; use std::time::Duration;
use types::{AttestationData, BeaconBlockHeader, Epoch, Hash256, PublicKeyBytes, SignedRoot, Slot}; use types::{AttestationData, BeaconBlockHeader, Epoch, Hash256, PublicKeyBytes, SignedRoot, Slot};
@ -50,7 +50,7 @@ impl SlashingDatabase {
/// ///
/// Error if a database (or any file) already exists at `path`. /// Error if a database (or any file) already exists at `path`.
pub fn create(path: &Path) -> Result<Self, NotSafe> { pub fn create(path: &Path) -> Result<Self, NotSafe> {
let _file = OpenOptions::new() let _file = File::options()
.write(true) .write(true)
.read(true) .read(true)
.create_new(true) .create_new(true)

View File

@ -11,7 +11,7 @@ use eth2_keystore::{
use rand::prelude::*; use rand::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
use std::fs::OpenOptions; use std::fs::File;
use std::io; use std::io;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -101,7 +101,7 @@ impl KeyCache {
/// Open an existing file, returning an error if the file does not exist. /// Open an existing file, returning an error if the file does not exist.
pub fn open<P: AsRef<Path>>(validators_dir: P) -> Result<Self, Error> { pub fn open<P: AsRef<Path>>(validators_dir: P) -> Result<Self, Error> {
let cache_path = validators_dir.as_ref().join(CACHE_FILENAME); let cache_path = validators_dir.as_ref().join(CACHE_FILENAME);
let file = OpenOptions::new() let file = File::options()
.read(true) .read(true)
.create_new(false) .create_new(false)
.open(&cache_path) .open(&cache_path)