feat(installer): v0.4.0 — 파일제거기, 커스텀 폴더명, 포트포워딩 개편, 이름/개발자용 표기
- 음악퀴즈 파일제거 도구 신규 추가: 동의 → 휴지통/완전삭제 선택 → 커스텀 폴더 (현재값 + 기본 .mc_custom) 전체, 데스크톱 바로가기, gameDir 가 해당 폴더인 마인크래프트 런처 프로필 정리. - MC_CUSTOM_DIR .env 로 커스텀 게임 폴더 이름 유동화(.mc_custom 기본). 렌더러 사전에도 실제 폴더명 반영. - 간편포트포워딩: 실행 중 UPnP 매핑 유지, 창 닫힘/종료 시 자동 제거(activePort 추적). - 개발자용 빌드는 창/헤더 제목 앞에 (개발자용) 표기, exe 이름에도 반영. - exe 이름 변경: 음악퀴즈 간편설치기 / 음악퀴즈 리소스팩설치기 / 간편포트포워딩. - README 및 .env 템플릿 갱신, 버전 0.3.23 → 0.4.0. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -16,6 +16,13 @@ const localeDict = i18n.dict
|
||||
|
||||
let mainWindow: BrowserWindow | null = null
|
||||
|
||||
// 이 도구가 UPnP 로 직접 열어둔 포트. 앱이 살아 있는 동안 매핑을 유지하고,
|
||||
// 창을 닫거나 종료할 때 이 포트의 매핑을 제거한다(사용자가 라우터에 직접 만든
|
||||
// 영구 규칙으로 이미 열려 있던 preForwarded 포트는 우리 것이 아니므로 추적하지 않음).
|
||||
let activePort: number | null = null
|
||||
// before-quit 재진입 가드. 매핑 정리를 마친 뒤에만 실제 종료로 넘어가게 한다.
|
||||
let cleanupDone = false
|
||||
|
||||
function createMainWindow(): void {
|
||||
const iconPath = path.join(__dirname, '..', '..', 'build', process.platform === 'win32' ? 'icon.ico' : 'icon.png')
|
||||
mainWindow = new BrowserWindow({
|
||||
@@ -355,6 +362,13 @@ ipcMain.handle('pf:open', async (_event, portInput: number): Promise<PortForward
|
||||
const localIp = detectLocalIpv4()
|
||||
if (localIp) sendLog(t('log.localIp', { ip: localIp }))
|
||||
|
||||
// 다른 포트를 이미 우리가 열어둔 상태에서 새 포트를 열면, 이전 포트 매핑을 먼저 닫아
|
||||
// 매핑이 새는 것을 막는다.
|
||||
if (activePort !== null && activePort !== port) {
|
||||
await removeUpnpMapping(activePort)
|
||||
activePort = null
|
||||
}
|
||||
|
||||
// 이전에 남은 매핑을 먼저 제거해 "사용자 라우터 규칙으로 이미 열린 상태" 와 구별.
|
||||
sendLog(t('log.cleanup'))
|
||||
await removeUpnpMapping(port)
|
||||
@@ -387,6 +401,8 @@ ipcMain.handle('pf:open', async (_event, portInput: number): Promise<PortForward
|
||||
sendLog(t('log.upnpTry', { port }))
|
||||
try {
|
||||
await openPortViaUpnp(port)
|
||||
// 우리가 연 포트로 기록 → 앱 종료/창 닫힘 시 자동으로 매핑 제거.
|
||||
activePort = port
|
||||
sendLog(t('log.upnpReqOk'))
|
||||
} catch (error) {
|
||||
const msg = (error as Error).message
|
||||
@@ -415,6 +431,7 @@ ipcMain.handle('pf:close', async (_event, portInput: number): Promise<void> => {
|
||||
const port = Number.isFinite(portInput) && portInput > 0 && portInput < 65536 ? Math.floor(portInput) : 25565
|
||||
sendLog(t('log.closeTry', { port }))
|
||||
await removeUpnpMapping(port)
|
||||
if (activePort === port) activePort = null
|
||||
})
|
||||
|
||||
ipcMain.handle('pf:quit', async () => {
|
||||
@@ -432,6 +449,20 @@ app.whenReady().then(() => {
|
||||
})
|
||||
})
|
||||
|
||||
// 창을 닫거나 종료할 때, 이 도구가 열어둔 UPnP 매핑을 제거한 뒤 실제 종료로 넘어간다.
|
||||
// removeUpnpMapping 은 비동기라 before-quit 을 한 번 막고(cleanup) 끝나면 다시 quit 한다.
|
||||
app.on('before-quit', (event) => {
|
||||
if (cleanupDone || activePort === null) return
|
||||
event.preventDefault()
|
||||
const port = activePort
|
||||
activePort = null
|
||||
sendLog(t('log.closeTry', { port }))
|
||||
void removeUpnpMapping(port).finally(() => {
|
||||
cleanupDone = true
|
||||
app.quit()
|
||||
})
|
||||
})
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
app.quit()
|
||||
})
|
||||
|
||||
@@ -9,7 +9,7 @@ import { URL } from 'node:url'
|
||||
import type { ChildProcess } from 'node:child_process'
|
||||
import type { Manifest, PackDefinition, PackList } from '../shared/types.js'
|
||||
import { normalizePackDefinition } from '../shared/store.js'
|
||||
import { getAppDataDir, getMcCustomDir } from '../shared/paths.js'
|
||||
import { getAppDataDir, getMcCustomDir, withCustomDirName } from '../shared/paths.js'
|
||||
import { loadEnv, getManifestUrl } from '../shared/env.js'
|
||||
import { loadComponentI18n } from '../shared/i18n.js'
|
||||
import { resolveAudience, isPackVisibleForAudience, type Audience } from '../shared/audience.js'
|
||||
@@ -273,7 +273,25 @@ ipcMain.handle('rp:packs:select', async (_event, packKey: string) => {
|
||||
sendLog(t('log.selectedPack', { key: packKey }))
|
||||
})
|
||||
|
||||
ipcMain.handle('rp:i18n:dict', () => localeDict)
|
||||
// 개발자용 빌드(musicQuizAudience=developer)면 렌더러에 넘기는 사전의 제목 앞에
|
||||
// "(개발자용) " 을 붙여, 창 제목/헤더에 개발자용임을 표시한다.
|
||||
function dictForRenderer(): Record<string, unknown> {
|
||||
// 커스텀 폴더명을 UI 문구에 반영.
|
||||
const base = withCustomDirName(localeDict)
|
||||
if (getAudience() !== 'developer') return base
|
||||
const prefix = '(개발자용) '
|
||||
const appBlock = (base.app ?? {}) as Record<string, unknown>
|
||||
const title = appBlock.title
|
||||
return {
|
||||
...base,
|
||||
app: {
|
||||
...appBlock,
|
||||
title: typeof title === 'string' && !title.startsWith(prefix) ? prefix + title : title
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ipcMain.handle('rp:i18n:dict', () => dictForRenderer())
|
||||
|
||||
// ── IPC: 약관 다운로드 ──────────────────────────────
|
||||
// v0.3.4~ : 사이트에서 임의 kind 가 만들어질 수 있으니 5종 화이트리스트 대신
|
||||
|
||||
224
src/installer-uninstall/main.ts
Normal file
224
src/installer-uninstall/main.ts
Normal file
@@ -0,0 +1,224 @@
|
||||
import { app, BrowserWindow, ipcMain, shell } from 'electron'
|
||||
import path from 'node:path'
|
||||
import fs from 'node:fs'
|
||||
import fsp from 'node:fs/promises'
|
||||
import { loadEnv } from '../shared/env.js'
|
||||
import { getAppDataDir, getMcCustomDir } from '../shared/paths.js'
|
||||
import { loadComponentI18n } from '../shared/i18n.js'
|
||||
|
||||
// 음악퀴즈 파일제거 도구. 음악퀴즈 간편설치기 / 리소스팩설치기가 만든 데이터를
|
||||
// 한 번에 정리한다. (설치기 exe 자체는 사용자가 임의 위치에 둔 포터블이라
|
||||
// 위치를 알 수 없어 삭제 대상에서 제외)
|
||||
loadEnv()
|
||||
|
||||
const i18n = loadComponentI18n('installer-uninstall')
|
||||
const t = i18n.t
|
||||
const localeDict = i18n.dict
|
||||
|
||||
let mainWindow: BrowserWindow | null = null
|
||||
|
||||
function createMainWindow(): void {
|
||||
const iconPath = path.join(__dirname, '..', '..', 'build', process.platform === 'win32' ? 'icon.ico' : 'icon.png')
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 720,
|
||||
height: 620,
|
||||
icon: iconPath,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false
|
||||
}
|
||||
})
|
||||
mainWindow.removeMenu()
|
||||
void mainWindow.loadFile(path.join(__dirname, '..', '..', 'installer-uninstall', 'index.html'))
|
||||
}
|
||||
|
||||
function sendLog(line: string): void {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) return
|
||||
const stamped = `[${new Date().toLocaleTimeString('ko-KR', { hour12: false })}] ${line}`
|
||||
mainWindow.webContents.send('log', stamped)
|
||||
}
|
||||
|
||||
/** 마인크래프트 런처 프로필 파일 경로. */
|
||||
function launcherProfilesPath(): string {
|
||||
return path.join(getAppDataDir(), '.minecraft', 'launcher_profiles.json')
|
||||
}
|
||||
|
||||
/** 데스크톱에 설치기가 만든 서버 실행 바로가기 경로. */
|
||||
function serverShortcutPath(): string {
|
||||
return path.join(app.getPath('desktop'), 'MusicQuiz Server.lnk')
|
||||
}
|
||||
|
||||
/** 기본 폴더 이름(.mc_custom) 경로. MC_CUSTOM_DIR 을 바꿔 빌드해도, 예전 기본 폴더가 남아 있을 수 있으므로 함께 지운다. */
|
||||
function defaultCustomDir(): string {
|
||||
return path.join(getAppDataDir(), '.mc_custom')
|
||||
}
|
||||
|
||||
/** 삭제 대상 커스텀 폴더 후보(현재 설정값 + 기본 .mc_custom)를 대소문자 무시로 중복 제거. */
|
||||
function targetCustomDirs(): string[] {
|
||||
const seen = new Set<string>()
|
||||
const out: string[] = []
|
||||
for (const dir of [getMcCustomDir(), defaultCustomDir()]) {
|
||||
const key = path.resolve(dir).toLowerCase()
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key)
|
||||
out.push(dir)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 두 경로가 같은 폴더거나, a 가 b 하위인지(대소문자 무시 — Windows 파일계). */
|
||||
function isSameOrInside(child: string, parent: string): boolean {
|
||||
const c = path.resolve(child).replace(/[\\/]+$/, '').toLowerCase()
|
||||
const p = path.resolve(parent).replace(/[\\/]+$/, '').toLowerCase()
|
||||
return c === p || c.startsWith(p + path.sep.toLowerCase()) || c.startsWith(p + '/')
|
||||
}
|
||||
|
||||
interface UninstallPreview {
|
||||
existingDirs: string[]
|
||||
allTargetDirs: string[]
|
||||
shortcutExists: boolean
|
||||
launcherProfiles: string[]
|
||||
}
|
||||
|
||||
/** 삭제 전 미리보기: 실제로 존재하는 대상만 추려 렌더러에 보여준다. */
|
||||
ipcMain.handle('uninstall:preview', async (): Promise<UninstallPreview> => {
|
||||
const allTargetDirs = targetCustomDirs()
|
||||
const existingDirs = allTargetDirs.filter((d) => fs.existsSync(d))
|
||||
const shortcutExists = fs.existsSync(serverShortcutPath())
|
||||
const launcherProfiles = findMusicQuizProfiles(allTargetDirs)
|
||||
return { existingDirs, allTargetDirs, shortcutExists, launcherProfiles }
|
||||
})
|
||||
|
||||
/** launcher_profiles.json 에서 gameDir 가 커스텀 폴더(또는 그 하위)인 프로필 이름 목록. */
|
||||
function findMusicQuizProfiles(customDirs: string[]): string[] {
|
||||
const file = launcherProfilesPath()
|
||||
if (!fs.existsSync(file)) return []
|
||||
try {
|
||||
const json = JSON.parse(fs.readFileSync(file, 'utf8')) as {
|
||||
profiles?: Record<string, { name?: string; gameDir?: string }>
|
||||
}
|
||||
const profiles = json.profiles ?? {}
|
||||
const names: string[] = []
|
||||
for (const [key, prof] of Object.entries(profiles)) {
|
||||
const gameDir = typeof prof?.gameDir === 'string' ? prof.gameDir : ''
|
||||
if (gameDir && customDirs.some((d) => isSameOrInside(gameDir, d))) {
|
||||
names.push(typeof prof?.name === 'string' && prof.name ? prof.name : key)
|
||||
}
|
||||
}
|
||||
return names
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
interface UninstallResult {
|
||||
removed: string[]
|
||||
profilesRemoved: string[]
|
||||
errors: string[]
|
||||
}
|
||||
|
||||
/** 하나의 파일/폴더를 mode 에 따라 휴지통 이동 또는 완전 삭제. */
|
||||
async function removeOne(target: string, mode: 'trash' | 'permanent'): Promise<void> {
|
||||
if (mode === 'trash') {
|
||||
await shell.trashItem(target)
|
||||
} else {
|
||||
await fsp.rm(target, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** launcher_profiles.json 에서 음악퀴즈 프로필만 제거하고 나머지는 보존. */
|
||||
async function cleanLauncherProfiles(customDirs: string[]): Promise<string[]> {
|
||||
const file = launcherProfilesPath()
|
||||
if (!fs.existsSync(file)) return []
|
||||
let json: { profiles?: Record<string, { name?: string; gameDir?: string }> }
|
||||
try {
|
||||
json = JSON.parse(await fsp.readFile(file, 'utf8'))
|
||||
} catch {
|
||||
sendLog(t('log.launcherParseFail', { path: file }))
|
||||
return []
|
||||
}
|
||||
const profiles = json.profiles ?? {}
|
||||
const removed: string[] = []
|
||||
for (const [key, prof] of Object.entries(profiles)) {
|
||||
const gameDir = typeof prof?.gameDir === 'string' ? prof.gameDir : ''
|
||||
if (gameDir && customDirs.some((d) => isSameOrInside(gameDir, d))) {
|
||||
removed.push(typeof prof?.name === 'string' && prof.name ? prof.name : key)
|
||||
delete profiles[key]
|
||||
}
|
||||
}
|
||||
if (removed.length > 0) {
|
||||
json.profiles = profiles
|
||||
await fsp.writeFile(file, `${JSON.stringify(json, null, 2)}\n`, 'utf8')
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
ipcMain.handle('uninstall:run', async (_event, modeInput: unknown): Promise<UninstallResult> => {
|
||||
const mode: 'trash' | 'permanent' = modeInput === 'permanent' ? 'permanent' : 'trash'
|
||||
const customDirs = targetCustomDirs()
|
||||
const removed: string[] = []
|
||||
const errors: string[] = []
|
||||
|
||||
sendLog(t('log.start', { mode: t(mode === 'trash' ? 'mode.trash' : 'mode.permanent') }))
|
||||
|
||||
// 1) 커스텀 게임/캐시 폴더 통째로(현재 설정값 + 기본 .mc_custom).
|
||||
for (const customDir of customDirs) {
|
||||
if (fs.existsSync(customDir)) {
|
||||
try {
|
||||
await removeOne(customDir, mode)
|
||||
removed.push(customDir)
|
||||
sendLog(t('log.removedDir', { path: customDir }))
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
errors.push(`${customDir}: ${msg}`)
|
||||
sendLog(t('log.removeFail', { path: customDir, message: msg }))
|
||||
}
|
||||
} else {
|
||||
sendLog(t('log.customDirMissing', { path: customDir }))
|
||||
}
|
||||
}
|
||||
|
||||
// 2) 데스크톱 서버 실행 바로가기.
|
||||
const shortcut = serverShortcutPath()
|
||||
if (fs.existsSync(shortcut)) {
|
||||
try {
|
||||
await removeOne(shortcut, mode)
|
||||
removed.push(shortcut)
|
||||
sendLog(t('log.removedShortcut', { path: shortcut }))
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
errors.push(`${shortcut}: ${msg}`)
|
||||
sendLog(t('log.removeFail', { path: shortcut, message: msg }))
|
||||
}
|
||||
}
|
||||
|
||||
// 3) 마인크래프트 런처 프로필에서 음악퀴즈 설정 제거.
|
||||
let profilesRemoved: string[] = []
|
||||
try {
|
||||
profilesRemoved = await cleanLauncherProfiles(customDirs)
|
||||
for (const name of profilesRemoved) sendLog(t('log.removedProfile', { name }))
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
errors.push(`launcher_profiles.json: ${msg}`)
|
||||
sendLog(t('log.launcherWriteFail', { message: msg }))
|
||||
}
|
||||
|
||||
sendLog(t('log.done', { count: removed.length + profilesRemoved.length }))
|
||||
return { removed, profilesRemoved, errors }
|
||||
})
|
||||
|
||||
ipcMain.handle('uninstall:i18n:dict', () => localeDict)
|
||||
ipcMain.handle('uninstall:quit', () => app.quit())
|
||||
|
||||
app.whenReady().then(() => {
|
||||
createMainWindow()
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) createMainWindow()
|
||||
})
|
||||
})
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
app.quit()
|
||||
})
|
||||
43
src/installer-uninstall/preload.ts
Normal file
43
src/installer-uninstall/preload.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
|
||||
interface UninstallPreview {
|
||||
customDir: string
|
||||
customDirExists: boolean
|
||||
shortcutExists: boolean
|
||||
launcherProfiles: string[]
|
||||
}
|
||||
|
||||
interface UninstallResult {
|
||||
removed: string[]
|
||||
profilesRemoved: string[]
|
||||
errors: string[]
|
||||
}
|
||||
|
||||
const api = {
|
||||
/** i18n 사전을 렌더러에 전달. */
|
||||
loadLocale: (): Promise<Record<string, unknown>> => ipcRenderer.invoke('uninstall:i18n:dict'),
|
||||
|
||||
/** 삭제 전, 실제로 존재하는 대상 미리보기. */
|
||||
preview: (): Promise<UninstallPreview> => ipcRenderer.invoke('uninstall:preview'),
|
||||
|
||||
/** 삭제 실행. mode: 'trash'(휴지통) | 'permanent'(완전 삭제). */
|
||||
run: (mode: 'trash' | 'permanent'): Promise<UninstallResult> => ipcRenderer.invoke('uninstall:run', mode),
|
||||
|
||||
/** 프로그램 종료. */
|
||||
quit: (): Promise<void> => ipcRenderer.invoke('uninstall:quit'),
|
||||
|
||||
/** 로그 스트림 구독. */
|
||||
onLog: (handler: (line: string) => void): (() => void) => {
|
||||
const listener = (_event: unknown, line: string) => handler(line)
|
||||
ipcRenderer.on('log', listener)
|
||||
return () => ipcRenderer.removeListener('log', listener)
|
||||
}
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('uninstaller', api)
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
uninstaller: typeof api
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import type {
|
||||
} from './types.js'
|
||||
import type { Manifest, PackDefinition } from '../shared/types.js'
|
||||
import { normalizePackDefinition } from '../shared/store.js'
|
||||
import { getMcCustomDirName, withCustomDirName } from '../shared/paths.js'
|
||||
import { loadEnv, getManifestUrl } from '../shared/env.js'
|
||||
import { loadComponentI18n } from '../shared/i18n.js'
|
||||
import { resolveAudience, isPackVisibleForAudience, type Audience } from '../shared/audience.js'
|
||||
@@ -1044,7 +1045,7 @@ function sleep(ms: number): Promise<void> {
|
||||
ipcMain.handle('client:install', async (_event, payload: ClientInstallPayload) => {
|
||||
const pack = state.packs.get(payload.packKey)
|
||||
if (!pack) throw new Error(t('errors.packNotFound2'))
|
||||
const customRoot = path.join(getAppDataDir(), '.mc_custom')
|
||||
const customRoot = path.join(getAppDataDir(), getMcCustomDirName())
|
||||
await fsp.mkdir(path.join(customRoot, 'mods'), { recursive: true })
|
||||
await fsp.mkdir(path.join(customRoot, 'resourcepacks'), { recursive: true })
|
||||
|
||||
@@ -1587,7 +1588,27 @@ ipcMain.handle('finish:startLauncher', async () => {
|
||||
sendLog(t('log.launcherAllFail'))
|
||||
})
|
||||
|
||||
ipcMain.handle('i18n:dict', () => localeDict)
|
||||
// 개발자용 빌드(musicQuizAudience=developer)면 렌더러에 넘기는 사전의 제목 앞에
|
||||
// "(개발자용) " 을 붙여, 창 제목/헤더에 개발자용임을 표시한다.
|
||||
function dictForRenderer(): Record<string, unknown> {
|
||||
// 커스텀 폴더명을 UI 문구에 반영.
|
||||
const base = withCustomDirName(localeDict)
|
||||
if (getAudience() !== 'developer') return base
|
||||
const prefix = '(개발자용) '
|
||||
const appBlock = (base.app ?? {}) as Record<string, unknown>
|
||||
const withPrefix = (v: unknown): unknown =>
|
||||
typeof v === 'string' && !v.startsWith(prefix) ? prefix + v : v
|
||||
return {
|
||||
...base,
|
||||
app: {
|
||||
...appBlock,
|
||||
browserTitle: withPrefix(appBlock.browserTitle),
|
||||
headerTitle: withPrefix(appBlock.headerTitle)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ipcMain.handle('i18n:dict', () => dictForRenderer())
|
||||
|
||||
ipcMain.handle('app:quit', () => {
|
||||
// 모든 창을 닫고 앱 종료. macOS에서도 종료(설치기는 한 번 쓰고 끝이니 잔류시키지 않음).
|
||||
|
||||
@@ -73,7 +73,9 @@ export function createI18n(filePath: string): I18n {
|
||||
* 1. 패키징된 Electron 앱이면 `process.resourcesPath/locales/<component>/ko-kr.json`
|
||||
* 2. `<프로젝트 루트>/locales/<component>/ko-kr.json`
|
||||
*/
|
||||
export function loadComponentI18n(component: 'server' | 'installer' | 'installer-rp' | 'installer-pf'): I18n {
|
||||
export function loadComponentI18n(
|
||||
component: 'server' | 'installer' | 'installer-rp' | 'installer-pf' | 'installer-uninstall'
|
||||
): I18n {
|
||||
// 컴파일된 dist/shared/i18n.js 기준으로 프로젝트 루트는 2단계 위.
|
||||
const projectRoot = path.resolve(__dirname, '..', '..')
|
||||
|
||||
|
||||
@@ -39,9 +39,43 @@ export function getAppDataDir(): string {
|
||||
return process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config')
|
||||
}
|
||||
|
||||
/** %appdata%/.mc_custom — 음악퀴즈 관련 외부 도구/캐시 보관 디렉터리. */
|
||||
/**
|
||||
* 커스텀 게임 디렉터리의 폴더 이름. 기본은 `.mc_custom` 이지만 환경변수
|
||||
* `MC_CUSTOM_DIR` 로 다른 이름을 지정할 수 있다(.env / .env.build 로 주입).
|
||||
* 경로 구분자·상위경로 이스케이프(`/`, `\`, `..`)는 제거해 항상 %appdata%
|
||||
* 바로 아래 단일 폴더로 강제한다.
|
||||
*/
|
||||
export function getMcCustomDirName(): string {
|
||||
const raw = (process.env.MC_CUSTOM_DIR ?? '').trim()
|
||||
if (!raw) return '.mc_custom'
|
||||
const sanitized = raw.replace(/[\\/]+/g, '').replace(/\.\.+/g, '.')
|
||||
return sanitized || '.mc_custom'
|
||||
}
|
||||
|
||||
/** %appdata%/<MC_CUSTOM_DIR|.mc_custom> — 음악퀴즈 관련 게임 폴더/외부 도구/캐시 보관 디렉터리. */
|
||||
export function getMcCustomDir(): string {
|
||||
return path.join(getAppDataDir(), '.mc_custom')
|
||||
return path.join(getAppDataDir(), getMcCustomDirName())
|
||||
}
|
||||
|
||||
/**
|
||||
* 사전/문자열 구조 안의 리터럴 `.mc_custom` 을 실제 폴더 이름으로 치환한 깊은
|
||||
* 복사본을 돌려준다. 기본값(`.mc_custom`)이면 원본을 그대로 반환한다. 렌더러로
|
||||
* 넘기는 i18n 사전에 적용해 UI 안내 문구가 실제 폴더 이름과 어긋나지 않게 한다.
|
||||
*/
|
||||
export function withCustomDirName<T>(value: T): T {
|
||||
const name = getMcCustomDirName()
|
||||
if (name === '.mc_custom') return value
|
||||
const replace = (v: unknown): unknown => {
|
||||
if (typeof v === 'string') return v.split('.mc_custom').join(name)
|
||||
if (Array.isArray(v)) return v.map(replace)
|
||||
if (v && typeof v === 'object') {
|
||||
const out: Record<string, unknown> = {}
|
||||
for (const [k, val] of Object.entries(v as Record<string, unknown>)) out[k] = replace(val)
|
||||
return out
|
||||
}
|
||||
return v
|
||||
}
|
||||
return replace(value) as T
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user