From 91e83c211f67b987ce05e0bde39b1e51a53e73e9 Mon Sep 17 00:00:00 2001 From: Alex Lohr Date: Sat, 18 May 2024 21:57:13 +0200 Subject: [PATCH] remove stray getAppConfig + refactor --- packages/commands/src/handlers/add.ts | 2 - packages/commands/src/lib/integrations.ts | 89 ++++---- packages/commands/src/lib/utils/helpers.ts | 229 +++++++++++---------- 3 files changed, 162 insertions(+), 158 deletions(-) diff --git a/packages/commands/src/handlers/add.ts b/packages/commands/src/handlers/add.ts index 5b1f48c..1667521 100644 --- a/packages/commands/src/handlers/add.ts +++ b/packages/commands/src/handlers/add.ts @@ -109,8 +109,6 @@ export const handleAdd = async (packages?: string[], forceTransform: boolean = f }) .filter((p) => p) as Configs; - const appConfig = await getAppConfig(); - for (let i = 0; i < configs.length; i++) { const config = configs[i]; config.installs.forEach((p) => queueUpdate({ type: "package", name: p, dev: false })); diff --git a/packages/commands/src/lib/integrations.ts b/packages/commands/src/lib/integrations.ts index 336fb43..04b2049 100644 --- a/packages/commands/src/lib/integrations.ts +++ b/packages/commands/src/lib/integrations.ts @@ -1,6 +1,6 @@ import { insertAfter, insertAtBeginning } from "@solid-cli/utils/fs"; -import { readFile, writeFile } from "fs/promises"; -import { fileExists, validateFilePath } from "./utils/helpers"; +import { writeFile } from "fs/promises"; +import { fileExists, manipulateJsonFile, validateFilePath } from "./utils/helpers"; import { $ } from "execa"; import { getRunnerCommand, detectPackageManager } from "@solid-cli/utils/package-manager"; import { createSignal } from "@solid-cli/reactivity"; @@ -123,36 +123,30 @@ export const integrations: Record = { additionalConfig: async () => { try { p.log.info("Adding test script to package.json"); - const packageJsonString = await readFile("package.json", "utf8"); - const packageJson = JSON.parse(packageJsonString); - if (!packageJson.scripts) { packageJson.scripts = {}; } - if (!/\bvitest\b/.test(packageJson.scripts.test || "")) { - packageJson.scripts.test = "vitest"; - await writeFile( - "package.json", - JSON.stringify(packageJson, null, /^(\t|\s+)/m.exec(packageJsonString)?.[0] || 2) + "\n", - "utf8" - ); - } + let hasStart = false; + manipulateJsonFile("package.json", (packageJson) => { + if (!packageJson.scripts) { packageJson.scripts = {}; } + if (!/\bvitest\b/.test(packageJson.scripts.test || "")) { + packageJson.scripts.test = "vitest"; + } + hasStart = packageJson.dependencies["@solidjs/start"] + return packageJson; + }); const hasTs = fileExists("tsconfig.json"); - if (hasTs) { + if (hasTs) { p.log.info("Adding testing types to tsconfig.json"); - const tsConfigString = await readFile("tsconfig.json", "utf8"); - const tsConfig = JSON.parse(tsConfigString); - if (!tsConfig.compilerOptions) { - tsConfig.compilerOptions = {}; - } - tsConfig.compilerOptions.types = [ - ...new Set([...(tsConfig.compilerOptions.types || []), "vite/client", "@testing-library/jest-dom"]), - ]; - await writeFile( - "tsconfig.json", - JSON.stringify(tsConfig, null, /^(\t|\s+)/m.exec(tsConfigString)?.[0] || 2) + "\n", - "utf8" - ); + manipulateJsonFile("tsconfig.json", (tsConfig) => { + if (!tsConfig.compilerOptions) { + tsConfig.compilerOptions = {}; + } + tsConfig.compilerOptions.types = [ + ...new Set([...(tsConfig.compilerOptions.types || []), "vite/client", "@testing-library/jest-dom"]), + ]; + return tsConfig; + }); } if ( - packageJson.dependencies["@solidjs/start"] && + hasStart && ["ts", "mjs", "cjs", "js"].every( (suffix) => !fileExists(`vite.config.${suffix}`) && !fileExists(`vitest.config.${suffix}`), ) @@ -183,20 +177,17 @@ export default defineConfig({ installs: ["@tauri-apps/cli"], postInstall: async () => { try { - const packageJsonString = await readFile("package.json", "utf8"); - const packageJson = JSON.parse(packageJsonString); - if (!packageJson.scripts) { packageJson.scripts = {}; } - packageJson.scripts.tauri = "tauri"; - await writeFile( - "package.json", - JSON.stringify(packageJson, null, /^(\t|\s+)/m.exec(packageJsonString)?.[0] || 2) + "\n", - "utf8" - ); + let name = ""; + manipulateJsonFile("package.json", (packageJson) => { + if (!packageJson.scripts) { packageJson.scripts = {}; } + packageJson.scripts.tauri = "tauri"; + name = packageJson.name; + return packageJson; + }); await flushQueue(); - const name = packageJson.name; const pM = detectPackageManager(); await $`${getRunnerCommand(pM)} tauri init --ci -A ${name} -W ${name} -D ../dist -P http://localhost:3000`; - p.outro(`Make sure you have installed all prerequisites: https://tauri.app/v1/guides/getting-started/prerequisites + p.note(`Make sure you have installed all prerequisites: https://tauri.app/v1/guides/getting-started/prerequisites Start tauri development with ${color.bold(pM.name)} ${color.bold(pM.runScriptCommand("tauri dev"))}`); } catch (err) { @@ -208,20 +199,17 @@ export default defineConfig({ installs: ["@tauri-apps/cli@next"], postInstall: async () => { try { - const packageJsonString = await readFile("package.json", "utf8"); - const packageJson = JSON.parse(packageJsonString); - if (!packageJson.scripts) { packageJson.scripts = {}; } - packageJson.scripts.tauri = "tauri"; - await writeFile( - "package.json", - JSON.stringify(packageJson, null, /^(\t|\s+)/m.exec(packageJsonString)?.[0] || 2) + "\n", - "utf8" - ); + let name = ""; + manipulateJsonFile("package.json", (packageJson) => { + if (!packageJson.scripts) { packageJson.scripts = {}; } + packageJson.scripts.tauri = "tauri"; + name = packageJson.name; + return packageJson; + }) await flushQueue(); - const name = packageJson.name; const pM = detectPackageManager(); await $`${getRunnerCommand(pM)} tauri init --ci -A ${name} -W ${name} -D ../dist -P http://localhost:3000`; - p.outro(`Make sure you have installed all prerequisites: https://v2.tauri.app/start/prerequisites/ + p.note(`Make sure you have installed all prerequisites: https://v2.tauri.app/start/prerequisites/ Start tauri development with ${color.bold(pM.name)} ${color.bold(pM.runScriptCommand("tauri dev"))}`); } catch (err) { @@ -230,3 +218,4 @@ export default defineConfig({ }, }, }; + diff --git a/packages/commands/src/lib/utils/helpers.ts b/packages/commands/src/lib/utils/helpers.ts index c56ac54..8fd03dd 100644 --- a/packages/commands/src/lib/utils/helpers.ts +++ b/packages/commands/src/lib/utils/helpers.ts @@ -1,4 +1,5 @@ import { existsSync, lstatSync, readdirSync } from "fs"; +import { readFile, writeFile } from "fs/promises"; import { isSolidStart } from "@solid-cli/utils"; import { join, resolve } from "path"; import { $ } from "execa"; @@ -7,129 +8,145 @@ import * as p from "@clack/prompts"; import color from "picocolors"; export const getProjectRoot = async () => { - const { stdout } = await $`npm root`; + const { stdout } = await $`npm root`; - return stdout.slice(0, stdout.lastIndexOf("/")); + return stdout.slice(0, stdout.lastIndexOf("/")); }; export const getRootFile = async () => { - if (await isSolidStart()) { - return "src/app.tsx"; - } - return "src/index.tsx"; + if (await isSolidStart()) { + return "src/app.tsx"; + } + return "src/index.tsx"; }; export const fileExists = (path: string) => { - return existsSync(path); + return existsSync(path); }; export function validateFilePath(path: string, lookingFor: string): string | undefined; export function validateFilePath(path: string, lookingFor: string[]): string | undefined; export function validateFilePath(path: string, lookingFor: string | string[]): string | undefined { - path = resolve(path); - let isDir: boolean; - try { - console.log(path) - isDir = lstatSync(path).isDirectory(); - } - catch (e) { return undefined } - if (isDir) { - const files = readdirSync(path, { withFileTypes: true }); - - const config = files.find((file) => { - if (Array.isArray(lookingFor)) { - return lookingFor.some((s) => file.name.startsWith(s)); - } - - return file.name.startsWith(lookingFor); - }); - return config ? join(path, config.name) : undefined; - } - - const pathIsValid = Array.isArray(lookingFor) - ? lookingFor.some((s) => path.startsWith(s)) - : path.startsWith(lookingFor); - - const exists = fileExists(path) && pathIsValid; - - return exists ? path : undefined; + path = resolve(path); + let isDir: boolean; + try { + console.log(path); + isDir = lstatSync(path).isDirectory(); + } catch (e) { + return undefined; + } + if (isDir) { + const files = readdirSync(path, { withFileTypes: true }); + + const config = files.find((file) => { + if (Array.isArray(lookingFor)) { + return lookingFor.some((s) => file.name.startsWith(s)); + } + + return file.name.startsWith(lookingFor); + }); + return config ? join(path, config.name) : undefined; + } + + const pathIsValid = Array.isArray(lookingFor) + ? lookingFor.some((s) => path.startsWith(s)) + : path.startsWith(lookingFor); + + const exists = fileExists(path) && pathIsValid; + + return exists ? path : undefined; } export async function findFiles( - startPath: string, - lookingFor: string | string[], - opts: { depth?: number; ignoreDirs?: string[]; startsWith?: boolean }, + startPath: string, + lookingFor: string | string[], + opts: { depth?: number; ignoreDirs?: string[]; startsWith?: boolean }, ): Promise { - let { depth = Infinity, ignoreDirs = ["node_modules", "."], startsWith = true } = opts; - - startPath = resolve(startPath); - let isDir: boolean; - try { - isDir = lstatSync(startPath).isDirectory(); - } - catch (e) { return [] }; - if (!isDir) { - startPath = resolve(startPath.slice(0, startPath.lastIndexOf("/"))); - } - - let filePaths: string[] = []; - - const files = readdirSync(startPath, { withFileTypes: true }); - - for (const file of files) { - if (file.isDirectory() && !ignoreDirs.some((s) => file.name.includes(s))) { - if (Number.isFinite(depth) && depth-- <= 0) continue; - filePaths = filePaths.concat(await findFiles(resolve(startPath, file.name), lookingFor, opts)); - continue; - } - - if (file.isFile()) { - const fileMatch = Array.isArray(lookingFor) - ? lookingFor.some((s) => (startsWith ? file.name.startsWith(s) : file.name.endsWith(s))) - : startsWith - ? file.name.startsWith(lookingFor) - : file.name.endsWith(lookingFor); - - if (fileMatch) { - filePaths.push(resolve(startPath, file.name)); - } - } - } - - return filePaths; + let { depth = Infinity, ignoreDirs = ["node_modules", "."], startsWith = true } = opts; + + startPath = resolve(startPath); + let isDir: boolean; + try { + isDir = lstatSync(startPath).isDirectory(); + } catch (e) { + return []; + } + if (!isDir) { + startPath = resolve(startPath.slice(0, startPath.lastIndexOf("/"))); + } + + let filePaths: string[] = []; + + const files = readdirSync(startPath, { withFileTypes: true }); + + for (const file of files) { + if (file.isDirectory() && !ignoreDirs.some((s) => file.name.includes(s))) { + if (Number.isFinite(depth) && depth-- <= 0) continue; + filePaths = filePaths.concat(await findFiles(resolve(startPath, file.name), lookingFor, opts)); + continue; + } + + if (file.isFile()) { + const fileMatch = Array.isArray(lookingFor) + ? lookingFor.some((s) => (startsWith ? file.name.startsWith(s) : file.name.endsWith(s))) + : startsWith + ? file.name.startsWith(lookingFor) + : file.name.endsWith(lookingFor); + + if (fileMatch) { + filePaths.push(resolve(startPath, file.name)); + } + } + } + + return filePaths; } export const getAppConfig = async () => { - let configFile = "app.config.ts"; - - const existsHere = fileExists(configFile); - - if (!existsHere) { - const root = await getProjectRoot(); - const existsInRoot = validateFilePath(root, "app.config"); - if (existsInRoot) { - const correctConfig = await cancelable( - p.confirm({ - message: `Could not find app config in current directory, but found app config in \`${root}\`. Is this the correct vite config?`, - }), - ); - if (correctConfig) return existsInRoot; - } - - p.log.error(color.red(`Can't find app.config file`)); - await cancelable( - p.text({ - message: "Type path to app config: ", - validate(value) { - const path = validateFilePath(value, "app.config"); - if (!path) return `App config not found. Please try again`; - else { - configFile = path; - } - }, - }), - ); - } - - return configFile; + let configFile = "app.config.ts"; + + const existsHere = fileExists(configFile); + + if (!existsHere) { + const root = await getProjectRoot(); + const existsInRoot = validateFilePath(root, "app.config"); + if (existsInRoot) { + const correctConfig = await cancelable( + p.confirm({ + message: `Could not find app config in current directory, but found app config in \`${root}\`. Is this the correct vite config?`, + }), + ); + if (correctConfig) return existsInRoot; + } + + p.log.error(color.red(`Can't find app.config file`)); + await cancelable( + p.text({ + message: "Type path to app config: ", + validate(value) { + const path = validateFilePath(value, "app.config"); + if (!path) return `App config not found. Please try again`; + else { + configFile = path; + } + }, + }), + ); + } + + return configFile; }; + +export async function manipulateJsonFile(name: string, manipulate: (obj: Record) => Record) { + try { + const jsonString = await readFile(name, "utf8"); + const jsonObj = JSON.parse(jsonString); + await writeFile( + name, + JSON.stringify(manipulate(jsonObj), null, /^(\t|\s+)/m.exec(jsonString)?.[0] || 2) + "\n", + "utf8", + ); + } catch (error) { + p.log.error(color.red(error ? error.toString() : `unknown error when manipulating ${name}`)); + } +}