Skip to content

Commit

Permalink
use writeFile directly instead of checking access first
Browse files Browse the repository at this point in the history
  • Loading branch information
going-confetti committed Feb 7, 2025
1 parent e883209 commit c2153db
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 30 deletions.
58 changes: 28 additions & 30 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ import {
import { ProxyStatus, StudioFile } from './types'
import { configureApplicationMenu } from './menu'
import * as Sentry from '@sentry/electron/main'
import { exhaustive } from './utils/typescript'
import { exhaustive, isNodeJsErrnoException } from './utils/typescript'
import { DataFilePreview } from './types/testData'
import { parseDataFile } from './utils/dataFile'
import { createNewGeneratorFile } from './utils/generator'
Expand Down Expand Up @@ -430,16 +430,13 @@ ipcMain.handle(
ipcMain.handle(
'har:save',
async (_, data: HarWithOptionalResponse, prefix: string) => {
const fileName = await generateUniqueFileName({
const fileName = await createFileWithUniqueName({
data: JSON.stringify(data, null, 2),
directory: RECORDINGS_PATH,
ext: '.har',
prefix,
})

await writeFile(
path.join(RECORDINGS_PATH, fileName),
JSON.stringify(data, null, 4)
)
return fileName
}
)
Expand Down Expand Up @@ -488,17 +485,13 @@ ipcMain.handle('har:import', async (event) => {
// Generator
ipcMain.handle('generator:create', async (_, recordingPath: string) => {
const generator = createNewGeneratorFile(recordingPath)
const fileName = await generateUniqueFileName({
const fileName = await createFileWithUniqueName({
data: JSON.stringify(generator, null, 2),
directory: GENERATORS_PATH,
ext: '.json',
prefix: 'Generator',
})

await writeFile(
path.join(GENERATORS_PATH, fileName),
JSON.stringify(generator, null, 2)
)

return fileName
})

Expand Down Expand Up @@ -612,10 +605,7 @@ ipcMain.handle(
await access(newPath)
throw new Error(`File with name ${newFileName} already exists`)
} catch (error) {
if (
error instanceof Error &&
(error as NodeJS.ErrnoException).code !== 'ENOENT'
) {
if (isNodeJsErrnoException(error) && error.code !== 'ENOENT') {
throw error
}
}
Expand Down Expand Up @@ -986,34 +976,42 @@ const cleanUpProxies = async () => {
})
}

const generateUniqueFileName = async ({
const createFileWithUniqueName = async ({
directory,
data,
prefix,
ext,
}: {
directory: string
data: string
prefix: string
ext: string
}): Promise<string> => {
const timestamp = new Date().toISOString().split('T')[0] ?? ''
const template = `${prefix ? `${prefix} - ` : ''}${timestamp}${ext}`

// Start from 2 as it follows the the OS behavior for duplicate files
let fileVersion = 2
let uniqueFileName = template
let fileExists = await access(path.join(directory, uniqueFileName))
.then(() => true)
.catch(() => false)
let fileCreated = false

// Start from 2 as it follows the the OS behavior for duplicate files
let counter = 2
do {
try {
// ax+ flag will throw an error if the file already exists
await writeFile(path.join(directory, uniqueFileName), data, {
flag: 'ax+',
})
fileCreated = true
} catch (error) {
if (isNodeJsErrnoException(error) && error.code !== 'EEXIST') {
throw error
}

while (fileExists) {
const { name, ext } = path.parse(template)
uniqueFileName = `${name} (${counter})${ext}`
fileExists = await access(path.join(directory, uniqueFileName))
.then(() => true)
.catch(() => false)
counter++
}
const { name, ext } = path.parse(template)
uniqueFileName = `${name} (${fileVersion})${ext}`
fileVersion++
}
} while (!fileCreated)

return uniqueFileName
}
11 changes: 11 additions & 0 deletions src/utils/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,14 @@ export type ImmerStateCreator<T> = StateCreator<
[],
T
>

export function isNodeJsErrnoException(
error: unknown
): error is NodeJS.ErrnoException {
return (
error instanceof Error &&
'code' in error &&
'errno' in error &&
'syscall' in error
)
}

0 comments on commit c2153db

Please sign in to comment.