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

fix(cli): always check if tempfile exists #1041

Merged
merged 2 commits into from
Dec 26, 2024
Merged
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
36 changes: 19 additions & 17 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ export async function main() {
await importPath(filepath)
}

export async function runScript(script: string, ext = EXT) {
const filepath = path.join($.cwd ?? process.cwd(), `zx-${randomId()}${ext}`)
export async function runScript(script: string, ext?: string) {
const filepath = getFilepath($.cwd, 'zx', ext)
await writeAndImport(script, filepath)
}

Expand All @@ -154,18 +154,16 @@ export async function scriptFromStdin(ext?: string): Promise<boolean> {
return false
}

export async function scriptFromHttp(remote: string, _ext = EXT) {
export async function scriptFromHttp(remote: string, _ext?: string) {
const res = await fetch(remote)
if (!res.ok) {
console.error(`Error: Can't get ${remote}`)
process.exit(1)
}
const script = await res.text()
const pathname = new URL(remote).pathname
const name = path.basename(pathname)
const ext = path.extname(pathname) || _ext
const cwd = $.cwd ?? process.cwd()
const filepath = path.join(cwd, `${name}-${randomId()}${ext}`)
const { name, ext } = path.parse(pathname)
const filepath = getFilepath($.cwd, name, _ext || ext)
await writeAndImport(script, filepath)
}

Expand All @@ -188,22 +186,15 @@ export async function importPath(
origin = filepath
): Promise<void> {
const { ext, base, dir } = path.parse(filepath)
const tempFilename = getFilepath(dir, base)

if (ext === '') {
const tmpFilename = fs.existsSync(filepath + EXT)
? base + '-' + randomId() + EXT
: base + EXT

return writeAndImport(
await fs.readFile(filepath),
path.join(dir, tmpFilename),
origin
)
return writeAndImport(await fs.readFile(filepath), tempFilename, origin)
}
if (ext === '.md') {
return writeAndImport(
transformMarkdown(await fs.readFile(filepath)),
path.join(dir, base + EXT),
tempFilename,
origin
)
}
Expand Down Expand Up @@ -311,3 +302,14 @@ export function isMain(
export function normalizeExt(ext?: string): string | undefined {
return ext ? path.parse(`foo.${ext}`).ext : ext
}

// prettier-ignore
function getFilepath(cwd = '.', name = 'zx', _ext?: string): string {
const ext = _ext || argv.ext || EXT
return [
name + ext,
name + '-' + randomId() + ext,
]
.map(f => path.resolve(process.cwd(), cwd, f))
.find(f => !fs.existsSync(f))!
}
Loading