Forked from
Eclipse Projects / Oniro Core / Oniro
22 commits behind the upstream repository.
-
Andrei Gherzan authored
Signed-off-by:
Andrei Gherzan <andrei.gherzan@huawei.com>
Andrei Gherzan authoredSigned-off-by:
Andrei Gherzan <andrei.gherzan@huawei.com>
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
upgrade_oniro.py 31.80 KiB
#!/usr/bin/python
# SPDX-FileCopyrightText: Huawei Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# A tool to upgrade to a newer version of Oniro
# Steps to upgrade:
# 1. Get the input from the user:
# 1.1. Target version
# 1.2. Build directory, can be empty or not and this will define some additional checks to perform
# 1.3. Machine and target to build, in order to test the upgraded build we need to know these things
# 1.4. Optional: Conf directory path, this can be specified in order to use a specific config directory.
# In case we have a clean build directory and this is not specified the default config will be used.
# 1.5. Flavour. The flavour of Oniro in use (Linux, Zephyr,Freertos...).
# 1.6. Optional Flag: --dry-run: this enables the upgrade tool to create a local copy of the project and perform the upgrade on it.
# 1.7. Oniro path: Path to the Oniro project folder, which contains the "oniro" folder and other "meta-" folders in it.
#
# 2. Upgrade tool pre-upgrade checks.
# 2.1 Check if the target version of Oniro is newer than the current one
# 2.2 Check if possible if an updated version of the tool exist. If it's impossible to access the gitlab repository,
# for example due to missing internet connection, a specific error message will be printed.
# 2.3 If the newest version of Oniro has a new version of this script it should be upgraded before
# Oniro's upgrade, then it should be run instead of the old one.
#
# 3. Additional pre-upgrade checks:
# 3.1 Check if the flavor is correct if the conf dir is specified
#
# 4. Pre-upgrade backup to ensure that if something goes wrong we can restore a good state of the build.
# Option to also backup the build (tmp dir excluded) if the build directory is not empty.
#
# 5. Update:
# 5.1. Sync the repos
# 5.2. Update the .bbappends files (needs user confirmation) if needed
# 5.2. Run the script to init the environment
# 5.3. If specified copy the conf directory
# 5.4. Update the configs
# 5.5. If present delete the tmp directory
# 5.6. Build the target (needs user confirmation) and print updated conf and .bbappend files.
# These will be printed before building if the build part is skipped.
# 6. In case of error let the user know that they can restore the old version using this tool
#
import argparse
from distutils.command.build import build
import pathlib
import tarfile
import os
import shutil
import sys
script_description = "[WIP] A tool to upgrade to a newer version of Oniro"
# Script options
command = ""
# Upgrade options
target_version = ""
machine = ""
flavour = ""
image = ""
conf_directory = None
dry_run = False
store_backup = False
target_list = []
# Backup options
verbose_backup = False
extra_folders = []
# Restore options
backup_archive_arg = ""
# Global vars
backup_archive_name = ""
oniro_path = None
build_directory = None
def init_script_options():
"""
Initialize script options.
Get user parameters as arguments which will define the action of this script
and initialize the main global variables.
Returns:
None.
"""
import subprocess
parser = argparse.ArgumentParser(description=script_description)
subparsers = parser.add_subparsers(dest="command")
global target_list
target_list = [
"v0.1.0-rc1",
"v0.1.0",
"v1.0.0-alpha",
"v1.0.0-beta",
"v1.0.0-rc",
"v1.0.0-rc2",
"v2.0.0-alpha",
"v2.0.0-alpha2",
"v2.0.0-beta",
"v2.0.0",
"kirkstone",
]
# Build subcommand
build_parser = subparsers.add_parser(
"build", help="Build target with current Oniro setup."
)
build_parser.add_argument(
"build-directory",
type=pathlib.Path,
help="Path to the build directory you want to use",
)
build_parser.add_argument(
"-m",
"--machine",
type=str,
default="qemux86-64",
choices=[
"qemux86",
"qemux86-64",
"seco-intel-b68",
"seco-imx8mm-c61-2gb",
"seco-imx8mm-c61-4gb",
"seco-px30-d23",
"raspberrypi4-64",
],
help="The target machine for the Oniro build. (qemux86-64 by default)",
)
build_parser.add_argument(
"-f",
"--flavour",
type=str,
default="linux",
choices=[
"linux",
"freertos",
"zephyr",
],
help="The flavour for the Oniro build. (linux by default)",
)
build_parser.add_argument(
"-i",
"--image",
type=str,
default="oniro-image-base",
choices=[
"oniro-image-base",
"oniro-image-base-dev",
"oniro-image-base-tests",
"oniro-image-common",
"oniro-image-extra",
"oniro-image-extra-dev",
"oniro-image-extra-tests",
],
help="The image that will be built (oniro-image-base by default)",
)
build_parser.add_argument(
"oniro-path",
type=pathlib.Path,
help="Path to Oniro project, which contains the oniro folder and other meta- folders",
)
# Upgrade subcommand
upgrade_parser = subparsers.add_parser("upgrade", help="Upgrade Oniro.")
upgrade_parser.add_argument(
"-tv",
"--target-version",
type=str,
default="kirkstone",
choices=target_list,
help="Specify the target version of Oniro you want to upgrade to. (kirkstone by default)",
)
upgrade_parser.add_argument(
"build-directory",
type=pathlib.Path,
help="Path to the build directory you want to use",
)
upgrade_parser.add_argument(
"-m",
"--machine",
type=str,
default="qemux86-64",
choices=[
"qemux86",
"qemux86-64",
"seco-intel-b68",
"seco-imx8mm-c61-2gb",
"seco-imx8mm-c61-4gb",
"seco-px30-d23",
"raspberrypi4-64",
],
help="The target machine for the Oniro build. (qemux86-64 by default)",
)
upgrade_parser.add_argument(
"-f",
"--flavour",
type=str,
choices=[
"linux",
"freertos",
"zephyr",
],
default="linux",
help="The flavour for the Oniro build. (linux by default)",
)
upgrade_parser.add_argument(
"-i",
"--image",
type=str,
default="oniro-image-base",
choices=[
"oniro-image-base",
"oniro-image-base-dev",
"oniro-image-base-tests",
"oniro-image-common",
"oniro-image-extra",
"oniro-image-extra-dev",
"oniro-image-extra-tests",
],
help="The image that will be built to check if the upgrade is successful. (oniro-image-base by default)",
)
upgrade_parser.add_argument(
"-c",
"--conf-directory",
type=pathlib.Path,
help="Path to the config directory you want to use. If omitted the default configs will be use.",
)
upgrade_parser.add_argument(
"--dry-run",
action="store_true",
help="Perform the upgrade on a local copy of the project.",
)
upgrade_parser.add_argument(
"--store-backup",
action="store_true",
help="Store the backup even if the upgrade was successful.",
)
upgrade_parser.add_argument(
"oniro-path",
type=pathlib.Path,
help="Path to Oniro project, which contains the oniro folder and other meta- folders",
)
# Backup subcommand
backup_parser = subparsers.add_parser("backup", help="Backup Oniro manually.")
backup_parser.add_argument(
"-v", "--verbose", action="store_true", help="Activate verbose output mode"
)
backup_parser.add_argument(
"-ef",
"--extra-folders",
action="extend",
nargs="+",
type=pathlib.Path,
help="Specify a list of extra folders to backup",
)
backup_parser.add_argument(
"oniro-path",
type=pathlib.Path,
help="Path to Oniro project, which contains the oniro folder and other meta- folders",
)
backup_parser.add_argument(
"-bd",
"--build-directory",
type=pathlib.Path,
default=None,
help="Path to the build directory you want to use",
)
# Restore subcommand
restore_parser = subparsers.add_parser("restore", help="Restore a local backup.")
restore_parser.add_argument(
"backup_archive_arg",
type=str,
help="Specify the path of a local backup archive to restore. Use 'latest' to use the latest backup found.",
)
restore_parser.add_argument(
"oniro-path",
type=pathlib.Path,
help="Path to Oniro project, which contains the oniro folder and other meta- folders",
)
parsed_args = vars(parser.parse_args())
global command
command = parsed_args["command"]
if command == "upgrade":
global target_version, build_directory, machine, flavour, image, conf_directory, dry_run, store_backup, oniro_path
image = parsed_args["image"]
target_version = parsed_args["target_version"]
build_directory = parsed_args["build-directory"]
machine = parsed_args["machine"]
flavour = parsed_args["flavour"]
conf_directory = parsed_args["conf_directory"]
dry_run = parsed_args["dry_run"]
store_backup = parsed_args["store_backup"]
oniro_path = parsed_args["oniro-path"]
elif command == "backup":
global verbose_backup, extra_folders
verbose_backup = parsed_args["verbose"]
extra_folders = parsed_args["extra_folders"]
oniro_path = parsed_args["oniro-path"]
build_directory = parsed_args["build_directory"]
elif command == "restore":
global backup_archive_arg
backup_archive_arg = parsed_args["backup_archive_arg"]
oniro_path = parsed_args["oniro-path"]
elif command == "build":
build_directory = parsed_args["build-directory"]
machine = parsed_args["machine"]
flavour = parsed_args["flavour"]
image = parsed_args["image"]
oniro_path = parsed_args["oniro-path"]
def upgrade_tool():
"""
Verify that the target version of Oniro is newer than the current one.
Check if a newer version of the upgrade_oniro and upgrade_oniro_utils python scripts
exist for the target version of Oniro. If a newer version of upgrade_oniro exists locally,
it has to be executed instead of the older version.
Returns:
0 if the target version of Oniro is not newer than the current one.
1 if a newer version of the upgrade_oniro script is found in the current directory.
2 if the current version of upgrade_oniro is the correct one for the target version of Oniro.
3 if a newer versipn of upgrade_oniro has been downloaded.
4 if it was not possible to search for an updated version of the tool (for example if the script is executed offline)
"""
import platform
import re
import requests
current_version = ""
os_name = platform.system()
os_name = os_name.lower()
pos_current = 0
pos_target = 0
with open(
f"{oniro_path}/oniro/meta-oniro-core/conf/distro/oniro-" + os_name + ".conf"
) as file:
data = file.readlines()
# Get the current version of Oniro. To check whether the target version
# is newer than the current one, we can find their position in the list
# composed of all the available version, since it's sorted by default.
for line in data:
if line.startswith("DISTRO_VERSION"):
current_version = re.findall(r'"([^"]*)"', line)[0]
break
for version in target_list:
if version == current_version:
break
elif "v" + current_version == version:
break
pos_current = pos_current + 1
for version in target_list:
if version == target_version:
break
elif "v" + target_version == version:
break
pos_target = pos_target + 1
if pos_target <= pos_current:
print(
"The target version chosen is not newer than the current oniro version, quitting..."
)
return 0
# find update for upgrade_oniro_utils.py for the target version, if it exists
# the try/except command will also verify if the user is not offline
try:
response_utils = requests.get(
f"https://gitlab.eclipse.org/eclipse/oniro-core/oniro/-/raw/{target_version}/scripts/upgrade_tool/upgrade_oniro_utils.py"
)
except Exception:
print(
"It was not possible to search for an updated version of the tool, please check your internet connection and retry, quitting..."
)
return 4
if response_utils.status_code != 404:
print(
"A newer version of upgrade_oniro_utils.py exists for the target version of Oniro, the older version will be updated..."
)
new_utils_code = response_utils.text
with open("upgrade_oniro_utils.py", "w") as f:
f.write(new_utils_code)
# find updated version of the current script upgrade_oniro, either locally in this directory or in the right repository on gitlab
# if it exists, then the new version should be run instead and it will have the same name as this file
# plus a suffix of the target version
current_file_name = sys.argv[0].split("/")[-1]
new_file_name = current_file_name.split(".")[:-1]
new_file_name = ".".join(new_file_name)
new_file_name = new_file_name + "_" + target_version + ".py"
if current_file_name == new_file_name:
return 2
if os.path.isfile(new_file_name):
print(
"A newer version of this script has been found in the current directory, please execute the more recent version instead of this one, quitting..."
)
return 1
response = requests.get(
f"https://gitlab.eclipse.org/eclipse/oniro-core/oniro/-/raw/{target_version}/scripts/upgrade_tool/upgrade_oniro.py"
)
if response.status_code == 404:
return 2
new_version_code = response.text
print(new_file_name)
print(
f"A newer version of this script exist for the target version of Oniro, it will be downloaded in the current directory as {new_file_name}"
)
with open(new_file_name, "w") as f:
f.write(new_version_code)
print(
"The newer script has been downloaded, please execute the updated version instead of this one, quitting..."
)
return 3
def perform_pre_upgrade_checks():
"""
Perform pre-upgrade checks.
Check if the flavour chosen by the user is the correct one
if the conf directory is provided.
Returns:
0 if the flavour is incorrect.
1 if the flavour is correct.
"""
# check if flavour is correct given conf directory
if conf_directory is not None and conf_directory.exists():
if os.path.isfile(f"{conf_directory}/templateconf.cfg"):
with open(f"{conf_directory}/templateconf.cfg", "r") as file:
conf_data = file.readlines()
for line in conf_data:
if line.strip().endswith("linux"):
if flavour != "linux":
print("The flavour inserted is incorrect, quitting...")
return 0
elif line.strip().endswith("zephyr"):
if flavour != "zephyr":
print("The flavour inserted is incorrect, quitting...")
return 0
elif line.strip().endswith("freertos"):
if flavour != "freertos":
print("The flavour inserted is incorrect, quitting...")
return 0
def backup_oniro():
"""
Create a backup of Oniro.
This function creates a backup of Oniro containing the following files:
- all the layers specified in the Oniro Manifest
- .repo folder
- `build_directory` if it exists, excluding tmp sub-folders
- all the folders starting with "meta-"
- all the folders / files in `extra_folders`
The backup file will contain also a text file with a list of all the
folders that have been saved, this will be used to delete them
in the `restore_oniro` function.
Returns:
None. Side effects the creation of a backup in './upgrade_oniro_backups/'.
"""
from upgrade_oniro_utils import get_manifest_projects
from datetime import datetime
# Save all the layers / repo in the manifest
backup_folders = [layer["path"] for layer in get_manifest_projects(oniro_path)]
backup_folders_full = []
for folder in backup_folders:
backup_folders_full.append(f"{oniro_path}/" + folder)
backup_folders = backup_folders_full
# Save repo workspace
backup_folders.append(f"{oniro_path}/.repo")
# If a build directory is specified save the sstates, the cache and conf
if build_directory and build_directory.exists():
for child in build_directory.iterdir():
if child.is_dir() and "tmp" not in child.name and child.name != "downloads":
backup_folders.append(f"{build_directory}/{child.name}")
# Save all the folders starting with "meta-"
this_dir = pathlib.Path(f"{oniro_path}")
for child in this_dir.iterdir():
dir_name = child.name
if len(dir_name) > 4 and dir_name[:5] == "meta-":
backup_folders.append(child)
# Save all the folders specified by the user
if extra_folders is not None:
backup_folders += [f.name for f in extra_folders if f.exists()]
# To guarantee no duplicates
backup_folders = set(backup_folders)
# Create a metadata file containing all the folders that have been backed up
with open("backup_folders", "w") as f:
for folder in backup_folders:
f.write(f"{folder}\n")
print("Oniro backup started")
if not os.path.exists(f"{oniro_path}/upgrade_oniro_backups"):
os.mkdir(f"{oniro_path}/upgrade_oniro_backups")
archive_name = f"{oniro_path}/upgrade_oniro_backups/upgrade_oniro_backup-{datetime.timestamp(datetime.now())}.tar.gz"
with tarfile.open(archive_name, "w:gz") as tar_archive:
tar_archive.add("backup_folders")
for folder in backup_folders:
tar_archive.add(folder)
if verbose_backup:
print(f"{folder} has been backed up")
# Remove the uncompressed copy of backup_folders
os.remove("backup_folders")
print(f"Backup created at {archive_name}")
return
def restore_oniro():
"""
Restore a backup of Oniro.
This function will restore a backup of Oniro, to do so it will delete
all the folders (and their content) from repo's dir and substitute them with
the copy of the backup.
The backup must be created with `backup_oniro`.
Returns:
0 if the "latest" backup option is chosen but no backup has been found.
1 if the specified backup is not a valid archive.
2 if the metadata file containing backup folders has not been found in the archive.
3 if the specified archive isn't a valid Oniro backup.
4 if the archive path provided doesn't exist.
5 if the backup is restored succesfully.
"""
# TODO if something created some files / directories we are not able to
# delete those and we may end up with a inconsistent state
# TODO make this functon work with user inserted oniro project path
# currently it won't work
from upgrade_oniro_utils import find_latest_backup
from upgrade_oniro_utils import get_manifest_projects
if backup_archive_arg == "latest":
backup_archive_name = find_latest_backup("upgrade_oniro_backups")
if backup_archive_name is None:
print("No backup found, aborting...")
return
elif os.path.exists(backup_archive_arg):
# Check if the path is a valid archive
if tarfile.is_tarfile(backup_archive_arg) == False:
print("The specified path is not valid archive, aborting...")
return
tarf = tarfile.open(backup_archive_arg, "r:gz")
# Extract the metadata file and add its content in a set
metadata_set = {}
backup_folders = [layer["path"] for layer in get_manifest_projects(oniro_path)]
valid_metadata_file = True
with tarfile.open(backup_archive_arg) as backup_archive:
try:
backup_folders_file = backup_archive.extract("backup_folders")
except KeyError:
print("Metadata file not found in the backup archive, aborting...")
return
metadata_list = open("backup_folders").read().split("\n")
metadata_list.pop()
metadata_set = set(metadata_list)
# Check if the metadata file contains all the folder names required,
# so that we can confirm that they were backed up
for folder in backup_folders:
if folder in metadata_set == False:
valid_metadata_file = False
break
if valid_metadata_file == False:
print("The specified path is not a valid Oniro backup, aborting...")
return
backup_archive_name = backup_archive_arg
else:
print(f"'{backup_archive_arg}' has not been found, aborting...")
return
print(f"Restoring {backup_archive_name}")
with tarfile.open(backup_archive_name) as backup_archive:
# Extract the metadata file and delete all the old folders
try:
backup_folders_file = backup_archive.extract("backup_folders")
except KeyError:
print("Metadata file not found in the backup archive, aborting...")
return
with open("backup_folders", "r") as bf:
for folder in bf.readlines():
if os.path.exists(folder):
shutil.rmtree(folder.strip())
# Restore the backed up folders
backup_archive.extractall(".")
# Remove the uncompressed copy of backup_folders
os.remove("backup_folders")
print(f"{backup_archive_name} successfully restored!")
return
def upgrade_oniro():
# TODO implement a verbose output and a silent one
"""
Upgrade Oniro.
Upgrade Oniro to the target version. This function performs the
update of the conf files, bbappend files for custom layers (if the user wishes to)
and syncs the repo with the target version.
The target Oniro image is built after the update.
Returns:
0 if the upgrade process is interrupted by user choice.
1 if the upgrade is successful.
"""
import difflib
import subprocess
from upgrade_oniro_utils import (
update_bblayers,
get_layers,
update_local_conf,
update_bbappends,
update_oniro_inc,
)
print(
"In case of errors in the procedure, or if you want to revert the update, it's possibile to restore a previous backup"
)
# Get old layers for later use (used to update bblayers.conf)
old_layers, _ = get_layers(
pathlib.Path(f"{oniro_path}/oniro/flavours/{flavour}/bblayers.conf.sample")
)
# List of conf files and .bbappend files updated
updated_files_manual = []
# Get differences between local.conf and local.conf.sample before update if conf directory is specified
local_conf_diff = []
if conf_directory and conf_directory.is_dir():
with open(
f"{oniro_path}/oniro/flavours/{flavour}/local.conf.sample", "r"
) as local_sample_file:
with open(f"{conf_directory}/local.conf", "r") as local_conf_file:
diff = difflib.unified_diff(
local_sample_file.readlines(),
local_conf_file.readlines(),
fromfile="local_sample_file",
tofile="local_conf_file",
)
for line in diff:
if (
line.startswith("---") == False
and line.startswith("+++") == False
):
if line.startswith("+") or line.startswith("-"):
local_conf_diff.append(line)
# Update oniro repo and show changes that will be applied
# the user will be asked whether to continue or not
if target_version == "kirkstone":
oniro_diff = subprocess.Popen(
f"cd {oniro_path}/oniro; git diff -R --compact-summary kirkstone",
shell=True,
stdout=subprocess.PIPE,
)
print(oniro_diff.stdout.read().decode("utf-8"))
print("The above changes will be applied, do you want to continue? [y/n]")
user_choice = input()
user_choice = user_choice.lower()
if user_choice == "n":
print("Quitting...")
return 0
oniro_checkout = subprocess.Popen(
f"cd {oniro_path}/oniro; git checkout kirkstone; git pull eclipse kirkstone",
shell=True,
stdout=subprocess.PIPE,
)
else:
oniro_diff = subprocess.Popen(
f"cd {oniro_path}/oniro; git diff -R --compact-summary {target_version}",
shell=True,
stdout=subprocess.PIPE,
)
print(oniro_diff.stdout.read().decode("utf-8"))
print("The above changes will be applied, do you want to continue? [y/n]")
user_choice = input()
user_choice = user_choice.lower()
if user_choice == "n":
print("Quitting...")
return 0
oniro_checkout = subprocess.Popen(
f"cd {oniro_path}/oniro; git checkout {target_version}",
shell=True,
stdout=subprocess.PIPE,
)
print(oniro_checkout.stdout.read().decode("utf-8"))
# Sync the repos
repo_sync = subprocess.Popen(
f"repo sync -m {oniro_path}/oniro/manifests/default.xml",
shell=True,
stdout=subprocess.PIPE,
)
print(repo_sync.stdout.read().decode("utf-8"))
# Update the .bbappends files (needs user confirmation) if needed and print the renamed files
print("Do you wish to update the .bbappend files in your own custom layers? [y/n]")
update_user_choice = input()
update_user_choice = update_user_choice.lower()
if update_user_choice == "y":
updated_bbappend_files = update_bbappends(build_directory, flavour, oniro_path)
updated_files_manual.extend(updated_bbappend_files)
# Run the script to init the environment
init_env = subprocess.Popen(
f'cd {oniro_path}; bash -c "TEMPLATECONF=../oniro/flavours/{flavour} source ./oe-core/oe-init-build-env {build_directory}"',
shell=True,
stdout=subprocess.PIPE,
)
# If specified copy the conf directory
if conf_directory and conf_directory.is_dir():
print(f"Coping custom conf directory into {build_directory}...", end="")
shutil.rmtree(build_directory / "conf")
shutil.copytree(conf_directory, build_directory / "conf", symlinks=True)
print("Done")
# Update local.conf
print("Updating local.conf...", end="")
update_local_conf(build_directory, local_conf_diff, flavour, oniro_path)
print("Done")
updated_files_manual.append(
f"{build_directory}/conf/local.conf has been updated"
)
# Update bblayers.conf
print("Updating bblayers...", end="")
update_bblayers(build_directory, flavour, old_layers, oniro_path)
print("Done")
updated_files_manual.append(
f"{build_directory}/conf/bblayers.conf has been updated"
)
# Update oniro.inc if necessary
print("Updating oniro.inc if necessary...", end="")
oniro_inc_return_value = update_oniro_inc(oniro_path)
print("Done")
if oniro_inc_return_value == 2:
updated_files_manual.append(
f"{oniro_path}/oniro/meta-oniro-core/conf/distro/include/oniro.inc has been updated"
)
# If present delete the tmp directory
tmp_folder = "tmp-newlib" if flavour == "zephyr" else "tmp"
build_tmp_dir = pathlib.Path(build_directory / tmp_folder)
if build_tmp_dir.exists():
print(f"Removing {build_tmp_dir}")
shutil.rmtree(build_tmp_dir)
print("Would you like to build the target image? [y/n]")
build_choice = input()
build_choice = build_choice.lower()
if build_choice == "n":
for file in updated_files_manual:
print(file)
return 1
# Build the target
build_oniro = subprocess.run(
f'cd {oniro_path};bash -c "TEMPLATECONF=../oniro/flavours/{flavour} source ./oe-core/oe-init-build-env {build_directory}; MACHINE={machine} bitbake {image}"',
shell=True,
)
# print updated conf files and .bbappend files
for file in updated_files_manual:
print(file)
return 1
def build_oniro():
"""
Build Oniro.
Builds the target Oniro image.
Returns:
None. The target Oniro image will be built
"""
import subprocess
init_env = subprocess.Popen(
f'cd {oniro_path};bash -c "TEMPLATECONF=../oniro/flavours/{flavour} source ./oe-core/oe-init-build-env {build_directory}"',
shell=True,
stdout=subprocess.PIPE,
)
build_oniro = subprocess.run(
f'cd {oniro_path};bash -c "TEMPLATECONF=../oniro/flavours/{flavour} source ./oe-core/oe-init-build-env {build_directory}; MACHINE={machine} bitbake {image}"',
shell=True,
)
if __name__ == "__main__":
init_script_options()
# the command needs to be specified
if command not in ["upgrade", "backup", "restore", "build"]:
print(
"The inserted arguments are not valid, please choose between upgrade, backup, restore or build, quitting..."
)
sys.exit()
# check if the provided oniro project path is valid
oniro_folder = f"{oniro_path}/oniro"
if os.path.exists(oniro_folder) == False:
print("The inserted Oniro project path is not valid, quitting...")
sys.exit()
# check if the build directory specified exists and is non-empty and the permissions don't restrict operations into it
if build_directory and build_directory.exists():
if build_directory.is_dir() == False:
print(
"The specified build directory path exists, but it's not a directory, quitting..."
)
sys.exit()
elif len(os.listdir(f"{build_directory}")) == 0:
print("The specified build directory is not valid, quitting...")
sys.exit()
elif (
os.access(f"{build_directory}", os.X_OK | os.W_OK) == False
or os.access(f"{build_directory}", os.R_OK) == False
):
print(
"The tool cannot be executed with the build directory provided due to restricted permissions, quitting..."
)
sys.exit()
elif command in ["upgrade", "build"]:
print("The specified build directory does not exist, quitting...")
sys.exit()
# If the return code is 2, we can continue updating, otherwise there is another version of this script
# already found or the newer version could not be searched, for example if internet connection is
# missing.
upgrade_tool_code = upgrade_tool()
if upgrade_tool_code != 2:
sys.exit()
if command == "upgrade":
return_value = perform_pre_upgrade_checks()
if return_value == 0:
sys.exit()
# backup_oniro()
# restore_oniro()
upgrade_oniro()
elif command == "backup":
backup_oniro()
elif command == "restore":
# IMPORTANT: to avoid deleting local changes to the script
# backup everything before restoring something
# This is a developer aid (could it be used by end users?)
backup_oniro()
restore_oniro(backup_archive_arg)
elif command == "build":
return_value = perform_pre_upgrade_checks()
if return_value == 0:
sys.exit()
build_oniro()