Skip to content

copyDirectory in flutter_tools always follows links #144032

@vashworth

Description

@vashworth

/// Creates `destDir` if needed, then recursively copies `srcDir` to
/// `destDir`, invoking [onFileCopied], if specified, for each
/// source/destination file pair.
///
/// Skips files if [shouldCopyFile] returns `false`.
/// Does not recurse over directories if [shouldCopyDirectory] returns `false`.
void copyDirectory(
Directory srcDir,
Directory destDir, {
bool Function(File srcFile, File destFile)? shouldCopyFile,
bool Function(Directory)? shouldCopyDirectory,
void Function(File srcFile, File destFile)? onFileCopied,
}) {
if (!srcDir.existsSync()) {
throw Exception('Source directory "${srcDir.path}" does not exist, nothing to copy');
}
if (!destDir.existsSync()) {
destDir.createSync(recursive: true);
}
for (final FileSystemEntity entity in srcDir.listSync()) {
final String newPath = destDir.fileSystem.path.join(destDir.path, entity.basename);
if (entity is Link) {
final Link newLink = destDir.fileSystem.link(newPath);
newLink.createSync(entity.targetSync());
} else if (entity is File) {
final File newFile = destDir.fileSystem.file(newPath);
if (shouldCopyFile != null && !shouldCopyFile(entity, newFile)) {
continue;
}
newFile.writeAsBytesSync(entity.readAsBytesSync());
onFileCopied?.call(entity, newFile);
} else if (entity is Directory) {
if (shouldCopyDirectory != null && !shouldCopyDirectory(entity)) {
continue;
}
copyDirectory(
entity,
destDir.fileSystem.directory(newPath),
shouldCopyFile: shouldCopyFile,
onFileCopied: onFileCopied,
);
} else {
throw Exception('${entity.path} is neither File nor Directory, was ${entity.runtimeType}');
}
}
}

srcDir.listSync() will always return entities of File/Directory and never Link since followLinks is never false.

In the description of listSync, it read

If [followLinks] is false, then any symbolic links found are reported as [Link] objects, rather than as directories or files, and are not recursed into.

If [followLinks] is true, then working links are reported as directories or files, depending on what they point to, and links to directories are recursed into if [recursive] is true.

Metadata

Metadata

Assignees

Labels

team-toolOwned by Flutter Tool team

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions