Skip to content
This repository has been archived by the owner on Jan 30, 2023. It is now read-only.

Commit

Permalink
argparse.FileType can be handy, but it doesn't create directories.
Browse files Browse the repository at this point in the history
Be kind to the user and create the lock directory for them if it doesn't
exist.
  • Loading branch information
embray committed Sep 6, 2017
1 parent 63f4b2d commit 5e89b68
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/bin/sage-flock
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,32 @@ import pipes
import sys


class FileType(argparse.FileType):
"""
Version of argparse.FileType with the option to ensure that the full path
to the file exists.
"""

def __init__(self, mode='r', makedirs=False):
# Note, the base class __init__ takes other arguments too depending on
# the Python version but we don't care about them for this purpose
super(FileType, self).__init__(mode=mode)
self._makedirs = makedirs

def __call__(self, string):
if self._makedirs and string != '-':
dirname = os.path.dirname(string)
try:
os.makedirs(dirname)
except OSError as exc:
if not os.path.isdir(dirname):
raise argparse.ArgumentTypeError(
"can't create '{0}': {1}".format(dirname, exc))

return super(FileType, self).__call__(string)



def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
group = parser.add_mutually_exclusive_group()
Expand All @@ -34,7 +60,8 @@ def main(argv=None):
# but supplying the --exclusive flag explicitly may help clarity
group.add_argument('-x', '--exclusive', action='store_true',
help='create an exclusive lock (the default)')
parser.add_argument('lock', metavar='LOCK', type=argparse.FileType('w+'),
parser.add_argument('lock', metavar='LOCK',
type=FileType('w+', makedirs=True),
help='filename of the lock')
parser.add_argument('command', metavar='COMMAND', nargs=argparse.REMAINDER,
help='command to run with the lock including any '
Expand Down

0 comments on commit 5e89b68

Please sign in to comment.