mirror of
1
0
Fork 0
dotbot/dotbot/plugins/create.py

60 lines
1.9 KiB
Python
Raw Normal View History

import os
import dotbot
class Create(dotbot.Plugin):
2022-01-30 18:48:30 -05:00
"""
Create empty paths.
2022-01-30 18:48:30 -05:00
"""
2022-01-30 18:48:30 -05:00
_directive = "create"
def can_handle(self, directive):
return directive == self._directive
def handle(self, directive, data):
if directive != self._directive:
2022-01-30 18:48:30 -05:00
raise ValueError("Create cannot handle directive %s" % directive)
return self._process_paths(data)
def _process_paths(self, paths):
success = True
2022-01-30 18:48:30 -05:00
defaults = self._context.defaults().get("create", {})
for key in paths:
2022-04-25 10:02:58 -04:00
path = os.path.abspath(os.path.expandvars(os.path.expanduser(key)))
2022-01-30 18:48:30 -05:00
mode = defaults.get("mode", 0o777) # same as the default for os.makedirs
if isinstance(paths, dict):
options = paths[key]
if options:
2022-01-30 18:48:30 -05:00
mode = options.get("mode", mode)
success &= self._create(path, mode)
if success:
2022-01-30 18:48:30 -05:00
self._log.info("All paths have been set up")
else:
2022-01-30 18:48:30 -05:00
self._log.error("Some paths were not successfully set up")
return success
def _exists(self, path):
2022-01-30 18:48:30 -05:00
"""
Returns true if the path exists.
2022-01-30 18:48:30 -05:00
"""
path = os.path.expanduser(path)
return os.path.exists(path)
def _create(self, path, mode):
success = True
if not self._exists(path):
2022-01-30 18:48:30 -05:00
self._log.debug("Trying to create path %s with mode %o" % (path, mode))
try:
2022-01-30 18:48:30 -05:00
self._log.lowinfo("Creating path %s" % path)
os.makedirs(path, mode)
2022-04-25 10:02:58 -04:00
# On Windows, the *mode* argument to `os.makedirs()` is ignored.
# The mode must be set explicitly in a follow-up call.
os.chmod(path, mode)
except OSError:
2022-01-30 18:48:30 -05:00
self._log.warning("Failed to create path %s" % path)
success = False
else:
2022-01-30 18:48:30 -05:00
self._log.lowinfo("Path exists %s" % path)
return success