コード例 #1
0
    def write_file(self, path):
        if not hasattr(self, 'cached_obj') or self.kobj._always_regenerate:
            self.render()

        if self.cached_obj is None:
            return

        if not hasattr(self, 'cached_yaml'):
            self.yaml()

        if self.uses_namespace:
            path = os.path.join(path, self.namespace_name)
            mkdir_p(path)

        self.filedir = path
        self.filename = self.filename_conversion(self.identifier) + '.yaml'

        self.debug(3, "writing file {}/{}".format(self.filedir, self.filename))

        sav_context = var_types.VarContext.current_context
        var_types.VarContext.current_context = {'confidential': False}
        try:
            content = str(self.cached_yaml)
            self.is_confidential = var_types.VarContext.current_context[
                'confidential']
        finally:
            var_types.VarContext.current_context = sav_context

        if self.is_confidential:
            self.debug(
                3,
                "  file {}/{} is confidential".format(self.filedir,
                                                      self.filename))

        changed = False
        if self.content_check is not None and self.content_check in (
                'contents', 'yaml', 'exists'):
            try:
                with open(os.path.join(path, self.filename), 'rb') as f:
                    if self.content_check == 'contents':
                        if content != f.read().decode('utf8'):
                            changed = True
                    elif self.content_check == 'yaml':
                        if yaml_load(content) != yaml_load(
                                f.read().decode('utf8')):
                            changed = True
            except:
                changed = True

        with open(os.path.join(path, '.' + self.identifier + '.tmp'),
                  'w') as f:
            f.write(content)
        os.rename(os.path.join(path, '.' + self.identifier + '.tmp'),
                  os.path.join(path, self.filename))

        if changed:
            return os.path.join(path, self.filename)
        return None
コード例 #2
0
    def run(self, args):
        self.get_repository(can_fail=True)
        load_python.PythonBaseFile.get_kube_objs()

        if args.file == '-':
            data = sys.stdin.read()
            sys.stdin.close()
        else:
            with open(args.file) as f:
                data = f.read()

        value = None
        if data.lstrip().startswith('{'):
            try:
                value = json.loads(data)
            except ValueError:
                pass

        if value is None:
            try:
                value = kube_yaml.yaml_load(data)
                if not isinstance(value, dict):
                    value = None
            except ValueError:
                pass

        if value is None:
            print("Cannot load {} as either JSON or YAML".format(args.file), file=sys.stderr)
            return 1

        namespace = args.namespace
        if 'kind' in value and value['kind'] == 'List':
            values = value['items']
        else:
            values = [value]

        last_ns = None

        for v in values:
            if args.namespace is None:
                try:
                    namespace = v['metadata']['namespace']
                except KeyError:
                    pass

            indent = args.indent

            obj = KubeObj.parse_obj(v)

            if not obj._uses_namespace:
                namespace = None

            if namespace is not None and (args.namespace is not None or args.with_namespace):
                if namespace != last_ns:
                    print((' ' * args.indent) + 'with namespace({}):'.format(repr(namespace)))
                indent += 4

            print((' ' * indent) + obj.dump_obj(indent, args.include_defaults) + '\n')
            last_ns = namespace
コード例 #3
0
ファイル: lookup.py プロジェクト: rleite-olx/rubiks
    def _load_files(self):
        data = None
        for path in self.path:
            try:
                with open(path.full_path, 'rb') as f:
                    data = f.read()
            except:
                if not self.non_exist_ok:
                    raise

            if data is None:
                return

            if b'GITCRYPT' in data[0:10]:
                if self.has_data:
                    raise ValueError(
                        "Mixed crypt and notcrypt data in lookup files")

                if not self.git_crypt_ok:
                    raise ValueError(
                        "file {} was git-crypt-ed and cannot be read".format(
                            path.repo_rel_path))
                self.has_gitcrypt = True
                continue

            if self.has_gitcrypt:
                raise ValueError(
                    "Mixed crypt and notcrypt data in lookup files")

            try:
                data = data.decode('utf8')
            except:
                if self.fail_ok:
                    print("Can't parse {} as unicode, let alone JSON or YAML".
                          format(path.hrepo_rel_path),
                          file=sys.stderr)
                    return
                raise

            try:
                if data.lstrip().startswith('{') and data.rstrip().endswith(
                        '}'):
                    self.data.update(json.loads(data))
                    self.has_data = True
                else:
                    raise ValueError("not json")
            except ValueError:
                try:
                    self.data.update(yaml_load(data))
                    self.has_data = True
                except:
                    if self.fail_ok:
                        print("Can't parse {} as JSON or YAML".format(
                            path.repo_rel_path),
                              file=sys.stderr)
                    else:
                        raise ValueError("Unparseable file " +
                                         path.repo_rel_path)
コード例 #4
0
    def run(self, args):
        try:
            with open(args.source) as f:
                s_data = f.read()
        except:
            print("Error reading {}".format(args.source), file=sys.stderr)
            return 1

        try:
            with open(args.dest) as f:
                d_data = f.read()
        except:
            print("Error reading {}".format(args.dest), file=sys.stderr)
            return 1

        try:
            src = kube_yaml.yaml_load(s_data)
        except:
            print("Error parsing {}".format(args.source), file=sys.stderr)
            return 1

        try:
            dst = kube_yaml.yaml_load(d_data)
        except:
            print("Error parsing {}".format(args.dest), file=sys.stderr)
            return 1

        self.allow_reorder = not args.no_reorder
        self.colour = not args.no_colour
        self.ignore_none = args.ignore_none
        self.ignore_empty = args.ignore_empty
        self.output = False

        if not (hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()):
            self.colour = False

        return self.diff('<top>', src, dst)
コード例 #5
0
    def run(self, args):
        def walk(arg):
            if os.path.isfile(arg):
                return [arg]
            elif os.path.isdir(arg):
                ret = []
                for d in os.listdir(arg):
                    if d.startswith('.'):
                        continue
                    ret.extend(walk(os.path.join(arg, d)))
                return ret
            elif args.follow_symlinks and os.path.islink(arg):
                return walk(os.path.realpath(arg))
            else:
                return []

        files = []
        for f in args.file_or_dir:
            files.extend(walk(f))

        excludes = set()
        if args.exclude_namespace:
            excludes.add('namespace')
            excludes.add('project')

        if args.exclude is not None:
            for e in args.exclude:
                excludes.add(e.lower())

        ordering = {}

        for ff in files:
            try:
                with open(ff) as f:
                    data = f.read()

                value = None
                if data.lstrip().startswith('{'):
                    try:
                        value = json.loads(data)
                    except ValueError:
                        pass

                if value is None:
                    value = kube_yaml.yaml_load(data)
                    assert isinstance(value, dict)

                obj = KubeObj.find_class_from_obj(value)
                assert obj is not None

                assert obj.kind.lower() not in excludes

                if obj._output_order not in ordering:
                    ordering[obj._output_order] = []
                ordering[obj._output_order].append(ff)
            except:
                pass

        for k in sorted(ordering.keys(), reverse=args.reverse):
            for f in ordering[k]:
                print(f)

        return 0
コード例 #6
0
 def yaml_load(string):
     return kube_yaml.yaml_load(string)