qinglong/back/shared/utils.ts
copilot-swe-agent[bot] df7f13c6bf Optimize writeFileWithLock to avoid redundant chmod calls
- Track if file is newly created to skip redundant chmod
- Only call chmod for existing files that need permission changes
- Improves performance and reduces unnecessary system calls

Co-authored-by: whyour <22700758+whyour@users.noreply.github.com>
2025-11-07 16:20:30 +00:00

48 lines
1.4 KiB
TypeScript

import { lock } from 'proper-lockfile';
import os from 'os';
import path from 'path';
import { writeFile, open, chmod } from 'fs/promises';
import { fileExist } from '../config/util';
function getUniqueLockPath(filePath: string) {
const sanitizedPath = filePath
.replace(/[<>:"/\\|?*]/g, '_')
.replace(/^_/, '');
return path.join(os.tmpdir(), `${sanitizedPath}.ql_lock`);
}
export async function writeFileWithLock(
filePath: string,
content: string,
options: Parameters<typeof writeFile>[2] = {},
) {
if (typeof options === 'string') {
options = { encoding: options };
}
let isNewFile = false;
if (!(await fileExist(filePath))) {
// Create the file with the specified mode if provided, otherwise use default
const fileMode = options?.mode || 0o666;
const fileHandle = await open(filePath, 'w', fileMode);
await fileHandle.close();
isNewFile = true;
}
const lockfilePath = getUniqueLockPath(filePath);
const release = await lock(filePath, {
retries: {
retries: 10,
factor: 2,
minTimeout: 100,
maxTimeout: 3000,
},
lockfilePath,
});
await writeFile(filePath, content, { encoding: 'utf8', ...options });
// Only chmod if the file already existed (not just created with the correct mode)
if (!isNewFile && options?.mode) {
await chmod(filePath, options.mode);
}
await release();
}