views:

57

answers:

1

On the surface, this is pretty simple, and I could implement it myself easily. Just successively call dirname() to go up each level in the file's path and check each one to see if it's the directory we're checking for.

But symlinks throw the whole thing into chaos. Any directory along the path of either the file or directory being checked could be a symlink, and any symlink could have an arbitrary chain of symlinks to other symlinks. At this point my brain melts and I'm not sure what to do. I've tried writing the code to handle these special cases, but it soon gets too complicated and I assume I'm doing it wrong. Is there a reasonably elegant way to do this?

I'm using Python, so any mention of a library that does this would be cool. Otherwise, this is a pretty language-neutral problem.

+4  A: 

Use os.path.realpath and os.path.commonprefix:

os.path.commonprefix(['/the/dir/', os.path.realpath(filename)])

os.path.realpath will expand any symlinks as well as .. in the filename. os.path.commonprefix is a bit fickle -- it doesn't really test for paths, just plain string prefixes, so you should make sure your directory ends in a directory separator. If you don't, it will claim `/the/dirtwo/filename' is also in '/the/dir'

Thomas Wouters
Maybe the edge cases are all in my head. I could swear that symlinks make this approach fail in some cases, but I can't come up with examples to prove it. I feel like I'm fighting a ghost...
mackstann
Since every hierarchical file system I can think of requires a single, unique, canonical, real named directories, this actually works. Although it may be counter-intuitive that you could get from here to there, for directories the "one real parent" has to be true or bad things ensue.
msw
Well, it's good news to hear this. Now I just need to check four cases (realpath and non-realpath for both dir and file). Thanks!
mackstann