Пример #1
0
        def fmt_field(name, value='', key=None, level=0):
            hl = False

            # resolve values
            if isinstance(value, Script):
                hl = True
                value = value.script
            elif cls.is_secret(name, key):
                reveal = "reveal with: {}".format(
                    HighlightColor(
                        join('avendesora', 'value', cls.get_name(),
                             cls.combine_field(name, key))))
                value = ', '.join(cull([value.get_description(), reveal]))
            elif isinstance(value, (GeneratedSecret, ObscuredSecret)):
                v = cls.get_scalar(name, key)
                value = ', '.join(cull([value.get_description(), str(v)]))
            else:
                value = str(value)

            # format values
            if '\n' in value:
                value = indent(dedent(value),
                               get_setting('indent')).strip('\n')
                sep = '\n'
            elif value:
                sep = ' '
            else:
                sep = ''
            if hl:
                value = HighlightColor(value)
            name = str(name).replace('_', ' ')
            leader = level * get_setting('indent')
            return indent(
                LabelColor((name if key is None else str(key)) + ':') + sep +
                value, leader)
Пример #2
0
    def fail(self, *msg, cmd='<unknown>'):
        msg = join(*msg)
        try:
            msg = msg.decode('ascii', errors='replace')
        except AttributeError:
            pass
        try:
            if self.notify and not Color.isTTY():
                Run(
                    [
                        "mail", "-s",
                        f"{PROGRAM_NAME} failed on {username}@{hostname}"
                    ] + self.notify.split(),
                    stdin=dedent(f"""\
                        {PROGRAM_NAME} fails.

                        command: {cmd}
                        config: {self.config_name}
                        source: {username}@{fullhostname}:{', '.join(str(d) for d in self.src_dirs)}
                        destination: {self.repository!s}
                        error message:
                        """) + indent(msg) + "\n",
                    modes="soeW",
                    encoding="ascii",
                )
        except Error:
            pass
        try:
            notifier = self.settings.get("notifier")
            # don't use self.value as we don't want arguments expanded yet
            if notifier and not Color.isTTY():
                Run(self.notifier.format(
                    cmd=cmd,
                    msg=msg,
                    hostname=hostname,
                    user_name=username,
                    prog_name=PROGRAM_NAME,
                ),
                    modes="SoeW"
                    # need to use the shell as user will generally quote msg
                    )
        except Error:
            pass
        except KeyError as e:
            warn("unknown key.", culprit=(self.settings_file, "notifier", e))
Пример #3
0
 def write_playlist(self, path):
     try:
         path.write_text(join(*self.songs))
     except OSError as e:
         raise Error(os_error(e))
Пример #4
0
    def __init__(self, filename, sep=':', use_cache=True, update_cache=True):
        psf_filepath = to_path(filename)
        cache_filepath = psf_filepath.with_suffix(psf_filepath.suffix +
                                                  '.cache')

        # read cache if desired and current
        if use_cache:
            try:
                if cache_filepath.stat().st_mtime > psf_filepath.stat(
                ).st_mtime:
                    self._read_cache(cache_filepath)
                    return
            except OSError as e:
                log(os_error(e))
            except Exception as e:
                log(e)

        # open and parse PSF file
        parser = ParsePSF()
        try:
            content = psf_filepath.read_text()
            sections = parser.parse(filename, content)
        except ParseError as e:
            raise Error(str(e))
        except OSError as e:
            raise Error(os_error(e))
        except UnicodeError as e:
            raise Error(e,
                        culprit=psf_filepath,
                        codicil=join(
                            'This is likely a binary PSF file,',
                            'psf_utils only supports ASCII PSF files.',
                            '\nUse `psf {0!s} {0!s}.ascii` to convert.'.format(
                                psf_filepath),
                        ))
        meta, types, sweeps, traces, values = sections
        self.meta = meta
        self.types = types
        self.sweeps = sweeps
        self.traces = traces

        # add values to sweeps
        if sweeps:
            for sweep in sweeps:
                n = sweep.name
                sweep.abscissa = np.array([v[0] for v in values[n].values])

        # process signals
        # 1. convert to numpy and delete the original list
        # 2. convert to Signal class
        # 3. create signals dictionary
        signals = {}
        if traces:
            traces, groups = traces
            for trace in traces:
                name = trace.name
                type = types.get(trace.type, trace.type)
                vals = values[name].values
                if type == 'GROUP':
                    group = {
                        k: types.get(v, v)
                        for k, v in groups[name].items()
                    }
                    prefix = ''
                    get_value = lambda v, i: v[i]
                elif type.struct:
                    group = type.struct.types
                    prefix = name + ':'
                    get_value = lambda v, i: v[0][i]
                else:
                    group = {name: type}
                    prefix = ''
                    get_value = lambda v, i: v[i]
                for i, v in enumerate(group.items()):
                    n, t = v
                    joined_name = prefix + n
                    if 'complex' in t.kind:
                        ordinate = np.array(
                            [complex(*get_value(v, i)) for v in vals])
                    else:
                        ordinate = np.array([get_value(v, i) for v in vals])
                    signal = Signal(
                        name=joined_name,
                        ordinate=ordinate,
                        type=t,
                        access=t.name,
                        units=t.units,
                        meta=meta,
                    )
                    signals[joined_name] = signal
                del values[name]
        else:
            # no traces, this should be a DC op-point analysis dataset
            for name, value in values.items():
                assert len(value.values) == 1
                type = types[value.type]
                if type.struct:
                    for t, v in zip(type.struct.types.values(),
                                    value.values[0][0]):
                        n = f'{name}.{t.name}'
                        v = Quantity(v, unicode_units(t.units))
                        signal = Signal(
                            name=n,
                            ordinate=v,
                            type=t,
                            access=t.name,
                            units=t.units,
                            meta=meta,
                        )
                        signals[n] = signal
                else:
                    v = Quantity(value.values[0][0], unicode_units(type.units))
                    signal = Signal(
                        name=name,
                        ordinate=v,
                        type=type,
                        access=type.name,
                        units=type.units,
                        meta=meta,
                    )
                    signals[name] = signal
        self.signals = signals

        if update_cache:
            self._write_cache(cache_filepath)