1#
2# SPDX-License-Identifier: GPL-2.0-only
3#
4
5import logging
6import os
7
8from wic import WicError
9from wic.pluginbase import SourcePlugin
10from wic.misc import exec_cmd, get_bitbake_var
11from wic.filemap import sparse_copy
12
13logger = logging.getLogger('wic')
14
15class RawCopyPlugin(SourcePlugin):
16    """
17    Populate partition content from raw image file.
18    """
19
20    name = 'rawcopy'
21
22    @staticmethod
23    def do_image_label(fstype, dst, label):
24        if fstype.startswith('ext'):
25            cmd = 'tune2fs -L %s %s' % (label, dst)
26        elif fstype in ('msdos', 'vfat'):
27            cmd = 'dosfslabel %s %s' % (dst, label)
28        elif fstype == 'btrfs':
29            cmd = 'btrfs filesystem label %s %s' % (dst, label)
30        elif fstype == 'swap':
31            cmd = 'mkswap -L %s %s' % (label, dst)
32        elif fstype in ('squashfs', 'erofs'):
33            raise WicError("It's not possible to update a %s "
34                           "filesystem label '%s'" % (fstype, label))
35        else:
36            raise WicError("Cannot update filesystem label: "
37                           "Unknown fstype: '%s'" % (fstype))
38
39        exec_cmd(cmd)
40
41    @classmethod
42    def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
43                             oe_builddir, bootimg_dir, kernel_dir,
44                             rootfs_dir, native_sysroot):
45        """
46        Called to do the actual content population for a partition i.e. it
47        'prepares' the partition to be incorporated into the image.
48        """
49        if not kernel_dir:
50            kernel_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
51            if not kernel_dir:
52                raise WicError("Couldn't find DEPLOY_DIR_IMAGE, exiting")
53
54        logger.debug('Kernel dir: %s', kernel_dir)
55
56        if 'file' not in source_params:
57            raise WicError("No file specified")
58
59        src = os.path.join(kernel_dir, source_params['file'])
60        dst = os.path.join(cr_workdir, "%s.%s" % (os.path.basename(source_params['file']), part.lineno))
61
62        if not os.path.exists(os.path.dirname(dst)):
63            os.makedirs(os.path.dirname(dst))
64
65        if 'skip' in source_params:
66            sparse_copy(src, dst, skip=int(source_params['skip']))
67        else:
68            sparse_copy(src, dst)
69
70        # get the size in the right units for kickstart (kB)
71        du_cmd = "du -Lbks %s" % dst
72        out = exec_cmd(du_cmd)
73        filesize = int(out.split()[0])
74
75        if filesize > part.size:
76            part.size = filesize
77
78        if part.label:
79            RawCopyPlugin.do_image_label(part.fstype, dst, part.label)
80
81        part.source_file = dst
82