iTermBackup.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. export function markITerm2SetupComplete(): void {
  7. saveGlobalConfig(current => ({
  8. ...current,
  9. iterm2SetupInProgress: false,
  10. }))
  11. }
  12. function getIterm2RecoveryInfo(): {
  13. inProgress: boolean
  14. backupPath: string | null
  15. } {
  16. const config = getGlobalConfig()
  17. return {
  18. inProgress: config.iterm2SetupInProgress ?? false,
  19. backupPath: config.iterm2BackupPath || null,
  20. }
  21. }
  22. function getITerm2PlistPath(): string {
  23. return join(
  24. homedir(),
  25. 'Library',
  26. 'Preferences',
  27. 'com.googlecode.iterm2.plist',
  28. )
  29. }
  30. type RestoreResult =
  31. | {
  32. status: 'restored' | 'no_backup'
  33. }
  34. | {
  35. status: 'failed'
  36. backupPath: string
  37. }
  38. export async function checkAndRestoreITerm2Backup(): Promise<RestoreResult> {
  39. const { inProgress, backupPath } = getIterm2RecoveryInfo()
  40. if (!inProgress) {
  41. return { status: 'no_backup' }
  42. }
  43. if (!backupPath) {
  44. markITerm2SetupComplete()
  45. return { status: 'no_backup' }
  46. }
  47. try {
  48. await stat(backupPath)
  49. } catch {
  50. markITerm2SetupComplete()
  51. return { status: 'no_backup' }
  52. }
  53. try {
  54. await copyFile(backupPath, getITerm2PlistPath())
  55. markITerm2SetupComplete()
  56. return { status: 'restored' }
  57. } catch (restoreError) {
  58. logError(
  59. new Error(`Failed to restore iTerm2 settings with: ${restoreError}`),
  60. )
  61. markITerm2SetupComplete()
  62. return { status: 'failed', backupPath }
  63. }
  64. }