restoreFile function

Future<void> restoreFile(
  1. String pathToFile, {
  2. bool ignoreMissing = false,
})

Designed to work with backupFile to restore a file from backup. The existing file is deleted and restored from the .bak/

Consider using withFileProtection for a more robust solution.

When the last .bak file is restored, the .bak directory will be deleted. If you don't restore all files (your app crashes) then a .bak directory and files may be left hanging around and you may need to manually restore these files. If the backup file doesn't exists this function throws a RestoreFileException unless you pass the ignoreMissing flag.

Implementation

Future<void> restoreFile(String pathToFile,
    {bool ignoreMissing = false}) async {
  final pathToBackupFile = _backupFilePath(pathToFile);

  if (exists(pathToBackupFile)) {
    if (exists(pathToFile)) {
      await delete(pathToFile);
    }

    await move(pathToBackupFile, pathToFile);

    if (await isEmpty(dirname(pathToBackupFile))) {
      await deleteDir(dirname(pathToBackupFile));
    }
    verbose(() => 'Restoring  ${truepath(pathToFile)}');
  } else {
    if (ignoreMissing) {
      verbose(
        () => 'Missing restoreFile ${truepath(pathToBackupFile)} ignored.',
      );
    } else {
      throw RestoreFileException(
        'The backup file ${truepath(pathToBackupFile)} is missing',
      );
    }
  }
}