Skip to main content

bynk/
new.rs

1//! `bynk new` — scaffold a new project.
2//!
3//! The zero-to-one step of the driver arc `doctor → new → dev` (proposal
4//! v0.58): it writes a **complete, runnable** single-context HTTP service that
5//! `bynk dev` serves unmodified. Unlike `dev`, `new` shells nothing, compiles
6//! nothing, and reads no network — it is pure, offline file-writing, so it
7//! works before `bynk`, Node, or `wrangler` are installed (D4).
8//!
9//! The starter, manifest, `.gitignore` and `.gitattributes` are **embedded**
10//! via `include_str!` (the first-party precedent, ADR 0086): each template carries a
11//! [`PLACEHOLDER`] identifier substituted for the project name at write time.
12//! A standing test (`tests/new.rs`) renders the starter with a non-default name
13//! and asserts it compiles and is `bynk-fmt`-clean, so the scaffold can never
14//! rot into something that doesn't build.
15
16use bynk_driver::colour;
17use bynk_driver::emsg;
18use std::fs;
19use std::io;
20use std::path::{Path, PathBuf};
21use std::process::ExitCode;
22
23/// The sentinel identifier in the embedded templates, replaced by the project
24/// name when the scaffold is written. Chosen as a legal Bynk identifier so each
25/// template is itself parseable, and distinctive enough that a plain
26/// substring substitution only ever hits the intended occurrences.
27pub const PLACEHOLDER: &str = "appname";
28
29const STARTER_BYNK: &str = include_str!("templates/starter.bynk");
30const BYNK_TOML: &str = include_str!("templates/bynk.toml");
31const GITIGNORE: &str = include_str!("templates/gitignore");
32/// #1763: `*.bynk text eol=lf`, so a Windows checkout keeps `fmt`'s LF form.
33const GITATTRIBUTES: &str = include_str!("templates/gitattributes");
34
35/// Directory entries that don't count as "non-empty" for the clobber check
36/// (D5): VCS metadata and OS cruft a freshly-`mkdir`ed or `git init`ed
37/// directory commonly carries. Mirrors `cargo`'s look-the-other-way set.
38const SCAFFOLD_IGNORES: &[&str] = &[
39    ".git",
40    ".gitattributes",
41    ".gitignore",
42    ".hg",
43    ".hgignore",
44    ".svn",
45    ".DS_Store",
46];
47
48/// Parsed `bynk new` arguments.
49#[derive(Debug, Clone)]
50pub struct NewOptions {
51    /// Directory to create for the new project.
52    pub path: PathBuf,
53    /// `--name` override for the project / context identifier. Defaults to
54    /// `path`'s final component.
55    pub name: Option<String>,
56}
57
58/// Scaffold a new project: derive & validate the name, refuse to clobber, write
59/// the tree, and print next steps. Returns a non-zero exit (touching nothing)
60/// on an underivable/invalid name or a non-empty target.
61pub fn run(opts: &NewOptions) -> ExitCode {
62    let name = match opts.name.clone().or_else(|| derive_name(&opts.path)) {
63        Some(name) => name,
64        None => {
65            colour::eprint(&cannot_derive_message(&display(&opts.path)));
66            return ExitCode::FAILURE;
67        }
68    };
69
70    if !is_legal_name(&name) {
71        colour::eprint(&invalid_name_message(&name));
72        return ExitCode::FAILURE;
73    }
74
75    match target_is_nonempty(&opts.path) {
76        Ok(true) => {
77            colour::eprint(&clobber_message(&display(&opts.path)));
78            return ExitCode::FAILURE;
79        }
80        Ok(false) => {}
81        Err(e) => {
82            emsg!("bynk: error: cannot inspect `{}`: {e}", display(&opts.path));
83            return ExitCode::FAILURE;
84        }
85    }
86
87    if let Err(e) = write_scaffold(&opts.path, &name) {
88        emsg!("bynk: error: failed to write the scaffold: {e}");
89        return ExitCode::FAILURE;
90    }
91
92    print!("{}", next_steps_message(&display(&opts.path)));
93    ExitCode::SUCCESS
94}
95
96/// The project name implied by a target path: its final component. `None` when
97/// the path has no final component (e.g. `.` or `/`), in which case `--name` is
98/// required.
99fn derive_name(path: &Path) -> Option<String> {
100    path.file_name().map(|s| s.to_string_lossy().into_owned())
101}
102
103/// Is `name` a legal Bynk identifier — a single, dotless `Ident`? Answered by
104/// the real lexer rather than a hand-rolled regex, so it tracks the language
105/// exactly: a dash, dot, leading digit, or reserved keyword all yield something
106/// other than one lone `Ident` token and are rejected.
107pub fn is_legal_name(name: &str) -> bool {
108    match bynk_syntax::lexer::tokenize(name) {
109        Ok(tokens) => tokens.len() == 1 && tokens[0].kind == bynk_syntax::lexer::TokenKind::Ident,
110        Err(_) => false,
111    }
112}
113
114/// Render an embedded template for `name` by substituting [`PLACEHOLDER`].
115pub fn render(template: &str, name: &str) -> String {
116    template.replace(PLACEHOLDER, name)
117}
118
119/// The rendered starter source for `name` — the `context <name>` HTTP service
120/// written to `src/<name>.bynk`.
121pub fn starter_source(name: &str) -> String {
122    render(STARTER_BYNK, name)
123}
124
125/// Does the target exist and hold anything that isn't [`SCAFFOLD_IGNORES`]
126/// cruft? A missing or cruft-only directory is fine to scaffold into (D5).
127fn target_is_nonempty(target: &Path) -> io::Result<bool> {
128    let entries = match fs::read_dir(target) {
129        Ok(entries) => entries,
130        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
131        Err(e) => return Err(e),
132    };
133    for entry in entries {
134        let entry = entry?;
135        let name = entry.file_name();
136        if !SCAFFOLD_IGNORES.contains(&name.to_string_lossy().as_ref()) {
137            return Ok(true);
138        }
139    }
140    Ok(false)
141}
142
143/// Create the directory tree and write the four files. Never overwrites: the
144/// clobber check has already cleared the target of everything except
145/// [`SCAFFOLD_IGNORES`] cruft. `.gitignore` and `.gitattributes` (#1763) are
146/// the members of that set the scaffold also writes — a hand-written one (e.g.
147/// in a `git init`ed target) passes the clobber check, so we write ours only
148/// when none is present rather than clobbering the user's.
149fn write_scaffold(target: &Path, name: &str) -> io::Result<()> {
150    let src_dir = target.join("src");
151    fs::create_dir_all(&src_dir)?;
152    fs::write(target.join("bynk.toml"), render(BYNK_TOML, name))?;
153    let gitignore = target.join(".gitignore");
154    if !gitignore.exists() {
155        fs::write(gitignore, render(GITIGNORE, name))?;
156    }
157    // #1763: likewise, never over the user's own.
158    let gitattributes = target.join(".gitattributes");
159    if !gitattributes.exists() {
160        fs::write(gitattributes, render(GITATTRIBUTES, name))?;
161    }
162    fs::write(src_dir.join(format!("{name}.bynk")), starter_source(name))?;
163    Ok(())
164}
165
166fn display(path: &Path) -> String {
167    path.display().to_string()
168}
169
170// ---------------------------------------------------------------------------
171// Output surface — pinned by goldens (proposal §5). Built here as pure
172// functions so the tests can assert them without touching the filesystem.
173// ---------------------------------------------------------------------------
174
175/// The success "next steps" message, printed to stdout.
176pub fn next_steps_message(dir: &str) -> String {
177    format!(
178        "Created a new Bynk project in `{dir}`.\n\
179         \n\
180         Next steps:\n  \
181         cd {dir}\n  \
182         bynk dev          # build and serve it locally\n\
183         \n\
184         New to Bynk? `bynk doctor` checks your toolchain is ready.\n"
185    )
186}
187
188/// The failure message for a name that isn't a legal Bynk identifier.
189pub fn invalid_name_message(name: &str) -> String {
190    format!(
191        "bynk: error: `{name}` isn't a valid Bynk name.\n      \
192         A name must be a single identifier — a letter followed by letters, \
193         digits, or underscores (no dashes or dots).\n      \
194         Pass `--name <ident>` to choose the project's identifier.\n"
195    )
196}
197
198/// The failure message when a name can't be derived from the path.
199pub fn cannot_derive_message(path: &str) -> String {
200    format!(
201        "bynk: error: couldn't derive a project name from `{path}`.\n      \
202         Pass `--name <ident>` to name the project.\n"
203    )
204}
205
206/// The failure message when the target exists and isn't empty (D5).
207pub fn clobber_message(dir: &str) -> String {
208    format!(
209        "bynk: error: `{dir}` already exists and isn't empty — refusing to overwrite.\n      \
210         Choose a different path, or empty that directory first.\n"
211    )
212}