Skip to content
This repository was archived by the owner on Aug 31, 2023. It is now read-only.

Commit 2eda94a

Browse files
committed
feat(rome_cli): Add a new option --config to set the path to rome.json
1 parent ced6f5b commit 2eda94a

File tree

9 files changed

+188
-20
lines changed

9 files changed

+188
-20
lines changed

crates/rome_cli/src/commands/help.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ const CHECK: Markup = markup! {
3737
"<Dim>"--apply"</Dim>" Apply safe fixes
3838
"<Dim>"--apply-unsafe"</Dim>" Apply safe and unsafe fixes
3939
"<Dim>"--max-diagnostics"</Dim>" Cap the amount of diagnostics displayed (default: 20)
40+
"<Dim>"--config"</Dim>" Set the filesystem path to the directory of the rome.json configuration file
4041
"<Dim>"--verbose"</Dim>" Print additional verbose advices on diagnostics
4142
"
4243
};
@@ -65,6 +66,7 @@ const CI: Markup = markup! {
6566
"<Dim>"--formatter-enabled"</Dim>" Allow to enable or disable the formatter check. (default: true)
6667
"<Dim>"--linter-enabled"</Dim>" Allow to enable or disable the linter check. (default: true)
6768
"<Dim>"--max-diagnostics"</Dim>" Cap the amount of diagnostics displayed (default: 50)
69+
"<Dim>"--config"</Dim>" Set the filesystem path to the directory of the rome.json configuration file
6870
"<Dim>"--verbose"</Dim>" Print additional verbose advices on diagnostics"
6971
{FORMAT_OPTIONS}
7072
};
@@ -81,6 +83,7 @@ const FORMAT: Markup = markup! {
8183
"<Dim>"--write"</Dim>" Edit the files in place (beware!) instead of printing the diff to the console
8284
"<Dim>"--skip-errors"</Dim>" Skip over files containing syntax errors instead of emitting an error diagnostic.
8385
"<Dim>"--max-diagnostics"</Dim>" Cap the amount of diagnostics displayed (default: 50)
86+
"<Dim>"--config"</Dim>" Set the filesystem path to the directory of the rome.json configuration file
8487
"<Dim>"--verbose"</Dim>" Print additional verbose advices on diagnostics"
8588
{FORMAT_OPTIONS}
8689
""<Dim>"--stdin-file-path <string>"</Dim>" A file name with its extension to pass when reading from standard in, e.g. echo 'let a;' | rome format --stdin-file-path file.js

crates/rome_cli/src/commands/rage.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ impl Display for RageConfiguration<'_, '_> {
163163
fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> {
164164
Section("Rome Configuration").fmt(fmt)?;
165165

166-
match load_config(self.0, None) {
166+
match load_config(self.0, None, false) {
167167
Ok(None) => KeyValuePair("Status", markup!(<Dim>"unset"</Dim>)).fmt(fmt)?,
168168
Ok(Some(configuration)) => {
169169
markup! (
Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,31 @@
1+
use std::path::PathBuf;
2+
13
use rome_service::{load_config, Configuration};
24

35
use crate::{CliDiagnostic, CliSession};
46

57
/// Load the configuration for this session of the CLI, merging the content of
68
/// the `rome.json` file if it exists on disk with common command line options
79
pub(crate) fn load_configuration(session: &mut CliSession) -> Result<Configuration, CliDiagnostic> {
8-
let mut configuration = load_config(&session.app.fs, None)?.unwrap_or_default();
10+
let config_path: Option<PathBuf> = session
11+
.args
12+
.opt_value_from_str("--config")
13+
.map_err(|source| CliDiagnostic::parse_error("--config", source))?;
14+
15+
let is_config_path = config_path.is_some();
16+
17+
let mut config =
18+
load_config(&session.app.fs, config_path, is_config_path)?.unwrap_or_default();
919

1020
let files_max_size = session
1121
.args
1222
.opt_value_from_str("--files-max-size")
1323
.map_err(|source| CliDiagnostic::parse_error("--files-max-size", source))?;
1424

1525
if let Some(files_max_size) = files_max_size {
16-
let files = configuration.files.get_or_insert_with(Default::default);
26+
let files = config.files.get_or_insert_with(Default::default);
1727
files.max_size = Some(files_max_size);
1828
}
1929

20-
Ok(configuration)
30+
Ok(config)
2131
}

crates/rome_cli/tests/commands/format.rs

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,15 @@ const APPLY_TRAILING_COMMA_AFTER: &str = r#"const a = [
4444
];
4545
"#;
4646

47+
const DEFAULT_CONFIGURATION_BEFORE: &str = r#"function f() {
48+
return { a, b }
49+
}"#;
50+
51+
const DEFAULT_CONFIGURATION_AFTER: &str = "function f() {
52+
return { a, b };
53+
}
54+
";
55+
4756
const CUSTOM_CONFIGURATION_BEFORE: &str = r#"function f() {
4857
return { a, b }
4958
}"#;
@@ -236,6 +245,87 @@ fn lint_warning() {
236245
));
237246
}
238247

248+
#[test]
249+
fn custom_config_file_path() {
250+
let mut fs = MemoryFileSystem::default();
251+
let mut console = BufferConsole::default();
252+
253+
let config_path = Path::new("/test/rome.json");
254+
fs.insert(config_path.into(), CONFIG_FORMAT.as_bytes());
255+
256+
let file_path = Path::new("file.js");
257+
fs.insert(file_path.into(), DEFAULT_CONFIGURATION_BEFORE.as_bytes());
258+
259+
let mut config_path = PathBuf::from(config_path);
260+
config_path.pop();
261+
262+
let result = run_cli(
263+
DynRef::Borrowed(&mut fs),
264+
&mut console,
265+
Arguments::from_vec(vec![
266+
OsString::from("format"),
267+
OsString::from("--config"),
268+
OsString::from(config_path),
269+
OsString::from("--write"),
270+
file_path.as_os_str().into(),
271+
]),
272+
);
273+
274+
assert!(result.is_ok(), "run_cli returned {result:?}");
275+
276+
let mut file = fs
277+
.open(file_path)
278+
.expect("formatting target file was removed by the CLI");
279+
280+
let mut content = String::new();
281+
file.read_to_string(&mut content)
282+
.expect("failed to read file from memory FS");
283+
284+
assert_eq!(content, DEFAULT_CONFIGURATION_AFTER);
285+
286+
drop(file);
287+
assert_cli_snapshot(SnapshotPayload::new(
288+
module_path!(),
289+
"custom_config_file_path",
290+
fs,
291+
console,
292+
result,
293+
));
294+
}
295+
296+
// Should throw an error when an invalid configuration path is specified
297+
#[test]
298+
fn invalid_config_file_path() {
299+
let mut fs = MemoryFileSystem::default();
300+
let mut console = BufferConsole::default();
301+
302+
let config_path = Path::new("/test");
303+
let file_path = Path::new("file.js");
304+
fs.insert(file_path.into(), *b"content");
305+
306+
let result = run_cli(
307+
DynRef::Borrowed(&mut fs),
308+
&mut console,
309+
Arguments::from_vec(vec![
310+
OsString::from("format"),
311+
OsString::from("--config"),
312+
OsString::from(config_path),
313+
OsString::from("--write"),
314+
file_path.as_os_str().into(),
315+
]),
316+
);
317+
318+
assert!(result.is_err(), "run_cli returned {result:?}");
319+
320+
assert_cli_snapshot(SnapshotPayload::new(
321+
module_path!(),
322+
"invalid_config_file_path",
323+
fs,
324+
console,
325+
result,
326+
));
327+
}
328+
239329
#[test]
240330
fn applies_custom_configuration() {
241331
let mut fs = MemoryFileSystem::default();
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
---
2+
source: crates/rome_cli/tests/snap_test.rs
3+
assertion_line: 335
4+
expression: content
5+
---
6+
## `/test/rome.json`
7+
8+
```json
9+
{
10+
"formatter": {
11+
"enabled": true,
12+
"lineWidth": 160,
13+
"indentStyle": "space",
14+
"indentSize": 6
15+
}
16+
}
17+
18+
```
19+
20+
## `file.js`
21+
22+
```js
23+
function f() {
24+
return { a, b };
25+
}
26+
27+
```
28+
29+
# Emitted Messages
30+
31+
```block
32+
Formatted 1 file(s) in <TIME>
33+
```
34+
35+
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
source: crates/rome_cli/tests/snap_test.rs
3+
assertion_line: 335
4+
expression: content
5+
---
6+
## `file.js`
7+
8+
```js
9+
content
10+
```
11+
12+
# Termination Message
13+
14+
```block
15+
/test/rome.json internalError/fs ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
16+
17+
× Rome couldn't read the following file, maybe for permissions reasons or it doesn't exists: /test/rome.json
18+
19+
20+
21+
```
22+
23+

crates/rome_lsp/src/session.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@ impl Session {
366366
pub(crate) async fn load_workspace_settings(&self) {
367367
let base_path = self.base_path();
368368

369-
let status = match load_config(&self.fs, base_path) {
369+
let status = match load_config(&self.fs, base_path, false) {
370370
Ok(Some(configuration)) => {
371371
info!("Loaded workspace settings: {configuration:#?}");
372372

crates/rome_service/src/configuration/mod.rs

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -128,50 +128,51 @@ impl FilesConfiguration {
128128
pub fn load_config(
129129
file_system: &DynRef<dyn FileSystem>,
130130
base_path: Option<PathBuf>,
131+
show_error: bool,
131132
) -> Result<Option<Configuration>, WorkspaceError> {
132133
let config_name = file_system.config_name();
133-
let configuration_path = if let Some(base_path) = base_path {
134+
let config_path = if let Some(ref base_path) = base_path {
134135
base_path.join(config_name)
135136
} else {
136137
PathBuf::from(config_name)
137138
};
138139
info!(
139-
"Attempting to load the configuration file at path {:?}",
140-
configuration_path
140+
"Attempting to read the configuration file from {:?}",
141+
config_path
141142
);
142143
let options = OpenOptions::default().read(true);
143-
let file = file_system.open_with_options(&configuration_path, options);
144+
let file = file_system.open_with_options(&config_path, options);
144145
match file {
145146
Ok(mut file) => {
146147
let mut buffer = String::new();
147148
file.read_to_string(&mut buffer).map_err(|_| {
148-
WorkspaceError::cant_read_file(format!("{}", configuration_path.display()))
149+
WorkspaceError::cant_read_file(format!("{}", config_path.display()))
149150
})?;
150151

151-
let configuration: Configuration = serde_json::from_str(&buffer).map_err(|err| {
152+
let config: Configuration = serde_json::from_str(&buffer).map_err(|err| {
152153
WorkspaceError::Configuration(ConfigurationDiagnostic::new_deserialization_error(
153154
err.to_string(),
154155
from_serde_error_to_range(&err, &buffer),
155156
))
156157
})?;
157158

158-
Ok(Some(configuration))
159+
Ok(Some(config))
159160
}
160161
Err(err) => {
161-
// We throw an error only when the error is found.
162-
// In case we don't fine the file, we swallow the error and we continue; not having
163-
// a file should not be a cause of error (for now)
164-
if err.kind() != ErrorKind::NotFound {
162+
// We skip the error when the configuration file is not found
163+
// and the base path is not explicitly set; not having a configuration
164+
// file is not a cause of error
165+
if show_error || err.kind() != ErrorKind::NotFound {
165166
return Err(WorkspaceError::cant_read_file(format!(
166167
"{}",
167-
configuration_path.display()
168+
config_path.display()
168169
)));
169170
}
170171
error!(
171-
"Could not find the file configuration at {:?}",
172-
configuration_path.display()
172+
"Could not read the configuration file from {:?}, reason:\n {}",
173+
config_path.display(),
174+
err
173175
);
174-
error!("Reason: {:?}", err);
175176
Ok(None)
176177
}
177178
}

website/src/pages/cli.mdx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@ Set the formatting mode for markup: `off` prints everything as plain text,
5959
`force` forces the formatting of markup using ANSI even if the console output
6060
is determined to be incompatible
6161

62+
### `--config`
63+
64+
Set the filesystem path to the directory of the rome.json configuration file.
65+
This is optional. Rome will try to read a rome.json configuration file from the
66+
current working directory by default.
67+
6268
### `--use-server`
6369

6470
Connect to a running instance of the Rome daemon server

0 commit comments

Comments
 (0)