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

file-helpers.ts

294 lines7.7 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.js'
8import type { Environment } from './types.js'
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 in memory.
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 isDemoFilePath(path?: string): boolean {
116 if (!path) return false
117 const normalized = path.replace(/\\/g, '/')
118​
119 if (
120 normalized.includes('/routes/demo/') ||
121 normalized.includes('/routes/example/')
122 ) {
123 return true
124 }
125​
126 const filename = normalized.split('/').pop() || ''
127 return (
128 filename.startsWith('demo.') ||
129 filename.startsWith('demo-') ||
130 filename.startsWith('example.') ||
131 filename.startsWith('example-')
132 )
134​
135export function findFilesRecursively(
136 path: string,
137 files: Record<string, string>,
138) {
139 const dirFiles = readdirSync(path)
140 for (const file of dirFiles) {
141 const filePath = resolve(path, file)
142 if (isDirectory(filePath)) {
143 findFilesRecursively(filePath, files)
144 } else {
145 files[filePath] = readFileHelper(filePath)
146 }
147 }
149​
150async function recursivelyGatherFilesHelper(
151 basePath: string,
152 path: string,
153 files: Record<string, string>,
154 ignore: (filePath: string) => boolean,
155) {
156 const dirFiles = await readdir(path, { withFileTypes: true })
157 for (const file of dirFiles) {
158 if (ignore(file.name)) {
159 continue
160 }
161 if (file.isDirectory()) {
162 await recursivelyGatherFilesHelper(
163 basePath,
164 resolve(path, file.name),
165 files,
166 ignore,
167 )
168 } else {
169 const filePath = resolve(path, file.name)
170 files[toCleanPath(filePath, basePath)] = await readFileHelper(filePath)
171 }
172 }
174​
175export async function recursivelyGatherFiles(
176 path: string,
177 includeProjectFiles = true,
178) {
179 const ignore = createIgnore(path, includeProjectFiles)
180 const files: Record<string, string> = {}
181 await recursivelyGatherFilesHelper(path, path, files, ignore)
182 return files
184​
185async function recursivelyGatherFilesFromEnvironmentHelper(
186 environment: Environment,
187 basePath: string,
188 path: string,
189 files: Record<string, string>,
190 ignore: (filePath: string) => boolean,
191) {
192 const dirFiles = await environment.readdir(path)
193 for (const file of dirFiles) {
194 if (ignore(file)) {
195 continue
196 }
197 if (environment.isDirectory(resolve(path, file))) {
198 await recursivelyGatherFilesFromEnvironmentHelper(
199 environment,
200 basePath,
201 resolve(path, file),
202 files,
203 ignore,
204 )
205 } else {
206 const filePath = resolve(path, file)
207 files[toCleanPath(filePath, basePath)] =
208 await environment.readFile(filePath)
209 }
210 }
212​
213export async function recursivelyGatherFilesFromEnvironment(
214 environment: Environment,
215 path: string,
216 includeProjectFiles = true,
217) {
218 const ignore = createIgnore(path, includeProjectFiles)
219 const files: Record<string, string> = {}
220 await recursivelyGatherFilesFromEnvironmentHelper(
221 environment,
222 path,
223 path,
224 files,
225 ignore,
226 )
227 return files
229​
230export const IGNORE_FILES = [
231 '.starter',
232 '.template',
233 '.add-on',
234 '.cta.json',
235 '.git',
236 'add-on-info.json',
237 'add-on.json',
238 'build',
239 'bun.lock',
240 'bun.lockb',
241 'deno.lock',
242 'dist',
243 'node_modules',
244 'package-lock.json',
245 'pnpm-lock.yaml',
246 'starter.json',
247 'starter-info.json',
248 'yarn.lock',
250​
251const PROJECT_FILES = ['package.json']
252​
253export function createIgnore(path: string, includeProjectFiles = true) {
254 const ignoreList = existsSync(resolve(path, '.gitignore'))
255 ? (
256 parseGitignore(
257 readFileSync(resolve(path, '.gitignore')),
258 ) as unknown as { patterns: Array<string> }
259 ).patterns
260 : []
261 const ig = ignore().add(ignoreList)
262 return (filePath: string) => {
263 const fileName = basename(filePath)
264 if (
265 IGNORE_FILES.includes(fileName) ||
266 (includeProjectFiles && PROJECT_FILES.includes(fileName))
267 ) {
268 return true
269 }
270 const nameWithoutDotSlash = fileName.replace(/^\.\//, '')
271 return ig.ignores(nameWithoutDotSlash)
272 }
274​
275export function cleanUpFiles(
276 files: Record<string, string>,
277 targetDir?: string,
278) {
279 return Object.keys(files).reduce<Record<string, string>>((acc, file) => {
280 if (basename(file) !== '.cta.json') {
281 acc[targetDir ? toCleanPath(file, targetDir) : file] = files[file]
282 }
283 return acc
284 }, {})
286​
287export function cleanUpFileArray(files: Array<string>, targetDir?: string) {
288 return files.reduce<Array<string>>((acc, file) => {
289 if (basename(file) !== '.cta.json') {
290 acc.push(targetDir ? toCleanPath(file, targetDir) : file)
291 }
292 return acc
293 }, [])