1#
2# Copyright OpenEmbedded Contributors
3#
4# SPDX-License-Identifier: MIT
5#
6
7inherit package
8
9IMAGE_PKGTYPE ?= "ipk"
10
11IPKGCONF_TARGET = "${WORKDIR}/opkg.conf"
12IPKGCONF_SDK =  "${WORKDIR}/opkg-sdk.conf"
13IPKGCONF_SDK_TARGET = "${WORKDIR}/opkg-sdk-target.conf"
14
15PKGWRITEDIRIPK = "${WORKDIR}/deploy-ipks"
16
17# Program to be used to build opkg packages
18OPKGBUILDCMD ??= 'opkg-build -Z xz -a "${XZ_DEFAULTS}"'
19
20OPKG_ARGS += "--force_postinstall --prefer-arch-to-version"
21OPKG_ARGS += "${@['', '--no-install-recommends'][d.getVar("NO_RECOMMENDATIONS") == "1"]}"
22OPKG_ARGS += "${@['', '--add-exclude ' + ' --add-exclude '.join((d.getVar('PACKAGE_EXCLUDE') or "").split())][(d.getVar("PACKAGE_EXCLUDE") or "").strip() != ""]}"
23
24OPKGLIBDIR ??= "${localstatedir}/lib"
25
26python do_package_ipk () {
27    workdir = d.getVar('WORKDIR')
28    outdir = d.getVar('PKGWRITEDIRIPK')
29    tmpdir = d.getVar('TMPDIR')
30    pkgdest = d.getVar('PKGDEST')
31    if not workdir or not outdir or not tmpdir:
32        bb.error("Variables incorrectly set, unable to package")
33        return
34
35    packages = d.getVar('PACKAGES')
36    if not packages or packages == '':
37        bb.debug(1, "No packages; nothing to do")
38        return
39
40    # We're about to add new packages so the index needs to be checked
41    # so remove the appropriate stamp file.
42    if os.access(os.path.join(tmpdir, "stamps", "IPK_PACKAGE_INDEX_CLEAN"), os.R_OK):
43        os.unlink(os.path.join(tmpdir, "stamps", "IPK_PACKAGE_INDEX_CLEAN"))
44
45    oe.utils.multiprocess_launch(ipk_write_pkg, packages.split(), d, extraargs=(d,))
46}
47do_package_ipk[vardeps] += "ipk_write_pkg"
48do_package_ipk[vardepsexclude] = "BB_NUMBER_THREADS"
49
50def ipk_write_pkg(pkg, d):
51    import re, copy
52    import subprocess
53    import textwrap
54    import collections
55    import glob
56
57    def cleanupcontrol(root):
58        for p in ['CONTROL', 'DEBIAN']:
59            p = os.path.join(root, p)
60            if os.path.exists(p):
61                bb.utils.prunedir(p)
62
63    outdir = d.getVar('PKGWRITEDIRIPK')
64    pkgdest = d.getVar('PKGDEST')
65    recipesource = os.path.basename(d.getVar('FILE'))
66
67    localdata = bb.data.createCopy(d)
68    root = "%s/%s" % (pkgdest, pkg)
69
70    lf = bb.utils.lockfile(root + ".lock")
71    try:
72        localdata.setVar('ROOT', '')
73        localdata.setVar('ROOT_%s' % pkg, root)
74        pkgname = localdata.getVar('PKG:%s' % pkg)
75        if not pkgname:
76            pkgname = pkg
77        localdata.setVar('PKG', pkgname)
78
79        localdata.setVar('OVERRIDES', d.getVar("OVERRIDES", False) + ":" + pkg)
80
81        basedir = os.path.join(os.path.dirname(root))
82        arch = localdata.getVar('PACKAGE_ARCH')
83
84        if localdata.getVar('IPK_HIERARCHICAL_FEED', False) == "1":
85            # Spread packages across subdirectories so each isn't too crowded
86            if pkgname.startswith('lib'):
87                pkg_prefix = 'lib' + pkgname[3]
88            else:
89                pkg_prefix = pkgname[0]
90
91            # Keep -dbg, -dev, -doc, -staticdev, -locale and -locale-* packages
92            # together. These package suffixes are taken from the definitions of
93            # PACKAGES and PACKAGES_DYNAMIC in meta/conf/bitbake.conf
94            if pkgname[-4:] in ('-dbg', '-dev', '-doc'):
95                pkg_subdir = pkgname[:-4]
96            elif pkgname.endswith('-staticdev'):
97                pkg_subdir = pkgname[:-10]
98            elif pkgname.endswith('-locale'):
99                pkg_subdir = pkgname[:-7]
100            elif '-locale-' in pkgname:
101                pkg_subdir = pkgname[:pkgname.find('-locale-')]
102            else:
103                pkg_subdir = pkgname
104
105            pkgoutdir = "%s/%s/%s/%s" % (outdir, arch, pkg_prefix, pkg_subdir)
106        else:
107            pkgoutdir = "%s/%s" % (outdir, arch)
108
109        bb.utils.mkdirhier(pkgoutdir)
110        os.chdir(root)
111        cleanupcontrol(root)
112        g = glob.glob('*')
113        if not g and localdata.getVar('ALLOW_EMPTY', False) != "1":
114            bb.note("Not creating empty archive for %s-%s-%s" % (pkg, localdata.getVar('PKGV'), localdata.getVar('PKGR')))
115            return
116
117        controldir = os.path.join(root, 'CONTROL')
118        bb.utils.mkdirhier(controldir)
119        ctrlfile = open(os.path.join(controldir, 'control'), 'w')
120
121        fields = []
122        pe = d.getVar('PKGE')
123        if pe and int(pe) > 0:
124            fields.append(["Version: %s:%s-%s\n", ['PKGE', 'PKGV', 'PKGR']])
125        else:
126            fields.append(["Version: %s-%s\n", ['PKGV', 'PKGR']])
127        fields.append(["Description: %s\n", ['DESCRIPTION']])
128        fields.append(["Section: %s\n", ['SECTION']])
129        fields.append(["Priority: %s\n", ['PRIORITY']])
130        fields.append(["Maintainer: %s\n", ['MAINTAINER']])
131        fields.append(["License: %s\n", ['LICENSE']])
132        fields.append(["Architecture: %s\n", ['PACKAGE_ARCH']])
133        fields.append(["OE: %s\n", ['PN']])
134        if d.getVar('HOMEPAGE'):
135            fields.append(["Homepage: %s\n", ['HOMEPAGE']])
136
137        def pullData(l, d):
138            l2 = []
139            for i in l:
140                l2.append(d.getVar(i))
141            return l2
142
143        ctrlfile.write("Package: %s\n" % pkgname)
144        # check for required fields
145        for (c, fs) in fields:
146            for f in fs:
147                if localdata.getVar(f, False) is None:
148                    raise KeyError(f)
149            # Special behavior for description...
150            if 'DESCRIPTION' in fs:
151                summary = localdata.getVar('SUMMARY') or localdata.getVar('DESCRIPTION') or "."
152                ctrlfile.write('Description: %s\n' % summary)
153                description = localdata.getVar('DESCRIPTION') or "."
154                description = textwrap.dedent(description).strip()
155                if '\\n' in description:
156                    # Manually indent: multiline description includes a leading space
157                    for t in description.split('\\n'):
158                        ctrlfile.write(' %s\n' % (t.strip() or ' .'))
159                else:
160                    # Auto indent
161                    ctrlfile.write('%s\n' % textwrap.fill(description, width=74, initial_indent=' ', subsequent_indent=' '))
162            else:
163                ctrlfile.write(c % tuple(pullData(fs, localdata)))
164
165        custom_fields_chunk = get_package_additional_metadata("ipk", localdata)
166        if custom_fields_chunk is not None:
167            ctrlfile.write(custom_fields_chunk)
168            ctrlfile.write("\n")
169
170        mapping_rename_hook(localdata)
171
172        def debian_cmp_remap(var):
173            # In debian '>' and '<' do not mean what it appears they mean
174            #   '<' = less or equal
175            #   '>' = greater or equal
176            # adjust these to the '<<' and '>>' equivalents
177            # Also, "=" specifiers only work if they have the PR in, so 1.2.3 != 1.2.3-r0
178            # so to avoid issues, map this to ">= 1.2.3 << 1.2.3.0"
179            for dep in var:
180                for i, v in enumerate(var[dep]):
181                    if (v or "").startswith("< "):
182                        var[dep][i] = var[dep][i].replace("< ", "<< ")
183                    elif (v or "").startswith("> "):
184                        var[dep][i] = var[dep][i].replace("> ", ">> ")
185                    elif (v or "").startswith("= ") and "-r" not in v:
186                        ver = var[dep][i].replace("= ", "")
187                        var[dep][i] = var[dep][i].replace("= ", ">= ")
188                        var[dep].append("<< " + ver + ".0")
189
190        rdepends = bb.utils.explode_dep_versions2(localdata.getVar("RDEPENDS") or "")
191        debian_cmp_remap(rdepends)
192        rrecommends = bb.utils.explode_dep_versions2(localdata.getVar("RRECOMMENDS") or "")
193        debian_cmp_remap(rrecommends)
194        rsuggests = bb.utils.explode_dep_versions2(localdata.getVar("RSUGGESTS") or "")
195        debian_cmp_remap(rsuggests)
196        # Deliberately drop version information here, not wanted/supported by ipk
197        rprovides = dict.fromkeys(bb.utils.explode_dep_versions2(localdata.getVar("RPROVIDES") or ""), [])
198        rprovides = collections.OrderedDict(sorted(rprovides.items(), key=lambda x: x[0]))
199        debian_cmp_remap(rprovides)
200        rreplaces = bb.utils.explode_dep_versions2(localdata.getVar("RREPLACES") or "")
201        debian_cmp_remap(rreplaces)
202        rconflicts = bb.utils.explode_dep_versions2(localdata.getVar("RCONFLICTS") or "")
203        debian_cmp_remap(rconflicts)
204
205        if rdepends:
206            ctrlfile.write("Depends: %s\n" % bb.utils.join_deps(rdepends))
207        if rsuggests:
208            ctrlfile.write("Suggests: %s\n" % bb.utils.join_deps(rsuggests))
209        if rrecommends:
210            ctrlfile.write("Recommends: %s\n" % bb.utils.join_deps(rrecommends))
211        if rprovides:
212            ctrlfile.write("Provides: %s\n" % bb.utils.join_deps(rprovides))
213        if rreplaces:
214            ctrlfile.write("Replaces: %s\n" % bb.utils.join_deps(rreplaces))
215        if rconflicts:
216            ctrlfile.write("Conflicts: %s\n" % bb.utils.join_deps(rconflicts))
217        ctrlfile.write("Source: %s\n" % recipesource)
218        ctrlfile.close()
219
220        for script in ["preinst", "postinst", "prerm", "postrm"]:
221            scriptvar = localdata.getVar('pkg_%s' % script)
222            if not scriptvar:
223                continue
224            scriptfile = open(os.path.join(controldir, script), 'w')
225            scriptfile.write(scriptvar)
226            scriptfile.close()
227            os.chmod(os.path.join(controldir, script), 0o755)
228
229        conffiles_str = ' '.join(get_conffiles(pkg, d))
230        if conffiles_str:
231            conffiles = open(os.path.join(controldir, 'conffiles'), 'w')
232            for f in conffiles_str.split():
233                if os.path.exists(oe.path.join(root, f)):
234                    conffiles.write('%s\n' % f)
235            conffiles.close()
236
237        os.chdir(basedir)
238        subprocess.check_output("PATH=\"%s\" %s %s %s" % (localdata.getVar("PATH"),
239                                                          d.getVar("OPKGBUILDCMD"), pkg, pkgoutdir),
240                                stderr=subprocess.STDOUT,
241                                shell=True)
242
243        if d.getVar('IPK_SIGN_PACKAGES') == '1':
244            ipkver = "%s-%s" % (localdata.getVar('PKGV'), localdata.getVar('PKGR'))
245            ipk_to_sign = "%s/%s_%s_%s.ipk" % (pkgoutdir, pkgname, ipkver, localdata.getVar('PACKAGE_ARCH'))
246            sign_ipk(d, ipk_to_sign)
247
248    finally:
249        cleanupcontrol(root)
250        bb.utils.unlockfile(lf)
251
252# Have to list any variables referenced as X_<pkg> that aren't in pkgdata here
253IPKEXTRAVARS = "PRIORITY MAINTAINER PACKAGE_ARCH HOMEPAGE PACKAGE_ADD_METADATA_IPK"
254ipk_write_pkg[vardeps] += "${@gen_packagevar(d, 'IPKEXTRAVARS')}"
255
256# Otherwise allarch packages may change depending on override configuration
257ipk_write_pkg[vardepsexclude] = "OVERRIDES"
258
259
260SSTATETASKS += "do_package_write_ipk"
261do_package_write_ipk[sstate-inputdirs] = "${PKGWRITEDIRIPK}"
262do_package_write_ipk[sstate-outputdirs] = "${DEPLOY_DIR_IPK}"
263
264python do_package_write_ipk_setscene () {
265    tmpdir = d.getVar('TMPDIR')
266
267    if os.access(os.path.join(tmpdir, "stamps", "IPK_PACKAGE_INDEX_CLEAN"), os.R_OK):
268        os.unlink(os.path.join(tmpdir, "stamps", "IPK_PACKAGE_INDEX_CLEAN"))
269
270    sstate_setscene(d)
271}
272addtask do_package_write_ipk_setscene
273
274python () {
275    if d.getVar('PACKAGES') != '':
276        deps = ' opkg-utils-native:do_populate_sysroot virtual/fakeroot-native:do_populate_sysroot xz-native:do_populate_sysroot'
277        d.appendVarFlag('do_package_write_ipk', 'depends', deps)
278        d.setVarFlag('do_package_write_ipk', 'fakeroot', "1")
279}
280
281python do_package_write_ipk () {
282    bb.build.exec_func("read_subpackage_metadata", d)
283    bb.build.exec_func("do_package_ipk", d)
284}
285do_package_write_ipk[dirs] = "${PKGWRITEDIRIPK}"
286do_package_write_ipk[cleandirs] = "${PKGWRITEDIRIPK}"
287do_package_write_ipk[depends] += "${@oe.utils.build_depends_string(d.getVar('PACKAGE_WRITE_DEPS'), 'do_populate_sysroot')}"
288addtask package_write_ipk after do_packagedata do_package do_deploy_source_date_epoch before do_build
289do_build[rdeptask] += "do_package_write_ipk"
290
291PACKAGEINDEXDEPS += "opkg-utils-native:do_populate_sysroot"
292PACKAGEINDEXDEPS += "opkg-native:do_populate_sysroot"
293