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

Make codegen only generate one output file #79

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
16 changes: 10 additions & 6 deletions src/commands/init.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use crate::commands::sync::config::CodegenLanguage;

use super::sync::config::{CodegenConfig, CodegenStyle, Creator, CreatorType, SyncConfig};
use anyhow::Context;
use console::style;
Expand Down Expand Up @@ -52,11 +54,13 @@ pub async fn init() -> anyhow::Result<()> {
.prompt_skippable()
.unwrap_or_else(|_| exit(1));

let typescript = Confirm::new("TypeScript support")
.with_help_message("Generate TypeScript definition files.")
.with_default(false)
.prompt()
.unwrap_or_else(|_| exit(1));
let codegen_language = Select::new(
"Language",
vec![CodegenLanguage::Luau, CodegenLanguage::TypeScript],
)
.with_help_message("The language to generate code in.")
.prompt()
.unwrap_or_else(|_| exit(1));

let codegen_style = Select::new("Style", vec![CodegenStyle::Flat, CodegenStyle::Nested])
.with_help_message("The style to use for generated code.")
Expand All @@ -76,7 +80,7 @@ pub async fn init() -> anyhow::Result<()> {
creator: Creator { creator_type, id },
codegen: CodegenConfig {
output_name,
typescript: Some(typescript),
language: Some(codegen_language),
style: Some(codegen_style),
strip_extension: Some(strip_extension),
},
Expand Down
4 changes: 2 additions & 2 deletions src/commands/sync/codegen/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ impl AstFormat for ReturnStatement {
write!(output, "return ")
}
AstTarget::Typescript { output_dir } => {
write!(output, "declare const {output_dir}: ")
write!(output, "const {output_dir} = ")
}
}?;

Expand Down Expand Up @@ -148,7 +148,7 @@ impl AstFormat for Table {
fn fmt_ast(&self, output: &mut AstStream<'_, '_>) -> fmt::Result {
let typescript = matches!(output.target, AstTarget::Typescript { .. });
let (assignment, ending) = if typescript {
(": ", ";")
(": ", ",")
} else {
(" = ", ",")
};
Expand Down
41 changes: 21 additions & 20 deletions src/commands/sync/codegen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,32 +5,33 @@ use ast::{AstTarget, Expression, ReturnStatement};

use crate::commands::sync::config::CodegenStyle;

use super::config::CodegenLanguage;

mod ast;
mod flat;
mod nested;

pub fn generate_luau(
assets: &BTreeMap<String, String>,
strip_dir: &str,
style: &CodegenStyle,
strip_extension: bool,
) -> anyhow::Result<String> {
match style {
CodegenStyle::Flat => flat::generate_luau(assets, strip_dir, strip_extension),
CodegenStyle::Nested => nested::generate_luau(assets, strip_dir, strip_extension),
}
}

pub fn generate_ts(
pub fn generate_file(
assets: &BTreeMap<String, String>,
strip_dir: &str,
output_dir: &str,
language: &CodegenLanguage,
style: &CodegenStyle,
strip_extension: bool,
) -> anyhow::Result<String> {
match style {
CodegenStyle::Flat => flat::generate_ts(assets, strip_dir, output_dir, strip_extension),
CodegenStyle::Nested => nested::generate_ts(assets, strip_dir, output_dir, strip_extension),
match (language, style) {
(CodegenLanguage::Luau, CodegenStyle::Flat) => {
flat::generate_luau(assets, strip_dir, strip_extension)
}
(CodegenLanguage::TypeScript, CodegenStyle::Flat) => {
flat::generate_ts(assets, strip_dir, output_dir, strip_extension)
}
(CodegenLanguage::Luau, CodegenStyle::Nested) => {
nested::generate_luau(assets, strip_dir, strip_extension)
}
(CodegenLanguage::TypeScript, CodegenStyle::Nested) => {
nested::generate_ts(assets, strip_dir, output_dir, strip_extension)
}
}
}

Expand Down Expand Up @@ -73,10 +74,10 @@ mod tests {
let lockfile = test_assets();

let ts = super::flat::generate_ts(&lockfile, "assets", "assets", false).unwrap();
assert_eq!(ts, "declare const assets: {\n\t\"/bar/baz.png\": \"rbxasset://.asphalt/bar/baz.png\";\n\t\"/foo.png\": \"rbxassetid://1\";\n};\nexport = assets;\n");
assert_eq!(ts, "const assets = {\n\t\"/bar/baz.png\": \"rbxasset://.asphalt/bar/baz.png\",\n\t\"/foo.png\": \"rbxassetid://1\",\n};\nexport = assets;\n");

let ts = super::flat::generate_ts(&lockfile, "assets", "assets", true).unwrap();
assert_eq!(ts, "declare const assets: {\n\t\"/bar/baz\": \"rbxasset://.asphalt/bar/baz.png\";\n\t\"/foo\": \"rbxassetid://1\";\n};\nexport = assets;\n");
assert_eq!(ts, "const assets = {\n\t\"/bar/baz\": \"rbxasset://.asphalt/bar/baz.png\",\n\t\"/foo\": \"rbxassetid://1\",\n};\nexport = assets;\n");
}

#[test]
Expand All @@ -103,13 +104,13 @@ mod tests {
let ts = super::nested::generate_ts(&lockfile, "assets", "assets", false).unwrap();
assert_eq!(
ts,
"declare const assets: {\n\tbar: {\n\t\t\"baz.png\": \"rbxasset://.asphalt/bar/baz.png\";\n\t};\n\t\"foo.png\": \"rbxassetid://1\";\n};\nexport = assets;\n"
"const assets = {\n\tbar: {\n\t\t\"baz.png\": \"rbxasset://.asphalt/bar/baz.png\",\n\t};\n\t\"foo.png\": \"rbxassetid://1\",\n};\nexport = assets;\n"
);

let ts = super::nested::generate_ts(&lockfile, "assets", "assets", true).unwrap();
assert_eq!(
ts,
"declare const assets: {\n\tbar: {\n\t\tbaz: \"rbxasset://.asphalt/bar/baz.png\";\n\t};\n\tfoo: \"rbxassetid://1\";\n};\nexport = assets;\n"
"const assets = {\n\tbar: {\n\t\tbaz: \"rbxasset://.asphalt/bar/baz.png\",\n\t};\n\tfoo: \"rbxassetid://1\",\n};\nexport = assets;\n"
);
}
}
27 changes: 26 additions & 1 deletion src/commands/sync/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,31 @@ impl Display for CodegenStyle {
}
}

#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CodegenLanguage {
Luau,
TypeScript,
}

impl Display for CodegenLanguage {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
CodegenLanguage::Luau => write!(f, "Luau"),
CodegenLanguage::TypeScript => write!(f, "TypeScript"),
}
}
}

impl CodegenLanguage {
pub fn extension(&self) -> &'static str {
match self {
CodegenLanguage::Luau => "luau",
CodegenLanguage::TypeScript => "ts",
}
}
}

#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum CreatorType {
Expand Down Expand Up @@ -53,7 +78,7 @@ pub struct ExistingAsset {
#[derive(Debug, Deserialize, Serialize)]
pub struct CodegenConfig {
pub output_name: Option<String>,
pub typescript: Option<bool>,
pub language: Option<CodegenLanguage>,
pub style: Option<CodegenStyle>,
pub strip_extension: Option<bool>,
}
Expand Down
34 changes: 13 additions & 21 deletions src/commands/sync/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use anyhow::Context;
use backend::{
cloud::CloudBackend, debug::DebugBackend, studio::StudioBackend, SyncBackend, SyncResult,
};
use codegen::{generate_luau, generate_ts};
use codegen::generate_file;
use config::SyncConfig;
use log::{debug, info, warn};
use std::{
Expand Down Expand Up @@ -194,30 +194,22 @@ pub async fn sync(args: SyncArgs, existing_lockfile: LockFile) -> anyhow::Result
(path, format_asset_id(asset.id))
}));

let luau_filename = format!("{}.{}", state.output_name, "luau");
let luau_output = generate_luau(&assets, asset_dir, &state.style, state.strip_extension);
let codegen_output = generate_file(
&assets,
asset_dir,
&state.output_name,
&state.language,
&state.style,
state.strip_extension,
)?;
let codegen_filename = format!("{}.{}", state.output_name, state.language.extension());

write(
Path::new(&state.write_dir).join(luau_filename),
luau_output?,
Path::new(&state.write_dir).join(codegen_filename),
codegen_output,
)
.await
.context("Failed to write output Luau file")?;

if state.typescript {
let ts_filename = format!("{}.d.ts", state.output_name);
let ts_output = generate_ts(
&assets,
asset_dir,
state.output_name.as_str(),
&state.style,
state.strip_extension,
);

write(Path::new(&state.write_dir).join(ts_filename), ts_output?)
.await
.context("Failed to write output TypeScript file")?;
}
.context("Failed to write output file")?;

info!(
"Synced {} asset{}!",
Expand Down
8 changes: 4 additions & 4 deletions src/commands/sync/state.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::config::{CodegenStyle, CreatorType, ExistingAsset, SyncConfig};
use super::config::{CodegenLanguage, CodegenStyle, CreatorType, ExistingAsset, SyncConfig};
use crate::{
cli::{SyncArgs, SyncTarget},
LockFile,
Expand Down Expand Up @@ -53,7 +53,7 @@ pub struct SyncState {

pub creator: AssetCreator,

pub typescript: bool,
pub language: CodegenLanguage,
pub output_name: String,
pub style: CodegenStyle,
pub strip_extension: bool,
Expand Down Expand Up @@ -101,7 +101,7 @@ impl SyncState {
.unwrap_or(&"assets".to_string())
.to_string();

let typescript = config.codegen.typescript.unwrap_or(false);
let language = config.codegen.language.unwrap_or(CodegenLanguage::Luau);
let style = config.codegen.style.unwrap_or(CodegenStyle::Flat);

let strip_extension = config.codegen.strip_extension.unwrap_or(false);
Expand All @@ -126,7 +126,7 @@ impl SyncState {
exclude_assets_matcher,
api_key,
creator,
typescript,
language,
output_name,
style,
strip_extension,
Expand Down
Loading