Beispiel #1
0
class Options(AttrMonitor):
    def __init__(self, args=None):
        """constructor
        @args: argument dictionary (if None use sys)
        """
        self.args = args
        if not args:
            self.args = docopt(USAGE, version=VERSION)
        self.log = Logger()
        self.debug = self.args['--verbose']
        if not self.debug and ENV_DEBUG in os.environ:
            self.debug = True
        if ENV_NODEBUG in os.environ:
            self.debug = False
        self.profile = self.args['--profile']
        self.confpath = os.path.expanduser(self.args['--cfg'])
        if self.debug:
            self.log.dbg('config file: {}'.format(self.confpath))

        self._read_config(self.profile)
        self._apply_args()
        self._fill_attr()
        if ENV_NOBANNER not in os.environ \
           and self.banner \
           and not self.args['--no-banner']:
            self._header()
        self._print_attr()
        # start monitoring for bad attribute
        self._set_attr_err = True

    def _header(self):
        """print the header"""
        self.log.log(BANNER)
        self.log.log('')

    def _read_config(self, profile=None):
        """read the config file"""
        self.conf = Cfg(self.confpath, profile=profile, debug=self.debug)
        # transform the configs in attribute
        for k, v in self.conf.get_settings().items():
            setattr(self, k, v)

    def _apply_args(self):
        """apply cli args as attribute"""
        # the commands
        self.cmd_list = self.args['list']
        self.cmd_listfiles = self.args['listfiles']
        self.cmd_install = self.args['install']
        self.cmd_compare = self.args['compare']
        self.cmd_import = self.args['import']
        self.cmd_update = self.args['update']
        self.cmd_detail = self.args['detail']

        # adapt attributes based on arguments
        self.dry = self.args['--dry']
        self.safe = not self.args['--force']
        self.link = LinkTypes.NOLINK
        if self.link_by_default:
            self.link = LinkTypes.PARENTS

        if self.args['--inv-link']:
            # Only invert link type from NOLINK to PARENTS and vice-versa
            if self.link == LinkTypes.NOLINK:
                self.link = LinkTypes.PARENTS
            elif self.link == LinkTypes.PARENTS:
                self.link = LinkTypes.NOLINK

        # "listfiles" specifics
        self.listfiles_templateonly = self.args['--template']
        # "install" specifics
        self.install_temporary = self.args['--temp']
        self.install_keys = self.args['<key>']
        self.install_diff = not self.args['--nodiff']
        self.install_showdiff = self.showdiff or self.args['--showdiff']
        self.install_backup_suffix = BACKUP_SUFFIX
        # "compare" specifics
        self.compare_dopts = self.args['--dopts']
        self.compare_focus = self.args['--file']
        self.compare_ignore = self.args['--ignore']
        self.compare_ignore.append('*{}'.format(self.install_backup_suffix))
        # "import" specifics
        self.import_path = self.args['<path>']
        # "update" specifics
        self.update_path = self.args['<path>']
        self.update_iskey = self.args['--key']
        self.update_ignore = self.args['--ignore']
        self.update_ignore.append('*{}'.format(self.install_backup_suffix))
        self.update_showpatch = self.args['--show-patch']
        # "detail" specifics
        self.detail_keys = self.args['<key>']

    def _fill_attr(self):
        """create attributes from conf"""
        # variables
        self.variables = self.conf.get_variables(self.profile,
                                                 debug=self.debug).copy()
        # the dotfiles
        self.dotfiles = self.conf.eval_dotfiles(self.profile,
                                                self.variables,
                                                debug=self.debug).copy()
        # the profiles
        self.profiles = self.conf.get_profiles()

    def _print_attr(self):
        """print all of this class attributes"""
        if not self.debug:
            return
        self.log.dbg('options:')
        for att in dir(self):
            if att.startswith('_'):
                continue
            val = getattr(self, att)
            if callable(val):
                continue
            self.log.dbg('- {}: \"{}\"'.format(att, val))

    def _attr_set(self, attr):
        """error when some inexistent attr is set"""
        raise Exception('bad option: {}'.format(attr))
Beispiel #2
0
def main():
    """entry point"""
    ret = True
    args = docopt(USAGE, version=VERSION)

    try:
        conf = Cfg(os.path.expanduser(args['--cfg']))
    except ValueError as e:
        LOG.err('Config format error: {}'.format(str(e)))
        return False

    opts = conf.get_settings()
    opts['dry'] = args['--dry']
    opts['profile'] = args['--profile']
    opts['safe'] = not args['--force']
    opts['installdiff'] = not args['--nodiff']
    opts['link'] = args['--link']
    opts['debug'] = args['--verbose']
    opts['variables'] = conf.get_variables()
    opts['showdiff'] = opts['showdiff'] or args['--showdiff']

    if opts['debug']:
        LOG.dbg('config file: {}'.format(args['--cfg']))
        LOG.dbg('opts: {}'.format(opts))

    # resolve dynamic paths
    conf.eval_dotfiles(opts['profile'], debug=opts['debug'])

    if ENV_NOBANNER not in os.environ \
            and opts['banner'] \
            and not args['--no-banner']:
        _header()

    try:

        if args['list']:
            # list existing profiles
            if opts['debug']:
                LOG.dbg('running cmd: list')
            cmd_list_profiles(conf)

        elif args['listfiles']:
            # list files for selected profile
            if opts['debug']:
                LOG.dbg('running cmd: listfiles')
            cmd_list_files(opts, conf, templateonly=args['--template'])

        elif args['install']:
            # install the dotfiles stored in dotdrop
            if opts['debug']:
                LOG.dbg('running cmd: install')
            ret = cmd_install(opts,
                              conf,
                              temporary=args['--temp'],
                              keys=args['<key>'])

        elif args['compare']:
            # compare local dotfiles with dotfiles stored in dotdrop
            if opts['debug']:
                LOG.dbg('running cmd: compare')
            tmp = get_tmpdir()
            opts['dopts'] = args['--dopts']
            ret = cmd_compare(opts,
                              conf,
                              tmp,
                              focus=args['--file'],
                              ignore=args['--ignore'])
            # clean tmp directory
            remove(tmp)

        elif args['import']:
            # import dotfile(s)
            if opts['debug']:
                LOG.dbg('running cmd: import')
            ret = cmd_importer(opts, conf, args['<path>'])

        elif args['update']:
            # update a dotfile
            if opts['debug']:
                LOG.dbg('running cmd: update')
            iskey = args['--key']
            ret = cmd_update(opts, conf, args['<path>'], iskey=iskey)

        elif args['detail']:
            # detail files
            if opts['debug']:
                LOG.dbg('running cmd: update')
            cmd_detail(opts, conf, keys=args['<key>'])

    except KeyboardInterrupt:
        LOG.err('interrupted')
        ret = False

    return ret