Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(create-farm): rewrite create-farm #1700

Merged
merged 7 commits into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/afraid-turtles-roll.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-farm": patch
---

Fix tauri development command in `create-farm`
5 changes: 5 additions & 0 deletions .changeset/brave-phones-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-farm": patch
---

Refactor `create-farm` prompts
5 changes: 5 additions & 0 deletions .changeset/silent-colts-juggle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-farm": patch
---

Fix supported templates display
5 changes: 5 additions & 0 deletions .changeset/tasty-ants-kick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-farm": patch
---

Auto rewrite template project name in `create-farm`
5 changes: 5 additions & 0 deletions .changeset/violet-lions-impress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-farm": patch
---

Support `create-farm` to run with `--force`
5 changes: 4 additions & 1 deletion crates/create-farm-rs/src/args.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{package_manager::PackageManager, template::Template};
use clap::Parser;
use clap::{ArgAction, Parser};

#[derive(Parser, Debug)]
#[command(
Expand All @@ -15,6 +15,8 @@ pub struct Args {
pub manager: Option<PackageManager>,
#[arg(short, long, help = "Project template to use")]
pub template: Option<Template>,
#[arg(short, long, help = "Force overwrite of existing files", action = ArgAction::SetTrue)]
pub force: bool,
}

impl Default for Args {
Expand All @@ -23,6 +25,7 @@ impl Default for Args {
project_name: Some("farm-project".to_string()),
manager: Some(PackageManager::Npm),
template: Some(Template::Vanilla),
force: false,
}
}
}
130 changes: 53 additions & 77 deletions crates/create-farm-rs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use anyhow::Context;
use clap::Parser;
use dialoguer::{Confirm, Input, Select};
use dialoguer::Input;
use std::{ffi::OsString, fs, process::exit};
use utils::prompts;

use crate::{
package_manager::PackageManager,
Expand Down Expand Up @@ -35,19 +36,20 @@ where
I: IntoIterator<Item = A>,
A: Into<OsString> + Clone,
{
handle_brand_text("\n ⚡ Welcome To Farm ! \n");

let detected_manager = detected_manager.and_then(|p| p.parse::<PackageManager>().ok());
// Clap will auto parse the `bin_name` as the first argument, so we need to add it to the args
let args = args::Args::parse_from(
std::iter::once(OsString::from(bin_name.unwrap_or_default()))
.chain(args.into_iter().map(Into::into)),
);

handle_brand_text("\n ⚡ Welcome To Farm ! \n");
let defaults = args::Args::default();
let args::Args {
manager,
project_name,
template,
force,
} = args;
let cwd = std::env::current_dir()?;
let project_name = match project_name {
Expand All @@ -66,21 +68,22 @@ where
let target_dir = cwd.join(&project_name);

if target_dir.exists() && target_dir.read_dir()?.next().is_some() {
let overwrite = Confirm::with_theme(&ColorfulTheme::default())
.with_prompt(format!(
"{} directory is not empty, do you want to overwrite?",
if target_dir == cwd {
"Current".to_string()
} else {
target_dir
.file_name()
.unwrap()
.to_string_lossy()
.to_string()
}
))
.default(false)
.interact()?;
let overwrite = force
|| prompts::confirm(
&format!(
"{} directory is not empty, do you want to overwrite?",
if target_dir == cwd {
"Current".to_string()
} else {
target_dir
.file_name()
.unwrap()
.to_string_lossy()
.to_string()
}
),
false,
)?;
if !overwrite {
eprintln!("{BOLD}{RED}✘{RESET} Directory is not empty, Operation Cancelled");
exit(1);
Expand All @@ -97,80 +100,41 @@ where
let template = match template {
Some(template) => template,
None => {
let templates_text = templates_no_flavors
.iter()
.map(|t| t.select_text())
.collect::<Vec<_>>();

let index = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Select a framework:")
.items(&templates_text)
.default(0)
.interact()?;

let selected_template = templates_no_flavors[index];
let selected_template =
prompts::select("Select a framework:", &templates_no_flavors, Some(0))?.unwrap();

match selected_template {
Template::Tauri(None) => {
let sub_templates_text = vec![
let sub_templates = vec![
TauriSubTemplate::React,
TauriSubTemplate::Vue,
TauriSubTemplate::Svelte,
TauriSubTemplate::Vanilla,
TauriSubTemplate::Solid,
TauriSubTemplate::Preact,
]
.iter()
.map(|sub_template| format!("{}", sub_template))
.collect::<Vec<_>>();

let sub_template_index = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Select a Tauri template:")
.items(&sub_templates_text)
.default(0)
.interact()?;

let sub_template = match sub_template_index {
0 => TauriSubTemplate::React,
1 => TauriSubTemplate::Vue,
2 => TauriSubTemplate::Svelte,
3 => TauriSubTemplate::Vanilla,
4 => TauriSubTemplate::Solid,
5 => TauriSubTemplate::Preact,
_ => unreachable!(),
};
Template::Tauri(Some(sub_template))
];

let sub_template =
prompts::select("Select a Tauri template:", &sub_templates, Some(0))?.unwrap();

Template::Tauri(Some(*sub_template))
}
Template::Electron(None) => {
let sub_templates_text = vec![
let sub_templates = vec![
ElectronSubTemplate::React,
ElectronSubTemplate::Vue,
ElectronSubTemplate::Svelte,
ElectronSubTemplate::Vanilla,
ElectronSubTemplate::Solid,
ElectronSubTemplate::Preact,
]
.iter()
.map(|sub_template| format!("{}", sub_template))
.collect::<Vec<_>>();

let sub_template_index = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Select an Electron template:")
.items(&sub_templates_text)
.default(0)
.interact()?;

let sub_template = match sub_template_index {
0 => ElectronSubTemplate::React,
1 => ElectronSubTemplate::Vue,
2 => ElectronSubTemplate::Svelte,
3 => ElectronSubTemplate::Vanilla,
4 => ElectronSubTemplate::Solid,
5 => ElectronSubTemplate::Preact,
_ => unreachable!(),
};
Template::Electron(Some(sub_template))
];

let sub_template =
prompts::select("Select an Electron template:", &sub_templates, Some(0))?.unwrap();

Template::Electron(Some(*sub_template))
}
_ => selected_template,
_ => *selected_template,
}
}
};
Expand All @@ -196,7 +160,7 @@ where
let _ = fs::create_dir_all(&target_dir);
}

// Render the template
// Render the template
template.render(&target_dir, pkg_manager, &project_name, &project_name)?;

handle_brand_text("\n > Initial Farm Project created successfully ✨ ✨ \n");
Expand All @@ -214,7 +178,7 @@ where
if let Some(cmd) = pkg_manager.install_cmd() {
handle_brand_text(&format!(" {} \n", cmd));
}
handle_brand_text(&format!(" {} \n", &pkg_manager.run_cmd()));
handle_brand_text(&format!(" {} \n", get_run_cmd(&pkg_manager, &template)));

Ok(())
}
Expand Down Expand Up @@ -244,3 +208,15 @@ fn to_valid_pkg_name(project_name: &str) -> String {
ret
}
}

fn get_run_cmd(pkg_manager: &PackageManager, template: &Template) -> &'static str {
match template {
Template::Tauri(_) => match pkg_manager {
PackageManager::Pnpm => "pnpm tauri dev",
PackageManager::Yarn => "yarn tauri dev",
PackageManager::Npm => "npm run tauri dev",
PackageManager::Bun => "bun tauri dev",
},
_ => pkg_manager.default_cmd(),
}
}
34 changes: 1 addition & 33 deletions crates/create-farm-rs/src/package_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,6 @@ impl<'a> PackageManager {
PackageManager::Npm,
PackageManager::Bun,
];

/// Node.js managers
pub const _NODE: &'a [PackageManager] = &[
PackageManager::Pnpm,
PackageManager::Yarn,
PackageManager::Npm,
PackageManager::Bun,
];
}

impl PackageManager {
Expand All @@ -85,23 +77,6 @@ impl PackageManager {
}
}

pub const fn _templates(&self) -> &[Template] {
match self {
PackageManager::Pnpm | PackageManager::Yarn | PackageManager::Npm | PackageManager::Bun => &[
Template::Vanilla,
Template::React,
Template::Vue3,
Template::Vue2,
Template::Svelte,
Template::Solid,
Template::Lit,
Template::Preact,
Template::Tauri(None),
Template::Electron(None)
],
}
}

pub const fn install_cmd(&self) -> Option<&str> {
match self {
PackageManager::Pnpm => Some("pnpm install"),
Expand All @@ -111,19 +86,12 @@ impl PackageManager {
}
}

pub const fn run_cmd(&self) -> &str {
pub const fn default_cmd(&self) -> &'static str {
match self {
PackageManager::Pnpm => "pnpm dev",
PackageManager::Yarn => "yarn dev",
PackageManager::Npm => "npm run dev",
PackageManager::Bun => "bun run dev",
}
}

pub const fn _is_node(&self) -> bool {
matches!(
self,
PackageManager::Pnpm | PackageManager::Yarn | PackageManager::Npm | PackageManager::Bun,
)
}
}
Loading
Loading