getNewFileWithIdenticalBasename method

File getNewFileWithIdenticalBasename({
  1. int maxTries = 999,
  2. Context? pathContext,
  3. FileFactory factory = File.new,
})

Returns a new file with the same basename as this in parent.

If parent already contains a file with the same basename as this, then a counter will be appended to the new Files' basename, in the form basename (counter).extension.

Example: dart

...
final file = File("script.dart");
final newFile = file.getNewFileWithIdenticalBasename();
print(newFile.name); // -> prints "script (1).dart"
...

Implementation

File getNewFileWithIdenticalBasename({
  int maxTries = 999,
  lib_path.Context? pathContext,
  FileFactory factory = File.new,
}) {
  // If this file does not already exist, return it
  if (!existsSync()) return this;

  pathContext ??= lib_path.context;

  // Match:
  // filename (123).ext
  // filename (123)
  //
  // But do not match:
  // filename(123).ext
  // filename ()
  // filename ().ext
  final indexFileRegex = RegExp(
    "(?<basename>.*)"
    r" \((?<index>\d+)\)"
    r"(\.(?<extension>.+))?",
  );

  final thisMatch = indexFileRegex.firstMatch(
    getName(pathContext: pathContext),
  );

  int index;
  final String basename;
  final String ext;
  if (null == thisMatch) {
    index = 0;
    basename = getNameWithoutExtension(pathContext: pathContext);
    ext = extension;
  } else {
    index = thisMatch.namedGroup("index")!.toInt();
    basename = thisMatch.namedGroup("basename")!;
    final extension = thisMatch.namedGroup("extension");
    ext = null == extension ? "" : ".$extension";
  }

  int loopCount;
  File newFile;

  for (loopCount = 0; loopCount < maxTries; loopCount++) {
    index++;
    newFile = factory(
      lib_path.join(
        getDirname(pathContext: pathContext),
        "$basename ($index)$ext",
      ),
    );
    if (!newFile.existsSync()) return newFile;
  }

  throw OutOfTriesException(
    tries: loopCount,
    message: "Could not create a new file with the same name "
        "as '$getName' in the directory '${parent.path}'",
  );
}