xref: /openbmc/openbmc/poky/bitbake/lib/bb/fetch2/crate.py (revision 517393d9)
1# ex:ts=4:sw=4:sts=4:et
2# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
3"""
4BitBake 'Fetch' implementation for crates.io
5"""
6
7# Copyright (C) 2016 Doug Goldstein
8#
9# SPDX-License-Identifier: GPL-2.0-only
10#
11# Based on functions from the base bb module, Copyright 2003 Holger Schurig
12
13import hashlib
14import json
15import os
16import subprocess
17import bb
18from   bb.fetch2 import logger, subprocess_setup, UnpackError
19from   bb.fetch2.wget import Wget
20
21
22class Crate(Wget):
23
24    """Class to fetch crates via wget"""
25
26    def _cargo_bitbake_path(self, rootdir):
27        return os.path.join(rootdir, "cargo_home", "bitbake")
28
29    def supports(self, ud, d):
30        """
31        Check to see if a given url is for this fetcher
32        """
33        return ud.type in ['crate']
34
35    def recommends_checksum(self, urldata):
36        return False
37
38    def urldata_init(self, ud, d):
39        """
40        Sets up to download the respective crate from crates.io
41        """
42
43        if ud.type == 'crate':
44            self._crate_urldata_init(ud, d)
45
46        super(Crate, self).urldata_init(ud, d)
47
48    def _crate_urldata_init(self, ud, d):
49        """
50        Sets up the download for a crate
51        """
52
53        # URL syntax is: crate://NAME/VERSION
54        # break the URL apart by /
55        parts = ud.url.split('/')
56        if len(parts) < 5:
57            raise bb.fetch2.ParameterError("Invalid URL: Must be crate://HOST/NAME/VERSION", ud.url)
58
59        # last field is version
60        version = parts[len(parts) - 1]
61        # second to last field is name
62        name = parts[len(parts) - 2]
63        # host (this is to allow custom crate registries to be specified
64        host = '/'.join(parts[2:len(parts) - 2])
65
66        # if using upstream just fix it up nicely
67        if host == 'crates.io':
68            host = 'crates.io/api/v1/crates'
69
70        ud.url = "https://%s/%s/%s/download" % (host, name, version)
71        ud.parm['downloadfilename'] = "%s-%s.crate" % (name, version)
72        ud.parm['name'] = name
73
74        logger.debug2("Fetching %s to %s" % (ud.url, ud.parm['downloadfilename']))
75
76    def unpack(self, ud, rootdir, d):
77        """
78        Uses the crate to build the necessary paths for cargo to utilize it
79        """
80        if ud.type == 'crate':
81            return self._crate_unpack(ud, rootdir, d)
82        else:
83            super(Crate, self).unpack(ud, rootdir, d)
84
85    def _crate_unpack(self, ud, rootdir, d):
86        """
87        Unpacks a crate
88        """
89        thefile = ud.localpath
90
91        # possible metadata we need to write out
92        metadata = {}
93
94        # change to the rootdir to unpack but save the old working dir
95        save_cwd = os.getcwd()
96        os.chdir(rootdir)
97
98        pn = d.getVar('BPN')
99        if pn == ud.parm.get('name'):
100            cmd = "tar -xz --no-same-owner -f %s" % thefile
101        else:
102            cargo_bitbake = self._cargo_bitbake_path(rootdir)
103
104            cmd = "tar -xz --no-same-owner -f %s -C %s" % (thefile, cargo_bitbake)
105
106            # ensure we've got these paths made
107            bb.utils.mkdirhier(cargo_bitbake)
108
109            # generate metadata necessary
110            with open(thefile, 'rb') as f:
111                # get the SHA256 of the original tarball
112                tarhash = hashlib.sha256(f.read()).hexdigest()
113
114            metadata['files'] = {}
115            metadata['package'] = tarhash
116
117        path = d.getVar('PATH')
118        if path:
119            cmd = "PATH=\"%s\" %s" % (path, cmd)
120        bb.note("Unpacking %s to %s/" % (thefile, os.getcwd()))
121
122        ret = subprocess.call(cmd, preexec_fn=subprocess_setup, shell=True)
123
124        os.chdir(save_cwd)
125
126        if ret != 0:
127            raise UnpackError("Unpack command %s failed with return value %s" % (cmd, ret), ud.url)
128
129        # if we have metadata to write out..
130        if len(metadata) > 0:
131            cratepath = os.path.splitext(os.path.basename(thefile))[0]
132            bbpath = self._cargo_bitbake_path(rootdir)
133            mdfile = '.cargo-checksum.json'
134            mdpath = os.path.join(bbpath, cratepath, mdfile)
135            with open(mdpath, "w") as f:
136                json.dump(metadata, f)
137