0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-10-31 09:14:20 -04:00
denoland-deno/cli/tools/init/mod.rs
Leo Kettmeir 1ffbd56164
feat: add "deno init" subcommand (#15469)
This adds an init subcommand to that creates a project starter similar to cargo init.

```
$ deno init my_project
Project initialized
Run these commands to get started:
  cd my_project
  deno run main.ts
  deno run main_test.ts
$ deno run main.ts
Add 2 + 3 5
$ cat main.ts
export function add(a: number, b: number): number {
  return a + b;
}
if (import.meta.main) {
  console.log("Add 2 + 3", add(2, 3));
}
$ cat main_test.ts
import { assertEquals } from "https://deno.land/std@0.151.0/testing/asserts.ts";
import { add } from "./main.ts";
Deno.test(function addTest() {
    assertEquals(add(2, 3), 5);
});
```

Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
2022-08-20 01:37:05 +02:00

49 lines
1.3 KiB
Rust

// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
use crate::args::InitFlags;
use crate::compat;
use deno_core::{anyhow::Context, error::AnyError};
use std::io::Write;
use std::path::Path;
fn create_file(
dir: &Path,
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 {} file", filename))?;
file.write_all(content.as_bytes())?;
Ok(())
}
pub async fn init_project(init_flags: InitFlags) -> Result<(), AnyError> {
let cwd =
std::env::current_dir().context("Can't read current working directory.")?;
let dir = if let Some(dir) = &init_flags.dir {
let dir = cwd.join(dir);
std::fs::create_dir_all(&dir)?;
dir
} else {
cwd
};
let main_ts = include_str!("./templates/main.ts");
create_file(&dir, "main.ts", main_ts)?;
let main_test_ts = include_str!("./templates/main_test.ts")
.replace("{CURRENT_STD_URL}", compat::STD_URL_STR);
create_file(&dir, "main_test.ts", &main_test_ts)?;
println!("✅ Project initialized");
println!("Run these commands to get started");
if let Some(dir) = init_flags.dir {
println!(" cd {}", dir);
}
println!(" deno run main.ts");
println!(" deno test");
Ok(())
}