Skip to content
This repository has been archived by the owner on May 22, 2024. It is now read-only.

Commit

Permalink
chore: enforce newline before return and after variable declarations (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
danez committed Jun 10, 2022
1 parent 32a7387 commit 14bf813
Show file tree
Hide file tree
Showing 22 changed files with 41 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ module.exports = {
// This rule enforces using Buffers with `JSON.parse()`. However, TypeScript
// does not recognize yet that `JSON.parse()` accepts Buffers as argument.
'unicorn/prefer-json-parse-buffer': 'off',
'padding-line-between-statements': [
'error',
// Require newline before return
{ blankLine: 'always', prev: '*', next: 'return' },
// Require newline after a batch of variable declarations
{ blankLine: 'always', prev: ['const', 'let', 'var'], next: '*' },
{ blankLine: 'any', prev: ['const', 'let', 'var'], next: ['const', 'let', 'var'] },
],
},
overrides: [
...overrides,
Expand All @@ -31,6 +39,7 @@ module.exports = {
'max-lines-per-function': 'off',
'max-statements': 'off',
'no-magic-numbers': 'off',
'padding-line-between-statements': 'off',
},
},
{
Expand Down
3 changes: 3 additions & 0 deletions src/archive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,17 @@ const pEndOfStream = promisify(endOfStream)
export const startZip = function (destPath: string): { archive: Archiver; output: Writable } {
const output = createWriteStream(destPath)
const archive = archiver('zip')

archive.pipe(output)

return { archive, output }
}

// Add new file to zip
export const addZipFile = function (archive: Archiver, file: string, name: string, stat: Stats): void {
if (stat.isSymbolicLink()) {
const linkContent = readlinkSync(file)

archive.symlink(name, linkContent, stat.mode)
} else {
archive.file(file, {
Expand Down
1 change: 1 addition & 0 deletions src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const runCli = async function () {
try {
// @ts-expect-error TODO: `options` is not getting the right types.
const zipped = await zipFunctions(srcFolder, destFolder, options)

console.log(JSON.stringify(zipped, null, 2))
} catch (error) {
console.error(error.toString())
Expand Down
4 changes: 4 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const augmentWithISC = async (func: FunctionSource): Promise<AugmentedFunctionSo
}

const inSourceConfig = await findISCDeclarationsInPath(func.mainFile)

return { ...func, inSourceConfig }
}

Expand All @@ -58,6 +59,7 @@ export const listFunctions = async function (
const functionsMap = await getFunctionsFromPaths(paths, { featureFlags, config })
const functions = [...functionsMap.values()]
const augmentedFunctions = parseISC ? await Promise.all(functions.map(augmentWithISC)) : functions

return augmentedFunctions.map(getListedFunction)
}

Expand All @@ -72,6 +74,7 @@ export const listFunction = async function (
) {
const featureFlags = getFlags(inputFeatureFlags)
const func = await getFunctionFromPath(path, { featureFlags, config })

if (!func) {
return
}
Expand Down Expand Up @@ -115,6 +118,7 @@ const getListedFunctionFiles = async function (
options: { basePath?: string; featureFlags: FeatureFlags },
): Promise<ListedFunctionFile[]> {
const srcFiles = await getSrcFiles({ ...func, ...options })

return srcFiles.map((srcFile) => ({ ...getListedFunction(func), srcFile, extension: extname(srcFile) }))
}

Expand Down
1 change: 1 addition & 0 deletions src/runtimes/go/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const build = async ({ destPath, mainFile, srcDir }: { destPath: string;
})
} catch (error) {
const runtime: RuntimeName = 'go'

error.customErrorInfo = { type: 'functionsBundling', location: { functionName, runtime } }

console.error(`Could not compile Go function ${functionName}:\n`)
Expand Down
1 change: 1 addition & 0 deletions src/runtimes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ export const getFunctionFromPath = async (

for (const runtime of RUNTIMES) {
const func = await runtime.findFunctionInPath({ path, fsCache, featureFlags })

if (func) {
return {
...func,
Expand Down
1 change: 1 addition & 0 deletions src/runtimes/node/bundlers/esbuild/bundler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ export const bundleJsFile = async function ({
} catch (error) {
const bundler: NodeBundlerName = 'esbuild'
const runtime: RuntimeName = 'js'

error.customErrorInfo = {
type: 'functionsBundling',
location: { bundler, functionName: name, runtime },
Expand Down
1 change: 1 addition & 0 deletions src/runtimes/node/bundlers/zisi/list_imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export const listImports = async ({
} catch (error) {
const bundler: NodeBundlerName = 'zisi'
const runtime: RuntimeName = 'js'

error.customErrorInfo = {
type: 'functionsBundling',
location: { bundler, functionName, runtime },
Expand Down
1 change: 1 addition & 0 deletions src/runtimes/node/bundlers/zisi/published.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const getPublishedFiles = async function (modulePath: string): Promise<st
absolute: true,
dot: true,
})

return publishedFiles
}

Expand Down
3 changes: 3 additions & 0 deletions src/runtimes/node/bundlers/zisi/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ const resolvePathPreserveSymlinksForDir = function (path: string, basedir: strin
// we return the first resolved location or the first error if all failed
export const resolvePathPreserveSymlinks = async function (path: string, baseDirs: string[]): Promise<string> {
let firstError

for (const basedir of baseDirs) {
try {
return await resolvePathPreserveSymlinksForDir(path, basedir)
Expand All @@ -91,9 +92,11 @@ const resolvePathFollowSymlinks = function (path: string, baseDirs: string[]) {
const resolvePackageFallback = async function (moduleName: string, baseDirs: string[], error: Error) {
const mainFilePath = resolvePathFollowSymlinks(moduleName, baseDirs)
const packagePath = await findUp(isPackageDir.bind(null, moduleName), { cwd: mainFilePath, type: 'directory' })

if (packagePath === undefined) {
throw error
}

return packagePath
}

Expand Down
1 change: 1 addition & 0 deletions src/runtimes/node/bundlers/zisi/side_files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { getPublishedFiles } from './published.js'
// inside the module's directory itself.
export const getSideFiles = async function (modulePath: string, moduleName: string): Promise<string[]> {
const sideFiles = SIDE_FILES[moduleName]

if (sideFiles === undefined) {
return []
}
Expand Down
2 changes: 2 additions & 0 deletions src/runtimes/node/bundlers/zisi/src_files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ const getImportDependencies = function ({
treeShakeNext: boolean
}): Promise<string[]> {
const shouldTreeShakeNext = treeShakeNext || isNextOnNetlify(dependency)

if (shouldTreeShake(dependency, shouldTreeShakeNext)) {
return getTreeShakedDependencies({
dependency,
Expand Down Expand Up @@ -204,6 +205,7 @@ const getTreeShakedDependencies = async function ({
state,
treeShakeNext,
})

return [path, ...depsPath]
}
/* eslint-enable max-lines */
2 changes: 2 additions & 0 deletions src/runtimes/node/bundlers/zisi/traverse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ const getDependenciesForModuleName = async function ({
getSideFiles(modulePath, moduleName),
getNestedModules({ modulePath, state, packageJson, pluginsModulesPath }),
])

return [...publishedFiles, ...sideFiles, ...depsPaths]
}

Expand All @@ -107,5 +108,6 @@ const getNestedModules = async function ({
getDependencyPathsForDependency({ dependency, basedir: modulePath, state, packageJson, pluginsModulesPath }),
),
)

return depsPaths.flat()
}
1 change: 1 addition & 0 deletions src/runtimes/node/in_source_config/properties/schedule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const parse = ({ args }: { args: ISCHandlerArg[] }, getAllBindings: Bindi

if (expression.type === 'Identifier') {
const binding = getAllBindings().get(expression.name)

if (binding) {
expression = binding
}
Expand Down
2 changes: 2 additions & 0 deletions src/runtimes/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ const zipFunction: ZipFunction = async function ({
// We simply copy it to the destination path with no further processing.
if (extension === '.zip') {
const destPath = join(destFolder, filename)

await cpFile(srcPath, destPath)

return { config, path: destPath }
}

Expand Down
1 change: 1 addition & 0 deletions src/runtimes/node/parser/bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export type BindingMethod = () => Bindings
export const createBindingsMethod = function (nodes: Statement[]): BindingMethod {
// memoize the result for these nodes
let result: Bindings

return () => {
if (!result) {
result = getAllBindings(nodes)
Expand Down
1 change: 1 addition & 0 deletions src/runtimes/node/parser/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ const getMainExportFromESM = (node: Statement, getAllBindings: BindingMethod) =>
// or with StringLiteral `export { x as "handler" }`
const isHandlerExport = (node: ExportNamedDeclaration['specifiers'][number]): node is ExportSpecifier => {
const { type, exported } = node

return (
type === 'ExportSpecifier' &&
((exported.type === 'Identifier' && exported.name === 'handler') ||
Expand Down
1 change: 1 addition & 0 deletions src/runtimes/node/utils/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ const BACKSLASH_REGEXP = /\\/g
export const getModuleName = function (dependency: string): string {
const dependencyA = dependency.replace(BACKSLASH_REGEXP, '/')
const moduleName = requirePackageName(dependencyA)

return moduleName
}
1 change: 1 addition & 0 deletions src/runtimes/node/utils/normalize_path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ export const normalizeFilePath = function ({
const pathA = normalize(path)
const pathB = pathA.replace(commonPrefix, userNamespacePathSegment)
const pathC = unixify(pathB)

return pathC
}
2 changes: 2 additions & 0 deletions src/runtimes/node/utils/package_json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export const getClosestPackageJson = async (resolveDir: string): Promise<Package
// Retrieve the `package.json` of a specific project or module
export const getPackageJson = async function (srcDir: string): Promise<PackageJson> {
const result = await getClosestPackageJson(srcDir)

return result?.contents ?? {}
}

Expand All @@ -71,6 +72,7 @@ const readPackageJson = async (path: string) => {
try {
// The path depends on the user's build, i.e. must be dynamic
const packageJson = JSON.parse(await fs.readFile(path, 'utf8'))

return sanitisePackageJson(packageJson)
} catch (error) {
throw new Error(`${path} is invalid JSON: ${error.message}`)
Expand Down
1 change: 1 addition & 0 deletions src/utils/matching.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const pGlob = promisify(globFunction)

export const glob = function (pattern: string, options: globFunction.IOptions): Promise<string[]> {
let normalizedIgnore

if (options.ignore) {
normalizedIgnore =
typeof options.ignore === 'string'
Expand Down
1 change: 1 addition & 0 deletions src/zip_binary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export const zipBinary = async function ({
stat: Stats
}) {
const { archive, output } = startZip(destPath)

addZipFile(archive, srcPath, filename, stat)
addZipContent(archive, JSON.stringify({ runtime: runtime.name }), 'netlify-toolchain')
await endZip(archive, output)
Expand Down

1 comment on commit 14bf813

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⏱ Benchmark results

largeDepsEsbuild: 6.1s

largeDepsNft: 29.4s

largeDepsZisi: 44.8s

Please sign in to comment.