createSnapshot method

Future<String> createSnapshot()

Copies every .dart and pubspec.yaml file under projectPath into a timestamped snapshot directory and writes a manifest for rollback. Returns the path of the created snapshot directory.

Implementation

Future<String> createSnapshot() async {
  final snapshotsRoot = Directory('$projectPath/$_snapshotDir');
  if (!snapshotsRoot.existsSync()) {
    snapshotsRoot.createSync(recursive: true);
  }

  final timestamp = DateTime.now().millisecondsSinceEpoch;
  final backupDir = Directory('${snapshotsRoot.path}/$timestamp');
  backupDir.createSync();

  print('🛡️  Creating project snapshot...');

  final files = _collectFiles(Directory(projectPath));
  final manifest = <String, String>{};

  for (final file in files) {
    final relative = _relativePath(file.path);
    final dest = File('${backupDir.path}/$relative');
    dest.parent.createSync(recursive: true);
    file.copySync(dest.path);
    manifest[relative] = dest.path;
  }

  final manifestFile = File('${backupDir.path}/$_manifestName');
  manifestFile.writeAsStringSync(
    JsonEncoder.withIndent('  ').convert({
      'timestamp': DateTime.fromMillisecondsSinceEpoch(
        timestamp,
      ).toIso8601String(),
      'projectPath': projectPath,
      'fileCount': files.length,
      'files': manifest,
    }),
  );

  print('✅ Snapshot created: ${files.length} files → ${backupDir.path}');
  return backupDir.path;
}