|
1 | 1 | import { exec } from 'node:child_process' |
2 | 2 | import path from 'node:path' |
| 3 | +import { Worker } from 'node:worker_threads' |
3 | 4 |
|
4 | 5 | import { dialog, ipcMain } from 'electron' |
5 | 6 | import fs from 'fs-extra' |
6 | 7 | import trash from 'trash' |
7 | 8 |
|
8 | 9 | import { projectsFilePath } from '../utils/dataPath' |
9 | 10 | import type { LinguistResult } from '../utils/linguist' |
10 | | -import { analyzeFolder } from '../utils/linguist' |
11 | 11 |
|
12 | 12 | // 传入项目根目录,获取项目各编程语言的占比 |
13 | | -ipcMain.handle('project:analyze', async (_, folderPath): Promise<LinguistResult | { error: string }> => { |
14 | | - try { |
15 | | - const stat = await fs.stat(folderPath) |
| 13 | +ipcMain.handle('project:analyze', async (event, folderPath): Promise<LinguistResult | { error: string }> => { |
| 14 | + return await new Promise((resolve) => { |
| 15 | + try { |
| 16 | + const workerUrl = new URL('../workers/linguistAnalyze.worker.js', import.meta.url) |
| 17 | + const worker = new Worker(workerUrl, { type: 'module', workerData: { folderPath } } as any) |
| 18 | + |
| 19 | + const cleanup = () => worker.removeAllListeners() |
| 20 | + const send = (stage: 'start' | 'checking' | 'analyzing' | 'done') => { |
| 21 | + try { |
| 22 | + event.sender.send('project:analyze:progress', { |
| 23 | + folderPath, |
| 24 | + stage, |
| 25 | + }) |
| 26 | + } |
| 27 | + catch {} |
| 28 | + } |
16 | 29 |
|
17 | | - // 检查是否是目录 |
18 | | - if (!stat.isDirectory()) { |
19 | | - return { error: 'Provided path is not a directory' } |
| 30 | + worker.on('message', (msg: any) => { |
| 31 | + if (msg?.type === 'progress') { |
| 32 | + send(msg.stage) |
| 33 | + } |
| 34 | + else if (msg?.type === 'result') { |
| 35 | + cleanup() |
| 36 | + resolve(msg.result as LinguistResult) |
| 37 | + } |
| 38 | + else if (msg?.type === 'error') { |
| 39 | + cleanup() |
| 40 | + resolve({ error: msg.error || 'analyze error' }) |
| 41 | + } |
| 42 | + }) |
| 43 | + |
| 44 | + worker.once('error', (err) => { |
| 45 | + cleanup() |
| 46 | + resolve({ error: String(err) }) |
| 47 | + }) |
| 48 | + worker.once('exit', (code) => { |
| 49 | + if (code !== 0) { |
| 50 | + cleanup() |
| 51 | + resolve({ error: `analyze worker exited with code ${code}` }) |
| 52 | + } |
| 53 | + }) |
20 | 54 | } |
21 | | - |
22 | | - // 如果路径是有效的目录,继续分析 |
23 | | - return analyzeFolder(folderPath) |
24 | | - } |
25 | | - catch (error) { |
26 | | - return { error: `Error checking folder path:${error}` } |
27 | | - } |
| 55 | + catch (e) { |
| 56 | + resolve({ error: `Error starting analyze worker: ${String(e)}` }) |
| 57 | + } |
| 58 | + }) |
28 | 59 | }) |
29 | 60 |
|
30 | 61 | // 使用IDE打开项目 |
|
0 commit comments