spdx_tools.spdx.clitools.pyspdxtools

  1#!/usr/bin/env python3
  2
  3# Copyright (c) 2020 Yash Varshney
  4# Copyright (c) 2023 spdx contributors
  5# SPDX-License-Identifier: Apache-2.0
  6# Licensed under the Apache License, Version 2.0 (the "License");
  7# you may not use this file except in compliance with the License.
  8# You may obtain a copy of the License at
  9#    http://www.apache.org/licenses/LICENSE-2.0
 10# Unless required by applicable law or agreed to in writing, software
 11# distributed under the License is distributed on an "AS IS" BASIS,
 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13# See the License for the specific language governing permissions and
 14# limitations under the License.
 15import logging
 16import sys
 17
 18import click
 19from beartype.typing import List
 20
 21from spdx_tools.spdx.graph_generation import export_graph_from_document
 22from spdx_tools.spdx.model import Document
 23from spdx_tools.spdx.parser.error import SPDXParsingError
 24from spdx_tools.spdx.parser.parse_anything import parse_file
 25from spdx_tools.spdx.validation.document_validator import validate_full_spdx_document
 26from spdx_tools.spdx.validation.validation_message import ValidationMessage
 27from spdx_tools.spdx.writer.tagvalue import tagvalue_writer
 28from spdx_tools.spdx.writer.write_anything import write_file
 29
 30
 31@click.command()
 32@click.option("--infile", "-i", required=True, help="The file containing the document to be validated or converted.")
 33@click.option(
 34    "--outfile",
 35    "-o",
 36    help="The file to write the converted document to (write a dash for output to stdout or omit for no conversion). "
 37    "If you add the option --graph to the command the generated graph will be written to this file.",
 38)
 39@click.option(
 40    "--version",
 41    help='The SPDX version to be used during parsing and validation ("SPDX-2.2" or "SPDX-2.3"). '
 42    "Will be read from the document if not provided.",
 43    default=None,
 44)
 45@click.option("--novalidation", is_flag=True, help="Don't validate the provided document.")
 46@click.option(
 47    "--graph",
 48    is_flag=True,
 49    default=False,
 50    help="Generate a relationship graph from the input file. "
 51    "The generated graph is saved to the file specified with --outfile. "
 52    "Note: You need to install the optional dependencies 'networkx' and 'pygraphviz' for this feature.",
 53)
 54def main(infile: str, outfile: str, version: str, novalidation: bool, graph: bool):
 55    """
 56    CLI-tool for validating SPDX documents and converting between RDF, TAG-VALUE, JSON, YAML and XML formats.
 57    Formats are determined by the file endings.
 58    To use, run: 'pyspdxtools --infile <input file name> --outfile <output file name>'
 59    """
 60    try:
 61        document: Document = parse_file(infile)
 62
 63        if not novalidation:
 64            if not version:
 65                version = document.creation_info.spdx_version
 66
 67            if version not in ["SPDX-2.2", "SPDX-2.3"]:
 68                logging.error(f"This tool only supports SPDX versions SPDX-2.2 and SPDX-2.3, but got: {version}")
 69                sys.exit(1)
 70
 71            validation_messages: List[ValidationMessage] = validate_full_spdx_document(document, version)
 72            if validation_messages:
 73                log_string = "\n".join(
 74                    ["The document is invalid. The following issues have been found:"]
 75                    + [message.validation_message for message in validation_messages]
 76                )
 77                logging.error(log_string)
 78                sys.exit(1)
 79            else:
 80                logging.info("The document is valid.")
 81
 82        if outfile == "-":
 83            tagvalue_writer.write_document(document, sys.stdout)
 84
 85        elif graph:
 86            try:
 87                export_graph_from_document(document, outfile)
 88            except ImportError:
 89                logging.error(
 90                    "To be able to draw a relationship graph of the parsed document "
 91                    "you need to install 'networkx' and 'pygraphviz'. Run 'pip install \".[graph_generation]\"'."
 92                )
 93                sys.exit(1)
 94
 95        elif outfile:
 96            write_file(document, outfile, validate=False)
 97
 98    except NotImplementedError as err:
 99        logging.error(
100            err.args[0]
101            + "\nPlease note that this project is currently undergoing a major refactoring and therefore missing "
102            "a few features which will be added in time (refer to https://github.com/spdx/tools-python/issues "
103            "for insights into the current status).\n"
104            "In the meantime, please use the current PyPI release version."
105        )
106        sys.exit(1)
107
108    except SPDXParsingError as err:
109        log_string = "\n".join(
110            ["There have been issues while parsing the provided document:"]
111            + [message for message in err.get_messages()]
112        )
113        logging.error(log_string)
114        sys.exit(1)
115
116
117if __name__ == "__main__":
118    main()
main = <Command main>

CLI-tool for validating SPDX documents and converting between RDF, TAG-VALUE, JSON, YAML and XML formats. Formats are determined by the file endings. To use, run: 'pyspdxtools --infile --outfile '