|
| 1 | +import type { Promisable } from '@subframe7536/type-utils' |
| 2 | +import { existsSync, rmSync } from 'node:fs' |
| 3 | +import { readFileSync, writeFileSync } from 'atomically' |
1 | 4 | import { useLogger } from 'reactive-vscode'
|
2 | 5 | import { commands, window } from 'vscode'
|
3 |
| -import { displayName } from './generated/meta' |
| 6 | +import { displayName, name } from './generated/meta' |
4 | 7 |
|
5 | 8 | export const logger = useLogger(displayName)
|
6 | 9 |
|
7 |
| -export async function runAndRestart(message: string, action: () => Promise<any>) { |
8 |
| - await action() |
9 |
| - const item = await window.showInformationMessage(message, { title: 'Restart vscode' }) |
10 |
| - if (item) { |
11 |
| - commands.executeCommand('workbench.action.reloadWindow') |
| 10 | +const lockFileName = `__${name}__.lock` |
| 11 | + |
| 12 | +async function runWithLock(fn: () => Promisable<void>) { |
| 13 | + let count = 5 |
| 14 | + const check = () => existsSync(lockFileName) |
| 15 | + while (check() && count--) { |
| 16 | + await new Promise(resolve => setTimeout(resolve, 1000)) |
| 17 | + } |
| 18 | + if (!count) { |
| 19 | + // If exists and expire time exceed 10 minutes, just remove it |
| 20 | + if (check() && Number(readFileSync(lockFileName, 'utf-8')) - Date.now() > 6e5) { |
| 21 | + rmSync(lockFileName) |
| 22 | + } else { |
| 23 | + await showMessage('File locked, cancel operation') |
| 24 | + return |
| 25 | + } |
12 | 26 | }
|
| 27 | + writeFileSync(lockFileName, String(Date.now())) |
| 28 | + try { |
| 29 | + await fn() |
| 30 | + } finally { |
| 31 | + rmSync(lockFileName) |
| 32 | + } |
| 33 | +} |
| 34 | +export async function runAndRestart(message: string, action: () => Promise<any>) { |
| 35 | + await runWithLock(async () => { |
| 36 | + await action() |
| 37 | + const item = await window.showInformationMessage(message, { title: 'Restart vscode' }) |
| 38 | + if (item) { |
| 39 | + commands.executeCommand('workbench.action.reloadWindow') |
| 40 | + } |
| 41 | + }) |
13 | 42 | }
|
14 | 43 |
|
15 | 44 | export async function showMessage(content: string) {
|
|
0 commit comments