Skip to content
Source
Sign inSign up
TanStack/cli
Open History to see the last commit

file-helpers.ts

273 lines7.3 KB

1import { readdir } from 'node:fs/promises'
2import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
3import { basename, extname, resolve } from 'node:path'
4import parseGitignore from 'parse-gitignore'
5import ignore from 'ignore'
6​
7import { hasDrive, stripDrive } from './utils'
8import type { Environment } from './types'
9​
10const BINARY_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico']
11​
12export function readFileHelper(path: string): string {
13 if (isBinaryFile(path)) {
14 return `base64::${readFileSync(path).toString('base64')}`
15 } else {
16 return readFileSync(path, 'utf-8').toString()
17 }
19​
20export function isBinaryFile(path: string): boolean {
21 return BINARY_EXTENSIONS.includes(extname(path))
23​
24export function convertBinaryContentsToBase64(contents: any): string {
25 return `base64::${Buffer.from(contents).toString('base64')}`
27​
28export function isBase64(content: string): boolean {
29 return content.startsWith('base64::')
31​
32export function getBinaryFile(content: string): string | null {
33 if (content.startsWith('base64::')) {
34 const binaryContent = Buffer.from(content.replace('base64::', ''), 'base64')
35 return binaryContent as unknown as string
36 }
37 return null
39​
40/**
41 * Returns a path without leading ./ or / prefix.
42 */
43export function toCleanPath(absolutePath: string, baseDir: string): string {
44 // Normalize both paths to use forward slashes for consistent comparison
45 const normalizedPath = absolutePath.replace(/\\/g, '/')
46 const normalizedBase = baseDir.replace(/\\/g, '/')
47 let cleanPath = normalizedPath
48 if (normalizedPath.startsWith(normalizedBase)) {
49 cleanPath = normalizedPath.slice(normalizedBase.length)
50 } else if (hasDrive(normalizedPath) !== hasDrive(normalizedBase)) {
51 // Handle paths that are missing the Windows drive letter (e.g. memfs on Windows)
52 const pathNoDrive = stripDrive(normalizedPath)
53 const baseNoDrive = stripDrive(normalizedBase)
54 if (pathNoDrive.startsWith(baseNoDrive)) {
55 cleanPath = pathNoDrive.slice(baseNoDrive.length)
56 }
57 }
58 // Handle leading path separator
59 if (cleanPath.startsWith('/')) {
60 cleanPath = cleanPath.slice(1)
61 }
62 return cleanPath
64​
65export function relativePath(
66 from: string,
67 to: string,
68 stripExtension: boolean = false,
69) {
70 // Always normalize backslashes to forward slashes for Windows compatibility
71 const normalized = from.replace(/\\/g, '/')
72 const cleanedFrom = normalized.startsWith('./')
73 ? normalized.slice(2)
74 : normalized
75 const cleanedTo = to.startsWith('./') ? to.slice(2) : to
76​
77 const fromSegments = cleanedFrom.split('/')
78 const toSegments = cleanedTo.split('/')
79​
80 fromSegments.pop()
81 toSegments.pop()
82​
83 let commonIndex = 0
84 while (
85 commonIndex < fromSegments.length &&
86 commonIndex < toSegments.length &&
87 fromSegments[commonIndex] === toSegments[commonIndex]
88 ) {
89 commonIndex++
90 }
91​
92 const upLevels = fromSegments.length - commonIndex
93 const downLevels = toSegments.slice(commonIndex)
94​
95 if (stripExtension) {
96 to = to.replace(extname(to), '')
97 }
98​
99 if (upLevels === 0 && downLevels.length === 0) {
100 return `./${basename(to)}`
101 } else if (upLevels === 0 && downLevels.length > 0) {
102 return `./${downLevels.join('/')}/${basename(to)}`
103 } else {
104 const relativePath = [...Array(upLevels).fill('..'), ...downLevels].join(
105 '/',
106 )
107 return `${relativePath}/${basename(to)}`
108 }
110​
111export function isDirectory(path: string): boolean {
112 return statSync(path).isDirectory()
114​
115export function findFilesRecursively(
116 path: string,
117 files: Record<string, string>,
118) {
119 const dirFiles = readdirSync(path)
120 for (const file of dirFiles) {
121 const filePath = resolve(path, file)
122 if (isDirectory(filePath)) {
123 findFilesRecursively(filePath, files)
124 } else {
125 files[filePath] = readFileHelper(filePath)
126 }
127 }
129​
130async function recursivelyGatherFilesHelper(
131 basePath: string,
132 path: string,
133 files: Record<string, string>,
134 ignore: (filePath: string) => boolean,
135) {
136 const dirFiles = await readdir(path, { withFileTypes: true })
137 for (const file of dirFiles) {
138 if (ignore(file.name)) {
139 continue
140 }
141 if (file.isDirectory()) {
142 await recursivelyGatherFilesHelper(
143 basePath,
144 resolve(path, file.name),
145 files,
146 ignore,
147 )
148 } else {
149 const filePath = resolve(path, file.name)
150 files[toCleanPath(filePath, basePath)] = await readFileHelper(filePath)
151 }
152 }
154​
155export async function recursivelyGatherFiles(
156 path: string,
157 includeProjectFiles = true,
158) {
159 const ignore = createIgnore(path, includeProjectFiles)
160 const files: Record<string, string> = {}
161 await recursivelyGatherFilesHelper(path, path, files, ignore)
162 return files
164​
165async function recursivelyGatherFilesFromEnvironmentHelper(
166 environment: Environment,
167 basePath: string,
168 path: string,
169 files: Record<string, string>,
170 ignore: (filePath: string) => boolean,
171) {
172 const dirFiles = await environment.readdir(path)
173 for (const file of dirFiles) {
174 if (ignore(file)) {
175 continue
176 }
177 if (environment.isDirectory(resolve(path, file))) {
178 await recursivelyGatherFilesFromEnvironmentHelper(
179 environment,
180 basePath,
181 resolve(path, file),
182 files,
183 ignore,
184 )
185 } else {
186 const filePath = resolve(path, file)
187 files[toCleanPath(filePath, basePath)] =
188 await environment.readFile(filePath)
189 }
190 }
192​
193export async function recursivelyGatherFilesFromEnvironment(
194 environment: Environment,
195 path: string,
196 includeProjectFiles = true,
197) {
198 const ignore = createIgnore(path, includeProjectFiles)
199 const files: Record<string, string> = {}
200 await recursivelyGatherFilesFromEnvironmentHelper(
201 environment,
202 path,
203 path,
204 files,
205 ignore,
206 )
207 return files
209​
210export const IGNORE_FILES = [
211 '.starter',
212 '.add-on',
213 '.cta.json',
214 '.git',
215 'add-on-info.json',
216 'add-on.json',
217 'build',
218 'bun.lock',
219 'bun.lockb',
220 'deno.lock',
221 'dist',
222 'node_modules',
223 'package-lock.json',
224 'pnpm-lock.yaml',
225 'starter.json',
226 'starter-info.json',
227 'yarn.lock',
229​
230const PROJECT_FILES = ['package.json']
231​
232export function createIgnore(path: string, includeProjectFiles = true) {
233 const ignoreList = existsSync(resolve(path, '.gitignore'))
234 ? (
235 parseGitignore(
236 readFileSync(resolve(path, '.gitignore')),
237 ) as unknown as { patterns: Array<string> }
238 ).patterns
239 : []
240 const ig = ignore().add(ignoreList)
241 return (filePath: string) => {
242 const fileName = basename(filePath)
243 if (
244 IGNORE_FILES.includes(fileName) ||
245 (includeProjectFiles && PROJECT_FILES.includes(fileName))
246 ) {
247 return true
248 }
249 const nameWithoutDotSlash = fileName.replace(/^\.\//, '')
250 return ig.ignores(nameWithoutDotSlash)
251 }
253​
254export function cleanUpFiles(
255 files: Record<string, string>,
256 targetDir?: string,
257) {
258 return Object.keys(files).reduce<Record<string, string>>((acc, file) => {
259 if (basename(file) !== '.cta.json') {
260 acc[targetDir ? toCleanPath(file, targetDir) : file] = files[file]
261 }
262 return acc
263 }, {})
265​
266export function cleanUpFileArray(files: Array<string>, targetDir?: string) {
267 return files.reduce<Array<string>>((acc, file) => {
268 if (basename(file) !== '.cta.json') {
269 acc.push(targetDir ? toCleanPath(file, targetDir) : file)
270 }
271 return acc
272 }, [])