Files
cpython/Lib/statcache.py

71 lines
1.4 KiB
Python
Raw Permalink Normal View History

"""Maintain a cache of stat() information on files.
There are functions to reset the cache or to selectively remove items.
"""
1990-10-13 19:23:40 +00:00
1992-03-31 19:04:48 +00:00
import os
from stat import *
1990-10-13 19:23:40 +00:00
# The cache.
1992-03-31 19:04:48 +00:00
# Keys are pathnames, values are `os.stat' outcomes.
1990-10-13 19:23:40 +00:00
#
cache = {}
def stat(path):
"""Stat a file, possibly out of the cache."""
ret = cache.get(path, None)
if ret is not None:
return ret
1992-03-31 19:04:48 +00:00
cache[path] = ret = os.stat(path)
1990-10-13 19:23:40 +00:00
return ret
def reset():
"""Reset the cache completely."""
cache.clear()
1990-10-13 19:23:40 +00:00
def forget(path):
"""Remove a given item from the cache, if it exists."""
try:
1990-10-13 19:23:40 +00:00
del cache[path]
except KeyError:
pass
1990-10-13 19:23:40 +00:00
def forget_prefix(prefix):
"""Remove all pathnames with a given prefix."""
1990-10-13 19:23:40 +00:00
n = len(prefix)
for path in cache.keys():
1992-01-01 19:35:13 +00:00
if path[:n] == prefix:
forget(path)
1990-10-13 19:23:40 +00:00
def forget_dir(prefix):
"""Forget about a directory and all entries in it, but not about
entries in subdirectories."""
import os.path
prefix = os.path.dirname(os.path.join(prefix, "xxx"))
1990-10-13 19:23:40 +00:00
forget(prefix)
for path in cache.keys():
2001-06-15 16:43:54 +00:00
if path.startswith(prefix) and os.path.dirname(path) == prefix:
forget(path)
1990-10-13 19:23:40 +00:00
def forget_except_prefix(prefix):
"""Remove all pathnames except with a given prefix.
Normally used with prefix = '/' after a chdir()."""
1990-10-13 19:23:40 +00:00
n = len(prefix)
for path in cache.keys():
if path[:n] <> prefix:
forget(path)
1990-10-13 19:23:40 +00:00
def isdir(path):
"""Check for directory."""
1990-10-13 19:23:40 +00:00
try:
st = stat(path)
1992-03-31 19:04:48 +00:00
except os.error:
1990-10-13 19:23:40 +00:00
return 0
return S_ISDIR(st[ST_MODE])