Compare commits

..

15 Commits

Author SHA1 Message Date
Chen Asraf
ce9fededf0 update workflows + release alpha 2022-04-19 17:05:57 +03:00
Chen Asraf
4653428bda Merge pull request #33 from chenasraf/feature/before-write-callback
beforeWrite callback
2022-04-19 17:02:04 +03:00
Chen Asraf
19b2203f30 correct version number 2022-04-19 16:59:15 +03:00
Chen Asraf
3f103cd4c2 docs: add table of contents 2022-04-19 16:55:16 +03:00
Chen Asraf
ec5503bc3e bump version number 2022-04-19 16:49:57 +03:00
Chen Asraf
19ad60c3cb add explicit function return types 2022-04-19 16:43:57 +03:00
Chen Asraf
f04dd7e487 clean up + update docs 2022-04-19 16:43:57 +03:00
Chen Asraf
4c9a838ebe implementation of before-write callback + tests 2022-04-19 16:43:57 +03:00
Chen Asraf
6700708e1d update PR workflow 2022-04-19 16:43:11 +03:00
Chen Asraf
2727bd526c Merge pull request #29 from chenasraf/github/issue-templates
Update issue templates [skip ci]
2022-04-19 15:50:13 +03:00
Chen Asraf
834a805794 Update issue templates [skip ci] 2022-04-13 18:08:45 +03:00
Chen Asraf
ba9434f504 chore: remove unneeded dep 2022-04-13 10:21:46 +03:00
Chen Asraf
59353f4121 add develop branch 2022-04-13 10:19:55 +03:00
Chen Asraf
b2799d0bad chore: use rimraf + add error debug log [skip ci] 2022-04-10 22:53:44 +03:00
Chen Asraf
f4997c6289 docs: Update README.md [skip ci] 2022-04-10 22:53:31 +03:00
14 changed files with 250 additions and 72 deletions

37
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,37 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug, needs-triage
assignees: chenasraf
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Prepare templates:
```
template contents
```
2. Run with args/config:
```
npx simple-scaffold@latest -t ... -o output TplName
```
**Expected behavior**
A clear and concise description of what you expected to happen.
**Logs**
If applicable, paste your logs to help explain your problem.
To see more logs, run the scaffold with `-v 1` to enable debug logging.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Node.js: [e.g. 16.8]
- Simple Scaffold Version [e.g. 1.0.4]
**Additional context**
Add any other context about the problem here.

View File

@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement, needs-triage
assignees: chenasraf
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@@ -2,7 +2,7 @@ name: Alpha Releases
on:
push:
branches: [alpha]
branches: [develop]
jobs:
build:
runs-on: ubuntu-latest

View File

@@ -2,7 +2,7 @@ name: Pull Requests
on:
pull_request:
branches: [master, alpha, beta]
branches: [master, develop]
jobs:
build:
runs-on: ubuntu-latest

View File

@@ -1,4 +1,4 @@
name: Releases
name: Release
on:
push:

8
.markdownlint.json Normal file
View File

@@ -0,0 +1,8 @@
{
"MD013": {
"line_length": 100,
"tables": false,
"code_blocks": false
},
"MD033": false
}

View File

@@ -9,6 +9,35 @@ Simply organize your commonly-created files in their original structure, and run
will copy the files to the output path, while replacing values (such as component or app name, or
other custom data) inside the paths or contents of the files using Handlebars.js syntax.
<br />
<details>
<summary>Table of contents</summary>
- [simple-scaffold](#simple-scaffold)
- [Install](#install)
- [Use as a command line tool](#use-as-a-command-line-tool)
- [Command Line Options](#command-line-options)
- [Use in Node.js](#use-in-nodejs)
- [Node-specific options](#node-specific-options)
- [Preparing files](#preparing-files)
- [Template files](#template-files)
- [Variable/token replacement](#variabletoken-replacement)
- [Helpers](#helpers)
- [Examples](#examples)
- [Command Example](#command-example)
- [Example Scaffold Input](#example-scaffold-input)
- [Input Directory structure](#input-directory-structure)
- [Contents of `project/scaffold/{{Name}}.jsx`](#contents-of-projectscaffoldnamejsx)
- [Example Scaffold Output](#example-scaffold-output)
- [Output directory structure](#output-directory-structure)
- [Contents of `project/scaffold/MyComponent/MyComponent.jsx`](#contents-of-projectscaffoldmycomponentmycomponentjsx)
- [Contributing](#contributing)
</details>
---
## Install
You can either use it as a command line tool or import into your own code and run from there.
@@ -104,30 +133,23 @@ const config = {
},
helpers: {
twice: (text) => [text, text].join(" ")
}
},
beforeWrite: (content, rawContent, outputPath) => content.toString().toUpperCase()
}
const scaffold = Scaffold(config)
```
### Additional Node.js options
### Node-specific options
In addition to all the options available in the command line, there are some JS-specific options
available:
In addition to all the options available in the command line, there are some Node/JS-specific
options available:
1. When `output` is used in Node directly, it may also be passed a function for each input file to
output into a dynamic path:
```typescript
config.output = (fullPath, baseDir, baseName) => {
console.log({ fullPath, baseDir, baseName })
return path.resolve(baseDir, baseName)
}
```
2. You may add custom `helpers` to your scaffolds. Helpers are simple `(string) => string` functions
that transform your `data` variables into other values. See [Helpers](#helpers) for the list of
default helpers, or add your own to be loaded into the template parser.
| Option | Type | Description |
| ------------- | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `output` | | In addition to being passed the same as CLI, it may also be passed a function for each input file to output into a dynamic path: `{ output: (fullPath, baseDir, baseName) => path.resolve(baseDir, baseName) }` |
| `helpers` | `Record<string, (string) => string>` | Helpers are simple functions that transform your `data` variables into other values. See [Helpers](#helpers) for the list of default helpers, or add your own to be loaded into the template parser. |
| `beforeWrite` | `(content: Buffer, rawContent: Buffer, outputPath: string) => String \| Buffer \| undefined` | Supply this function to override the final output contents of each of your files. The return value of this function will replace the output content of the respective file, which you may discriminate (if needed) using the `outputPath` argument. |
## Preparing files
@@ -135,6 +157,22 @@ available:
Put your template files anywhere, and fill them with tokens for replacement.
Each template (not file) in the config array is parsed individually, and copied to the output
directory. If a single template path contains multiple files (e.g. if you use a folder path or a
glob pattern), the first directory up the tree of that template will become the base inside the
defined output path for that template, while copying files recursively and maintaining their
relative structure.
Examples:
> In the following examples, the config `name` is `AppName`, and the config `output` is `src`.
| Input template | Output path(s) |
| ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| `./templates/{{ name }}.txt` | `src/AppName.txt` |
| `./templates/directory` <br /><br /> Directory contents:<br /> <ol><li>`outer/{{name}}.txt`</li></li><li>`outer2/inner/{{name.txt}}`</li></ol> | `src/outer/AppName.txt`,<br />`src/outer2/inner/AppName.txt` |
| `./templates/others/**/*.txt` <br /><br /> Directory contents:<br /> <ol><li>`outer/{{name}}.jpg`</li></li><li>`outer2/inner/{{name.txt}}`</li></ol> | `src/outer2/inner/AppName.txt` |
### Variable/token replacement
Scaffolding will replace `{{ varName }}` in both the file name and its contents and put the
@@ -146,7 +184,11 @@ The data available for the template parser is the data you pass to the `data` co
For example, using the following command:
```bash
npx simple-scaffold@latest --templates templates/components/{{name}}.jsx --output src/components -create-sub-folder true MyComponent
npx simple-scaffold@latest \
--templates templates/components/{{name}}.jsx \
--output src/components \
-create-sub-folder true \
MyComponent
```
Will output a file with the path:
@@ -165,9 +207,10 @@ Your `data` will be pre-populated with the following:
> Simple-Scaffold uses [Handlebars.js](https://handlebarsjs.com/) for outputting the file contents.
> Any `data` you add in the config will be available for use with their names wrapped in
> `{{` and `}}`. Other Handlebars built-ins such as `each`, `if` and `with` are also supported, see
> [Handlebars.js Language Features](https://handlebarsjs.com/guide/#language-features) for more information.
> [Handlebars.js Language Features](https://handlebarsjs.com/guide/#language-features) for more
> information.
#### Helpers
### Helpers
Simple-Scaffold provides some built-in text transformation filters usable by handleBars.

View File

@@ -1,15 +1,25 @@
{
"name": "simple-scaffold",
"version": "1.0.4",
"version": "1.1.0-alpha.1",
"description": "Create files based on templates",
"repository": "https://github.com/chenasraf/simple-scaffold.git",
"author": "Chen Asraf <inbox@casraf.com>",
"license": "MIT",
"main": "index.js",
"bin": "cmd.js",
"keywords": ["javascript", "cli", "template", "files", "typescript", "generator", "scaffold", "file", "scaffolding"],
"keywords": [
"javascript",
"cli",
"template",
"files",
"typescript",
"generator",
"scaffold",
"file",
"scaffolding"
],
"scripts": {
"clean": "rm -rf dist/",
"clean": "rimraf dist/",
"build": "yarn clean && tsc && chmod -R +x ./dist && cp ./package.json ./README.md ./dist/",
"dev": "tsc --watch",
"start": "node dist/scaffold.js",
@@ -27,7 +37,6 @@
"util.promisify": "^1.1.1"
},
"devDependencies": {
"@types/args": "^3.0.1",
"@types/glob": "^7.1.1",
"@types/jest": "^26.0.24",
"@types/lodash": "^4.14.171",
@@ -35,6 +44,7 @@
"@types/node": "^14.14.22",
"jest": "^27.0.6",
"mock-fs": "^5.0.0",
"rimraf": "^3.0.2",
"ts-jest": "^27.0.3",
"ts-node": "^10.1.0",
"typescript": "^4.3.5"

View File

@@ -51,7 +51,7 @@ import { LogLevel, ScaffoldConfig } from "./types"
* Any functions you provide in `helpers` option will also be available to you to make custom formatting as you see fit
* (for example, formatting a date)
*/
export async function Scaffold({ ...options }: ScaffoldConfig) {
export async function Scaffold({ ...options }: ScaffoldConfig): Promise<void> {
options.output ??= process.cwd()
registerHelpers(options)
@@ -82,7 +82,10 @@ export async function Scaffold({ ...options }: ScaffoldConfig) {
isDirOrGlob,
isGlob,
})
await handleTemplateFile(options, options.data, { templatePath: inputFilePath, basePath })
await handleTemplateFile(options, options.data, {
templatePath: inputFilePath,
basePath,
})
}
} catch (e: any) {
handleErr(e)
@@ -104,7 +107,7 @@ async function handleTemplateFile(
templatePath,
basePath,
})
const overwrite = getOptionValueForFile(options, inputPath, data, options.overwrite ?? false)
const overwrite = getOptionValueForFile(options, inputPath, options.overwrite ?? false)
log(
options,
@@ -121,7 +124,7 @@ async function handleTemplateFile(
await createDirIfNotExists(path.dirname(outputPath), options)
log(options, LogLevel.Info, `Writing to ${outputPath}`)
await copyFileTransformed(options, data, { exists, overwrite, outputPath, inputPath })
await copyFileTransformed(options, { exists, overwrite, outputPath, inputPath })
resolve()
} catch (e: any) {
handleErr(e)

View File

@@ -113,6 +113,22 @@ export interface ScaffoldConfig {
* helpers, or a custom one you provide to `helpers`. Defaults to `undefined`, which means no transformation is done.
*/
subFolderNameHelper?: DefaultHelperKeys | string
/**
* This callback runs right before content is being written to the disk. If you supply this function, you may return
* a string that represents the final content of your file, you may process the content as you see fit. For example,
* you may run formatters on a file, fix output in edge-cases not supported by helpers or data, etc.
*
* If the return value of this function is `undefined`, the original content will be used.
*
* @param content The original template after token replacement
* @param rawContent The original template before token replacement
* @param outputPath The final output path of the processed file
*
* @returns `String | Buffer | undefined` The final output of the file contents-only, after further modifications -
* or `undefined` to use the original content (i.e. `content.toString()`)
*/
beforeWrite?(content: Buffer, rawContent: Buffer, outputPath: string): string | Buffer | undefined
}
export interface ScaffoldCmdConfig {
name: string

View File

@@ -25,7 +25,7 @@ export const defaultHelpers: Record<DefaultHelperKeys, Helper> = {
upperCase: (text) => text.toUpperCase(),
}
export function registerHelpers(options: ScaffoldConfig) {
export function registerHelpers(options: ScaffoldConfig): void {
const _helpers = { ...defaultHelpers, ...options.helpers }
for (const helperName in _helpers) {
log(options, LogLevel.Debug, `Registering helper: ${helperName}`)
@@ -33,11 +33,11 @@ export function registerHelpers(options: ScaffoldConfig) {
}
}
export function handleErr(err: NodeJS.ErrnoException | null) {
export function handleErr(err: NodeJS.ErrnoException | null): void {
if (err) throw err
}
export function log(options: ScaffoldConfig, level: LogLevel, ...obj: any[]) {
export function log(options: ScaffoldConfig, level: LogLevel, ...obj: any[]): void {
if (options.quiet || options.verbose === LogLevel.None || level < (options.verbose ?? LogLevel.Info)) {
return
}
@@ -86,7 +86,6 @@ export async function createDirIfNotExists(dir: string, options: ScaffoldConfig)
export function getOptionValueForFile<T>(
options: ScaffoldConfig,
filePath: string,
data: Record<string, string>,
fn: FileResponse<T>,
defaultValue?: T
): T {
@@ -104,7 +103,7 @@ export function handlebarsParse(
options: ScaffoldConfig,
templateBuffer: Buffer | string,
{ isPath = false }: { isPath?: boolean } = {}
) {
): Buffer {
const { data } = options
try {
let str = templateBuffer.toString()
@@ -116,10 +115,11 @@ export function handlebarsParse(
if (isPath && path.sep !== "/") {
outputContents = outputContents.replace(/\//g, "\\")
}
return outputContents
} catch {
return Buffer.from(outputContents)
} catch (e) {
log(options, LogLevel.Debug, e)
log(options, LogLevel.Warning, "Couldn't parse file with handlebars, returning original content")
return templateBuffer
return Buffer.from(templateBuffer)
}
}
@@ -144,7 +144,7 @@ export async function isDir(path: string): Promise<boolean> {
return tplStat.isDirectory()
}
export function removeGlob(template: string) {
export function removeGlob(template: string): string {
return template.replace(/\*/g, "").replace(/(\/\/|\\\\)/g, path.sep)
}
@@ -152,14 +152,14 @@ export function makeRelativePath(str: string): string {
return str.startsWith(path.sep) ? str.slice(1) : str
}
export function getBasePath(relPath: string) {
export function getBasePath(relPath: string): string {
return path
.resolve(process.cwd(), relPath)
.replace(process.cwd() + path.sep, "")
.replace(process.cwd(), "")
}
export async function getFileList(options: ScaffoldConfig, template: string) {
export async function getFileList(options: ScaffoldConfig, template: string): Promise<string[]> {
return (
await promisify(glob)(template, {
dot: true,
@@ -192,7 +192,7 @@ export async function getTemplateGlobInfo(options: ScaffoldConfig, template: str
return { nonGlobTemplate, origTemplate, isDirOrGlob, isGlob, template: _template }
}
export async function ensureFileExists(template: string, isGlob: boolean) {
export async function ensureFileExists(template: string, isGlob: boolean): Promise<void> {
if (!isGlob && !(await pathExists(template))) {
const err: NodeJS.ErrnoException = new Error(`ENOENT, no such file or directory ${template}`)
err.code = "ENOENT"
@@ -216,8 +216,8 @@ export async function getTemplateFileInfo(
{ templatePath, basePath }: { templatePath: string; basePath: string }
): Promise<OutputFileInfo> {
const inputPath = path.resolve(process.cwd(), templatePath)
const outputPathOpt = getOptionValueForFile(options, inputPath, data, options.output)
const outputDir = getOutputDir(options, data, outputPathOpt, basePath)
const outputPathOpt = getOptionValueForFile(options, inputPath, options.output)
const outputDir = getOutputDir(options, outputPathOpt, basePath)
const outputPath = handlebarsParse(options, path.join(outputDir, path.basename(inputPath)), {
isPath: true,
}).toString()
@@ -227,39 +227,41 @@ export async function getTemplateFileInfo(
export async function copyFileTransformed(
options: ScaffoldConfig,
data: Record<string, string>,
{
exists,
overwrite,
outputPath,
inputPath,
}: { exists: boolean; overwrite: boolean; outputPath: string; inputPath: string }
) {
}: {
exists: boolean
overwrite: boolean
outputPath: string
inputPath: string
}
): Promise<void> {
if (!exists || overwrite) {
if (exists && overwrite) {
log(options, LogLevel.Info, `File ${outputPath} exists, overwriting`)
}
const templateBuffer = await readFile(inputPath)
const outputContents = handlebarsParse(options, templateBuffer)
const unprocessedOutputContents = handlebarsParse(options, templateBuffer)
const finalOutputContents = (
options.beforeWrite?.(unprocessedOutputContents, templateBuffer, outputPath) ?? unprocessedOutputContents
).toString()
if (!options.dryRun) {
await writeFile(outputPath, outputContents)
await writeFile(outputPath, finalOutputContents)
log(options, LogLevel.Info, "Done.")
} else {
log(options, LogLevel.Info, "Content output:")
log(options, LogLevel.Info, outputContents)
log(options, LogLevel.Info, finalOutputContents)
}
} else if (exists) {
log(options, LogLevel.Info, `File ${outputPath} already exists, skipping`)
}
}
export function getOutputDir(
options: ScaffoldConfig,
data: Record<string, string>,
outputPathOpt: string,
basePath: string
) {
export function getOutputDir(options: ScaffoldConfig, outputPathOpt: string, basePath: string): string {
return path.resolve(
process.cwd(),
...([
@@ -267,7 +269,7 @@ export function getOutputDir(
basePath,
options.createSubFolder
? options.subFolderNameHelper
? handlebarsParse(options, `{{ ${options.subFolderNameHelper} name }}`)
? handlebarsParse(options, `{{ ${options.subFolderNameHelper} name }}`).toString()
: options.name
: undefined,
].filter(Boolean) as string[])
@@ -295,7 +297,7 @@ export function logInputFile(
isDirOrGlob: boolean
isGlob: boolean
}
) {
): void {
log(
options,
LogLevel.Debug,
@@ -312,7 +314,7 @@ export function logInputFile(
)
}
export function logInitStep(options: ScaffoldConfig) {
export function logInitStep(options: ScaffoldConfig): void {
log(options, LogLevel.Debug, "Full config:", {
name: options.name,
templates: options.templates,

View File

@@ -291,7 +291,7 @@ describe("Scaffold", () => {
verbose: 0,
})
const data = readFileSync(join(process.cwd(), "output", "app_name/app_name.txt"))
const data = readFileSync(join(process.cwd(), "output", "app_name", "app_name.txt"))
expect(data.toString()).toBe("Hello, my app is app_name")
})
@@ -305,7 +305,7 @@ describe("Scaffold", () => {
subFolderNameHelper: "upperCase",
})
const data = readFileSync(join(process.cwd(), "output", "APP_NAME/app_name.txt"))
const data = readFileSync(join(process.cwd(), "output", "APP_NAME", "app_name.txt"))
expect(data.toString()).toBe("Hello, my app is app_name")
})
@@ -322,9 +322,51 @@ describe("Scaffold", () => {
},
})
const data = readFileSync(join(process.cwd(), "output", "REPLACED/app_name.txt"))
const data = readFileSync(join(process.cwd(), "output", "REPLACED", "app_name.txt"))
expect(data.toString()).toBe("Hello, my app is app_name")
})
})
)
describe(
"before write",
withMock(fileStructNormal, () => {
test("should work with no callback", async () => {
await Scaffold({
name: "app_name",
output: "output",
templates: ["input"],
verbose: 0,
data: {
value: "value",
},
})
const data = readFileSync(join(process.cwd(), "output", "app_name.txt"))
expect(data.toString()).toBe("Hello, my app is app_name")
})
test("should work with custom callback", async () => {
await Scaffold({
name: "app_name",
output: "output",
templates: ["input"],
verbose: 0,
data: {
value: "value",
},
beforeWrite: (content, beforeContent, outputPath) =>
[content.toString().toUpperCase(), beforeContent, outputPath].join(", "),
})
const data = readFileSync(join(process.cwd(), "output", "app_name.txt"))
expect(data.toString()).toBe(
[
"Hello, my app is app_name".toUpperCase(),
fileStructNormal.input["{{name}}.txt"],
join(process.cwd(), "output", "app_name.txt"),
].join(", ")
)
})
})
)
})

View File

@@ -23,7 +23,7 @@ describe("Utils", () => {
})
test("should work for windows paths", async () => {
expect(handlebarsParse(blankConf, "C:\\exports\\{{name}}.txt", { isPath: true })).toEqual(
"C:\\exports\\test.txt"
Buffer.from("C:\\exports\\test.txt")
)
})
})
@@ -36,7 +36,9 @@ describe("Utils", () => {
Object.defineProperty(path, "sep", { value: origSep })
})
test("should work for non-windows paths", async () => {
expect(handlebarsParse(blankConf, "/home/test/{{name}}.txt", { isPath: true })).toEqual("/home/test/test.txt")
expect(handlebarsParse(blankConf, "/home/test/{{name}}.txt", { isPath: true })).toEqual(
Buffer.from("/home/test/test.txt")
)
})
})
test("should not do path escaping on non-path compiles", async () => {
@@ -48,7 +50,7 @@ describe("Utils", () => {
isPath: false,
}
)
).toEqual("/home/test/test {{escaped}}.txt")
).toEqual(Buffer.from("/home/test/test {{escaped}}.txt"))
})
})
})

View File

@@ -537,11 +537,6 @@
resolved "https://registry.yarnpkg.com/@tsconfig/node16/-/node16-1.0.1.tgz#a6ca6a9a0ff366af433f42f5f0e124794ff6b8f1"
integrity sha512-FTgBI767POY/lKNDNbIzgAX6miIDBs6NTCbdlDb8TrWovHsSvaVIZDlTqym29C6UqhzwcJx4CYr+AlrMywA0cA==
"@types/args@^3.0.1":
version "3.0.1"
resolved "https://registry.yarnpkg.com/@types/args/-/args-3.0.1.tgz#59e8e787ed8a810408dd9a324157cc20b7001468"
integrity sha512-Mfre8T2comeJbw2D6W8mzQP+0Q8fpS7nkbHgatzU31tWsLs0Lkyc+ObdYfgV4SuMZn/n5MEWlxh2rc25125s0Q==
"@types/babel__core@^7.0.0", "@types/babel__core@^7.1.14":
version "7.1.15"
resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.15.tgz#2ccfb1ad55a02c83f8e0ad327cbc332f55eb1024"
@@ -2444,7 +2439,7 @@ resolve@^1.20.0:
is-core-module "^2.2.0"
path-parse "^1.0.6"
rimraf@^3.0.0:
rimraf@^3.0.0, rimraf@^3.0.2:
version "3.0.2"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a"
integrity sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==