#16 Add an action to retrieve the SPDX license string from a crate
Opened a month ago by ozbenh. Modified 17 days ago
fedora-rust/ ozbenh/cargo2rpm add-action-license  into  main

file modified
+17
@@ -170,6 +170,23 @@ 

                  break_the_build(str(exc))

                  exit(1)

  

+         case "license":

+             try:

+                 metadata = Metadata.from_cargo(args.path)

+ 

+                 if metadata.is_workspace():

+                     print("Cannot determine crate license from a cargo workspace.", file=sys.stderr)

+                     # exit code 1 will fail package scriptlets

+                     exit(1)

+ 

+                 print(metadata.packages[0].license)

+                 exit(0)

+ 

+             except subprocess.CalledProcessError as exc:

+                 # catch the exception to ensure stdout and stderr are printed

+                 print(pretty_called_process_error(exc), file=sys.stderr)

+                 exit(1)

+ 

          case "parse-vendor-manifest":

              try:

                  action_parse_vendor_manifest(args)

file modified
+3
@@ -59,6 +59,9 @@ 

      )

      action_parse_vendor_manifest.set_defaults(action="parse-vendor-manifest")

  

+     action_license = action_parsers.add_parser("license", help="Print the license of the current crate.")

+     action_license.set_defaults(action="license")

+ 

      if args:

          return parser.parse_args(args)

      else:  # pragma nocover

This is useful for a script I'm writing to collect all the bundled
crate licenses for centos-style vendored crates

Signed-off-by: Benjamin Herrenschmidt benh@amazon.com

Sorry for the late response.

I'm wondering if it wouldn't be easier if you used a short Python script directly?

Using cargo2rpm for what you're describing here just adds two layers of indirection:

  • using cargo to read metadata and re-output it in JSON format
  • using cargo2rpm to parse that JSON format and print results

You could do both with plain Python 3.11 and the tomllib module from the Python standard library in probably three lines of Python code, without adding both cargo and cargo2rpm to your script's dependencies.

Ok, depending on how you do it, four lines of dependency-free Python 3.11 code:

import tomllib
with file = open("Cargo.toml"):
    toml = tomllib.loads(file.read())
license = toml["package"]["license"]