def get_timezone(tzname): """Fetch timezone instance by name or return `None`""" try: # if given unicode parameter, pytz.timezone fails with: # "type() argument 1 must be string, not unicode" tz = pytz.timezone(to_unicode(tzname).encode('ascii', 'replace')) except (KeyError, IOError): tz = _tzmap.get(tzname) if tz and tzname.startswith('Etc/'): tz = _tzoffsetmap.get(tz.utcoffset(None)) return tz
def set(self, name, value): """ Change a config value. Needs to be saved before it will be persistent. """ if not self.config.parser.has_section(self.name): self.config.parser.add_section(self.name) if value is None: self.overridden[name] = True value = '' else: value = to_unicode(value).encode('utf-8') return self.config.parser.set(self.name, name, value)
def onecmd(self, line): """`line` may be a `str` or an `unicode` object""" try: if isinstance(line, str): if self.interactive: encoding = sys.stdin.encoding else: encoding = locale.getpreferredencoding() # sys.argv line = to_unicode(line, encoding) if self.interactive: line = line.replace('\\', '\\\\') rv = cmd.Cmd.onecmd(self, line) or 0 except SystemExit: raise except BaseError as e: printerr(_("Command failed:"), e) rv = 2 if not self.interactive: return rv
def save(self): """ Save current sections and items. This will make them persisten! """ if not self.filename: return # Only save options that differ from the defaults sections = [] for section in self.sections(): options = [] for option in self[section]: default = None if self.based_on: default = self.based_on.get(section, option) current = self.parser.has_option(section, option) and \ to_unicode(self.parser.get(section, option)) if current is not False and current != default: options.append((option, current)) if options: sections.append((section, sorted(options))) try: fileobj = open(self.filename, 'w') try: fileobj.write('# -*- coding: utf-8 -*-\n\n') for section, options in sections: fileobj.write('[%s]\n' % section) for key, val in options: if key in self[section].overridden: fileobj.write('# %s = <baseon>\n' % key) else: val = val.replace(CRLF, '\n').replace('\n', '\n ') fileobj.write('%s = %s\n' % (key, val.encode('utf-8'))) fileobj.write('\n') finally: fileobj.close() self._old_sections = deepcopy(self.parser._sections) except Exception: # Revert all changes to avoid inconsistencies self.parser._sections = deepcopy(self._old_sections) raise
def get(self, name, default=''): """ Get a plain item value """ if self.config.parser.has_option(self.name, name): value = self.config.parser.get(self.name, name) elif self.config.based_on: value = self.config.based_on[self.name].get(name, default) else: option = ConfigItem.reg_dict.get((self.name, name)) if option: value = option.default or default else: value = default if not value: return u'' elif isinstance(value, basestring): return to_unicode(value) else: return value
def do_createenv(self, line): """ Create environment by passed arguments or interactively """ def createenv_error(msg): printerr(_("Createenv for '%(env)s' failed:", env=self.envname), "\n", msg) if self.ceck_env(): createenv_error("Environment already created in specified path!") return 2 if os.path.exists(self.envname) and os.listdir(self.envname): createenv_error("Target folder not empty!") return 2 project_name = None # get arguments args = self.unicod_safe_split(line) if len(args) == 1 and not args[0]: returnvals = self.get_createenv_data() path, project_name = returnvals elif len(args) != 2: createenv_error('Wrong number of arguments: %d' % len(args)) return 2 else: path, project_name = args[:2] try: # Uppdate promt and internal stuff self.set_env(path) # Start env creation printout(_("Creating and Initializing Environment")) options = [ ('env', 'path', self.envname), ('project', 'name', project_name), ] # OVER-WRITE THESE OPTIONS from a file try: self.__env = Environment(self.envname, create=True, args=options) except Exception as e: # Bad thing happened! createenv_error( 'Failed to create environment. Created files will be deleted' ) printerr(e) traceback.print_exc() purge_dir(path) sys.exit(1) except Exception as e: createenv_error(to_unicode(e)) traceback.print_exc() return 2 # Close environment! self.__env.shutdown() self.print_line() printout( _("""Project environment for '%(project_name)s' created. You may now configure the environment by editing the file: %(config_path)s Have a nice day! """, project_name=project_name, project_path=self.envname, project_dir=os.path.basename(self.envname), config_path=os.path.join(self.__env.get_configs_dir(), _INI_FILENAME)))
def do_createenv(self, line): """ Create environment by passed arguments or interactively """ def createenv_error(msg): printerr(_("Createenv for '%(env)s' failed:", env=self.envname), "\n", msg) if self.ceck_env(): createenv_error("Environment already created in specified path!") return 2 if os.path.exists(self.envname) and os.listdir(self.envname): createenv_error("Target folder not empty!") return 2 project_name = None # get arguments args = self.unicod_safe_split(line) if len(args) == 1 and not args[0]: returnvals = self.get_createenv_data() path, project_name = returnvals elif len(args) != 2: createenv_error('Wrong number of arguments: %d' % len(args)) return 2 else: path, project_name = args[:2] try: # Uppdate promt and internal stuff self.set_env(path) # Start env creation printout(_("Creating and Initializing Environment")) options = [ ('env', 'path', self.envname), ('project', 'name', project_name), ] # OVER-WRITE THESE OPTIONS from a file try: self.__env = Environment(self.envname, create=True, args=options) except Exception as e: # Bad thing happened! createenv_error('Failed to create environment. Created files will be deleted') printerr(e) traceback.print_exc() purge_dir( path ) sys.exit(1) except Exception as e: createenv_error(to_unicode(e)) traceback.print_exc() return 2 # Close environment! self.__env.shutdown() self.print_line() printout(_("""Project environment for '%(project_name)s' created. You may now configure the environment by editing the file: %(config_path)s Have a nice day! """, project_name=project_name, project_path=self.envname, project_dir=os.path.basename(self.envname), config_path=os.path.join(self.__env.get_configs_dir(), _INI_FILENAME)))