Repository navigation
Description
os.File provides two ways to read a directory: Readdirnames returns a list of the names of the directory entries, and Readdir returns the names along with stat information.
On Plan 9 and Windows, Readdir can be implemented with only a directory read - the directory read operation provides the full stat information.
But many Go users use Unix systems.
On most Unix systems, the directory read does not provide full stat information. So the implementation of Readdir reads the names from the directory and then calls Lstat for each file. This is fairly expensive.
Much of the time, such as in the implementation of file system walking, the only information the caller of Readdir really needs is the name and whether the name denotes a directory. On most Unix systems, that single bit of information—is this name a directory?—is available from the plain directory read, without an additional stat. If the caller is only using that bit, the extra Lstat calls are unnecessary and slow. (Goimports, for example, has its own directory walker to avoid this cost.) In fact, a survey of existing Go code found that only about 10% of uses of ReadDir actually need more than names and is-directory bits.
It appears that a third way to read directories should be added, to let all this code be written more efficiently. Expanding on a suggestion by @mpx, I propose to add:
// ReadDir reads the contents of the directory associated with the file f
// and returns a slice of DirEntry values in directory order.
// Subsequent calls on the same file will yield later DirEntry records in the directory.
//
// If n > 0, ReadDir returns at most n DirEntry records.
// In this case, if ReadDir returns an empty slice, it will return an error explaining why.
// At the end of a directory, the error is io.EOF.
//
// If n <= 0, ReadDir returns all the DirEntry records remaining in the directory.
// When it succeeds, it returns a nil error (not io.EOF).
func (f *File) ReadDir(n int) ([]DirEntry, error)
// A DirEntry is an entry read from a directory (using the ReadDir method).
type DirEntry interface {
// Name returns the name of the file (or subdirectory) described by the entry.
// This name is only the final element of the path, not the entire path.
// For example, Name would return "hello.go" not "/home/gopher/hello.go".
Name() string
// IsDir reports whether the entry describes a subdirectory.
IsDir() bool
// Info returns the FileInfo for the file or subdirectory described by the entry.
// The returned FileInfo may be from the time of the original directory read
// or from the time of the call to Info. If the file has been removed or renamed
// since the directory read, Info may return an error satisfying errors.Is(err, ErrNotExist).
// If the entry denotes a symbolic link, Info reports the information about the link itself,
// not the link's target.
Info() (FileInfo, error)
}
The FS proposal would then adopt this ReadDir and ignore Readdir entirely.
In #41188 I wrote:
Various people have proposed adding a third directory reading option of one form or another, to get names and IsDir bits. This would certainly address the slow directory walk issue on Unix systems, but it seems like overfitting to Unix.
I still believe that, but the survey convinced me that nearly all existing Readdir uses fall into this category, so it's not quite so bad to provide an optimized path for Unix systems. The DirEntry.Info method specification above allows both the eager info loading of Plan 9/Windows and the lazy loading needed on Unix. In contrast to #41188, the laziness is explicitly allowed from the beginning, and failures of the lazy loading can be reported in the error result.
Thoughts?
Update: A few clarifications to common questions:
- Info returns the result of Lstat on systems where symbolic links happen.
- On file systems that do not return even IsDir bits in the directory listing, ReadDir will have to do the full lstat loop that Readdir does today. That seems OK: slow file systems are slow.
- IsDir returns false for symlinks to directories, since Lstat's FileInfo's IsDir does too.
- ReadDir vs Readdir corrects the spelling of the name but does not differ only in case. It also differs in signature, so mistakes will not silently misbehave; they will loudly miscompile. In any event, the motivation here is to set a good, short name for the FS proposal, and for a method many people will need to implement, ReadDir is better than the longer ReadDirEntries.
Update 2: A few changes were made along the way to acceptnce. See #41467 (comment) for the final version.
Activity
benhoyt commentedon Sep 18, 2020
I like this a lot (it's similar to Python's
os.scandir, but simpler). A few questions:d_typefield can beDT_UNKNOWNif the file system doesn't support it. Docs says "Currently, only some file systems (among them: Btrfs, ext2, ext3, and ext4) have full support for returning the file type in d_type. All applications must properly handle a return of DT_UNKNOWN." So we need to support this case. EitherReadDircould call Lstat at the time of the read if it gets anyd_type==DT_UNKNOWNvalues, or we need to change the signature toIsDir() (bool, error)to reflect the fact that it too may call Lstat realtime -- I vote keeping the signature as Russ has it and having ReadDir call Lstat in that case (should be rare, so falling back to slower but correct seems fine).ReadDirseems to similar to the existingReaddir-- differentiating just on the case of one letter seems like asking for trouble. What aboutReadEntries?IsDirandInforeturn info about the entry itself, without following symlinks? In other words, it's like Lstat and not Stat? Does this need mentioning explicitly? Or maybe it's clear from "the entry"?IsDirreturn in the case of a symbolic link (to a directory)? Presumably false given the above.mpx commentedon Sep 18, 2020
This looks great.
I felt that there may be some advantage to making
DirEntrya subset ofFileInfointerface, hence I didn't include theInfomethod and started with the smaller interface. However, I can't convince myself there there is any tangible disadvantage to addingInfo. There certainly needs to be a way of "upgrading" aDirEntryinto aFileInfo.One comment from #41188 regarding this suggestion was that
d_typeis not always available forIsDir. In those cases extra work needs to be done to provide that information.NameandIsDirare the minimum required to support implementing walk. Upgrading toFileInfowould be free on those systems, so it's no more expensive to do it this way.It might be good to rename
ReadDirdue to the unfortunate similarity withReaddir. I understand it works in practice, but it might cause some confusion ("ReadDir" with the capital "D" or lowercase "d"?).From my point of view, I think the
ReadDireffectively replaces the need forReaddirandReaddirnames. If it existed from Go1 I wouldn't see the need for adding the other calls. Obviously the existing methods shouldn't be removed, but they may not be needed inio/fs.I have a number tools that will benefit significantly from this proposal.
mpx commentedon Sep 18, 2020
@benhoyt
IsDirshould returnbool. As I mentioned on #41188 there is an advantage to providing interfaces that are guaranteed to work. Systems that cannot provide "IsDir" will need to do extra work up front. However, it will be effectively free for them to upgrade to FileInfo, so it should be no slower to "walk" a tree.Good point regarding IsDir and symlinks. I think it needs to return false. Following a symlink will necessarily require another Stat to determine whether the target is a directory. This is probably worth documenting.
richardwilkes commentedon Sep 18, 2020
Regardless of which way this ends up working (Lstat vs Stat), it should be mentioned explicitly in the comments/docs for the method, as what is "obvious" to one person will not be to another.
diamondburned commentedon Sep 18, 2020
I personally don't see a point in this. Implementations could simply just return an internal
FileInfoor itself whenInfo()is called.rsc commentedon Sep 18, 2020
@benhoyt, added answers above but (1) I agree with you; (2) ReadEntries is the wrong long-term name, and in the long term Readdir will just be deprecated (but not removed) and fade away; (3) yes, Lstat; (4) yes, false.
networkimprov commentedon Sep 18, 2020
Russ, glad to see a new API proposed, thanks. Some Q's
This entails a per-item
lstat()when the type is absent in native dirent. You don't want that if you don't need to checkDirEntry.IsDir()for every result. Can it be optional?Does
DirEntry.Info()cache its result if it had tolstat(), or ifReadDir()had to?Could we flush the
FileInfocache, so a subsequent.Info()reloads it?Wouldn't the different behavior of
DirEntry.Info()on unix & Windows cause trouble in cross-platform apps? Such apps would callos.File.Readdir()when they needFileInfofor all results, andxfs.File.ReadDir()otherwise. The mix of those two could be confusing.There is no way to get the Windows fileId (analagous to inode) via
FileInfo. Could a way be added toDirEntry?Unix dirents include the inode -- needed for tree replication. Could
DirEntryprovide that?For the latter two, I think you'd return a
type FileId interface { ... }EDIT: Background... I'm building a desktop app for Windows, MacOS, and Linux -- and a server app for Linux -- that make heavy use of the filesystem. Go has thrown me a fair number of curve balls, and I expect more :-/
diamondburned commentedon Sep 18, 2020
As far as I know, no, this cannot be optional. Perhaps it could be if a more optimized
Readdirnamescould be made, but personally, I think that should stay there.If we're going with my idea of returning an internal
FileInfo, then I can see the behavior differing a little bit: on Windows, aFileInfocan be returned, but in Linux, a newFileInfowould be obtained on everyInfo()call.In my honest opinion, this behavior is fine. In fact, it would be preferable if
FileInfoof the Linux implementation is cached. The reason being that if the caller wants the newest information, then they should callLstatorStatexplicitly.Worst case scenario, the
DirEntinterface could perhaps be overloaded to accommodate for the above flaws, but I feel like that would be overdesigning and overcomplicating it.mpx commentedon Sep 18, 2020
Any caller needing to guarantee a fresh stat should call
Lstat/Statthemselves.I've wanted to retrieve unique file identifiers for both Linux (inode) and Windows (fileId) to improve performance for several applications, so I'd appreciate a solution too. However, I think
DirEntryshould be kept simple. Most callers don't need a unique identifier, and it would unnecessarily complicate many implementations which don't use/need it. I think this could be solved via a separate proposal after this "DirEntry" proposal is settled. Eg, perhaps it could be a provided via an optional interfaceFileID() uint64.rsc commentedon Sep 18, 2020
I agree with what @diamondburned and @mpx said but just to reply directly as well.
In practice, when is that type absent? I'm not too worried if, say, VFAT file systems are slower to access.
The doc says the Info is either from the time of the ReadDir or the time of the Info call. So a stat during ReadDir can be cached, but not a stat during an earlier Info.
Adding cache state & manipulation to the API is needlessly complex. Lstat still exists.
There is no magic wand here. Unix and Windows are different. They will always be different.
The path separator alone causes trouble in cross-platform apps. The answer is to use APIs like filepath.Clean and filepath.Join as appropriate. If you don't do that, you have trouble. It's not our job to make trouble impossible, only avoidable.
The docs on ReadDir are very clear about what you can rely on and what you cannot. If you rely on more than that, again, you will have trouble, same as hard-coding use of / or \ in your program.
Pretty much all apps should probably move to calling ReadDir or, if it matters, Lstat/Stat directly.
What's confusing is having two different APIs, but we clearly need a new one, and can't remove the old one. So be it.
[Note that Go would spell it FileID not FileId (the file does not have a mind).]
The concept seems too special-purpose for a general interface, and a bit difficult to use correctly.
The problem is that Windows file IDs and Unix inode numbers are not really identifiers: they only identify a file within a particular file system. Another file system can have a file with the same file ID/inode number. So to use them properly you need to combine them with some kind of identifier for the file system itself (like fsid_t or dev_t on Unix). It gets messy fast.
Also, if you are writing "tree replication", then you are already stat'ing all the files to get the other metadata, and you're already writing very OS-specific code to preserve all the OS-specific attributes. That same code can easily grab the info you need as far as inode number and file system identifier.
It's not our job to union together all the possible APIs on all the possible systems. Our job is to find a simple API that is enough for the vast majority of Go programs, with an option for the rest to get at what they need (FileInfo.Sys in this case).
ianlancetaylor commentedon Sep 18, 2020
What about
Readdirnames?If we expect all users of
Readdirnamesto switch toReadDirover time, then I'm not quite convinced thatIsDirshould not return(bool, error). Neither AIX nor Solaris record the type of the file in the directory entry. Even on GNU/Linux there are various obscure file systems that do not record the dirent type.The downside of
IsDirreturning(bool, error)seems fairly low to me.networkimprov commentedon Sep 18, 2020
Ian, wouldn't the error you're suggesting be returned by
ReadDir()when it trieslstat()after seeing entries without types?Or are you suggesting that
ReadDir()should neverlstat()?ianlancetaylor commentedon Sep 18, 2020
I'm suggesting that
ReadDirshould never calllstat, just as the currentReaddirnamesnever callslstat.101 remaining items
rsc commentedon Oct 16, 2020
@benhoyt, I added a note and link to the top comment. Thanks.
[-]proposal: os: add ReadDir method for lightweight directory reading[/-][+]os: add ReadDir method for lightweight directory reading[/+]gopherbot commentedon Jan 22, 2021
Change https://golang.org/cl/285592 mentions this issue:
doc/go1.16: mention os.DirEntry and types moved from os to io/fsdoc/go1.16: mention os.DirEntry and types moved from os to io/fs
os: add File.ReadDir method and DirEntry type