dircache.py 1.09 KB
Newer Older
1 2 3 4 5
"""Read and cache directory listings.

The listdir() routine returns a sorted list of the files in a directory,
using a cache to avoid reading the directory more often than necessary.
The annotate() routine appends slashes to directories."""
Guido van Rossum's avatar
Guido van Rossum committed
6

Guido van Rossum's avatar
Guido van Rossum committed
7
import os
Guido van Rossum's avatar
Guido van Rossum committed
8

9
__all__ = ["listdir", "opendir", "annotate", "reset"]
10

Guido van Rossum's avatar
Guido van Rossum committed
11 12
cache = {}

13
def reset():
Tim Peters's avatar
Tim Peters committed
14 15 16
    """Reset the cache completely."""
    global cache
    cache = {}
17

18 19 20 21 22 23 24 25 26 27 28
def listdir(path):
    """List directory contents, using cache."""
    try:
        cached_mtime, list = cache[path]
        del cache[path]
    except KeyError:
        cached_mtime, list = -1, []
    try:
        mtime = os.stat(path)[8]
    except os.error:
        return []
29
    if mtime != cached_mtime:
30 31 32 33 34 35 36
        try:
            list = os.listdir(path)
        except os.error:
            return []
        list.sort()
    cache[path] = mtime, list
    return list
Guido van Rossum's avatar
Guido van Rossum committed
37 38 39

opendir = listdir # XXX backward compatibility

40 41 42 43 44
def annotate(head, list):
    """Add '/' suffixes to directories."""
    for i in range(len(list)):
        if os.path.isdir(os.path.join(head, list[i])):
            list[i] = list[i] + '/'