mirror of
https://github.com/denoland/deno.git
synced 2024-11-21 15:04:11 -05:00
fix(init): skip existing files instead of erroring (#20434)
### What Skip writing files from the template if the files already exist in the project directory. ### Why When I run deno init in a directory that already has a main.ts, or one of the other template files, I usually want to initialize a workspace around a file I've started working in. A hard error in this case seems counter productive. An informational message about what's being skipped seems sufficient. Close #20433
This commit is contained in:
parent
f32acb945e
commit
4a8b873111
2 changed files with 57 additions and 7 deletions
|
@ -128,3 +128,44 @@ fn init_subcommand_with_quiet_arg() {
|
|||
assert_contains!(output.stdout(), "1 passed");
|
||||
output.skip_output_check();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_subcommand_with_existing_file() {
|
||||
let context = TestContextBuilder::new().use_temp_cwd().build();
|
||||
let cwd = context.temp_dir().path();
|
||||
|
||||
cwd
|
||||
.join("main.ts")
|
||||
.write("console.log('Log from main.ts that already exists');");
|
||||
|
||||
let output = context.new_command().args("init").split_output().run();
|
||||
|
||||
output.assert_exit_code(0);
|
||||
output.assert_stderr_matches_text(
|
||||
"ℹ️ Skipped creating main.ts as it already exists
|
||||
✅ Project initialized
|
||||
|
||||
Run these commands to get started
|
||||
|
||||
# Run the program
|
||||
deno run main.ts
|
||||
|
||||
# Run the program and watch for file changes
|
||||
deno task dev
|
||||
|
||||
# Run the tests
|
||||
deno test
|
||||
",
|
||||
);
|
||||
|
||||
assert!(cwd.join("deno.json").exists());
|
||||
|
||||
let output = context
|
||||
.new_command()
|
||||
.env("NO_COLOR", "1")
|
||||
.args("run main.ts")
|
||||
.run();
|
||||
|
||||
output.assert_exit_code(0);
|
||||
output.assert_matches_text("Log from main.ts that already exists\n");
|
||||
}
|
||||
|
|
|
@ -14,13 +14,22 @@ fn create_file(
|
|||
filename: &str,
|
||||
content: &str,
|
||||
) -> Result<(), AnyError> {
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(dir.join(filename))
|
||||
.with_context(|| format!("Failed to create {filename} file"))?;
|
||||
file.write_all(content.as_bytes())?;
|
||||
Ok(())
|
||||
let path = dir.join(filename);
|
||||
if path.exists() {
|
||||
info!(
|
||||
"ℹ️ {}",
|
||||
colors::gray(format!("Skipped creating {filename} as it already exists"))
|
||||
);
|
||||
Ok(())
|
||||
} else {
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)
|
||||
.with_context(|| format!("Failed to create {filename} file"))?;
|
||||
file.write_all(content.as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn init_project(init_flags: InitFlags) -> Result<(), AnyError> {
|
||||
|
|
Loading…
Reference in a new issue