rmdir method

Stream<Es> rmdir({
  1. bool force = false,
  2. bool keeptop = false,
})

remove directory if empty

  • force: force remove directory if not empty.
  • keeptop: keep top (source) directory.
final source = '~/Downloads/temp/ft/';
final action = BasicPathAction(source);

action.rmdir();
// action.rmdir(force:true, keeptop:true); // no remove ~/Downloads/temp/ft/

Implementation

Stream<Es> rmdir({bool force = false, bool keeptop = false}) {
  final action = PathAction.rmdir.name, chk = 'validator';
  argErr ??= validator();
  if (argErr!.isNotEmpty) throw ArgumentError.value(argErr, action, chk);

  final fields = fieldsFromOptions(fmtFields);
  final fseType = FileSystemEntityType.directory;

  final stream = scEntity.stream;
  final dStream =
      stream.where((event) => event.fs.type == fseType).asBroadcastStream();
  dStream.toList().then(
    (events) {
      if (type == FileSystemEntityType.directory) {
        final source = Directory(path);
        final es = Es((source, source.statSync(), 'source'));
        events.add(es);
      }
      events.sort((a, b) => b.fse.path.length.compareTo(a.fse.path.length));
      if (events.isNotEmpty && keeptop) events.removeLast(); // keep top?
      bool errexit = false;
      for (var event in events) {
        if (errexit) break;
        final (entity, stat, extra) = event.asRecord;
        // print('---${entity.path}');
        final dir = Directory(entity.path);
        final exist = dir.existsSync();
        if (exist) {
          var ok = false;

          try {
            if (force) {
              dir.deleteSync(recursive: true);
            } else {
              if (isDirEmpty(dir, isDirExist: exist)) dir.deleteSync();
            }
            ok = true;
          } on FileSystemException catch (e, s) {
            exitCode = ExitCodeExt.error.code;
            if (cancelOnError) errexit = true;
            logger
              ..stderr('e, $action, delete, $e')
              ..stderr((kIsDebug ? '' : s.toString()));
          }
          final line =
              Formatter(entity, stat, extra, action, shows: fields, ok: ok);
          logger.stdout(line.toString());
        }
      } // end_for
    },
  );

  return dStream;
}