Skip to content

Commit

Permalink
Add name + const declaration
Browse files Browse the repository at this point in the history
  • Loading branch information
Vorlias committed Jan 29, 2024
1 parent 7eb3e83 commit 4157cab
Show file tree
Hide file tree
Showing 8 changed files with 187 additions and 28 deletions.
8 changes: 5 additions & 3 deletions examples/02-spritesheets/pack-these/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ interface ImageSlice {
interface Folder_TestDpi {
L: (dpiScale: 1 | 2) => ImageSlice;
}
interface Assets {
interface PackedSprites {
H: ImageSlice;
I: ImageSlice;
J: ImageSlice;
K: ImageSlice;
L: ImageSlice;
TestDpi: Folder_TestDpi;
["Test Dpi"]: Folder_TestDpi;
a: ImageSlice;
b: ImageSlice;
c: ImageSlice;
Expand All @@ -22,4 +22,6 @@ interface Assets {
f: ImageSlice;
g: ImageSlice;
}
export = Assets;
/** Tarmac Generated Asset Types */
declare const PackedSprites: PackedSprites;
export = PackedSprites;
2 changes: 1 addition & 1 deletion examples/02-spritesheets/pack-these/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ return {
ImageRectOffset = Vector2.new(513, 506),
ImageRectSize = Vector2.new(505, 505),
},
TestDpi = {
["Test Dpi"] = {
L = function(dpiScale)
if dpiScale >= 2 then
return {
Expand Down
3 changes: 2 additions & 1 deletion examples/02-spritesheets/tarmac.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
name = "02-spritesheets"

[[inputs]]
name = "PackedSprites"
glob = "pack-these/**/*.png"

# Set packable to true to tell Tarmac that we're okay with these images being
Expand All @@ -18,4 +19,4 @@ glob = "dont-pack-these/**/*.png"
# packable defaults to false, but we can also explicitly specify it.
packable = false

codegen = true
codegen = true
3 changes: 3 additions & 0 deletions src/data/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ fn default_spritesheet_padding_size() -> u32 {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct InputConfig {
#[serde(default)]
pub name: Option<String>,

/// A glob that will match all files that should be considered for this
/// group of inputs.
pub glob: Glob,
Expand Down
74 changes: 61 additions & 13 deletions src/typescript/codegen.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
use std::{
collections::BTreeMap,
fs,
io::{self, Write},
path::Path,
};

use fs_err::File;
use fs_err::{os::windows, File};

use crate::{
codegen::GroupedItem,
data::{AssetId, SyncInput},
lua::lua_ast::Function,
typescript::ts_ast::Expression,
typescript::ts_ast::{Expression, VariableDeclaration, VariableKind},
};

use super::ts_ast::{
FunctionType, InterfaceDeclaration, ModifierToken, Parameter, PropertySignature, Statement,
TypeReference,
TemplateHead, TemplateLiteralExpression, TypeReference,
};

const CODEGEN_HEADER: &str =
Expand Down Expand Up @@ -94,7 +95,7 @@ fn get_properties(item: &GroupedItem) -> (Vec<PropertySignature>, Vec<Statement>
prereqs.push(Statement::InterfaceDeclaration(assets_interface));

fields.push(PropertySignature::new(
sanitized_name.clone(),
name.clone(),
None,
Expression::Identifier(interface_name),
));
Expand Down Expand Up @@ -165,13 +166,32 @@ fn get_sprite_interface() -> Statement {
/// We'll build up a Lua file containing nested tables that match the structure
/// of the input's path with its base path stripped away.
fn codegen_grouped(output_path: &Path, inputs: &[&SyncInput]) -> io::Result<()> {
let declaration_path = output_path.parent().unwrap().join("index.d.ts");

let should_generate_d_ts = inputs
.iter()
.find(|f| f.config.codegen_typescript_declaration);

if should_generate_d_ts.is_none() {
// Remove file if exists
if declaration_path.exists() {
fs::remove_file(declaration_path)?;
}

return Ok(());
}

let first = should_generate_d_ts.unwrap();
let name = &first.config.name;
println!("Name is {}", name.clone().unwrap());

let root_folder = GroupedItem::parse_root_folder(output_path, inputs);

let root = &GroupedItem::Folder {
children_by_name: root_folder,
};

let mut file = File::create(output_path.parent().unwrap().join("index.d.ts"))?;
let mut file = File::create(declaration_path)?;
writeln!(file, "{}", CODEGEN_HEADER)?;

let (properties, prereqs) = get_properties(&root);
Expand All @@ -182,14 +202,39 @@ fn codegen_grouped(output_path: &Path, inputs: &[&SyncInput]) -> io::Result<()>
write!(file, "{}", prereq)?;
}

let assets_interface = InterfaceDeclaration::new("Assets".into(), None, properties);
let export_assignment = Statement::export_assignment(Expression::Identifier("Assets".into()));
let interface_name = should_generate_d_ts
.unwrap()
.config
.name
.clone()
.unwrap_or("TarmacAssets".into());

let sanitized_name: String = interface_name
.chars()
.filter(|c| c.is_alphanumeric())
.collect();

let assets_interface = InterfaceDeclaration::new(sanitized_name.to_string(), None, properties);
let export_assignment = Statement::export_assignment(Expression::Identifier(sanitized_name.to_string()));

write!(
file,
"{}",
Statement::InterfaceDeclaration(assets_interface)
)?;

write!(
file,
"/** Tarmac Generated Asset Types */\n{}",
VariableDeclaration::new(
sanitized_name.to_string(),
VariableKind::Const,
Some(Expression::Identifier(sanitized_name.to_string())),
Some(vec![ModifierToken::Declare]),
None,
)
)?;

write!(file, "{}", export_assignment)?;

Ok(())
Expand All @@ -199,19 +244,22 @@ fn codegen_grouped(output_path: &Path, inputs: &[&SyncInput]) -> io::Result<()>
/// defined, and so generate individual files.
fn codegen_individual(inputs: &[&SyncInput]) -> io::Result<()> {
for input in inputs {
// let expression = match (&input.id, input.slice) {
// (Some(id), Some(slice)) => codegen_url_and_slice(id, slice),
// (Some(id), None) => codegen_just_asset_url(id),
// _ => continue,
// };
if !input.config.codegen_typescript_declaration {
continue;
}

// let ast = Statement::Return(expression);

let path = input.path.with_extension("d.ts");

let mut file = File::create(path)?;
writeln!(file, "{}", CODEGEN_HEADER)?;
//write!(file, "{}", ast)?;

write!(
file,
"{}",
Statement::export_assignment(Expression::Identifier(input.human_name().into()))
)?;
}

Ok(())
Expand Down
Loading

0 comments on commit 4157cab

Please sign in to comment.