Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit a5cc780

Browse files
authored
Merge pull request rust-lang#3468 from topecongiro/refactor-create_config
Move some code out of create_config
2 parents 9b43441 + 0d67db4 commit a5cc780

File tree

2 files changed

+136
-137
lines changed

2 files changed

+136
-137
lines changed

src/config/config_type.rs

Lines changed: 0 additions & 137 deletions
Original file line numberDiff line numberDiff line change
@@ -93,19 +93,6 @@ macro_rules! create_config {
9393
$(pub $i: Option<$ty>),+
9494
}
9595

96-
impl PartialConfig {
97-
pub fn to_toml(&self) -> Result<String, String> {
98-
// Non-user-facing options can't be specified in TOML
99-
let mut cloned = self.clone();
100-
cloned.file_lines = None;
101-
cloned.verbose = None;
102-
cloned.width_heuristics = None;
103-
104-
::toml::to_string(&cloned)
105-
.map_err(|e| format!("Could not output config: {}", e))
106-
}
107-
}
108-
10996
// Macro hygiene won't allow us to make `set_$i()` methods on Config
11097
// for each item, so this struct is used to give the API to set values:
11198
// `config.set().option(false)`. It's pretty ugly. Consider replacing
@@ -139,23 +126,6 @@ macro_rules! create_config {
139126
}
140127

141128
impl Config {
142-
pub(crate) fn version_meets_requirement(&self) -> bool {
143-
if self.was_set().required_version() {
144-
let version = env!("CARGO_PKG_VERSION");
145-
let required_version = self.required_version();
146-
if version != required_version {
147-
println!(
148-
"Error: rustfmt version ({}) doesn't match the required version ({})",
149-
version,
150-
required_version,
151-
);
152-
return false;
153-
}
154-
}
155-
156-
true
157-
}
158-
159129
$(
160130
pub fn $i(&self) -> $ty {
161131
self.$i.0.set(true);
@@ -213,37 +183,6 @@ macro_rules! create_config {
213183
}
214184
}
215185

216-
pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
217-
let parsed: ::toml::Value =
218-
toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
219-
let mut err: String = String::new();
220-
{
221-
let table = parsed
222-
.as_table()
223-
.ok_or(String::from("Parsed config was not table"))?;
224-
for key in table.keys() {
225-
if !Config::is_valid_name(key) {
226-
let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
227-
err.push_str(msg)
228-
}
229-
}
230-
}
231-
match parsed.try_into() {
232-
Ok(parsed_config) => {
233-
if !err.is_empty() {
234-
eprint!("{}", err);
235-
}
236-
Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
237-
}
238-
Err(e) => {
239-
err.push_str("Error: Decoding config file failed:\n");
240-
err.push_str(format!("{}\n", e).as_str());
241-
err.push_str("Please check your config file.");
242-
Err(err)
243-
}
244-
}
245-
}
246-
247186
pub fn used_options(&self) -> PartialConfig {
248187
PartialConfig {
249188
$(
@@ -287,82 +226,6 @@ macro_rules! create_config {
287226
}
288227
}
289228

290-
/// Constructs a `Config` from the toml file specified at `file_path`.
291-
///
292-
/// This method only looks at the provided path, for a method that
293-
/// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
294-
///
295-
/// Returns a `Config` if the config could be read and parsed from
296-
/// the file, otherwise errors.
297-
pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
298-
let mut file = File::open(&file_path)?;
299-
let mut toml = String::new();
300-
file.read_to_string(&mut toml)?;
301-
Config::from_toml(&toml, file_path.parent().unwrap())
302-
.map_err(|err| Error::new(ErrorKind::InvalidData, err))
303-
}
304-
305-
/// Resolves the config for input in `dir`.
306-
///
307-
/// Searches for `rustfmt.toml` beginning with `dir`, and
308-
/// recursively checking parents of `dir` if no config file is found.
309-
/// If no config file exists in `dir` or in any parent, a
310-
/// default `Config` will be returned (and the returned path will be empty).
311-
///
312-
/// Returns the `Config` to use, and the path of the project file if there was
313-
/// one.
314-
pub(super) fn from_resolved_toml_path(
315-
dir: &Path,
316-
) -> Result<(Config, Option<PathBuf>), Error> {
317-
/// Try to find a project file in the given directory and its parents.
318-
/// Returns the path of a the nearest project file if one exists,
319-
/// or `None` if no project file was found.
320-
fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
321-
let mut current = if dir.is_relative() {
322-
env::current_dir()?.join(dir)
323-
} else {
324-
dir.to_path_buf()
325-
};
326-
327-
current = fs::canonicalize(current)?;
328-
329-
loop {
330-
match get_toml_path(&current) {
331-
Ok(Some(path)) => return Ok(Some(path)),
332-
Err(e) => return Err(e),
333-
_ => ()
334-
}
335-
336-
// If the current directory has no parent, we're done searching.
337-
if !current.pop() {
338-
break;
339-
}
340-
}
341-
342-
// If nothing was found, check in the home directory.
343-
if let Some(home_dir) = dirs::home_dir() {
344-
if let Some(path) = get_toml_path(&home_dir)? {
345-
return Ok(Some(path));
346-
}
347-
}
348-
349-
// If none was found ther either, check in the user's configuration directory.
350-
if let Some(mut config_dir) = dirs::config_dir() {
351-
config_dir.push("rustfmt");
352-
if let Some(path) = get_toml_path(&config_dir)? {
353-
return Ok(Some(path));
354-
}
355-
}
356-
357-
return Ok(None);
358-
}
359-
360-
match resolve_project_file(dir)? {
361-
None => Ok((Config::default(), None)),
362-
Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
363-
}
364-
}
365-
366229
pub fn is_hidden_option(name: &str) -> bool {
367230
const HIDE_OPTIONS: [&str; 4] =
368231
["verbose", "verbose_diff", "file_lines", "width_heuristics"];

src/config/mod.rs

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,142 @@ create_config! {
150150
make_backup: bool, false, false, "Backup changed files";
151151
}
152152

153+
impl PartialConfig {
154+
pub fn to_toml(&self) -> Result<String, String> {
155+
// Non-user-facing options can't be specified in TOML
156+
let mut cloned = self.clone();
157+
cloned.file_lines = None;
158+
cloned.verbose = None;
159+
cloned.width_heuristics = None;
160+
161+
::toml::to_string(&cloned).map_err(|e| format!("Could not output config: {}", e))
162+
}
163+
}
164+
165+
impl Config {
166+
pub(crate) fn version_meets_requirement(&self) -> bool {
167+
if self.was_set().required_version() {
168+
let version = env!("CARGO_PKG_VERSION");
169+
let required_version = self.required_version();
170+
if version != required_version {
171+
println!(
172+
"Error: rustfmt version ({}) doesn't match the required version ({})",
173+
version, required_version,
174+
);
175+
return false;
176+
}
177+
}
178+
179+
true
180+
}
181+
182+
/// Constructs a `Config` from the toml file specified at `file_path`.
183+
///
184+
/// This method only looks at the provided path, for a method that
185+
/// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
186+
///
187+
/// Returns a `Config` if the config could be read and parsed from
188+
/// the file, otherwise errors.
189+
pub(super) fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
190+
let mut file = File::open(&file_path)?;
191+
let mut toml = String::new();
192+
file.read_to_string(&mut toml)?;
193+
Config::from_toml(&toml, file_path.parent().unwrap())
194+
.map_err(|err| Error::new(ErrorKind::InvalidData, err))
195+
}
196+
197+
/// Resolves the config for input in `dir`.
198+
///
199+
/// Searches for `rustfmt.toml` beginning with `dir`, and
200+
/// recursively checking parents of `dir` if no config file is found.
201+
/// If no config file exists in `dir` or in any parent, a
202+
/// default `Config` will be returned (and the returned path will be empty).
203+
///
204+
/// Returns the `Config` to use, and the path of the project file if there was
205+
/// one.
206+
pub(super) fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
207+
/// Try to find a project file in the given directory and its parents.
208+
/// Returns the path of a the nearest project file if one exists,
209+
/// or `None` if no project file was found.
210+
fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
211+
let mut current = if dir.is_relative() {
212+
env::current_dir()?.join(dir)
213+
} else {
214+
dir.to_path_buf()
215+
};
216+
217+
current = fs::canonicalize(current)?;
218+
219+
loop {
220+
match get_toml_path(&current) {
221+
Ok(Some(path)) => return Ok(Some(path)),
222+
Err(e) => return Err(e),
223+
_ => (),
224+
}
225+
226+
// If the current directory has no parent, we're done searching.
227+
if !current.pop() {
228+
break;
229+
}
230+
}
231+
232+
// If nothing was found, check in the home directory.
233+
if let Some(home_dir) = dirs::home_dir() {
234+
if let Some(path) = get_toml_path(&home_dir)? {
235+
return Ok(Some(path));
236+
}
237+
}
238+
239+
// If none was found ther either, check in the user's configuration directory.
240+
if let Some(mut config_dir) = dirs::config_dir() {
241+
config_dir.push("rustfmt");
242+
if let Some(path) = get_toml_path(&config_dir)? {
243+
return Ok(Some(path));
244+
}
245+
}
246+
247+
return Ok(None);
248+
}
249+
250+
match resolve_project_file(dir)? {
251+
None => Ok((Config::default(), None)),
252+
Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
253+
}
254+
}
255+
256+
pub(crate) fn from_toml(toml: &str, dir: &Path) -> Result<Config, String> {
257+
let parsed: ::toml::Value = toml
258+
.parse()
259+
.map_err(|e| format!("Could not parse TOML: {}", e))?;
260+
let mut err: String = String::new();
261+
{
262+
let table = parsed
263+
.as_table()
264+
.ok_or(String::from("Parsed config was not table"))?;
265+
for key in table.keys() {
266+
if !Config::is_valid_name(key) {
267+
let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
268+
err.push_str(msg)
269+
}
270+
}
271+
}
272+
match parsed.try_into() {
273+
Ok(parsed_config) => {
274+
if !err.is_empty() {
275+
eprint!("{}", err);
276+
}
277+
Ok(Config::default().fill_from_parsed_config(parsed_config, dir))
278+
}
279+
Err(e) => {
280+
err.push_str("Error: Decoding config file failed:\n");
281+
err.push_str(format!("{}\n", e).as_str());
282+
err.push_str("Please check your config file.");
283+
Err(err)
284+
}
285+
}
286+
}
287+
}
288+
153289
/// Loads a config by checking the client-supplied options and if appropriate, the
154290
/// file system (including searching the file system for overrides).
155291
pub fn load_config<O: CliOptions>(

0 commit comments

Comments
 (0)