Skip to content

Commit

Permalink
Fixed #42 -- use a user cache directory
Browse files Browse the repository at this point in the history
  • Loading branch information
alex committed Sep 1, 2015
1 parent 700daa7 commit 76d268a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 30 deletions.
46 changes: 16 additions & 30 deletions rply/parsergenerator.py
Expand Up @@ -8,6 +8,8 @@
import tempfile
import warnings

from appdirs import AppDirs

from rply.errors import ParserGeneratorError, ParserGeneratorWarning
from rply.grammar import Grammar
from rply.parser import LRParser
Expand Down Expand Up @@ -175,44 +177,28 @@ def build(self):
g.compute_first()
g.compute_follow()

# win32 temp directories are already per-user
if os.name == "nt":
cache_file = os.path.join(
tempfile.gettempdir(),
"rply-%s-%s-%s.json" % (
self.VERSION, self.cache_id, self.compute_grammar_hash(g)
)
)
else:
cache_file = os.path.join(
tempfile.gettempdir(),
"rply-%s-%s-%s-%s.json" % (
self.VERSION,
os.getuid(),
self.cache_id,
self.compute_grammar_hash(g)
)
cache_dir = AppDirs("rply").user_cache_dir
cache_file = os.path.join(
cache_dir,
"rply-%s-%s-%s.json" % (
self.VERSION, self.cache_id, self.compute_grammar_hash(g)
)
)

table = None
if os.path.exists(cache_file):
with open(cache_file) as f:
data = json.load(f)
stat_result = os.fstat(f.fileno())
if (
os.name == "nt" or (
stat_result.st_uid == os.getuid() and
stat.S_IMODE(stat_result.st_mode) == 0o0600
)
):
if self.data_is_valid(g, data):
table = LRTable.from_cache(g, data)
if self.data_is_valid(g, data):
table = LRTable.from_cache(g, data)
if table is None:
table = LRTable.from_grammar(g)
fd = os.open(
cache_file, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o0600
)
with os.fdopen(fd, "w") as f:
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)

with open(cache_file, "w") as f:
json.dump(self.serialize_table(table), f)

if table.sr_conflicts:
warnings.warn(
"%d shift/reduce conflict%s" % (
Expand Down
1 change: 1 addition & 0 deletions setup.py
Expand Up @@ -13,4 +13,5 @@
author="Alex Gaynor",
author_email="alex.gaynor@gmail.com",
packages=["rply"],
install_requires=["appdirs"],
)

0 comments on commit 76d268a

Please sign in to comment.