create-django-bolt 1.4.1

Ultra-fast CLI tool to scaffold production-ready Django-Bolt applications with Docker, Kubernetes, and Fly.io
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use colored::*;
use dialoguer::{Confirm, Input};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use walkdir::WalkDir;

const REPO_URL: &str = "https://github.com/bmartel/django-lightning.git";

#[derive(Parser)]
#[command(
    name = "create-django-bolt",
    author,
    version,
    about = "Ultra-fast CLI binary to scaffold production-ready Django-Bolt applications"
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    /// Project name
    #[arg(value_name = "PROJECT_NAME")]
    name: Option<String>,

    /// Destination directory
    #[arg(short, long)]
    path: Option<PathBuf>,

    /// Custom template directory or repository URL
    #[arg(short, long)]
    template: Option<String>,

    /// Include preconfigured GitHub Actions CI/CD workflows
    #[arg(long, default_value_t = false)]
    github_actions: bool,

    /// Exclude native Rust extension core (rust_core)
    #[arg(long, default_value_t = false)]
    no_rust: bool,
}

#[derive(Subcommand)]
enum Commands {
    /// Scaffold a new Django-Bolt project
    New {
        /// Project name
        name: Option<String>,

        /// Destination directory
        #[arg(short, long)]
        path: Option<PathBuf>,

        /// Custom template directory or repository URL
        #[arg(short, long)]
        template: Option<String>,

        /// Include preconfigured GitHub Actions CI/CD workflows
        #[arg(long, default_value_t = false)]
        github_actions: bool,

        /// Exclude native Rust extension core (rust_core)
        #[arg(long, default_value_t = false)]
        no_rust: bool,
    },
}

fn sanitize_names(input: &str) -> (String, String) {
    let clean = input.trim().to_lowercase();
    let slug = clean.replace(['_', ' '], "-");
    let snake = clean.replace(['-', ' '], "_");
    (slug, snake)
}

fn is_dir_empty(path: &Path) -> bool {
    if !path.exists() {
        return true;
    }
    match fs::read_dir(path) {
        Ok(mut entries) => entries.next().is_none(),
        Err(_) => false,
    }
}

fn copy_and_transform_dir(
    src_dir: &Path,
    dest_dir: &Path,
    slug_name: &str,
    snake_name: &str,
    include_ci: bool,
    include_rust: bool,
) -> Result<()> {
    let mut ignored_dirs = vec![
        ".git", "git", ".venv", "venv", "__pycache__", ".pytest_cache", ".ruff_cache",
        "staticfiles", "scratch", "target", "cli", ".worktrees",
    ];
    if !include_rust {
        ignored_dirs.push("rust_core");
    }

    let ignored_files = ["db.sqlite3", "db.sqlite3-journal", ".DS_Store"];

    for entry in WalkDir::new(src_dir).into_iter().filter_map(|e| e.ok()) {
        let path = entry.path();
        let rel_path = path.strip_prefix(src_dir)?;

        if rel_path.components().any(|c| {
            let name = c.as_os_str().to_string_lossy();
            ignored_dirs.contains(&name.as_ref())
        }) {
            continue;
        }

        // Exclude GitHub release workflow (starter repo specific)
        if rel_path == Path::new(".github/workflows/release.yml") {
            continue;
        }

        // Exclude GitHub workflows if user opted out
        if !include_ci && rel_path.starts_with(".github") {
            continue;
        }

        // Exclude Rust demo route if user opted out
        if !include_rust && rel_path == Path::new("app/routes/rust_demo.py") {
            continue;
        }

        let target_path = dest_dir.join(rel_path);

        if path.is_dir() {
            fs::create_dir_all(&target_path)?;
        } else if path.is_file() {
            let file_name = path.file_name().unwrap_or_default().to_string_lossy();
            if ignored_files.contains(&file_name.as_ref()) || file_name.ends_with(".pyc") {
                continue;
            }

            if let Ok(content) = fs::read_to_string(path) {
                let mut transformed = content
                    .replace("django-lightning-mcp", &format!("{}-mcp", slug_name))
                    .replace("django-lightning", slug_name)
                    .replace("django_lightning", snake_name)
                    .replace("Django Lightning", &slug_name.replace('-', " "));

                if file_name == "justfile" {
                    transformed = transformed.replace(
                        "\n# Build the Rust CLI tool (create-django-bolt)\nbuild-cli:\n    cargo build --manifest-path cli/Cargo.toml --release\n",
                        "",
                    );
                    if !include_rust {
                        let rust_tasks = "# Compile Rust core in debug mode for local development\nrust-dev:\n    uv run maturin develop\n\n# Compile Rust core in release mode for maximum production performance\nrust-build:\n    uv run maturin build --release --manifest-path rust_core/Cargo.toml --out target/wheels && uv pip install target/wheels/*.whl\n\n# Run unit tests for Rust native core crate\nrust-test:\n    cargo test --manifest-path rust_core/Cargo.toml\n";

                        transformed = transformed.replace(rust_tasks, "");
                    }
                }

                if !include_rust && file_name == "api.py" {
                    transformed = transformed.replace("from app.routes.rust_demo import register_rust_routes\n", "");
                    transformed = transformed.replace("register_rust_routes(api)\n", "");
                }

                if !include_rust && file_name == "pyproject.toml" {
                    let maturin_build = "[tool.maturin]\nmanifest-path = \"rust_core/Cargo.toml\"\npython-packages = [\"app\"]\nmodule-name = \"app.rust_core\"\n";

                    transformed = transformed.replace(maturin_build, "");
                    transformed = transformed.replace("    \"maturin>=1.5.0\",\n", "");
                }

                fs::write(&target_path, transformed)?;
            } else {
                fs::copy(path, &target_path)?;
            }
        }
    }
    Ok(())
}


fn transform_in_place(
    dest_dir: &Path,
    slug_name: &str,
    snake_name: &str,
    include_ci: bool,
    include_rust: bool,
) -> Result<()> {
    let mut ignored_dirs = vec![
        ".git", "git", ".venv", "venv", "__pycache__", ".pytest_cache", ".ruff_cache",
        "staticfiles", "scratch", "target", "cli",
    ];
    if !include_rust {
        ignored_dirs.push("rust_core");
        let _ = fs::remove_dir_all(dest_dir.join("rust_core"));
        let _ = fs::remove_file(dest_dir.join("app/routes/rust_demo.py"));
    }

    let ignored_files = ["db.sqlite3", "db.sqlite3-journal", ".DS_Store"];

    let _ = fs::remove_file(dest_dir.join(".github/workflows/release.yml"));

    if !include_ci {
        let _ = fs::remove_dir_all(dest_dir.join(".github"));
    }

    for entry in WalkDir::new(dest_dir).into_iter().filter_map(|e| e.ok()) {
        let path = entry.path();
        let rel_path = path.strip_prefix(dest_dir)?;

        if rel_path.components().any(|c| {
            let name = c.as_os_str().to_string_lossy();
            ignored_dirs.contains(&name.as_ref())
        }) {
            continue;
        }

        if path.is_file() {
            let file_name = path.file_name().unwrap_or_default().to_string_lossy();
            if ignored_files.contains(&file_name.as_ref()) || file_name.ends_with(".pyc") {
                continue;
            }
            if let Ok(content) = fs::read_to_string(&path) {
                let mut transformed = content
                    .replace("django-lightning-mcp", &format!("{}-mcp", slug_name))
                    .replace("django-lightning", slug_name)
                    .replace("django_lightning", snake_name)
                    .replace("Django Lightning", &slug_name.replace('-', " "));

                if file_name == "justfile" {
                    transformed = transformed.replace(
                        "\n# Build the Rust CLI tool (create-django-bolt)\nbuild-cli:\n    cargo build --manifest-path cli/Cargo.toml --release\n",
                        "",
                    );
                    if !include_rust {
                        let rust_tasks = "# Compile Rust core in debug mode for local development\nrust-dev:\n    uv run maturin develop\n\n# Compile Rust core in release mode for maximum production performance\nrust-build:\n    uv run maturin develop --release\n\n# Run unit tests for Rust native core crate\nrust-test:\n    cargo test --manifest-path rust_core/Cargo.toml\n";
                        transformed = transformed.replace(rust_tasks, "");
                    }
                }

                if !include_rust && file_name == "api.py" {
                    transformed = transformed.replace("from app.routes.rust_demo import register_rust_routes\n", "");
                    transformed = transformed.replace("register_rust_routes(api)\n", "");
                }

                if !include_rust && file_name == "pyproject.toml" {
                    let maturin_build = "[build-system]\nrequires = [\"maturin>=1.5,<2.0\"]\nbuild-backend = \"maturin\"\n\n[tool.maturin]\nmanifest-path = \"rust_core/Cargo.toml\"\npython-packages = [\"app\"]\nmodule-name = \"app.rust_core\"\n";
                    transformed = transformed.replace(maturin_build, "");
                    transformed = transformed.replace("    \"maturin>=1.5.0\",\n", "");
                }

                let _ = fs::write(&path, transformed);
            }
        }
    }
    Ok(())
}

fn download_template_from_github(dest_dir: &Path) -> Result<()> {
    println!("  {}", "Downloading template from GitHub (bmartel/django-lightning)...".dimmed());

    if !dest_dir.exists() {
        let status = Command::new("git")
            .args(["clone", "--depth", "1", REPO_URL, &dest_dir.to_string_lossy()])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .context("Failed to execute git clone")?;

        if !status.success() {
            anyhow::bail!("Failed to clone template repository from '{}'", REPO_URL);
        }
    } else {
        let status = Command::new("git")
            .args(["clone", "--depth", "1", REPO_URL, "."])
            .current_dir(dest_dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .context("Failed to execute git clone")?;

        if !status.success() {
            anyhow::bail!("Failed to clone template repository into existing directory '{}'", dest_dir.display());
        }
    }
    Ok(())
}

fn initialize_git(dest_dir: &Path) {
    let _ = fs::remove_dir_all(dest_dir.join(".git"));

    if Command::new("git")
        .args(["init"])
        .current_dir(dest_dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
    {
        println!("  {}", "✓ Initialized Git repository".green());
    }
}

fn setup_uv_env(dest_dir: &Path) {
    println!("\n{}", "âš™ Setting up Python environment with uv...".cyan());

    let venv_status = Command::new("uv")
        .arg("venv")
        .current_dir(dest_dir)
        .status();

    if venv_status.map(|s| s.success()).unwrap_or(false) {
        println!("  {}", "✓ Created virtual environment (.venv)".green());

        let install_status = Command::new("uv")
            .args(["pip", "install", "-e", ".[dev]"])
            .current_dir(dest_dir)
            .status();

        if install_status.map(|s| s.success()).unwrap_or(false) {
            println!("  {}", "✓ Installed dependencies with uv".green());
        }
    } else {
        println!("  {}", "! 'uv' not found or failed. Skipping virtual environment creation.".yellow());
    }
}

fn run_generator(
    name_opt: Option<String>,
    path_opt: Option<PathBuf>,
    template_opt: Option<String>,
    github_actions_flag: bool,
    no_rust_flag: bool,
) -> Result<()> {
    println!("{}", "âš¡ create-django-bolt".bold().cyan());
    println!("{}", "   High-Performance Django-Bolt Project Generator\n".dimmed());

    let raw_name = match name_opt {
        Some(n) => n,
        None => Input::<String>::new()
            .with_prompt("Project name")
            .default("my-bolt-app".into())
            .interact_text()?,
    };

    let (slug_name, snake_name) = sanitize_names(&raw_name);

    let is_tty = dialoguer::console::user_attended_stderr() || dialoguer::console::Term::stdout().is_term();

    let include_ci = if github_actions_flag {
        true
    } else if is_tty {
        Confirm::new()
            .with_prompt("Include preconfigured GitHub Actions CI/CD workflows?")
            .default(true)
            .interact_opt()?
            .unwrap_or(true)
    } else {
        true
    };

    let include_rust = if no_rust_flag {
        false
    } else if is_tty {
        Confirm::new()
            .with_prompt("Include native Rust extension core (rust_core)?")
            .default(true)
            .interact_opt()?
            .unwrap_or(true)
    } else {
        true
    };

    let current_dir = std::env::current_dir()?;
    let dest_dir = match path_opt {
        Some(p) => p,
        None => current_dir.join(&slug_name),
    };

    if dest_dir.exists() && !is_dir_empty(&dest_dir) {
        anyhow::bail!(
            "Destination directory '{}' already exists and is not empty!\nPlease specify a different name or path (e.g. create-django-bolt new {} -p /path/to/dir).",
            dest_dir.display(),
            slug_name
        );
    }

    println!("🚀 Creating Django-Bolt project '{}' in '{}'...", slug_name.bold().green(), dest_dir.display());

    if let Some(template_path) = template_opt {
        let src_path = PathBuf::from(template_path);
        if !src_path.exists() {
            anyhow::bail!("Template path '{}' does not exist!", src_path.display());
        }
        fs::create_dir_all(&dest_dir)?;
        copy_and_transform_dir(&src_path, &dest_dir, &slug_name, &snake_name, include_ci, include_rust)?;
    } else if current_dir.join("manage.py").exists() && current_dir.join("pyproject.toml").exists() {
        fs::create_dir_all(&dest_dir)?;
        copy_and_transform_dir(&current_dir, &dest_dir, &slug_name, &snake_name, include_ci, include_rust)?;
    } else {
        download_template_from_github(&dest_dir)?;
        transform_in_place(&dest_dir, &slug_name, &snake_name, include_ci, include_rust)?;
    }

    initialize_git(&dest_dir);

    if include_ci {
        println!("  {}", "✓ Added GitHub Actions CI/CD workflows (.github/workflows)".green());
    }

    if include_rust {
        println!("  {}", "✓ Added Native Rust extension core (rust_core)".green());
    } else {
        println!("  {}", "ℹ Python-only project configured (rust_core excluded)".dimmed());
    }

    let setup_env = if is_tty {
        Confirm::new()
            .with_prompt("Would you like to setup virtual environment and dependencies with 'uv' now?")
            .default(true)
            .interact_opt()?
            .unwrap_or(false)
    } else {
        false
    };

    if setup_env {
        setup_uv_env(&dest_dir);
    }

    println!("\n{}", "✨ Project scaffolding complete!".bold().green());
    println!("\nNext steps:");
    let mut step = 1;
    println!("  {}. cd {}", step, dest_dir.display().to_string().bold());
    step += 1;
    if !setup_env {
        println!("  {}. uv venv", step);
        step += 1;
        if include_rust {
            println!("  {}. uv run maturin develop", step);
            step += 1;
        }
        println!("  {}. uv pip install -e \".[dev]\"", step);
        step += 1;
    }
    println!("  {}. uv run manage.py migrate", step);
    step += 1;
    println!("  {}. uv run manage.py collectstatic --noinput", step);
    step += 1;
    println!("  {}. uv run manage.py runbolt --dev", step);

    Ok(())
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Some(Commands::New {
            name,
            path,
            template,
            github_actions,
            no_rust,
        }) => run_generator(name, path, template, github_actions, no_rust)?,
        None => run_generator(cli.name, cli.path, cli.template, cli.github_actions, cli.no_rust)?,
    }

    Ok(())
}