pmbootstrap/pmb/parse/_apkbuild.py

249 lines
8.8 KiB
Python
Raw Normal View History

2017-05-26 20:08:45 +00:00
"""
Copyright 2018 Oliver Smith
2017-05-26 20:08:45 +00:00
This file is part of pmbootstrap.
pmbootstrap is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pmbootstrap is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with pmbootstrap. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import logging
2017-05-26 20:08:45 +00:00
import pmb.config
import pmb.parse.version
2017-05-26 20:08:45 +00:00
def replace_variables(apkbuild):
"""
Replace a hardcoded list of variables inside the APKBUILD.
"""
ret = apkbuild
# _flavor: ${_device} (lineageos kernel packages)
ret["_flavor"] = ret["_flavor"].replace("${_device}",
ret["_device"])
# pkgname: $_flavor
ret["pkgname"] = ret["pkgname"].replace("${_flavor}", ret["_flavor"])
# subpackages, *depends*: $pkgname
for key in ["subpackages", "depends", "makedepends", "makedepends_host",
"makedepends_build"]:
replaced = []
for subpackage in ret[key]:
replaced.append(subpackage.replace("$pkgname", ret["pkgname"]))
ret[key] = replaced
2017-05-26 20:08:45 +00:00
2017-06-05 01:58:45 +00:00
# makedepends: $makedepends_host, $makedepends_build, $_llvmver
2017-05-26 20:08:45 +00:00
replaced = []
for makedepend in ret["makedepends"]:
if makedepend.startswith("$"):
key = makedepend[1:]
if key in ret:
replaced += ret[key]
else:
raise RuntimeError("Could not resolve variable " +
makedepend + " in APKBUILD of " +
apkbuild["pkgname"])
else:
# replace in the middle of the string
for var in ["_llvmver"]:
makedepend = makedepend.replace("$" + var, ret[var])
replaced += [makedepend]
# Python: ${pkgname#py-}
if ret["pkgname"].startswith("py-"):
replacement = ret["pkgname"][3:]
for var in ["depends", "makedepends", "subpackages"]:
for i in range(len(ret[var])):
ret[var][i] = ret[var][i].replace(
"${pkgname#py-}", replacement)
2017-05-26 20:08:45 +00:00
ret["makedepends"] = replaced
return ret
def cut_off_function_names(apkbuild):
"""
For subpackages: only keep the subpackage name, without the internal
function name, that tells how to build the subpackage.
"""
sub = apkbuild["subpackages"]
for i in range(len(sub)):
sub[i] = sub[i].split(":", 1)[0]
apkbuild["subpackages"] = sub
return apkbuild
aportgen: Gracefully handle old aports_upstream (#1291) In order to get cross-compilers, we generate a few aports (e.g. binutils-armhf, gcc-armhf) automatically from Alpine's aports. pmbootstrap was already able to perform a git checkout of Alpine's aports repository. But it needed to be manually updated. Otherwise the `pmbootstrap aportgen` command could actually downgrade the aport instead of updating it to the current version. After thinking about adding a dedicated pmbootstrap command for updating git repositories, I thought it would be better to not open that can of worms (pmbootstrap as general git wrapper? no thanks). The solution implemented here compares the upstream aport version of the git checkout of a certain package (e.g. gcc for gcc-armhf) with the version in Alpine's binary package APKINDEX. When the aport version is lower than the binary package version, it shows the user how to update the git repository with just one command: pmbootstrap chroot --add=git --user -- \ git -C /mnt/pmbootstrap-git/aports_upstream pull Changes: * `pmb.aportgen.core.get_upstream_aport()`: new function, that returns the absolute path to the upstream aport on disk, after checking the version of the aport against the binary package. * Use that new function in pmb.aportgen.gcc and pmb.aportgen.binutils * New function `pmb.helpers.repo.alpine_apkindex_path()`: updates the APKINDEX if necessary and returns the absolute path to the APKINDEX. This code was basically present already, but not as function, so now we have a bit less overhead there. * `pmbootstrap chroot`: new `--user` argument * `pmb.parse.apkbuild`: make pkgname check optional, as it fails with the official gcc APKBUILD before we modify it (the current APKBUILD parser is not meant to be perfect, as this would require a full shell parsing implementation). * Extended `test_aportgen.py` and enabled it by default in `testcases_fast.sh`. Previously it was disabled due to traffic concerns (cloning the aports repo, but then again we do a full KDE plasma mobile installation in Travis now, so that shouldn't matter too much). * `testcases_fast.sh`: With "test_aport_in_sync_with_git" removed from the disabled-by-default list (left over from timestamp based rebuilds), there were no more test cases disabled by default. I've changed it, so now the qemu_running_processes test case is disabled, and added an `--all` parameter to the script to disable no test cases. Travis runs with the `--all` parameter while it's useful to do a quick local test without `--all` in roughly 2 minutes instead of 10. * `aports/cross/binutils-*`: Fix `_mirror` variable to point to current default Alpine mirror (so the aportgen testcase runs through).
2018-03-11 14:18:21 +00:00
def apkbuild(args, path, check_pkgver=True, check_pkgname=True):
2017-05-26 20:08:45 +00:00
"""
Parse relevant information out of the APKBUILD file. This is not meant
to be perfect and catch every edge case (for that, a full shell parser
would be necessary!). Instead, it should just work with the use-cases
covered by pmbootstrap and not take too long.
2018-11-15 07:36:39 +00:00
Run 'pmbootstrap apkbuild_parse hello-world' for a full output example.
2017-05-26 20:08:45 +00:00
:param path: full path to the APKBUILD
aportgen: Gracefully handle old aports_upstream (#1291) In order to get cross-compilers, we generate a few aports (e.g. binutils-armhf, gcc-armhf) automatically from Alpine's aports. pmbootstrap was already able to perform a git checkout of Alpine's aports repository. But it needed to be manually updated. Otherwise the `pmbootstrap aportgen` command could actually downgrade the aport instead of updating it to the current version. After thinking about adding a dedicated pmbootstrap command for updating git repositories, I thought it would be better to not open that can of worms (pmbootstrap as general git wrapper? no thanks). The solution implemented here compares the upstream aport version of the git checkout of a certain package (e.g. gcc for gcc-armhf) with the version in Alpine's binary package APKINDEX. When the aport version is lower than the binary package version, it shows the user how to update the git repository with just one command: pmbootstrap chroot --add=git --user -- \ git -C /mnt/pmbootstrap-git/aports_upstream pull Changes: * `pmb.aportgen.core.get_upstream_aport()`: new function, that returns the absolute path to the upstream aport on disk, after checking the version of the aport against the binary package. * Use that new function in pmb.aportgen.gcc and pmb.aportgen.binutils * New function `pmb.helpers.repo.alpine_apkindex_path()`: updates the APKINDEX if necessary and returns the absolute path to the APKINDEX. This code was basically present already, but not as function, so now we have a bit less overhead there. * `pmbootstrap chroot`: new `--user` argument * `pmb.parse.apkbuild`: make pkgname check optional, as it fails with the official gcc APKBUILD before we modify it (the current APKBUILD parser is not meant to be perfect, as this would require a full shell parsing implementation). * Extended `test_aportgen.py` and enabled it by default in `testcases_fast.sh`. Previously it was disabled due to traffic concerns (cloning the aports repo, but then again we do a full KDE plasma mobile installation in Travis now, so that shouldn't matter too much). * `testcases_fast.sh`: With "test_aport_in_sync_with_git" removed from the disabled-by-default list (left over from timestamp based rebuilds), there were no more test cases disabled by default. I've changed it, so now the qemu_running_processes test case is disabled, and added an `--all` parameter to the script to disable no test cases. Travis runs with the `--all` parameter while it's useful to do a quick local test without `--all` in roughly 2 minutes instead of 10. * `aports/cross/binutils-*`: Fix `_mirror` variable to point to current default Alpine mirror (so the aportgen testcase runs through).
2018-03-11 14:18:21 +00:00
:param check_pkgver: verify that the pkgver is valid.
:param check_pkgname: the pkgname must match the name of the aport folder
:returns: relevant variables from the APKBUILD. Arrays get returned as
arrays.
2017-05-26 20:08:45 +00:00
"""
Properly rebuild/install packages when something changed (Fix #120, #108, #131) (#129) TLDR: Always rebuild/install packages when something changed when executing "pmbootstrap install/initfs/flash", more speed in dependency resolution. --- pmbootstrap has already gotten some support for "timestamp based rebuilds", which modifies the logic for when packages should be rebuilt. It doesn't only consider packages outdated with old pkgver/pkgrel combinations, but also packages, where a source file has a newer timestamp, than the built package has. I've found out, that this can lead to more rebuilds than expected. For example, when you check out the pmbootstrap git repository again into another folder, although you have already built packages. Then all files have the timestamp of the checkout, and the packages will appear to be outdated. While this is not largely a concern now, this will become a problem once we have a binary package repository, because then the packages from the binary repo will always seem to be outdated, if you just freshly checked out the repository. To combat this, git gets asked if the files from the aport we're looking at are in sync with upstream, or not. Only when the files are not in sync with upstream and the timestamps of the sources are newer, a rebuild gets triggered from now on. In case this logic should fail, I've added an option during "pmbootstrap init" where you can enable or disable the "timestamp based rebuilds" option. In addition to that, this commit also works on fixing #120: packages do not get updated in "pmbootstrap install" after they have been rebuilt. For this to work, we specify all packages explicitly for abuild, instead of letting abuild do the resolving. This feature will also work with the "timestamp based rebuilds". This commit also fixes the working_dir argument in pmb.helpers.run.user, which was simply ignored before. Finally, the performance of the dependency resolution is faster again (when compared to the current version in master), because the parsed apkbuilds and finding the aport by pkgname gets cached during one pmbootstrap call (in args.cache, which also makes it easy to put fake data there in testcases). The new dependency resolution code can output lots of verbose messages for debugging by specifying the `-v` parameter. The meaning of that changed, it used to output the file names where log messages come from, but no one seemed to use that anyway.
2017-07-10 15:23:43 +00:00
# Try to get a cached result first (we assume, that the aports don't change
# in one pmbootstrap call)
if path in args.cache["apkbuild"]:
return args.cache["apkbuild"][path]
# Read the file and check line endings
2017-05-26 20:08:45 +00:00
with open(path, encoding="utf-8") as handle:
lines = handle.readlines()
if handle.newlines != '\n':
raise RuntimeError("Wrong line endings in APKBUILD: " + path)
2017-05-26 20:08:45 +00:00
# Parse all attributes from the config
ret = {}
for i in range(len(lines)):
for attribute, options in pmb.config.apkbuild_attributes.items():
if not lines[i].startswith(attribute + "="):
continue
# Extend the line value until we reach the ending quote sign
line_value = lines[i][len(attribute + "="):-1]
end_char = None
if line_value.startswith("\""):
end_char = "\""
value = ""
first_line = i
2017-05-26 20:08:45 +00:00
while i < len(lines) - 1:
value += line_value.replace("\"", "").strip()
if not end_char:
2017-05-26 20:08:45 +00:00
break
elif line_value.endswith(end_char):
# This check is needed to allow line break directly after opening quote
if i != first_line or line_value.count(end_char) > 1:
break
2017-05-26 20:08:45 +00:00
value += " "
i += 1
line_value = lines[i][:-1]
# Split up arrays, delete empty strings inside the list
if options["array"]:
if value:
value = list(filter(None, value.split(" ")))
else:
value = []
ret[attribute] = value
# Add missing keys
2017-05-26 20:08:45 +00:00
for attribute, options in pmb.config.apkbuild_attributes.items():
if attribute not in ret:
if options["array"]:
ret[attribute] = []
else:
ret[attribute] = ""
# Properly format values
ret = replace_variables(ret)
ret = cut_off_function_names(ret)
# Sanity check: pkgname
suffix = "/" + ret["pkgname"] + "/APKBUILD"
aportgen: Gracefully handle old aports_upstream (#1291) In order to get cross-compilers, we generate a few aports (e.g. binutils-armhf, gcc-armhf) automatically from Alpine's aports. pmbootstrap was already able to perform a git checkout of Alpine's aports repository. But it needed to be manually updated. Otherwise the `pmbootstrap aportgen` command could actually downgrade the aport instead of updating it to the current version. After thinking about adding a dedicated pmbootstrap command for updating git repositories, I thought it would be better to not open that can of worms (pmbootstrap as general git wrapper? no thanks). The solution implemented here compares the upstream aport version of the git checkout of a certain package (e.g. gcc for gcc-armhf) with the version in Alpine's binary package APKINDEX. When the aport version is lower than the binary package version, it shows the user how to update the git repository with just one command: pmbootstrap chroot --add=git --user -- \ git -C /mnt/pmbootstrap-git/aports_upstream pull Changes: * `pmb.aportgen.core.get_upstream_aport()`: new function, that returns the absolute path to the upstream aport on disk, after checking the version of the aport against the binary package. * Use that new function in pmb.aportgen.gcc and pmb.aportgen.binutils * New function `pmb.helpers.repo.alpine_apkindex_path()`: updates the APKINDEX if necessary and returns the absolute path to the APKINDEX. This code was basically present already, but not as function, so now we have a bit less overhead there. * `pmbootstrap chroot`: new `--user` argument * `pmb.parse.apkbuild`: make pkgname check optional, as it fails with the official gcc APKBUILD before we modify it (the current APKBUILD parser is not meant to be perfect, as this would require a full shell parsing implementation). * Extended `test_aportgen.py` and enabled it by default in `testcases_fast.sh`. Previously it was disabled due to traffic concerns (cloning the aports repo, but then again we do a full KDE plasma mobile installation in Travis now, so that shouldn't matter too much). * `testcases_fast.sh`: With "test_aport_in_sync_with_git" removed from the disabled-by-default list (left over from timestamp based rebuilds), there were no more test cases disabled by default. I've changed it, so now the qemu_running_processes test case is disabled, and added an `--all` parameter to the script to disable no test cases. Travis runs with the `--all` parameter while it's useful to do a quick local test without `--all` in roughly 2 minutes instead of 10. * `aports/cross/binutils-*`: Fix `_mirror` variable to point to current default Alpine mirror (so the aportgen testcase runs through).
2018-03-11 14:18:21 +00:00
if check_pkgname:
if not os.path.realpath(path).endswith(suffix):
logging.info("Folder: '" + os.path.dirname(path) + "'")
logging.info("Pkgname: '" + ret["pkgname"] + "'")
raise RuntimeError("The pkgname must be equal to the name of"
" the folder, that contains the APKBUILD!")
# Sanity check: arch
if not len(ret["arch"]):
raise RuntimeError("Arch must not be empty: " + path)
# Sanity check: pkgver
if check_pkgver:
if "-r" in ret["pkgver"] or not pmb.parse.version.validate(ret["pkgver"]):
logging.info("NOTE: Valid pkgvers are described here:")
logging.info("<https://wiki.alpinelinux.org/wiki/APKBUILD_Reference#pkgver>")
raise RuntimeError("Invalid pkgver '" + ret["pkgver"] +
"' in APKBUILD: " + path)
# Fill cache
Properly rebuild/install packages when something changed (Fix #120, #108, #131) (#129) TLDR: Always rebuild/install packages when something changed when executing "pmbootstrap install/initfs/flash", more speed in dependency resolution. --- pmbootstrap has already gotten some support for "timestamp based rebuilds", which modifies the logic for when packages should be rebuilt. It doesn't only consider packages outdated with old pkgver/pkgrel combinations, but also packages, where a source file has a newer timestamp, than the built package has. I've found out, that this can lead to more rebuilds than expected. For example, when you check out the pmbootstrap git repository again into another folder, although you have already built packages. Then all files have the timestamp of the checkout, and the packages will appear to be outdated. While this is not largely a concern now, this will become a problem once we have a binary package repository, because then the packages from the binary repo will always seem to be outdated, if you just freshly checked out the repository. To combat this, git gets asked if the files from the aport we're looking at are in sync with upstream, or not. Only when the files are not in sync with upstream and the timestamps of the sources are newer, a rebuild gets triggered from now on. In case this logic should fail, I've added an option during "pmbootstrap init" where you can enable or disable the "timestamp based rebuilds" option. In addition to that, this commit also works on fixing #120: packages do not get updated in "pmbootstrap install" after they have been rebuilt. For this to work, we specify all packages explicitly for abuild, instead of letting abuild do the resolving. This feature will also work with the "timestamp based rebuilds". This commit also fixes the working_dir argument in pmb.helpers.run.user, which was simply ignored before. Finally, the performance of the dependency resolution is faster again (when compared to the current version in master), because the parsed apkbuilds and finding the aport by pkgname gets cached during one pmbootstrap call (in args.cache, which also makes it easy to put fake data there in testcases). The new dependency resolution code can output lots of verbose messages for debugging by specifying the `-v` parameter. The meaning of that changed, it used to output the file names where log messages come from, but no one seemed to use that anyway.
2017-07-10 15:23:43 +00:00
args.cache["apkbuild"][path] = ret
2017-05-26 20:08:45 +00:00
return ret
Make proprietary drivers optional (1/2): pmbootstrap changes (#1254) Here are the changes necessary in pmbootstrap to make proprietary software installed onto the device (firmware and userspace drivers) optional (#756). To full close the issue, we need to apply this concept to all device packages we already have in a follow-up PR. Changes: * New config file options nonfree_firmware and nonfree_userland, which we ask for during "pmbootstrap init" if there are non-free components for the selected device. * We find that out by checking the APKBUILD's subpakages: The non-free packages are called $pkgname-nonfree-firmware and $pkgname-nonfree-userland. * During "pmbootstrap init" we also show the pkgdesc of these subpackages. Parsing that is implemented in pmb.parse._apkbuild.subpkgdesc(). It was not implemented as part of the regular APKBUILD parsing, as this would need a change in the output format, and it is a lot *less* code if done like in this commit. * pmb/parse/apkbuild.py was renamed to _apkbuild.py, and pmb/install/install.py to _install.py: needed to call the function in the usual way (e.g. pmb.parse.apkbuild()) but still being able to test the individual functions from these files in the test suite. We did the same thing for pmb/build/_package.py already. * Install: New function get_nonfree_packages() returns the non-free packages that will be installed, based on the user's choice in "pmbootstrap init" and on the subpackages the device has. * Added test cases and test data (APKBUILDs) for all new code, refactored test/test_questions.py to have multiple functions for testing the various questions / question types from "pmbootstrap init" instead of having it all in one big function. This allows to use another aport folder for testing the new non-free related questions in init.
2018-02-24 21:49:10 +00:00
def subpkgdesc(path, function):
"""
Get the pkgdesc of a subpackage in an APKBUILD.
:param path: to the APKBUILD file
:param function: name of the subpackage (e.g. "nonfree_userland")
:returns: the subpackage's pkgdesc
"""
# Read all lines
with open(path, encoding="utf-8") as handle:
lines = handle.readlines()
# Prefixes
prefix_function = function + "() {"
prefix_pkgdesc = "\tpkgdesc=\""
# Find the pkgdesc
in_function = False
for line in lines:
if in_function:
if line.startswith(prefix_pkgdesc):
return line[len(prefix_pkgdesc):-2]
elif line.startswith(prefix_function):
in_function = True
# Failure
if not in_function:
raise RuntimeError("Could not find subpackage function, no line starts"
" with '" + prefix_function + "' in " + path)
raise RuntimeError("Could not find pkgdesc of subpackage function '" +
function + "' (spaces used instead of tabs?) in " +
path)
pmbootstrap init: kernel selection / remove linux-pmos-lts (#1363) * As discussed in IRC/matrix, we're removing `linux-postmarketos-lts` for now. The kernel isn't used right now, and we save lots of maintenance effort with not updating it every week or so. * new config option `"kernel"` with possible values: `"downstream", "mainline", "stable"` (downstream is always `linux-$devicename`) * ask for the kernel during `pmbootstrap init` if the device package has kernel subpackages and install it in `_install.py` * postmarketos-mkinitfs: display note instead of exit with error when the `deviceinfo_dtb` file is missing (because we expect it to be missing for downstream kernels) * device-sony-amami: * add kernel subpackages for downstream, mainline * set `deviceinfo_dtb` * device-qemu-amd64: add kernel subpackages for stable, lts, mainline * test cases and test data for new functions * test case that checks all aports for right usage of the feature: * don't mix specifying kernels in depends *and* subpackages * 1 kernel in depends is maximum * kernel subpackages must have a valid name * Test if devices packages reference at least one kernel * Remove `_build_device_depends_note()` which informs the user that `--ignore-depends` can be used with device packages to avoid building the kernel. The idea was to make the transition easier after a change we did months ago, and now the kernel doesn't always get built before building the device package so it's not relevant anymore. * pmb/chroot/other.py: * Add autoinstall=True to kernel_flavors_installed(). When the flag is set, the function makes sure that at least one kernel for the device is installed. * Remove kernel_flavor_autodetect() function, wherever it was used, it has been replaced with kernel_flavors_installed()[0]. * pmb.helpers.frontend.py: remove code to install at least one kernel, kernel_flavors_installed() takes care of that now.
2018-04-03 23:50:09 +00:00
def kernels(args, device):
"""
Get the possible kernels from a device-* APKBUILD.
:param device: the device name, e.g. "lg-mako"
:returns: None when the kernel is hardcoded in depends
:returns: kernel types and their description (as read from the subpackages)
possible types: "downstream", "stable", "mainline"
example: {"mainline": "Mainline description",
"downstream": "Downstream description"}
"""
# Read the APKBUILD
apkbuild_path = args.aports + "/device/device-" + device + "/APKBUILD"
if not os.path.exists(apkbuild_path):
return None
subpackages = apkbuild(args, apkbuild_path)["subpackages"]
# Read kernels from subpackages
ret = {}
subpackage_prefix = "device-" + device + "-kernel-"
for subpackage in subpackages:
if not subpackage.startswith(subpackage_prefix):
continue
name = subpackage[len(subpackage_prefix):]
func = "kernel_" + name
desc = pmb.parse._apkbuild.subpkgdesc(apkbuild_path, func)
ret[name] = desc
# Return
if ret:
return ret
return None