Content-Length: 631359 | pFad | http://github.com/postgresml/postgresml/pull/1037/files

F5 Add node resolver to pgml-components by levkk · Pull Request #1037 · postgresml/postgresml · GitHub
Skip to content

Add node resolver to pgml-components #1037

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

Merged
merged 3 commits into from
Sep 30, 2023
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
4 changes: 3 additions & 1 deletion pgml-apps/cargo-pgml-components/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion pgml-apps/cargo-pgml-components/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "cargo-pgml-components"
version = "0.1.15"
version = "0.1.16"
edition = "2021"
authors = ["PostgresML <team@postgresml.org>"]
license = "MIT"
Expand All @@ -19,6 +19,8 @@ anyhow = "1"
owo-colors = "3"
sailfish = "0.8"
regex = "1"
toml = "0.7"
serde = { version = "1", features = ["derive"] }

[dev-dependencies]
assert_cmd = "2"
Expand Down
33 changes: 33 additions & 0 deletions pgml-apps/cargo-pgml-components/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Default, Clone)]
pub struct Javascript {
#[serde(default = "Javascript::default_additional_paths")]
pub additional_paths: Vec<String>,
}

impl Javascript {
fn default_additional_paths() -> Vec<String> {
vec![]
}
}

#[derive(Serialize, Deserialize, Default, Clone)]
pub struct Config {
pub javascript: Javascript,
}

impl Config {
pub fn from_path(path: &str) -> anyhow::Result<Config> {
let config_str = std::fs::read_to_string(path)?;
let config: Config = toml::from_str(&config_str)?;
Ok(config)
}

pub fn load() -> Config {
match Self::from_path("pgml-components.toml") {
Ok(config) => config,
Err(_) => Config::default(),
}
}
}
13 changes: 4 additions & 9 deletions pgml-apps/cargo-pgml-components/src/frontend/components.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,10 +191,7 @@ fn update_module(path: &Path) {
}

if has_more_modules(&path) {
debug!("{} has more modules", path.display());
update_module(&path);
} else {
debug!("it does not really no");
}

let component_path = path.components().skip(2).collect::<PathBuf>();
Expand All @@ -205,8 +202,7 @@ fn update_module(path: &Path) {
debug!("writing {} modules to mod.rs", modules.len());

let components_mod = path.join("mod.rs");
let modules =
unwrap_or_exit!(templates::Mod { modules }.render_once()).replace("\n\n", "\n");
let modules = unwrap_or_exit!(templates::Mod { modules }.render_once()).replace("\n\n", "\n");

let existing_modules = if components_mod.is_file() {
unwrap_or_exit!(read_to_string(&components_mod))
Expand All @@ -220,15 +216,15 @@ fn update_module(path: &Path) {
info(&format!("written {}", components_mod.display().to_string()));
}

debug!("mod.rs is the same");
debug!("{}/mod.rs is different", components_mod.display());
}

//github.com/ Check that the path has more Rust modules.
fn has_more_modules(path: &Path) -> bool {
debug!("checking if {} has more modules", path.display());

if !path.exists() {
debug!("path does not exist");
debug!("path {} does not exist", path.display());
return false;
}

Expand All @@ -244,13 +240,12 @@ fn has_more_modules(path: &Path) -> bool {

if let Some(file_name) = path.file_name() {
if file_name != "mod.rs" {
debug!("it has another file that's not mod.rs");
debug!("{} has another file that's not mod.rs", path.display());
return false;
}
}
}

debug!("it does");
true
}

Expand Down
83 changes: 56 additions & 27 deletions pgml-apps/cargo-pgml-components/src/frontend/javascript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use std::process::{exit, Command};

use convert_case::{Case, Casing};

use crate::config::Config;
use crate::frontend::tools::execute_with_nvm;
use crate::util::{error, info, unwrap_or_exit, warn};

Expand Down Expand Up @@ -42,16 +43,26 @@ fn cleanup_old_bundles() {
}
}

fn assemble_modules() {
fn assemble_modules(config: Config) {
let js = unwrap_or_exit!(glob(MODULES_GLOB));
let js = js.chain(unwrap_or_exit!(glob(STATIC_JS_GLOB)));
let mut js = js
.chain(unwrap_or_exit!(glob(STATIC_JS_GLOB)))
.collect::<Vec<_>>();

for path in &config.javascript.additional_paths {
debug!("adding additional path to javascript bundle: {}", path);
js = js
.into_iter()
.chain(unwrap_or_exit!(glob(path)))
.collect::<Vec<_>>();
}

// Don't bundle artifacts we produce.
let js = js.filter(|path| {
let js = js.iter().filter(|path| {
let path = path.as_ref().unwrap();
let path = path.display().to_string();

!path.contains("main.js") && !path.contains("bundle.js") && !path.contains("modules.js")
!path.contains("main.") && !path.contains("bundle.") && !path.contains("modules.")
});

let mut modules = unwrap_or_exit!(File::create(MODULES_FILE));
Expand All @@ -75,27 +86,37 @@ fn assemble_modules() {

let full_path = source.display().to_string();

let path = source
.components()
.skip(2) // skip src/components or static/js
.collect::<Vec<_>>();
let path = source.components().collect::<Vec<_>>();

assert!(!path.is_empty());

let path = path.iter().collect::<PathBuf>();
let components = path.components();
let controller_name = if components.clone().count() > 1 {
components
let file_stem = path.file_stem().unwrap().to_str().unwrap().to_string();
let controller_name = if file_stem.ends_with("controller") {
let mut parts = vec![];

let pp = components
.map(|c| c.as_os_str().to_str().expect("component to be valid utf-8"))
.filter(|c| !c.ends_with(".js"))
.collect::<Vec<&str>>()
.join("_")
.collect::<Vec<&str>>();
let mut saw_src = false;
let mut saw_components = false;
for p in pp {
if p == "src" {
saw_src = true;
} else if p == "components" {
saw_components = true;
} else if saw_src && saw_components {
parts.push(p);
}
}

assert!(!parts.is_empty());

parts.join("_")
} else {
path.file_stem()
.expect("old controllers to be a single file")
.to_str()
.expect("stemp to be valid utf-8")
.to_string()
file_stem
};
let upper_camel = controller_name.to_case(Case::UpperCamel).to_string();
let controller_name = controller_name.replace("_", "-");
Expand All @@ -121,20 +142,28 @@ fn assemble_modules() {
info(&format!("written {}", MODULES_FILE));
}

pub fn bundle() {
pub fn bundle(config: Config, minify: bool) {
cleanup_old_bundles();
assemble_modules();
assemble_modules(config.clone());

let mut command = Command::new(JS_COMPILER);

command
.arg(MODULES_FILE)
.arg("--file")
.arg(JS_FILE)
.arg("--format")
.arg("es")
.arg("-p")
.arg("@rollup/plugin-node-resolve");

if minify {
command.arg("-p").arg("@rollup/plugin-terser");
}

// Bundle JavaScript.
info("bundling javascript with rollup");
unwrap_or_exit!(execute_with_nvm(
Command::new(JS_COMPILER)
.arg(MODULES_FILE)
.arg("--file")
.arg(JS_FILE)
.arg("--format")
.arg("es"),
));
unwrap_or_exit!(execute_with_nvm(&mut command));

info(&format!("written {}", JS_FILE));

Expand Down
25 changes: 24 additions & 1 deletion pgml-apps/cargo-pgml-components/src/frontend/tools.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
//! Tools required by us to build stuff.

use crate::util::{debug1, error, execute_command, unwrap_or_exit, warn};
use crate::util::{debug1, error, execute_command, info, unwrap_or_exit, warn};
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::{exit, Command};

//github.com/ Required tools.
static TOOLS: &[&str] = &["sass", "rollup"];
static ROLLUP_PLUGINS: &[&str] = &["@rollup/plugin-terser", "@rollup/plugin-node-resolve"];
static NVM_EXEC: &'static str = "/tmp/pgml-components-nvm.sh";
static NVM_SOURCE: &'static str = "https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh";
static NVM_SOURCE_DOWNLOADED: &'static str = "/tmp/pgml-components-nvm-source.sh";
Expand All @@ -30,6 +32,27 @@ pub fn install() {
}
}
}

for plugin in ROLLUP_PLUGINS {
if execute_with_nvm(
Command::new("rollup")
.arg("-p")
.arg(plugin)
.arg("--version"),
)
.is_err()
{
warn(&format!("installing rollup plugin {}", plugin));
unwrap_or_exit!(execute_with_nvm(
Command::new("npm").arg("install").arg("-g").arg(plugin)
));
}
}

if Path::new("package.json").exists() {
info("installing dependencies from package.json");
unwrap_or_exit!(execute_with_nvm(Command::new("npm").arg("install")));
}
}

//github.com/ Execute a command making sure that nvm is available.
Expand Down
15 changes: 11 additions & 4 deletions pgml-apps/cargo-pgml-components/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ use std::path::Path;
extern crate log;

mod backend;
mod config;
mod frontend;
mod util;

use config::Config;
use util::{info, unwrap_or_exit};

//github.com/ These paths are exepcted to exist in the project directory.
Expand Down Expand Up @@ -51,7 +54,10 @@ struct PgmlCommands {
#[derive(Subcommand, Debug)]
enum Commands {
//github.com/ Bundle SASS and JavaScript into neat bundle files.
Bundle {},
Bundle {
#[arg(short, long, default_value = "false")]
minify: bool,
},

//github.com/ Add new elements to the project.
#[command(subcommand)]
Expand All @@ -65,14 +71,15 @@ enum AddCommands {
}

fn main() {
let config = Config::load();
env_logger::init();
let cli = Cli::parse();

match cli.subcomand {
CargoSubcommands::PgmlComponents(pgml_commands) => {
validate_project(pgml_commands.project_path);
match pgml_commands.command {
Commands::Bundle {} => bundle(),
Commands::Bundle { minify } => bundle(config, minify),
Commands::Add(command) => match command {
AddCommands::Component { name } => {
crate::frontend::components::add(&Path::new(&name), pgml_commands.overwrite)
Expand Down Expand Up @@ -108,9 +115,9 @@ fn validate_project(project_path: Option<String>) {
}

//github.com/ Bundle SASS and JavaScript into neat bundle files.
fn bundle() {
fn bundle(config: Config, minify: bool) {
frontend::sass::bundle();
frontend::javascript::bundle();
frontend::javascript::bundle(config, minify);
frontend::components::update_modules();

info("bundle complete");
Expand Down
2 changes: 2 additions & 0 deletions pgml-apps/cargo-pgml-components/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ pub fn warn(value: &str) {
}

pub fn execute_command(command: &mut Command) -> std::io::Result<String> {
debug!("Executing {:?}", command);

let output = match command.output() {
Ok(output) => output,
Err(err) => {
Expand Down








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/postgresml/postgresml/pull/1037/files

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy