From 472001d703305bc820d4731af31497da08319317 Mon Sep 17 00:00:00 2001 From: Anshuman Singh Date: Sun, 25 Aug 2024 12:57:33 +0100 Subject: [PATCH] Ensure certain paths are always in gitignore --- programs/create/module.ts | 2 ++ programs/create/steps/write-gitignore.ts | 38 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 programs/create/steps/write-gitignore.ts diff --git a/programs/create/module.ts b/programs/create/module.ts index 6397f966..59d5ce4f 100644 --- a/programs/create/module.ts +++ b/programs/create/module.ts @@ -9,6 +9,7 @@ import {installDependencies} from './steps/install-dependencies' import {writeReadmeFile} from './steps/write-readme-file' import {writeManifestJson} from './steps/write-manifest-json' import {generateExtensionTypes} from './steps/generate-extension-types' +import {writeGitignore} from './steps/write-gitignore' import {initializeGitRepository} from './steps/initialize-git-repository' export interface CreateOptions { @@ -53,6 +54,7 @@ export async function extensionCreate( await writeReadmeFile(projectPath, projectName) await writeManifestJson(projectPath, projectName) await initializeGitRepository(projectPath, projectName) + await writeGitignore(projectPath) if (utils.isTypeScriptTemplate(template)) { await generateExtensionTypes(projectPath, projectName) diff --git a/programs/create/steps/write-gitignore.ts b/programs/create/steps/write-gitignore.ts new file mode 100644 index 00000000..6c09d541 --- /dev/null +++ b/programs/create/steps/write-gitignore.ts @@ -0,0 +1,38 @@ +import fs from 'fs/promises' + +const globalLines = ['/dist', 'extension.d.ts'] + +export async function writeGitignore(projectPath: string) { + const gitIgnorePath = projectPath + '/.gitignore' + + const fileHandle = await fs.open(gitIgnorePath, 'a+').catch((err) => { + console.error(err) + process.exit(1) + }) + + const paths = new Set() + // autoClose is required, otherwise the stream will close the file + // and we'll be unable to append to it + // + // Note: while readLines works for this use-case, care needs to be had + // if adding more contents to the loop, basically, the loop should just + // consume the data from readLines and nothing else + // + // Reference: https://stackoverflow.com/a/70616910 + for await (let line of fileHandle.readLines({autoClose: false})) { + line = line.trim() + if (line.length === 0 || line.startsWith('#')) { + continue + } + paths.add(line) + } + + const linesToAdd = globalLines.filter((line) => !paths.has(line)) + + await fileHandle + .appendFile(linesToAdd.join('\n'), {flush: true}) + .catch((err) => { + console.error(err) + process.exit(1) + }) +}