restructured build.ts and added a helpcommand

This commit is contained in:
2022-06-10 22:50:59 -05:00
parent c51ca65751
commit d00ddeb1e1
9 changed files with 225 additions and 177 deletions

View File

@@ -1,16 +1,14 @@
import { buildSync, BuildFailure, BuildOptions } from 'esbuild'
import { buildSync, BuildFailure, BuildOptions, BuildResult } from 'esbuild'
import { existsSync, writeFileSync, unlinkSync } from 'fs'
import { DistPath, ScriptBase, ScriptPath } from './paths'
import { UserScriptMetaFull } from './types'
import readMeta from './readmeta'
import { format, Options } from 'prettier'
import { format, resolveConfig } from 'prettier'
import { CLIArgs } from './main'
export default function (
name: string,
watchCallback: (meta: UserScriptMetaFull, error: string | null) => void,
PrettierConfig: Options,
CLIArgs: CLIArgs
watchCallback: (meta: UserScriptMetaFull, error: string | null) => void
): [UserScriptMetaFull, string | null] {
//read meta file
let [metaJson, metaString] = readMeta(name)
@@ -39,45 +37,16 @@ export default function (
},
},
result => {
let error = runPostEsbuild(
name,
result,
metaString,
CLIArgs,
PrettierConfig
)
let error = postBuild(name, result, metaString)
watchCallback(metaJson, error)
},
CLIArgs
}
)
let error = runPostEsbuild(
name,
result,
metaString,
CLIArgs,
PrettierConfig
)
let error = postBuild(name, result, metaString)
return [metaJson, error]
}
function doErrorFile(
pathError: string,
pathOutFile: string,
error: string | null
) {
if (error !== null) {
writeFileSync(pathError, `${new Date().toISOString()}\n\n${error}`)
if (existsSync(pathOutFile)) {
unlinkSync(pathOutFile)
}
} else if (existsSync(pathError)) {
unlinkSync(pathError)
}
}
interface RunEsbuildResult {
content: string | null
error: string | null
@@ -86,49 +55,37 @@ interface RunEsbuildResult {
function runEsbuild(
opts: BuildOptions,
watchCallback: (result: RunEsbuildResult) => void,
CLIArgs: CLIArgs
watchCallback: (result: RunEsbuildResult) => void
): RunEsbuildResult {
opts.write = false
if (CLIArgs.watch) {
opts.watch = {
onRebuild(err, res) {
if (err) {
watchCallback({
content: null,
error: (err as BuildFailure).message,
errorRaw: err,
})
} else if (res) {
let content = ''
if (res.outputFiles && res.outputFiles.length > 0) {
content = res.outputFiles[0].text
}
if (content === '') {
watchCallback({
content: null,
error: 'No output',
})
}
watchCallback({
content,
error: null,
})
} else {
watchCallback({
content: null,
error: 'No result',
})
}
watchCallback(getResult(err, res))
},
}
}
try {
let res = buildSync(opts)
return getResult(null, res)
} catch (err) {
return getResult(err as BuildFailure, null)
}
}
function getResult(error: BuildFailure | null, result: BuildResult | null) {
if (error) {
return {
content: null,
error: (error as BuildFailure).message,
errorRaw: error,
}
} else if (result) {
let content = ''
if (res.outputFiles && res.outputFiles.length > 0) {
content = clearFilenameComments(res.outputFiles[0].text)
if (result.outputFiles && result.outputFiles.length > 0) {
content = result.outputFiles[0].text
if (!CLIArgs.srccomment) content = clearFilenameComments(content)
}
if (content === '') {
return {
@@ -140,45 +97,59 @@ function runEsbuild(
content,
error: null,
}
} catch (err) {
} else {
return {
content: null,
error: (err as BuildFailure).message,
error: 'No result',
}
}
}
function runPostEsbuild(
name: string,
result: RunEsbuildResult,
metaString: string,
CLIArgs: CLIArgs,
PrettierConfig: Options
) {
function clearFilenameComments(content: string): string {
let regexp = new RegExp(`//\\s*${ScriptBase}/.*(?:\\n|$)`, 'g')
return content.replace(regexp, '')
}
function postBuild(name: string, result: RunEsbuildResult, metaString: string) {
let error: string | null = null
let path = ScriptPath(name)
let pathDist = DistPath(name)
let PrettierConfig = resolveConfig.sync(path.dir) || {}
if (result.error) {
console.error(name, result.errorRaw || result.error)
error = result.error
} else if (result.content) {
let content = metaString + result.content
if (CLIArgs.prettier) {
content = format(content, PrettierConfig)
content = format(content, {
...PrettierConfig,
parser: 'babel',
})
}
writeFileSync(pathDist, content)
} else {
console.error(name, 'No output')
}
doErrorFile(path.error, pathDist, error)
doErrorFile(name, error)
return error
}
//remove all filename comments
function clearFilenameComments(content: string): string {
let regexp = new RegExp(`//\\s*${ScriptBase}/.*(?:\\n|$)`, 'g')
return content.replace(regexp, '')
function doErrorFile(name: string, error: string | null) {
let path = ScriptPath(name)
let outfile = DistPath(name)
let content = `${new Date().toISOString()}\n\n${error}`
if (error !== null) {
writeFileSync(path.error, content)
if (existsSync(outfile)) {
unlinkSync(outfile)
}
} else if (existsSync(path.error)) {
unlinkSync(path.error)
}
}

View File

@@ -1,22 +1,59 @@
import { existsSync, lstatSync, readdirSync, unlinkSync } from 'fs'
import commandLineArgs from 'command-line-args'
import { resolveConfig } from 'prettier'
import { DistBase, ScriptBase, ScriptPath } from './paths'
import { readmeData, updateReadmeFile } from './readmefile'
import runBuild from './build'
import { UserScriptMetaFull } from './types'
import * as Path from 'path'
export interface CLIArgs {
export interface CLIArgsT {
watch: boolean
minify: boolean
prettier: boolean
srccomment: boolean
help: boolean
}
const CLIArgs = commandLineArgs([
export const CLIArgs = commandLineArgs([
{ name: 'watch', alias: 'w', type: Boolean, defaultValue: false },
{ name: 'minify', alias: 'm', type: Boolean, defaultValue: false },
{ name: 'prettier', alias: 'p', type: Boolean, defaultValue: false },
]) as CLIArgs
{ name: 'srccomment', alias: 's', type: Boolean, defaultValue: false },
{ name: 'help', alias: 'h', type: Boolean, defaultValue: false },
]) as CLIArgsT
if (CLIArgs.help) {
let command = '<command>'
if (process.argv.length > 0) {
command = Path.parse(process.argv[0]).name
}
if (command.toLowerCase() === 'node' && process.argv.length > 1) {
let path = Path.relative(process.cwd(), process.argv[1]) || '.'
command = `${command} ${path}`
}
console.log(`
Usage: ${command} [options]
options:
--watch
alias: -w
automatically recompile on save
--minify
alias: -m
minify output files
--prettier
alias: -p
prettify output files
--srccomment
alias: -s
include src file path comments in the output files, i.e. // scripts/example/main.ts
--help
alias: -h
show this help message
`)
process.exit(0)
}
//if package.json doesn't exist then there is no point in continuing
if (!existsSync('package.json') || !lstatSync('package.json').isFile()) {
@@ -27,15 +64,6 @@ if (!existsSync('package.json') || !lstatSync('package.json').isFile()) {
//delete compiled scripts
readdirSync(DistBase).forEach(file => unlinkSync(`${DistBase}/${file}`))
//read prettierrc file and make sure `babel` is the configured parser
const PrettierConfig = (() => {
let config = resolveConfig.sync(process.cwd()) || {}
return {
...config,
parser: 'babel',
}
})()
//compile scripts
let scripts = readdirSync(ScriptBase)
let scriptMeta: readmeData[] = []
@@ -61,12 +89,7 @@ for (let name of scripts) {
updateReadmeFile(scriptMeta)
}
let [meta, error] = runBuild(
name,
postWatchUpdate,
PrettierConfig,
CLIArgs
)
let [meta, error] = runBuild(name, postWatchUpdate)
scriptMeta[id] = { meta, error }
console.log(name, meta.version)

View File

@@ -7,7 +7,13 @@ export const SupportUrl = `${BaseUrl}/issues`
export const FileUrl = (name: string) =>
`${BaseUrl}/raw/branch/${RemoteBranch}/${DistBase}/${name}.user.js`
export const ScriptPath = (name: string) => ({
export interface ScriptPathT {
dir: `${string}/${string}`
main: `${string}/${string}/main.ts`
meta: `${string}/${string}/meta.json`
error: `${string}/${string}/error.log`
}
export const ScriptPath = (name: string): ScriptPathT => ({
dir: `${ScriptBase}/${name}`,
main: `${ScriptBase}/${name}/main.ts`,
meta: `${ScriptBase}/${name}/meta.json`,