1
0
Fork 0
mirror of synced 2024-11-22 16:25:34 -05:00
dotbot/plugins/clean.py

58 lines
2.2 KiB
Python
Raw Normal View History

2016-01-16 22:00:15 -05:00
import os, dotbot
2014-06-08 14:30:10 -04:00
2016-01-16 22:00:15 -05:00
class Clean(dotbot.Plugin):
2014-06-08 14:30:10 -04:00
'''
Cleans broken symbolic links.
'''
_directive = 'clean'
def can_handle(self, directive):
return directive == self._directive
def handle(self, directive, data):
if directive != self._directive:
2016-01-16 22:00:15 -05:00
raise ValueError('Clean cannot handle directive %s' % directive)
2014-06-08 14:30:10 -04:00
return self._process_clean(data)
def _process_clean(self, targets):
success = True
2017-03-22 06:22:10 -04:00
defaults = self._context.defaults().get(self._directive, {})
force = defaults.get('force', False)
2014-06-08 14:30:10 -04:00
for target in targets:
2017-03-22 06:22:10 -04:00
if isinstance(targets, dict):
force = targets[target].get('force', force)
success &= self._clean(target, force)
2014-06-08 14:30:10 -04:00
if success:
self._log.info('All targets have been cleaned')
else:
self._log.error('Some targets were not successfully cleaned')
2014-06-08 14:30:10 -04:00
return success
2017-03-22 06:22:10 -04:00
def _clean(self, target, force):
2014-06-08 14:30:10 -04:00
'''
2017-03-22 06:22:10 -04:00
Cleans all the broken symbolic links in target if they point to
a subdirectory of the base directory or if forced to clean.
2014-06-08 14:30:10 -04:00
'''
if not os.path.isdir(os.path.expanduser(target)):
self._log.debug('Ignoring nonexistent directory %s' % target)
return True
2014-06-08 14:30:10 -04:00
for item in os.listdir(os.path.expanduser(target)):
path = os.path.join(os.path.expanduser(target), item)
if not os.path.exists(path) and os.path.islink(path):
2017-03-22 06:22:10 -04:00
points_at = os.path.join(os.path.dirname(path), os.readlink(path))
if self._in_directory(path, self._context.base_directory()) or force:
self._log.lowinfo('Removing invalid link %s -> %s' % (path, points_at))
2014-06-08 14:30:10 -04:00
os.remove(path)
2017-03-22 06:22:10 -04:00
else:
self._log.lowinfo('Link %s -> %s not removed.' % (path, points_at))
2014-06-08 14:30:10 -04:00
return True
def _in_directory(self, path, directory):
'''
Returns true if the path is in the directory.
'''
directory = os.path.join(os.path.realpath(directory), '')
path = os.path.realpath(path)
return os.path.commonprefix([path, directory]) == directory