mirror method

Stream<Es> mirror(
  1. Directory toDir, [
  2. bool useRelPath = true
])

incrementally mirror source path to target directory.

  • toDir: target directory.
  • useRelPath: use relative path If true else use deroot absolute path.

Example:
source: ~/tmp.txt, target: ~/Downloads/temp/;
Result:
~/Downloads/temp/tmp.txt if true else ~/Downloads/temp/Users/kaguya/tmp.txt

final excludes = [r'.**'];
final source = '.';
final action = BasicPathAction(source, excludes: excludes);

final toDir = Direcotry(expandTilde('~/Downloads/ft/'))..createSync(recursive: true);
action.mirror(toDir);

Implementation

Stream<Es> mirror(Directory toDir, [bool useRelPath = true]) {
  final action = PathAction.mirror.name, chk = 'validator';
  argErr ??= validator();
  if (argErr!.isNotEmpty) throw ArgumentError.value(argErr, action, chk);
  final srcPath = (type == FileSystemEntityType.directory)
      ? Directory(path).absolute.path
      : path;

  final fields = fieldsFromOptions(fmtFields);
  final fseType = FileSystemEntityType.file;
  final stream = scEntity.stream;
  final fStream =
      stream.where((event) => event.fs.type == fseType).asBroadcastStream();

  final dst = toDir.path;
  late StreamSubscription subs;
  subs = fStream.listen(
    (event) {
      final (entity, stat, extra) = event.asRecord;
      final oldPath = entity.isAbsolute ? entity.path : entity.absolute.path;
      // keep the original, useRelPath
      var newPath = p.join(dst, pathderoot(oldPath)); // default false
      if (useRelPath) {
        if (type == FileSystemEntityType.directory) {
          newPath = p.join(dst, oldPath.substring(srcPath.length + 1));
        } else {
          newPath = p.join(dst, p.basename(oldPath));
        }
      }
      var ok = false;
      var file = File(entity.path);
      var newFile = File(newPath);
      try {
        file = fileMirror(file, newFile);
        ok = true;
      } catch (e, s) {
        logger.stderr('e, $action, data, filesync, $oldPath -> $newPath');
        scEntity.addError(e, s);
      }

      final line = Formatter(file, ok ? file.statSync() : stat, extra, action,
          shows: fields, ok: ok);
      logger.stdout(line.toString());
    },
    cancelOnError: cancelOnError,
    onDone: () => logger.trace('d, $action, done.'),
    onError: (e, s) {
      if (cancelOnError) {
        exitCode = ExitCodeExt.error.code;
        subs.cancel();
      }

      logger
        ..trace('d, $action, cancelOnError:$cancelOnError')
        ..stderr('e, $action, error. $e')
        ..stderr(kIsDebug ? '$s' : '');
    }, // onError
  );

  return fStream;
}