/ utils / iTermBackup.ts
iTermBackup.ts
 1  import { copyFile, stat } from 'fs/promises'
 2  import { homedir } from 'os'
 3  import { join } from 'path'
 4  import { getGlobalConfig, saveGlobalConfig } from './config.js'
 5  import { logError } from './log.js'
 6  
 7  export function markITerm2SetupComplete(): void {
 8    saveGlobalConfig(current => ({
 9      ...current,
10      iterm2SetupInProgress: false,
11    }))
12  }
13  
14  function getIterm2RecoveryInfo(): {
15    inProgress: boolean
16    backupPath: string | null
17  } {
18    const config = getGlobalConfig()
19    return {
20      inProgress: config.iterm2SetupInProgress ?? false,
21      backupPath: config.iterm2BackupPath || null,
22    }
23  }
24  
25  function getITerm2PlistPath(): string {
26    return join(
27      homedir(),
28      'Library',
29      'Preferences',
30      'com.googlecode.iterm2.plist',
31    )
32  }
33  
34  type RestoreResult =
35    | {
36        status: 'restored' | 'no_backup'
37      }
38    | {
39        status: 'failed'
40        backupPath: string
41      }
42  
43  export async function checkAndRestoreITerm2Backup(): Promise<RestoreResult> {
44    const { inProgress, backupPath } = getIterm2RecoveryInfo()
45    if (!inProgress) {
46      return { status: 'no_backup' }
47    }
48  
49    if (!backupPath) {
50      markITerm2SetupComplete()
51      return { status: 'no_backup' }
52    }
53  
54    try {
55      await stat(backupPath)
56    } catch {
57      markITerm2SetupComplete()
58      return { status: 'no_backup' }
59    }
60  
61    try {
62      await copyFile(backupPath, getITerm2PlistPath())
63  
64      markITerm2SetupComplete()
65      return { status: 'restored' }
66    } catch (restoreError) {
67      logError(
68        new Error(`Failed to restore iTerm2 settings with: ${restoreError}`),
69      )
70      markITerm2SetupComplete()
71      return { status: 'failed', backupPath }
72    }
73  }