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

Fix #1119 csr remove unecessary code #1170

Open
wants to merge 20 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
c09fde4
refactor: rename asset tests to rendering_method tests
JonasCir Jan 5, 2025
341b69f
refactor: rename AssetsOption to RenderingMethodOption
JonasCir Jan 5, 2025
be15960
refactor: rename rendering_method template tests from asset to render…
JonasCir Jan 5, 2025
4908dff
refactor: rename remaining occurences of assets vars to rendering_met…
JonasCir Jan 5, 2025
53ef8e7
refactor: rename Asset to RenderingMethod
JonasCir Jan 5, 2025
f0a8160
refactor: rename Selections.asset -> rendering_method
JonasCir Jan 5, 2025
8c4d874
refactor: rename ArgsPlaceholder.asset -> rendering_method
JonasCir Jan 5, 2025
7dce087
refactor: rename Settings.asset -> rendering_method. Adjust templatin…
JonasCir Jan 5, 2025
9d9e7d4
refactor: rename asset scope var to rendering_method
JonasCir Jan 5, 2025
2b16fba
refactor: rename the remaing asset occurences
JonasCir Jan 5, 2025
586d4cd
refactor: rename the remaing asset occurences in main.rs
JonasCir Jan 5, 2025
476ef5c
refactor: rename the remaing asset occurences in tests
JonasCir Jan 5, 2025
c60a557
fix: view_engine is not needed for csr
JonasCir Jan 10, 2025
6dbc1cd
fix: asset folder is not needed for csr
JonasCir Jan 10, 2025
0d0eb50
fix: cargo dependencies for csr
JonasCir Jan 10, 2025
7d60ac0
fix: use initializers module if there is any
JonasCir Jan 10, 2025
af375f3
style: run nightly cargo fmt
JonasCir Jan 10, 2025
016cd49
style: fix rhai_settings_extensions imports
JonasCir Jan 10, 2025
9c472fa
docs: add documentation
JonasCir Jan 10, 2025
4bdbfac
Merge branch 'master' into fix/#1119-csr-remove-unecessary-code
kaplanelad Jan 14, 2025
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
4 changes: 2 additions & 2 deletions loco-new/base_template/.github/workflows/ci.yaml.t
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ jobs:
with:
toolchain: ${% raw %}{{ env.RUST_TOOLCHAIN }}{% endraw %}

{%- if settings.asset %}
{%- if settings.asset.kind == "client" %}
{%- if settings.rendering_method %}
{%- if settings.rendering_method.kind == "client" %}
- name: Setup node
uses: actions/setup-node@v4
with:
Expand Down
4 changes: 3 additions & 1 deletion loco-new/base_template/Cargo.toml.t
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,14 @@ uuid = { version = "1.6.0", features = ["v4"] }
include_dir = { version = "0.7" }
{%- endif %}

{%- if settings.asset %}
{%- if settings.rendering_method.kind %}
{%- if settings.rendering_method.kind == "server" %}
# view engine i18n
fluent-templates = { version = "0.8.0", features = ["tera"] }
unic-langid = { version = "0.9.4" }
# /view engine
{%- endif %}
{%- endif %}

[[bin]]
name = "{{settings.module_name}}-cli"
Expand Down
6 changes: 3 additions & 3 deletions loco-new/base_template/config/development.yaml.t
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ server:
host: http://localhost
# Out of the box middleware configuration. to disable middleware you can changed the `enable` field to `false` of comment the middleware block
middlewares:
{%- if settings.asset %}
{%- if settings.asset.kind == "server" %}
{%- if settings.rendering_method %}
{%- if settings.rendering_method.kind == "server" %}
static:
enable: true
must_exist: true
Expand All @@ -34,7 +34,7 @@ server:
uri: "/static"
path: "assets/static"
fallback: "assets/static/404.html"
{%- elif settings.asset.kind == "client" %}
{%- elif settings.rendering_method.kind == "client" %}
fallback:
enable: false
static:
Expand Down
6 changes: 3 additions & 3 deletions loco-new/base_template/config/test.yaml.t
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ server:
host: http://localhost
# Out of the box middleware configuration. to disable middleware you can changed the `enable` field to `false` of comment the middleware block
middlewares:
{%- if settings.asset %}
{%- if settings.asset.kind == "server" %}
{%- if settings.rendering_method %}
{%- if settings.rendering_method.kind == "server" %}
static:
enable: true
must_exist: true
Expand All @@ -32,7 +32,7 @@ server:
uri: "/static"
path: "assets/static"
fallback: "assets/static/404.html"
{%- elif settings.asset.kind == "client" %}
{%- elif settings.rendering_method.kind == "client" %}
fallback:
enable: false
static:
Expand Down
6 changes: 3 additions & 3 deletions loco-new/setup.rhai
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ if db {
// =====================
// Initializers Support
// =====================
if initializers {
if settings.initializers.view_engine {
gen.copy_file("src/initializers/view_engine.rs"); // Template for view engine initializer
}

Expand Down Expand Up @@ -125,7 +125,7 @@ if background {
// =====================
// Adds asset directory if assets are configured in the app.

if asset {
if settings.assets {
gen.copy_dir("assets"); // Static assets directory
}

Expand All @@ -134,7 +134,7 @@ if asset {
// Client side
// =====================

if settings.clientside {
if settings.rendering_method.client_side {
gen.copy_dir("frontend");
gen.create_file("frontend/dist/index.html", "this is a placeholder. please run your frontend build (npm build)");
}
14 changes: 9 additions & 5 deletions loco-new/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ enum Commands {
#[arg(long)]
bg: Option<wizard::BackgroundOption>,

/// Assets serving configuration
/// Frontend rendering method configuration
#[arg(long)]
assets: Option<wizard::AssetsOption>,
rendering_method: Option<wizard::RenderingMethodOption>,

/// Create the starter in target git repository
#[arg(short, long)]
Expand Down Expand Up @@ -82,12 +82,12 @@ fn main() -> Result<()> {
path,
db,
bg,
assets,
rendering_method,
name,
allow_in_git_repo,
os,
} => {
tracing::debug!(path = ?path, db = ?db, bg=?bg, assets=?assets,name=?name, allow_in_git_repo=allow_in_git_repo, os=?os, "CLI options");
tracing::debug!(path = ?path, db = ?db, bg=?bg, rendering_method=?rendering_method,name=?name, allow_in_git_repo=allow_in_git_repo, os=?os, "CLI options");
if !allow_in_git_repo && is_a_git_repo(path.as_path()).unwrap_or(false) {
tracing::debug!("the target directory is a Git repository");
wizard::warn_if_in_git_repo()?;
Expand All @@ -106,7 +106,11 @@ fn main() -> Result<()> {
tracing::debug!(dir = %to.display(), "creating application directory");
std::fs::create_dir_all(&to)?;

let args = wizard::ArgsPlaceholder { db, bg, assets };
let args = wizard::ArgsPlaceholder {
db,
bg,
rendering_method,
};
let user_selection = wizard::start(&args)?;

let generator_tmp_folder = extract_default_template()?;
Expand Down
53 changes: 46 additions & 7 deletions loco-new/src/generator/mod.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
//! This module defines the `Generator` struct, which is responsible for
//! executing scripted commands

use std::path::{Path, PathBuf};
pub mod executer;
pub mod template;
use std::sync::Arc;

use std::{
path::{Path, PathBuf},
sync::Arc,
};

use include_dir::{include_dir, Dir};
use rhai::{Engine, Scope};
use rhai::{export_module, exported_module, plugin::*, Dynamic, Engine, Scope};

use crate::{settings, OS};
use crate::{
settings,
settings::{Initializers, RenderingMethod},
wizard::RenderingMethodOption,
OS,
};

static APP_TEMPLATE: Dir<'_> = include_dir!("base_template");

Expand Down Expand Up @@ -68,7 +76,12 @@ impl Generator {
);
engine
.build_type::<settings::Settings>()
.build_type::<settings::Initializers>()
.register_type_with_name::<Option<Initializers>>("Option<Initializers>")
.register_type_with_name::<Option<RenderingMethod>>("Option<RenderingMethod>")
.register_static_module(
"rhai_settings_extensions",
exported_module!(rhai_settings_extensions).into(),
)
.register_fn("copy_file", Self::copy_file)
.register_fn("create_file", Self::create_file)
.register_fn("copy_files", Self::copy_files)
Expand All @@ -85,8 +98,6 @@ impl Generator {
// TODO:: move it as part of the settings?
scope.push("db", self.settings.db.is_some());
scope.push("background", self.settings.background.is_some());
scope.push("initializers", self.settings.initializers.is_some());
scope.push("asset", self.settings.asset.is_some());
scope.push("windows", self.settings.os == OS::Windows);

engine.run_with_scope(&mut scope, script)?;
Expand Down Expand Up @@ -232,6 +243,34 @@ impl Generator {
}
}

/// This module provides extensions to the Rhai scripting language to access
/// the inner fields of the [Settings] struct in a more ergonomic way.
#[export_module]
mod rhai_settings_extensions {

/// Gives the script access to `settings.initializers.view_engine`.
#[rhai_fn(global, get = "view_engine", pure)]
pub fn view_engine(initializers: &mut Option<Initializers>) -> bool {
initializers.as_ref().map_or(false, |i| i.view_engine)
}

/// Gives the script access to `settings.rendering_method.client_side`.
#[rhai_fn(global, get = "client_side", pure)]
pub fn client_side(rendering_method: &mut Option<RenderingMethod>) -> bool {
rendering_method.as_ref().map_or(false, |r| {
matches!(r.kind, RenderingMethodOption::Clientside)
})
}

/// Gives the script access to `settings.rendering_method.server_side`.
#[rhai_fn(global, get = "server_side", pure)]
pub fn server_side(rendering_method: &mut Option<RenderingMethod>) -> bool {
rendering_method.as_ref().map_or(false, |r| {
matches!(r.kind, RenderingMethodOption::Serverside)
})
}
}

#[cfg(test)]
mod tests {
use executer::MockExecuter;
Expand Down
56 changes: 36 additions & 20 deletions loco-new/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use rhai::{CustomType, TypeBuilder};
use serde::{Deserialize, Serialize};

use crate::{
wizard::{self, AssetsOption, BackgroundOption, DBOption},
wizard::{self, BackgroundOption, DBOption, RenderingMethodOption},
LOCO_VERSION, OS,
};

Expand All @@ -18,10 +18,12 @@ pub struct Settings {
pub module_name: String,
pub db: Option<Db>,
pub background: Option<Background>,
pub asset: Option<Asset>,
/// Frontend rendering method configuration
pub rendering_method: Option<RenderingMethod>,
/// Copy the asset folder to the new project
pub assets: bool,
pub auth: bool,
pub mailer: bool,
pub clientside: bool,
pub initializers: Option<Initializers>,
pub features: Features,
pub loco_version_text: String,
Expand Down Expand Up @@ -49,11 +51,13 @@ impl From<BackgroundOption> for Option<Background> {
}
}

impl From<AssetsOption> for Option<Asset> {
fn from(asset: AssetsOption) -> Self {
match asset {
AssetsOption::None => None,
_ => Some(Asset { kind: asset }),
impl From<RenderingMethodOption> for Option<RenderingMethod> {
fn from(rendering_method: RenderingMethodOption) -> Self {
match rendering_method {
RenderingMethodOption::None => None,
_ => Some(RenderingMethod {
kind: rendering_method,
}),
}
}
}
Expand All @@ -72,20 +76,32 @@ impl Settings {
features
};

// we only need the view engine initializer for serverside rendering
let initializers = if matches!(
prompt_selection.rendering_method,
RenderingMethodOption::Serverside
) {
Some(Initializers { view_engine: true })
} else {
None
};

// we only need to copy the asset folder for serverside rendering
let assets = matches!(
prompt_selection.rendering_method,
RenderingMethodOption::Serverside
);

Self {
package_name: package_name.to_string(),
module_name: package_name.to_snake_case(),
assets,
auth: prompt_selection.db.enable() && prompt_selection.background.enable(),
mailer: prompt_selection.db.enable() && prompt_selection.background.enable(),
db: prompt_selection.db.clone().into(),
background: prompt_selection.background.clone().into(),
asset: prompt_selection.asset.clone().into(),
clientside: prompt_selection.asset.enable(),
initializers: if prompt_selection.asset.enable() {
Some(Initializers { view_engine: true })
} else {
None
},
rendering_method: prompt_selection.rendering_method.clone().into(),
initializers,
features,
loco_version_text: get_loco_version_text(),
os,
Expand All @@ -100,10 +116,10 @@ impl Default for Settings {
module_name: Default::default(),
db: Default::default(),
background: Default::default(),
asset: Default::default(),
rendering_method: Default::default(),
assets: Default::default(),
auth: Default::default(),
mailer: Default::default(),
clientside: Default::default(),
initializers: Default::default(),
features: Default::default(),
loco_version_text: get_loco_version_text(),
Expand Down Expand Up @@ -135,10 +151,10 @@ pub struct Background {
pub kind: BackgroundOption,
}

/// Asset configuration settings.
/// Rendering method configuration.
#[derive(Serialize, Deserialize, Clone, Debug, Default, CustomType)]
pub struct Asset {
pub kind: AssetsOption,
pub struct RenderingMethod {
pub kind: RenderingMethodOption,
}

#[derive(Serialize, Deserialize, Clone, Debug, Default, CustomType)]
Expand Down
Loading