1#
2# Copyright OpenEmbedded Contributors
3#
4# SPDX-License-Identifier: MIT
5#
6
7##
8## Purpose:
9## This class is used to update the list of crates in SRC_URI
10## by reading Cargo.lock in the source tree.
11##
12## See meta/recipes-devtools/python/python3-bcrypt_*.bb for an example
13##
14## To perform the update: bitbake -c update_crates recipe-name
15
16addtask do_update_crates after do_patch
17do_update_crates[depends] = "python3-native:do_populate_sysroot"
18do_update_crates[nostamp] = "1"
19do_update_crates[doc] = "Update the recipe by reading Cargo.lock and write in ${THISDIR}/${BPN}-crates.inc"
20
21RECIPE_UPDATE_EXTRA_TASKS += "do_update_crates"
22
23# The directory where to search for Cargo.lock files
24CARGO_LOCK_SRC_DIR ??= "${S}"
25
26do_update_crates() {
27    TARGET_FILE="${THISDIR}/${BPN}-crates.inc"
28
29    nativepython3 - <<EOF
30
31def get_crates(f):
32    import tomllib
33    c_list = '# from %s' % os.path.relpath(f, '${CARGO_LOCK_SRC_DIR}')
34    c_list += '\nSRC_URI += " \\\'
35    crates = tomllib.load(open(f, 'rb'))
36
37    # Build a list with crates info that have crates.io in the source
38    crates_candidates = list(filter(lambda c: 'crates.io' in c.get('source', ''), crates['package']))
39
40    if not crates_candidates:
41        raise ValueError("Unable to find any candidate crates that use crates.io")
42
43    # Update crates uri and their checksum, to avoid name clashing on the checksum
44    # we need to rename crates with name and version to have a unique key
45    cksum_list = ''
46    for c in crates_candidates:
47        rename = "%s-%s" % (c['name'], c['version'])
48        c_list += '\n    crate://crates.io/%s/%s \\\' % (c['name'], c['version'])
49        if 'checksum' in c:
50            cksum_list += '\nSRC_URI[%s.sha256sum] = "%s"' % (rename, c['checksum'])
51
52    c_list += '\n"\n'
53    c_list += cksum_list
54    c_list += '\n'
55    return c_list
56
57import os
58crates = "# Autogenerated with 'bitbake -c update_crates ${PN}'\n\n"
59found = False
60for root, dirs, files in os.walk('${CARGO_LOCK_SRC_DIR}'):
61    # ignore git and patches directories
62    if root.startswith(os.path.join('${CARGO_LOCK_SRC_DIR}', '.pc')):
63        continue
64    if root.startswith(os.path.join('${CARGO_LOCK_SRC_DIR}', '.git')):
65        continue
66    for file in files:
67        if file == 'Cargo.lock':
68            try:
69                cargo_lock_path = os.path.join(root, file)
70                crates += get_crates(os.path.join(root, file))
71            except Exception as e:
72                raise ValueError("Cannot parse '%s'" % cargo_lock_path) from e
73            else:
74                found = True
75if not found:
76    raise ValueError("Unable to find any Cargo.lock in ${CARGO_LOCK_SRC_DIR}")
77open("${TARGET_FILE}", 'w').write(crates)
78EOF
79
80    bbnote "Successfully update crates inside '${TARGET_FILE}'"
81}
82