Swader Swader - 4 months ago 28
Dart Question

How do I recognize a symlink in Dart when dealing with the Directory class?

When I instantiate a Directory in Dart, and that file exists, how can I check whether the Directory is a real folder, or just a symlink?


The way you can recognize a symlink is if the path differs from the full path. Directory doesn't have fullPath() or fullPathSync(), but File.fullPathSync() works on directories. So you can do this:

bool maybeIsSymlink(String path) {
  var fullPath = new File(path).fullPathSync();
  return path != fullPath;

However this only works correctly when path is absolute, and none of its ancestors are symlinks. To work around that you can get the full path of the directory's parent, append the directory name and compare that:

bool isSymlink(String pathString) {
  var path = new Path(path);

  var parentPath = path.directoryPath;
  var fullParentPath = new File.fromPath(parentPath).fullPathSync();
  var expectedPath = new Path(fullParentPath).append(path.filename).toString();

  var fullPath = new File.fromPath(path).fullPathSync();

  return fullPath != expectedPath;

Note that I have not tested this, but I've dealt with symlinks a lot in Dart, and this should work. If pathString ends in '/' you'll have to remove it. I usually end up getting paths from a directory listing, so I track the expected path as I recurse down the directory structure.

You can see a special listDirectory() implementation that detects symlinks and sends Symlink instances to the stream along with Files and Directorys in a branch in buildtool: https://github.com/dart-lang/buildtool/blob/m4/lib/src/util/io.dart