All files / src/cli/install backup.ts

100% Statements 31/31
83.33% Branches 10/12
100% Functions 3/3
100% Lines 31/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84          3x 3x           3x 4x 4x 4x 4x           3x 4x     4x 1x           3x     3x   1x 1x   1x 1x   2x       3x   2x         1x                   3x 3x 3x 1x       2x 2x 1x     2x 1x   1x      
/**
 * Backup utility for MCP client configurations
 * Creates timestamped backups before modifying config files
 */
 
import { existsSync, copyFileSync, mkdirSync } from "fs";
import { dirname, basename, join } from "path";
import { BackupOptions, BackupResult } from "./types";
 
/**
 * Generate backup filename with timestamp
 */
export function generateBackupFilename(originalPath: string): string {
  const dir = dirname(originalPath);
  const name = basename(originalPath);
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
  return join(dir, `${name}.backup-${timestamp}`);
}
 
/**
 * Create a backup of a config file
 */
export function createBackup(options: BackupOptions): BackupResult {
  const { configPath, backupDir } = options;
 
  // Check if source file exists
  if (!existsSync(configPath)) {
    return {
      created: false,
      error: "Config file does not exist, no backup needed",
    };
  }
 
  try {
    // Determine backup path
    let backupPath: string;
    if (backupDir) {
      // Ensure backup directory exists
      Eif (!existsSync(backupDir)) {
        mkdirSync(backupDir, { recursive: true });
      }
      const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
      backupPath = join(backupDir, `${basename(configPath)}.backup-${timestamp}`);
    } else {
      backupPath = generateBackupFilename(configPath);
    }
 
    // Copy file to backup location
    copyFileSync(configPath, backupPath);
 
    return {
      created: true,
      backupPath,
    };
  } catch (error) {
    return {
      created: false,
      error: error instanceof Error ? error.message : String(error),
    };
  }
}
 
/**
 * Restore a backup file
 */
export function restoreBackup(backupPath: string, targetPath: string): boolean {
  try {
    if (!existsSync(backupPath)) {
      return false;
    }
 
    // Ensure target directory exists
    const targetDir = dirname(targetPath);
    if (!existsSync(targetDir)) {
      mkdirSync(targetDir, { recursive: true });
    }
 
    copyFileSync(backupPath, targetPath);
    return true;
  } catch {
    return false;
  }
}