Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect/resolve ambiguous script names #9848

Merged
merged 2 commits into from
Aug 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changesets/9848.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
- Detect/resolve ambiguous script names (#9848) by @codersmith

Detects and resolves ambiguous script name combinations like `[foo.js, foo.ts]` or `[foo.ts, foo.json]` when running `yarn rw exec foo`.
38 changes: 34 additions & 4 deletions packages/cli/src/commands/__tests__/exec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,23 @@ import { handler } from '../execHandler'
vi.mock('envinfo', () => ({ default: { run: () => '' } }))
vi.mock('@redwoodjs/project-config', () => ({
getPaths: () => ({
scripts: path.join(
__dirname,
'../../../../../__fixtures__/test-project/scripts',
),
scripts: path.join('redwood-app', 'scripts'),
}),
resolveFile: (path: string) => path,
}))
vi.mock('@redwoodjs/internal/dist/files', () => ({
findScripts: () => {
const scriptsPath = path.join('redwood-app', 'scripts')

return [
path.join(scriptsPath, 'one', 'two', 'myNestedScript.ts'),
path.join(scriptsPath, 'conflicting.js'),
path.join(scriptsPath, 'conflicting.ts'),
path.join(scriptsPath, 'normalScript.ts'),
path.join(scriptsPath, 'secondNormalScript.ts'),
]
},
}))

const mockRedwoodToml = {
fileContents: '',
Expand Down Expand Up @@ -49,4 +59,24 @@ describe('yarn rw exec --list', () => {
expect.stringMatching(new RegExp('\\b' + scriptPath + '\\b')),
)
})

it("does not include the file extension if there's no ambiguity", async () => {
await handler({ list: true })
expect(vi.mocked(console).log).toHaveBeenCalledWith(
expect.stringMatching(new RegExp('\\bnormalScript\\b')),
)
expect(vi.mocked(console).log).toHaveBeenCalledWith(
expect.stringMatching(new RegExp('\\bsecondNormalScript\\b')),
)
})

it('includes the file extension if there could be ambiguity', async () => {
await handler({ list: true })
expect(vi.mocked(console).log).toHaveBeenCalledWith(
expect.stringMatching(new RegExp('\\bconflicting.js\\b')),
)
expect(vi.mocked(console).log).toHaveBeenCalledWith(
expect.stringMatching(new RegExp('\\bconflicting.ts\\b')),
)
})
})
82 changes: 70 additions & 12 deletions packages/cli/src/commands/execHandler.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import path from 'path'
import fs from 'node:fs'
import path from 'node:path'

import { context } from '@opentelemetry/api'
import { suppressTracing } from '@opentelemetry/core'
Expand All @@ -17,12 +18,30 @@ import { runScriptFunction } from '../lib/exec'
import { generatePrismaClient } from '../lib/generatePrismaClient'

const printAvailableScriptsToConsole = () => {
console.log('Available scripts:')
findScripts(getPaths().scripts).forEach((scriptPath) => {
// Loop through all scripts and get their relative path
// Also group scripts with the same name but different extensions
const scripts = findScripts(getPaths().scripts).reduce((acc, scriptPath) => {
const relativePath = path.relative(getPaths().scripts, scriptPath)
const { ext } = path.parse(relativePath)
const relativePathWithoutExt = relativePath.slice(0, -ext.length)
console.log(c.info(`- ${relativePathWithoutExt}`))
const ext = path.parse(relativePath).ext
const pathNoExt = relativePath.slice(0, -ext.length)

acc[pathNoExt] ||= []
acc[pathNoExt].push(relativePath)

return acc
}, {})

console.log('Available scripts:')
Object.entries(scripts).forEach(([name, paths]) => {
// If a script name exists with multiple extensions, print them all,
// including the extension
if (paths.length > 1) {
paths.forEach((scriptPath) => {
console.log(c.info(`- ${scriptPath}`))
})
} else {
console.log(c.info(`- ${name}`))
}
})
console.log()
}
Expand All @@ -40,8 +59,6 @@ export const handler = async (args) => {
return
}

const scriptPath = path.join(getPaths().scripts, name)

const {
overrides: _overrides,
plugins: webPlugins,
Expand Down Expand Up @@ -101,11 +118,11 @@ export const handler = async (args) => {
],
})

try {
require.resolve(scriptPath)
} catch {
const scriptPath = resolveScriptPath(name)

if (!scriptPath) {
console.error(
c.error(`\nNo script called ${c.underline(name)} in ./scripts folder.\n`),
c.error(`\nNo script called \`${name}\` in the ./scripts folder.\n`),
)

printAvailableScriptsToConsole()
Expand Down Expand Up @@ -145,3 +162,44 @@ export const handler = async (args) => {
await tasks.run()
})
}

function resolveScriptPath(name) {
const scriptPath = path.join(getPaths().scripts, name)

// If scriptPath already has an extension, and it's a valid path, return it
// as it is
if (fs.existsSync(scriptPath)) {
return scriptPath
}

// These extensions match the ones in internal/src/files.ts::findScripts()
const extensions = ['.js', '.jsx', '.ts', '.tsx']
const matches = []

for (const extension of extensions) {
const p = scriptPath + extension

if (fs.existsSync(p)) {
matches.push(p)
}
}

if (matches.length === 1) {
return matches[0]
} else if (matches.length > 1) {
console.error(
c.error(
`\nMultiple scripts found for \`${name}\`. Please specify the ` +
'extension.',
),
)

matches.forEach((match) => {
console.log(c.info(`- ${path.relative(getPaths().scripts, match)}`))
})

process.exit(1)
}

return null
}
Loading