Skip to content

Commit

Permalink
fix: 修复 convertor 问题
Browse files Browse the repository at this point in the history
  • Loading branch information
luckyadam committed Nov 20, 2023
1 parent 0f13831 commit 34cad6d
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 60 deletions.
7 changes: 7 additions & 0 deletions crates/native_binding/binding.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
/* auto-generated by NAPI-RS */
/* eslint-disable */

export class Creator {
templateRoot: string
destinationRoot: string
constructor(templateRoot: string, destinationRoot: string)
createFileFromTemplate(templateName: string, templatePath: string, destPath: string, options: CreateOptions): Promise<void>
}

export const enum CompilerType {
Webpack4 = 'Webpack4',
Webpack5 = 'Webpack5',
Expand Down
12 changes: 12 additions & 0 deletions crates/taro_init/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@ use std::collections::HashMap;
use napi_derive::napi;
use once_cell::sync::Lazy;
use serde::Serialize;
use handlebars::{handlebars_helper, Handlebars, JsonRender};
use handlebars_misc_helpers::{new_hbs, register};

handlebars_helper!(includes: |{ s: str = "" }, *args| args.iter().map(|a| a.render()).any(|arg| arg == s));
// handlebars_helper!(eq: |x: str, y: str| x == y);

pub static HANDLEBARS: Lazy<Handlebars<'static>> = Lazy::new(|| {
let mut hbs = new_hbs();
register(&mut hbs);
hbs.register_helper("includes", Box::new(includes));
hbs
});

pub static STYLE_EXT_MAP: Lazy<HashMap<&CSSType, &str>> = Lazy::new(|| {
let mut map = HashMap::new();
Expand Down
58 changes: 22 additions & 36 deletions crates/taro_init/src/creator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ use std::{collections::HashMap, path::PathBuf};

use anyhow::Context;
use console::style;
use handlebars::{handlebars_helper, Handlebars, JsonRender};
use handlebars_misc_helpers::{new_hbs, register};
use napi::{
assert_type_of,
bindgen_prelude::FromNapiValue,
Expand All @@ -12,13 +10,12 @@ use napi::{
JsBoolean, JsObject, Result, Status, ValueType,
};
use napi_derive::napi;
use once_cell::sync::Lazy;
use serde::Serialize;

use crate::{
async_fs,
constants::{CSSType, CompilerType, FrameworkType, MEDIA_REGEX, STYLE_EXT_MAP},
utils::normalize_path_str,
utils::{normalize_path_str, generate_with_template},
};

#[derive(Debug, Clone, Serialize)]
Expand Down Expand Up @@ -94,16 +91,6 @@ impl FromNapiValue for JSReturn {
}
}

handlebars_helper!(includes: |{ s: str = "" }, *args| args.iter().map(|a| a.render()).any(|arg| arg == s));
// handlebars_helper!(eq: |x: str, y: str| x == y);

static HANDLEBARS: Lazy<Handlebars<'static>> = Lazy::new(|| {
let mut hbs = new_hbs();
register(&mut hbs);
hbs.register_helper("includes", Box::new(includes));
hbs
});

#[derive(Debug, Clone)]
#[napi(constructor)]
pub struct Creator {
Expand Down Expand Up @@ -152,6 +139,26 @@ impl Creator {
}

#[napi]
pub async fn create_file_from_template(
&self,
template_name: String,
template_path: String,
dest_path: String,
options: CreateOptions,
) -> napi::Result<()> {
let from_path = normalize_path_str(template_path.as_str());
let dest_path = normalize_path_str(dest_path.as_str());
let from_path = self.get_template_path(&[&template_name, &from_path]);
let dest_path = self.get_destination_path(&[&dest_path]);
let result = generate_with_template(&from_path, &dest_path, &options).await;
if let Err(e) = result {
println!("创建文件错误,原因如下:");
println!("{}", e);
return Err(napi::Error::from_reason(format!("{:?}", e)));
}
Ok(())
}

pub async fn tempate(
&self,
from_path: &str,
Expand All @@ -172,28 +179,7 @@ impl Creator {
.with_context(|| format!("文件复制失败: {}", from_path))?;
return Ok(());
}
let form_template = async_fs::read(from_path)
.await
.with_context(|| format!("文件读取失败: {}", from_path))?;
let from_template = String::from_utf8_lossy(&form_template);
let template = if from_template == "" {
"".to_string()
} else {
HANDLEBARS
.render_template(&from_template, options)
.with_context(|| format!("模板渲染失败: {}", from_path))?
};
let dir_name = PathBuf::from(dest_path)
.parent()
.unwrap()
.to_string_lossy()
.to_string();
async_fs::create_dir_all(&dir_name)
.await
.with_context(|| format!("文件夹创建失败: {}", dir_name))?;
async_fs::write(dest_path, template)
.await
.with_context(|| format!("文件写入失败: {}", dest_path))?;
generate_with_template(from_path, dest_path, options).await?;
Ok(())
}

Expand Down
19 changes: 17 additions & 2 deletions crates/taro_init/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::{Error, Ok};
use anyhow::{Error, Ok, Context};
use console::style;
use futures::FutureExt;
use spinners::{Spinner, Spinners};
Expand All @@ -7,7 +7,8 @@ use std::{fs, path::Path, process::Stdio};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command;

use crate::constants::{NpmType, PACKAGES_MANAGEMENT};
use crate::async_fs;
use crate::constants::{NpmType, PACKAGES_MANAGEMENT, HANDLEBARS};

pub fn get_all_files_in_folder(folder: String, filter: &[&str]) -> Result<Vec<String>, Error> {
let mut files = Vec::new();
Expand All @@ -27,6 +28,20 @@ pub fn get_all_files_in_folder(folder: String, filter: &[&str]) -> Result<Vec<St
Ok(files)
}

pub async fn generate_with_template(from_path: &str, dest_path: &str, data: &impl serde::Serialize) -> anyhow::Result<()> {
let form_template = async_fs::read(from_path).await.with_context(|| format!("文件读取失败: {}", from_path))?;
let from_template = String::from_utf8_lossy(&form_template);
let template = if from_template == "" {
"".to_string()
} else {
HANDLEBARS.render_template(&from_template, data).with_context(|| format!("模板渲染失败: {}", from_path))?
};
let dir_name = Path::new(dest_path).parent().unwrap().to_string_lossy().to_string();
async_fs::create_dir_all(&dir_name).await.with_context(|| format!("文件夹创建失败: {}", dir_name))?;
async_fs::write(dest_path, template).await.with_context(|| format!("文件写入失败: {}", dest_path))?;
Ok(())
}

pub fn normalize_path_str(path: &str) -> String {
let mut path = path.replace("\\", "/");
if path.ends_with("/") {
Expand Down
68 changes: 48 additions & 20 deletions packages/taro-cli-convertor/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import template from '@babel/template'
import traverse, { NodePath } from '@babel/traverse'
import * as t from '@babel/types'
import { CompilerType, createProject, CSSType, FrameworkType, NpmType, PeriodType } from '@tarojs/binding'
import { Creator } from '@tarojs/cli'
import { CompilerType, Creator, CSSType, FrameworkType } from '@tarojs/binding'
import { getRootPath } from '@tarojs/cli'
import {
chalk,
CSS_IMPORT_REG,
Expand Down Expand Up @@ -874,28 +874,56 @@ ${code}
}

generateConfigFiles () {
const creator = new Creator()
const template = 'default'
const templatePath = creator.templatePath(template)
const handlerPath = path.join(templatePath, 'template_creator.js')
const handler = fs.existsSync(handlerPath) ? require(handlerPath).handler : {}
const creator = new Creator(getRootPath(), this.convertRoot)
const dateObj = new Date()
createProject({
projectRoot: this.convertRoot,
projectName: 'taroConvert',
template,
npm: NpmType.Pnpm,
framework: this.framework,
const date = `${dateObj.getFullYear()}-${dateObj.getMonth() + 1}-${dateObj.getDate()}`
const templateName = 'default'
const projectName = 'taroConvert'
const version = getPkgVersion()
const description = ''
const ps: Promise<void>[] = []
const createOpts = {
css: CSSType.Sass,
autoInstall: false,
templateRoot: creator.rootPath,
version: getPkgVersion(),
cssExt: '.scss',
framework: this.framework,
description,
projectName,
version,
date,
typescript: false,
date: `${dateObj.getFullYear()}-${dateObj.getMonth() + 1}-${dateObj.getDate()}`,
description: '',
template: templateName,
compiler: CompilerType.Webpack5,
period: PeriodType.CreateAPP,
}, handler).then(() => {
}
ps.push(creator.createFileFromTemplate(templateName, 'package.json.tmpl', 'package.json', createOpts))
ps.push(creator.createFileFromTemplate(templateName, 'config/index.js', 'config/index.js', createOpts))
ps.push(creator.createFileFromTemplate(templateName, 'config/dev.js', 'config/dev.js', createOpts))
ps.push(creator.createFileFromTemplate(templateName, 'config/prod.js', 'config/prod.js', createOpts))
ps.push(creator.createFileFromTemplate(templateName, 'project.config.json', 'project.config.json', createOpts))
ps.push(creator.createFileFromTemplate(templateName, '.gitignore', '.gitignore', createOpts))
ps.push(creator.createFileFromTemplate(templateName, '.editorconfig', '.editorconfig', createOpts))
ps.push(creator.createFileFromTemplate(templateName, '.eslintrc.js', '.eslintrc.js', createOpts))
ps.push(creator.createFileFromTemplate(templateName, 'babel.config.js', 'babel.config.js', createOpts))
ps.push(creator.createFileFromTemplate(templateName, 'src/index.html', 'src/index.html', createOpts))
Promise.all(ps).then(() => {
const pkgObj = JSON.parse(fs.readFileSync(path.join(this.convertRoot, 'package.json')).toString())
pkgObj.dependencies['@tarojs/with-weapp'] = `^${version}`
fs.writeJSONSync(path.join(this.convertRoot, 'package.json'), pkgObj, {
spaces: 2,
EOL: '\n'
})
printLog(processTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertRoot, 'package.json')))
printLog(processTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertRoot, 'config/index.js')))
printLog(processTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertRoot, 'config/dev.js')))
printLog(processTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertRoot, 'config/prod')))
printLog(
processTypeEnum.GENERATE,
'文件',
this.generateShowPath(path.join(this.convertRoot, 'project.config.json'))
)
printLog(processTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertRoot, '.gitignore')))
printLog(processTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertRoot, '.editorconfig')))
printLog(processTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertRoot, '.eslintrc')))
printLog(processTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertDir, 'index.html')))
this.showLog()
})
}
Expand Down
6 changes: 4 additions & 2 deletions packages/taro-cli/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import Creator from './create/creator'
import Project from './create/project'
import doctor from './doctor'
import { getRootPath } from './util'
import { type ConfigEnv, type UserConfigExport, type UserConfigFn, defineConfig } from './util/defineConfig'

export default {
doctor,
Project,
Creator,
defineConfig,
getRootPath
}

export {
Expand All @@ -17,5 +19,5 @@ export {
Creator,
defineConfig,
doctor,
Project
}
getRootPath,
Project }

0 comments on commit 34cad6d

Please sign in to comment.