Ejemplo n.º 1
0
    def execute(self, args, uargs):
        def tostring(item):
            if item is None:
                return ""
            if isinstance(item, (list, tuple)):
                return ", ".join(map(tostring, item))
            if isinstance(item, dict):
                return tostring(
                    list(
                        map(lambda kv: "{0}={1}".format(kv[0], kv[1]),
                            item.items())))
            return str(item)

        for index in range(0, len(args.files)):
            if index > 0:
                print("")
            file = args.files[index]
            try:
                la = LeafArtifact(file)
                if args.format is None:
                    print(file)
                    kvfmt = "  {k}: {v}"
                    print(kvfmt.format(k="identifier", v=la.identifier))
                    print(kvfmt.format(k="name", v=la.name))
                    print(kvfmt.format(k="version", v=la.version))
                    for k, v in la.info_node.items():
                        if k not in ("name", "version"):
                            print(kvfmt.format(k=k, v=tostring(v)))
                elif args.format == "json":
                    print(jtostring(la.info_node, pp=True))
                else:

                    class MyFormatter(Formatter):
                        def __init__(self, la, *args, **kwargs):
                            Formatter.__init__(self, *args, **kwargs)

                        def get_value(self, key, args, kwargs):
                            return tostring(la.info_node.get(key))

                    print(MyFormatter(la).format(args.format))
            except BaseException as e:
                print("Invalid leaf file {f}: {e}".format(f=file, e=e))
Ejemplo n.º 2
0
    def generate_manifest(self,
                          output_file: Path,
                          fragment_files: list = None,
                          info_map: dict = None,
                          resolve_envvars: bool = False):
        """
        Used to create a manifest.json file
        """
        model = OrderedDict()

        # Load fragments
        if fragment_files is not None:
            for fragment_file in fragment_files:
                self.logger.print_default(
                    "Use json fragment: {fragment}".format(
                        fragment=fragment_file))
                jlayer_update(model,
                              jloadfile(fragment_file),
                              list_append=True)

        # Load model
        manifest = Manifest(model)
        info = manifest.jsonget(JsonConstants.INFO, default=OrderedDict())

        # Set the common info
        if info_map is not None:
            for key in (
                    JsonConstants.INFO_NAME,
                    JsonConstants.INFO_VERSION,
                    JsonConstants.INFO_DESCRIPTION,
                    JsonConstants.INFO_MASTER,
                    JsonConstants.INFO_DATE,
                    JsonConstants.INFO_REQUIRES,
                    JsonConstants.INFO_DEPENDS,
                    JsonConstants.INFO_TAGS,
                    JsonConstants.INFO_LEAF_MINVER,
                    JsonConstants.INFO_AUTOUPGRADE,
            ):
                if key in info_map:
                    value = info_map[key]
                    if value is not None:
                        if key in (JsonConstants.INFO_REQUIRES,
                                   JsonConstants.INFO_DEPENDS,
                                   JsonConstants.INFO_TAGS):
                            # Handle lists
                            model_list = manifest.jsonpath(
                                [JsonConstants.INFO, key], default=[])
                            for motif in value:
                                if motif not in model_list:
                                    if key == JsonConstants.INFO_DEPENDS:
                                        # Try to parse as a conditional package
                                        # identifier
                                        ConditionalPackageIdentifier.parse(
                                            motif)
                                    elif key == JsonConstants.INFO_REQUIRES:
                                        # Try to parse as a package identifier
                                        PackageIdentifier.parse(motif)

                                    self.logger.print_verbose(
                                        "Add '{motif}' to '{key}' list".format(
                                            motif=motif, key=key))
                                    model_list.append(motif)
                        else:
                            self.logger.print_verbose(
                                "Set '{key}' = '{value}'".format(key=key,
                                                                 value=value))
                            info[key] = value

        # String replacement
        jsonstr = jtostring(manifest.json, pp=True)
        if resolve_envvars:
            for var in set(
                    re.compile(r"#\{([a-zA-Z0-9_]+)\}").findall(jsonstr)):
                value = os.environ.get(var)
                if value is None:
                    raise LeafException(
                        "Cannot find '{var}' in env".format(var=var),
                        hints="Set the variable with 'export {var}=xxx'".
                        format(var=var))
                self.logger.print_default("Replace {key} --> {value}".format(
                    key=var, value=value))
                jsonstr = jsonstr.replace("#{{{var}}}".format(var=var), value)

        if is_latest_package(manifest.identifier):
            raise LeafException(
                "Invalid version ({word} is a reserved keyword)".format(
                    word=LeafConstants.LATEST))

        self.logger.print_default(
            "Save '{mf.identifier}' manifest to {file}".format(
                mf=manifest, file=output_file))

        with output_file.open("w") as fp:
            fp.write(jsonstr)