summaryrefslogtreecommitdiffstats
path: root/scripts/lib
diff options
context:
space:
mode:
Diffstat (limited to 'scripts/lib')
-rw-r--r--scripts/lib/argparse_oe.py180
-rw-r--r--scripts/lib/build_perf/__init__.py24
-rw-r--r--scripts/lib/build_perf/html.py12
-rw-r--r--scripts/lib/build_perf/html/measurement_chart.html50
-rw-r--r--scripts/lib/build_perf/html/report.html289
-rw-r--r--scripts/lib/build_perf/report.py339
-rw-r--r--scripts/lib/build_perf/scrape-html-report.js56
-rw-r--r--scripts/lib/buildstats.py346
-rw-r--r--scripts/lib/checklayer/__init__.py425
-rw-r--r--scripts/lib/checklayer/case.py9
-rw-r--r--scripts/lib/checklayer/cases/__init__.py (renamed from scripts/lib/wic/3rdparty/pykickstart/__init__.py)0
-rw-r--r--scripts/lib/checklayer/cases/bsp.py206
-rw-r--r--scripts/lib/checklayer/cases/common.py60
-rw-r--r--scripts/lib/checklayer/cases/distro.py28
-rw-r--r--scripts/lib/checklayer/context.py17
-rw-r--r--scripts/lib/devtool/__init__.py345
-rw-r--r--scripts/lib/devtool/build-image.py95
-rw-r--r--scripts/lib/devtool/build.py92
-rw-r--r--scripts/lib/devtool/build_image.py164
-rw-r--r--scripts/lib/devtool/build_sdk.py55
-rw-r--r--scripts/lib/devtool/deploy.py390
-rw-r--r--scripts/lib/devtool/export.py109
-rw-r--r--scripts/lib/devtool/import.py134
-rw-r--r--scripts/lib/devtool/menuconfig.py79
-rw-r--r--scripts/lib/devtool/package.py50
-rw-r--r--scripts/lib/devtool/runqemu.py64
-rw-r--r--scripts/lib/devtool/sdk.py329
-rw-r--r--scripts/lib/devtool/search.py109
-rw-r--r--scripts/lib/devtool/standard.py2561
-rw-r--r--scripts/lib/devtool/upgrade.py661
-rw-r--r--scripts/lib/devtool/utilcmds.py242
-rw-r--r--scripts/lib/recipetool/append.py106
-rw-r--r--scripts/lib/recipetool/create.py1380
-rw-r--r--scripts/lib/recipetool/create_buildsys.py827
-rw-r--r--scripts/lib/recipetool/create_buildsys_python.py168
-rw-r--r--scripts/lib/recipetool/create_kernel.py89
-rw-r--r--scripts/lib/recipetool/create_kmod.py142
-rw-r--r--scripts/lib/recipetool/create_npm.py299
-rw-r--r--scripts/lib/recipetool/edit.py44
-rw-r--r--scripts/lib/recipetool/licenses.csv37
-rw-r--r--scripts/lib/recipetool/newappend.py79
-rw-r--r--scripts/lib/recipetool/setvar.py65
-rw-r--r--scripts/lib/resulttool/__init__.py (renamed from scripts/lib/wic/3rdparty/pykickstart/handlers/__init__.py)0
-rw-r--r--scripts/lib/resulttool/log.py104
-rwxr-xr-xscripts/lib/resulttool/manualexecution.py235
-rw-r--r--scripts/lib/resulttool/merge.py46
-rw-r--r--scripts/lib/resulttool/regression.py186
-rw-r--r--scripts/lib/resulttool/report.py312
-rw-r--r--scripts/lib/resulttool/resultutils.py224
-rw-r--r--scripts/lib/resulttool/store.py104
-rw-r--r--scripts/lib/resulttool/template/test_report_full_text.txt79
-rw-r--r--scripts/lib/scriptpath.py12
-rw-r--r--scripts/lib/scriptutils.py273
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/base.py466
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/commands/__init__.py20
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/commands/bootloader.py216
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/commands/partition.py314
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/constants.py57
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/errors.py103
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/handlers/control.py46
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/handlers/f16.py24
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/ko.py37
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/options.py223
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/parser.py619
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/sections.py244
-rw-r--r--scripts/lib/wic/3rdparty/pykickstart/version.py168
-rw-r--r--scripts/lib/wic/__init__.py12
-rw-r--r--scripts/lib/wic/__version__.py1
-rw-r--r--scripts/lib/wic/canned-wks/common.wks.inc3
-rw-r--r--scripts/lib/wic/canned-wks/directdisk-bootloader-config.cfg27
-rw-r--r--scripts/lib/wic/canned-wks/directdisk-bootloader-config.wks8
-rw-r--r--scripts/lib/wic/canned-wks/directdisk-gpt.wks2
-rw-r--r--scripts/lib/wic/canned-wks/directdisk-multi-rootfs.wks2
-rw-r--r--scripts/lib/wic/canned-wks/directdisk.wks6
-rw-r--r--scripts/lib/wic/canned-wks/efi-bootdisk.wks.in3
-rw-r--r--scripts/lib/wic/canned-wks/mkefidisk.wks4
-rw-r--r--scripts/lib/wic/canned-wks/mkgummidisk.wks11
-rw-r--r--scripts/lib/wic/canned-wks/mkhybridiso.wks2
-rw-r--r--scripts/lib/wic/canned-wks/qemuriscv.wks3
-rw-r--r--scripts/lib/wic/canned-wks/qemux86-directdisk.wks6
-rw-r--r--scripts/lib/wic/canned-wks/sdimage-bootpart.wks4
-rw-r--r--scripts/lib/wic/canned-wks/systemd-bootdisk.wks11
-rw-r--r--scripts/lib/wic/conf.py100
-rw-r--r--scripts/lib/wic/config/wic.conf6
-rw-r--r--scripts/lib/wic/creator.py124
-rw-r--r--scripts/lib/wic/engine.py522
-rw-r--r--scripts/lib/wic/filemap.py576
-rw-r--r--scripts/lib/wic/help.py481
-rw-r--r--scripts/lib/wic/imager/__init__.py0
-rw-r--r--scripts/lib/wic/imager/baseimager.py192
-rw-r--r--scripts/lib/wic/imager/direct.py378
-rw-r--r--scripts/lib/wic/kickstart/__init__.py122
-rw-r--r--scripts/lib/wic/kickstart/custom_commands/__init__.py7
-rw-r--r--scripts/lib/wic/kickstart/custom_commands/partition.py526
-rw-r--r--scripts/lib/wic/kickstart/custom_commands/wicboot.py60
-rw-r--r--scripts/lib/wic/ksparser.py295
-rw-r--r--scripts/lib/wic/misc.py264
-rw-r--r--scripts/lib/wic/msger.py309
-rw-r--r--scripts/lib/wic/partition.py496
-rw-r--r--scripts/lib/wic/plugin.py150
-rw-r--r--scripts/lib/wic/pluginbase.py116
-rw-r--r--scripts/lib/wic/plugins/imager/direct.py623
-rw-r--r--scripts/lib/wic/plugins/imager/direct_plugin.py102
-rw-r--r--scripts/lib/wic/plugins/source/bootimg-biosplusefi.py213
-rw-r--r--scripts/lib/wic/plugins/source/bootimg-efi.py384
-rw-r--r--scripts/lib/wic/plugins/source/bootimg-partition.py207
-rw-r--r--scripts/lib/wic/plugins/source/bootimg-pcbios.py207
-rw-r--r--scripts/lib/wic/plugins/source/empty.py32
-rw-r--r--scripts/lib/wic/plugins/source/fsimage.py73
-rw-r--r--scripts/lib/wic/plugins/source/isoimage-isohybrid.py443
-rw-r--r--scripts/lib/wic/plugins/source/rawcopy.py92
-rw-r--r--scripts/lib/wic/plugins/source/rootfs.py222
-rw-r--r--scripts/lib/wic/plugins/source/rootfs_pcbios_ext.py181
-rw-r--r--scripts/lib/wic/test1
-rw-r--r--scripts/lib/wic/utils/__init__.py0
-rw-r--r--scripts/lib/wic/utils/errors.py29
-rw-r--r--scripts/lib/wic/utils/fs_related.py84
-rw-r--r--scripts/lib/wic/utils/misc.py58
-rw-r--r--scripts/lib/wic/utils/oe/__init__.py22
-rw-r--r--scripts/lib/wic/utils/oe/misc.py234
-rw-r--r--scripts/lib/wic/utils/partitionedfs.py362
-rw-r--r--scripts/lib/wic/utils/runner.py110
-rw-r--r--scripts/lib/wic/utils/syslinux.py58
123 files changed, 15457 insertions, 7977 deletions
diff --git a/scripts/lib/argparse_oe.py b/scripts/lib/argparse_oe.py
new file mode 100644
index 0000000000..94a4ac5011
--- /dev/null
+++ b/scripts/lib/argparse_oe.py
@@ -0,0 +1,180 @@
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import sys
+import argparse
+from collections import defaultdict, OrderedDict
+
+class ArgumentUsageError(Exception):
+ """Exception class you can raise (and catch) in order to show the help"""
+ def __init__(self, message, subcommand=None):
+ self.message = message
+ self.subcommand = subcommand
+
+class ArgumentParser(argparse.ArgumentParser):
+ """Our own version of argparse's ArgumentParser"""
+ def __init__(self, *args, **kwargs):
+ kwargs.setdefault('formatter_class', OeHelpFormatter)
+ self._subparser_groups = OrderedDict()
+ super(ArgumentParser, self).__init__(*args, **kwargs)
+ self._positionals.title = 'arguments'
+ self._optionals.title = 'options'
+
+ def error(self, message):
+ """error(message: string)
+
+ Prints a help message incorporating the message to stderr and
+ exits.
+ """
+ self._print_message('%s: error: %s\n' % (self.prog, message), sys.stderr)
+ self.print_help(sys.stderr)
+ sys.exit(2)
+
+ def error_subcommand(self, message, subcommand):
+ if subcommand:
+ action = self._get_subparser_action()
+ try:
+ subparser = action._name_parser_map[subcommand]
+ except KeyError:
+ self.error('no subparser for name "%s"' % subcommand)
+ else:
+ subparser.error(message)
+
+ self.error(message)
+
+ def add_subparsers(self, *args, **kwargs):
+ if 'dest' not in kwargs:
+ kwargs['dest'] = '_subparser_name'
+
+ ret = super(ArgumentParser, self).add_subparsers(*args, **kwargs)
+ # Need a way of accessing the parent parser
+ ret._parent_parser = self
+ # Ensure our class gets instantiated
+ ret._parser_class = ArgumentSubParser
+ # Hacky way of adding a method to the subparsers object
+ ret.add_subparser_group = self.add_subparser_group
+ return ret
+
+ def add_subparser_group(self, groupname, groupdesc, order=0):
+ self._subparser_groups[groupname] = (groupdesc, order)
+
+ def parse_args(self, args=None, namespace=None):
+ """Parse arguments, using the correct subparser to show the error."""
+ args, argv = self.parse_known_args(args, namespace)
+ if argv:
+ message = 'unrecognized arguments: %s' % ' '.join(argv)
+ if self._subparsers:
+ subparser = self._get_subparser(args)
+ subparser.error(message)
+ else:
+ self.error(message)
+ sys.exit(2)
+ return args
+
+ def _get_subparser(self, args):
+ action = self._get_subparser_action()
+ if action.dest == argparse.SUPPRESS:
+ self.error('cannot get subparser, the subparser action dest is suppressed')
+
+ name = getattr(args, action.dest)
+ try:
+ return action._name_parser_map[name]
+ except KeyError:
+ self.error('no subparser for name "%s"' % name)
+
+ def _get_subparser_action(self):
+ if not self._subparsers:
+ self.error('cannot return the subparser action, no subparsers added')
+
+ for action in self._subparsers._group_actions:
+ if isinstance(action, argparse._SubParsersAction):
+ return action
+
+
+class ArgumentSubParser(ArgumentParser):
+ def __init__(self, *args, **kwargs):
+ if 'group' in kwargs:
+ self._group = kwargs.pop('group')
+ if 'order' in kwargs:
+ self._order = kwargs.pop('order')
+ super(ArgumentSubParser, self).__init__(*args, **kwargs)
+
+ def parse_known_args(self, args=None, namespace=None):
+ # This works around argparse not handling optional positional arguments being
+ # intermixed with other options. A pretty horrible hack, but we're not left
+ # with much choice given that the bug in argparse exists and it's difficult
+ # to subclass.
+ # Borrowed from http://stackoverflow.com/questions/20165843/argparse-how-to-handle-variable-number-of-arguments-nargs
+ # with an extra workaround (in format_help() below) for the positional
+ # arguments disappearing from the --help output, as well as structural tweaks.
+ # Originally simplified from http://bugs.python.org/file30204/test_intermixed.py
+ positionals = self._get_positional_actions()
+ for action in positionals:
+ # deactivate positionals
+ action.save_nargs = action.nargs
+ action.nargs = 0
+
+ namespace, remaining_args = super(ArgumentSubParser, self).parse_known_args(args, namespace)
+ for action in positionals:
+ # remove the empty positional values from namespace
+ if hasattr(namespace, action.dest):
+ delattr(namespace, action.dest)
+ for action in positionals:
+ action.nargs = action.save_nargs
+ # parse positionals
+ namespace, extras = super(ArgumentSubParser, self).parse_known_args(remaining_args, namespace)
+ return namespace, extras
+
+ def format_help(self):
+ # Quick, restore the positionals!
+ positionals = self._get_positional_actions()
+ for action in positionals:
+ if hasattr(action, 'save_nargs'):
+ action.nargs = action.save_nargs
+ return super(ArgumentParser, self).format_help()
+
+
+class OeHelpFormatter(argparse.HelpFormatter):
+ def _format_action(self, action):
+ if hasattr(action, '_get_subactions'):
+ # subcommands list
+ groupmap = defaultdict(list)
+ ordermap = {}
+ subparser_groups = action._parent_parser._subparser_groups
+ groups = sorted(subparser_groups.keys(), key=lambda item: subparser_groups[item][1], reverse=True)
+ for subaction in self._iter_indented_subactions(action):
+ parser = action._name_parser_map[subaction.dest]
+ group = getattr(parser, '_group', None)
+ groupmap[group].append(subaction)
+ if group not in groups:
+ groups.append(group)
+ order = getattr(parser, '_order', 0)
+ ordermap[subaction.dest] = order
+
+ lines = []
+ if len(groupmap) > 1:
+ groupindent = ' '
+ else:
+ groupindent = ''
+ for group in groups:
+ subactions = groupmap[group]
+ if not subactions:
+ continue
+ if groupindent:
+ if not group:
+ group = 'other'
+ groupdesc = subparser_groups.get(group, (group, 0))[0]
+ lines.append(' %s:' % groupdesc)
+ for subaction in sorted(subactions, key=lambda item: ordermap[item.dest], reverse=True):
+ lines.append('%s%s' % (groupindent, self._format_action(subaction).rstrip()))
+ return '\n'.join(lines)
+ else:
+ return super(OeHelpFormatter, self)._format_action(action)
+
+def int_positive(value):
+ ivalue = int(value)
+ if ivalue <= 0:
+ raise argparse.ArgumentTypeError(
+ "%s is not a positive int value" % value)
+ return ivalue
diff --git a/scripts/lib/build_perf/__init__.py b/scripts/lib/build_perf/__init__.py
new file mode 100644
index 0000000000..dcbb78042d
--- /dev/null
+++ b/scripts/lib/build_perf/__init__.py
@@ -0,0 +1,24 @@
+#
+# Copyright (c) 2017, Intel Corporation.
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+"""Build performance test library functions"""
+
+def print_table(rows, row_fmt=None):
+ """Print data table"""
+ if not rows:
+ return
+ if not row_fmt:
+ row_fmt = ['{:{wid}} '] * len(rows[0])
+
+ # Go through the data to get maximum cell widths
+ num_cols = len(row_fmt)
+ col_widths = [0] * num_cols
+ for row in rows:
+ for i, val in enumerate(row):
+ col_widths[i] = max(col_widths[i], len(str(val)))
+
+ for row in rows:
+ print(*[row_fmt[i].format(col, wid=col_widths[i]) for i, col in enumerate(row)])
+
diff --git a/scripts/lib/build_perf/html.py b/scripts/lib/build_perf/html.py
new file mode 100644
index 0000000000..d1273c9c50
--- /dev/null
+++ b/scripts/lib/build_perf/html.py
@@ -0,0 +1,12 @@
+#
+# Copyright (c) 2017, Intel Corporation.
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+"""Helper module for HTML reporting"""
+from jinja2 import Environment, PackageLoader
+
+
+env = Environment(loader=PackageLoader('build_perf', 'html'))
+
+template = env.get_template('report.html')
diff --git a/scripts/lib/build_perf/html/measurement_chart.html b/scripts/lib/build_perf/html/measurement_chart.html
new file mode 100644
index 0000000000..65f1a227ad
--- /dev/null
+++ b/scripts/lib/build_perf/html/measurement_chart.html
@@ -0,0 +1,50 @@
+<script type="text/javascript">
+ chartsDrawing += 1;
+ google.charts.setOnLoadCallback(drawChart_{{ chart_elem_id }});
+ function drawChart_{{ chart_elem_id }}() {
+ var data = new google.visualization.DataTable();
+
+ // Chart options
+ var options = {
+ theme : 'material',
+ legend: 'none',
+ hAxis: { format: '', title: 'Commit number',
+ minValue: {{ chart_opts.haxis.min }},
+ maxValue: {{ chart_opts.haxis.max }} },
+ {% if measurement.type == 'time' %}
+ vAxis: { format: 'h:mm:ss' },
+ {% else %}
+ vAxis: { format: '' },
+ {% endif %}
+ pointSize: 5,
+ chartArea: { left: 80, right: 15 },
+ };
+
+ // Define data columns
+ data.addColumn('number', 'Commit');
+ data.addColumn('{{ measurement.value_type.gv_data_type }}',
+ '{{ measurement.value_type.quantity }}');
+ // Add data rows
+ data.addRows([
+ {% for sample in measurement.samples %}
+ [{{ sample.commit_num }}, {{ sample.mean.gv_value() }}],
+ {% endfor %}
+ ]);
+
+ // Finally, draw the chart
+ chart_div = document.getElementById('{{ chart_elem_id }}');
+ var chart = new google.visualization.LineChart(chart_div);
+ google.visualization.events.addListener(chart, 'ready', function () {
+ //chart_div = document.getElementById('{{ chart_elem_id }}');
+ //chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
+ png_div = document.getElementById('{{ chart_elem_id }}_png');
+ png_div.outerHTML = '<a id="{{ chart_elem_id }}_png" href="' + chart.getImageURI() + '">PNG</a>';
+ console.log("CHART READY: {{ chart_elem_id }}");
+ chartsDrawing -= 1;
+ if (chartsDrawing == 0)
+ console.log("ALL CHARTS READY");
+ });
+ chart.draw(data, options);
+}
+</script>
+
diff --git a/scripts/lib/build_perf/html/report.html b/scripts/lib/build_perf/html/report.html
new file mode 100644
index 0000000000..d1ba6f2578
--- /dev/null
+++ b/scripts/lib/build_perf/html/report.html
@@ -0,0 +1,289 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+{# Scripts, for visualization#}
+<!--START-OF-SCRIPTS-->
+<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
+<script type="text/javascript">
+google.charts.load('current', {'packages':['corechart']});
+var chartsDrawing = 0;
+</script>
+
+{# Render measurement result charts #}
+{% for test in test_data %}
+ {% if test.status == 'SUCCESS' %}
+ {% for measurement in test.measurements %}
+ {% set chart_elem_id = test.name + '_' + measurement.name + '_chart' %}
+ {% include 'measurement_chart.html' %}
+ {% endfor %}
+ {% endif %}
+{% endfor %}
+
+<!--END-OF-SCRIPTS-->
+
+{# Styles #}
+<style>
+.meta-table {
+ font-size: 14px;
+ text-align: left;
+ border-collapse: collapse;
+}
+.meta-table tr:nth-child(even){background-color: #f2f2f2}
+meta-table th, .meta-table td {
+ padding: 4px;
+}
+.summary {
+ margin: 0;
+ font-size: 14px;
+ text-align: left;
+ border-collapse: collapse;
+}
+summary th, .meta-table td {
+ padding: 4px;
+}
+.measurement {
+ padding: 8px 0px 8px 8px;
+ border: 2px solid #f0f0f0;
+ margin-bottom: 10px;
+}
+.details {
+ margin: 0;
+ font-size: 12px;
+ text-align: left;
+ border-collapse: collapse;
+}
+.details th {
+ padding-right: 8px;
+}
+.details.plain th {
+ font-weight: normal;
+}
+.preformatted {
+ font-family: monospace;
+ white-space: pre-wrap;
+ background-color: #f0f0f0;
+ margin-left: 10px;
+}
+hr {
+ color: #f0f0f0;
+}
+h2 {
+ font-size: 20px;
+ margin-bottom: 0px;
+ color: #707070;
+}
+h3 {
+ font-size: 16px;
+ margin: 0px;
+ color: #707070;
+}
+</style>
+
+<title>{{ title }}</title>
+</head>
+
+{% macro poky_link(commit) -%}
+ <a href="http://git.yoctoproject.org/cgit/cgit.cgi/poky/log/?id={{ commit }}">{{ commit[0:11] }}</a>
+{%- endmacro %}
+
+<body><div style="width: 700px">
+ {# Test metadata #}
+ <h2>General</h2>
+ <hr>
+ <table class="meta-table" style="width: 100%">
+ <tr>
+ <th></th>
+ <th>Current commit</th>
+ <th>Comparing with</th>
+ </tr>
+ {% for key, item in metadata.items() %}
+ <tr>
+ <th>{{ item.title }}</th>
+ {%if key == 'commit' %}
+ <td>{{ poky_link(item.value) }}</td>
+ <td>{{ poky_link(item.value_old) }}</td>
+ {% else %}
+ <td>{{ item.value }}</td>
+ <td>{{ item.value_old }}</td>
+ {% endif %}
+ </tr>
+ {% endfor %}
+ </table>
+
+ {# Test result summary #}
+ <h2>Test result summary</h2>
+ <hr>
+ <table class="summary" style="width: 100%">
+ {% for test in test_data %}
+ {% if loop.index is even %}
+ {% set row_style = 'style="background-color: #f2f2f2"' %}
+ {% else %}
+ {% set row_style = 'style="background-color: #ffffff"' %}
+ {% endif %}
+ {% if test.status == 'SUCCESS' %}
+ {% for measurement in test.measurements %}
+ <tr {{ row_style }}>
+ {% if loop.index == 1 %}
+ <td>{{ test.name }}: {{ test.description }}</td>
+ {% else %}
+ {# add empty cell in place of the test name#}
+ <td></td>
+ {% endif %}
+ {% if measurement.absdiff > 0 %}
+ {% set result_style = "color: red" %}
+ {% elif measurement.absdiff == measurement.absdiff %}
+ {% set result_style = "color: green" %}
+ {% else %}
+ {% set result_style = "color: orange" %}
+ {%endif %}
+ {% if measurement.reldiff|abs > 2 %}
+ {% set result_style = result_style + "; font-weight: bold" %}
+ {% endif %}
+ <td>{{ measurement.description }}</td>
+ <td style="font-weight: bold">{{ measurement.value.mean }}</td>
+ <td style="{{ result_style }}">{{ measurement.absdiff_str }}</td>
+ <td style="{{ result_style }}">{{ measurement.reldiff_str }}</td>
+ </tr>
+ {% endfor %}
+ {% else %}
+ <td style="font-weight: bold; color: red;">{{test.status }}</td>
+ <td></td> <td></td> <td></td> <td></td>
+ {% endif %}
+ {% endfor %}
+ </table>
+
+ {# Detailed test results #}
+ {% for test in test_data %}
+ <h2>{{ test.name }}: {{ test.description }}</h2>
+ <hr>
+ {% if test.status == 'SUCCESS' %}
+ {% for measurement in test.measurements %}
+ <div class="measurement">
+ <h3>{{ measurement.description }}</h3>
+ <div style="font-weight:bold;">
+ <span style="font-size: 23px;">{{ measurement.value.mean }}</span>
+ <span style="font-size: 20px; margin-left: 12px">
+ {% if measurement.absdiff > 0 %}
+ <span style="color: red">
+ {% elif measurement.absdiff == measurement.absdiff %}
+ <span style="color: green">
+ {% else %}
+ <span style="color: orange">
+ {% endif %}
+ {{ measurement.absdiff_str }} ({{measurement.reldiff_str}})
+ </span></span>
+ </div>
+ {# Table for trendchart and the statistics #}
+ <table style="width: 100%">
+ <tr>
+ <td style="width: 75%">
+ {# Linechart #}
+ <div id="{{ test.name }}_{{ measurement.name }}_chart"></div>
+ </td>
+ <td>
+ {# Measurement statistics #}
+ <table class="details plain">
+ <tr>
+ <th>Test runs</th><td>{{ measurement.value.sample_cnt }}</td>
+ </tr><tr>
+ <th>-/+</th><td>-{{ measurement.value.minus }} / +{{ measurement.value.plus }}</td>
+ </tr><tr>
+ <th>Min</th><td>{{ measurement.value.min }}</td>
+ </tr><tr>
+ <th>Max</th><td>{{ measurement.value.max }}</td>
+ </tr><tr>
+ <th>Stdev</th><td>{{ measurement.value.stdev }}</td>
+ </tr><tr>
+ <th><div id="{{ test.name }}_{{ measurement.name }}_chart_png"></div></th>
+ <td></td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ </table>
+
+ {# Task and recipe summary from buildstats #}
+ {% if 'buildstats' in measurement %}
+ Task resource usage
+ <table class="details" style="width:100%">
+ <tr>
+ <th>Number of tasks</th>
+ <th>Top consumers of cputime</th>
+ </tr>
+ <tr>
+ <td style="vertical-align: top">{{ measurement.buildstats.tasks.count }} ({{ measurement.buildstats.tasks.change }})</td>
+ {# Table of most resource-hungry tasks #}
+ <td>
+ <table class="details plain">
+ {% for diff in measurement.buildstats.top_consumer|reverse %}
+ <tr>
+ <th>{{ diff.pkg }}.{{ diff.task }}</th>
+ <td>{{ '%0.0f' % diff.value2 }} s</td>
+ </tr>
+ {% endfor %}
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <th>Biggest increase in cputime</th>
+ <th>Biggest decrease in cputime</th>
+ </tr>
+ <tr>
+ {# Table biggest increase in resource usage #}
+ <td>
+ <table class="details plain">
+ {% for diff in measurement.buildstats.top_increase|reverse %}
+ <tr>
+ <th>{{ diff.pkg }}.{{ diff.task }}</th>
+ <td>{{ '%+0.0f' % diff.absdiff }} s</td>
+ </tr>
+ {% endfor %}
+ </table>
+ </td>
+ {# Table biggest decrease in resource usage #}
+ <td>
+ <table class="details plain">
+ {% for diff in measurement.buildstats.top_decrease %}
+ <tr>
+ <th>{{ diff.pkg }}.{{ diff.task }}</th>
+ <td>{{ '%+0.0f' % diff.absdiff }} s</td>
+ </tr>
+ {% endfor %}
+ </table>
+ </td>
+ </tr>
+ </table>
+
+ {# Recipe version differences #}
+ {% if measurement.buildstats.ver_diff %}
+ <div style="margin-top: 16px">Recipe version changes</div>
+ <table class="details">
+ {% for head, recipes in measurement.buildstats.ver_diff.items() %}
+ <tr>
+ <th colspan="2">{{ head }}</th>
+ </tr>
+ {% for name, info in recipes|sort %}
+ <tr>
+ <td>{{ name }}</td>
+ <td>{{ info }}</td>
+ </tr>
+ {% endfor %}
+ {% endfor %}
+ </table>
+ {% else %}
+ <div style="margin-top: 16px">No recipe version changes detected</div>
+ {% endif %}
+ {% endif %}
+ </div>
+ {% endfor %}
+ {# Unsuccessful test #}
+ {% else %}
+ <span style="font-size: 150%; font-weight: bold; color: red;">{{ test.status }}
+ {% if test.err_type %}<span style="font-size: 75%; font-weight: normal">({{ test.err_type }})</span>{% endif %}
+ </span>
+ <div class="preformatted">{{ test.message }}</div>
+ {% endif %}
+ {% endfor %}
+</div></body>
+</html>
+
diff --git a/scripts/lib/build_perf/report.py b/scripts/lib/build_perf/report.py
new file mode 100644
index 0000000000..ab77424cc7
--- /dev/null
+++ b/scripts/lib/build_perf/report.py
@@ -0,0 +1,339 @@
+#
+# Copyright (c) 2017, Intel Corporation.
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+"""Handling of build perf test reports"""
+from collections import OrderedDict, namedtuple
+from collections.abc import Mapping
+from datetime import datetime, timezone
+from numbers import Number
+from statistics import mean, stdev, variance
+
+
+AggregateTestData = namedtuple('AggregateTestData', ['metadata', 'results'])
+
+
+def isofmt_to_timestamp(string):
+ """Convert timestamp string in ISO 8601 format into unix timestamp"""
+ if '.' in string:
+ dt = datetime.strptime(string, '%Y-%m-%dT%H:%M:%S.%f')
+ else:
+ dt = datetime.strptime(string, '%Y-%m-%dT%H:%M:%S')
+ return dt.replace(tzinfo=timezone.utc).timestamp()
+
+
+def metadata_xml_to_json(elem):
+ """Convert metadata xml into JSON format"""
+ assert elem.tag == 'metadata', "Invalid metadata file format"
+
+ def _xml_to_json(elem):
+ """Convert xml element to JSON object"""
+ out = OrderedDict()
+ for child in elem.getchildren():
+ key = child.attrib.get('name', child.tag)
+ if len(child):
+ out[key] = _xml_to_json(child)
+ else:
+ out[key] = child.text
+ return out
+ return _xml_to_json(elem)
+
+
+def results_xml_to_json(elem):
+ """Convert results xml into JSON format"""
+ rusage_fields = ('ru_utime', 'ru_stime', 'ru_maxrss', 'ru_minflt',
+ 'ru_majflt', 'ru_inblock', 'ru_oublock', 'ru_nvcsw',
+ 'ru_nivcsw')
+ iostat_fields = ('rchar', 'wchar', 'syscr', 'syscw', 'read_bytes',
+ 'write_bytes', 'cancelled_write_bytes')
+
+ def _read_measurement(elem):
+ """Convert measurement to JSON"""
+ data = OrderedDict()
+ data['type'] = elem.tag
+ data['name'] = elem.attrib['name']
+ data['legend'] = elem.attrib['legend']
+ values = OrderedDict()
+
+ # SYSRES measurement
+ if elem.tag == 'sysres':
+ for subel in elem:
+ if subel.tag == 'time':
+ values['start_time'] = isofmt_to_timestamp(subel.attrib['timestamp'])
+ values['elapsed_time'] = float(subel.text)
+ elif subel.tag == 'rusage':
+ rusage = OrderedDict()
+ for field in rusage_fields:
+ if 'time' in field:
+ rusage[field] = float(subel.attrib[field])
+ else:
+ rusage[field] = int(subel.attrib[field])
+ values['rusage'] = rusage
+ elif subel.tag == 'iostat':
+ values['iostat'] = OrderedDict([(f, int(subel.attrib[f]))
+ for f in iostat_fields])
+ elif subel.tag == 'buildstats_file':
+ values['buildstats_file'] = subel.text
+ else:
+ raise TypeError("Unknown sysres value element '{}'".format(subel.tag))
+ # DISKUSAGE measurement
+ elif elem.tag == 'diskusage':
+ values['size'] = int(elem.find('size').text)
+ else:
+ raise Exception("Unknown measurement tag '{}'".format(elem.tag))
+ data['values'] = values
+ return data
+
+ def _read_testcase(elem):
+ """Convert testcase into JSON"""
+ assert elem.tag == 'testcase', "Expecting 'testcase' element instead of {}".format(elem.tag)
+
+ data = OrderedDict()
+ data['name'] = elem.attrib['name']
+ data['description'] = elem.attrib['description']
+ data['status'] = 'SUCCESS'
+ data['start_time'] = isofmt_to_timestamp(elem.attrib['timestamp'])
+ data['elapsed_time'] = float(elem.attrib['time'])
+ measurements = OrderedDict()
+
+ for subel in elem.getchildren():
+ if subel.tag == 'error' or subel.tag == 'failure':
+ data['status'] = subel.tag.upper()
+ data['message'] = subel.attrib['message']
+ data['err_type'] = subel.attrib['type']
+ data['err_output'] = subel.text
+ elif subel.tag == 'skipped':
+ data['status'] = 'SKIPPED'
+ data['message'] = subel.text
+ else:
+ measurements[subel.attrib['name']] = _read_measurement(subel)
+ data['measurements'] = measurements
+ return data
+
+ def _read_testsuite(elem):
+ """Convert suite to JSON"""
+ assert elem.tag == 'testsuite', \
+ "Expecting 'testsuite' element instead of {}".format(elem.tag)
+
+ data = OrderedDict()
+ if 'hostname' in elem.attrib:
+ data['tester_host'] = elem.attrib['hostname']
+ data['start_time'] = isofmt_to_timestamp(elem.attrib['timestamp'])
+ data['elapsed_time'] = float(elem.attrib['time'])
+ tests = OrderedDict()
+
+ for case in elem.getchildren():
+ tests[case.attrib['name']] = _read_testcase(case)
+ data['tests'] = tests
+ return data
+
+ # Main function
+ assert elem.tag == 'testsuites', "Invalid test report format"
+ assert len(elem) == 1, "Too many testsuites"
+
+ return _read_testsuite(elem.getchildren()[0])
+
+
+def aggregate_metadata(metadata):
+ """Aggregate metadata into one, basically a sanity check"""
+ mutable_keys = ('pretty_name', 'version_id')
+
+ def aggregate_obj(aggregate, obj, assert_str=True):
+ """Aggregate objects together"""
+ assert type(aggregate) is type(obj), \
+ "Type mismatch: {} != {}".format(type(aggregate), type(obj))
+ if isinstance(obj, Mapping):
+ assert set(aggregate.keys()) == set(obj.keys())
+ for key, val in obj.items():
+ aggregate_obj(aggregate[key], val, key not in mutable_keys)
+ elif isinstance(obj, list):
+ assert len(aggregate) == len(obj)
+ for i, val in enumerate(obj):
+ aggregate_obj(aggregate[i], val)
+ elif not isinstance(obj, str) or (isinstance(obj, str) and assert_str):
+ assert aggregate == obj, "Data mismatch {} != {}".format(aggregate, obj)
+
+ if not metadata:
+ return {}
+
+ # Do the aggregation
+ aggregate = metadata[0].copy()
+ for testrun in metadata[1:]:
+ aggregate_obj(aggregate, testrun)
+ aggregate['testrun_count'] = len(metadata)
+ return aggregate
+
+
+def aggregate_data(data):
+ """Aggregate multiple test results JSON structures into one"""
+
+ mutable_keys = ('status', 'message', 'err_type', 'err_output')
+
+ class SampleList(list):
+ """Container for numerical samples"""
+ pass
+
+ def new_aggregate_obj(obj):
+ """Create new object for aggregate"""
+ if isinstance(obj, Number):
+ new_obj = SampleList()
+ new_obj.append(obj)
+ elif isinstance(obj, str):
+ new_obj = obj
+ else:
+ # Lists and and dicts are kept as is
+ new_obj = obj.__class__()
+ aggregate_obj(new_obj, obj)
+ return new_obj
+
+ def aggregate_obj(aggregate, obj, assert_str=True):
+ """Recursive "aggregation" of JSON objects"""
+ if isinstance(obj, Number):
+ assert isinstance(aggregate, SampleList)
+ aggregate.append(obj)
+ return
+
+ assert type(aggregate) == type(obj), \
+ "Type mismatch: {} != {}".format(type(aggregate), type(obj))
+ if isinstance(obj, Mapping):
+ for key, val in obj.items():
+ if not key in aggregate:
+ aggregate[key] = new_aggregate_obj(val)
+ else:
+ aggregate_obj(aggregate[key], val, key not in mutable_keys)
+ elif isinstance(obj, list):
+ for i, val in enumerate(obj):
+ if i >= len(aggregate):
+ aggregate[key] = new_aggregate_obj(val)
+ else:
+ aggregate_obj(aggregate[i], val)
+ elif isinstance(obj, str):
+ # Sanity check for data
+ if assert_str:
+ assert aggregate == obj, "Data mismatch {} != {}".format(aggregate, obj)
+ else:
+ raise Exception("BUG: unable to aggregate '{}' ({})".format(type(obj), str(obj)))
+
+ if not data:
+ return {}
+
+ # Do the aggregation
+ aggregate = data[0].__class__()
+ for testrun in data:
+ aggregate_obj(aggregate, testrun)
+ return aggregate
+
+
+class MeasurementVal(float):
+ """Base class representing measurement values"""
+ gv_data_type = 'number'
+
+ def gv_value(self):
+ """Value formatting for visualization"""
+ if self != self:
+ return "null"
+ else:
+ return self
+
+
+class TimeVal(MeasurementVal):
+ """Class representing time values"""
+ quantity = 'time'
+ gv_title = 'elapsed time'
+ gv_data_type = 'timeofday'
+
+ def hms(self):
+ """Split time into hours, minutes and seconeds"""
+ hhh = int(abs(self) / 3600)
+ mmm = int((abs(self) % 3600) / 60)
+ sss = abs(self) % 60
+ return hhh, mmm, sss
+
+ def __str__(self):
+ if self != self:
+ return "nan"
+ hh, mm, ss = self.hms()
+ sign = '-' if self < 0 else ''
+ if hh > 0:
+ return '{}{:d}:{:02d}:{:02.0f}'.format(sign, hh, mm, ss)
+ elif mm > 0:
+ return '{}{:d}:{:04.1f}'.format(sign, mm, ss)
+ elif ss > 1:
+ return '{}{:.1f} s'.format(sign, ss)
+ else:
+ return '{}{:.2f} s'.format(sign, ss)
+
+ def gv_value(self):
+ """Value formatting for visualization"""
+ if self != self:
+ return "null"
+ hh, mm, ss = self.hms()
+ return [hh, mm, int(ss), int(ss*1000) % 1000]
+
+
+class SizeVal(MeasurementVal):
+ """Class representing time values"""
+ quantity = 'size'
+ gv_title = 'size in MiB'
+ gv_data_type = 'number'
+
+ def __str__(self):
+ if self != self:
+ return "nan"
+ if abs(self) < 1024:
+ return '{:.1f} kiB'.format(self)
+ elif abs(self) < 1048576:
+ return '{:.2f} MiB'.format(self / 1024)
+ else:
+ return '{:.2f} GiB'.format(self / 1048576)
+
+ def gv_value(self):
+ """Value formatting for visualization"""
+ if self != self:
+ return "null"
+ return self / 1024
+
+def measurement_stats(meas, prefix=''):
+ """Get statistics of a measurement"""
+ if not meas:
+ return {prefix + 'sample_cnt': 0,
+ prefix + 'mean': MeasurementVal('nan'),
+ prefix + 'stdev': MeasurementVal('nan'),
+ prefix + 'variance': MeasurementVal('nan'),
+ prefix + 'min': MeasurementVal('nan'),
+ prefix + 'max': MeasurementVal('nan'),
+ prefix + 'minus': MeasurementVal('nan'),
+ prefix + 'plus': MeasurementVal('nan')}
+
+ stats = {'name': meas['name']}
+ if meas['type'] == 'sysres':
+ val_cls = TimeVal
+ values = meas['values']['elapsed_time']
+ elif meas['type'] == 'diskusage':
+ val_cls = SizeVal
+ values = meas['values']['size']
+ else:
+ raise Exception("Unknown measurement type '{}'".format(meas['type']))
+ stats['val_cls'] = val_cls
+ stats['quantity'] = val_cls.quantity
+ stats[prefix + 'sample_cnt'] = len(values)
+
+ mean_val = val_cls(mean(values))
+ min_val = val_cls(min(values))
+ max_val = val_cls(max(values))
+
+ stats[prefix + 'mean'] = mean_val
+ if len(values) > 1:
+ stats[prefix + 'stdev'] = val_cls(stdev(values))
+ stats[prefix + 'variance'] = val_cls(variance(values))
+ else:
+ stats[prefix + 'stdev'] = float('nan')
+ stats[prefix + 'variance'] = float('nan')
+ stats[prefix + 'min'] = min_val
+ stats[prefix + 'max'] = max_val
+ stats[prefix + 'minus'] = val_cls(mean_val - min_val)
+ stats[prefix + 'plus'] = val_cls(max_val - mean_val)
+
+ return stats
+
diff --git a/scripts/lib/build_perf/scrape-html-report.js b/scripts/lib/build_perf/scrape-html-report.js
new file mode 100644
index 0000000000..05a1f57001
--- /dev/null
+++ b/scripts/lib/build_perf/scrape-html-report.js
@@ -0,0 +1,56 @@
+var fs = require('fs');
+var system = require('system');
+var page = require('webpage').create();
+
+// Examine console log for message from chart drawing
+page.onConsoleMessage = function(msg) {
+ console.log(msg);
+ if (msg === "ALL CHARTS READY") {
+ window.charts_ready = true;
+ }
+ else if (msg.slice(0, 11) === "CHART READY") {
+ var chart_id = msg.split(" ")[2];
+ console.log('grabbing ' + chart_id);
+ var png_data = page.evaluate(function (chart_id) {
+ var chart_div = document.getElementById(chart_id + '_png');
+ return chart_div.outerHTML;
+ }, chart_id);
+ fs.write(args[2] + '/' + chart_id + '.png', png_data, 'w');
+ }
+};
+
+// Check command line arguments
+var args = system.args;
+if (args.length != 3) {
+ console.log("USAGE: " + args[0] + " REPORT_HTML OUT_DIR\n");
+ phantom.exit(1);
+}
+
+// Open the web page
+page.open(args[1], function(status) {
+ if (status == 'fail') {
+ console.log("Failed to open file '" + args[1] + "'");
+ phantom.exit(1);
+ }
+});
+
+// Check status every 100 ms
+interval = window.setInterval(function () {
+ //console.log('waiting');
+ if (window.charts_ready) {
+ clearTimeout(timer);
+ clearInterval(interval);
+
+ var fname = args[1].replace(/\/+$/, "").split("/").pop()
+ console.log("saving " + fname);
+ fs.write(args[2] + '/' + fname, page.content, 'w');
+ phantom.exit(0);
+ }
+}, 100);
+
+// Time-out after 10 seconds
+timer = window.setTimeout(function () {
+ clearInterval(interval);
+ console.log("ERROR: timeout");
+ phantom.exit(1);
+}, 10000);
diff --git a/scripts/lib/buildstats.py b/scripts/lib/buildstats.py
new file mode 100644
index 0000000000..c69b5bf4d7
--- /dev/null
+++ b/scripts/lib/buildstats.py
@@ -0,0 +1,346 @@
+#
+# Copyright (c) 2017, Intel Corporation.
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+"""Functionality for analyzing buildstats"""
+import json
+import logging
+import os
+import re
+from collections import namedtuple,OrderedDict
+from statistics import mean
+
+
+log = logging.getLogger()
+
+
+taskdiff_fields = ('pkg', 'pkg_op', 'task', 'task_op', 'value1', 'value2',
+ 'absdiff', 'reldiff')
+TaskDiff = namedtuple('TaskDiff', ' '.join(taskdiff_fields))
+
+
+class BSError(Exception):
+ """Error handling of buildstats"""
+ pass
+
+
+class BSTask(dict):
+ def __init__(self, *args, **kwargs):
+ self['start_time'] = None
+ self['elapsed_time'] = None
+ self['status'] = None
+ self['iostat'] = {}
+ self['rusage'] = {}
+ self['child_rusage'] = {}
+ super(BSTask, self).__init__(*args, **kwargs)
+
+ @property
+ def cputime(self):
+ """Sum of user and system time taken by the task"""
+ rusage = self['rusage']['ru_stime'] + self['rusage']['ru_utime']
+ if self['child_rusage']:
+ # Child rusage may have been optimized out
+ return rusage + self['child_rusage']['ru_stime'] + self['child_rusage']['ru_utime']
+ else:
+ return rusage
+
+ @property
+ def walltime(self):
+ """Elapsed wall clock time"""
+ return self['elapsed_time']
+
+ @property
+ def read_bytes(self):
+ """Bytes read from the block layer"""
+ return self['iostat']['read_bytes']
+
+ @property
+ def write_bytes(self):
+ """Bytes written to the block layer"""
+ return self['iostat']['write_bytes']
+
+ @property
+ def read_ops(self):
+ """Number of read operations on the block layer"""
+ if self['child_rusage']:
+ # Child rusage may have been optimized out
+ return self['rusage']['ru_inblock'] + self['child_rusage']['ru_inblock']
+ else:
+ return self['rusage']['ru_inblock']
+
+ @property
+ def write_ops(self):
+ """Number of write operations on the block layer"""
+ if self['child_rusage']:
+ # Child rusage may have been optimized out
+ return self['rusage']['ru_oublock'] + self['child_rusage']['ru_oublock']
+ else:
+ return self['rusage']['ru_oublock']
+
+ @classmethod
+ def from_file(cls, buildstat_file):
+ """Read buildstat text file"""
+ bs_task = cls()
+ log.debug("Reading task buildstats from %s", buildstat_file)
+ end_time = None
+ with open(buildstat_file) as fobj:
+ for line in fobj.readlines():
+ key, val = line.split(':', 1)
+ val = val.strip()
+ if key == 'Started':
+ start_time = float(val)
+ bs_task['start_time'] = start_time
+ elif key == 'Ended':
+ end_time = float(val)
+ elif key.startswith('IO '):
+ split = key.split()
+ bs_task['iostat'][split[1]] = int(val)
+ elif key.find('rusage') >= 0:
+ split = key.split()
+ ru_key = split[-1]
+ if ru_key in ('ru_stime', 'ru_utime'):
+ val = float(val)
+ else:
+ val = int(val)
+ ru_type = 'rusage' if split[0] == 'rusage' else \
+ 'child_rusage'
+ bs_task[ru_type][ru_key] = val
+ elif key == 'Status':
+ bs_task['status'] = val
+ if end_time is not None and start_time is not None:
+ bs_task['elapsed_time'] = end_time - start_time
+ else:
+ raise BSError("{} looks like a invalid buildstats file".format(buildstat_file))
+ return bs_task
+
+
+class BSTaskAggregate(object):
+ """Class representing multiple runs of the same task"""
+ properties = ('cputime', 'walltime', 'read_bytes', 'write_bytes',
+ 'read_ops', 'write_ops')
+
+ def __init__(self, tasks=None):
+ self._tasks = tasks or []
+ self._properties = {}
+
+ def __getattr__(self, name):
+ if name in self.properties:
+ if name not in self._properties:
+ # Calculate properties on demand only. We only provide mean
+ # value, so far
+ self._properties[name] = mean([getattr(t, name) for t in self._tasks])
+ return self._properties[name]
+ else:
+ raise AttributeError("'BSTaskAggregate' has no attribute '{}'".format(name))
+
+ def append(self, task):
+ """Append new task"""
+ # Reset pre-calculated properties
+ assert isinstance(task, BSTask), "Type is '{}' instead of 'BSTask'".format(type(task))
+ self._properties = {}
+ self._tasks.append(task)
+
+
+class BSRecipe(object):
+ """Class representing buildstats of one recipe"""
+ def __init__(self, name, epoch, version, revision):
+ self.name = name
+ self.epoch = epoch
+ self.version = version
+ self.revision = revision
+ if epoch is None:
+ self.evr = "{}-{}".format(version, revision)
+ else:
+ self.evr = "{}_{}-{}".format(epoch, version, revision)
+ self.tasks = {}
+
+ def aggregate(self, bsrecipe):
+ """Aggregate data of another recipe buildstats"""
+ if self.nevr != bsrecipe.nevr:
+ raise ValueError("Refusing to aggregate buildstats, recipe version "
+ "differs: {} vs. {}".format(self.nevr, bsrecipe.nevr))
+ if set(self.tasks.keys()) != set(bsrecipe.tasks.keys()):
+ raise ValueError("Refusing to aggregate buildstats, set of tasks "
+ "in {} differ".format(self.name))
+
+ for taskname, taskdata in bsrecipe.tasks.items():
+ if not isinstance(self.tasks[taskname], BSTaskAggregate):
+ self.tasks[taskname] = BSTaskAggregate([self.tasks[taskname]])
+ self.tasks[taskname].append(taskdata)
+
+ @property
+ def nevr(self):
+ return self.name + '-' + self.evr
+
+
+class BuildStats(dict):
+ """Class representing buildstats of one build"""
+
+ @property
+ def num_tasks(self):
+ """Get number of tasks"""
+ num = 0
+ for recipe in self.values():
+ num += len(recipe.tasks)
+ return num
+
+ @classmethod
+ def from_json(cls, bs_json):
+ """Create new BuildStats object from JSON object"""
+ buildstats = cls()
+ for recipe in bs_json:
+ if recipe['name'] in buildstats:
+ raise BSError("Cannot handle multiple versions of the same "
+ "package ({})".format(recipe['name']))
+ bsrecipe = BSRecipe(recipe['name'], recipe['epoch'],
+ recipe['version'], recipe['revision'])
+ for task, data in recipe['tasks'].items():
+ bsrecipe.tasks[task] = BSTask(data)
+
+ buildstats[recipe['name']] = bsrecipe
+
+ return buildstats
+
+ @staticmethod
+ def from_file_json(path):
+ """Load buildstats from a JSON file"""
+ with open(path) as fobj:
+ bs_json = json.load(fobj)
+ return BuildStats.from_json(bs_json)
+
+
+ @staticmethod
+ def split_nevr(nevr):
+ """Split name and version information from recipe "nevr" string"""
+ n_e_v, revision = nevr.rsplit('-', 1)
+ match = re.match(r'^(?P<name>\S+)-((?P<epoch>[0-9]{1,5})_)?(?P<version>[0-9]\S*)$',
+ n_e_v)
+ if not match:
+ # If we're not able to parse a version starting with a number, just
+ # take the part after last dash
+ match = re.match(r'^(?P<name>\S+)-((?P<epoch>[0-9]{1,5})_)?(?P<version>[^-]+)$',
+ n_e_v)
+ name = match.group('name')
+ version = match.group('version')
+ epoch = match.group('epoch')
+ return name, epoch, version, revision
+
+ @classmethod
+ def from_dir(cls, path):
+ """Load buildstats from a buildstats directory"""
+ if not os.path.isfile(os.path.join(path, 'build_stats')):
+ raise BSError("{} does not look like a buildstats directory".format(path))
+
+ log.debug("Reading buildstats directory %s", path)
+
+ buildstats = cls()
+ subdirs = os.listdir(path)
+ for dirname in subdirs:
+ recipe_dir = os.path.join(path, dirname)
+ if not os.path.isdir(recipe_dir):
+ continue
+ name, epoch, version, revision = cls.split_nevr(dirname)
+ bsrecipe = BSRecipe(name, epoch, version, revision)
+ for task in os.listdir(recipe_dir):
+ bsrecipe.tasks[task] = BSTask.from_file(
+ os.path.join(recipe_dir, task))
+ if name in buildstats:
+ raise BSError("Cannot handle multiple versions of the same "
+ "package ({})".format(name))
+ buildstats[name] = bsrecipe
+
+ return buildstats
+
+ def aggregate(self, buildstats):
+ """Aggregate other buildstats into this"""
+ if set(self.keys()) != set(buildstats.keys()):
+ raise ValueError("Refusing to aggregate buildstats, set of "
+ "recipes is different: %s" % (set(self.keys()) ^ set(buildstats.keys())))
+ for pkg, data in buildstats.items():
+ self[pkg].aggregate(data)
+
+
+def diff_buildstats(bs1, bs2, stat_attr, min_val=None, min_absdiff=None, only_tasks=[]):
+ """Compare the tasks of two buildstats"""
+ tasks_diff = []
+ pkgs = set(bs1.keys()).union(set(bs2.keys()))
+ for pkg in pkgs:
+ tasks1 = bs1[pkg].tasks if pkg in bs1 else {}
+ tasks2 = bs2[pkg].tasks if pkg in bs2 else {}
+ if only_tasks:
+ tasks1 = {k: v for k, v in tasks1.items() if k in only_tasks}
+ tasks2 = {k: v for k, v in tasks2.items() if k in only_tasks}
+
+ if not tasks1:
+ pkg_op = '+'
+ elif not tasks2:
+ pkg_op = '-'
+ else:
+ pkg_op = ' '
+
+ for task in set(tasks1.keys()).union(set(tasks2.keys())):
+ task_op = ' '
+ if task in tasks1:
+ val1 = getattr(bs1[pkg].tasks[task], stat_attr)
+ else:
+ task_op = '+'
+ val1 = 0
+ if task in tasks2:
+ val2 = getattr(bs2[pkg].tasks[task], stat_attr)
+ else:
+ val2 = 0
+ task_op = '-'
+
+ if val1 == 0:
+ reldiff = float('inf')
+ else:
+ reldiff = 100 * (val2 - val1) / val1
+
+ if min_val and max(val1, val2) < min_val:
+ log.debug("Filtering out %s:%s (%s)", pkg, task,
+ max(val1, val2))
+ continue
+ if min_absdiff and abs(val2 - val1) < min_absdiff:
+ log.debug("Filtering out %s:%s (difference of %s)", pkg, task,
+ val2-val1)
+ continue
+ tasks_diff.append(TaskDiff(pkg, pkg_op, task, task_op, val1, val2,
+ val2-val1, reldiff))
+ return tasks_diff
+
+
+class BSVerDiff(object):
+ """Class representing recipe version differences between two buildstats"""
+ def __init__(self, bs1, bs2):
+ RecipeVerDiff = namedtuple('RecipeVerDiff', 'left right')
+
+ recipes1 = set(bs1.keys())
+ recipes2 = set(bs2.keys())
+
+ self.new = dict([(r, bs2[r]) for r in sorted(recipes2 - recipes1)])
+ self.dropped = dict([(r, bs1[r]) for r in sorted(recipes1 - recipes2)])
+ self.echanged = {}
+ self.vchanged = {}
+ self.rchanged = {}
+ self.unchanged = {}
+ self.empty_diff = False
+
+ common = recipes2.intersection(recipes1)
+ if common:
+ for recipe in common:
+ rdiff = RecipeVerDiff(bs1[recipe], bs2[recipe])
+ if bs1[recipe].epoch != bs2[recipe].epoch:
+ self.echanged[recipe] = rdiff
+ elif bs1[recipe].version != bs2[recipe].version:
+ self.vchanged[recipe] = rdiff
+ elif bs1[recipe].revision != bs2[recipe].revision:
+ self.rchanged[recipe] = rdiff
+ else:
+ self.unchanged[recipe] = rdiff
+
+ if len(recipes1) == len(recipes2) == len(self.unchanged):
+ self.empty_diff = True
+
+ def __bool__(self):
+ return not self.empty_diff
diff --git a/scripts/lib/checklayer/__init__.py b/scripts/lib/checklayer/__init__.py
new file mode 100644
index 0000000000..e69a10f452
--- /dev/null
+++ b/scripts/lib/checklayer/__init__.py
@@ -0,0 +1,425 @@
+# Yocto Project layer check tool
+#
+# Copyright (C) 2017 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+#
+
+import os
+import re
+import subprocess
+from enum import Enum
+
+import bb.tinfoil
+
+class LayerType(Enum):
+ BSP = 0
+ DISTRO = 1
+ SOFTWARE = 2
+ ERROR_NO_LAYER_CONF = 98
+ ERROR_BSP_DISTRO = 99
+
+def _get_configurations(path):
+ configs = []
+
+ for f in os.listdir(path):
+ file_path = os.path.join(path, f)
+ if os.path.isfile(file_path) and f.endswith('.conf'):
+ configs.append(f[:-5]) # strip .conf
+ return configs
+
+def _get_layer_collections(layer_path, lconf=None, data=None):
+ import bb.parse
+ import bb.data
+
+ if lconf is None:
+ lconf = os.path.join(layer_path, 'conf', 'layer.conf')
+
+ if data is None:
+ ldata = bb.data.init()
+ bb.parse.init_parser(ldata)
+ else:
+ ldata = data.createCopy()
+
+ ldata.setVar('LAYERDIR', layer_path)
+ try:
+ ldata = bb.parse.handle(lconf, ldata, include=True)
+ except:
+ raise RuntimeError("Parsing of layer.conf from layer: %s failed" % layer_path)
+ ldata.expandVarref('LAYERDIR')
+
+ collections = (ldata.getVar('BBFILE_COLLECTIONS') or '').split()
+ if not collections:
+ name = os.path.basename(layer_path)
+ collections = [name]
+
+ collections = {c: {} for c in collections}
+ for name in collections:
+ priority = ldata.getVar('BBFILE_PRIORITY_%s' % name)
+ pattern = ldata.getVar('BBFILE_PATTERN_%s' % name)
+ depends = ldata.getVar('LAYERDEPENDS_%s' % name)
+ compat = ldata.getVar('LAYERSERIES_COMPAT_%s' % name)
+ try:
+ depDict = bb.utils.explode_dep_versions2(depends or "")
+ except bb.utils.VersionStringException as vse:
+ bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (name, str(vse)))
+
+ collections[name]['priority'] = priority
+ collections[name]['pattern'] = pattern
+ collections[name]['depends'] = ' '.join(depDict.keys())
+ collections[name]['compat'] = compat
+
+ return collections
+
+def _detect_layer(layer_path):
+ """
+ Scans layer directory to detect what type of layer
+ is BSP, Distro or Software.
+
+ Returns a dictionary with layer name, type and path.
+ """
+
+ layer = {}
+ layer_name = os.path.basename(layer_path)
+
+ layer['name'] = layer_name
+ layer['path'] = layer_path
+ layer['conf'] = {}
+
+ if not os.path.isfile(os.path.join(layer_path, 'conf', 'layer.conf')):
+ layer['type'] = LayerType.ERROR_NO_LAYER_CONF
+ return layer
+
+ machine_conf = os.path.join(layer_path, 'conf', 'machine')
+ distro_conf = os.path.join(layer_path, 'conf', 'distro')
+
+ is_bsp = False
+ is_distro = False
+
+ if os.path.isdir(machine_conf):
+ machines = _get_configurations(machine_conf)
+ if machines:
+ is_bsp = True
+
+ if os.path.isdir(distro_conf):
+ distros = _get_configurations(distro_conf)
+ if distros:
+ is_distro = True
+
+ if is_bsp and is_distro:
+ layer['type'] = LayerType.ERROR_BSP_DISTRO
+ elif is_bsp:
+ layer['type'] = LayerType.BSP
+ layer['conf']['machines'] = machines
+ elif is_distro:
+ layer['type'] = LayerType.DISTRO
+ layer['conf']['distros'] = distros
+ else:
+ layer['type'] = LayerType.SOFTWARE
+
+ layer['collections'] = _get_layer_collections(layer['path'])
+
+ return layer
+
+def detect_layers(layer_directories, no_auto):
+ layers = []
+
+ for directory in layer_directories:
+ directory = os.path.realpath(directory)
+ if directory[-1] == '/':
+ directory = directory[0:-1]
+
+ if no_auto:
+ conf_dir = os.path.join(directory, 'conf')
+ if os.path.isdir(conf_dir):
+ layer = _detect_layer(directory)
+ if layer:
+ layers.append(layer)
+ else:
+ for root, dirs, files in os.walk(directory):
+ dir_name = os.path.basename(root)
+ conf_dir = os.path.join(root, 'conf')
+ if os.path.isdir(conf_dir):
+ layer = _detect_layer(root)
+ if layer:
+ layers.append(layer)
+
+ return layers
+
+def _find_layer(depend, layers):
+ for layer in layers:
+ if 'collections' not in layer:
+ continue
+
+ for collection in layer['collections']:
+ if depend == collection:
+ return layer
+ return None
+
+def get_layer_dependencies(layer, layers, logger):
+ def recurse_dependencies(depends, layer, layers, logger, ret = []):
+ logger.debug('Processing dependencies %s for layer %s.' % \
+ (depends, layer['name']))
+
+ for depend in depends.split():
+ # core (oe-core) is suppose to be provided
+ if depend == 'core':
+ continue
+
+ layer_depend = _find_layer(depend, layers)
+ if not layer_depend:
+ logger.error('Layer %s depends on %s and isn\'t found.' % \
+ (layer['name'], depend))
+ ret = None
+ continue
+
+ # We keep processing, even if ret is None, this allows us to report
+ # multiple errors at once
+ if ret is not None and layer_depend not in ret:
+ ret.append(layer_depend)
+ else:
+ # we might have processed this dependency already, in which case
+ # we should not do it again (avoid recursive loop)
+ continue
+
+ # Recursively process...
+ if 'collections' not in layer_depend:
+ continue
+
+ for collection in layer_depend['collections']:
+ collect_deps = layer_depend['collections'][collection]['depends']
+ if not collect_deps:
+ continue
+ ret = recurse_dependencies(collect_deps, layer_depend, layers, logger, ret)
+
+ return ret
+
+ layer_depends = []
+ for collection in layer['collections']:
+ depends = layer['collections'][collection]['depends']
+ if not depends:
+ continue
+
+ layer_depends = recurse_dependencies(depends, layer, layers, logger, layer_depends)
+
+ # Note: [] (empty) is allowed, None is not!
+ return layer_depends
+
+def add_layer_dependencies(bblayersconf, layer, layers, logger):
+
+ layer_depends = get_layer_dependencies(layer, layers, logger)
+ if layer_depends is None:
+ return False
+ else:
+ add_layers(bblayersconf, layer_depends, logger)
+
+ return True
+
+def add_layers(bblayersconf, layers, logger):
+ # Don't add a layer that is already present.
+ added = set()
+ output = check_command('Getting existing layers failed.', 'bitbake-layers show-layers').decode('utf-8')
+ for layer, path, pri in re.findall(r'^(\S+) +([^\n]*?) +(\d+)$', output, re.MULTILINE):
+ added.add(path)
+
+ with open(bblayersconf, 'a+') as f:
+ for layer in layers:
+ logger.info('Adding layer %s' % layer['name'])
+ name = layer['name']
+ path = layer['path']
+ if path in added:
+ logger.info('%s is already in %s' % (name, bblayersconf))
+ else:
+ added.add(path)
+ f.write("\nBBLAYERS += \"%s\"\n" % path)
+ return True
+
+def check_bblayers(bblayersconf, layer_path, logger):
+ '''
+ If layer_path found in BBLAYERS return True
+ '''
+ import bb.parse
+ import bb.data
+
+ ldata = bb.parse.handle(bblayersconf, bb.data.init(), include=True)
+ for bblayer in (ldata.getVar('BBLAYERS') or '').split():
+ if os.path.normpath(bblayer) == os.path.normpath(layer_path):
+ return True
+
+ return False
+
+def check_command(error_msg, cmd, cwd=None):
+ '''
+ Run a command under a shell, capture stdout and stderr in a single stream,
+ throw an error when command returns non-zero exit code. Returns the output.
+ '''
+
+ p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd)
+ output, _ = p.communicate()
+ if p.returncode:
+ msg = "%s\nCommand: %s\nOutput:\n%s" % (error_msg, cmd, output.decode('utf-8'))
+ raise RuntimeError(msg)
+ return output
+
+def get_signatures(builddir, failsafe=False, machine=None):
+ import re
+
+ # some recipes needs to be excluded like meta-world-pkgdata
+ # because a layer can add recipes to a world build so signature
+ # will be change
+ exclude_recipes = ('meta-world-pkgdata',)
+
+ sigs = {}
+ tune2tasks = {}
+
+ cmd = 'BB_ENV_EXTRAWHITE="$BB_ENV_EXTRAWHITE BB_SIGNATURE_HANDLER" BB_SIGNATURE_HANDLER="OEBasicHash" '
+ if machine:
+ cmd += 'MACHINE=%s ' % machine
+ cmd += 'bitbake '
+ if failsafe:
+ cmd += '-k '
+ cmd += '-S none world'
+ sigs_file = os.path.join(builddir, 'locked-sigs.inc')
+ if os.path.exists(sigs_file):
+ os.unlink(sigs_file)
+ try:
+ check_command('Generating signatures failed. This might be due to some parse error and/or general layer incompatibilities.',
+ cmd, builddir)
+ except RuntimeError as ex:
+ if failsafe and os.path.exists(sigs_file):
+ # Ignore the error here. Most likely some recipes active
+ # in a world build lack some dependencies. There is a
+ # separate test_machine_world_build which exposes the
+ # failure.
+ pass
+ else:
+ raise
+
+ sig_regex = re.compile("^(?P<task>.*:.*):(?P<hash>.*) .$")
+ tune_regex = re.compile("(^|\s)SIGGEN_LOCKEDSIGS_t-(?P<tune>\S*)\s*=\s*")
+ current_tune = None
+ with open(sigs_file, 'r') as f:
+ for line in f.readlines():
+ line = line.strip()
+ t = tune_regex.search(line)
+ if t:
+ current_tune = t.group('tune')
+ s = sig_regex.match(line)
+ if s:
+ exclude = False
+ for er in exclude_recipes:
+ (recipe, task) = s.group('task').split(':')
+ if er == recipe:
+ exclude = True
+ break
+ if exclude:
+ continue
+
+ sigs[s.group('task')] = s.group('hash')
+ tune2tasks.setdefault(current_tune, []).append(s.group('task'))
+
+ if not sigs:
+ raise RuntimeError('Can\'t load signatures from %s' % sigs_file)
+
+ return (sigs, tune2tasks)
+
+def get_depgraph(targets=['world'], failsafe=False):
+ '''
+ Returns the dependency graph for the given target(s).
+ The dependency graph is taken directly from DepTreeEvent.
+ '''
+ depgraph = None
+ with bb.tinfoil.Tinfoil() as tinfoil:
+ tinfoil.prepare(config_only=False)
+ tinfoil.set_event_mask(['bb.event.NoProvider', 'bb.event.DepTreeGenerated', 'bb.command.CommandCompleted'])
+ if not tinfoil.run_command('generateDepTreeEvent', targets, 'do_build'):
+ raise RuntimeError('starting generateDepTreeEvent failed')
+ while True:
+ event = tinfoil.wait_event(timeout=1000)
+ if event:
+ if isinstance(event, bb.command.CommandFailed):
+ raise RuntimeError('Generating dependency information failed: %s' % event.error)
+ elif isinstance(event, bb.command.CommandCompleted):
+ break
+ elif isinstance(event, bb.event.NoProvider):
+ if failsafe:
+ # The event is informational, we will get information about the
+ # remaining dependencies eventually and thus can ignore this
+ # here like we do in get_signatures(), if desired.
+ continue
+ if event._reasons:
+ raise RuntimeError('Nothing provides %s: %s' % (event._item, event._reasons))
+ else:
+ raise RuntimeError('Nothing provides %s.' % (event._item))
+ elif isinstance(event, bb.event.DepTreeGenerated):
+ depgraph = event._depgraph
+
+ if depgraph is None:
+ raise RuntimeError('Could not retrieve the depgraph.')
+ return depgraph
+
+def compare_signatures(old_sigs, curr_sigs):
+ '''
+ Compares the result of two get_signatures() calls. Returns None if no
+ problems found, otherwise a string that can be used as additional
+ explanation in self.fail().
+ '''
+ # task -> (old signature, new signature)
+ sig_diff = {}
+ for task in old_sigs:
+ if task in curr_sigs and \
+ old_sigs[task] != curr_sigs[task]:
+ sig_diff[task] = (old_sigs[task], curr_sigs[task])
+
+ if not sig_diff:
+ return None
+
+ # Beware, depgraph uses task=<pn>.<taskname> whereas get_signatures()
+ # uses <pn>:<taskname>. Need to convert sometimes. The output follows
+ # the convention from get_signatures() because that seems closer to
+ # normal bitbake output.
+ def sig2graph(task):
+ pn, taskname = task.rsplit(':', 1)
+ return pn + '.' + taskname
+ def graph2sig(task):
+ pn, taskname = task.rsplit('.', 1)
+ return pn + ':' + taskname
+ depgraph = get_depgraph(failsafe=True)
+ depends = depgraph['tdepends']
+
+ # If a task A has a changed signature, but none of its
+ # dependencies, then we need to report it because it is
+ # the one which introduces a change. Any task depending on
+ # A (directly or indirectly) will also have a changed
+ # signature, but we don't need to report it. It might have
+ # its own changes, which will become apparent once the
+ # issues that we do report are fixed and the test gets run
+ # again.
+ sig_diff_filtered = []
+ for task, (old_sig, new_sig) in sig_diff.items():
+ deps_tainted = False
+ for dep in depends.get(sig2graph(task), ()):
+ if graph2sig(dep) in sig_diff:
+ deps_tainted = True
+ break
+ if not deps_tainted:
+ sig_diff_filtered.append((task, old_sig, new_sig))
+
+ msg = []
+ msg.append('%d signatures changed, initial differences (first hash before, second after):' %
+ len(sig_diff))
+ for diff in sorted(sig_diff_filtered):
+ recipe, taskname = diff[0].rsplit(':', 1)
+ cmd = 'bitbake-diffsigs --task %s %s --signature %s %s' % \
+ (recipe, taskname, diff[1], diff[2])
+ msg.append(' %s: %s -> %s' % diff)
+ msg.append(' %s' % cmd)
+ try:
+ output = check_command('Determining signature difference failed.',
+ cmd).decode('utf-8')
+ except RuntimeError as error:
+ output = str(error)
+ if output:
+ msg.extend([' ' + line for line in output.splitlines()])
+ msg.append('')
+ return '\n'.join(msg)
diff --git a/scripts/lib/checklayer/case.py b/scripts/lib/checklayer/case.py
new file mode 100644
index 0000000000..fa9dee384e
--- /dev/null
+++ b/scripts/lib/checklayer/case.py
@@ -0,0 +1,9 @@
+# Copyright (C) 2017 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+#
+
+from oeqa.core.case import OETestCase
+
+class OECheckLayerTestCase(OETestCase):
+ pass
diff --git a/scripts/lib/wic/3rdparty/pykickstart/__init__.py b/scripts/lib/checklayer/cases/__init__.py
index e69de29bb2..e69de29bb2 100644
--- a/scripts/lib/wic/3rdparty/pykickstart/__init__.py
+++ b/scripts/lib/checklayer/cases/__init__.py
diff --git a/scripts/lib/checklayer/cases/bsp.py b/scripts/lib/checklayer/cases/bsp.py
new file mode 100644
index 0000000000..7fd56f5d36
--- /dev/null
+++ b/scripts/lib/checklayer/cases/bsp.py
@@ -0,0 +1,206 @@
+# Copyright (C) 2017 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+#
+
+import unittest
+
+from checklayer import LayerType, get_signatures, check_command, get_depgraph
+from checklayer.case import OECheckLayerTestCase
+
+class BSPCheckLayer(OECheckLayerTestCase):
+ @classmethod
+ def setUpClass(self):
+ if self.tc.layer['type'] != LayerType.BSP:
+ raise unittest.SkipTest("BSPCheckLayer: Layer %s isn't BSP one." %\
+ self.tc.layer['name'])
+
+ def test_bsp_defines_machines(self):
+ self.assertTrue(self.tc.layer['conf']['machines'],
+ "Layer is BSP but doesn't defines machines.")
+
+ def test_bsp_no_set_machine(self):
+ from oeqa.utils.commands import get_bb_var
+
+ machine = get_bb_var('MACHINE')
+ self.assertEqual(self.td['bbvars']['MACHINE'], machine,
+ msg="Layer %s modified machine %s -> %s" % \
+ (self.tc.layer['name'], self.td['bbvars']['MACHINE'], machine))
+
+
+ def test_machine_world(self):
+ '''
+ "bitbake world" is expected to work regardless which machine is selected.
+ BSP layers sometimes break that by enabling a recipe for a certain machine
+ without checking whether that recipe actually can be built in the current
+ distro configuration (for example, OpenGL might not enabled).
+
+ This test iterates over all machines. It would be nicer to instantiate
+ it once per machine. It merely checks for errors during parse
+ time. It does not actually attempt to build anything.
+ '''
+
+ if not self.td['machines']:
+ self.skipTest('No machines set with --machines.')
+ msg = []
+ for machine in self.td['machines']:
+ # In contrast to test_machine_signatures() below, errors are fatal here.
+ try:
+ get_signatures(self.td['builddir'], failsafe=False, machine=machine)
+ except RuntimeError as ex:
+ msg.append(str(ex))
+ if msg:
+ msg.insert(0, 'The following machines broke a world build:')
+ self.fail('\n'.join(msg))
+
+ def test_machine_signatures(self):
+ '''
+ Selecting a machine may only affect the signature of tasks that are specific
+ to that machine. In other words, when MACHINE=A and MACHINE=B share a recipe
+ foo and the output of foo, then both machine configurations must build foo
+ in exactly the same way. Otherwise it is not possible to use both machines
+ in the same distribution.
+
+ This criteria can only be tested by testing different machines in combination,
+ i.e. one main layer, potentially several additional BSP layers and an explicit
+ choice of machines:
+ yocto-check-layer --additional-layers .../meta-intel --machines intel-corei7-64 imx6slevk -- .../meta-freescale
+ '''
+
+ if not self.td['machines']:
+ self.skipTest('No machines set with --machines.')
+
+ # Collect signatures for all machines that we are testing
+ # and merge that into a hash:
+ # tune -> task -> signature -> list of machines with that combination
+ #
+ # It is an error if any tune/task pair has more than one signature,
+ # because that implies that the machines that caused those different
+ # signatures do not agree on how to execute the task.
+ tunes = {}
+ # Preserve ordering of machines as chosen by the user.
+ for machine in self.td['machines']:
+ curr_sigs, tune2tasks = get_signatures(self.td['builddir'], failsafe=True, machine=machine)
+ # Invert the tune -> [tasks] mapping.
+ tasks2tune = {}
+ for tune, tasks in tune2tasks.items():
+ for task in tasks:
+ tasks2tune[task] = tune
+ for task, sighash in curr_sigs.items():
+ tunes.setdefault(tasks2tune[task], {}).setdefault(task, {}).setdefault(sighash, []).append(machine)
+
+ msg = []
+ pruned = 0
+ last_line_key = None
+ # do_fetch, do_unpack, ..., do_build
+ taskname_list = []
+ if tunes:
+ # The output below is most useful when we start with tasks that are at
+ # the bottom of the dependency chain, i.e. those that run first. If
+ # those tasks differ, the rest also does.
+ #
+ # To get an ordering of tasks, we do a topological sort of the entire
+ # depgraph for the base configuration, then on-the-fly flatten that list by stripping
+ # out the recipe names and removing duplicates. The base configuration
+ # is not necessarily representative, but should be close enough. Tasks
+ # that were not encountered get a default priority.
+ depgraph = get_depgraph()
+ depends = depgraph['tdepends']
+ WHITE = 1
+ GRAY = 2
+ BLACK = 3
+ color = {}
+ found = set()
+ def visit(task):
+ color[task] = GRAY
+ for dep in depends.get(task, ()):
+ if color.setdefault(dep, WHITE) == WHITE:
+ visit(dep)
+ color[task] = BLACK
+ pn, taskname = task.rsplit('.', 1)
+ if taskname not in found:
+ taskname_list.append(taskname)
+ found.add(taskname)
+ for task in depends.keys():
+ if color.setdefault(task, WHITE) == WHITE:
+ visit(task)
+
+ taskname_order = dict([(task, index) for index, task in enumerate(taskname_list) ])
+ def task_key(task):
+ pn, taskname = task.rsplit(':', 1)
+ return (pn, taskname_order.get(taskname, len(taskname_list)), taskname)
+
+ for tune in sorted(tunes.keys()):
+ tasks = tunes[tune]
+ # As for test_signatures it would be nicer to sort tasks
+ # by dependencies here, but that is harder because we have
+ # to report on tasks from different machines, which might
+ # have different dependencies. We resort to pruning the
+ # output by reporting only one task per recipe if the set
+ # of machines matches.
+ #
+ # "bitbake-diffsigs -t -s" is intelligent enough to print
+ # diffs recursively, so often it does not matter that much
+ # if we don't pick the underlying difference
+ # here. However, sometimes recursion fails
+ # (https://bugzilla.yoctoproject.org/show_bug.cgi?id=6428).
+ #
+ # To mitigate that a bit, we use a hard-coded ordering of
+ # tasks that represents how they normally run and prefer
+ # to print the ones that run first.
+ for task in sorted(tasks.keys(), key=task_key):
+ signatures = tasks[task]
+ # do_build can be ignored: it is know to have
+ # different signatures in some cases, for example in
+ # the allarch ca-certificates due to RDEPENDS=openssl.
+ # That particular dependency is whitelisted via
+ # SIGGEN_EXCLUDE_SAFE_RECIPE_DEPS, but still shows up
+ # in the sstate signature hash because filtering it
+ # out would be hard and running do_build multiple
+ # times doesn't really matter.
+ if len(signatures.keys()) > 1 and \
+ not task.endswith(':do_build'):
+ # Error!
+ #
+ # Sort signatures by machines, because the hex values don't mean anything.
+ # => all-arch adwaita-icon-theme:do_build: 1234... (beaglebone, qemux86) != abcdf... (qemux86-64)
+ #
+ # Skip the line if it is covered already by the predecessor (same pn, same sets of machines).
+ pn, taskname = task.rsplit(':', 1)
+ next_line_key = (pn, sorted(signatures.values()))
+ if next_line_key != last_line_key:
+ line = ' %s %s: ' % (tune, task)
+ line += ' != '.join(['%s (%s)' % (signature, ', '.join([m for m in signatures[signature]])) for
+ signature in sorted(signatures.keys(), key=lambda s: signatures[s])])
+ last_line_key = next_line_key
+ msg.append(line)
+ # Randomly pick two mismatched signatures and remember how to invoke
+ # bitbake-diffsigs for them.
+ iterator = iter(signatures.items())
+ a = next(iterator)
+ b = next(iterator)
+ diffsig_machines = '(%s) != (%s)' % (', '.join(a[1]), ', '.join(b[1]))
+ diffsig_params = '-t %s %s -s %s %s' % (pn, taskname, a[0], b[0])
+ else:
+ pruned += 1
+
+ if msg:
+ msg.insert(0, 'The machines have conflicting signatures for some shared tasks:')
+ if pruned > 0:
+ msg.append('')
+ msg.append('%d tasks where not listed because some other task of the recipe already differed.' % pruned)
+ msg.append('It is likely that differences from different recipes also have the same root cause.')
+ msg.append('')
+ # Explain how to investigate...
+ msg.append('To investigate, run bitbake-diffsigs -t recipename taskname -s fromsig tosig.')
+ cmd = 'bitbake-diffsigs %s' % diffsig_params
+ msg.append('Example: %s in the last line' % diffsig_machines)
+ msg.append('Command: %s' % cmd)
+ # ... and actually do it automatically for that example, but without aborting
+ # when that fails.
+ try:
+ output = check_command('Comparing signatures failed.', cmd).decode('utf-8')
+ except RuntimeError as ex:
+ output = str(ex)
+ msg.extend([' ' + line for line in output.splitlines()])
+ self.fail('\n'.join(msg))
diff --git a/scripts/lib/checklayer/cases/common.py b/scripts/lib/checklayer/cases/common.py
new file mode 100644
index 0000000000..b82304e361
--- /dev/null
+++ b/scripts/lib/checklayer/cases/common.py
@@ -0,0 +1,60 @@
+# Copyright (C) 2017 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+#
+
+import glob
+import os
+import unittest
+from checklayer import get_signatures, LayerType, check_command, get_depgraph, compare_signatures
+from checklayer.case import OECheckLayerTestCase
+
+class CommonCheckLayer(OECheckLayerTestCase):
+ def test_readme(self):
+ # The top-level README file may have a suffix (like README.rst or README.txt).
+ readme_files = glob.glob(os.path.join(self.tc.layer['path'], '[Rr][Ee][Aa][Dd][Mm][Ee]*'))
+ self.assertTrue(len(readme_files) > 0,
+ msg="Layer doesn't contains README file.")
+
+ # There might be more than one file matching the file pattern above
+ # (for example, README.rst and README-COPYING.rst). The one with the shortest
+ # name is considered the "main" one.
+ readme_file = sorted(readme_files)[0]
+ data = ''
+ with open(readme_file, 'r') as f:
+ data = f.read()
+ self.assertTrue(data,
+ msg="Layer contains a README file but it is empty.")
+
+ def test_parse(self):
+ check_command('Layer %s failed to parse.' % self.tc.layer['name'],
+ 'bitbake -p')
+
+ def test_show_environment(self):
+ check_command('Layer %s failed to show environment.' % self.tc.layer['name'],
+ 'bitbake -e')
+
+ def test_world(self):
+ '''
+ "bitbake world" is expected to work. test_signatures does not cover that
+ because it is more lenient and ignores recipes in a world build that
+ are not actually buildable, so here we fail when "bitbake -S none world"
+ fails.
+ '''
+ get_signatures(self.td['builddir'], failsafe=False)
+
+ def test_signatures(self):
+ if self.tc.layer['type'] == LayerType.SOFTWARE and \
+ not self.tc.test_software_layer_signatures:
+ raise unittest.SkipTest("Not testing for signature changes in a software layer %s." \
+ % self.tc.layer['name'])
+
+ curr_sigs, _ = get_signatures(self.td['builddir'], failsafe=True)
+ msg = compare_signatures(self.td['sigs'], curr_sigs)
+ if msg is not None:
+ self.fail('Adding layer %s changed signatures.\n%s' % (self.tc.layer['name'], msg))
+
+ def test_layerseries_compat(self):
+ for collection_name, collection_data in self.tc.layer['collections'].items():
+ self.assertTrue(collection_data['compat'], "Collection %s from layer %s does not set compatible oe-core versions via LAYERSERIES_COMPAT_collection." \
+ % (collection_name, self.tc.layer['name']))
diff --git a/scripts/lib/checklayer/cases/distro.py b/scripts/lib/checklayer/cases/distro.py
new file mode 100644
index 0000000000..f0bee5493c
--- /dev/null
+++ b/scripts/lib/checklayer/cases/distro.py
@@ -0,0 +1,28 @@
+# Copyright (C) 2017 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+#
+
+import unittest
+
+from checklayer import LayerType
+from checklayer.case import OECheckLayerTestCase
+
+class DistroCheckLayer(OECheckLayerTestCase):
+ @classmethod
+ def setUpClass(self):
+ if self.tc.layer['type'] != LayerType.DISTRO:
+ raise unittest.SkipTest("DistroCheckLayer: Layer %s isn't Distro one." %\
+ self.tc.layer['name'])
+
+ def test_distro_defines_distros(self):
+ self.assertTrue(self.tc.layer['conf']['distros'],
+ "Layer is BSP but doesn't defines machines.")
+
+ def test_distro_no_set_distros(self):
+ from oeqa.utils.commands import get_bb_var
+
+ distro = get_bb_var('DISTRO')
+ self.assertEqual(self.td['bbvars']['DISTRO'], distro,
+ msg="Layer %s modified distro %s -> %s" % \
+ (self.tc.layer['name'], self.td['bbvars']['DISTRO'], distro))
diff --git a/scripts/lib/checklayer/context.py b/scripts/lib/checklayer/context.py
new file mode 100644
index 0000000000..4de8f668fd
--- /dev/null
+++ b/scripts/lib/checklayer/context.py
@@ -0,0 +1,17 @@
+# Copyright (C) 2017 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+#
+
+import os
+import sys
+import glob
+import re
+
+from oeqa.core.context import OETestContext
+
+class CheckLayerTestContext(OETestContext):
+ def __init__(self, td=None, logger=None, layer=None, test_software_layer_signatures=True):
+ super(CheckLayerTestContext, self).__init__(td, logger)
+ self.layer = layer
+ self.test_software_layer_signatures = test_software_layer_signatures
diff --git a/scripts/lib/devtool/__init__.py b/scripts/lib/devtool/__init__.py
index 404d3e6645..702db669de 100644
--- a/scripts/lib/devtool/__init__.py
+++ b/scripts/lib/devtool/__init__.py
@@ -1,34 +1,27 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Development tool - utility functions for plugins
#
# Copyright (C) 2014 Intel Corporation
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
+# SPDX-License-Identifier: GPL-2.0-only
#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Devtool plugins module"""
import os
import sys
import subprocess
import logging
+import re
+import codecs
logger = logging.getLogger('devtool')
-
class DevtoolError(Exception):
"""Exception for handling devtool errors"""
- pass
+ def __init__(self, message, exitcode=1):
+ super(DevtoolError, self).__init__(message)
+ self.exitcode = exitcode
def exec_build_env_command(init_path, builddir, cmd, watch=False, **options):
@@ -58,16 +51,17 @@ def exec_build_env_command(init_path, builddir, cmd, watch=False, **options):
def exec_watch(cmd, **options):
"""Run program with stdout shown on sys.stdout"""
import bb
- if isinstance(cmd, basestring) and not "shell" in options:
+ if isinstance(cmd, str) and not "shell" in options:
options["shell"] = True
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **options
)
+ reader = codecs.getreader('utf-8')(process.stdout)
buf = ''
while True:
- out = process.stdout.read(1)
+ out = reader.read(1, 1)
if out:
sys.stdout.write(out)
sys.stdout.flush()
@@ -83,56 +77,303 @@ def exec_watch(cmd, **options):
def exec_fakeroot(d, cmd, **kwargs):
"""Run a command under fakeroot (pseudo, in fact) so that it picks up the appropriate file permissions"""
# Grab the command and check it actually exists
- fakerootcmd = d.getVar('FAKEROOTCMD', True)
+ fakerootcmd = d.getVar('FAKEROOTCMD')
if not os.path.exists(fakerootcmd):
logger.error('pseudo executable %s could not be found - have you run a build yet? pseudo-native should install this and if you have run any build then that should have been built')
return 2
# Set up the appropriate environment
newenv = dict(os.environ)
- fakerootenv = d.getVar('FAKEROOTENV', True)
+ fakerootenv = d.getVar('FAKEROOTENV')
for varvalue in fakerootenv.split():
if '=' in varvalue:
splitval = varvalue.split('=', 1)
newenv[splitval[0]] = splitval[1]
return subprocess.call("%s %s" % (fakerootcmd, cmd), env=newenv, **kwargs)
-def setup_tinfoil(config_only=False):
+def setup_tinfoil(config_only=False, basepath=None, tracking=False):
"""Initialize tinfoil api from bitbake"""
import scriptpath
- bitbakepath = scriptpath.add_bitbake_lib_path()
- if not bitbakepath:
- logger.error("Unable to find bitbake by searching parent directory of this script or PATH")
- sys.exit(1)
-
- import bb.tinfoil
- tinfoil = bb.tinfoil.Tinfoil()
- tinfoil.prepare(config_only)
- tinfoil.logger.setLevel(logger.getEffectiveLevel())
+ orig_cwd = os.path.abspath(os.curdir)
+ try:
+ if basepath:
+ os.chdir(basepath)
+ bitbakepath = scriptpath.add_bitbake_lib_path()
+ if not bitbakepath:
+ logger.error("Unable to find bitbake by searching parent directory of this script or PATH")
+ sys.exit(1)
+
+ import bb.tinfoil
+ tinfoil = bb.tinfoil.Tinfoil(tracking=tracking)
+ try:
+ tinfoil.logger.setLevel(logger.getEffectiveLevel())
+ tinfoil.prepare(config_only)
+ except bb.tinfoil.TinfoilUIException:
+ tinfoil.shutdown()
+ raise DevtoolError('Failed to start bitbake environment')
+ except:
+ tinfoil.shutdown()
+ raise
+ finally:
+ os.chdir(orig_cwd)
return tinfoil
-def get_recipe_file(cooker, pn):
- """Find recipe file corresponding a package name"""
- import oe.recipeutils
- recipefile = oe.recipeutils.pn_to_recipe(cooker, pn)
- if not recipefile:
- skipreasons = oe.recipeutils.get_unavailable_reasons(cooker, pn)
- if skipreasons:
- logger.error('\n'.join(skipreasons))
- else:
- logger.error("Unable to find any recipe file matching %s" % pn)
- return recipefile
-
-def parse_recipe(config, tinfoil, pn, appends):
- """Parse recipe of a package"""
- import oe.recipeutils
- recipefile = get_recipe_file(tinfoil.cooker, pn)
- if not recipefile:
- # Error already logged
+def parse_recipe(config, tinfoil, pn, appends, filter_workspace=True):
+ """Parse the specified recipe"""
+ try:
+ recipefile = tinfoil.get_recipe_file(pn)
+ except bb.providers.NoProvider as e:
+ logger.error(str(e))
return None
if appends:
- append_files = tinfoil.cooker.collection.get_file_appends(recipefile)
- # Filter out appends from the workspace
- append_files = [path for path in append_files if
- not path.startswith(config.workspace_path)]
- return oe.recipeutils.parse_recipe(recipefile, append_files,
- tinfoil.config_data)
+ append_files = tinfoil.get_file_appends(recipefile)
+ if filter_workspace:
+ # Filter out appends from the workspace
+ append_files = [path for path in append_files if
+ not path.startswith(config.workspace_path)]
+ else:
+ append_files = None
+ try:
+ rd = tinfoil.parse_recipe_file(recipefile, appends, append_files)
+ except Exception as e:
+ logger.error(str(e))
+ return None
+ return rd
+
+def check_workspace_recipe(workspace, pn, checksrc=True, bbclassextend=False):
+ """
+ Check that a recipe is in the workspace and (optionally) that source
+ is present.
+ """
+
+ workspacepn = pn
+
+ for recipe, value in workspace.items():
+ if recipe == pn:
+ break
+ if bbclassextend:
+ recipefile = value['recipefile']
+ if recipefile:
+ targets = get_bbclassextend_targets(recipefile, recipe)
+ if pn in targets:
+ workspacepn = recipe
+ break
+ else:
+ raise DevtoolError("No recipe named '%s' in your workspace" % pn)
+
+ if checksrc:
+ srctree = workspace[workspacepn]['srctree']
+ if not os.path.exists(srctree):
+ raise DevtoolError("Source tree %s for recipe %s does not exist" % (srctree, workspacepn))
+ if not os.listdir(srctree):
+ raise DevtoolError("Source tree %s for recipe %s is empty" % (srctree, workspacepn))
+
+ return workspacepn
+
+def use_external_build(same_dir, no_same_dir, d):
+ """
+ Determine if we should use B!=S (separate build and source directories) or not
+ """
+ b_is_s = True
+ if no_same_dir:
+ logger.info('Using separate build directory since --no-same-dir specified')
+ b_is_s = False
+ elif same_dir:
+ logger.info('Using source tree as build directory since --same-dir specified')
+ elif bb.data.inherits_class('autotools-brokensep', d):
+ logger.info('Using source tree as build directory since recipe inherits autotools-brokensep')
+ elif os.path.abspath(d.getVar('B')) == os.path.abspath(d.getVar('S')):
+ logger.info('Using source tree as build directory since that would be the default for this recipe')
+ else:
+ b_is_s = False
+ return b_is_s
+
+def setup_git_repo(repodir, version, devbranch, basetag='devtool-base', d=None):
+ """
+ Set up the git repository for the source tree
+ """
+ import bb.process
+ import oe.patch
+ if not os.path.exists(os.path.join(repodir, '.git')):
+ bb.process.run('git init', cwd=repodir)
+ bb.process.run('git config --local gc.autodetach 0', cwd=repodir)
+ bb.process.run('git add -f -A .', cwd=repodir)
+ commit_cmd = ['git']
+ oe.patch.GitApplyTree.gitCommandUserOptions(commit_cmd, d=d)
+ commit_cmd += ['commit', '-q']
+ stdout, _ = bb.process.run('git status --porcelain', cwd=repodir)
+ if not stdout:
+ commit_cmd.append('--allow-empty')
+ commitmsg = "Initial empty commit with no upstream sources"
+ elif version:
+ commitmsg = "Initial commit from upstream at version %s" % version
+ else:
+ commitmsg = "Initial commit from upstream"
+ commit_cmd += ['-m', commitmsg]
+ bb.process.run(commit_cmd, cwd=repodir)
+
+ # Ensure singletask.lock (as used by externalsrc.bbclass) is ignored by git
+ gitinfodir = os.path.join(repodir, '.git', 'info')
+ try:
+ os.mkdir(gitinfodir)
+ except FileExistsError:
+ pass
+ excludes = []
+ excludefile = os.path.join(gitinfodir, 'exclude')
+ try:
+ with open(excludefile, 'r') as f:
+ excludes = f.readlines()
+ except FileNotFoundError:
+ pass
+ if 'singletask.lock\n' not in excludes:
+ excludes.append('singletask.lock\n')
+ with open(excludefile, 'w') as f:
+ for line in excludes:
+ f.write(line)
+
+ bb.process.run('git checkout -b %s' % devbranch, cwd=repodir)
+ bb.process.run('git tag -f %s' % basetag, cwd=repodir)
+
+def recipe_to_append(recipefile, config, wildcard=False):
+ """
+ Convert a recipe file to a bbappend file path within the workspace.
+ NOTE: if the bbappend already exists, you should be using
+ workspace[args.recipename]['bbappend'] instead of calling this
+ function.
+ """
+ appendname = os.path.splitext(os.path.basename(recipefile))[0]
+ if wildcard:
+ appendname = re.sub(r'_.*', '_%', appendname)
+ appendpath = os.path.join(config.workspace_path, 'appends')
+ appendfile = os.path.join(appendpath, appendname + '.bbappend')
+ return appendfile
+
+def get_bbclassextend_targets(recipefile, pn):
+ """
+ Cheap function to get BBCLASSEXTEND and then convert that to the
+ list of targets that would result.
+ """
+ import bb.utils
+
+ values = {}
+ def get_bbclassextend_varfunc(varname, origvalue, op, newlines):
+ values[varname] = origvalue
+ return origvalue, None, 0, True
+ with open(recipefile, 'r') as f:
+ bb.utils.edit_metadata(f, ['BBCLASSEXTEND'], get_bbclassextend_varfunc)
+
+ targets = []
+ bbclassextend = values.get('BBCLASSEXTEND', '').split()
+ if bbclassextend:
+ for variant in bbclassextend:
+ if variant == 'nativesdk':
+ targets.append('%s-%s' % (variant, pn))
+ elif variant in ['native', 'cross', 'crosssdk']:
+ targets.append('%s-%s' % (pn, variant))
+ return targets
+
+def replace_from_file(path, old, new):
+ """Replace strings on a file"""
+
+ def read_file(path):
+ data = None
+ with open(path) as f:
+ data = f.read()
+ return data
+
+ def write_file(path, data):
+ if data is None:
+ return
+ wdata = data.rstrip() + "\n"
+ with open(path, "w") as f:
+ f.write(wdata)
+
+ # In case old is None, return immediately
+ if old is None:
+ return
+ try:
+ rdata = read_file(path)
+ except IOError as e:
+ # if file does not exit, just quit, otherwise raise an exception
+ if e.errno == errno.ENOENT:
+ return
+ else:
+ raise
+
+ old_contents = rdata.splitlines()
+ new_contents = []
+ for old_content in old_contents:
+ try:
+ new_contents.append(old_content.replace(old, new))
+ except ValueError:
+ pass
+ write_file(path, "\n".join(new_contents))
+
+
+def update_unlockedsigs(basepath, workspace, fixed_setup, extra=None):
+ """ This function will make unlocked-sigs.inc match the recipes in the
+ workspace plus any extras we want unlocked. """
+
+ if not fixed_setup:
+ # Only need to write this out within the eSDK
+ return
+
+ if not extra:
+ extra = []
+
+ confdir = os.path.join(basepath, 'conf')
+ unlockedsigs = os.path.join(confdir, 'unlocked-sigs.inc')
+
+ # Get current unlocked list if any
+ values = {}
+ def get_unlockedsigs_varfunc(varname, origvalue, op, newlines):
+ values[varname] = origvalue
+ return origvalue, None, 0, True
+ if os.path.exists(unlockedsigs):
+ with open(unlockedsigs, 'r') as f:
+ bb.utils.edit_metadata(f, ['SIGGEN_UNLOCKED_RECIPES'], get_unlockedsigs_varfunc)
+ unlocked = sorted(values.get('SIGGEN_UNLOCKED_RECIPES', []))
+
+ # If the new list is different to the current list, write it out
+ newunlocked = sorted(list(workspace.keys()) + extra)
+ if unlocked != newunlocked:
+ bb.utils.mkdirhier(confdir)
+ with open(unlockedsigs, 'w') as f:
+ f.write("# DO NOT MODIFY! YOUR CHANGES WILL BE LOST.\n" +
+ "# This layer was created by the OpenEmbedded devtool" +
+ " utility in order to\n" +
+ "# contain recipes that are unlocked.\n")
+
+ f.write('SIGGEN_UNLOCKED_RECIPES += "\\\n')
+ for pn in newunlocked:
+ f.write(' ' + pn)
+ f.write('"')
+
+def check_prerelease_version(ver, operation):
+ if 'pre' in ver or 'rc' in ver:
+ logger.warning('Version "%s" looks like a pre-release version. '
+ 'If that is the case, in order to ensure that the '
+ 'version doesn\'t appear to go backwards when you '
+ 'later upgrade to the final release version, it is '
+ 'recommmended that instead you use '
+ '<current version>+<pre-release version> e.g. if '
+ 'upgrading from 1.9 to 2.0-rc2 use "1.9+2.0-rc2". '
+ 'If you prefer not to reset and re-try, you can change '
+ 'the version after %s succeeds using "devtool rename" '
+ 'with -V/--version.' % (ver, operation))
+
+def check_git_repo_dirty(repodir):
+ """Check if a git repository is clean or not"""
+ stdout, _ = bb.process.run('git status --porcelain', cwd=repodir)
+ return stdout
+
+def check_git_repo_op(srctree, ignoredirs=None):
+ """Check if a git repository is in the middle of a rebase"""
+ stdout, _ = bb.process.run('git rev-parse --show-toplevel', cwd=srctree)
+ topleveldir = stdout.strip()
+ if ignoredirs and topleveldir in ignoredirs:
+ return
+ gitdir = os.path.join(topleveldir, '.git')
+ if os.path.exists(os.path.join(gitdir, 'rebase-merge')):
+ raise DevtoolError("Source tree %s appears to be in the middle of a rebase - please resolve this first" % srctree)
+ if os.path.exists(os.path.join(gitdir, 'rebase-apply')):
+ raise DevtoolError("Source tree %s appears to be in the middle of 'git am' or 'git apply' - please resolve this first" % srctree)
diff --git a/scripts/lib/devtool/build-image.py b/scripts/lib/devtool/build-image.py
deleted file mode 100644
index 817703a0e5..0000000000
--- a/scripts/lib/devtool/build-image.py
+++ /dev/null
@@ -1,95 +0,0 @@
-# Development tool - build-image plugin
-#
-# Copyright (C) 2015 Intel Corporation
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-"""Devtool plugin containing the build-image subcommand."""
-
-import os
-import logging
-
-from bb.process import ExecutionError
-from devtool import exec_build_env_command, setup_tinfoil, parse_recipe
-
-logger = logging.getLogger('devtool')
-
-def plugin_init(pluginlist):
- """Plugin initialization"""
- pass
-
-def _get_recipes(workspace, config):
- """Get list of target recipes from the workspace."""
- result = []
- tinfoil = setup_tinfoil()
- for recipe in workspace:
- data = parse_recipe(config, tinfoil, recipe, True)
- if 'class-target' in data.getVar('OVERRIDES', True).split(':'):
- if recipe in data.getVar('PACKAGES', True):
- result.append(recipe)
- else:
- logger.warning("Skipping recipe %s as it doesn't produce "
- "package with the same name", recipe)
- tinfoil.shutdown()
- return result
-
-def build_image(args, config, basepath, workspace):
- """Entry point for the devtool 'build-image' subcommand."""
- image = args.recipe
- appendfile = os.path.join(config.workspace_path, 'appends',
- '%s.bbappend' % image)
-
- # remove <image>.bbapend to make sure setup_tinfoil doesn't
- # breake because of it
- if os.path.isfile(appendfile):
- os.unlink(appendfile)
-
- recipes = _get_recipes(workspace, config)
- if recipes:
- with open(appendfile, 'w') as afile:
- # include selected recipes into the image
- afile.write('IMAGE_INSTALL_append = " %s"\n' % ' '.join(recipes))
-
- # Generate notification callback devtool_warn_image_extended
- afile.write('do_rootfs[prefuncs] += "devtool_warn_image_extended"\n\n')
- afile.write("python devtool_warn_image_extended() {\n")
- afile.write(" bb.plain('NOTE: %%s: building with additional '\n"
- " 'packages due to \"devtool build-image\"'"
- " %% d.getVar('PN', True))\n"
- " bb.plain('NOTE: delete %%s to clear this' %% \\\n"
- " '%s')\n" % os.path.relpath(appendfile, basepath))
- afile.write("}\n")
-
- logger.info('Building image %s with the following '
- 'additional packages: %s', image, ' '.join(recipes))
- else:
- logger.warning('No recipes in workspace, building image %s unmodified', image)
-
- # run bitbake to build image
- try:
- exec_build_env_command(config.init_path, basepath,
- 'bitbake %s' % image, watch=True)
- except ExecutionError as err:
- return err.exitcode
-
- logger.info('Successfully built %s', image)
-
-def register_commands(subparsers, context):
- """Register devtool subcommands from the build-image plugin"""
- parser = subparsers.add_parser('build-image',
- help='Build image including workspace recipe packages',
- description='Builds an image, extending it to include '
- 'packages from recipes in the workspace')
- parser.add_argument('recipe', help='Image recipe to build')
- parser.set_defaults(func=build_image)
diff --git a/scripts/lib/devtool/build.py b/scripts/lib/devtool/build.py
new file mode 100644
index 0000000000..935ffab46c
--- /dev/null
+++ b/scripts/lib/devtool/build.py
@@ -0,0 +1,92 @@
+# Development tool - build command plugin
+#
+# Copyright (C) 2014-2015 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+"""Devtool build plugin"""
+
+import os
+import bb
+import logging
+import argparse
+import tempfile
+from devtool import exec_build_env_command, setup_tinfoil, check_workspace_recipe, DevtoolError
+from devtool import parse_recipe
+
+logger = logging.getLogger('devtool')
+
+
+def _set_file_values(fn, values):
+ remaining = list(values.keys())
+
+ def varfunc(varname, origvalue, op, newlines):
+ newvalue = values.get(varname, origvalue)
+ remaining.remove(varname)
+ return (newvalue, '=', 0, True)
+
+ with open(fn, 'r') as f:
+ (updated, newlines) = bb.utils.edit_metadata(f, values, varfunc)
+
+ for item in remaining:
+ updated = True
+ newlines.append('%s = "%s"' % (item, values[item]))
+
+ if updated:
+ with open(fn, 'w') as f:
+ f.writelines(newlines)
+ return updated
+
+def _get_build_tasks(config):
+ tasks = config.get('Build', 'build_task', 'populate_sysroot,packagedata').split(',')
+ return ['do_%s' % task.strip() for task in tasks]
+
+def build(args, config, basepath, workspace):
+ """Entry point for the devtool 'build' subcommand"""
+ workspacepn = check_workspace_recipe(workspace, args.recipename, bbclassextend=True)
+ tinfoil = setup_tinfoil(config_only=False, basepath=basepath)
+ try:
+ rd = parse_recipe(config, tinfoil, args.recipename, appends=True, filter_workspace=False)
+ if not rd:
+ return 1
+ deploytask = 'do_deploy' in rd.getVar('__BBTASKS')
+ finally:
+ tinfoil.shutdown()
+
+ if args.clean:
+ # use clean instead of cleansstate to avoid messing things up in eSDK
+ build_tasks = ['do_clean']
+ else:
+ build_tasks = _get_build_tasks(config)
+ if deploytask:
+ build_tasks.append('do_deploy')
+
+ bbappend = workspace[workspacepn]['bbappend']
+ if args.disable_parallel_make:
+ logger.info("Disabling 'make' parallelism")
+ _set_file_values(bbappend, {'PARALLEL_MAKE': ''})
+ try:
+ bbargs = []
+ for task in build_tasks:
+ if args.recipename.endswith('-native') and 'package' in task:
+ continue
+ bbargs.append('%s:%s' % (args.recipename, task))
+ exec_build_env_command(config.init_path, basepath, 'bitbake %s' % ' '.join(bbargs), watch=True)
+ except bb.process.ExecutionError as e:
+ # We've already seen the output since watch=True, so just ensure we return something to the user
+ return e.exitcode
+ finally:
+ if args.disable_parallel_make:
+ _set_file_values(bbappend, {'PARALLEL_MAKE': None})
+
+ return 0
+
+def register_commands(subparsers, context):
+ """Register devtool subcommands from this plugin"""
+ parser_build = subparsers.add_parser('build', help='Build a recipe',
+ description='Builds the specified recipe using bitbake (up to and including %s)' % ', '.join(_get_build_tasks(context.config)),
+ group='working', order=50)
+ parser_build.add_argument('recipename', help='Recipe to build')
+ parser_build.add_argument('-s', '--disable-parallel-make', action="store_true", help='Disable make parallelism')
+ parser_build.add_argument('-c', '--clean', action='store_true', help='clean up recipe building results')
+ parser_build.set_defaults(func=build)
diff --git a/scripts/lib/devtool/build_image.py b/scripts/lib/devtool/build_image.py
new file mode 100644
index 0000000000..980f90ddd6
--- /dev/null
+++ b/scripts/lib/devtool/build_image.py
@@ -0,0 +1,164 @@
+# Development tool - build-image plugin
+#
+# Copyright (C) 2015 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+"""Devtool plugin containing the build-image subcommand."""
+
+import os
+import errno
+import logging
+
+from bb.process import ExecutionError
+from devtool import exec_build_env_command, setup_tinfoil, parse_recipe, DevtoolError
+
+logger = logging.getLogger('devtool')
+
+class TargetNotImageError(Exception):
+ pass
+
+def _get_packages(tinfoil, workspace, config):
+ """Get list of packages from recipes in the workspace."""
+ result = []
+ for recipe in workspace:
+ data = parse_recipe(config, tinfoil, recipe, True)
+ if 'class-target' in data.getVar('OVERRIDES').split(':'):
+ if recipe in data.getVar('PACKAGES').split():
+ result.append(recipe)
+ else:
+ logger.warning("Skipping recipe %s as it doesn't produce a "
+ "package with the same name", recipe)
+ return result
+
+def build_image(args, config, basepath, workspace):
+ """Entry point for the devtool 'build-image' subcommand."""
+
+ image = args.imagename
+ auto_image = False
+ if not image:
+ sdk_targets = config.get('SDK', 'sdk_targets', '').split()
+ if sdk_targets:
+ image = sdk_targets[0]
+ auto_image = True
+ if not image:
+ raise DevtoolError('Unable to determine image to build, please specify one')
+
+ try:
+ if args.add_packages:
+ add_packages = args.add_packages.split(',')
+ else:
+ add_packages = None
+ result, outputdir = build_image_task(config, basepath, workspace, image, add_packages)
+ except TargetNotImageError:
+ if auto_image:
+ raise DevtoolError('Unable to determine image to build, please specify one')
+ else:
+ raise DevtoolError('Specified recipe %s is not an image recipe' % image)
+
+ if result == 0:
+ logger.info('Successfully built %s. You can find output files in %s'
+ % (image, outputdir))
+ return result
+
+def build_image_task(config, basepath, workspace, image, add_packages=None, task=None, extra_append=None):
+ # remove <image>.bbappend to make sure setup_tinfoil doesn't
+ # break because of it
+ target_basename = config.get('SDK', 'target_basename', '')
+ if target_basename:
+ appendfile = os.path.join(config.workspace_path, 'appends',
+ '%s.bbappend' % target_basename)
+ try:
+ os.unlink(appendfile)
+ except OSError as exc:
+ if exc.errno != errno.ENOENT:
+ raise
+
+ tinfoil = setup_tinfoil(basepath=basepath)
+ try:
+ rd = parse_recipe(config, tinfoil, image, True)
+ if not rd:
+ # Error already shown
+ return (1, None)
+ if not bb.data.inherits_class('image', rd):
+ raise TargetNotImageError()
+
+ # Get the actual filename used and strip the .bb and full path
+ target_basename = rd.getVar('FILE')
+ target_basename = os.path.splitext(os.path.basename(target_basename))[0]
+ config.set('SDK', 'target_basename', target_basename)
+ config.write()
+
+ appendfile = os.path.join(config.workspace_path, 'appends',
+ '%s.bbappend' % target_basename)
+
+ outputdir = None
+ try:
+ if workspace or add_packages:
+ if add_packages:
+ packages = add_packages
+ else:
+ packages = _get_packages(tinfoil, workspace, config)
+ else:
+ packages = None
+ if not task:
+ if not packages and not add_packages and workspace:
+ logger.warning('No recipes in workspace, building image %s unmodified', image)
+ elif not packages:
+ logger.warning('No packages to add, building image %s unmodified', image)
+
+ if packages or extra_append:
+ bb.utils.mkdirhier(os.path.dirname(appendfile))
+ with open(appendfile, 'w') as afile:
+ if packages:
+ # include packages from workspace recipes into the image
+ afile.write('IMAGE_INSTALL:append = " %s"\n' % ' '.join(packages))
+ if not task:
+ logger.info('Building image %s with the following '
+ 'additional packages: %s', image, ' '.join(packages))
+ if extra_append:
+ for line in extra_append:
+ afile.write('%s\n' % line)
+
+ if task in ['populate_sdk', 'populate_sdk_ext']:
+ outputdir = rd.getVar('SDK_DEPLOY')
+ else:
+ outputdir = rd.getVar('DEPLOY_DIR_IMAGE')
+
+ tmp_tinfoil = tinfoil
+ tinfoil = None
+ tmp_tinfoil.shutdown()
+
+ options = ''
+ if task:
+ options += '-c %s' % task
+
+ # run bitbake to build image (or specified task)
+ try:
+ exec_build_env_command(config.init_path, basepath,
+ 'bitbake %s %s' % (options, image), watch=True)
+ except ExecutionError as err:
+ return (err.exitcode, None)
+ finally:
+ if os.path.isfile(appendfile):
+ os.unlink(appendfile)
+ finally:
+ if tinfoil:
+ tinfoil.shutdown()
+ return (0, outputdir)
+
+
+def register_commands(subparsers, context):
+ """Register devtool subcommands from the build-image plugin"""
+ parser = subparsers.add_parser('build-image',
+ help='Build image including workspace recipe packages',
+ description='Builds an image, extending it to include '
+ 'packages from recipes in the workspace',
+ group='testbuild', order=-10)
+ parser.add_argument('imagename', help='Image recipe to build', nargs='?')
+ parser.add_argument('-p', '--add-packages', help='Instead of adding packages for the '
+ 'entire workspace, specify packages to be added to the image '
+ '(separate multiple packages by commas)',
+ metavar='PACKAGES')
+ parser.set_defaults(func=build_image)
diff --git a/scripts/lib/devtool/build_sdk.py b/scripts/lib/devtool/build_sdk.py
new file mode 100644
index 0000000000..6fe02fff2a
--- /dev/null
+++ b/scripts/lib/devtool/build_sdk.py
@@ -0,0 +1,55 @@
+# Development tool - build-sdk command plugin
+#
+# Copyright (C) 2015-2016 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import os
+import subprocess
+import logging
+import glob
+import shutil
+import errno
+import sys
+import tempfile
+from devtool import exec_build_env_command, setup_tinfoil, parse_recipe, DevtoolError
+from devtool import build_image
+
+logger = logging.getLogger('devtool')
+
+
+def build_sdk(args, config, basepath, workspace):
+ """Entry point for the devtool build-sdk command"""
+
+ sdk_targets = config.get('SDK', 'sdk_targets', '').split()
+ if sdk_targets:
+ image = sdk_targets[0]
+ else:
+ raise DevtoolError('Unable to determine image to build SDK for')
+
+ extra_append = ['SDK_DERIVATIVE = "1"']
+ try:
+ result, outputdir = build_image.build_image_task(config,
+ basepath,
+ workspace,
+ image,
+ task='populate_sdk_ext',
+ extra_append=extra_append)
+ except build_image.TargetNotImageError:
+ raise DevtoolError('Unable to determine image to build SDK for')
+
+ if result == 0:
+ logger.info('Successfully built SDK. You can find output files in %s'
+ % outputdir)
+ return result
+
+
+def register_commands(subparsers, context):
+ """Register devtool subcommands"""
+ if context.fixed_setup:
+ parser_build_sdk = subparsers.add_parser('build-sdk',
+ help='Build a derivative SDK of this one',
+ description='Builds an extensible SDK based upon this one and the items in your workspace',
+ group='advanced')
+ parser_build_sdk.set_defaults(func=build_sdk)
diff --git a/scripts/lib/devtool/deploy.py b/scripts/lib/devtool/deploy.py
index 448db9637d..833322571f 100644
--- a/scripts/lib/devtool/deploy.py
+++ b/scripts/lib/devtool/deploy.py
@@ -1,117 +1,278 @@
# Development tool - deploy/undeploy command plugin
#
-# Copyright (C) 2014-2015 Intel Corporation
+# Copyright (C) 2014-2016 Intel Corporation
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
+# SPDX-License-Identifier: GPL-2.0-only
#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Devtool plugin containing the deploy subcommands"""
+import logging
import os
+import shutil
import subprocess
-import logging
-from devtool import exec_fakeroot, setup_tinfoil, DevtoolError
+import tempfile
+
+import bb.utils
+import argparse_oe
+import oe.types
+
+from devtool import exec_fakeroot, setup_tinfoil, check_workspace_recipe, DevtoolError
logger = logging.getLogger('devtool')
-def plugin_init(pluginlist):
- """Plugin initialization"""
- pass
+deploylist_path = '/.devtool'
+
+def _prepare_remote_script(deploy, verbose=False, dryrun=False, undeployall=False, nopreserve=False, nocheckspace=False):
+ """
+ Prepare a shell script for running on the target to
+ deploy/undeploy files. We have to be careful what we put in this
+ script - only commands that are likely to be available on the
+ target are suitable (the target might be constrained, e.g. using
+ busybox rather than bash with coreutils).
+ """
+ lines = []
+ lines.append('#!/bin/sh')
+ lines.append('set -e')
+ if undeployall:
+ # Yes, I know this is crude - but it does work
+ lines.append('for entry in %s/*.list; do' % deploylist_path)
+ lines.append('[ ! -f $entry ] && exit')
+ lines.append('set `basename $entry | sed "s/.list//"`')
+ if dryrun:
+ if not deploy:
+ lines.append('echo "Previously deployed files for $1:"')
+ lines.append('manifest="%s/$1.list"' % deploylist_path)
+ lines.append('preservedir="%s/$1.preserve"' % deploylist_path)
+ lines.append('if [ -f $manifest ] ; then')
+ # Read manifest in reverse and delete files / remove empty dirs
+ lines.append(' sed \'1!G;h;$!d\' $manifest | while read file')
+ lines.append(' do')
+ if dryrun:
+ lines.append(' if [ ! -d $file ] ; then')
+ lines.append(' echo $file')
+ lines.append(' fi')
+ else:
+ lines.append(' if [ -d $file ] ; then')
+ # Avoid deleting a preserved directory in case it has special perms
+ lines.append(' if [ ! -d $preservedir/$file ] ; then')
+ lines.append(' rmdir $file > /dev/null 2>&1 || true')
+ lines.append(' fi')
+ lines.append(' else')
+ lines.append(' rm -f $file')
+ lines.append(' fi')
+ lines.append(' done')
+ if not dryrun:
+ lines.append(' rm $manifest')
+ if not deploy and not dryrun:
+ # May as well remove all traces
+ lines.append(' rmdir `dirname $manifest` > /dev/null 2>&1 || true')
+ lines.append('fi')
+
+ if deploy:
+ if not nocheckspace:
+ # Check for available space
+ # FIXME This doesn't take into account files spread across multiple
+ # partitions, but doing that is non-trivial
+ # Find the part of the destination path that exists
+ lines.append('checkpath="$2"')
+ lines.append('while [ "$checkpath" != "/" ] && [ ! -e $checkpath ]')
+ lines.append('do')
+ lines.append(' checkpath=`dirname "$checkpath"`')
+ lines.append('done')
+ lines.append(r'freespace=$(df -P $checkpath | sed -nre "s/^(\S+\s+){3}([0-9]+).*/\2/p")')
+ # First line of the file is the total space
+ lines.append('total=`head -n1 $3`')
+ lines.append('if [ $total -gt $freespace ] ; then')
+ lines.append(' echo "ERROR: insufficient space on target (available ${freespace}, needed ${total})"')
+ lines.append(' exit 1')
+ lines.append('fi')
+ if not nopreserve:
+ # Preserve any files that exist. Note that this will add to the
+ # preserved list with successive deployments if the list of files
+ # deployed changes, but because we've deleted any previously
+ # deployed files at this point it will never preserve anything
+ # that was deployed, only files that existed prior to any deploying
+ # (which makes the most sense)
+ lines.append('cat $3 | sed "1d" | while read file fsize')
+ lines.append('do')
+ lines.append(' if [ -e $file ] ; then')
+ lines.append(' dest="$preservedir/$file"')
+ lines.append(' mkdir -p `dirname $dest`')
+ lines.append(' mv $file $dest')
+ lines.append(' fi')
+ lines.append('done')
+ lines.append('rm $3')
+ lines.append('mkdir -p `dirname $manifest`')
+ lines.append('mkdir -p $2')
+ if verbose:
+ lines.append(' tar xv -C $2 -f - | tee $manifest')
+ else:
+ lines.append(' tar xv -C $2 -f - > $manifest')
+ lines.append('sed -i "s!^./!$2!" $manifest')
+ elif not dryrun:
+ # Put any preserved files back
+ lines.append('if [ -d $preservedir ] ; then')
+ lines.append(' cd $preservedir')
+ # find from busybox might not have -exec, so we don't use that
+ lines.append(' find . -type f | while read file')
+ lines.append(' do')
+ lines.append(' mv $file /$file')
+ lines.append(' done')
+ lines.append(' cd /')
+ lines.append(' rm -rf $preservedir')
+ lines.append('fi')
+
+ if undeployall:
+ if not dryrun:
+ lines.append('echo "NOTE: Successfully undeployed $1"')
+ lines.append('done')
+
+ # Delete the script itself
+ lines.append('rm $0')
+ lines.append('')
+
+ return '\n'.join(lines)
+
def deploy(args, config, basepath, workspace):
"""Entry point for the devtool 'deploy' subcommand"""
- import re
+ import math
import oe.recipeutils
+ import oe.package
+
+ check_workspace_recipe(workspace, args.recipename, checksrc=False)
- if not args.recipename in workspace:
- raise DevtoolError("no recipe named %s in your workspace" %
- args.recipename)
try:
host, destdir = args.target.split(':')
except ValueError:
destdir = '/'
else:
args.target = host
+ if not destdir.endswith('/'):
+ destdir += '/'
- deploy_dir = os.path.join(basepath, 'target_deploy', args.target)
- deploy_file = os.path.join(deploy_dir, args.recipename + '.list')
-
- tinfoil = setup_tinfoil()
+ tinfoil = setup_tinfoil(basepath=basepath)
try:
- rd = oe.recipeutils.parse_recipe_simple(tinfoil.cooker, args.recipename, tinfoil.config_data)
- except Exception as e:
- raise DevtoolError('Exception parsing recipe %s: %s' %
- (args.recipename, e))
- recipe_outdir = rd.getVar('D', True)
- if not os.path.exists(recipe_outdir) or not os.listdir(recipe_outdir):
- raise DevtoolError('No files to deploy - have you built the %s '
- 'recipe? If so, the install step has not installed '
- 'any files.' % args.recipename)
-
- if args.dry_run:
- print('Files to be deployed for %s on target %s:' % (args.recipename, args.target))
+ try:
+ rd = tinfoil.parse_recipe(args.recipename)
+ except Exception as e:
+ raise DevtoolError('Exception parsing recipe %s: %s' %
+ (args.recipename, e))
+ recipe_outdir = rd.getVar('D')
+ if not os.path.exists(recipe_outdir) or not os.listdir(recipe_outdir):
+ raise DevtoolError('No files to deploy - have you built the %s '
+ 'recipe? If so, the install step has not installed '
+ 'any files.' % args.recipename)
+
+ if args.strip and not args.dry_run:
+ # Fakeroot copy to new destination
+ srcdir = recipe_outdir
+ recipe_outdir = os.path.join(rd.getVar('WORKDIR'), 'devtool-deploy-target-stripped')
+ if os.path.isdir(recipe_outdir):
+ bb.utils.remove(recipe_outdir, True)
+ exec_fakeroot(rd, "cp -af %s %s" % (os.path.join(srcdir, '.'), recipe_outdir), shell=True)
+ os.environ['PATH'] = ':'.join([os.environ['PATH'], rd.getVar('PATH') or ''])
+ oe.package.strip_execs(args.recipename, recipe_outdir, rd.getVar('STRIP'), rd.getVar('libdir'),
+ rd.getVar('base_libdir'), rd)
+
+ filelist = []
+ inodes = set({})
+ ftotalsize = 0
for root, _, files in os.walk(recipe_outdir):
for fn in files:
- print(' %s' % os.path.join(destdir, os.path.relpath(root, recipe_outdir), fn))
- return 0
+ fstat = os.lstat(os.path.join(root, fn))
+ # Get the size in kiB (since we'll be comparing it to the output of du -k)
+ # MUST use lstat() here not stat() or getfilesize() since we don't want to
+ # dereference symlinks
+ if fstat.st_ino in inodes:
+ fsize = 0
+ else:
+ fsize = int(math.ceil(float(fstat.st_size)/1024))
+ inodes.add(fstat.st_ino)
+ ftotalsize += fsize
+ # The path as it would appear on the target
+ fpath = os.path.join(destdir, os.path.relpath(root, recipe_outdir), fn)
+ filelist.append((fpath, fsize))
- if os.path.exists(deploy_file):
- if undeploy(args, config, basepath, workspace):
- # Error already shown
- return 1
+ if args.dry_run:
+ print('Files to be deployed for %s on target %s:' % (args.recipename, args.target))
+ for item, _ in filelist:
+ print(' %s' % item)
+ return 0
- extraoptions = ''
- if args.no_host_check:
- extraoptions += '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
- if args.show_status:
- tarextractopts = 'xv'
- else:
- tarextractopts = 'x'
- extraoptions += ' -q'
- # We cannot use scp here, because it doesn't preserve symlinks
- ret = exec_fakeroot(rd, 'tar cf - . | ssh %s %s \'tar %s -C %s -f -\'' % (extraoptions, args.target, tarextractopts, destdir), cwd=recipe_outdir, shell=True)
- if ret != 0:
- raise DevtoolError('Deploy failed - rerun with -s to get a complete '
- 'error message')
+ extraoptions = ''
+ if args.no_host_check:
+ extraoptions += '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
+ if not args.show_status:
+ extraoptions += ' -q'
+
+ scp_sshexec = ''
+ ssh_sshexec = 'ssh'
+ if args.ssh_exec:
+ scp_sshexec = "-S %s" % args.ssh_exec
+ ssh_sshexec = args.ssh_exec
+ scp_port = ''
+ ssh_port = ''
+ if args.port:
+ scp_port = "-P %s" % args.port
+ ssh_port = "-p %s" % args.port
+
+ if args.key:
+ extraoptions += ' -i %s' % args.key
- logger.info('Successfully deployed %s' % recipe_outdir)
+ # In order to delete previously deployed files and have the manifest file on
+ # the target, we write out a shell script and then copy it to the target
+ # so we can then run it (piping tar output to it).
+ # (We cannot use scp here, because it doesn't preserve symlinks.)
+ tmpdir = tempfile.mkdtemp(prefix='devtool')
+ try:
+ tmpscript = '/tmp/devtool_deploy.sh'
+ tmpfilelist = os.path.join(os.path.dirname(tmpscript), 'devtool_deploy.list')
+ shellscript = _prepare_remote_script(deploy=True,
+ verbose=args.show_status,
+ nopreserve=args.no_preserve,
+ nocheckspace=args.no_check_space)
+ # Write out the script to a file
+ with open(os.path.join(tmpdir, os.path.basename(tmpscript)), 'w') as f:
+ f.write(shellscript)
+ # Write out the file list
+ with open(os.path.join(tmpdir, os.path.basename(tmpfilelist)), 'w') as f:
+ f.write('%d\n' % ftotalsize)
+ for fpath, fsize in filelist:
+ f.write('%s %d\n' % (fpath, fsize))
+ # Copy them to the target
+ ret = subprocess.call("scp %s %s %s %s/* %s:%s" % (scp_sshexec, scp_port, extraoptions, tmpdir, args.target, os.path.dirname(tmpscript)), shell=True)
+ if ret != 0:
+ raise DevtoolError('Failed to copy script to %s - rerun with -s to '
+ 'get a complete error message' % args.target)
+ finally:
+ shutil.rmtree(tmpdir)
- if not os.path.exists(deploy_dir):
- os.makedirs(deploy_dir)
+ # Now run the script
+ ret = exec_fakeroot(rd, 'tar cf - . | %s %s %s %s \'sh %s %s %s %s\'' % (ssh_sshexec, ssh_port, extraoptions, args.target, tmpscript, args.recipename, destdir, tmpfilelist), cwd=recipe_outdir, shell=True)
+ if ret != 0:
+ raise DevtoolError('Deploy failed - rerun with -s to get a complete '
+ 'error message')
- files_list = []
- for root, _, files in os.walk(recipe_outdir):
- for filename in files:
- filename = os.path.relpath(os.path.join(root, filename), recipe_outdir)
- files_list.append(os.path.join(destdir, filename))
+ logger.info('Successfully deployed %s' % recipe_outdir)
- with open(deploy_file, 'w') as fobj:
- fobj.write('\n'.join(files_list))
+ files_list = []
+ for root, _, files in os.walk(recipe_outdir):
+ for filename in files:
+ filename = os.path.relpath(os.path.join(root, filename), recipe_outdir)
+ files_list.append(os.path.join(destdir, filename))
+ finally:
+ tinfoil.shutdown()
return 0
def undeploy(args, config, basepath, workspace):
"""Entry point for the devtool 'undeploy' subcommand"""
- deploy_file = os.path.join(basepath, 'target_deploy', args.target, args.recipename + '.list')
- if not os.path.exists(deploy_file):
- raise DevtoolError('%s has not been deployed' % args.recipename)
-
- if args.dry_run:
- print('Previously deployed files to be un-deployed for %s on target %s:' % (args.recipename, args.target))
- with open(deploy_file, 'r') as f:
- for line in f:
- print(' %s' % line.rstrip())
- return 0
+ if args.all and args.recipename:
+ raise argparse_oe.ArgumentUsageError('Cannot specify -a/--all with a recipe name', 'undeploy-target')
+ elif not args.recipename and not args.all:
+ raise argparse_oe.ArgumentUsageError('If you don\'t specify a recipe, you must specify -a/--all', 'undeploy-target')
extraoptions = ''
if args.no_host_check:
@@ -119,36 +280,87 @@ def undeploy(args, config, basepath, workspace):
if not args.show_status:
extraoptions += ' -q'
- ret = subprocess.call("scp %s %s %s:/tmp" % (extraoptions, deploy_file, args.target), shell=True)
- if ret != 0:
- raise DevtoolError('Failed to copy file list to %s - rerun with -s to '
- 'get a complete error message' % args.target)
+ scp_sshexec = ''
+ ssh_sshexec = 'ssh'
+ if args.ssh_exec:
+ scp_sshexec = "-S %s" % args.ssh_exec
+ ssh_sshexec = args.ssh_exec
+ scp_port = ''
+ ssh_port = ''
+ if args.port:
+ scp_port = "-P %s" % args.port
+ ssh_port = "-p %s" % args.port
- ret = subprocess.call("ssh %s %s 'xargs -n1 rm -f </tmp/%s'" % (extraoptions, args.target, os.path.basename(deploy_file)), shell=True)
- if ret == 0:
- logger.info('Successfully undeployed %s' % args.recipename)
- os.remove(deploy_file)
- else:
+ args.target = args.target.split(':')[0]
+
+ tmpdir = tempfile.mkdtemp(prefix='devtool')
+ try:
+ tmpscript = '/tmp/devtool_undeploy.sh'
+ shellscript = _prepare_remote_script(deploy=False, dryrun=args.dry_run, undeployall=args.all)
+ # Write out the script to a file
+ with open(os.path.join(tmpdir, os.path.basename(tmpscript)), 'w') as f:
+ f.write(shellscript)
+ # Copy it to the target
+ ret = subprocess.call("scp %s %s %s %s/* %s:%s" % (scp_sshexec, scp_port, extraoptions, tmpdir, args.target, os.path.dirname(tmpscript)), shell=True)
+ if ret != 0:
+ raise DevtoolError('Failed to copy script to %s - rerun with -s to '
+ 'get a complete error message' % args.target)
+ finally:
+ shutil.rmtree(tmpdir)
+
+ # Now run the script
+ ret = subprocess.call('%s %s %s %s \'sh %s %s\'' % (ssh_sshexec, ssh_port, extraoptions, args.target, tmpscript, args.recipename), shell=True)
+ if ret != 0:
raise DevtoolError('Undeploy failed - rerun with -s to get a complete '
'error message')
- return ret
+ if not args.all and not args.dry_run:
+ logger.info('Successfully undeployed %s' % args.recipename)
+ return 0
def register_commands(subparsers, context):
"""Register devtool subcommands from the deploy plugin"""
- parser_deploy = subparsers.add_parser('deploy-target', help='Deploy recipe output files to live target machine')
+
+ parser_deploy = subparsers.add_parser('deploy-target',
+ help='Deploy recipe output files to live target machine',
+ description='Deploys a recipe\'s build output (i.e. the output of the do_install task) to a live target machine over ssh. By default, any existing files will be preserved instead of being overwritten and will be restored if you run devtool undeploy-target. Note: this only deploys the recipe itself and not any runtime dependencies, so it is assumed that those have been installed on the target beforehand.',
+ group='testbuild')
parser_deploy.add_argument('recipename', help='Recipe to deploy')
parser_deploy.add_argument('target', help='Live target machine running an ssh server: user@hostname[:destdir]')
parser_deploy.add_argument('-c', '--no-host-check', help='Disable ssh host key checking', action='store_true')
parser_deploy.add_argument('-s', '--show-status', help='Show progress/status output', action='store_true')
parser_deploy.add_argument('-n', '--dry-run', help='List files to be deployed only', action='store_true')
+ parser_deploy.add_argument('-p', '--no-preserve', help='Do not preserve existing files', action='store_true')
+ parser_deploy.add_argument('--no-check-space', help='Do not check for available space before deploying', action='store_true')
+ parser_deploy.add_argument('-e', '--ssh-exec', help='Executable to use in place of ssh')
+ parser_deploy.add_argument('-P', '--port', help='Specify port to use for connection to the target')
+ parser_deploy.add_argument('-I', '--key',
+ help='Specify ssh private key for connection to the target')
+
+ strip_opts = parser_deploy.add_mutually_exclusive_group(required=False)
+ strip_opts.add_argument('-S', '--strip',
+ help='Strip executables prior to deploying (default: %(default)s). '
+ 'The default value of this option can be controlled by setting the strip option in the [Deploy] section to True or False.',
+ default=oe.types.boolean(context.config.get('Deploy', 'strip', default='0')),
+ action='store_true')
+ strip_opts.add_argument('--no-strip', help='Do not strip executables prior to deploy', dest='strip', action='store_false')
+
parser_deploy.set_defaults(func=deploy)
- parser_undeploy = subparsers.add_parser('undeploy-target', help='Undeploy recipe output files in live target machine')
- parser_undeploy.add_argument('recipename', help='Recipe to undeploy')
+ parser_undeploy = subparsers.add_parser('undeploy-target',
+ help='Undeploy recipe output files in live target machine',
+ description='Un-deploys recipe output files previously deployed to a live target machine by devtool deploy-target.',
+ group='testbuild')
+ parser_undeploy.add_argument('recipename', help='Recipe to undeploy (if not using -a/--all)', nargs='?')
parser_undeploy.add_argument('target', help='Live target machine running an ssh server: user@hostname')
parser_undeploy.add_argument('-c', '--no-host-check', help='Disable ssh host key checking', action='store_true')
parser_undeploy.add_argument('-s', '--show-status', help='Show progress/status output', action='store_true')
+ parser_undeploy.add_argument('-a', '--all', help='Undeploy all recipes deployed on the target', action='store_true')
parser_undeploy.add_argument('-n', '--dry-run', help='List files to be undeployed only', action='store_true')
+ parser_undeploy.add_argument('-e', '--ssh-exec', help='Executable to use in place of ssh')
+ parser_undeploy.add_argument('-P', '--port', help='Specify port to use for connection to the target')
+ parser_undeploy.add_argument('-I', '--key',
+ help='Specify ssh private key for connection to the target')
+
parser_undeploy.set_defaults(func=undeploy)
diff --git a/scripts/lib/devtool/export.py b/scripts/lib/devtool/export.py
new file mode 100644
index 0000000000..01174edae5
--- /dev/null
+++ b/scripts/lib/devtool/export.py
@@ -0,0 +1,109 @@
+# Development tool - export command plugin
+#
+# Copyright (C) 2014-2017 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+"""Devtool export plugin"""
+
+import os
+import argparse
+import tarfile
+import logging
+import datetime
+import json
+
+logger = logging.getLogger('devtool')
+
+# output files
+default_arcname_prefix = "workspace-export"
+metadata = '.export_metadata'
+
+def export(args, config, basepath, workspace):
+ """Entry point for the devtool 'export' subcommand"""
+
+ def add_metadata(tar):
+ """Archive the workspace object"""
+ # finally store the workspace metadata
+ with open(metadata, 'w') as fd:
+ fd.write(json.dumps((config.workspace_path, workspace)))
+ tar.add(metadata)
+ os.unlink(metadata)
+
+ def add_recipe(tar, recipe, data):
+ """Archive recipe with proper arcname"""
+ # Create a map of name/arcnames
+ arcnames = []
+ for key, name in data.items():
+ if name:
+ if key == 'srctree':
+ # all sources, no matter where are located, goes into the sources directory
+ arcname = 'sources/%s' % recipe
+ else:
+ arcname = name.replace(config.workspace_path, '')
+ arcnames.append((name, arcname))
+
+ for name, arcname in arcnames:
+ tar.add(name, arcname=arcname)
+
+
+ # Make sure workspace is non-empty and possible listed include/excluded recipes are in workspace
+ if not workspace:
+ logger.info('Workspace contains no recipes, nothing to export')
+ return 0
+ else:
+ for param, recipes in {'include':args.include,'exclude':args.exclude}.items():
+ for recipe in recipes:
+ if recipe not in workspace:
+ logger.error('Recipe (%s) on %s argument not in the current workspace' % (recipe, param))
+ return 1
+
+ name = args.file
+
+ default_name = "%s-%s.tar.gz" % (default_arcname_prefix, datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
+ if not name:
+ name = default_name
+ else:
+ # if name is a directory, append the default name
+ if os.path.isdir(name):
+ name = os.path.join(name, default_name)
+
+ if os.path.exists(name) and not args.overwrite:
+ logger.error('Tar archive %s exists. Use --overwrite/-o to overwrite it')
+ return 1
+
+ # if all workspace is excluded, quit
+ if not len(set(workspace.keys()).difference(set(args.exclude))):
+ logger.warning('All recipes in workspace excluded, nothing to export')
+ return 0
+
+ exported = []
+ with tarfile.open(name, 'w:gz') as tar:
+ if args.include:
+ for recipe in args.include:
+ add_recipe(tar, recipe, workspace[recipe])
+ exported.append(recipe)
+ else:
+ for recipe, data in workspace.items():
+ if recipe not in args.exclude:
+ add_recipe(tar, recipe, data)
+ exported.append(recipe)
+
+ add_metadata(tar)
+
+ logger.info('Tar archive created at %s with the following recipes: %s' % (name, ', '.join(exported)))
+ return 0
+
+def register_commands(subparsers, context):
+ """Register devtool export subcommands"""
+ parser = subparsers.add_parser('export',
+ help='Export workspace into a tar archive',
+ description='Export one or more recipes from current workspace into a tar archive',
+ group='advanced')
+
+ parser.add_argument('--file', '-f', help='Output archive file name')
+ parser.add_argument('--overwrite', '-o', action="store_true", help='Overwrite previous export tar archive')
+ group = parser.add_mutually_exclusive_group()
+ group.add_argument('--include', '-i', nargs='+', default=[], help='Include recipes into the tar archive')
+ group.add_argument('--exclude', '-e', nargs='+', default=[], help='Exclude recipes into the tar archive')
+ parser.set_defaults(func=export)
diff --git a/scripts/lib/devtool/import.py b/scripts/lib/devtool/import.py
new file mode 100644
index 0000000000..6829851669
--- /dev/null
+++ b/scripts/lib/devtool/import.py
@@ -0,0 +1,134 @@
+# Development tool - import command plugin
+#
+# Copyright (C) 2014-2017 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+"""Devtool import plugin"""
+
+import os
+import tarfile
+import logging
+import collections
+import json
+import fnmatch
+
+from devtool import standard, setup_tinfoil, replace_from_file, DevtoolError
+from devtool import export
+
+logger = logging.getLogger('devtool')
+
+def devimport(args, config, basepath, workspace):
+ """Entry point for the devtool 'import' subcommand"""
+
+ def get_pn(name):
+ """ Returns the filename of a workspace recipe/append"""
+ metadata = name.split('/')[-1]
+ fn, _ = os.path.splitext(metadata)
+ return fn
+
+ if not os.path.exists(args.file):
+ raise DevtoolError('Tar archive %s does not exist. Export your workspace using "devtool export"' % args.file)
+
+ with tarfile.open(args.file) as tar:
+ # Get exported metadata
+ export_workspace_path = export_workspace = None
+ try:
+ metadata = tar.getmember(export.metadata)
+ except KeyError as ke:
+ raise DevtoolError('The export metadata file created by "devtool export" was not found. "devtool import" can only be used to import tar archives created by "devtool export".')
+
+ tar.extract(metadata)
+ with open(metadata.name) as fdm:
+ export_workspace_path, export_workspace = json.load(fdm)
+ os.unlink(metadata.name)
+
+ members = tar.getmembers()
+
+ # Get appends and recipes from the exported archive, these
+ # will be needed to find out those appends without corresponding
+ # recipe pair
+ append_fns, recipe_fns = set(), set()
+ for member in members:
+ if member.name.startswith('appends'):
+ append_fns.add(get_pn(member.name))
+ elif member.name.startswith('recipes'):
+ recipe_fns.add(get_pn(member.name))
+
+ # Setup tinfoil, get required data and shutdown
+ tinfoil = setup_tinfoil(config_only=False, basepath=basepath)
+ try:
+ current_fns = [os.path.basename(recipe[0]) for recipe in tinfoil.cooker.recipecaches[''].pkg_fn.items()]
+ finally:
+ tinfoil.shutdown()
+
+ # Find those appends that do not have recipes in current metadata
+ non_importables = []
+ for fn in append_fns - recipe_fns:
+ # Check on current metadata (covering those layers indicated in bblayers.conf)
+ for current_fn in current_fns:
+ if fnmatch.fnmatch(current_fn, '*' + fn.replace('%', '') + '*'):
+ break
+ else:
+ non_importables.append(fn)
+ logger.warning('No recipe to append %s.bbapppend, skipping' % fn)
+
+ # Extract
+ imported = []
+ for member in members:
+ if member.name == export.metadata:
+ continue
+
+ for nonimp in non_importables:
+ pn = nonimp.split('_')[0]
+ # do not extract data from non-importable recipes or metadata
+ if member.name.startswith('appends/%s' % nonimp) or \
+ member.name.startswith('recipes/%s' % nonimp) or \
+ member.name.startswith('sources/%s' % pn):
+ break
+ else:
+ path = os.path.join(config.workspace_path, member.name)
+ if os.path.exists(path):
+ # by default, no file overwrite is done unless -o is given by the user
+ if args.overwrite:
+ try:
+ tar.extract(member, path=config.workspace_path)
+ except PermissionError as pe:
+ logger.warning(pe)
+ else:
+ logger.warning('File already present. Use --overwrite/-o to overwrite it: %s' % member.name)
+ continue
+ else:
+ tar.extract(member, path=config.workspace_path)
+
+ # Update EXTERNALSRC and the devtool md5 file
+ if member.name.startswith('appends'):
+ if export_workspace_path:
+ # appends created by 'devtool modify' just need to update the workspace
+ replace_from_file(path, export_workspace_path, config.workspace_path)
+
+ # appends created by 'devtool add' need replacement of exported source tree
+ pn = get_pn(member.name).split('_')[0]
+ exported_srctree = export_workspace[pn]['srctree']
+ if exported_srctree:
+ replace_from_file(path, exported_srctree, os.path.join(config.workspace_path, 'sources', pn))
+
+ standard._add_md5(config, pn, path)
+ imported.append(pn)
+
+ if imported:
+ logger.info('Imported recipes into workspace %s: %s' % (config.workspace_path, ', '.join(imported)))
+ else:
+ logger.warning('No recipes imported into the workspace')
+
+ return 0
+
+def register_commands(subparsers, context):
+ """Register devtool import subcommands"""
+ parser = subparsers.add_parser('import',
+ help='Import exported tar archive into workspace',
+ description='Import tar archive previously created by "devtool export" into workspace',
+ group='advanced')
+ parser.add_argument('file', metavar='FILE', help='Name of the tar archive to import')
+ parser.add_argument('--overwrite', '-o', action="store_true", help='Overwrite files when extracting')
+ parser.set_defaults(func=devimport)
diff --git a/scripts/lib/devtool/menuconfig.py b/scripts/lib/devtool/menuconfig.py
new file mode 100644
index 0000000000..95384c5333
--- /dev/null
+++ b/scripts/lib/devtool/menuconfig.py
@@ -0,0 +1,79 @@
+# OpenEmbedded Development tool - menuconfig command plugin
+#
+# Copyright (C) 2018 Xilinx
+# Written by: Chandana Kalluri <ckalluri@xilinx.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+"""Devtool menuconfig plugin"""
+
+import os
+import bb
+import logging
+import argparse
+import re
+import glob
+from devtool import setup_tinfoil, parse_recipe, DevtoolError, standard, exec_build_env_command
+from devtool import check_workspace_recipe
+logger = logging.getLogger('devtool')
+
+def menuconfig(args, config, basepath, workspace):
+ """Entry point for the devtool 'menuconfig' subcommand"""
+
+ rd = ""
+ kconfigpath = ""
+ pn_src = ""
+ localfilesdir = ""
+ workspace_dir = ""
+ tinfoil = setup_tinfoil(basepath=basepath)
+ try:
+ rd = parse_recipe(config, tinfoil, args.component, appends=True, filter_workspace=False)
+ if not rd:
+ return 1
+
+ check_workspace_recipe(workspace, args.component)
+ pn = rd.getVar('PN', True)
+
+ if not rd.getVarFlag('do_menuconfig','task'):
+ raise DevtoolError("This recipe does not support menuconfig option")
+
+ workspace_dir = os.path.join(config.workspace_path,'sources')
+ kconfigpath = rd.getVar('B')
+ pn_src = os.path.join(workspace_dir,pn)
+
+ # add check to see if oe_local_files exists or not
+ localfilesdir = os.path.join(pn_src,'oe-local-files')
+ if not os.path.exists(localfilesdir):
+ bb.utils.mkdirhier(localfilesdir)
+ # Add gitignore to ensure source tree is clean
+ gitignorefile = os.path.join(localfilesdir,'.gitignore')
+ with open(gitignorefile, 'w') as f:
+ f.write('# Ignore local files, by default. Remove this file if you want to commit the directory to Git\n')
+ f.write('*\n')
+
+ finally:
+ tinfoil.shutdown()
+
+ logger.info('Launching menuconfig')
+ exec_build_env_command(config.init_path, basepath, 'bitbake -c menuconfig %s' % pn, watch=True)
+ fragment = os.path.join(localfilesdir, 'devtool-fragment.cfg')
+ res = standard._create_kconfig_diff(pn_src,rd,fragment)
+
+ return 0
+
+def register_commands(subparsers, context):
+ """register devtool subcommands from this plugin"""
+ parser_menuconfig = subparsers.add_parser('menuconfig',help='Alter build-time configuration for a recipe', description='Launches the make menuconfig command (for recipes where do_menuconfig is available), allowing users to make changes to the build-time configuration. Creates a config fragment corresponding to changes made.', group='advanced')
+ parser_menuconfig.add_argument('component', help='compenent to alter config')
+ parser_menuconfig.set_defaults(func=menuconfig,fixed_setup=context.fixed_setup)
diff --git a/scripts/lib/devtool/package.py b/scripts/lib/devtool/package.py
new file mode 100644
index 0000000000..c2367342c3
--- /dev/null
+++ b/scripts/lib/devtool/package.py
@@ -0,0 +1,50 @@
+# Development tool - package command plugin
+#
+# Copyright (C) 2014-2015 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+"""Devtool plugin containing the package subcommands"""
+
+import os
+import subprocess
+import logging
+from bb.process import ExecutionError
+from devtool import exec_build_env_command, setup_tinfoil, check_workspace_recipe, DevtoolError
+
+logger = logging.getLogger('devtool')
+
+def package(args, config, basepath, workspace):
+ """Entry point for the devtool 'package' subcommand"""
+ check_workspace_recipe(workspace, args.recipename)
+
+ tinfoil = setup_tinfoil(basepath=basepath, config_only=True)
+ try:
+ image_pkgtype = config.get('Package', 'image_pkgtype', '')
+ if not image_pkgtype:
+ image_pkgtype = tinfoil.config_data.getVar('IMAGE_PKGTYPE')
+
+ deploy_dir_pkg = tinfoil.config_data.getVar('DEPLOY_DIR_%s' % image_pkgtype.upper())
+ finally:
+ tinfoil.shutdown()
+
+ package_task = config.get('Package', 'package_task', 'package_write_%s' % image_pkgtype)
+ try:
+ exec_build_env_command(config.init_path, basepath, 'bitbake -c %s %s' % (package_task, args.recipename), watch=True)
+ except bb.process.ExecutionError as e:
+ # We've already seen the output since watch=True, so just ensure we return something to the user
+ return e.exitcode
+
+ logger.info('Your packages are in %s' % deploy_dir_pkg)
+
+ return 0
+
+def register_commands(subparsers, context):
+ """Register devtool subcommands from the package plugin"""
+ if context.fixed_setup:
+ parser_package = subparsers.add_parser('package',
+ help='Build packages for a recipe',
+ description='Builds packages for a recipe\'s output files',
+ group='testbuild', order=-5)
+ parser_package.add_argument('recipename', help='Recipe to package')
+ parser_package.set_defaults(func=package)
diff --git a/scripts/lib/devtool/runqemu.py b/scripts/lib/devtool/runqemu.py
new file mode 100644
index 0000000000..ead978aabc
--- /dev/null
+++ b/scripts/lib/devtool/runqemu.py
@@ -0,0 +1,64 @@
+# Development tool - runqemu command plugin
+#
+# Copyright (C) 2015 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+"""Devtool runqemu plugin"""
+
+import os
+import bb
+import logging
+import argparse
+import glob
+from devtool import exec_build_env_command, setup_tinfoil, DevtoolError
+
+logger = logging.getLogger('devtool')
+
+def runqemu(args, config, basepath, workspace):
+ """Entry point for the devtool 'runqemu' subcommand"""
+
+ tinfoil = setup_tinfoil(config_only=True, basepath=basepath)
+ try:
+ machine = tinfoil.config_data.getVar('MACHINE')
+ bindir_native = os.path.join(tinfoil.config_data.getVar('STAGING_DIR'),
+ tinfoil.config_data.getVar('BUILD_ARCH'),
+ tinfoil.config_data.getVar('bindir_native').lstrip(os.path.sep))
+ finally:
+ tinfoil.shutdown()
+
+ if not glob.glob(os.path.join(bindir_native, 'qemu-system-*')):
+ raise DevtoolError('QEMU is not available within this SDK')
+
+ imagename = args.imagename
+ if not imagename:
+ sdk_targets = config.get('SDK', 'sdk_targets', '').split()
+ if sdk_targets:
+ imagename = sdk_targets[0]
+ if not imagename:
+ raise DevtoolError('Unable to determine image name to run, please specify one')
+
+ try:
+ # FIXME runqemu assumes that if OECORE_NATIVE_SYSROOT is set then it shouldn't
+ # run bitbake to find out the values of various environment variables, which
+ # isn't the case for the extensible SDK. Work around it for now.
+ newenv = dict(os.environ)
+ newenv.pop('OECORE_NATIVE_SYSROOT', '')
+ exec_build_env_command(config.init_path, basepath, 'runqemu %s %s %s' % (machine, imagename, " ".join(args.args)), watch=True, env=newenv)
+ except bb.process.ExecutionError as e:
+ # We've already seen the output since watch=True, so just ensure we return something to the user
+ return e.exitcode
+
+ return 0
+
+def register_commands(subparsers, context):
+ """Register devtool subcommands from this plugin"""
+ if context.fixed_setup:
+ parser_runqemu = subparsers.add_parser('runqemu', help='Run QEMU on the specified image',
+ description='Runs QEMU to boot the specified image',
+ group='testbuild', order=-20)
+ parser_runqemu.add_argument('imagename', help='Name of built image to boot within QEMU', nargs='?')
+ parser_runqemu.add_argument('args', help='Any remaining arguments are passed to the runqemu script (pass --help after imagename to see what these are)',
+ nargs=argparse.REMAINDER)
+ parser_runqemu.set_defaults(func=runqemu)
diff --git a/scripts/lib/devtool/sdk.py b/scripts/lib/devtool/sdk.py
new file mode 100644
index 0000000000..ae3fc4caf9
--- /dev/null
+++ b/scripts/lib/devtool/sdk.py
@@ -0,0 +1,329 @@
+# Development tool - sdk-update command plugin
+#
+# Copyright (C) 2015-2016 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import os
+import subprocess
+import logging
+import glob
+import shutil
+import errno
+import sys
+import tempfile
+import re
+from devtool import exec_build_env_command, setup_tinfoil, parse_recipe, DevtoolError
+
+logger = logging.getLogger('devtool')
+
+def parse_locked_sigs(sigfile_path):
+ """Return <pn:task>:<hash> dictionary"""
+ sig_dict = {}
+ with open(sigfile_path) as f:
+ lines = f.readlines()
+ for line in lines:
+ if ':' in line:
+ taskkey, _, hashval = line.rpartition(':')
+ sig_dict[taskkey.strip()] = hashval.split()[0]
+ return sig_dict
+
+def generate_update_dict(sigfile_new, sigfile_old):
+ """Return a dict containing <pn:task>:<hash> which indicates what need to be updated"""
+ update_dict = {}
+ sigdict_new = parse_locked_sigs(sigfile_new)
+ sigdict_old = parse_locked_sigs(sigfile_old)
+ for k in sigdict_new:
+ if k not in sigdict_old:
+ update_dict[k] = sigdict_new[k]
+ continue
+ if sigdict_new[k] != sigdict_old[k]:
+ update_dict[k] = sigdict_new[k]
+ continue
+ return update_dict
+
+def get_sstate_objects(update_dict, sstate_dir):
+ """Return a list containing sstate objects which are to be installed"""
+ sstate_objects = []
+ for k in update_dict:
+ files = set()
+ hashval = update_dict[k]
+ p = sstate_dir + '/' + hashval[:2] + '/*' + hashval + '*.tgz'
+ files |= set(glob.glob(p))
+ p = sstate_dir + '/*/' + hashval[:2] + '/*' + hashval + '*.tgz'
+ files |= set(glob.glob(p))
+ files = list(files)
+ if len(files) == 1:
+ sstate_objects.extend(files)
+ elif len(files) > 1:
+ logger.error("More than one matching sstate object found for %s" % hashval)
+
+ return sstate_objects
+
+def mkdir(d):
+ try:
+ os.makedirs(d)
+ except OSError as e:
+ if e.errno != errno.EEXIST:
+ raise e
+
+def install_sstate_objects(sstate_objects, src_sdk, dest_sdk):
+ """Install sstate objects into destination SDK"""
+ sstate_dir = os.path.join(dest_sdk, 'sstate-cache')
+ if not os.path.exists(sstate_dir):
+ logger.error("Missing sstate-cache directory in %s, it might not be an extensible SDK." % dest_sdk)
+ raise
+ for sb in sstate_objects:
+ dst = sb.replace(src_sdk, dest_sdk)
+ destdir = os.path.dirname(dst)
+ mkdir(destdir)
+ logger.debug("Copying %s to %s" % (sb, dst))
+ shutil.copy(sb, dst)
+
+def check_manifest(fn, basepath):
+ import bb.utils
+ changedfiles = []
+ with open(fn, 'r') as f:
+ for line in f:
+ splitline = line.split()
+ if len(splitline) > 1:
+ chksum = splitline[0]
+ fpath = splitline[1]
+ curr_chksum = bb.utils.sha256_file(os.path.join(basepath, fpath))
+ if chksum != curr_chksum:
+ logger.debug('File %s changed: old csum = %s, new = %s' % (os.path.join(basepath, fpath), curr_chksum, chksum))
+ changedfiles.append(fpath)
+ return changedfiles
+
+def sdk_update(args, config, basepath, workspace):
+ """Entry point for devtool sdk-update command"""
+ updateserver = args.updateserver
+ if not updateserver:
+ updateserver = config.get('SDK', 'updateserver', '')
+ logger.debug("updateserver: %s" % updateserver)
+
+ # Make sure we are using sdk-update from within SDK
+ logger.debug("basepath = %s" % basepath)
+ old_locked_sig_file_path = os.path.join(basepath, 'conf/locked-sigs.inc')
+ if not os.path.exists(old_locked_sig_file_path):
+ logger.error("Not using devtool's sdk-update command from within an extensible SDK. Please specify correct basepath via --basepath option")
+ return -1
+ else:
+ logger.debug("Found conf/locked-sigs.inc in %s" % basepath)
+
+ if not '://' in updateserver:
+ logger.error("Update server must be a URL")
+ return -1
+
+ layers_dir = os.path.join(basepath, 'layers')
+ conf_dir = os.path.join(basepath, 'conf')
+
+ # Grab variable values
+ tinfoil = setup_tinfoil(config_only=True, basepath=basepath)
+ try:
+ stamps_dir = tinfoil.config_data.getVar('STAMPS_DIR')
+ sstate_mirrors = tinfoil.config_data.getVar('SSTATE_MIRRORS')
+ site_conf_version = tinfoil.config_data.getVar('SITE_CONF_VERSION')
+ finally:
+ tinfoil.shutdown()
+
+ tmpsdk_dir = tempfile.mkdtemp()
+ try:
+ os.makedirs(os.path.join(tmpsdk_dir, 'conf'))
+ new_locked_sig_file_path = os.path.join(tmpsdk_dir, 'conf', 'locked-sigs.inc')
+ # Fetch manifest from server
+ tmpmanifest = os.path.join(tmpsdk_dir, 'conf', 'sdk-conf-manifest')
+ ret = subprocess.call("wget -q -O %s %s/conf/sdk-conf-manifest" % (tmpmanifest, updateserver), shell=True)
+ if ret != 0:
+ logger.error("Cannot dowload files from %s" % updateserver)
+ return ret
+ changedfiles = check_manifest(tmpmanifest, basepath)
+ if not changedfiles:
+ logger.info("Already up-to-date")
+ return 0
+ # Update metadata
+ logger.debug("Updating metadata via git ...")
+ #Check for the status before doing a fetch and reset
+ if os.path.exists(os.path.join(basepath, 'layers/.git')):
+ out = subprocess.check_output("git status --porcelain", shell=True, cwd=layers_dir)
+ if not out:
+ ret = subprocess.call("git fetch --all; git reset --hard @{u}", shell=True, cwd=layers_dir)
+ else:
+ logger.error("Failed to update metadata as there have been changes made to it. Aborting.");
+ logger.error("Changed files:\n%s" % out);
+ return -1
+ else:
+ ret = -1
+ if ret != 0:
+ ret = subprocess.call("git clone %s/layers/.git" % updateserver, shell=True, cwd=tmpsdk_dir)
+ if ret != 0:
+ logger.error("Updating metadata via git failed")
+ return ret
+ logger.debug("Updating conf files ...")
+ for changedfile in changedfiles:
+ ret = subprocess.call("wget -q -O %s %s/%s" % (changedfile, updateserver, changedfile), shell=True, cwd=tmpsdk_dir)
+ if ret != 0:
+ logger.error("Updating %s failed" % changedfile)
+ return ret
+
+ # Check if UNINATIVE_CHECKSUM changed
+ uninative = False
+ if 'conf/local.conf' in changedfiles:
+ def read_uninative_checksums(fn):
+ chksumitems = []
+ with open(fn, 'r') as f:
+ for line in f:
+ if line.startswith('UNINATIVE_CHECKSUM'):
+ splitline = re.split(r'[\[\]"\']', line)
+ if len(splitline) > 3:
+ chksumitems.append((splitline[1], splitline[3]))
+ return chksumitems
+
+ oldsums = read_uninative_checksums(os.path.join(basepath, 'conf/local.conf'))
+ newsums = read_uninative_checksums(os.path.join(tmpsdk_dir, 'conf/local.conf'))
+ if oldsums != newsums:
+ uninative = True
+ for buildarch, chksum in newsums:
+ uninative_file = os.path.join('downloads', 'uninative', chksum, '%s-nativesdk-libc.tar.bz2' % buildarch)
+ mkdir(os.path.join(tmpsdk_dir, os.path.dirname(uninative_file)))
+ ret = subprocess.call("wget -q -O %s %s/%s" % (uninative_file, updateserver, uninative_file), shell=True, cwd=tmpsdk_dir)
+
+ # Ok, all is well at this point - move everything over
+ tmplayers_dir = os.path.join(tmpsdk_dir, 'layers')
+ if os.path.exists(tmplayers_dir):
+ shutil.rmtree(layers_dir)
+ shutil.move(tmplayers_dir, layers_dir)
+ for changedfile in changedfiles:
+ destfile = os.path.join(basepath, changedfile)
+ os.remove(destfile)
+ shutil.move(os.path.join(tmpsdk_dir, changedfile), destfile)
+ os.remove(os.path.join(conf_dir, 'sdk-conf-manifest'))
+ shutil.move(tmpmanifest, conf_dir)
+ if uninative:
+ shutil.rmtree(os.path.join(basepath, 'downloads', 'uninative'))
+ shutil.move(os.path.join(tmpsdk_dir, 'downloads', 'uninative'), os.path.join(basepath, 'downloads'))
+
+ if not sstate_mirrors:
+ with open(os.path.join(conf_dir, 'site.conf'), 'a') as f:
+ f.write('SCONF_VERSION = "%s"\n' % site_conf_version)
+ f.write('SSTATE_MIRRORS:append = " file://.* %s/sstate-cache/PATH \\n "\n' % updateserver)
+ finally:
+ shutil.rmtree(tmpsdk_dir)
+
+ if not args.skip_prepare:
+ # Find all potentially updateable tasks
+ sdk_update_targets = []
+ tasks = ['do_populate_sysroot', 'do_packagedata']
+ for root, _, files in os.walk(stamps_dir):
+ for fn in files:
+ if not '.sigdata.' in fn:
+ for task in tasks:
+ if '.%s.' % task in fn or '.%s_setscene.' % task in fn:
+ sdk_update_targets.append('%s:%s' % (os.path.basename(root), task))
+ # Run bitbake command for the whole SDK
+ logger.info("Preparing build system... (This may take some time.)")
+ try:
+ exec_build_env_command(config.init_path, basepath, 'bitbake --setscene-only %s' % ' '.join(sdk_update_targets), stderr=subprocess.STDOUT)
+ output, _ = exec_build_env_command(config.init_path, basepath, 'bitbake -n %s' % ' '.join(sdk_update_targets), stderr=subprocess.STDOUT)
+ runlines = []
+ for line in output.splitlines():
+ if 'Running task ' in line:
+ runlines.append(line)
+ if runlines:
+ logger.error('Unexecuted tasks found in preparation log:\n %s' % '\n '.join(runlines))
+ return -1
+ except bb.process.ExecutionError as e:
+ logger.error('Preparation failed:\n%s' % e.stdout)
+ return -1
+ return 0
+
+def sdk_install(args, config, basepath, workspace):
+ """Entry point for the devtool sdk-install command"""
+
+ import oe.recipeutils
+ import bb.process
+
+ for recipe in args.recipename:
+ if recipe in workspace:
+ raise DevtoolError('recipe %s is a recipe in your workspace' % recipe)
+
+ tasks = ['do_populate_sysroot', 'do_packagedata']
+ stampprefixes = {}
+ def checkstamp(recipe):
+ stampprefix = stampprefixes[recipe]
+ stamps = glob.glob(stampprefix + '*')
+ for stamp in stamps:
+ if '.sigdata.' not in stamp and stamp.startswith((stampprefix + '.', stampprefix + '_setscene.')):
+ return True
+ else:
+ return False
+
+ install_recipes = []
+ tinfoil = setup_tinfoil(config_only=False, basepath=basepath)
+ try:
+ for recipe in args.recipename:
+ rd = parse_recipe(config, tinfoil, recipe, True)
+ if not rd:
+ return 1
+ stampprefixes[recipe] = '%s.%s' % (rd.getVar('STAMP'), tasks[0])
+ if checkstamp(recipe):
+ logger.info('%s is already installed' % recipe)
+ else:
+ install_recipes.append(recipe)
+ finally:
+ tinfoil.shutdown()
+
+ if install_recipes:
+ logger.info('Installing %s...' % ', '.join(install_recipes))
+ install_tasks = []
+ for recipe in install_recipes:
+ for task in tasks:
+ if recipe.endswith('-native') and 'package' in task:
+ continue
+ install_tasks.append('%s:%s' % (recipe, task))
+ options = ''
+ if not args.allow_build:
+ options += ' --setscene-only'
+ try:
+ exec_build_env_command(config.init_path, basepath, 'bitbake %s %s' % (options, ' '.join(install_tasks)), watch=True)
+ except bb.process.ExecutionError as e:
+ raise DevtoolError('Failed to install %s:\n%s' % (recipe, str(e)))
+ failed = False
+ for recipe in install_recipes:
+ if checkstamp(recipe):
+ logger.info('Successfully installed %s' % recipe)
+ else:
+ raise DevtoolError('Failed to install %s - unavailable' % recipe)
+ failed = True
+ if failed:
+ return 2
+
+ try:
+ exec_build_env_command(config.init_path, basepath, 'bitbake build-sysroots', watch=True)
+ except bb.process.ExecutionError as e:
+ raise DevtoolError('Failed to bitbake build-sysroots:\n%s' % (str(e)))
+
+
+def register_commands(subparsers, context):
+ """Register devtool subcommands from the sdk plugin"""
+ if context.fixed_setup:
+ parser_sdk = subparsers.add_parser('sdk-update',
+ help='Update SDK components',
+ description='Updates installed SDK components from a remote server',
+ group='sdk')
+ updateserver = context.config.get('SDK', 'updateserver', '')
+ if updateserver:
+ parser_sdk.add_argument('updateserver', help='The update server to fetch latest SDK components from (default %s)' % updateserver, nargs='?')
+ else:
+ parser_sdk.add_argument('updateserver', help='The update server to fetch latest SDK components from')
+ parser_sdk.add_argument('--skip-prepare', action="store_true", help='Skip re-preparing the build system after updating (for debugging only)')
+ parser_sdk.set_defaults(func=sdk_update)
+
+ parser_sdk_install = subparsers.add_parser('sdk-install',
+ help='Install additional SDK components',
+ description='Installs additional recipe development files into the SDK. (You can use "devtool search" to find available recipes.)',
+ group='sdk')
+ parser_sdk_install.add_argument('recipename', help='Name of the recipe to install the development artifacts for', nargs='+')
+ parser_sdk_install.add_argument('-s', '--allow-build', help='Allow building requested item(s) from source', action='store_true')
+ parser_sdk_install.set_defaults(func=sdk_install)
diff --git a/scripts/lib/devtool/search.py b/scripts/lib/devtool/search.py
new file mode 100644
index 0000000000..70b81cac5e
--- /dev/null
+++ b/scripts/lib/devtool/search.py
@@ -0,0 +1,109 @@
+# Development tool - search command plugin
+#
+# Copyright (C) 2015 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+"""Devtool search plugin"""
+
+import os
+import bb
+import logging
+import argparse
+import re
+from devtool import setup_tinfoil, parse_recipe, DevtoolError
+
+logger = logging.getLogger('devtool')
+
+def search(args, config, basepath, workspace):
+ """Entry point for the devtool 'search' subcommand"""
+
+ tinfoil = setup_tinfoil(config_only=False, basepath=basepath)
+ try:
+ pkgdata_dir = tinfoil.config_data.getVar('PKGDATA_DIR')
+ defsummary = tinfoil.config_data.getVar('SUMMARY', False) or ''
+
+ keyword_rc = re.compile(args.keyword)
+
+ def print_match(pn):
+ rd = parse_recipe(config, tinfoil, pn, True)
+ if not rd:
+ return
+ summary = rd.getVar('SUMMARY')
+ if summary == rd.expand(defsummary):
+ summary = ''
+ print("%s %s" % (pn.ljust(20), summary))
+
+
+ matches = []
+ if os.path.exists(pkgdata_dir):
+ for fn in os.listdir(pkgdata_dir):
+ pfn = os.path.join(pkgdata_dir, fn)
+ if not os.path.isfile(pfn):
+ continue
+
+ packages = []
+ match = False
+ if keyword_rc.search(fn):
+ match = True
+
+ if not match:
+ with open(pfn, 'r') as f:
+ for line in f:
+ if line.startswith('PACKAGES:'):
+ packages = line.split(':', 1)[1].strip().split()
+
+ for pkg in packages:
+ if keyword_rc.search(pkg):
+ match = True
+ break
+ if os.path.exists(os.path.join(pkgdata_dir, 'runtime', pkg + '.packaged')):
+ with open(os.path.join(pkgdata_dir, 'runtime', pkg), 'r') as f:
+ for line in f:
+ if ': ' in line:
+ splitline = line.split(': ', 1)
+ key = splitline[0]
+ value = splitline[1].strip()
+ key = key.replace(":" + pkg, "")
+ if key in ['PKG', 'DESCRIPTION', 'FILES_INFO', 'FILERPROVIDES']:
+ if keyword_rc.search(value):
+ match = True
+ break
+ if match:
+ print_match(fn)
+ matches.append(fn)
+ else:
+ logger.warning('Package data is not available, results may be limited')
+
+ for recipe in tinfoil.all_recipes():
+ if args.fixed_setup and 'nativesdk' in recipe.inherits():
+ continue
+
+ match = False
+ if keyword_rc.search(recipe.pn):
+ match = True
+ else:
+ for prov in recipe.provides:
+ if keyword_rc.search(prov):
+ match = True
+ break
+ if not match:
+ for rprov in recipe.rprovides:
+ if keyword_rc.search(rprov):
+ match = True
+ break
+ if match and not recipe.pn in matches:
+ print_match(recipe.pn)
+ finally:
+ tinfoil.shutdown()
+
+ return 0
+
+def register_commands(subparsers, context):
+ """Register devtool subcommands from this plugin"""
+ parser_search = subparsers.add_parser('search', help='Search available recipes',
+ description='Searches for available recipes. Matches on recipe name, package name, description and installed files, and prints the recipe name and summary on match.',
+ group='info')
+ parser_search.add_argument('keyword', help='Keyword to search for (regular expression syntax allowed, use quotes to avoid shell expansion)')
+ parser_search.set_defaults(func=search, no_workspace=True, fixed_setup=context.fixed_setup)
diff --git a/scripts/lib/devtool/standard.py b/scripts/lib/devtool/standard.py
index e59fb5e567..01fb5ad96f 100644
--- a/scripts/lib/devtool/standard.py
+++ b/scripts/lib/devtool/standard.py
@@ -1,39 +1,31 @@
# Development tool - standard commands plugin
#
-# Copyright (C) 2014-2015 Intel Corporation
+# Copyright (C) 2014-2017 Intel Corporation
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
+# SPDX-License-Identifier: GPL-2.0-only
#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Devtool standard plugins"""
import os
import sys
import re
import shutil
+import subprocess
import tempfile
import logging
import argparse
+import argparse_oe
import scriptutils
import errno
-from devtool import exec_build_env_command, setup_tinfoil, DevtoolError
+import glob
+import filecmp
+from collections import OrderedDict
+from devtool import exec_build_env_command, setup_tinfoil, check_workspace_recipe, use_external_build, setup_git_repo, recipe_to_append, get_bbclassextend_targets, update_unlockedsigs, check_prerelease_version, check_git_repo_dirty, check_git_repo_op, DevtoolError
from devtool import parse_recipe
logger = logging.getLogger('devtool')
-
-def plugin_init(pluginlist):
- """Plugin initialization"""
- pass
+override_branch_prefix = 'devtool-override-'
def add(args, config, basepath, workspace):
@@ -41,17 +33,68 @@ def add(args, config, basepath, workspace):
import bb
import oe.recipeutils
- if args.recipename in workspace:
- raise DevtoolError("recipe %s is already in your workspace" %
- args.recipename)
+ if not args.recipename and not args.srctree and not args.fetch and not args.fetchuri:
+ raise argparse_oe.ArgumentUsageError('At least one of recipename, srctree, fetchuri or -f/--fetch must be specified', 'add')
+
+ # These are positional arguments, but because we're nice, allow
+ # specifying e.g. source tree without name, or fetch URI without name or
+ # source tree (if we can detect that that is what the user meant)
+ if scriptutils.is_src_url(args.recipename):
+ if not args.fetchuri:
+ if args.fetch:
+ raise DevtoolError('URI specified as positional argument as well as -f/--fetch')
+ args.fetchuri = args.recipename
+ args.recipename = ''
+ elif scriptutils.is_src_url(args.srctree):
+ if not args.fetchuri:
+ if args.fetch:
+ raise DevtoolError('URI specified as positional argument as well as -f/--fetch')
+ args.fetchuri = args.srctree
+ args.srctree = ''
+ elif args.recipename and not args.srctree:
+ if os.sep in args.recipename:
+ args.srctree = args.recipename
+ args.recipename = None
+ elif os.path.isdir(args.recipename):
+ logger.warning('Ambiguous argument "%s" - assuming you mean it to be the recipe name' % args.recipename)
+
+ if not args.fetchuri:
+ if args.srcrev:
+ raise DevtoolError('The -S/--srcrev option is only valid when fetching from an SCM repository')
+ if args.srcbranch:
+ raise DevtoolError('The -B/--srcbranch option is only valid when fetching from an SCM repository')
+
+ if args.srctree and os.path.isfile(args.srctree):
+ args.fetchuri = 'file://' + os.path.abspath(args.srctree)
+ args.srctree = ''
- reason = oe.recipeutils.validate_pn(args.recipename)
- if reason:
- raise DevtoolError(reason)
+ if args.fetch:
+ if args.fetchuri:
+ raise DevtoolError('URI specified as positional argument as well as -f/--fetch')
+ else:
+ logger.warning('-f/--fetch option is deprecated - you can now simply specify the URL to fetch as a positional argument instead')
+ args.fetchuri = args.fetch
+
+ if args.recipename:
+ if args.recipename in workspace:
+ raise DevtoolError("recipe %s is already in your workspace" %
+ args.recipename)
+ reason = oe.recipeutils.validate_pn(args.recipename)
+ if reason:
+ raise DevtoolError(reason)
+
+ if args.srctree:
+ srctree = os.path.abspath(args.srctree)
+ srctreeparent = None
+ tmpsrcdir = None
+ else:
+ srctree = None
+ srctreeparent = get_default_srctree(config)
+ bb.utils.mkdirhier(srctreeparent)
+ tmpsrcdir = tempfile.mkdtemp(prefix='devtoolsrc', dir=srctreeparent)
- srctree = os.path.abspath(args.srctree)
- if os.path.exists(srctree):
- if args.fetch:
+ if srctree and os.path.exists(srctree):
+ if args.fetchuri:
if not os.path.isdir(srctree):
raise DevtoolError("Cannot fetch into source tree path %s as "
"it exists and is not a directory" %
@@ -60,68 +103,195 @@ def add(args, config, basepath, workspace):
raise DevtoolError("Cannot fetch into source tree path %s as "
"it already exists and is non-empty" %
srctree)
- elif not args.fetch:
- raise DevtoolError("Specified source tree %s could not be found" %
- srctree)
-
- appendpath = os.path.join(config.workspace_path, 'appends')
- if not os.path.exists(appendpath):
- os.makedirs(appendpath)
+ elif not args.fetchuri:
+ if args.srctree:
+ raise DevtoolError("Specified source tree %s could not be found" %
+ args.srctree)
+ elif srctree:
+ raise DevtoolError("No source tree exists at default path %s - "
+ "either create and populate this directory, "
+ "or specify a path to a source tree, or a "
+ "URI to fetch source from" % srctree)
+ else:
+ raise DevtoolError("You must either specify a source tree "
+ "or a URI to fetch source from")
- recipedir = os.path.join(config.workspace_path, 'recipes', args.recipename)
- bb.utils.mkdirhier(recipedir)
- rfv = None
if args.version:
if '_' in args.version or ' ' in args.version:
raise DevtoolError('Invalid version string "%s"' % args.version)
- rfv = args.version
- if args.fetch:
- if args.fetch.startswith('git://'):
- rfv = 'git'
- elif args.fetch.startswith('svn://'):
- rfv = 'svn'
- elif args.fetch.startswith('hg://'):
- rfv = 'hg'
- if rfv:
- bp = "%s_%s" % (args.recipename, rfv)
- else:
- bp = args.recipename
- recipefile = os.path.join(recipedir, "%s.bb" % bp)
- if sys.stdout.isatty():
+
+ if args.color == 'auto' and sys.stdout.isatty():
color = 'always'
else:
color = args.color
extracmdopts = ''
- if args.fetch:
- source = args.fetch
- extracmdopts = '-x %s' % srctree
+ if args.fetchuri:
+ source = args.fetchuri
+ if srctree:
+ extracmdopts += ' -x %s' % srctree
+ else:
+ extracmdopts += ' -x %s' % tmpsrcdir
else:
source = srctree
+ if args.recipename:
+ extracmdopts += ' -N %s' % args.recipename
if args.version:
extracmdopts += ' -V %s' % args.version
+ if args.binary:
+ extracmdopts += ' -b'
+ if args.also_native:
+ extracmdopts += ' --also-native'
+ if args.src_subdir:
+ extracmdopts += ' --src-subdir "%s"' % args.src_subdir
+ if args.autorev:
+ extracmdopts += ' -a'
+ if args.npm_dev:
+ extracmdopts += ' --npm-dev'
+ if args.mirrors:
+ extracmdopts += ' --mirrors'
+ if args.srcrev:
+ extracmdopts += ' --srcrev %s' % args.srcrev
+ if args.srcbranch:
+ extracmdopts += ' --srcbranch %s' % args.srcbranch
+ if args.provides:
+ extracmdopts += ' --provides %s' % args.provides
+
+ tempdir = tempfile.mkdtemp(prefix='devtool')
try:
- stdout, _ = exec_build_env_command(config.init_path, basepath, 'recipetool --color=%s create -o %s "%s" %s' % (color, recipefile, source, extracmdopts))
- logger.info('Recipe %s has been automatically created; further editing may be required to make it fully functional' % recipefile)
- except bb.process.ExecutionError as e:
- raise DevtoolError('Command \'%s\' failed:\n%s' % (e.command, e.stdout))
+ try:
+ stdout, _ = exec_build_env_command(config.init_path, basepath, 'recipetool --color=%s create --devtool -o %s \'%s\' %s' % (color, tempdir, source, extracmdopts), watch=True)
+ except bb.process.ExecutionError as e:
+ if e.exitcode == 15:
+ raise DevtoolError('Could not auto-determine recipe name, please specify it on the command line')
+ else:
+ raise DevtoolError('Command \'%s\' failed' % e.command)
+
+ recipes = glob.glob(os.path.join(tempdir, '*.bb'))
+ if recipes:
+ recipename = os.path.splitext(os.path.basename(recipes[0]))[0].split('_')[0]
+ if recipename in workspace:
+ raise DevtoolError('A recipe with the same name as the one being created (%s) already exists in your workspace' % recipename)
+ recipedir = os.path.join(config.workspace_path, 'recipes', recipename)
+ bb.utils.mkdirhier(recipedir)
+ recipefile = os.path.join(recipedir, os.path.basename(recipes[0]))
+ appendfile = recipe_to_append(recipefile, config)
+ if os.path.exists(appendfile):
+ # This shouldn't be possible, but just in case
+ raise DevtoolError('A recipe with the same name as the one being created already exists in your workspace')
+ if os.path.exists(recipefile):
+ raise DevtoolError('A recipe file %s already exists in your workspace; this shouldn\'t be there - please delete it before continuing' % recipefile)
+ if tmpsrcdir:
+ srctree = os.path.join(srctreeparent, recipename)
+ if os.path.exists(tmpsrcdir):
+ if os.path.exists(srctree):
+ if os.path.isdir(srctree):
+ try:
+ os.rmdir(srctree)
+ except OSError as e:
+ if e.errno == errno.ENOTEMPTY:
+ raise DevtoolError('Source tree path %s already exists and is not empty' % srctree)
+ else:
+ raise
+ else:
+ raise DevtoolError('Source tree path %s already exists and is not a directory' % srctree)
+ logger.info('Using default source tree path %s' % srctree)
+ shutil.move(tmpsrcdir, srctree)
+ else:
+ raise DevtoolError('Couldn\'t find source tree created by recipetool')
+ bb.utils.mkdirhier(recipedir)
+ shutil.move(recipes[0], recipefile)
+ # Move any additional files created by recipetool
+ for fn in os.listdir(tempdir):
+ shutil.move(os.path.join(tempdir, fn), recipedir)
+ else:
+ raise DevtoolError('Command \'%s\' did not create any recipe file:\n%s' % (e.command, e.stdout))
+ attic_recipe = os.path.join(config.workspace_path, 'attic', recipename, os.path.basename(recipefile))
+ if os.path.exists(attic_recipe):
+ logger.warning('A modified recipe from a previous invocation exists in %s - you may wish to move this over the top of the new recipe if you had changes in it that you want to continue with' % attic_recipe)
+ finally:
+ if tmpsrcdir and os.path.exists(tmpsrcdir):
+ shutil.rmtree(tmpsrcdir)
+ shutil.rmtree(tempdir)
- _add_md5(config, args.recipename, recipefile)
+ for fn in os.listdir(recipedir):
+ _add_md5(config, recipename, os.path.join(recipedir, fn))
- initial_rev = None
- if os.path.exists(os.path.join(srctree, '.git')):
- (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=srctree)
- initial_rev = stdout.rstrip()
-
- appendfile = os.path.join(appendpath, '%s.bbappend' % bp)
- with open(appendfile, 'w') as f:
- f.write('inherit externalsrc\n')
- f.write('EXTERNALSRC = "%s"\n' % srctree)
- if args.same_dir:
- f.write('EXTERNALSRC_BUILD = "%s"\n' % srctree)
- if initial_rev:
- f.write('\n# initial_rev: %s\n' % initial_rev)
+ tinfoil = setup_tinfoil(config_only=True, basepath=basepath)
+ try:
+ try:
+ rd = tinfoil.parse_recipe_file(recipefile, False)
+ except Exception as e:
+ logger.error(str(e))
+ rd = None
+ if not rd:
+ # Parsing failed. We just created this recipe and we shouldn't
+ # leave it in the workdir or it'll prevent bitbake from starting
+ movefn = '%s.parsefailed' % recipefile
+ logger.error('Parsing newly created recipe failed, moving recipe to %s for reference. If this looks to be caused by the recipe itself, please report this error.' % movefn)
+ shutil.move(recipefile, movefn)
+ return 1
+
+ if args.fetchuri and not args.no_git:
+ setup_git_repo(srctree, args.version, 'devtool', d=tinfoil.config_data)
+
+ initial_rev = None
+ if os.path.exists(os.path.join(srctree, '.git')):
+ (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=srctree)
+ initial_rev = stdout.rstrip()
+
+ if args.src_subdir:
+ srctree = os.path.join(srctree, args.src_subdir)
+
+ bb.utils.mkdirhier(os.path.dirname(appendfile))
+ with open(appendfile, 'w') as f:
+ f.write('inherit externalsrc\n')
+ f.write('EXTERNALSRC = "%s"\n' % srctree)
+
+ b_is_s = use_external_build(args.same_dir, args.no_same_dir, rd)
+ if b_is_s:
+ f.write('EXTERNALSRC_BUILD = "%s"\n' % srctree)
+ if initial_rev:
+ f.write('\n# initial_rev: %s\n' % initial_rev)
+
+ if args.binary:
+ f.write('do_install:append() {\n')
+ f.write(' rm -rf ${D}/.git\n')
+ f.write(' rm -f ${D}/singletask.lock\n')
+ f.write('}\n')
+
+ if bb.data.inherits_class('npm', rd):
+ f.write('python do_configure:append() {\n')
+ f.write(' pkgdir = d.getVar("NPM_PACKAGE")\n')
+ f.write(' lockfile = os.path.join(pkgdir, "singletask.lock")\n')
+ f.write(' bb.utils.remove(lockfile)\n')
+ f.write('}\n')
+
+ # Check if the new layer provides recipes whose priorities have been
+ # overriden by PREFERRED_PROVIDER.
+ recipe_name = rd.getVar('PN')
+ provides = rd.getVar('PROVIDES')
+ # Search every item defined in PROVIDES
+ for recipe_provided in provides.split():
+ preferred_provider = 'PREFERRED_PROVIDER_' + recipe_provided
+ current_pprovider = rd.getVar(preferred_provider)
+ if current_pprovider and current_pprovider != recipe_name:
+ if args.fixed_setup:
+ #if we are inside the eSDK add the new PREFERRED_PROVIDER in the workspace layer.conf
+ layerconf_file = os.path.join(config.workspace_path, "conf", "layer.conf")
+ with open(layerconf_file, 'a') as f:
+ f.write('%s = "%s"\n' % (preferred_provider, recipe_name))
+ else:
+ logger.warning('Set \'%s\' in order to use the recipe' % preferred_provider)
+ break
- _add_md5(config, args.recipename, appendfile)
+ _add_md5(config, recipename, appendfile)
+
+ check_prerelease_version(rd.getVar('PV'), 'devtool add')
+
+ logger.info('Recipe %s has been automatically created; further editing may be required to make it fully functional' % recipefile)
+
+ finally:
+ tinfoil.shutdown()
return 0
@@ -130,33 +300,102 @@ def _check_compatible_recipe(pn, d):
"""Check if the recipe is supported by devtool"""
if pn == 'perf':
raise DevtoolError("The perf recipe does not actually check out "
- "source and thus cannot be supported by this tool")
+ "source and thus cannot be supported by this tool",
+ 4)
if pn in ['kernel-devsrc', 'package-index'] or pn.startswith('gcc-source'):
- raise DevtoolError("The %s recipe is not supported by this tool" % pn)
+ raise DevtoolError("The %s recipe is not supported by this tool" % pn, 4)
if bb.data.inherits_class('image', d):
raise DevtoolError("The %s recipe is an image, and therefore is not "
- "supported by this tool" % pn)
+ "supported by this tool" % pn, 4)
if bb.data.inherits_class('populate_sdk', d):
raise DevtoolError("The %s recipe is an SDK, and therefore is not "
- "supported by this tool" % pn)
+ "supported by this tool" % pn, 4)
if bb.data.inherits_class('packagegroup', d):
raise DevtoolError("The %s recipe is a packagegroup, and therefore is "
- "not supported by this tool" % pn)
-
- if bb.data.inherits_class('meta', d):
- raise DevtoolError("The %s recipe is a meta-recipe, and therefore is "
- "not supported by this tool" % pn)
+ "not supported by this tool" % pn, 4)
- if bb.data.inherits_class('externalsrc', d) and d.getVar('EXTERNALSRC', True):
+ if bb.data.inherits_class('externalsrc', d) and d.getVar('EXTERNALSRC'):
+ # Not an incompatibility error per se, so we don't pass the error code
raise DevtoolError("externalsrc is currently enabled for the %s "
"recipe. This prevents the normal do_patch task "
"from working. You will need to disable this "
"first." % pn)
+def _dry_run_copy(src, dst, dry_run_outdir, base_outdir):
+ """Common function for copying a file to the dry run output directory"""
+ relpath = os.path.relpath(dst, base_outdir)
+ if relpath.startswith('..'):
+ raise Exception('Incorrect base path %s for path %s' % (base_outdir, dst))
+ dst = os.path.join(dry_run_outdir, relpath)
+ dst_d = os.path.dirname(dst)
+ if dst_d:
+ bb.utils.mkdirhier(dst_d)
+ # Don't overwrite existing files, otherwise in the case of an upgrade
+ # the dry-run written out recipe will be overwritten with an unmodified
+ # version
+ if not os.path.exists(dst):
+ shutil.copy(src, dst)
+
+def _move_file(src, dst, dry_run_outdir=None, base_outdir=None):
+ """Move a file. Creates all the directory components of destination path."""
+ dry_run_suffix = ' (dry-run)' if dry_run_outdir else ''
+ logger.debug('Moving %s to %s%s' % (src, dst, dry_run_suffix))
+ if dry_run_outdir:
+ # We want to copy here, not move
+ _dry_run_copy(src, dst, dry_run_outdir, base_outdir)
+ else:
+ dst_d = os.path.dirname(dst)
+ if dst_d:
+ bb.utils.mkdirhier(dst_d)
+ shutil.move(src, dst)
+
+def _copy_file(src, dst, dry_run_outdir=None):
+ """Copy a file. Creates all the directory components of destination path."""
+ dry_run_suffix = ' (dry-run)' if dry_run_outdir else ''
+ logger.debug('Copying %s to %s%s' % (src, dst, dry_run_suffix))
+ if dry_run_outdir:
+ _dry_run_copy(src, dst, dry_run_outdir, base_outdir)
+ else:
+ dst_d = os.path.dirname(dst)
+ if dst_d:
+ bb.utils.mkdirhier(dst_d)
+ shutil.copy(src, dst)
+
+def _git_ls_tree(repodir, treeish='HEAD', recursive=False):
+ """List contents of a git treeish"""
+ import bb
+ cmd = ['git', 'ls-tree', '-z', treeish]
+ if recursive:
+ cmd.append('-r')
+ out, _ = bb.process.run(cmd, cwd=repodir)
+ ret = {}
+ if out:
+ for line in out.split('\0'):
+ if line:
+ split = line.split(None, 4)
+ ret[split[3]] = split[0:3]
+ return ret
+
+def _git_exclude_path(srctree, path):
+ """Return pathspec (list of paths) that excludes certain path"""
+ # NOTE: "Filtering out" files/paths in this way is not entirely reliable -
+ # we don't catch files that are deleted, for example. A more reliable way
+ # to implement this would be to use "negative pathspecs" which were
+ # introduced in Git v1.9.0. Revisit this when/if the required Git version
+ # becomes greater than that.
+ path = os.path.normpath(path)
+ recurse = True if len(path.split(os.path.sep)) > 1 else False
+ git_files = list(_git_ls_tree(srctree, 'HEAD', recurse).keys())
+ if path in git_files:
+ git_files.remove(path)
+ return git_files
+ else:
+ return ['.']
+
def _ls_tree(directory):
"""Recursive listing of files in a directory"""
ret = []
@@ -170,211 +409,316 @@ def extract(args, config, basepath, workspace):
"""Entry point for the devtool 'extract' subcommand"""
import bb
- tinfoil = _prep_extract_operation(config, basepath, args.recipename)
-
- rd = parse_recipe(config, tinfoil, args.recipename, True)
- if not rd:
+ tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
+ if not tinfoil:
+ # Error already shown
return 1
+ try:
+ rd = parse_recipe(config, tinfoil, args.recipename, True)
+ if not rd:
+ return 1
- srctree = os.path.abspath(args.srctree)
- initial_rev = _extract_source(srctree, args.keep_temp, args.branch, rd)
- if initial_rev:
- return 0
- else:
- return 1
+ srctree = os.path.abspath(args.srctree)
+ initial_rev, _ = _extract_source(srctree, args.keep_temp, args.branch, False, config, basepath, workspace, args.fixed_setup, rd, tinfoil, no_overrides=args.no_overrides)
+ logger.info('Source tree extracted to %s' % srctree)
+
+ if initial_rev:
+ return 0
+ else:
+ return 1
+ finally:
+ tinfoil.shutdown()
-class BbTaskExecutor(object):
- """Class for executing bitbake tasks for a recipe
+def sync(args, config, basepath, workspace):
+ """Entry point for the devtool 'sync' subcommand"""
+ import bb
- FIXME: This is very awkward. Unfortunately it's not currently easy to
- properly execute tasks outside of bitbake itself, until then this has to
- suffice if we are to handle e.g. linux-yocto's extra tasks
- """
+ tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
+ if not tinfoil:
+ # Error already shown
+ return 1
+ try:
+ rd = parse_recipe(config, tinfoil, args.recipename, True)
+ if not rd:
+ return 1
- def __init__(self, rdata):
- self.rdata = rdata
- self.executed = []
-
- def exec_func(self, func, report):
- """Run bitbake task function"""
- if not func in self.executed:
- deps = self.rdata.getVarFlag(func, 'deps')
- if deps:
- for taskdepfunc in deps:
- self.exec_func(taskdepfunc, True)
- if report:
- logger.info('Executing %s...' % func)
- fn = self.rdata.getVar('FILE', True)
- localdata = bb.build._task_data(fn, func, self.rdata)
- bb.build.exec_func(func, localdata)
- self.executed.append(func)
-
-
-def _prep_extract_operation(config, basepath, recipename):
- """HACK: Ugly workaround for making sure that requirements are met when
- trying to extract a package. Returns the tinfoil instance to be used."""
- tinfoil = setup_tinfoil()
- rd = parse_recipe(config, tinfoil, recipename, True)
+ srctree = os.path.abspath(args.srctree)
+ initial_rev, _ = _extract_source(srctree, args.keep_temp, args.branch, True, config, basepath, workspace, args.fixed_setup, rd, tinfoil, no_overrides=True)
+ logger.info('Source tree %s synchronized' % srctree)
- if bb.data.inherits_class('kernel-yocto', rd):
+ if initial_rev:
+ return 0
+ else:
+ return 1
+ finally:
tinfoil.shutdown()
- try:
- stdout, _ = exec_build_env_command(config.init_path, basepath,
- 'bitbake kern-tools-native')
- tinfoil = setup_tinfoil()
- except bb.process.ExecutionError as err:
- raise DevtoolError("Failed to build kern-tools-native:\n%s" %
- err.stdout)
- return tinfoil
+def symlink_oelocal_files_srctree(rd,srctree):
+ import oe.patch
+ if os.path.abspath(rd.getVar('S')) == os.path.abspath(rd.getVar('WORKDIR')):
+ # If recipe extracts to ${WORKDIR}, symlink the files into the srctree
+ # (otherwise the recipe won't build as expected)
+ local_files_dir = os.path.join(srctree, 'oe-local-files')
+ addfiles = []
+ for root, _, files in os.walk(local_files_dir):
+ relpth = os.path.relpath(root, local_files_dir)
+ if relpth != '.':
+ bb.utils.mkdirhier(os.path.join(srctree, relpth))
+ for fn in files:
+ if fn == '.gitignore':
+ continue
+ destpth = os.path.join(srctree, relpth, fn)
+ if os.path.exists(destpth):
+ os.unlink(destpth)
+ if relpth != '.':
+ back_relpth = os.path.relpath(local_files_dir, root)
+ os.symlink('%s/oe-local-files/%s/%s' % (back_relpth, relpth, fn), destpth)
+ else:
+ os.symlink('oe-local-files/%s' % fn, destpth)
+ addfiles.append(os.path.join(relpth, fn))
+ if addfiles:
+ bb.process.run('git add %s' % ' '.join(addfiles), cwd=srctree)
+ useroptions = []
+ oe.patch.GitApplyTree.gitCommandUserOptions(useroptions, d=rd)
+ bb.process.run('git %s commit -m "Committing local file symlinks\n\n%s"' % (' '.join(useroptions), oe.patch.GitApplyTree.ignore_commit_prefix), cwd=srctree)
-def _extract_source(srctree, keep_temp, devbranch, d):
+
+def _extract_source(srctree, keep_temp, devbranch, sync, config, basepath, workspace, fixed_setup, d, tinfoil, no_overrides=False):
"""Extract sources of a recipe"""
- import bb.event
import oe.recipeutils
+ import oe.patch
+ import oe.path
- def eventfilter(name, handler, event, d):
- """Bitbake event filter for devtool extract operation"""
- if name == 'base_eventhandler':
- return True
- else:
- return False
-
- if hasattr(bb.event, 'set_eventfilter'):
- bb.event.set_eventfilter(eventfilter)
-
- pn = d.getVar('PN', True)
+ pn = d.getVar('PN')
_check_compatible_recipe(pn, d)
- if os.path.exists(srctree):
- if not os.path.isdir(srctree):
- raise DevtoolError("output path %s exists and is not a directory" %
- srctree)
- elif os.listdir(srctree):
- raise DevtoolError("output path %s already exists and is "
- "non-empty" % srctree)
-
- # Prepare for shutil.move later on
- bb.utils.mkdirhier(srctree)
- os.rmdir(srctree)
-
- # We don't want notes to be printed, they are too verbose
- origlevel = bb.logger.getEffectiveLevel()
- if logger.getEffectiveLevel() > logging.DEBUG:
- bb.logger.setLevel(logging.WARNING)
+ if sync:
+ if not os.path.exists(srctree):
+ raise DevtoolError("output path %s does not exist" % srctree)
+ else:
+ if os.path.exists(srctree):
+ if not os.path.isdir(srctree):
+ raise DevtoolError("output path %s exists and is not a directory" %
+ srctree)
+ elif os.listdir(srctree):
+ raise DevtoolError("output path %s already exists and is "
+ "non-empty" % srctree)
+
+ if 'noexec' in (d.getVarFlags('do_unpack', False) or []):
+ raise DevtoolError("The %s recipe has do_unpack disabled, unable to "
+ "extract source" % pn, 4)
+
+ if not sync:
+ # Prepare for shutil.move later on
+ bb.utils.mkdirhier(srctree)
+ os.rmdir(srctree)
+
+ extra_overrides = []
+ if not no_overrides:
+ history = d.varhistory.variable('SRC_URI')
+ for event in history:
+ if not 'flag' in event:
+ if event['op'].startswith((':append[', ':prepend[')):
+ extra_overrides.append(event['op'].split('[')[1].split(']')[0])
+ # We want to remove duplicate overrides. If a recipe had multiple
+ # SRC_URI_override += values it would cause mulitple instances of
+ # overrides. This doesn't play nicely with things like creating a
+ # branch for every instance of DEVTOOL_EXTRA_OVERRIDES.
+ extra_overrides = list(set(extra_overrides))
+ if extra_overrides:
+ logger.info('SRC_URI contains some conditional appends/prepends - will create branches to represent these')
initial_rev = None
- tempdir = tempfile.mkdtemp(prefix='devtool')
+
+ recipefile = d.getVar('FILE')
+ appendfile = recipe_to_append(recipefile, config)
+ is_kernel_yocto = bb.data.inherits_class('kernel-yocto', d)
+
+ # We need to redirect WORKDIR, STAMPS_DIR etc. under a temporary
+ # directory so that:
+ # (a) we pick up all files that get unpacked to the WORKDIR, and
+ # (b) we don't disturb the existing build
+ # However, with recipe-specific sysroots the sysroots for the recipe
+ # will be prepared under WORKDIR, and if we used the system temporary
+ # directory (i.e. usually /tmp) as used by mkdtemp by default, then
+ # our attempts to hardlink files into the recipe-specific sysroots
+ # will fail on systems where /tmp is a different filesystem, and it
+ # would have to fall back to copying the files which is a waste of
+ # time. Put the temp directory under the WORKDIR to prevent that from
+ # being a problem.
+ tempbasedir = d.getVar('WORKDIR')
+ bb.utils.mkdirhier(tempbasedir)
+ tempdir = tempfile.mkdtemp(prefix='devtooltmp-', dir=tempbasedir)
try:
- crd = d.createCopy()
- # Make a subdir so we guard against WORKDIR==S
- workdir = os.path.join(tempdir, 'workdir')
- crd.setVar('WORKDIR', workdir)
- crd.setVar('T', os.path.join(tempdir, 'temp'))
- if not crd.getVar('S', True).startswith(workdir):
- # Usually a shared workdir recipe (kernel, gcc)
- # Try to set a reasonable default
- if bb.data.inherits_class('kernel', d):
- crd.setVar('S', '${WORKDIR}/source')
- else:
- crd.setVar('S', '${WORKDIR}/${BP}')
- if bb.data.inherits_class('kernel', d):
- # We don't want to move the source to STAGING_KERNEL_DIR here
- crd.setVar('STAGING_KERNEL_DIR', '${S}')
-
- task_executor = BbTaskExecutor(crd)
-
- crd.setVar('EXTERNALSRC_forcevariable', '')
-
- logger.info('Fetching %s...' % pn)
- task_executor.exec_func('do_fetch', False)
- logger.info('Unpacking...')
- task_executor.exec_func('do_unpack', False)
- if bb.data.inherits_class('kernel-yocto', d):
- # Extra step for kernel to populate the source directory
- logger.info('Doing kernel checkout...')
- task_executor.exec_func('do_kernel_checkout', False)
- srcsubdir = crd.getVar('S', True)
- if srcsubdir == workdir:
- # Find non-patch sources that were "unpacked" to srctree directory
- recipe_patches = [os.path.basename(patch) for patch in
- oe.recipeutils.get_recipe_patches(crd)]
- src_files = [fname for fname in _ls_tree(workdir) if
- os.path.basename(fname) not in recipe_patches]
- # Force separate S so that patch files can be left out from srctree
- srcsubdir = tempfile.mkdtemp(dir=workdir)
- crd.setVar('S', srcsubdir)
- # Move source files to S
- for path in src_files:
- tgt_dir = os.path.join(srcsubdir, os.path.dirname(path))
- bb.utils.mkdirhier(tgt_dir)
- shutil.move(os.path.join(workdir, path), tgt_dir)
- elif os.path.dirname(srcsubdir) != workdir:
- # Handle if S is set to a subdirectory of the source
- srcsubdir = os.path.join(workdir, os.path.relpath(srcsubdir, workdir).split(os.sep)[0])
+ tinfoil.logger.setLevel(logging.WARNING)
- scriptutils.git_convert_standalone_clone(srcsubdir)
+ # FIXME this results in a cache reload under control of tinfoil, which is fine
+ # except we don't get the knotty progress bar
- patchdir = os.path.join(srcsubdir, 'patches')
- haspatches = False
- if os.path.exists(patchdir):
- if os.listdir(patchdir):
- haspatches = True
+ if os.path.exists(appendfile):
+ appendbackup = os.path.join(tempdir, os.path.basename(appendfile) + '.bak')
+ shutil.copyfile(appendfile, appendbackup)
+ else:
+ appendbackup = None
+ bb.utils.mkdirhier(os.path.dirname(appendfile))
+ logger.debug('writing append file %s' % appendfile)
+ with open(appendfile, 'a') as f:
+ f.write('###--- _extract_source\n')
+ f.write('DEVTOOL_TEMPDIR = "%s"\n' % tempdir)
+ f.write('DEVTOOL_DEVBRANCH = "%s"\n' % devbranch)
+ if not is_kernel_yocto:
+ f.write('PATCHTOOL = "git"\n')
+ f.write('PATCH_COMMIT_FUNCTIONS = "1"\n')
+ if extra_overrides:
+ f.write('DEVTOOL_EXTRA_OVERRIDES = "%s"\n' % ':'.join(extra_overrides))
+ f.write('inherit devtool-source\n')
+ f.write('###--- _extract_source\n')
+
+ update_unlockedsigs(basepath, workspace, fixed_setup, [pn])
+
+ sstate_manifests = d.getVar('SSTATE_MANIFESTS')
+ bb.utils.mkdirhier(sstate_manifests)
+ preservestampfile = os.path.join(sstate_manifests, 'preserve-stamps')
+ with open(preservestampfile, 'w') as f:
+ f.write(d.getVar('STAMP'))
+ try:
+ if is_kernel_yocto:
+ # We need to generate the kernel config
+ task = 'do_configure'
else:
- os.rmdir(patchdir)
+ task = 'do_patch'
+
+ if 'noexec' in (d.getVarFlags(task, False) or []) or 'task' not in (d.getVarFlags(task, False) or []):
+ logger.info('The %s recipe has %s disabled. Running only '
+ 'do_configure task dependencies' % (pn, task))
+
+ if 'depends' in d.getVarFlags('do_configure', False):
+ pn = d.getVarFlags('do_configure', False)['depends']
+ pn = pn.replace('${PV}', d.getVar('PV'))
+ pn = pn.replace('${COMPILERDEP}', d.getVar('COMPILERDEP'))
+ task = None
+
+ # Run the fetch + unpack tasks
+ res = tinfoil.build_targets(pn,
+ task,
+ handle_events=True)
+ finally:
+ if os.path.exists(preservestampfile):
+ os.remove(preservestampfile)
- if not os.listdir(srcsubdir):
- raise DevtoolError("no source unpacked to S, perhaps the %s "
- "recipe doesn't use any source?" % pn)
+ if not res:
+ raise DevtoolError('Extracting source for %s failed' % pn)
- if not os.path.exists(os.path.join(srcsubdir, '.git')):
- bb.process.run('git init', cwd=srcsubdir)
- bb.process.run('git add .', cwd=srcsubdir)
- bb.process.run('git commit -q -m "Initial commit from upstream at version %s"' % crd.getVar('PV', True), cwd=srcsubdir)
+ if not is_kernel_yocto and ('noexec' in (d.getVarFlags('do_patch', False) or []) or 'task' not in (d.getVarFlags('do_patch', False) or [])):
+ workshareddir = d.getVar('S')
+ if os.path.islink(srctree):
+ os.unlink(srctree)
- (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=srcsubdir)
- initial_rev = stdout.rstrip()
+ os.symlink(workshareddir, srctree)
- bb.process.run('git checkout -b %s' % devbranch, cwd=srcsubdir)
- bb.process.run('git tag -f devtool-base', cwd=srcsubdir)
- crd.setVar('PATCHTOOL', 'git')
+ # The initial_rev file is created in devtool_post_unpack function that will not be executed if
+ # do_unpack/do_patch tasks are disabled so we have to directly say that source extraction was successful
+ return True, True
- logger.info('Patching...')
- task_executor.exec_func('do_patch', False)
+ try:
+ with open(os.path.join(tempdir, 'initial_rev'), 'r') as f:
+ initial_rev = f.read()
+
+ with open(os.path.join(tempdir, 'srcsubdir'), 'r') as f:
+ srcsubdir = f.read()
+ except FileNotFoundError as e:
+ raise DevtoolError('Something went wrong with source extraction - the devtool-source class was not active or did not function correctly:\n%s' % str(e))
+ srcsubdir_rel = os.path.relpath(srcsubdir, os.path.join(tempdir, 'workdir'))
+
+ # Check if work-shared is empty, if yes
+ # find source and copy to work-shared
+ if is_kernel_yocto:
+ workshareddir = d.getVar('STAGING_KERNEL_DIR')
+ staging_kerVer = get_staging_kver(workshareddir)
+ kernelVersion = d.getVar('LINUX_VERSION')
+
+ # handle dangling symbolic link in work-shared:
+ if os.path.islink(workshareddir):
+ os.unlink(workshareddir)
+
+ if os.path.exists(workshareddir) and (not os.listdir(workshareddir) or kernelVersion != staging_kerVer):
+ shutil.rmtree(workshareddir)
+ oe.path.copyhardlinktree(srcsubdir,workshareddir)
+ elif not os.path.exists(workshareddir):
+ oe.path.copyhardlinktree(srcsubdir,workshareddir)
+
+ tempdir_localdir = os.path.join(tempdir, 'oe-local-files')
+ srctree_localdir = os.path.join(srctree, 'oe-local-files')
+
+ if sync:
+ bb.process.run('git fetch file://' + srcsubdir + ' ' + devbranch + ':' + devbranch, cwd=srctree)
+
+ # Move oe-local-files directory to srctree
+ # As the oe-local-files is not part of the constructed git tree,
+ # remove them directly during the synchrounizating might surprise
+ # the users. Instead, we move it to oe-local-files.bak and remind
+ # user in the log message.
+ if os.path.exists(srctree_localdir + '.bak'):
+ shutil.rmtree(srctree_localdir, srctree_localdir + '.bak')
+
+ if os.path.exists(srctree_localdir):
+ logger.info('Backing up current local file directory %s' % srctree_localdir)
+ shutil.move(srctree_localdir, srctree_localdir + '.bak')
+
+ if os.path.exists(tempdir_localdir):
+ logger.info('Syncing local source files to srctree...')
+ shutil.copytree(tempdir_localdir, srctree_localdir)
+ else:
+ # Move oe-local-files directory to srctree
+ if os.path.exists(tempdir_localdir):
+ logger.info('Adding local source files to srctree...')
+ shutil.move(tempdir_localdir, srcsubdir)
- bb.process.run('git tag -f devtool-patched', cwd=srcsubdir)
+ shutil.move(srcsubdir, srctree)
+ symlink_oelocal_files_srctree(d,srctree)
- if os.path.exists(patchdir):
- shutil.rmtree(patchdir)
- if haspatches:
- bb.process.run('git checkout patches', cwd=srcsubdir)
+ if is_kernel_yocto:
+ logger.info('Copying kernel config to srctree')
+ shutil.copy2(os.path.join(tempdir, '.config'), srctree)
- shutil.move(srcsubdir, srctree)
- logger.info('Source tree extracted to %s' % srctree)
finally:
- bb.logger.setLevel(origlevel)
-
+ if appendbackup:
+ shutil.copyfile(appendbackup, appendfile)
+ elif os.path.exists(appendfile):
+ os.remove(appendfile)
if keep_temp:
logger.info('Preserving temporary directory %s' % tempdir)
else:
shutil.rmtree(tempdir)
- return initial_rev
+ return initial_rev, srcsubdir_rel
def _add_md5(config, recipename, filename):
- """Record checksum of a recipe to the md5-file of the workspace"""
+ """Record checksum of a file (or recursively for a directory) to the md5-file of the workspace"""
import bb.utils
- md5 = bb.utils.md5_file(filename)
- with open(os.path.join(config.workspace_path, '.devtool_md5'), 'a') as f:
- f.write('%s|%s|%s\n' % (recipename, os.path.relpath(filename, config.workspace_path), md5))
+
+ def addfile(fn):
+ md5 = bb.utils.md5_file(fn)
+ with open(os.path.join(config.workspace_path, '.devtool_md5'), 'a+') as f:
+ md5_str = '%s|%s|%s\n' % (recipename, os.path.relpath(fn, config.workspace_path), md5)
+ f.seek(0, os.SEEK_SET)
+ if not md5_str in f.read():
+ f.write(md5_str)
+
+ if os.path.isdir(filename):
+ for root, _, files in os.walk(filename):
+ for f in files:
+ addfile(os.path.join(root, f))
+ else:
+ addfile(filename)
def _check_preserve(config, recipename):
- """Check if a recipe was manually changed and needs to be saved in 'attic'
+ """Check if a file was manually changed and needs to be saved in 'attic'
directory"""
import bb.utils
origfile = os.path.join(config.workspace_path, '.devtool_md5')
newfile = os.path.join(config.workspace_path, '.devtool_md5_new')
- preservepath = os.path.join(config.workspace_path, 'attic')
+ preservepath = os.path.join(config.workspace_path, 'attic', recipename)
with open(origfile, 'r') as f:
with open(newfile, 'w') as tf:
for line in f.readlines():
@@ -392,195 +736,778 @@ def _check_preserve(config, recipename):
if splitline[2] != md5:
bb.utils.mkdirhier(preservepath)
preservefile = os.path.basename(removefile)
- logger.warn('File %s modified since it was written, preserving in %s' % (preservefile, preservepath))
+ logger.warning('File %s modified since it was written, preserving in %s' % (preservefile, preservepath))
shutil.move(removefile, os.path.join(preservepath, preservefile))
else:
os.remove(removefile)
else:
tf.write(line)
- os.rename(newfile, origfile)
+ bb.utils.rename(newfile, origfile)
+
+def get_staging_kver(srcdir):
+ # Kernel version from work-shared
+ kerver = []
+ staging_kerVer=""
+ if os.path.exists(srcdir) and os.listdir(srcdir):
+ with open(os.path.join(srcdir,"Makefile")) as f:
+ version = [next(f) for x in range(5)][1:4]
+ for word in version:
+ kerver.append(word.split('= ')[1].split('\n')[0])
+ staging_kerVer = ".".join(kerver)
+ return staging_kerVer
+
+def get_staging_kbranch(srcdir):
+ staging_kbranch = ""
+ if os.path.exists(srcdir) and os.listdir(srcdir):
+ (branch, _) = bb.process.run('git branch | grep \* | cut -d \' \' -f2', cwd=srcdir)
+ staging_kbranch = "".join(branch.split('\n')[0])
+ return staging_kbranch
def modify(args, config, basepath, workspace):
"""Entry point for the devtool 'modify' subcommand"""
import bb
import oe.recipeutils
+ import oe.patch
+ import oe.path
if args.recipename in workspace:
raise DevtoolError("recipe %s is already in your workspace" %
args.recipename)
- if not args.extract and not os.path.isdir(args.srctree):
- raise DevtoolError("directory %s does not exist or not a directory "
- "(specify -x to extract source from recipe)" %
- args.srctree)
- if args.extract:
- tinfoil = _prep_extract_operation(config, basepath, args.recipename)
- else:
- tinfoil = setup_tinfoil()
+ tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
+ try:
+ rd = parse_recipe(config, tinfoil, args.recipename, True)
+ if not rd:
+ return 1
- rd = parse_recipe(config, tinfoil, args.recipename, True)
- if not rd:
- return 1
- recipefile = rd.getVar('FILE', True)
- appendname = os.path.splitext(os.path.basename(recipefile))[0]
- if args.wildcard:
- appendname = re.sub(r'_.*', '_%', appendname)
- appendpath = os.path.join(config.workspace_path, 'appends')
- appendfile = os.path.join(appendpath, appendname + '.bbappend')
- if os.path.exists(appendfile):
- raise DevtoolError("Another variant of recipe %s is already in your "
- "workspace (only one variant of a recipe can "
- "currently be worked on at once)"
- % args.recipename)
-
- _check_compatible_recipe(args.recipename, rd)
+ pn = rd.getVar('PN')
+ if pn != args.recipename:
+ logger.info('Mapping %s to %s' % (args.recipename, pn))
+ if pn in workspace:
+ raise DevtoolError("recipe %s is already in your workspace" %
+ pn)
- initial_rev = None
- commits = []
- srctree = os.path.abspath(args.srctree)
- if args.extract:
- initial_rev = _extract_source(args.srctree, False, args.branch, rd)
- if not initial_rev:
- return 1
- # Get list of commits since this revision
- (stdout, _) = bb.process.run('git rev-list --reverse %s..HEAD' % initial_rev, cwd=args.srctree)
- commits = stdout.split()
- else:
- if os.path.exists(os.path.join(args.srctree, '.git')):
- # Check if it's a tree previously extracted by us
- try:
- (stdout, _) = bb.process.run('git branch --contains devtool-base', cwd=args.srctree)
- except bb.process.ExecutionError:
- stdout = ''
- for line in stdout.splitlines():
- if line.startswith('*'):
- (stdout, _) = bb.process.run('git rev-parse devtool-base', cwd=args.srctree)
- initial_rev = stdout.rstrip()
+ if args.srctree:
+ srctree = os.path.abspath(args.srctree)
+ else:
+ srctree = get_default_srctree(config, pn)
+
+ if args.no_extract and not os.path.isdir(srctree):
+ raise DevtoolError("--no-extract specified and source path %s does "
+ "not exist or is not a directory" %
+ srctree)
+
+ recipefile = rd.getVar('FILE')
+ appendfile = recipe_to_append(recipefile, config, args.wildcard)
+ if os.path.exists(appendfile):
+ raise DevtoolError("Another variant of recipe %s is already in your "
+ "workspace (only one variant of a recipe can "
+ "currently be worked on at once)"
+ % pn)
+
+ _check_compatible_recipe(pn, rd)
+
+ initial_rev = None
+ commits = []
+ check_commits = False
+
+ if bb.data.inherits_class('kernel-yocto', rd):
+ # Current set kernel version
+ kernelVersion = rd.getVar('LINUX_VERSION')
+ srcdir = rd.getVar('STAGING_KERNEL_DIR')
+ kbranch = rd.getVar('KBRANCH')
+
+ staging_kerVer = get_staging_kver(srcdir)
+ staging_kbranch = get_staging_kbranch(srcdir)
+ if (os.path.exists(srcdir) and os.listdir(srcdir)) and (kernelVersion in staging_kerVer and staging_kbranch == kbranch):
+ oe.path.copyhardlinktree(srcdir,srctree)
+ workdir = rd.getVar('WORKDIR')
+ srcsubdir = rd.getVar('S')
+ localfilesdir = os.path.join(srctree,'oe-local-files')
+ # Move local source files into separate subdir
+ recipe_patches = [os.path.basename(patch) for patch in oe.recipeutils.get_recipe_patches(rd)]
+ local_files = oe.recipeutils.get_recipe_local_files(rd)
+
+ for key in local_files.copy():
+ if key.endswith('scc'):
+ sccfile = open(local_files[key], 'r')
+ for l in sccfile:
+ line = l.split()
+ if line and line[0] in ('kconf', 'patch'):
+ cfg = os.path.join(os.path.dirname(local_files[key]), line[-1])
+ if not cfg in local_files.values():
+ local_files[line[-1]] = cfg
+ shutil.copy2(cfg, workdir)
+ sccfile.close()
+
+ # Ignore local files with subdir={BP}
+ srcabspath = os.path.abspath(srcsubdir)
+ local_files = [fname for fname in local_files if os.path.exists(os.path.join(workdir, fname)) and (srcabspath == workdir or not os.path.join(workdir, fname).startswith(srcabspath + os.sep))]
+ if local_files:
+ for fname in local_files:
+ _move_file(os.path.join(workdir, fname), os.path.join(srctree, 'oe-local-files', fname))
+ with open(os.path.join(srctree, 'oe-local-files', '.gitignore'), 'w') as f:
+ f.write('# Ignore local files, by default. Remove this file ''if you want to commit the directory to Git\n*\n')
+
+ symlink_oelocal_files_srctree(rd,srctree)
+
+ task = 'do_configure'
+ res = tinfoil.build_targets(pn, task, handle_events=True)
+
+ # Copy .config to workspace
+ kconfpath = rd.getVar('B')
+ logger.info('Copying kernel config to workspace')
+ shutil.copy2(os.path.join(kconfpath, '.config'),srctree)
+
+ # Set this to true, we still need to get initial_rev
+ # by parsing the git repo
+ args.no_extract = True
+
+ if not args.no_extract:
+ initial_rev, _ = _extract_source(srctree, args.keep_temp, args.branch, False, config, basepath, workspace, args.fixed_setup, rd, tinfoil, no_overrides=args.no_overrides)
if not initial_rev:
- # Otherwise, just grab the head revision
- (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=args.srctree)
- initial_rev = stdout.rstrip()
-
- # Check that recipe isn't using a shared workdir
- s = os.path.abspath(rd.getVar('S', True))
- workdir = os.path.abspath(rd.getVar('WORKDIR', True))
- if s.startswith(workdir) and s != workdir and os.path.dirname(s) != workdir:
- # Handle if S is set to a subdirectory of the source
- srcsubdir = os.path.relpath(s, workdir).split(os.sep, 1)[1]
- srctree = os.path.join(srctree, srcsubdir)
-
- if not os.path.exists(appendpath):
- os.makedirs(appendpath)
- with open(appendfile, 'w') as f:
- f.write('FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"\n\n')
- f.write('inherit externalsrc\n')
- f.write('# NOTE: We use pn- overrides here to avoid affecting multiple variants in the case where the recipe uses BBCLASSEXTEND\n')
- f.write('EXTERNALSRC_pn-%s = "%s"\n' % (args.recipename, srctree))
-
- b_is_s = True
- if args.no_same_dir:
- logger.info('using separate build directory since --no-same-dir specified')
- b_is_s = False
- elif args.same_dir:
- logger.info('using source tree as build directory since --same-dir specified')
- elif bb.data.inherits_class('autotools-brokensep', rd):
- logger.info('using source tree as build directory since original recipe inherits autotools-brokensep')
- elif rd.getVar('B', True) == s:
- logger.info('using source tree as build directory since that is the default for this recipe')
+ return 1
+ logger.info('Source tree extracted to %s' % srctree)
+ if os.path.exists(os.path.join(srctree, '.git')):
+ # Get list of commits since this revision
+ (stdout, _) = bb.process.run('git rev-list --reverse %s..HEAD' % initial_rev, cwd=srctree)
+ commits = stdout.split()
+ check_commits = True
else:
- b_is_s = False
- if b_is_s:
- f.write('EXTERNALSRC_BUILD_pn-%s = "%s"\n' % (args.recipename, srctree))
+ if os.path.exists(os.path.join(srctree, '.git')):
+ # Check if it's a tree previously extracted by us. This is done
+ # by ensuring that devtool-base and args.branch (devtool) exist.
+ # The check_commits logic will cause an exception if either one
+ # of these doesn't exist
+ try:
+ (stdout, _) = bb.process.run('git branch --contains devtool-base', cwd=srctree)
+ bb.process.run('git rev-parse %s' % args.branch, cwd=srctree)
+ except bb.process.ExecutionError:
+ stdout = ''
+ if stdout:
+ check_commits = True
+ for line in stdout.splitlines():
+ if line.startswith('*'):
+ (stdout, _) = bb.process.run('git rev-parse devtool-base', cwd=srctree)
+ initial_rev = stdout.rstrip()
+ if not initial_rev:
+ # Otherwise, just grab the head revision
+ (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=srctree)
+ initial_rev = stdout.rstrip()
- if bb.data.inherits_class('kernel', rd):
- f.write('SRCTREECOVEREDTASKS = "do_validate_branches do_kernel_checkout do_shared_workdir do_fetch do_unpack"\n')
- if initial_rev:
- f.write('\n# initial_rev: %s\n' % initial_rev)
- for commit in commits:
- f.write('# commit: %s\n' % commit)
+ branch_patches = {}
+ if check_commits:
+ # Check if there are override branches
+ (stdout, _) = bb.process.run('git branch', cwd=srctree)
+ branches = []
+ for line in stdout.rstrip().splitlines():
+ branchname = line[2:].rstrip()
+ if branchname.startswith(override_branch_prefix):
+ branches.append(branchname)
+ if branches:
+ logger.warning('SRC_URI is conditionally overridden in this recipe, thus several %s* branches have been created, one for each override that makes changes to SRC_URI. It is recommended that you make changes to the %s branch first, then checkout and rebase each %s* branch and update any unique patches there (duplicates on those branches will be ignored by devtool finish/update-recipe)' % (override_branch_prefix, args.branch, override_branch_prefix))
+ branches.insert(0, args.branch)
+ seen_patches = []
+ for branch in branches:
+ branch_patches[branch] = []
+ (stdout, _) = bb.process.run('git log devtool-base..%s' % branch, cwd=srctree)
+ for line in stdout.splitlines():
+ line = line.strip()
+ if line.startswith(oe.patch.GitApplyTree.patch_line_prefix):
+ origpatch = line[len(oe.patch.GitApplyTree.patch_line_prefix):].split(':', 1)[-1].strip()
+ if not origpatch in seen_patches:
+ seen_patches.append(origpatch)
+ branch_patches[branch].append(origpatch)
+
+ # Need to grab this here in case the source is within a subdirectory
+ srctreebase = srctree
+
+ # Check that recipe isn't using a shared workdir
+ s = os.path.abspath(rd.getVar('S'))
+ workdir = os.path.abspath(rd.getVar('WORKDIR'))
+ if s.startswith(workdir) and s != workdir and os.path.dirname(s) != workdir:
+ # Handle if S is set to a subdirectory of the source
+ srcsubdir = os.path.relpath(s, workdir).split(os.sep, 1)[1]
+ srctree = os.path.join(srctree, srcsubdir)
+
+ bb.utils.mkdirhier(os.path.dirname(appendfile))
+ with open(appendfile, 'w') as f:
+ f.write('FILESEXTRAPATHS:prepend := "${THISDIR}/${PN}:"\n')
+ # Local files can be modified/tracked in separate subdir under srctree
+ # Mostly useful for packages with S != WORKDIR
+ f.write('FILESPATH:prepend := "%s:"\n' %
+ os.path.join(srctreebase, 'oe-local-files'))
+ f.write('# srctreebase: %s\n' % srctreebase)
+
+ f.write('\ninherit externalsrc\n')
+ f.write('# NOTE: We use pn- overrides here to avoid affecting multiple variants in the case where the recipe uses BBCLASSEXTEND\n')
+ f.write('EXTERNALSRC:pn-%s = "%s"\n' % (pn, srctree))
+
+ b_is_s = use_external_build(args.same_dir, args.no_same_dir, rd)
+ if b_is_s:
+ f.write('EXTERNALSRC_BUILD:pn-%s = "%s"\n' % (pn, srctree))
+
+ if bb.data.inherits_class('kernel', rd):
+ f.write('SRCTREECOVEREDTASKS = "do_validate_branches do_kernel_checkout '
+ 'do_fetch do_unpack do_kernel_configcheck"\n')
+ f.write('\ndo_patch[noexec] = "1"\n')
+ f.write('\ndo_configure:append() {\n'
+ ' cp ${B}/.config ${S}/.config.baseline\n'
+ ' ln -sfT ${B}/.config ${S}/.config.new\n'
+ '}\n')
+ f.write('\ndo_kernel_configme:prepend() {\n'
+ ' if [ -e ${S}/.config ]; then\n'
+ ' mv ${S}/.config ${S}/.config.old\n'
+ ' fi\n'
+ '}\n')
+ if rd.getVarFlag('do_menuconfig','task'):
+ f.write('\ndo_configure:append() {\n'
+ ' if [ ! ${DEVTOOL_DISABLE_MENUCONFIG} ]; then\n'
+ ' cp ${B}/.config ${S}/.config.baseline\n'
+ ' ln -sfT ${B}/.config ${S}/.config.new\n'
+ ' fi\n'
+ '}\n')
+ if initial_rev:
+ f.write('\n# initial_rev: %s\n' % initial_rev)
+ for commit in commits:
+ f.write('# commit: %s\n' % commit)
+ if branch_patches:
+ for branch in branch_patches:
+ if branch == args.branch:
+ continue
+ f.write('# patches_%s: %s\n' % (branch, ','.join(branch_patches[branch])))
+
+ update_unlockedsigs(basepath, workspace, args.fixed_setup, [pn])
+
+ _add_md5(config, pn, appendfile)
+
+ logger.info('Recipe %s now set up to build from %s' % (pn, srctree))
+
+ finally:
+ tinfoil.shutdown()
+
+ return 0
+
+
+def rename(args, config, basepath, workspace):
+ """Entry point for the devtool 'rename' subcommand"""
+ import bb
+ import oe.recipeutils
+
+ check_workspace_recipe(workspace, args.recipename)
+
+ if not (args.newname or args.version):
+ raise DevtoolError('You must specify a new name, a version with -V/--version, or both')
+
+ recipefile = workspace[args.recipename]['recipefile']
+ if not recipefile:
+ raise DevtoolError('devtool rename can only be used where the recipe file itself is in the workspace (e.g. after devtool add)')
- _add_md5(config, args.recipename, appendfile)
+ if args.newname and args.newname != args.recipename:
+ reason = oe.recipeutils.validate_pn(args.newname)
+ if reason:
+ raise DevtoolError(reason)
+ newname = args.newname
+ else:
+ newname = args.recipename
+
+ append = workspace[args.recipename]['bbappend']
+ appendfn = os.path.splitext(os.path.basename(append))[0]
+ splitfn = appendfn.split('_')
+ if len(splitfn) > 1:
+ origfnver = appendfn.split('_')[1]
+ else:
+ origfnver = ''
+
+ recipefilemd5 = None
+ tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
+ try:
+ rd = parse_recipe(config, tinfoil, args.recipename, True)
+ if not rd:
+ return 1
+
+ bp = rd.getVar('BP')
+ bpn = rd.getVar('BPN')
+ if newname != args.recipename:
+ localdata = rd.createCopy()
+ localdata.setVar('PN', newname)
+ newbpn = localdata.getVar('BPN')
+ else:
+ newbpn = bpn
+ s = rd.getVar('S', False)
+ src_uri = rd.getVar('SRC_URI', False)
+ pv = rd.getVar('PV')
+
+ # Correct variable values that refer to the upstream source - these
+ # values must stay the same, so if the name/version are changing then
+ # we need to fix them up
+ new_s = s
+ new_src_uri = src_uri
+ if newbpn != bpn:
+ # ${PN} here is technically almost always incorrect, but people do use it
+ new_s = new_s.replace('${BPN}', bpn)
+ new_s = new_s.replace('${PN}', bpn)
+ new_s = new_s.replace('${BP}', '%s-${PV}' % bpn)
+ new_src_uri = new_src_uri.replace('${BPN}', bpn)
+ new_src_uri = new_src_uri.replace('${PN}', bpn)
+ new_src_uri = new_src_uri.replace('${BP}', '%s-${PV}' % bpn)
+ if args.version and origfnver == pv:
+ new_s = new_s.replace('${PV}', pv)
+ new_s = new_s.replace('${BP}', '${BPN}-%s' % pv)
+ new_src_uri = new_src_uri.replace('${PV}', pv)
+ new_src_uri = new_src_uri.replace('${BP}', '${BPN}-%s' % pv)
+ patchfields = {}
+ if new_s != s:
+ patchfields['S'] = new_s
+ if new_src_uri != src_uri:
+ patchfields['SRC_URI'] = new_src_uri
+ if patchfields:
+ recipefilemd5 = bb.utils.md5_file(recipefile)
+ oe.recipeutils.patch_recipe(rd, recipefile, patchfields)
+ newrecipefilemd5 = bb.utils.md5_file(recipefile)
+ finally:
+ tinfoil.shutdown()
- logger.info('Recipe %s now set up to build from %s' % (args.recipename, srctree))
+ if args.version:
+ newver = args.version
+ else:
+ newver = origfnver
+ if newver:
+ newappend = '%s_%s.bbappend' % (newname, newver)
+ newfile = '%s_%s.bb' % (newname, newver)
+ else:
+ newappend = '%s.bbappend' % newname
+ newfile = '%s.bb' % newname
+
+ oldrecipedir = os.path.dirname(recipefile)
+ newrecipedir = os.path.join(config.workspace_path, 'recipes', newname)
+ if oldrecipedir != newrecipedir:
+ bb.utils.mkdirhier(newrecipedir)
+
+ newappend = os.path.join(os.path.dirname(append), newappend)
+ newfile = os.path.join(newrecipedir, newfile)
+
+ # Rename bbappend
+ logger.info('Renaming %s to %s' % (append, newappend))
+ bb.utils.rename(append, newappend)
+ # Rename recipe file
+ logger.info('Renaming %s to %s' % (recipefile, newfile))
+ bb.utils.rename(recipefile, newfile)
+
+ # Rename source tree if it's the default path
+ appendmd5 = None
+ if not args.no_srctree:
+ srctree = workspace[args.recipename]['srctree']
+ if os.path.abspath(srctree) == os.path.join(config.workspace_path, 'sources', args.recipename):
+ newsrctree = os.path.join(config.workspace_path, 'sources', newname)
+ logger.info('Renaming %s to %s' % (srctree, newsrctree))
+ shutil.move(srctree, newsrctree)
+ # Correct any references (basically EXTERNALSRC*) in the .bbappend
+ appendmd5 = bb.utils.md5_file(newappend)
+ appendlines = []
+ with open(newappend, 'r') as f:
+ for line in f:
+ appendlines.append(line)
+ with open(newappend, 'w') as f:
+ for line in appendlines:
+ if srctree in line:
+ line = line.replace(srctree, newsrctree)
+ f.write(line)
+ newappendmd5 = bb.utils.md5_file(newappend)
+
+ bpndir = None
+ newbpndir = None
+ if newbpn != bpn:
+ bpndir = os.path.join(oldrecipedir, bpn)
+ if os.path.exists(bpndir):
+ newbpndir = os.path.join(newrecipedir, newbpn)
+ logger.info('Renaming %s to %s' % (bpndir, newbpndir))
+ shutil.move(bpndir, newbpndir)
+
+ bpdir = None
+ newbpdir = None
+ if newver != origfnver or newbpn != bpn:
+ bpdir = os.path.join(oldrecipedir, bp)
+ if os.path.exists(bpdir):
+ newbpdir = os.path.join(newrecipedir, '%s-%s' % (newbpn, newver))
+ logger.info('Renaming %s to %s' % (bpdir, newbpdir))
+ shutil.move(bpdir, newbpdir)
+
+ if oldrecipedir != newrecipedir:
+ # Move any stray files and delete the old recipe directory
+ for entry in os.listdir(oldrecipedir):
+ oldpath = os.path.join(oldrecipedir, entry)
+ newpath = os.path.join(newrecipedir, entry)
+ logger.info('Renaming %s to %s' % (oldpath, newpath))
+ shutil.move(oldpath, newpath)
+ os.rmdir(oldrecipedir)
+
+ # Now take care of entries in .devtool_md5
+ md5entries = []
+ with open(os.path.join(config.workspace_path, '.devtool_md5'), 'r') as f:
+ for line in f:
+ md5entries.append(line)
+
+ if bpndir and newbpndir:
+ relbpndir = os.path.relpath(bpndir, config.workspace_path) + '/'
+ else:
+ relbpndir = None
+ if bpdir and newbpdir:
+ relbpdir = os.path.relpath(bpdir, config.workspace_path) + '/'
+ else:
+ relbpdir = None
+
+ with open(os.path.join(config.workspace_path, '.devtool_md5'), 'w') as f:
+ for entry in md5entries:
+ splitentry = entry.rstrip().split('|')
+ if len(splitentry) > 2:
+ if splitentry[0] == args.recipename:
+ splitentry[0] = newname
+ if splitentry[1] == os.path.relpath(append, config.workspace_path):
+ splitentry[1] = os.path.relpath(newappend, config.workspace_path)
+ if appendmd5 and splitentry[2] == appendmd5:
+ splitentry[2] = newappendmd5
+ elif splitentry[1] == os.path.relpath(recipefile, config.workspace_path):
+ splitentry[1] = os.path.relpath(newfile, config.workspace_path)
+ if recipefilemd5 and splitentry[2] == recipefilemd5:
+ splitentry[2] = newrecipefilemd5
+ elif relbpndir and splitentry[1].startswith(relbpndir):
+ splitentry[1] = os.path.relpath(os.path.join(newbpndir, splitentry[1][len(relbpndir):]), config.workspace_path)
+ elif relbpdir and splitentry[1].startswith(relbpdir):
+ splitentry[1] = os.path.relpath(os.path.join(newbpdir, splitentry[1][len(relbpdir):]), config.workspace_path)
+ entry = '|'.join(splitentry) + '\n'
+ f.write(entry)
return 0
-def _get_patchset_revs(args, srctree, recipe_path):
+
+def _get_patchset_revs(srctree, recipe_path, initial_rev=None, force_patch_refresh=False):
"""Get initial and update rev of a recipe. These are the start point of the
whole patchset and start point for the patches to be re-generated/updated.
"""
import bb
- if args.initial_rev:
- return args.initial_rev, args.initial_rev
+ # Get current branch
+ stdout, _ = bb.process.run('git rev-parse --abbrev-ref HEAD',
+ cwd=srctree)
+ branchname = stdout.rstrip()
- # Parse initial rev from recipe
+ # Parse initial rev from recipe if not specified
commits = []
- initial_rev = None
+ patches = []
with open(recipe_path, 'r') as f:
for line in f:
if line.startswith('# initial_rev:'):
- initial_rev = line.split(':')[-1].strip()
- elif line.startswith('# commit:'):
+ if not initial_rev:
+ initial_rev = line.split(':')[-1].strip()
+ elif line.startswith('# commit:') and not force_patch_refresh:
commits.append(line.split(':')[-1].strip())
+ elif line.startswith('# patches_%s:' % branchname):
+ patches = line.split(':')[-1].strip().split(',')
update_rev = initial_rev
+ changed_revs = None
if initial_rev:
# Find first actually changed revision
stdout, _ = bb.process.run('git rev-list --reverse %s..HEAD' %
initial_rev, cwd=srctree)
newcommits = stdout.split()
- for i in xrange(min(len(commits), len(newcommits))):
+ for i in range(min(len(commits), len(newcommits))):
if newcommits[i] == commits[i]:
update_rev = commits[i]
- return initial_rev, update_rev
+ try:
+ stdout, _ = bb.process.run('git cherry devtool-patched',
+ cwd=srctree)
+ except bb.process.ExecutionError as err:
+ stdout = None
+
+ if stdout is not None and not force_patch_refresh:
+ changed_revs = []
+ for line in stdout.splitlines():
+ if line.startswith('+ '):
+ rev = line.split()[1]
+ if rev in newcommits:
+ changed_revs.append(rev)
-def _remove_patch_entries(srcuri, patchlist):
- """Remove patch entries from SRC_URI"""
- remaining = patchlist[:]
+ return initial_rev, update_rev, changed_revs, patches
+
+def _remove_file_entries(srcuri, filelist):
+ """Remove file:// entries from SRC_URI"""
+ remaining = filelist[:]
entries = []
- for patch in patchlist:
- patchfile = os.path.basename(patch)
- for i in xrange(len(srcuri)):
- if srcuri[i].startswith('file://') and os.path.basename(srcuri[i].split(';')[0]) == patchfile:
+ for fname in filelist:
+ basename = os.path.basename(fname)
+ for i in range(len(srcuri)):
+ if (srcuri[i].startswith('file://') and
+ os.path.basename(srcuri[i].split(';')[0]) == basename):
entries.append(srcuri[i])
- remaining.remove(patch)
+ remaining.remove(fname)
srcuri.pop(i)
break
return entries, remaining
-def _remove_patch_files(args, patches, destpath):
+def _replace_srcuri_entry(srcuri, filename, newentry):
+ """Replace entry corresponding to specified file with a new entry"""
+ basename = os.path.basename(filename)
+ for i in range(len(srcuri)):
+ if os.path.basename(srcuri[i].split(';')[0]) == basename:
+ srcuri.pop(i)
+ srcuri.insert(i, newentry)
+ break
+
+def _remove_source_files(append, files, destpath, no_report_remove=False, dry_run=False):
"""Unlink existing patch files"""
- for patchfile in patches:
- if args.append:
+
+ dry_run_suffix = ' (dry-run)' if dry_run else ''
+
+ for path in files:
+ if append:
if not destpath:
raise Exception('destpath should be set here')
- patchfile = os.path.join(destpath, os.path.basename(patchfile))
-
- if os.path.exists(patchfile):
- logger.info('Removing patch %s' % patchfile)
- # FIXME "git rm" here would be nice if the file in question is
- # tracked
- # FIXME there's a chance that this file is referred to by
- # another recipe, in which case deleting wouldn't be the
- # right thing to do
- os.remove(patchfile)
- # Remove directory if empty
- try:
- os.rmdir(os.path.dirname(patchfile))
- except OSError as ose:
- if ose.errno != errno.ENOTEMPTY:
- raise
-
-def _update_recipe_srcrev(args, srctree, rd, config_data):
+ path = os.path.join(destpath, os.path.basename(path))
+
+ if os.path.exists(path):
+ if not no_report_remove:
+ logger.info('Removing file %s%s' % (path, dry_run_suffix))
+ if not dry_run:
+ # FIXME "git rm" here would be nice if the file in question is
+ # tracked
+ # FIXME there's a chance that this file is referred to by
+ # another recipe, in which case deleting wouldn't be the
+ # right thing to do
+ os.remove(path)
+ # Remove directory if empty
+ try:
+ os.rmdir(os.path.dirname(path))
+ except OSError as ose:
+ if ose.errno != errno.ENOTEMPTY:
+ raise
+
+
+def _export_patches(srctree, rd, start_rev, destdir, changed_revs=None):
+ """Export patches from srctree to given location.
+ Returns three-tuple of dicts:
+ 1. updated - patches that already exist in SRCURI
+ 2. added - new patches that don't exist in SRCURI
+ 3 removed - patches that exist in SRCURI but not in exported patches
+ In each dict the key is the 'basepath' of the URI and value is the
+ absolute path to the existing file in recipe space (if any).
+ """
+ import oe.recipeutils
+ from oe.patch import GitApplyTree
+ updated = OrderedDict()
+ added = OrderedDict()
+ seqpatch_re = re.compile('^([0-9]{4}-)?(.+)')
+
+ existing_patches = dict((os.path.basename(path), path) for path in
+ oe.recipeutils.get_recipe_patches(rd))
+ logger.debug('Existing patches: %s' % existing_patches)
+
+ # Generate patches from Git, exclude local files directory
+ patch_pathspec = _git_exclude_path(srctree, 'oe-local-files')
+ GitApplyTree.extractPatches(srctree, start_rev, destdir, patch_pathspec)
+
+ new_patches = sorted(os.listdir(destdir))
+ for new_patch in new_patches:
+ # Strip numbering from patch names. If it's a git sequence named patch,
+ # the numbers might not match up since we are starting from a different
+ # revision This does assume that people are using unique shortlog
+ # values, but they ought to be anyway...
+ new_basename = seqpatch_re.match(new_patch).group(2)
+ match_name = None
+ for old_patch in existing_patches:
+ old_basename = seqpatch_re.match(old_patch).group(2)
+ old_basename_splitext = os.path.splitext(old_basename)
+ if old_basename.endswith(('.gz', '.bz2', '.Z')) and old_basename_splitext[0] == new_basename:
+ old_patch_noext = os.path.splitext(old_patch)[0]
+ match_name = old_patch_noext
+ break
+ elif new_basename == old_basename:
+ match_name = old_patch
+ break
+ if match_name:
+ # Rename patch files
+ if new_patch != match_name:
+ bb.utils.rename(os.path.join(destdir, new_patch),
+ os.path.join(destdir, match_name))
+ # Need to pop it off the list now before checking changed_revs
+ oldpath = existing_patches.pop(old_patch)
+ if changed_revs is not None:
+ # Avoid updating patches that have not actually changed
+ with open(os.path.join(destdir, match_name), 'r') as f:
+ firstlineitems = f.readline().split()
+ # Looking for "From <hash>" line
+ if len(firstlineitems) > 1 and len(firstlineitems[1]) == 40:
+ if not firstlineitems[1] in changed_revs:
+ continue
+ # Recompress if necessary
+ if oldpath.endswith(('.gz', '.Z')):
+ bb.process.run(['gzip', match_name], cwd=destdir)
+ if oldpath.endswith('.gz'):
+ match_name += '.gz'
+ else:
+ match_name += '.Z'
+ elif oldpath.endswith('.bz2'):
+ bb.process.run(['bzip2', match_name], cwd=destdir)
+ match_name += '.bz2'
+ updated[match_name] = oldpath
+ else:
+ added[new_patch] = None
+ return (updated, added, existing_patches)
+
+
+def _create_kconfig_diff(srctree, rd, outfile):
+ """Create a kconfig fragment"""
+ # Only update config fragment if both config files exist
+ orig_config = os.path.join(srctree, '.config.baseline')
+ new_config = os.path.join(srctree, '.config.new')
+ if os.path.exists(orig_config) and os.path.exists(new_config):
+ cmd = ['diff', '--new-line-format=%L', '--old-line-format=',
+ '--unchanged-line-format=', orig_config, new_config]
+ pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+ stdout, stderr = pipe.communicate()
+ if pipe.returncode == 1:
+ logger.info("Updating config fragment %s" % outfile)
+ with open(outfile, 'wb') as fobj:
+ fobj.write(stdout)
+ elif pipe.returncode == 0:
+ logger.info("Would remove config fragment %s" % outfile)
+ if os.path.exists(outfile):
+ # Remove fragment file in case of empty diff
+ logger.info("Removing config fragment %s" % outfile)
+ os.unlink(outfile)
+ else:
+ raise bb.process.ExecutionError(cmd, pipe.returncode, stdout, stderr)
+ return True
+ return False
+
+
+def _export_local_files(srctree, rd, destdir, srctreebase):
+ """Copy local files from srctree to given location.
+ Returns three-tuple of dicts:
+ 1. updated - files that already exist in SRCURI
+ 2. added - new files files that don't exist in SRCURI
+ 3 removed - files that exist in SRCURI but not in exported files
+ In each dict the key is the 'basepath' of the URI and value is the
+ absolute path to the existing file in recipe space (if any).
+ """
+ import oe.recipeutils
+
+ # Find out local files (SRC_URI files that exist in the "recipe space").
+ # Local files that reside in srctree are not included in patch generation.
+ # Instead they are directly copied over the original source files (in
+ # recipe space).
+ existing_files = oe.recipeutils.get_recipe_local_files(rd)
+ new_set = None
+ updated = OrderedDict()
+ added = OrderedDict()
+ removed = OrderedDict()
+ local_files_dir = os.path.join(srctreebase, 'oe-local-files')
+ git_files = _git_ls_tree(srctree)
+ if 'oe-local-files' in git_files:
+ # If tracked by Git, take the files from srctree HEAD. First get
+ # the tree object of the directory
+ tmp_index = os.path.join(srctree, '.git', 'index.tmp.devtool')
+ tree = git_files['oe-local-files'][2]
+ bb.process.run(['git', 'checkout', tree, '--', '.'], cwd=srctree,
+ env=dict(os.environ, GIT_WORK_TREE=destdir,
+ GIT_INDEX_FILE=tmp_index))
+ new_set = list(_git_ls_tree(srctree, tree, True).keys())
+ elif os.path.isdir(local_files_dir):
+ # If not tracked by Git, just copy from working copy
+ new_set = _ls_tree(local_files_dir)
+ bb.process.run(['cp', '-ax',
+ os.path.join(local_files_dir, '.'), destdir])
+ else:
+ new_set = []
+
+ # Special handling for kernel config
+ if bb.data.inherits_class('kernel-yocto', rd):
+ fragment_fn = 'devtool-fragment.cfg'
+ fragment_path = os.path.join(destdir, fragment_fn)
+ if _create_kconfig_diff(srctree, rd, fragment_path):
+ if os.path.exists(fragment_path):
+ if fragment_fn not in new_set:
+ new_set.append(fragment_fn)
+ # Copy fragment to local-files
+ if os.path.isdir(local_files_dir):
+ shutil.copy2(fragment_path, local_files_dir)
+ else:
+ if fragment_fn in new_set:
+ new_set.remove(fragment_fn)
+ # Remove fragment from local-files
+ if os.path.exists(os.path.join(local_files_dir, fragment_fn)):
+ os.unlink(os.path.join(local_files_dir, fragment_fn))
+
+ # Special handling for cml1, ccmake, etc bbclasses that generated
+ # configuration fragment files that are consumed as source files
+ for frag_class, frag_name in [("cml1", "fragment.cfg"), ("ccmake", "site-file.cmake")]:
+ if bb.data.inherits_class(frag_class, rd):
+ srcpath = os.path.join(rd.getVar('WORKDIR'), frag_name)
+ if os.path.exists(srcpath):
+ if frag_name not in new_set:
+ new_set.append(frag_name)
+ # copy fragment into destdir
+ shutil.copy2(srcpath, destdir)
+ # copy fragment into local files if exists
+ if os.path.isdir(local_files_dir):
+ shutil.copy2(srcpath, local_files_dir)
+
+ if new_set is not None:
+ for fname in new_set:
+ if fname in existing_files:
+ origpath = existing_files.pop(fname)
+ workpath = os.path.join(local_files_dir, fname)
+ if not filecmp.cmp(origpath, workpath):
+ updated[fname] = origpath
+ elif fname != '.gitignore':
+ added[fname] = None
+
+ workdir = rd.getVar('WORKDIR')
+ s = rd.getVar('S')
+ if not s.endswith(os.sep):
+ s += os.sep
+
+ if workdir != s:
+ # Handle files where subdir= was specified
+ for fname in list(existing_files.keys()):
+ # FIXME handle both subdir starting with BP and not?
+ fworkpath = os.path.join(workdir, fname)
+ if fworkpath.startswith(s):
+ fpath = os.path.join(srctree, os.path.relpath(fworkpath, s))
+ if os.path.exists(fpath):
+ origpath = existing_files.pop(fname)
+ if not filecmp.cmp(origpath, fpath):
+ updated[fpath] = origpath
+
+ removed = existing_files
+ return (updated, added, removed)
+
+
+def _determine_files_dir(rd):
+ """Determine the appropriate files directory for a recipe"""
+ recipedir = rd.getVar('FILE_DIRNAME')
+ for entry in rd.getVar('FILESPATH').split(':'):
+ relpth = os.path.relpath(entry, recipedir)
+ if not os.sep in relpth:
+ # One (or zero) levels below only, so we don't put anything in machine-specific directories
+ if os.path.isdir(entry):
+ return entry
+ return os.path.join(recipedir, rd.getVar('BPN'))
+
+
+def _update_recipe_srcrev(recipename, workspace, srctree, rd, appendlayerdir, wildcard_version, no_remove, no_report_remove, dry_run_outdir=None):
"""Implement the 'srcrev' mode of update-recipe"""
import bb
import oe.recipeutils
- from oe.patch import GitApplyTree
- recipefile = rd.getVar('FILE', True)
- logger.info('Updating SRCREV in recipe %s' % os.path.basename(recipefile))
+ dry_run_suffix = ' (dry-run)' if dry_run_outdir else ''
+
+ recipefile = rd.getVar('FILE')
+ recipedir = os.path.basename(recipefile)
+ logger.info('Updating SRCREV in recipe %s%s' % (recipedir, dry_run_suffix))
# Get HEAD revision
try:
@@ -593,164 +1520,314 @@ def _update_recipe_srcrev(args, srctree, rd, config_data):
raise DevtoolError('Invalid hash returned by git: %s' % stdout)
destpath = None
- removepatches = []
+ remove_files = []
patchfields = {}
patchfields['SRCREV'] = srcrev
orig_src_uri = rd.getVar('SRC_URI', False) or ''
- if not args.no_remove:
- # Find list of existing patches in recipe file
- existing_patches = oe.recipeutils.get_recipe_patches(rd)
-
- old_srcrev = (rd.getVar('SRCREV', False) or '')
- tempdir = tempfile.mkdtemp(prefix='devtool')
- try:
- GitApplyTree.extractPatches(srctree, old_srcrev, tempdir)
- newpatches = os.listdir(tempdir)
- for patch in existing_patches:
- patchfile = os.path.basename(patch)
- if patchfile in newpatches:
- removepatches.append(patch)
- finally:
- shutil.rmtree(tempdir)
-
- if removepatches:
- srcuri = orig_src_uri.split()
- removedentries, _ = _remove_patch_entries(srcuri, removepatches)
- if removedentries:
+ srcuri = orig_src_uri.split()
+ tempdir = tempfile.mkdtemp(prefix='devtool')
+ update_srcuri = False
+ appendfile = None
+ try:
+ local_files_dir = tempfile.mkdtemp(dir=tempdir)
+ srctreebase = workspace[recipename]['srctreebase']
+ upd_f, new_f, del_f = _export_local_files(srctree, rd, local_files_dir, srctreebase)
+ if not no_remove:
+ # Find list of existing patches in recipe file
+ patches_dir = tempfile.mkdtemp(dir=tempdir)
+ old_srcrev = rd.getVar('SRCREV') or ''
+ upd_p, new_p, del_p = _export_patches(srctree, rd, old_srcrev,
+ patches_dir)
+ logger.debug('Patches: update %s, new %s, delete %s' % (dict(upd_p), dict(new_p), dict(del_p)))
+
+ # Remove deleted local files and "overlapping" patches
+ remove_files = list(del_f.values()) + list(upd_p.values()) + list(del_p.values())
+ if remove_files:
+ removedentries = _remove_file_entries(srcuri, remove_files)[0]
+ update_srcuri = True
+
+ if appendlayerdir:
+ files = dict((os.path.join(local_files_dir, key), val) for
+ key, val in list(upd_f.items()) + list(new_f.items()))
+ removevalues = {}
+ if update_srcuri:
+ removevalues = {'SRC_URI': removedentries}
+ patchfields['SRC_URI'] = '\\\n '.join(srcuri)
+ if dry_run_outdir:
+ logger.info('Creating bbappend (dry-run)')
+ else:
+ appendfile, destpath = oe.recipeutils.bbappend_recipe(
+ rd, appendlayerdir, files, wildcardver=wildcard_version,
+ extralines=patchfields, removevalues=removevalues,
+ redirect_output=dry_run_outdir)
+ else:
+ files_dir = _determine_files_dir(rd)
+ for basepath, path in upd_f.items():
+ logger.info('Updating file %s%s' % (basepath, dry_run_suffix))
+ if os.path.isabs(basepath):
+ # Original file (probably with subdir pointing inside source tree)
+ # so we do not want to move it, just copy
+ _copy_file(basepath, path, dry_run_outdir=dry_run_outdir, base_outdir=recipedir)
+ else:
+ _move_file(os.path.join(local_files_dir, basepath), path,
+ dry_run_outdir=dry_run_outdir, base_outdir=recipedir)
+ update_srcuri= True
+ for basepath, path in new_f.items():
+ logger.info('Adding new file %s%s' % (basepath, dry_run_suffix))
+ _move_file(os.path.join(local_files_dir, basepath),
+ os.path.join(files_dir, basepath),
+ dry_run_outdir=dry_run_outdir,
+ base_outdir=recipedir)
+ srcuri.append('file://%s' % basepath)
+ update_srcuri = True
+ if update_srcuri:
patchfields['SRC_URI'] = ' '.join(srcuri)
-
- if args.append:
- _, destpath = oe.recipeutils.bbappend_recipe(
- rd, args.append, None, wildcardver=args.wildcard_version,
- extralines=patchfields)
- else:
- oe.recipeutils.patch_recipe(rd, recipefile, patchfields)
-
+ ret = oe.recipeutils.patch_recipe(rd, recipefile, patchfields, redirect_output=dry_run_outdir)
+ finally:
+ shutil.rmtree(tempdir)
if not 'git://' in orig_src_uri:
logger.info('You will need to update SRC_URI within the recipe to '
'point to a git repository where you have pushed your '
'changes')
- _remove_patch_files(args, removepatches, destpath)
+ _remove_source_files(appendlayerdir, remove_files, destpath, no_report_remove, dry_run=dry_run_outdir)
+ return True, appendfile, remove_files
-def _update_recipe_patch(args, config, srctree, rd, config_data):
+def _update_recipe_patch(recipename, workspace, srctree, rd, appendlayerdir, wildcard_version, no_remove, no_report_remove, initial_rev, dry_run_outdir=None, force_patch_refresh=False):
"""Implement the 'patch' mode of update-recipe"""
import bb
import oe.recipeutils
- from oe.patch import GitApplyTree
- recipefile = rd.getVar('FILE', True)
- append = os.path.join(config.workspace_path, 'appends', '%s.bbappend' %
- os.path.splitext(os.path.basename(recipefile))[0])
+ recipefile = rd.getVar('FILE')
+ recipedir = os.path.dirname(recipefile)
+ append = workspace[recipename]['bbappend']
if not os.path.exists(append):
raise DevtoolError('unable to find workspace bbappend for recipe %s' %
- args.recipename)
+ recipename)
- initial_rev, update_rev = _get_patchset_revs(args, srctree, append)
+ initial_rev, update_rev, changed_revs, filter_patches = _get_patchset_revs(srctree, append, initial_rev, force_patch_refresh)
if not initial_rev:
raise DevtoolError('Unable to find initial revision - please specify '
'it with --initial-rev')
- # Find list of existing patches in recipe file
- existing_patches = oe.recipeutils.get_recipe_patches(rd)
+ appendfile = None
+ dl_dir = rd.getVar('DL_DIR')
+ if not dl_dir.endswith('/'):
+ dl_dir += '/'
- removepatches = []
- seqpatch_re = re.compile('^([0-9]{4}-)?(.+)')
- if not args.no_remove:
- # Get all patches from source tree and check if any should be removed
- tempdir = tempfile.mkdtemp(prefix='devtool')
- try:
- GitApplyTree.extractPatches(srctree, initial_rev, tempdir)
- # Strip numbering from patch names. If it's a git sequence named
- # patch, the numbers might not match up since we are starting from
- # a different revision This does assume that people are using
- # unique shortlog values, but they ought to be anyway...
- newpatches = [seqpatch_re.match(fname).group(2) for fname in
- os.listdir(tempdir)]
- for patch in existing_patches:
- basename = seqpatch_re.match(
- os.path.basename(patch)).group(2)
- if basename not in newpatches:
- removepatches.append(patch)
- finally:
- shutil.rmtree(tempdir)
+ dry_run_suffix = ' (dry-run)' if dry_run_outdir else ''
- # Get updated patches from source tree
tempdir = tempfile.mkdtemp(prefix='devtool')
try:
- GitApplyTree.extractPatches(srctree, update_rev, tempdir)
-
- # Match up and replace existing patches with corresponding new patches
- updatepatches = False
+ local_files_dir = tempfile.mkdtemp(dir=tempdir)
+ if filter_patches:
+ upd_f = {}
+ new_f = {}
+ del_f = {}
+ else:
+ srctreebase = workspace[recipename]['srctreebase']
+ upd_f, new_f, del_f = _export_local_files(srctree, rd, local_files_dir, srctreebase)
+
+ remove_files = []
+ if not no_remove:
+ # Get all patches from source tree and check if any should be removed
+ all_patches_dir = tempfile.mkdtemp(dir=tempdir)
+ _, _, del_p = _export_patches(srctree, rd, initial_rev,
+ all_patches_dir)
+ # Remove deleted local files and patches
+ remove_files = list(del_f.values()) + list(del_p.values())
+
+ # Get updated patches from source tree
+ patches_dir = tempfile.mkdtemp(dir=tempdir)
+ upd_p, new_p, _ = _export_patches(srctree, rd, update_rev,
+ patches_dir, changed_revs)
+ logger.debug('Pre-filtering: update: %s, new: %s' % (dict(upd_p), dict(new_p)))
+ if filter_patches:
+ new_p = OrderedDict()
+ upd_p = OrderedDict((k,v) for k,v in upd_p.items() if k in filter_patches)
+ remove_files = [f for f in remove_files if f in filter_patches]
+ updatefiles = False
updaterecipe = False
destpath = None
- newpatches = os.listdir(tempdir)
- if args.append:
- patchfiles = {}
- for patch in existing_patches:
- patchfile = os.path.basename(patch)
- if patchfile in newpatches:
- patchfiles[os.path.join(tempdir, patchfile)] = patchfile
- newpatches.remove(patchfile)
- for patchfile in newpatches:
- patchfiles[os.path.join(tempdir, patchfile)] = None
-
- if patchfiles or removepatches:
+ srcuri = (rd.getVar('SRC_URI', False) or '').split()
+ if appendlayerdir:
+ files = OrderedDict((os.path.join(local_files_dir, key), val) for
+ key, val in list(upd_f.items()) + list(new_f.items()))
+ files.update(OrderedDict((os.path.join(patches_dir, key), val) for
+ key, val in list(upd_p.items()) + list(new_p.items())))
+ if files or remove_files:
removevalues = None
- if removepatches:
- srcuri = (rd.getVar('SRC_URI', False) or '').split()
- removedentries, remaining = _remove_patch_entries(
- srcuri, removepatches)
+ if remove_files:
+ removedentries, remaining = _remove_file_entries(
+ srcuri, remove_files)
if removedentries or remaining:
remaining = ['file://' + os.path.basename(item) for
item in remaining]
removevalues = {'SRC_URI': removedentries + remaining}
- _, destpath = oe.recipeutils.bbappend_recipe(
- rd, args.append, patchfiles,
- removevalues=removevalues)
+ appendfile, destpath = oe.recipeutils.bbappend_recipe(
+ rd, appendlayerdir, files,
+ wildcardver=wildcard_version,
+ removevalues=removevalues,
+ redirect_output=dry_run_outdir)
else:
- logger.info('No patches needed updating')
+ logger.info('No patches or local source files needed updating')
else:
- for patch in existing_patches:
- patchfile = os.path.basename(patch)
- if patchfile in newpatches:
- logger.info('Updating patch %s' % patchfile)
- shutil.move(os.path.join(tempdir, patchfile), patch)
- newpatches.remove(patchfile)
- updatepatches = True
- srcuri = (rd.getVar('SRC_URI', False) or '').split()
- if newpatches:
- # Add any patches left over
- patchdir = os.path.join(os.path.dirname(recipefile),
- rd.getVar('BPN', True))
- bb.utils.mkdirhier(patchdir)
- for patchfile in newpatches:
- logger.info('Adding new patch %s' % patchfile)
- shutil.move(os.path.join(tempdir, patchfile),
- os.path.join(patchdir, patchfile))
- srcuri.append('file://%s' % patchfile)
- updaterecipe = True
- if removepatches:
- removedentries, _ = _remove_patch_entries(srcuri, removepatches)
- if removedentries:
+ # Update existing files
+ files_dir = _determine_files_dir(rd)
+ for basepath, path in upd_f.items():
+ logger.info('Updating file %s' % basepath)
+ if os.path.isabs(basepath):
+ # Original file (probably with subdir pointing inside source tree)
+ # so we do not want to move it, just copy
+ _copy_file(basepath, path,
+ dry_run_outdir=dry_run_outdir, base_outdir=recipedir)
+ else:
+ _move_file(os.path.join(local_files_dir, basepath), path,
+ dry_run_outdir=dry_run_outdir, base_outdir=recipedir)
+ updatefiles = True
+ for basepath, path in upd_p.items():
+ patchfn = os.path.join(patches_dir, basepath)
+ if os.path.dirname(path) + '/' == dl_dir:
+ # This is a a downloaded patch file - we now need to
+ # replace the entry in SRC_URI with our local version
+ logger.info('Replacing remote patch %s with updated local version' % basepath)
+ path = os.path.join(files_dir, basepath)
+ _replace_srcuri_entry(srcuri, basepath, 'file://%s' % basepath)
updaterecipe = True
+ else:
+ logger.info('Updating patch %s%s' % (basepath, dry_run_suffix))
+ _move_file(patchfn, path,
+ dry_run_outdir=dry_run_outdir, base_outdir=recipedir)
+ updatefiles = True
+ # Add any new files
+ for basepath, path in new_f.items():
+ logger.info('Adding new file %s%s' % (basepath, dry_run_suffix))
+ _move_file(os.path.join(local_files_dir, basepath),
+ os.path.join(files_dir, basepath),
+ dry_run_outdir=dry_run_outdir,
+ base_outdir=recipedir)
+ srcuri.append('file://%s' % basepath)
+ updaterecipe = True
+ for basepath, path in new_p.items():
+ logger.info('Adding new patch %s%s' % (basepath, dry_run_suffix))
+ _move_file(os.path.join(patches_dir, basepath),
+ os.path.join(files_dir, basepath),
+ dry_run_outdir=dry_run_outdir,
+ base_outdir=recipedir)
+ srcuri.append('file://%s' % basepath)
+ updaterecipe = True
+ # Update recipe, if needed
+ if _remove_file_entries(srcuri, remove_files)[0]:
+ updaterecipe = True
if updaterecipe:
- logger.info('Updating recipe %s' % os.path.basename(recipefile))
- oe.recipeutils.patch_recipe(rd, recipefile,
- {'SRC_URI': ' '.join(srcuri)})
- elif not updatepatches:
+ if not dry_run_outdir:
+ logger.info('Updating recipe %s' % os.path.basename(recipefile))
+ ret = oe.recipeutils.patch_recipe(rd, recipefile,
+ {'SRC_URI': ' '.join(srcuri)},
+ redirect_output=dry_run_outdir)
+ elif not updatefiles:
# Neither patches nor recipe were updated
- logger.info('No patches need updating')
+ logger.info('No patches or files need updating')
+ return False, None, []
finally:
shutil.rmtree(tempdir)
- _remove_patch_files(args, removepatches, destpath)
+ _remove_source_files(appendlayerdir, remove_files, destpath, no_report_remove, dry_run=dry_run_outdir)
+ return True, appendfile, remove_files
+
+def _guess_recipe_update_mode(srctree, rdata):
+ """Guess the recipe update mode to use"""
+ src_uri = (rdata.getVar('SRC_URI') or '').split()
+ git_uris = [uri for uri in src_uri if uri.startswith('git://')]
+ if not git_uris:
+ return 'patch'
+ # Just use the first URI for now
+ uri = git_uris[0]
+ # Check remote branch
+ params = bb.fetch.decodeurl(uri)[5]
+ upstr_branch = params['branch'] if 'branch' in params else 'master'
+ # Check if current branch HEAD is found in upstream branch
+ stdout, _ = bb.process.run('git rev-parse HEAD', cwd=srctree)
+ head_rev = stdout.rstrip()
+ stdout, _ = bb.process.run('git branch -r --contains %s' % head_rev,
+ cwd=srctree)
+ remote_brs = [branch.strip() for branch in stdout.splitlines()]
+ if 'origin/' + upstr_branch in remote_brs:
+ return 'srcrev'
+
+ return 'patch'
+
+def _update_recipe(recipename, workspace, rd, mode, appendlayerdir, wildcard_version, no_remove, initial_rev, no_report_remove=False, dry_run_outdir=None, no_overrides=False, force_patch_refresh=False):
+ srctree = workspace[recipename]['srctree']
+ if mode == 'auto':
+ mode = _guess_recipe_update_mode(srctree, rd)
+
+ override_branches = []
+ mainbranch = None
+ startbranch = None
+ if not no_overrides:
+ stdout, _ = bb.process.run('git branch', cwd=srctree)
+ other_branches = []
+ for line in stdout.splitlines():
+ branchname = line[2:]
+ if line.startswith('* '):
+ startbranch = branchname
+ if branchname.startswith(override_branch_prefix):
+ override_branches.append(branchname)
+ else:
+ other_branches.append(branchname)
+
+ if override_branches:
+ logger.debug('_update_recipe: override branches: %s' % override_branches)
+ logger.debug('_update_recipe: other branches: %s' % other_branches)
+ if startbranch.startswith(override_branch_prefix):
+ if len(other_branches) == 1:
+ mainbranch = other_branches[1]
+ else:
+ raise DevtoolError('Unable to determine main branch - please check out the main branch in source tree first')
+ else:
+ mainbranch = startbranch
+
+ checkedout = None
+ anyupdated = False
+ appendfile = None
+ allremoved = []
+ if override_branches:
+ logger.info('Handling main branch (%s)...' % mainbranch)
+ if startbranch != mainbranch:
+ bb.process.run('git checkout %s' % mainbranch, cwd=srctree)
+ checkedout = mainbranch
+ try:
+ branchlist = [mainbranch] + override_branches
+ for branch in branchlist:
+ crd = bb.data.createCopy(rd)
+ if branch != mainbranch:
+ logger.info('Handling branch %s...' % branch)
+ override = branch[len(override_branch_prefix):]
+ crd.appendVar('OVERRIDES', ':%s' % override)
+ bb.process.run('git checkout %s' % branch, cwd=srctree)
+ checkedout = branch
+
+ if mode == 'srcrev':
+ updated, appendf, removed = _update_recipe_srcrev(recipename, workspace, srctree, crd, appendlayerdir, wildcard_version, no_remove, no_report_remove, dry_run_outdir)
+ elif mode == 'patch':
+ updated, appendf, removed = _update_recipe_patch(recipename, workspace, srctree, crd, appendlayerdir, wildcard_version, no_remove, no_report_remove, initial_rev, dry_run_outdir, force_patch_refresh)
+ else:
+ raise DevtoolError('update_recipe: invalid mode %s' % mode)
+ if updated:
+ anyupdated = True
+ if appendf:
+ appendfile = appendf
+ allremoved.extend(removed)
+ finally:
+ if startbranch and checkedout != startbranch:
+ bb.process.run('git checkout %s' % startbranch, cwd=srctree)
+
+ return anyupdated, appendfile, allremoved
def update_recipe(args, config, basepath, workspace):
"""Entry point for the devtool 'update-recipe' subcommand"""
- if not args.recipename in workspace:
- raise DevtoolError("no recipe named %s in your workspace" %
- args.recipename)
+ check_workspace_recipe(workspace, args.recipename)
if args.append:
if not os.path.exists(args.append):
@@ -760,29 +1837,26 @@ def update_recipe(args, config, basepath, workspace):
raise DevtoolError('conf/layer.conf not found in bbappend '
'destination layer "%s"' % args.append)
- tinfoil = setup_tinfoil()
-
- rd = parse_recipe(config, tinfoil, args.recipename, True)
- if not rd:
- return 1
-
- orig_src_uri = rd.getVar('SRC_URI', False) or ''
- if args.mode == 'auto':
- if 'git://' in orig_src_uri:
- mode = 'srcrev'
- else:
- mode = 'patch'
- else:
- mode = args.mode
+ tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
+ try:
- srctree = workspace[args.recipename]['srctree']
+ rd = parse_recipe(config, tinfoil, args.recipename, True)
+ if not rd:
+ return 1
- if mode == 'srcrev':
- _update_recipe_srcrev(args, srctree, rd, tinfoil.config_data)
- elif mode == 'patch':
- _update_recipe_patch(args, config, srctree, rd, tinfoil.config_data)
- else:
- raise DevtoolError('update_recipe: invalid mode %s' % mode)
+ dry_run_output = None
+ dry_run_outdir = None
+ if args.dry_run:
+ dry_run_output = tempfile.TemporaryDirectory(prefix='devtool')
+ dry_run_outdir = dry_run_output.name
+ updated, _, _ = _update_recipe(args.recipename, workspace, rd, args.mode, args.append, args.wildcard_version, args.no_remove, args.initial_rev, dry_run_outdir=dry_run_outdir, no_overrides=args.no_overrides, force_patch_refresh=args.force_patch_refresh)
+
+ if updated:
+ rf = rd.getVar('FILE')
+ if rf.startswith(config.workspace_path):
+ logger.warning('Recipe file %s has been updated but is inside the workspace - you will need to move it (and any associated files next to it) out to the desired layer before using "devtool reset" in order to keep any changes' % rf)
+ finally:
+ tinfoil.shutdown()
return 0
@@ -790,133 +1864,462 @@ def update_recipe(args, config, basepath, workspace):
def status(args, config, basepath, workspace):
"""Entry point for the devtool 'status' subcommand"""
if workspace:
- for recipe, value in workspace.iteritems():
- print("%s: %s" % (recipe, value['srctree']))
+ for recipe, value in sorted(workspace.items()):
+ recipefile = value['recipefile']
+ if recipefile:
+ recipestr = ' (%s)' % recipefile
+ else:
+ recipestr = ''
+ print("%s: %s%s" % (recipe, value['srctree'], recipestr))
else:
logger.info('No recipes currently in your workspace - you can use "devtool modify" to work on an existing recipe or "devtool add" to add a new one')
return 0
+def _reset(recipes, no_clean, remove_work, config, basepath, workspace):
+ """Reset one or more recipes"""
+ import oe.path
+
+ def clean_preferred_provider(pn, layerconf_path):
+ """Remove PREFERRED_PROVIDER from layer.conf'"""
+ import re
+ layerconf_file = os.path.join(layerconf_path, 'conf', 'layer.conf')
+ new_layerconf_file = os.path.join(layerconf_path, 'conf', '.layer.conf')
+ pprovider_found = False
+ with open(layerconf_file, 'r') as f:
+ lines = f.readlines()
+ with open(new_layerconf_file, 'a') as nf:
+ for line in lines:
+ pprovider_exp = r'^PREFERRED_PROVIDER_.*? = "' + pn + r'"$'
+ if not re.match(pprovider_exp, line):
+ nf.write(line)
+ else:
+ pprovider_found = True
+ if pprovider_found:
+ shutil.move(new_layerconf_file, layerconf_file)
+ else:
+ os.remove(new_layerconf_file)
+
+ if recipes and not no_clean:
+ if len(recipes) == 1:
+ logger.info('Cleaning sysroot for recipe %s...' % recipes[0])
+ else:
+ logger.info('Cleaning sysroot for recipes %s...' % ', '.join(recipes))
+ # If the recipe file itself was created in the workspace, and
+ # it uses BBCLASSEXTEND, then we need to also clean the other
+ # variants
+ targets = []
+ for recipe in recipes:
+ targets.append(recipe)
+ recipefile = workspace[recipe]['recipefile']
+ if recipefile and os.path.exists(recipefile):
+ targets.extend(get_bbclassextend_targets(recipefile, recipe))
+ try:
+ exec_build_env_command(config.init_path, basepath, 'bitbake -c clean %s' % ' '.join(targets))
+ except bb.process.ExecutionError as e:
+ raise DevtoolError('Command \'%s\' failed, output:\n%s\nIf you '
+ 'wish, you may specify -n/--no-clean to '
+ 'skip running this command when resetting' %
+ (e.command, e.stdout))
+
+ for pn in recipes:
+ _check_preserve(config, pn)
+
+ appendfile = workspace[pn]['bbappend']
+ if os.path.exists(appendfile):
+ # This shouldn't happen, but is possible if devtool errored out prior to
+ # writing the md5 file. We need to delete this here or the recipe won't
+ # actually be reset
+ os.remove(appendfile)
+
+ preservepath = os.path.join(config.workspace_path, 'attic', pn, pn)
+ def preservedir(origdir):
+ if os.path.exists(origdir):
+ for root, dirs, files in os.walk(origdir):
+ for fn in files:
+ logger.warning('Preserving %s in %s' % (fn, preservepath))
+ _move_file(os.path.join(origdir, fn),
+ os.path.join(preservepath, fn))
+ for dn in dirs:
+ preservedir(os.path.join(root, dn))
+ os.rmdir(origdir)
+
+ recipefile = workspace[pn]['recipefile']
+ if recipefile and oe.path.is_path_parent(config.workspace_path, recipefile):
+ # This should always be true if recipefile is set, but just in case
+ preservedir(os.path.dirname(recipefile))
+ # We don't automatically create this dir next to appends, but the user can
+ preservedir(os.path.join(config.workspace_path, 'appends', pn))
+
+ srctreebase = workspace[pn]['srctreebase']
+ if os.path.isdir(srctreebase):
+ if os.listdir(srctreebase):
+ if remove_work:
+ logger.info('-r argument used on %s, removing source tree.'
+ ' You will lose any unsaved work' %pn)
+ shutil.rmtree(srctreebase)
+ else:
+ # We don't want to risk wiping out any work in progress
+ logger.info('Leaving source tree %s as-is; if you no '
+ 'longer need it then please delete it manually'
+ % srctreebase)
+ else:
+ # This is unlikely, but if it's empty we can just remove it
+ os.rmdir(srctreebase)
+
+ clean_preferred_provider(pn, config.workspace_path)
+
def reset(args, config, basepath, workspace):
"""Entry point for the devtool 'reset' subcommand"""
import bb
+ import shutil
+
+ recipes = ""
+
if args.recipename:
if args.all:
raise DevtoolError("Recipe cannot be specified if -a/--all is used")
- elif not args.recipename in workspace:
- raise DevtoolError("no recipe named %s in your workspace" %
- args.recipename)
+ else:
+ for recipe in args.recipename:
+ check_workspace_recipe(workspace, recipe, checksrc=False)
elif not args.all:
raise DevtoolError("Recipe must be specified, or specify -a/--all to "
"reset all recipes")
if args.all:
- recipes = workspace
+ recipes = list(workspace.keys())
else:
- recipes = [args.recipename]
+ recipes = args.recipename
- for pn in recipes:
- if not args.no_clean:
- logger.info('Cleaning sysroot for recipe %s...' % pn)
- try:
- exec_build_env_command(config.init_path, basepath, 'bitbake -c clean %s' % pn)
- except bb.process.ExecutionError as e:
- raise DevtoolError('Command \'%s\' failed, output:\n%s\nIf you '
- 'wish, you may specify -n/--no-clean to '
- 'skip running this command when resetting' %
- (e.command, e.stdout))
+ _reset(recipes, args.no_clean, args.remove_work, config, basepath, workspace)
- _check_preserve(config, pn)
-
- preservepath = os.path.join(config.workspace_path, 'attic', pn)
- def preservedir(origdir):
- if os.path.exists(origdir):
- for fn in os.listdir(origdir):
- logger.warn('Preserving %s in %s' % (fn, preservepath))
- bb.utils.mkdirhier(preservepath)
- shutil.move(os.path.join(origdir, fn), os.path.join(preservepath, fn))
- os.rmdir(origdir)
+ return 0
- preservedir(os.path.join(config.workspace_path, 'recipes', pn))
- # We don't automatically create this dir next to appends, but the user can
- preservedir(os.path.join(config.workspace_path, 'appends', pn))
- return 0
+def _get_layer(layername, d):
+ """Determine the base layer path for the specified layer name/path"""
+ layerdirs = d.getVar('BBLAYERS').split()
+ layers = {} # {basename: layer_paths}
+ for p in layerdirs:
+ bn = os.path.basename(p)
+ if bn not in layers:
+ layers[bn] = [p]
+ else:
+ layers[bn].append(p)
+ # Provide some shortcuts
+ if layername.lower() in ['oe-core', 'openembedded-core']:
+ layername = 'meta'
+ layer_paths = layers.get(layername, None)
+ if not layer_paths:
+ return os.path.abspath(layername)
+ elif len(layer_paths) == 1:
+ return os.path.abspath(layer_paths[0])
+ else:
+ # multiple layers having the same base name
+ logger.warning("Multiple layers have the same base name '%s', use the first one '%s'." % (layername, layer_paths[0]))
+ logger.warning("Consider using path instead of base name to specify layer:\n\t\t%s" % '\n\t\t'.join(layer_paths))
+ return os.path.abspath(layer_paths[0])
-def build(args, config, basepath, workspace):
- """Entry point for the devtool 'build' subcommand"""
+def finish(args, config, basepath, workspace):
+ """Entry point for the devtool 'finish' subcommand"""
import bb
- if not args.recipename in workspace:
- raise DevtoolError("no recipe named %s in your workspace" %
- args.recipename)
- build_task = config.get('Build', 'build_task', 'populate_sysroot')
+ import oe.recipeutils
+
+ check_workspace_recipe(workspace, args.recipename)
+
+ dry_run_suffix = ' (dry-run)' if args.dry_run else ''
+
+ # Grab the equivalent of COREBASE without having to initialise tinfoil
+ corebasedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
+
+ srctree = workspace[args.recipename]['srctree']
+ check_git_repo_op(srctree, [corebasedir])
+ dirty = check_git_repo_dirty(srctree)
+ if dirty:
+ if args.force:
+ logger.warning('Source tree is not clean, continuing as requested by -f/--force')
+ else:
+ raise DevtoolError('Source tree is not clean:\n\n%s\nEnsure you have committed your changes or use -f/--force if you are sure there\'s nothing that needs to be committed' % dirty)
+
+ no_clean = args.no_clean
+ remove_work=args.remove_work
+ tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
try:
- exec_build_env_command(config.init_path, basepath, 'bitbake -c %s %s' % (build_task, args.recipename), watch=True)
- except bb.process.ExecutionError as e:
- # We've already seen the output since watch=True, so just ensure we return something to the user
- return e.exitcode
+ rd = parse_recipe(config, tinfoil, args.recipename, True)
+ if not rd:
+ return 1
+
+ destlayerdir = _get_layer(args.destination, tinfoil.config_data)
+ recipefile = rd.getVar('FILE')
+ recipedir = os.path.dirname(recipefile)
+ origlayerdir = oe.recipeutils.find_layerdir(recipefile)
+
+ if not os.path.isdir(destlayerdir):
+ raise DevtoolError('Unable to find layer or directory matching "%s"' % args.destination)
+
+ if os.path.abspath(destlayerdir) == config.workspace_path:
+ raise DevtoolError('"%s" specifies the workspace layer - that is not a valid destination' % args.destination)
+
+ # If it's an upgrade, grab the original path
+ origpath = None
+ origfilelist = None
+ append = workspace[args.recipename]['bbappend']
+ with open(append, 'r') as f:
+ for line in f:
+ if line.startswith('# original_path:'):
+ origpath = line.split(':')[1].strip()
+ elif line.startswith('# original_files:'):
+ origfilelist = line.split(':')[1].split()
+
+ destlayerbasedir = oe.recipeutils.find_layerdir(destlayerdir)
+
+ if origlayerdir == config.workspace_path:
+ # Recipe file itself is in workspace, update it there first
+ appendlayerdir = None
+ origrelpath = None
+ if origpath:
+ origlayerpath = oe.recipeutils.find_layerdir(origpath)
+ if origlayerpath:
+ origrelpath = os.path.relpath(origpath, origlayerpath)
+ destpath = oe.recipeutils.get_bbfile_path(rd, destlayerdir, origrelpath)
+ if not destpath:
+ raise DevtoolError("Unable to determine destination layer path - check that %s specifies an actual layer and %s/conf/layer.conf specifies BBFILES. You may also need to specify a more complete path." % (args.destination, destlayerdir))
+ # Warn if the layer isn't in bblayers.conf (the code to create a bbappend will do this in other cases)
+ layerdirs = [os.path.abspath(layerdir) for layerdir in rd.getVar('BBLAYERS').split()]
+ if not os.path.abspath(destlayerbasedir) in layerdirs:
+ bb.warn('Specified destination layer is not currently enabled in bblayers.conf, so the %s recipe will now be unavailable in your current configuration until you add the layer there' % args.recipename)
+
+ elif destlayerdir == origlayerdir:
+ # Same layer, update the original recipe
+ appendlayerdir = None
+ destpath = None
+ else:
+ # Create/update a bbappend in the specified layer
+ appendlayerdir = destlayerdir
+ destpath = None
+
+ # Actually update the recipe / bbappend
+ removing_original = (origpath and origfilelist and oe.recipeutils.find_layerdir(origpath) == destlayerbasedir)
+ dry_run_output = None
+ dry_run_outdir = None
+ if args.dry_run:
+ dry_run_output = tempfile.TemporaryDirectory(prefix='devtool')
+ dry_run_outdir = dry_run_output.name
+ updated, appendfile, removed = _update_recipe(args.recipename, workspace, rd, args.mode, appendlayerdir, wildcard_version=True, no_remove=False, no_report_remove=removing_original, initial_rev=args.initial_rev, dry_run_outdir=dry_run_outdir, no_overrides=args.no_overrides, force_patch_refresh=args.force_patch_refresh)
+ removed = [os.path.relpath(pth, recipedir) for pth in removed]
+
+ # Remove any old files in the case of an upgrade
+ if removing_original:
+ for fn in origfilelist:
+ fnp = os.path.join(origpath, fn)
+ if fn in removed or not os.path.exists(os.path.join(recipedir, fn)):
+ logger.info('Removing file %s%s' % (fnp, dry_run_suffix))
+ if not args.dry_run:
+ try:
+ os.remove(fnp)
+ except FileNotFoundError:
+ pass
+
+ if origlayerdir == config.workspace_path and destpath:
+ # Recipe file itself is in the workspace - need to move it and any
+ # associated files to the specified layer
+ no_clean = True
+ logger.info('Moving recipe file to %s%s' % (destpath, dry_run_suffix))
+ for root, _, files in os.walk(recipedir):
+ for fn in files:
+ srcpath = os.path.join(root, fn)
+ relpth = os.path.relpath(os.path.dirname(srcpath), recipedir)
+ destdir = os.path.abspath(os.path.join(destpath, relpth))
+ destfp = os.path.join(destdir, fn)
+ _move_file(srcpath, destfp, dry_run_outdir=dry_run_outdir, base_outdir=destpath)
+
+ if dry_run_outdir:
+ import difflib
+ comparelist = []
+ for root, _, files in os.walk(dry_run_outdir):
+ for fn in files:
+ outf = os.path.join(root, fn)
+ relf = os.path.relpath(outf, dry_run_outdir)
+ logger.debug('dry-run: output file %s' % relf)
+ if fn.endswith('.bb'):
+ if origfilelist and origpath and destpath:
+ # Need to match this up with the pre-upgrade recipe file
+ for origf in origfilelist:
+ if origf.endswith('.bb'):
+ comparelist.append((os.path.abspath(os.path.join(origpath, origf)),
+ outf,
+ os.path.abspath(os.path.join(destpath, relf))))
+ break
+ else:
+ # Compare to the existing recipe
+ comparelist.append((recipefile, outf, recipefile))
+ elif fn.endswith('.bbappend'):
+ if appendfile:
+ if os.path.exists(appendfile):
+ comparelist.append((appendfile, outf, appendfile))
+ else:
+ comparelist.append((None, outf, appendfile))
+ else:
+ if destpath:
+ recipedest = destpath
+ elif appendfile:
+ recipedest = os.path.dirname(appendfile)
+ else:
+ recipedest = os.path.dirname(recipefile)
+ destfp = os.path.join(recipedest, relf)
+ if os.path.exists(destfp):
+ comparelist.append((destfp, outf, destfp))
+ output = ''
+ for oldfile, newfile, newfileshow in comparelist:
+ if oldfile:
+ with open(oldfile, 'r') as f:
+ oldlines = f.readlines()
+ else:
+ oldfile = '/dev/null'
+ oldlines = []
+ with open(newfile, 'r') as f:
+ newlines = f.readlines()
+ if not newfileshow:
+ newfileshow = newfile
+ diff = difflib.unified_diff(oldlines, newlines, oldfile, newfileshow)
+ difflines = list(diff)
+ if difflines:
+ output += ''.join(difflines)
+ if output:
+ logger.info('Diff of changed files:\n%s' % output)
+ finally:
+ tinfoil.shutdown()
+
+ # Everything else has succeeded, we can now reset
+ if args.dry_run:
+ logger.info('Resetting recipe (dry-run)')
+ else:
+ _reset([args.recipename], no_clean=no_clean, remove_work=remove_work, config=config, basepath=basepath, workspace=workspace)
return 0
+def get_default_srctree(config, recipename=''):
+ """Get the default srctree path"""
+ srctreeparent = config.get('General', 'default_source_parent_dir', config.workspace_path)
+ if recipename:
+ return os.path.join(srctreeparent, 'sources', recipename)
+ else:
+ return os.path.join(srctreeparent, 'sources')
+
def register_commands(subparsers, context):
"""Register devtool subcommands from this plugin"""
+
+ defsrctree = get_default_srctree(context.config)
parser_add = subparsers.add_parser('add', help='Add a new recipe',
- description='Adds a new recipe')
- parser_add.add_argument('recipename', help='Name for new recipe to add')
- parser_add.add_argument('srctree', help='Path to external source tree')
- parser_add.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
- parser_add.add_argument('--fetch', '-f', help='Fetch the specified URI and extract it to create the source tree', metavar='URI')
+ description='Adds a new recipe to the workspace to build a specified source tree. Can optionally fetch a remote URI and unpack it to create the source tree.',
+ group='starting', order=100)
+ parser_add.add_argument('recipename', nargs='?', help='Name for new recipe to add (just name - no version, path or extension). If not specified, will attempt to auto-detect it.')
+ parser_add.add_argument('srctree', nargs='?', help='Path to external source tree. If not specified, a subdirectory of %s will be used.' % defsrctree)
+ parser_add.add_argument('fetchuri', nargs='?', help='Fetch the specified URI and extract it to create the source tree')
+ group = parser_add.add_mutually_exclusive_group()
+ group.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
+ group.add_argument('--no-same-dir', help='Force build in a separate build directory', action="store_true")
+ parser_add.add_argument('--fetch', '-f', help='Fetch the specified URI and extract it to create the source tree (deprecated - pass as positional argument instead)', metavar='URI')
+ parser_add.add_argument('--npm-dev', help='For npm, also fetch devDependencies', action="store_true")
parser_add.add_argument('--version', '-V', help='Version to use within recipe (PV)')
- parser_add.set_defaults(func=add)
+ parser_add.add_argument('--no-git', '-g', help='If fetching source, do not set up source tree as a git repository', action="store_true")
+ group = parser_add.add_mutually_exclusive_group()
+ group.add_argument('--srcrev', '-S', help='Source revision to fetch if fetching from an SCM such as git (default latest)')
+ group.add_argument('--autorev', '-a', help='When fetching from a git repository, set SRCREV in the recipe to a floating revision instead of fixed', action="store_true")
+ parser_add.add_argument('--srcbranch', '-B', help='Branch in source repository if fetching from an SCM such as git (default master)')
+ parser_add.add_argument('--binary', '-b', help='Treat the source tree as something that should be installed verbatim (no compilation, same directory structure). Useful with binary packages e.g. RPMs.', action='store_true')
+ parser_add.add_argument('--also-native', help='Also add native variant (i.e. support building recipe for the build host as well as the target machine)', action='store_true')
+ parser_add.add_argument('--src-subdir', help='Specify subdirectory within source tree to use', metavar='SUBDIR')
+ parser_add.add_argument('--mirrors', help='Enable PREMIRRORS and MIRRORS for source tree fetching (disable by default).', action="store_true")
+ parser_add.add_argument('--provides', '-p', help='Specify an alias for the item provided by the recipe. E.g. virtual/libgl')
+ parser_add.set_defaults(func=add, fixed_setup=context.fixed_setup)
parser_modify = subparsers.add_parser('modify', help='Modify the source for an existing recipe',
- description='Enables modifying the source for an existing recipe',
- formatter_class=argparse.ArgumentDefaultsHelpFormatter)
- parser_modify.add_argument('recipename', help='Name for recipe to edit')
- parser_modify.add_argument('srctree', help='Path to external source tree')
+ description='Sets up the build environment to modify the source for an existing recipe. The default behaviour is to extract the source being fetched by the recipe into a git tree so you can work on it; alternatively if you already have your own pre-prepared source tree you can specify -n/--no-extract.',
+ group='starting', order=90)
+ parser_modify.add_argument('recipename', help='Name of existing recipe to edit (just name - no version, path or extension)')
+ parser_modify.add_argument('srctree', nargs='?', help='Path to external source tree. If not specified, a subdirectory of %s will be used.' % defsrctree)
parser_modify.add_argument('--wildcard', '-w', action="store_true", help='Use wildcard for unversioned bbappend')
- parser_modify.add_argument('--extract', '-x', action="store_true", help='Extract source as well')
+ group = parser_modify.add_mutually_exclusive_group()
+ group.add_argument('--extract', '-x', action="store_true", help='Extract source for recipe (default)')
+ group.add_argument('--no-extract', '-n', action="store_true", help='Do not extract source, expect it to exist')
group = parser_modify.add_mutually_exclusive_group()
group.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
group.add_argument('--no-same-dir', help='Force build in a separate build directory', action="store_true")
- parser_modify.add_argument('--branch', '-b', default="devtool", help='Name for development branch to checkout (only when using -x)')
- parser_modify.set_defaults(func=modify)
+ parser_modify.add_argument('--branch', '-b', default="devtool", help='Name for development branch to checkout (when not using -n/--no-extract) (default "%(default)s")')
+ parser_modify.add_argument('--no-overrides', '-O', action="store_true", help='Do not create branches for other override configurations')
+ parser_modify.add_argument('--keep-temp', help='Keep temporary directory (for debugging)', action="store_true")
+ parser_modify.set_defaults(func=modify, fixed_setup=context.fixed_setup)
parser_extract = subparsers.add_parser('extract', help='Extract the source for an existing recipe',
description='Extracts the source for an existing recipe',
- formatter_class=argparse.ArgumentDefaultsHelpFormatter)
- parser_extract.add_argument('recipename', help='Name for recipe to extract the source for')
+ group='advanced')
+ parser_extract.add_argument('recipename', help='Name of recipe to extract the source for')
parser_extract.add_argument('srctree', help='Path to where to extract the source tree')
- parser_extract.add_argument('--branch', '-b', default="devtool", help='Name for development branch to checkout')
+ parser_extract.add_argument('--branch', '-b', default="devtool", help='Name for development branch to checkout (default "%(default)s")')
+ parser_extract.add_argument('--no-overrides', '-O', action="store_true", help='Do not create branches for other override configurations')
parser_extract.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
- parser_extract.set_defaults(func=extract)
+ parser_extract.set_defaults(func=extract, fixed_setup=context.fixed_setup)
+
+ parser_sync = subparsers.add_parser('sync', help='Synchronize the source tree for an existing recipe',
+ description='Synchronize the previously extracted source tree for an existing recipe',
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ group='advanced')
+ parser_sync.add_argument('recipename', help='Name of recipe to sync the source for')
+ parser_sync.add_argument('srctree', help='Path to the source tree')
+ parser_sync.add_argument('--branch', '-b', default="devtool", help='Name for development branch to checkout')
+ parser_sync.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
+ parser_sync.set_defaults(func=sync, fixed_setup=context.fixed_setup)
+
+ parser_rename = subparsers.add_parser('rename', help='Rename a recipe file in the workspace',
+ description='Renames the recipe file for a recipe in the workspace, changing the name or version part or both, ensuring that all references within the workspace are updated at the same time. Only works when the recipe file itself is in the workspace, e.g. after devtool add. Particularly useful when devtool add did not automatically determine the correct name.',
+ group='working', order=10)
+ parser_rename.add_argument('recipename', help='Current name of recipe to rename')
+ parser_rename.add_argument('newname', nargs='?', help='New name for recipe (optional, not needed if you only want to change the version)')
+ parser_rename.add_argument('--version', '-V', help='Change the version (NOTE: this does not change the version fetched by the recipe, just the version in the recipe file name)')
+ parser_rename.add_argument('--no-srctree', '-s', action='store_true', help='Do not rename the source tree directory (if the default source tree path has been used) - keeping the old name may be desirable if there are internal/other external references to this path')
+ parser_rename.set_defaults(func=rename)
parser_update_recipe = subparsers.add_parser('update-recipe', help='Apply changes from external source tree to recipe',
- description='Applies changes from external source tree to a recipe (updating/adding/removing patches as necessary, or by updating SRCREV)')
+ description='Applies changes from external source tree to a recipe (updating/adding/removing patches as necessary, or by updating SRCREV). Note that these changes need to have been committed to the git repository in order to be recognised.',
+ group='working', order=-90)
parser_update_recipe.add_argument('recipename', help='Name of recipe to update')
parser_update_recipe.add_argument('--mode', '-m', choices=['patch', 'srcrev', 'auto'], default='auto', help='Update mode (where %(metavar)s is %(choices)s; default is %(default)s)', metavar='MODE')
- parser_update_recipe.add_argument('--initial-rev', help='Starting revision for patches')
+ parser_update_recipe.add_argument('--initial-rev', help='Override starting revision for patches')
parser_update_recipe.add_argument('--append', '-a', help='Write changes to a bbappend in the specified layer instead of the recipe', metavar='LAYERDIR')
parser_update_recipe.add_argument('--wildcard-version', '-w', help='In conjunction with -a/--append, use a wildcard to make the bbappend apply to any recipe version', action='store_true')
parser_update_recipe.add_argument('--no-remove', '-n', action="store_true", help='Don\'t remove patches, only add or update')
+ parser_update_recipe.add_argument('--no-overrides', '-O', action="store_true", help='Do not handle other override branches (if they exist)')
+ parser_update_recipe.add_argument('--dry-run', '-N', action="store_true", help='Dry-run (just report changes instead of writing them)')
+ parser_update_recipe.add_argument('--force-patch-refresh', action="store_true", help='Update patches in the layer even if they have not been modified (useful for refreshing patch context)')
parser_update_recipe.set_defaults(func=update_recipe)
parser_status = subparsers.add_parser('status', help='Show workspace status',
description='Lists recipes currently in your workspace and the paths to their respective external source trees',
- formatter_class=argparse.ArgumentDefaultsHelpFormatter)
+ group='info', order=100)
parser_status.set_defaults(func=status)
- parser_build = subparsers.add_parser('build', help='Build a recipe',
- description='Builds the specified recipe using bitbake',
- formatter_class=argparse.ArgumentDefaultsHelpFormatter)
- parser_build.add_argument('recipename', help='Recipe to build')
- parser_build.set_defaults(func=build)
-
parser_reset = subparsers.add_parser('reset', help='Remove a recipe from your workspace',
- description='Removes the specified recipe from your workspace (resetting its state)',
- formatter_class=argparse.ArgumentDefaultsHelpFormatter)
- parser_reset.add_argument('recipename', nargs='?', help='Recipe to reset')
+ description='Removes the specified recipe(s) from your workspace (resetting its state back to that defined by the metadata).',
+ group='working', order=-100)
+ parser_reset.add_argument('recipename', nargs='*', help='Recipe to reset')
parser_reset.add_argument('--all', '-a', action="store_true", help='Reset all recipes (clear workspace)')
parser_reset.add_argument('--no-clean', '-n', action="store_true", help='Don\'t clean the sysroot to remove recipe output')
+ parser_reset.add_argument('--remove-work', '-r', action="store_true", help='Clean the sources directory along with append')
parser_reset.set_defaults(func=reset)
+
+ parser_finish = subparsers.add_parser('finish', help='Finish working on a recipe in your workspace',
+ description='Pushes any committed changes to the specified recipe to the specified layer and removes it from your workspace. Roughly equivalent to an update-recipe followed by reset, except the update-recipe step will do the "right thing" depending on the recipe and the destination layer specified. Note that your changes must have been committed to the git repository in order to be recognised.',
+ group='working', order=-100)
+ parser_finish.add_argument('recipename', help='Recipe to finish')
+ parser_finish.add_argument('destination', help='Layer/path to put recipe into. Can be the name of a layer configured in your bblayers.conf, the path to the base of a layer, or a partial path inside a layer. %(prog)s will attempt to complete the path based on the layer\'s structure.')
+ parser_finish.add_argument('--mode', '-m', choices=['patch', 'srcrev', 'auto'], default='auto', help='Update mode (where %(metavar)s is %(choices)s; default is %(default)s)', metavar='MODE')
+ parser_finish.add_argument('--initial-rev', help='Override starting revision for patches')
+ parser_finish.add_argument('--force', '-f', action="store_true", help='Force continuing even if there are uncommitted changes in the source tree repository')
+ parser_finish.add_argument('--remove-work', '-r', action="store_true", help='Clean the sources directory under workspace')
+ parser_finish.add_argument('--no-clean', '-n', action="store_true", help='Don\'t clean the sysroot to remove recipe output')
+ parser_finish.add_argument('--no-overrides', '-O', action="store_true", help='Do not handle other override branches (if they exist)')
+ parser_finish.add_argument('--dry-run', '-N', action="store_true", help='Dry-run (just report changes instead of writing them)')
+ parser_finish.add_argument('--force-patch-refresh', action="store_true", help='Update patches in the layer even if they have not been modified (useful for refreshing patch context)')
+ parser_finish.set_defaults(func=finish)
diff --git a/scripts/lib/devtool/upgrade.py b/scripts/lib/devtool/upgrade.py
new file mode 100644
index 0000000000..826a3f955f
--- /dev/null
+++ b/scripts/lib/devtool/upgrade.py
@@ -0,0 +1,661 @@
+# Development tool - upgrade command plugin
+#
+# Copyright (C) 2014-2017 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+"""Devtool upgrade plugin"""
+
+import os
+import sys
+import re
+import shutil
+import tempfile
+import logging
+import argparse
+import scriptutils
+import errno
+import bb
+
+devtool_path = os.path.dirname(os.path.realpath(__file__)) + '/../../../meta/lib'
+sys.path = sys.path + [devtool_path]
+
+import oe.recipeutils
+from devtool import standard
+from devtool import exec_build_env_command, setup_tinfoil, DevtoolError, parse_recipe, use_external_build, update_unlockedsigs, check_prerelease_version
+
+logger = logging.getLogger('devtool')
+
+def _run(cmd, cwd=''):
+ logger.debug("Running command %s> %s" % (cwd,cmd))
+ return bb.process.run('%s' % cmd, cwd=cwd)
+
+def _get_srctree(tmpdir):
+ srctree = tmpdir
+ dirs = scriptutils.filter_src_subdirs(tmpdir)
+ if len(dirs) == 1:
+ srctree = os.path.join(tmpdir, dirs[0])
+ return srctree
+
+def _copy_source_code(orig, dest):
+ for path in standard._ls_tree(orig):
+ dest_dir = os.path.join(dest, os.path.dirname(path))
+ bb.utils.mkdirhier(dest_dir)
+ dest_path = os.path.join(dest, path)
+ shutil.move(os.path.join(orig, path), dest_path)
+
+def _remove_patch_dirs(recipefolder):
+ for root, dirs, files in os.walk(recipefolder):
+ for d in dirs:
+ shutil.rmtree(os.path.join(root,d))
+
+def _recipe_contains(rd, var):
+ rf = rd.getVar('FILE')
+ varfiles = oe.recipeutils.get_var_files(rf, [var], rd)
+ for var, fn in varfiles.items():
+ if fn and fn.startswith(os.path.dirname(rf) + os.sep):
+ return True
+ return False
+
+def _rename_recipe_dirs(oldpv, newpv, path):
+ for root, dirs, files in os.walk(path):
+ # Rename directories with the version in their name
+ for olddir in dirs:
+ if olddir.find(oldpv) != -1:
+ newdir = olddir.replace(oldpv, newpv)
+ if olddir != newdir:
+ shutil.move(os.path.join(path, olddir), os.path.join(path, newdir))
+ # Rename any inc files with the version in their name (unusual, but possible)
+ for oldfile in files:
+ if oldfile.endswith('.inc'):
+ if oldfile.find(oldpv) != -1:
+ newfile = oldfile.replace(oldpv, newpv)
+ if oldfile != newfile:
+ bb.utils.rename(os.path.join(path, oldfile),
+ os.path.join(path, newfile))
+
+def _rename_recipe_file(oldrecipe, bpn, oldpv, newpv, path):
+ oldrecipe = os.path.basename(oldrecipe)
+ if oldrecipe.endswith('_%s.bb' % oldpv):
+ newrecipe = '%s_%s.bb' % (bpn, newpv)
+ if oldrecipe != newrecipe:
+ shutil.move(os.path.join(path, oldrecipe), os.path.join(path, newrecipe))
+ else:
+ newrecipe = oldrecipe
+ return os.path.join(path, newrecipe)
+
+def _rename_recipe_files(oldrecipe, bpn, oldpv, newpv, path):
+ _rename_recipe_dirs(oldpv, newpv, path)
+ return _rename_recipe_file(oldrecipe, bpn, oldpv, newpv, path)
+
+def _write_append(rc, srctree, same_dir, no_same_dir, rev, copied, workspace, d):
+ """Writes an append file"""
+ if not os.path.exists(rc):
+ raise DevtoolError("bbappend not created because %s does not exist" % rc)
+
+ appendpath = os.path.join(workspace, 'appends')
+ if not os.path.exists(appendpath):
+ bb.utils.mkdirhier(appendpath)
+
+ brf = os.path.basename(os.path.splitext(rc)[0]) # rc basename
+
+ srctree = os.path.abspath(srctree)
+ pn = d.getVar('PN')
+ af = os.path.join(appendpath, '%s.bbappend' % brf)
+ with open(af, 'w') as f:
+ f.write('FILESEXTRAPATHS:prepend := "${THISDIR}/${PN}:"\n\n')
+ f.write('inherit externalsrc\n')
+ f.write(('# NOTE: We use pn- overrides here to avoid affecting'
+ 'multiple variants in the case where the recipe uses BBCLASSEXTEND\n'))
+ f.write('EXTERNALSRC:pn-%s = "%s"\n' % (pn, srctree))
+ b_is_s = use_external_build(same_dir, no_same_dir, d)
+ if b_is_s:
+ f.write('EXTERNALSRC_BUILD:pn-%s = "%s"\n' % (pn, srctree))
+ f.write('\n')
+ if rev:
+ f.write('# initial_rev: %s\n' % rev)
+ if copied:
+ f.write('# original_path: %s\n' % os.path.dirname(d.getVar('FILE')))
+ f.write('# original_files: %s\n' % ' '.join(copied))
+ return af
+
+def _cleanup_on_error(rf, srctree):
+ rfp = os.path.split(rf)[0] # recipe folder
+ rfpp = os.path.split(rfp)[0] # recipes folder
+ if os.path.exists(rfp):
+ shutil.rmtree(rfp)
+ if not len(os.listdir(rfpp)):
+ os.rmdir(rfpp)
+ srctree = os.path.abspath(srctree)
+ if os.path.exists(srctree):
+ shutil.rmtree(srctree)
+
+def _upgrade_error(e, rf, srctree, keep_failure=False, extramsg=None):
+ if rf and not keep_failure:
+ _cleanup_on_error(rf, srctree)
+ logger.error(e)
+ if extramsg:
+ logger.error(extramsg)
+ if keep_failure:
+ logger.info('Preserving failed upgrade files (--keep-failure)')
+ sys.exit(1)
+
+def _get_uri(rd):
+ srcuris = rd.getVar('SRC_URI').split()
+ if not len(srcuris):
+ raise DevtoolError('SRC_URI not found on recipe')
+ # Get first non-local entry in SRC_URI - usually by convention it's
+ # the first entry, but not always!
+ srcuri = None
+ for entry in srcuris:
+ if not entry.startswith('file://'):
+ srcuri = entry
+ break
+ if not srcuri:
+ raise DevtoolError('Unable to find non-local entry in SRC_URI')
+ srcrev = '${AUTOREV}'
+ if '://' in srcuri:
+ # Fetch a URL
+ rev_re = re.compile(';rev=([^;]+)')
+ res = rev_re.search(srcuri)
+ if res:
+ srcrev = res.group(1)
+ srcuri = rev_re.sub('', srcuri)
+ return srcuri, srcrev
+
+def _extract_new_source(newpv, srctree, no_patch, srcrev, srcbranch, branch, keep_temp, tinfoil, rd):
+ """Extract sources of a recipe with a new version"""
+
+ def __run(cmd):
+ """Simple wrapper which calls _run with srctree as cwd"""
+ return _run(cmd, srctree)
+
+ crd = rd.createCopy()
+
+ pv = crd.getVar('PV')
+ crd.setVar('PV', newpv)
+
+ tmpsrctree = None
+ uri, rev = _get_uri(crd)
+ if srcrev:
+ rev = srcrev
+ if uri.startswith('git://') or uri.startswith('gitsm://'):
+ __run('git fetch')
+ __run('git checkout %s' % rev)
+ __run('git tag -f devtool-base-new')
+ md5 = None
+ sha256 = None
+ _, _, _, _, _, params = bb.fetch2.decodeurl(uri)
+ srcsubdir_rel = params.get('destsuffix', 'git')
+ if not srcbranch:
+ check_branch, check_branch_err = __run('git branch -r --contains %s' % srcrev)
+ get_branch = [x.strip() for x in check_branch.splitlines()]
+ # Remove HEAD reference point and drop remote prefix
+ get_branch = [x.split('/', 1)[1] for x in get_branch if not x.startswith('origin/HEAD')]
+ if 'master' in get_branch:
+ # If it is master, we do not need to append 'branch=master' as this is default.
+ # Even with the case where get_branch has multiple objects, if 'master' is one
+ # of them, we should default take from 'master'
+ srcbranch = ''
+ elif len(get_branch) == 1:
+ # If 'master' isn't in get_branch and get_branch contains only ONE object, then store result into 'srcbranch'
+ srcbranch = get_branch[0]
+ else:
+ # If get_branch contains more than one objects, then display error and exit.
+ mbrch = '\n ' + '\n '.join(get_branch)
+ raise DevtoolError('Revision %s was found on multiple branches: %s\nPlease provide the correct branch in the devtool command with "--srcbranch" or "-B" option.' % (srcrev, mbrch))
+ else:
+ __run('git checkout devtool-base -b devtool-%s' % newpv)
+
+ tmpdir = tempfile.mkdtemp(prefix='devtool')
+ try:
+ checksums, ftmpdir = scriptutils.fetch_url(tinfoil, uri, rev, tmpdir, logger, preserve_tmp=keep_temp)
+ except scriptutils.FetchUrlFailure as e:
+ raise DevtoolError(e)
+
+ if ftmpdir and keep_temp:
+ logger.info('Fetch temp directory is %s' % ftmpdir)
+
+ md5 = checksums['md5sum']
+ sha256 = checksums['sha256sum']
+
+ tmpsrctree = _get_srctree(tmpdir)
+ srctree = os.path.abspath(srctree)
+ srcsubdir_rel = os.path.relpath(tmpsrctree, tmpdir)
+
+ # Delete all sources so we ensure no stray files are left over
+ for item in os.listdir(srctree):
+ if item in ['.git', 'oe-local-files']:
+ continue
+ itempath = os.path.join(srctree, item)
+ if os.path.isdir(itempath):
+ shutil.rmtree(itempath)
+ else:
+ os.remove(itempath)
+
+ # Copy in new ones
+ _copy_source_code(tmpsrctree, srctree)
+
+ (stdout,_) = __run('git ls-files --modified --others')
+ filelist = stdout.splitlines()
+ pbar = bb.ui.knotty.BBProgress('Adding changed files', len(filelist))
+ pbar.start()
+ batchsize = 100
+ for i in range(0, len(filelist), batchsize):
+ batch = filelist[i:i+batchsize]
+ __run('git add -f -A %s' % ' '.join(['"%s"' % item for item in batch]))
+ pbar.update(i)
+ pbar.finish()
+
+ useroptions = []
+ oe.patch.GitApplyTree.gitCommandUserOptions(useroptions, d=rd)
+ __run('git %s commit -q -m "Commit of upstream changes at version %s" --allow-empty' % (' '.join(useroptions), newpv))
+ __run('git tag -f devtool-base-%s' % newpv)
+
+ (stdout, _) = __run('git rev-parse HEAD')
+ rev = stdout.rstrip()
+
+ if no_patch:
+ patches = oe.recipeutils.get_recipe_patches(crd)
+ if patches:
+ logger.warning('By user choice, the following patches will NOT be applied to the new source tree:\n %s' % '\n '.join([os.path.basename(patch) for patch in patches]))
+ else:
+ __run('git checkout devtool-patched -b %s' % branch)
+ (stdout, _) = __run('git branch --list devtool-override-*')
+ branches_to_rebase = [branch] + stdout.split()
+ for b in branches_to_rebase:
+ logger.info("Rebasing {} onto {}".format(b, rev))
+ __run('git checkout %s' % b)
+ try:
+ __run('git rebase %s' % rev)
+ except bb.process.ExecutionError as e:
+ if 'conflict' in e.stdout:
+ logger.warning('Command \'%s\' failed:\n%s\n\nYou will need to resolve conflicts in order to complete the upgrade.' % (e.command, e.stdout.rstrip()))
+ __run('git rebase --abort')
+ else:
+ logger.warning('Command \'%s\' failed:\n%s' % (e.command, e.stdout))
+ __run('git checkout %s' % branch)
+
+ if tmpsrctree:
+ if keep_temp:
+ logger.info('Preserving temporary directory %s' % tmpsrctree)
+ else:
+ shutil.rmtree(tmpsrctree)
+ if tmpdir != tmpsrctree:
+ shutil.rmtree(tmpdir)
+
+ return (rev, md5, sha256, srcbranch, srcsubdir_rel)
+
+def _add_license_diff_to_recipe(path, diff):
+ notice_text = """# FIXME: the LIC_FILES_CHKSUM values have been updated by 'devtool upgrade'.
+# The following is the difference between the old and the new license text.
+# Please update the LICENSE value if needed, and summarize the changes in
+# the commit message via 'License-Update:' tag.
+# (example: 'License-Update: copyright years updated.')
+#
+# The changes:
+#
+"""
+ commented_diff = "\n".join(["# {}".format(l) for l in diff.split('\n')])
+ with open(path, 'rb') as f:
+ orig_content = f.read()
+ with open(path, 'wb') as f:
+ f.write(notice_text.encode())
+ f.write(commented_diff.encode())
+ f.write("\n#\n\n".encode())
+ f.write(orig_content)
+
+def _create_new_recipe(newpv, md5, sha256, srcrev, srcbranch, srcsubdir_old, srcsubdir_new, workspace, tinfoil, rd, license_diff, new_licenses, srctree, keep_failure):
+ """Creates the new recipe under workspace"""
+
+ bpn = rd.getVar('BPN')
+ path = os.path.join(workspace, 'recipes', bpn)
+ bb.utils.mkdirhier(path)
+ copied, _ = oe.recipeutils.copy_recipe_files(rd, path, all_variants=True)
+ if not copied:
+ raise DevtoolError('Internal error - no files were copied for recipe %s' % bpn)
+ logger.debug('Copied %s to %s' % (copied, path))
+
+ oldpv = rd.getVar('PV')
+ if not newpv:
+ newpv = oldpv
+ origpath = rd.getVar('FILE')
+ fullpath = _rename_recipe_files(origpath, bpn, oldpv, newpv, path)
+ logger.debug('Upgraded %s => %s' % (origpath, fullpath))
+
+ newvalues = {}
+ if _recipe_contains(rd, 'PV') and newpv != oldpv:
+ newvalues['PV'] = newpv
+
+ if srcrev:
+ newvalues['SRCREV'] = srcrev
+
+ if srcbranch:
+ src_uri = oe.recipeutils.split_var_value(rd.getVar('SRC_URI', False) or '')
+ changed = False
+ replacing = True
+ new_src_uri = []
+ for entry in src_uri:
+ scheme, network, path, user, passwd, params = bb.fetch2.decodeurl(entry)
+ if replacing and scheme in ['git', 'gitsm']:
+ branch = params.get('branch', 'master')
+ if rd.expand(branch) != srcbranch:
+ # Handle case where branch is set through a variable
+ res = re.match(r'\$\{([^}@]+)\}', branch)
+ if res:
+ newvalues[res.group(1)] = srcbranch
+ # We know we won't change SRC_URI now, so break out
+ break
+ else:
+ params['branch'] = srcbranch
+ entry = bb.fetch2.encodeurl((scheme, network, path, user, passwd, params))
+ changed = True
+ replacing = False
+ new_src_uri.append(entry)
+ if changed:
+ newvalues['SRC_URI'] = ' '.join(new_src_uri)
+
+ newvalues['PR'] = None
+
+ # Work out which SRC_URI entries have changed in case the entry uses a name
+ crd = rd.createCopy()
+ crd.setVar('PV', newpv)
+ for var, value in newvalues.items():
+ crd.setVar(var, value)
+ old_src_uri = (rd.getVar('SRC_URI') or '').split()
+ new_src_uri = (crd.getVar('SRC_URI') or '').split()
+ newnames = []
+ addnames = []
+ for newentry in new_src_uri:
+ _, _, _, _, _, params = bb.fetch2.decodeurl(newentry)
+ if 'name' in params:
+ newnames.append(params['name'])
+ if newentry not in old_src_uri:
+ addnames.append(params['name'])
+ # Find what's been set in the original recipe
+ oldnames = []
+ noname = False
+ for varflag in rd.getVarFlags('SRC_URI'):
+ if varflag.endswith(('.md5sum', '.sha256sum')):
+ name = varflag.rsplit('.', 1)[0]
+ if name not in oldnames:
+ oldnames.append(name)
+ elif varflag in ['md5sum', 'sha256sum']:
+ noname = True
+ # Even if SRC_URI has named entries it doesn't have to actually use the name
+ if noname and addnames and addnames[0] not in oldnames:
+ addnames = []
+ # Drop any old names (the name actually might include ${PV})
+ for name in oldnames:
+ if name not in newnames:
+ newvalues['SRC_URI[%s.md5sum]' % name] = None
+ newvalues['SRC_URI[%s.sha256sum]' % name] = None
+
+ if sha256:
+ if addnames:
+ nameprefix = '%s.' % addnames[0]
+ else:
+ nameprefix = ''
+ newvalues['SRC_URI[%smd5sum]' % nameprefix] = None
+ newvalues['SRC_URI[%ssha256sum]' % nameprefix] = sha256
+
+ if srcsubdir_new != srcsubdir_old:
+ s_subdir_old = os.path.relpath(os.path.abspath(rd.getVar('S')), rd.getVar('WORKDIR'))
+ s_subdir_new = os.path.relpath(os.path.abspath(crd.getVar('S')), crd.getVar('WORKDIR'))
+ if srcsubdir_old == s_subdir_old and srcsubdir_new != s_subdir_new:
+ # Subdir for old extracted source matches what S points to (it should!)
+ # but subdir for new extracted source doesn't match what S will be
+ newvalues['S'] = '${WORKDIR}/%s' % srcsubdir_new.replace(newpv, '${PV}')
+ if crd.expand(newvalues['S']) == crd.expand('${WORKDIR}/${BP}'):
+ # It's the default, drop it
+ # FIXME what if S is being set in a .inc?
+ newvalues['S'] = None
+ logger.info('Source subdirectory has changed, dropping S value since it now matches the default ("${WORKDIR}/${BP}")')
+ else:
+ logger.info('Source subdirectory has changed, updating S value')
+
+ if license_diff:
+ newlicchksum = " ".join(["file://{}".format(l['path']) +
+ (";beginline={}".format(l['beginline']) if l['beginline'] else "") +
+ (";endline={}".format(l['endline']) if l['endline'] else "") +
+ (";md5={}".format(l['actual_md5'])) for l in new_licenses])
+ newvalues["LIC_FILES_CHKSUM"] = newlicchksum
+ _add_license_diff_to_recipe(fullpath, license_diff)
+
+ try:
+ rd = tinfoil.parse_recipe_file(fullpath, False)
+ except bb.tinfoil.TinfoilCommandFailed as e:
+ _upgrade_error(e, fullpath, srctree, keep_failure, 'Parsing of upgraded recipe failed')
+ oe.recipeutils.patch_recipe(rd, fullpath, newvalues)
+
+ return fullpath, copied
+
+
+def _check_git_config():
+ def getconfig(name):
+ try:
+ value = bb.process.run('git config --global %s' % name)[0].strip()
+ except bb.process.ExecutionError as e:
+ if e.exitcode == 1:
+ value = None
+ else:
+ raise
+ return value
+
+ username = getconfig('user.name')
+ useremail = getconfig('user.email')
+ configerr = []
+ if not username:
+ configerr.append('Please set your name using:\n git config --global user.name')
+ if not useremail:
+ configerr.append('Please set your email using:\n git config --global user.email')
+ if configerr:
+ raise DevtoolError('Your git configuration is incomplete which will prevent rebases from working:\n' + '\n'.join(configerr))
+
+def _extract_licenses(srcpath, recipe_licenses):
+ licenses = []
+ for url in recipe_licenses.split():
+ license = {}
+ (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(url)
+ license['path'] = path
+ license['md5'] = parm.get('md5', '')
+ license['beginline'], license['endline'] = 0, 0
+ if 'beginline' in parm:
+ license['beginline'] = int(parm['beginline'])
+ if 'endline' in parm:
+ license['endline'] = int(parm['endline'])
+ license['text'] = []
+ with open(os.path.join(srcpath, path), 'rb') as f:
+ import hashlib
+ actual_md5 = hashlib.md5()
+ lineno = 0
+ for line in f:
+ lineno += 1
+ if (lineno >= license['beginline']) and ((lineno <= license['endline']) or not license['endline']):
+ license['text'].append(line.decode(errors='ignore'))
+ actual_md5.update(line)
+ license['actual_md5'] = actual_md5.hexdigest()
+ licenses.append(license)
+ return licenses
+
+def _generate_license_diff(old_licenses, new_licenses):
+ need_diff = False
+ for l in new_licenses:
+ if l['md5'] != l['actual_md5']:
+ need_diff = True
+ break
+ if need_diff == False:
+ return None
+
+ import difflib
+ diff = ''
+ for old, new in zip(old_licenses, new_licenses):
+ for line in difflib.unified_diff(old['text'], new['text'], old['path'], new['path']):
+ diff = diff + line
+ return diff
+
+def upgrade(args, config, basepath, workspace):
+ """Entry point for the devtool 'upgrade' subcommand"""
+
+ if args.recipename in workspace:
+ raise DevtoolError("recipe %s is already in your workspace" % args.recipename)
+ if args.srcbranch and not args.srcrev:
+ raise DevtoolError("If you specify --srcbranch/-B then you must use --srcrev/-S to specify the revision" % args.recipename)
+
+ _check_git_config()
+
+ tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
+ try:
+ rd = parse_recipe(config, tinfoil, args.recipename, True)
+ if not rd:
+ return 1
+
+ pn = rd.getVar('PN')
+ if pn != args.recipename:
+ logger.info('Mapping %s to %s' % (args.recipename, pn))
+ if pn in workspace:
+ raise DevtoolError("recipe %s is already in your workspace" % pn)
+
+ if args.srctree:
+ srctree = os.path.abspath(args.srctree)
+ else:
+ srctree = standard.get_default_srctree(config, pn)
+
+ # Check that recipe isn't using a shared workdir
+ s = os.path.abspath(rd.getVar('S'))
+ workdir = os.path.abspath(rd.getVar('WORKDIR'))
+ srctree_s = srctree
+ if s.startswith(workdir) and s != workdir and os.path.dirname(s) != workdir:
+ # Handle if S is set to a subdirectory of the source
+ srcsubdir = os.path.relpath(s, workdir).split(os.sep, 1)[1]
+ srctree_s = os.path.join(srctree, srcsubdir)
+
+ # try to automatically discover latest version and revision if not provided on command line
+ if not args.version and not args.srcrev:
+ version_info = oe.recipeutils.get_recipe_upstream_version(rd)
+ if version_info['version'] and not version_info['version'].endswith("new-commits-available"):
+ args.version = version_info['version']
+ if version_info['revision']:
+ args.srcrev = version_info['revision']
+ if not args.version and not args.srcrev:
+ raise DevtoolError("Automatic discovery of latest version/revision failed - you must provide a version using the --version/-V option, or for recipes that fetch from an SCM such as git, the --srcrev/-S option.")
+
+ standard._check_compatible_recipe(pn, rd)
+ old_srcrev = rd.getVar('SRCREV')
+ if old_srcrev == 'INVALID':
+ old_srcrev = None
+ if old_srcrev and not args.srcrev:
+ raise DevtoolError("Recipe specifies a SRCREV value; you must specify a new one when upgrading")
+ old_ver = rd.getVar('PV')
+ if old_ver == args.version and old_srcrev == args.srcrev:
+ raise DevtoolError("Current and upgrade versions are the same version")
+ if args.version:
+ if bb.utils.vercmp_string(args.version, old_ver) < 0:
+ logger.warning('Upgrade version %s compares as less than the current version %s. If you are using a package feed for on-target upgrades or providing this recipe for general consumption, then you should increment PE in the recipe (or if there is no current PE value set, set it to "1")' % (args.version, old_ver))
+ check_prerelease_version(args.version, 'devtool upgrade')
+
+ rf = None
+ license_diff = None
+ try:
+ logger.info('Extracting current version source...')
+ rev1, srcsubdir1 = standard._extract_source(srctree, False, 'devtool-orig', False, config, basepath, workspace, args.fixed_setup, rd, tinfoil, no_overrides=args.no_overrides)
+ old_licenses = _extract_licenses(srctree_s, (rd.getVar('LIC_FILES_CHKSUM') or ""))
+ logger.info('Extracting upgraded version source...')
+ rev2, md5, sha256, srcbranch, srcsubdir2 = _extract_new_source(args.version, srctree, args.no_patch,
+ args.srcrev, args.srcbranch, args.branch, args.keep_temp,
+ tinfoil, rd)
+ new_licenses = _extract_licenses(srctree_s, (rd.getVar('LIC_FILES_CHKSUM') or ""))
+ license_diff = _generate_license_diff(old_licenses, new_licenses)
+ rf, copied = _create_new_recipe(args.version, md5, sha256, args.srcrev, srcbranch, srcsubdir1, srcsubdir2, config.workspace_path, tinfoil, rd, license_diff, new_licenses, srctree, args.keep_failure)
+ except bb.process.CmdError as e:
+ _upgrade_error(e, rf, srctree, args.keep_failure)
+ except DevtoolError as e:
+ _upgrade_error(e, rf, srctree, args.keep_failure)
+ standard._add_md5(config, pn, os.path.dirname(rf))
+
+ af = _write_append(rf, srctree_s, args.same_dir, args.no_same_dir, rev2,
+ copied, config.workspace_path, rd)
+ standard._add_md5(config, pn, af)
+
+ update_unlockedsigs(basepath, workspace, args.fixed_setup, [pn])
+
+ logger.info('Upgraded source extracted to %s' % srctree)
+ logger.info('New recipe is %s' % rf)
+ if license_diff:
+ logger.info('License checksums have been updated in the new recipe; please refer to it for the difference between the old and the new license texts.')
+ preferred_version = rd.getVar('PREFERRED_VERSION_%s' % rd.getVar('PN'))
+ if preferred_version:
+ logger.warning('Version is pinned to %s via PREFERRED_VERSION; it may need adjustment to match the new version before any further steps are taken' % preferred_version)
+ finally:
+ tinfoil.shutdown()
+ return 0
+
+def latest_version(args, config, basepath, workspace):
+ """Entry point for the devtool 'latest_version' subcommand"""
+ tinfoil = setup_tinfoil(basepath=basepath, tracking=True)
+ try:
+ rd = parse_recipe(config, tinfoil, args.recipename, True)
+ if not rd:
+ return 1
+ version_info = oe.recipeutils.get_recipe_upstream_version(rd)
+ # "new-commits-available" is an indication that upstream never issues version tags
+ if not version_info['version'].endswith("new-commits-available"):
+ logger.info("Current version: {}".format(version_info['current_version']))
+ logger.info("Latest version: {}".format(version_info['version']))
+ if version_info['revision']:
+ logger.info("Latest version's commit: {}".format(version_info['revision']))
+ else:
+ logger.info("Latest commit: {}".format(version_info['revision']))
+ finally:
+ tinfoil.shutdown()
+ return 0
+
+def check_upgrade_status(args, config, basepath, workspace):
+ if not args.recipe:
+ logger.info("Checking the upstream status for all recipes may take a few minutes")
+ results = oe.recipeutils.get_recipe_upgrade_status(args.recipe)
+ for result in results:
+ # pn, update_status, current, latest, maintainer, latest_commit, no_update_reason
+ if args.all or result[1] != 'MATCH':
+ logger.info("{:25} {:15} {:15} {} {} {}".format( result[0],
+ result[2],
+ result[1] if result[1] != 'UPDATE' else (result[3] if not result[3].endswith("new-commits-available") else "new commits"),
+ result[4],
+ result[5] if result[5] != 'N/A' else "",
+ "cannot be updated due to: %s" %(result[6]) if result[6] else ""))
+
+def register_commands(subparsers, context):
+ """Register devtool subcommands from this plugin"""
+
+ defsrctree = standard.get_default_srctree(context.config)
+
+ parser_upgrade = subparsers.add_parser('upgrade', help='Upgrade an existing recipe',
+ description='Upgrades an existing recipe to a new upstream version. Puts the upgraded recipe file into the workspace along with any associated files, and extracts the source tree to a specified location (in case patches need rebasing or adding to as a result of the upgrade).',
+ group='starting')
+ parser_upgrade.add_argument('recipename', help='Name of recipe to upgrade (just name - no version, path or extension)')
+ parser_upgrade.add_argument('srctree', nargs='?', help='Path to where to extract the source tree. If not specified, a subdirectory of %s will be used.' % defsrctree)
+ parser_upgrade.add_argument('--version', '-V', help='Version to upgrade to (PV). If omitted, latest upstream version will be determined and used, if possible.')
+ parser_upgrade.add_argument('--srcrev', '-S', help='Source revision to upgrade to (useful when fetching from an SCM such as git)')
+ parser_upgrade.add_argument('--srcbranch', '-B', help='Branch in source repository containing the revision to use (if fetching from an SCM such as git)')
+ parser_upgrade.add_argument('--branch', '-b', default="devtool", help='Name for new development branch to checkout (default "%(default)s")')
+ parser_upgrade.add_argument('--no-patch', action="store_true", help='Do not apply patches from the recipe to the new source code')
+ parser_upgrade.add_argument('--no-overrides', '-O', action="store_true", help='Do not create branches for other override configurations')
+ group = parser_upgrade.add_mutually_exclusive_group()
+ group.add_argument('--same-dir', '-s', help='Build in same directory as source', action="store_true")
+ group.add_argument('--no-same-dir', help='Force build in a separate build directory', action="store_true")
+ parser_upgrade.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
+ parser_upgrade.add_argument('--keep-failure', action="store_true", help='Keep failed upgrade recipe and associated files (for debugging)')
+ parser_upgrade.set_defaults(func=upgrade, fixed_setup=context.fixed_setup)
+
+ parser_latest_version = subparsers.add_parser('latest-version', help='Report the latest version of an existing recipe',
+ description='Queries the upstream server for what the latest upstream release is (for git, tags are checked, for tarballs, a list of them is obtained, and one with the highest version number is reported)',
+ group='info')
+ parser_latest_version.add_argument('recipename', help='Name of recipe to query (just name - no version, path or extension)')
+ parser_latest_version.set_defaults(func=latest_version)
+
+ parser_check_upgrade_status = subparsers.add_parser('check-upgrade-status', help="Report upgradability for multiple (or all) recipes",
+ description="Prints a table of recipes together with versions currently provided by recipes, and latest upstream versions, when there is a later version available",
+ group='info')
+ parser_check_upgrade_status.add_argument('recipe', help='Name of the recipe to report (omit to report upgrade info for all recipes)', nargs='*')
+ parser_check_upgrade_status.add_argument('--all', '-a', help='Show all recipes, not just recipes needing upgrade', action="store_true")
+ parser_check_upgrade_status.set_defaults(func=check_upgrade_status)
diff --git a/scripts/lib/devtool/utilcmds.py b/scripts/lib/devtool/utilcmds.py
new file mode 100644
index 0000000000..964817766b
--- /dev/null
+++ b/scripts/lib/devtool/utilcmds.py
@@ -0,0 +1,242 @@
+# Development tool - utility commands plugin
+#
+# Copyright (C) 2015-2016 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+"""Devtool utility plugins"""
+
+import os
+import sys
+import shutil
+import tempfile
+import logging
+import argparse
+import subprocess
+import scriptutils
+from devtool import exec_build_env_command, setup_tinfoil, check_workspace_recipe, DevtoolError
+from devtool import parse_recipe
+
+logger = logging.getLogger('devtool')
+
+def _find_recipe_path(args, config, basepath, workspace):
+ if args.any_recipe:
+ logger.warning('-a/--any-recipe option is now always active, and thus the option will be removed in a future release')
+ if args.recipename in workspace:
+ recipefile = workspace[args.recipename]['recipefile']
+ else:
+ recipefile = None
+ if not recipefile:
+ tinfoil = setup_tinfoil(config_only=False, basepath=basepath)
+ try:
+ rd = parse_recipe(config, tinfoil, args.recipename, True)
+ if not rd:
+ raise DevtoolError("Failed to find specified recipe")
+ recipefile = rd.getVar('FILE')
+ finally:
+ tinfoil.shutdown()
+ return recipefile
+
+
+def find_recipe(args, config, basepath, workspace):
+ """Entry point for the devtool 'find-recipe' subcommand"""
+ recipefile = _find_recipe_path(args, config, basepath, workspace)
+ print(recipefile)
+ return 0
+
+
+def edit_recipe(args, config, basepath, workspace):
+ """Entry point for the devtool 'edit-recipe' subcommand"""
+ return scriptutils.run_editor(_find_recipe_path(args, config, basepath, workspace), logger)
+
+
+def configure_help(args, config, basepath, workspace):
+ """Entry point for the devtool 'configure-help' subcommand"""
+ import oe.utils
+
+ check_workspace_recipe(workspace, args.recipename)
+ tinfoil = setup_tinfoil(config_only=False, basepath=basepath)
+ try:
+ rd = parse_recipe(config, tinfoil, args.recipename, appends=True, filter_workspace=False)
+ if not rd:
+ return 1
+ b = rd.getVar('B')
+ s = rd.getVar('S')
+ configurescript = os.path.join(s, 'configure')
+ confdisabled = 'noexec' in rd.getVarFlags('do_configure') or 'do_configure' not in (rd.getVar('__BBTASKS', False) or [])
+ configureopts = oe.utils.squashspaces(rd.getVar('CONFIGUREOPTS') or '')
+ extra_oeconf = oe.utils.squashspaces(rd.getVar('EXTRA_OECONF') or '')
+ extra_oecmake = oe.utils.squashspaces(rd.getVar('EXTRA_OECMAKE') or '')
+ do_configure = rd.getVar('do_configure') or ''
+ do_configure_noexpand = rd.getVar('do_configure', False) or ''
+ packageconfig = rd.getVarFlags('PACKAGECONFIG') or []
+ autotools = bb.data.inherits_class('autotools', rd) and ('oe_runconf' in do_configure or 'autotools_do_configure' in do_configure)
+ cmake = bb.data.inherits_class('cmake', rd) and ('cmake_do_configure' in do_configure)
+ cmake_do_configure = rd.getVar('cmake_do_configure')
+ pn = rd.getVar('PN')
+ finally:
+ tinfoil.shutdown()
+
+ if 'doc' in packageconfig:
+ del packageconfig['doc']
+
+ if autotools and not os.path.exists(configurescript):
+ logger.info('Running do_configure to generate configure script')
+ try:
+ stdout, _ = exec_build_env_command(config.init_path, basepath,
+ 'bitbake -c configure %s' % args.recipename,
+ stderr=subprocess.STDOUT)
+ except bb.process.ExecutionError:
+ pass
+
+ if confdisabled or do_configure.strip() in ('', ':'):
+ raise DevtoolError("do_configure task has been disabled for this recipe")
+ elif args.no_pager and not os.path.exists(configurescript):
+ raise DevtoolError("No configure script found and no other information to display")
+ else:
+ configopttext = ''
+ if autotools and configureopts:
+ configopttext = '''
+Arguments currently passed to the configure script:
+
+%s
+
+Some of those are fixed.''' % (configureopts + ' ' + extra_oeconf)
+ if extra_oeconf:
+ configopttext += ''' The ones that are specified through EXTRA_OECONF (which you can change or add to easily):
+
+%s''' % extra_oeconf
+
+ elif cmake:
+ in_cmake = False
+ cmake_cmd = ''
+ for line in cmake_do_configure.splitlines():
+ if in_cmake:
+ cmake_cmd = cmake_cmd + ' ' + line.strip().rstrip('\\')
+ if not line.endswith('\\'):
+ break
+ if line.lstrip().startswith('cmake '):
+ cmake_cmd = line.strip().rstrip('\\')
+ if line.endswith('\\'):
+ in_cmake = True
+ else:
+ break
+ if cmake_cmd:
+ configopttext = '''
+The current cmake command line:
+
+%s
+
+Arguments specified through EXTRA_OECMAKE (which you can change or add to easily)
+
+%s''' % (oe.utils.squashspaces(cmake_cmd), extra_oecmake)
+ else:
+ configopttext = '''
+The current implementation of cmake_do_configure:
+
+cmake_do_configure() {
+%s
+}
+
+Arguments specified through EXTRA_OECMAKE (which you can change or add to easily)
+
+%s''' % (cmake_do_configure.rstrip(), extra_oecmake)
+
+ elif do_configure:
+ configopttext = '''
+The current implementation of do_configure:
+
+do_configure() {
+%s
+}''' % do_configure.rstrip()
+ if '${EXTRA_OECONF}' in do_configure_noexpand:
+ configopttext += '''
+
+Arguments specified through EXTRA_OECONF (which you can change or add to easily):
+
+%s''' % extra_oeconf
+
+ if packageconfig:
+ configopttext += '''
+
+Some of these options may be controlled through PACKAGECONFIG; for more details please see the recipe.'''
+
+ if args.arg:
+ helpargs = ' '.join(args.arg)
+ elif cmake:
+ helpargs = '-LH'
+ else:
+ helpargs = '--help'
+
+ msg = '''configure information for %s
+------------------------------------------
+%s''' % (pn, configopttext)
+
+ if cmake:
+ msg += '''
+
+The cmake %s output for %s follows. After "-- Cache values" you should see a list of variables you can add to EXTRA_OECMAKE (prefixed with -D and suffixed with = followed by the desired value, without any spaces).
+------------------------------------------''' % (helpargs, pn)
+ elif os.path.exists(configurescript):
+ msg += '''
+
+The ./configure %s output for %s follows.
+------------------------------------------''' % (helpargs, pn)
+
+ olddir = os.getcwd()
+ tmppath = tempfile.mkdtemp()
+ with tempfile.NamedTemporaryFile('w', delete=False) as tf:
+ if not args.no_header:
+ tf.write(msg + '\n')
+ tf.close()
+ try:
+ try:
+ cmd = 'cat %s' % tf.name
+ if cmake:
+ cmd += '; cmake %s %s 2>&1' % (helpargs, s)
+ os.chdir(b)
+ elif os.path.exists(configurescript):
+ cmd += '; %s %s' % (configurescript, helpargs)
+ if sys.stdout.isatty() and not args.no_pager:
+ pager = os.environ.get('PAGER', 'less')
+ cmd = '(%s) | %s' % (cmd, pager)
+ subprocess.check_call(cmd, shell=True)
+ except subprocess.CalledProcessError as e:
+ return e.returncode
+ finally:
+ os.chdir(olddir)
+ shutil.rmtree(tmppath)
+ os.remove(tf.name)
+
+
+def register_commands(subparsers, context):
+ """Register devtool subcommands from this plugin"""
+ parser_edit_recipe = subparsers.add_parser('edit-recipe', help='Edit a recipe file',
+ description='Runs the default editor (as specified by the EDITOR variable) on the specified recipe. Note that this will be quicker for recipes in the workspace as the cache does not need to be loaded in that case.',
+ group='working')
+ parser_edit_recipe.add_argument('recipename', help='Recipe to edit')
+ # FIXME drop -a at some point in future
+ parser_edit_recipe.add_argument('--any-recipe', '-a', action="store_true", help='Does nothing (exists for backwards-compatibility)')
+ parser_edit_recipe.set_defaults(func=edit_recipe)
+
+ # Find-recipe
+ parser_find_recipe = subparsers.add_parser('find-recipe', help='Find a recipe file',
+ description='Finds a recipe file. Note that this will be quicker for recipes in the workspace as the cache does not need to be loaded in that case.',
+ group='working')
+ parser_find_recipe.add_argument('recipename', help='Recipe to find')
+ # FIXME drop -a at some point in future
+ parser_find_recipe.add_argument('--any-recipe', '-a', action="store_true", help='Does nothing (exists for backwards-compatibility)')
+ parser_find_recipe.set_defaults(func=find_recipe)
+
+ # NOTE: Needed to override the usage string here since the default
+ # gets the order wrong - recipename must come before --arg
+ parser_configure_help = subparsers.add_parser('configure-help', help='Get help on configure script options',
+ usage='devtool configure-help [options] recipename [--arg ...]',
+ description='Displays the help for the configure script for the specified recipe (i.e. runs ./configure --help) prefaced by a header describing the current options being specified. Output is piped through less (or whatever PAGER is set to, if set) for easy browsing.',
+ group='working')
+ parser_configure_help.add_argument('recipename', help='Recipe to show configure help for')
+ parser_configure_help.add_argument('-p', '--no-pager', help='Disable paged output', action="store_true")
+ parser_configure_help.add_argument('-n', '--no-header', help='Disable explanatory header text', action="store_true")
+ parser_configure_help.add_argument('--arg', help='Pass remaining arguments to the configure script instead of --help (useful if the script has additional help options)', nargs=argparse.REMAINDER)
+ parser_configure_help.set_defaults(func=configure_help)
diff --git a/scripts/lib/recipetool/append.py b/scripts/lib/recipetool/append.py
index ed7d0d4b27..88ed8c5f01 100644
--- a/scripts/lib/recipetool/append.py
+++ b/scripts/lib/recipetool/append.py
@@ -2,18 +2,8 @@
#
# Copyright (C) 2015 Intel Corporation
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
+# SPDX-License-Identifier: GPL-2.0-only
#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import sys
import os
@@ -33,10 +23,6 @@ logger = logging.getLogger('recipetool')
tinfoil = None
-def plugin_init(pluginlist):
- # Don't need to do anything here right now, but plugins must have this function defined
- pass
-
def tinfoil_init(instance):
global tinfoil
tinfoil = instance
@@ -52,7 +38,7 @@ def find_target_file(targetpath, d, pkglist=None):
"""Find the recipe installing the specified target path, optionally limited to a select list of packages"""
import json
- pkgdata_dir = d.getVar('PKGDATA_DIR', True)
+ pkgdata_dir = d.getVar('PKGDATA_DIR')
# The mix between /etc and ${sysconfdir} here may look odd, but it is just
# being consistent with usage elsewhere
@@ -63,9 +49,9 @@ def find_target_file(targetpath, d, pkglist=None):
'/etc/group': '/etc/group should be managed through the useradd and extrausers classes',
'/etc/shadow': '/etc/shadow should be managed through the useradd and extrausers classes',
'/etc/gshadow': '/etc/gshadow should be managed through the useradd and extrausers classes',
- '${sysconfdir}/hostname': '${sysconfdir}/hostname contents should be set by setting hostname_pn-base-files = "value" in configuration',}
+ '${sysconfdir}/hostname': '${sysconfdir}/hostname contents should be set by setting hostname:pn-base-files = "value" in configuration',}
- for pthspec, message in invalidtargets.iteritems():
+ for pthspec, message in invalidtargets.items():
if fnmatch.fnmatchcase(targetpath, d.expand(pthspec)):
raise InvalidTargetFileError(d.expand(message))
@@ -86,41 +72,27 @@ def find_target_file(targetpath, d, pkglist=None):
# This does assume that PN comes before other values, but that's a fairly safe assumption
for line in f:
if line.startswith('PN:'):
- pn = line.split(':', 1)[1].strip()
- elif line.startswith('FILES_INFO:'):
- val = line.split(':', 1)[1].strip()
+ pn = line.split(': ', 1)[1].strip()
+ elif line.startswith('FILES_INFO'):
+ val = line.split(': ', 1)[1].strip()
dictval = json.loads(val)
for fullpth in dictval.keys():
if fnmatch.fnmatchcase(fullpth, targetpath):
recipes[targetpath].append(pn)
- elif line.startswith('pkg_preinst_') or line.startswith('pkg_postinst_'):
- scriptval = line.split(':', 1)[1].strip().decode('string_escape')
+ elif line.startswith('pkg_preinst:') or line.startswith('pkg_postinst:'):
+ scriptval = line.split(': ', 1)[1].strip().encode('utf-8').decode('unicode_escape')
if 'update-alternatives --install %s ' % targetpath in scriptval:
recipes[targetpath].append('?%s' % pn)
elif targetpath_re.search(scriptval):
recipes[targetpath].append('!%s' % pn)
return recipes
-def _get_recipe_file(cooker, pn):
- import oe.recipeutils
- recipefile = oe.recipeutils.pn_to_recipe(cooker, pn)
- if not recipefile:
- skipreasons = oe.recipeutils.get_unavailable_reasons(cooker, pn)
- if skipreasons:
- logger.error('\n'.join(skipreasons))
- else:
- logger.error("Unable to find any recipe file matching %s" % pn)
- return recipefile
-
def _parse_recipe(pn, tinfoil):
- import oe.recipeutils
- recipefile = _get_recipe_file(tinfoil.cooker, pn)
- if not recipefile:
- # Error already logged
+ try:
+ rd = tinfoil.parse_recipe(pn)
+ except bb.providers.NoProvider as e:
+ logger.error(str(e))
return None
- append_files = tinfoil.cooker.collection.get_file_appends(recipefile)
- rd = oe.recipeutils.parse_recipe(recipefile, append_files,
- tinfoil.config_data)
return rd
def determine_file_source(targetpath, rd):
@@ -128,8 +100,8 @@ def determine_file_source(targetpath, rd):
import oe.recipeutils
# See if it's in do_install for the recipe
- workdir = rd.getVar('WORKDIR', True)
- src_uri = rd.getVar('SRC_URI', True)
+ workdir = rd.getVar('WORKDIR')
+ src_uri = rd.getVar('SRC_URI')
srcfile = ''
modpatches = []
elements = check_do_install(rd, targetpath)
@@ -139,7 +111,7 @@ def determine_file_source(targetpath, rd):
logger.debug('source path: %s' % srcpath)
if not srcpath.startswith('/'):
# Handle non-absolute path
- srcpath = os.path.abspath(os.path.join(rd.getVarFlag('do_install', 'dirs', True).split()[-1], srcpath))
+ srcpath = os.path.abspath(os.path.join(rd.getVarFlag('do_install', 'dirs').split()[-1], srcpath))
if srcpath.startswith(workdir):
# OK, now we have the source file name, look for it in SRC_URI
workdirfile = os.path.relpath(srcpath, workdir)
@@ -156,7 +128,7 @@ def determine_file_source(targetpath, rd):
# Check patches
srcpatches = []
patchedfiles = oe.recipeutils.get_recipe_patched_files(rd)
- for patch, filelist in patchedfiles.iteritems():
+ for patch, filelist in patchedfiles.items():
for fileitem in filelist:
if fileitem[0] == srcpath:
srcpatches.append((patch, fileitem[1]))
@@ -176,7 +148,7 @@ def get_source_path(cmdelements):
"""Find the source path specified within a command"""
command = cmdelements[0]
if command in ['install', 'cp']:
- helptext = subprocess.check_output('LC_ALL=C %s --help' % command, shell=True)
+ helptext = subprocess.check_output('LC_ALL=C %s --help' % command, shell=True).decode('utf-8')
argopts = ''
argopt_line_re = re.compile('^-([a-zA-Z0-9]), --[a-z-]+=')
for line in helptext.splitlines():
@@ -208,22 +180,22 @@ def get_source_path(cmdelements):
def get_func_deps(func, d):
"""Find the function dependencies of a shell function"""
- deps = bb.codeparser.ShellParser(func, logger).parse_shell(d.getVar(func, True))
- deps |= set((d.getVarFlag(func, "vardeps", True) or "").split())
+ deps = bb.codeparser.ShellParser(func, logger).parse_shell(d.getVar(func))
+ deps |= set((d.getVarFlag(func, "vardeps") or "").split())
funcdeps = []
for dep in deps:
- if d.getVarFlag(dep, 'func', True):
+ if d.getVarFlag(dep, 'func'):
funcdeps.append(dep)
return funcdeps
def check_do_install(rd, targetpath):
"""Look at do_install for a command that installs/copies the specified target path"""
- instpath = os.path.abspath(os.path.join(rd.getVar('D', True), targetpath.lstrip('/')))
- do_install = rd.getVar('do_install', True)
+ instpath = os.path.abspath(os.path.join(rd.getVar('D'), targetpath.lstrip('/')))
+ do_install = rd.getVar('do_install')
# Handle where do_install calls other functions (somewhat crudely, but good enough for this purpose)
deps = get_func_deps('do_install', rd)
for dep in deps:
- do_install = do_install.replace(dep, rd.getVar(dep, True))
+ do_install = do_install.replace(dep, rd.getVar(dep))
# Look backwards through do_install as we want to catch where a later line (perhaps
# from a bbappend) is writing over the top
@@ -256,7 +228,7 @@ def appendfile(args):
if stdout:
logger.debug('file command output: %s' % stdout.rstrip())
if ('executable' in stdout and not 'shell script' in stdout) or 'shared object' in stdout:
- logger.warn('This file looks like it is a binary or otherwise the output of compilation. If it is, you should consider building it properly instead of substituting a binary file directly.')
+ logger.warning('This file looks like it is a binary or otherwise the output of compilation. If it is, you should consider building it properly instead of substituting a binary file directly.')
if args.recipe:
recipes = {args.targetpath: [args.recipe],}
@@ -274,7 +246,7 @@ def appendfile(args):
postinst_pns = []
selectpn = None
- for targetpath, pnlist in recipes.iteritems():
+ for targetpath, pnlist in recipes.items():
for pn in pnlist:
if pn.startswith('?'):
alternative_pns.append(pn[1:])
@@ -293,7 +265,7 @@ def appendfile(args):
if selectpn:
logger.debug('Selecting recipe %s for file %s' % (selectpn, args.targetpath))
if postinst_pns:
- logger.warn('%s be modified by postinstall scripts for the following recipes:\n %s\nThis may or may not be an issue depending on what modifications these postinstall scripts make.' % (args.targetpath, '\n '.join(postinst_pns)))
+ logger.warning('%s be modified by postinstall scripts for the following recipes:\n %s\nThis may or may not be an issue depending on what modifications these postinstall scripts make.' % (args.targetpath, '\n '.join(postinst_pns)))
rd = _parse_recipe(selectpn, tinfoil)
if not rd:
# Error message already shown
@@ -304,12 +276,12 @@ def appendfile(args):
sourcetype, sourcepath = sourcefile.split('://', 1)
logger.debug('Original source file is %s (%s)' % (sourcepath, sourcetype))
if sourcetype == 'patch':
- logger.warn('File %s is added by the patch %s - you may need to remove or replace this patch in order to replace the file.' % (args.targetpath, sourcepath))
+ logger.warning('File %s is added by the patch %s - you may need to remove or replace this patch in order to replace the file.' % (args.targetpath, sourcepath))
sourcepath = None
else:
logger.debug('Unable to determine source file, proceeding anyway')
if modpatches:
- logger.warn('File %s is modified by the following patches:\n %s' % (args.targetpath, '\n '.join(modpatches)))
+ logger.warning('File %s is modified by the following patches:\n %s' % (args.targetpath, '\n '.join(modpatches)))
if instelements and sourcepath:
install = None
@@ -340,26 +312,28 @@ def appendfile(args):
def appendsrc(args, files, rd, extralines=None):
import oe.recipeutils
- srcdir = rd.getVar('S', True)
- workdir = rd.getVar('WORKDIR', True)
+ srcdir = rd.getVar('S')
+ workdir = rd.getVar('WORKDIR')
import bb.fetch
simplified = {}
- src_uri = rd.getVar('SRC_URI', True).split()
+ src_uri = rd.getVar('SRC_URI').split()
for uri in src_uri:
+ if uri.endswith(';'):
+ uri = uri[:-1]
simple_uri = bb.fetch.URI(uri)
simple_uri.params = {}
simplified[str(simple_uri)] = uri
copyfiles = {}
extralines = extralines or []
- for newfile, srcfile in files.iteritems():
+ for newfile, srcfile in files.items():
src_destdir = os.path.dirname(srcfile)
if not args.use_workdir:
- if rd.getVar('S', True) == rd.getVar('STAGING_KERNEL_DIR', True):
+ if rd.getVar('S') == rd.getVar('STAGING_KERNEL_DIR'):
srcdir = os.path.join(workdir, 'git')
if not bb.data.inherits_class('kernel-yocto', rd):
- logger.warn('S == STAGING_KERNEL_DIR and non-kernel-yocto, unable to determine path to srcdir, defaulting to ${WORKDIR}/git')
+ logger.warning('S == STAGING_KERNEL_DIR and non-kernel-yocto, unable to determine path to srcdir, defaulting to ${WORKDIR}/git')
src_destdir = os.path.join(os.path.relpath(srcdir, workdir), src_destdir)
src_destdir = os.path.normpath(src_destdir)
@@ -373,9 +347,9 @@ def appendsrc(args, files, rd, extralines=None):
if simple_str in simplified:
existing = simplified[simple_str]
if source_uri != existing:
- logger.warn('{0!r} is already in SRC_URI, with different parameters: {1!r}, not adding'.format(source_uri, existing))
+ logger.warning('{0!r} is already in SRC_URI, with different parameters: {1!r}, not adding'.format(source_uri, existing))
else:
- logger.warn('{0!r} is already in SRC_URI, not adding'.format(source_uri))
+ logger.warning('{0!r} is already in SRC_URI, not adding'.format(source_uri))
else:
extralines.append('SRC_URI += {0}'.format(source_uri))
copyfiles[newfile] = srcfile
@@ -437,7 +411,7 @@ def target_path(targetpath):
return targetpath
-def register_command(subparsers):
+def register_commands(subparsers):
common = argparse.ArgumentParser(add_help=False)
common.add_argument('-m', '--machine', help='Make bbappend changes specific to a machine only', metavar='MACHINE')
common.add_argument('-w', '--wildcard-version', help='Use wildcard to make the bbappend apply to any recipe version', action='store_true')
diff --git a/scripts/lib/recipetool/create.py b/scripts/lib/recipetool/create.py
index ec6e107e62..b6c4564761 100644
--- a/scripts/lib/recipetool/create.py
+++ b/scripts/lib/recipetool/create.py
@@ -1,19 +1,9 @@
# Recipe creation tool - create command plugin
#
-# Copyright (C) 2014-2015 Intel Corporation
+# Copyright (C) 2014-2017 Intel Corporation
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
+# SPDX-License-Identifier: GPL-2.0-only
#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import sys
import os
@@ -21,14 +11,29 @@ import argparse
import glob
import fnmatch
import re
+import json
import logging
import scriptutils
-
+from urllib.parse import urlparse, urldefrag, urlsplit
+import hashlib
+import bb.fetch2
logger = logging.getLogger('recipetool')
tinfoil = None
plugins = None
+def log_error_cond(message, debugonly):
+ if debugonly:
+ logger.debug(message)
+ else:
+ logger.error(message)
+
+def log_info_cond(message, debugonly):
+ if debugonly:
+ logger.debug(message)
+ else:
+ logger.info(message)
+
def plugin_init(pluginlist):
# Take a reference to the list so we can use it later
global plugins
@@ -38,111 +43,585 @@ def tinfoil_init(instance):
global tinfoil
tinfoil = instance
-class RecipeHandler():
+class RecipeHandler(object):
+ recipelibmap = {}
+ recipeheadermap = {}
+ recipecmakefilemap = {}
+ recipebinmap = {}
+
+ def __init__(self):
+ self._devtool = False
+
@staticmethod
- def checkfiles(path, speclist):
+ def load_libmap(d):
+ '''Load library->recipe mapping'''
+ import oe.package
+
+ if RecipeHandler.recipelibmap:
+ return
+ # First build up library->package mapping
+ d2 = bb.data.createCopy(d)
+ d2.setVar("WORKDIR_PKGDATA", "${PKGDATA_DIR}")
+ shlib_providers = oe.package.read_shlib_providers(d2)
+ libdir = d.getVar('libdir')
+ base_libdir = d.getVar('base_libdir')
+ libpaths = list(set([base_libdir, libdir]))
+ libname_re = re.compile(r'^lib(.+)\.so.*$')
+ pkglibmap = {}
+ for lib, item in shlib_providers.items():
+ for path, pkg in item.items():
+ if path in libpaths:
+ res = libname_re.match(lib)
+ if res:
+ libname = res.group(1)
+ if not libname in pkglibmap:
+ pkglibmap[libname] = pkg[0]
+ else:
+ logger.debug('unable to extract library name from %s' % lib)
+
+ # Now turn it into a library->recipe mapping
+ pkgdata_dir = d.getVar('PKGDATA_DIR')
+ for libname, pkg in pkglibmap.items():
+ try:
+ with open(os.path.join(pkgdata_dir, 'runtime', pkg)) as f:
+ for line in f:
+ if line.startswith('PN:'):
+ RecipeHandler.recipelibmap[libname] = line.split(':', 1)[-1].strip()
+ break
+ except IOError as ioe:
+ if ioe.errno == 2:
+ logger.warning('unable to find a pkgdata file for package %s' % pkg)
+ else:
+ raise
+
+ # Some overrides - these should be mapped to the virtual
+ RecipeHandler.recipelibmap['GL'] = 'virtual/libgl'
+ RecipeHandler.recipelibmap['EGL'] = 'virtual/egl'
+ RecipeHandler.recipelibmap['GLESv2'] = 'virtual/libgles2'
+
+ @staticmethod
+ def load_devel_filemap(d):
+ '''Build up development file->recipe mapping'''
+ if RecipeHandler.recipeheadermap:
+ return
+ pkgdata_dir = d.getVar('PKGDATA_DIR')
+ includedir = d.getVar('includedir')
+ cmakedir = os.path.join(d.getVar('libdir'), 'cmake')
+ for pkg in glob.glob(os.path.join(pkgdata_dir, 'runtime', '*-dev')):
+ with open(os.path.join(pkgdata_dir, 'runtime', pkg)) as f:
+ pn = None
+ headers = []
+ cmakefiles = []
+ for line in f:
+ if line.startswith('PN:'):
+ pn = line.split(':', 1)[-1].strip()
+ elif line.startswith('FILES_INFO:%s:' % pkg):
+ val = line.split(': ', 1)[1].strip()
+ dictval = json.loads(val)
+ for fullpth in sorted(dictval):
+ if fullpth.startswith(includedir) and fullpth.endswith('.h'):
+ headers.append(os.path.relpath(fullpth, includedir))
+ elif fullpth.startswith(cmakedir) and fullpth.endswith('.cmake'):
+ cmakefiles.append(os.path.relpath(fullpth, cmakedir))
+ if pn and headers:
+ for header in headers:
+ RecipeHandler.recipeheadermap[header] = pn
+ if pn and cmakefiles:
+ for fn in cmakefiles:
+ RecipeHandler.recipecmakefilemap[fn] = pn
+
+ @staticmethod
+ def load_binmap(d):
+ '''Build up native binary->recipe mapping'''
+ if RecipeHandler.recipebinmap:
+ return
+ sstate_manifests = d.getVar('SSTATE_MANIFESTS')
+ staging_bindir_native = d.getVar('STAGING_BINDIR_NATIVE')
+ build_arch = d.getVar('BUILD_ARCH')
+ fileprefix = 'manifest-%s-' % build_arch
+ for fn in glob.glob(os.path.join(sstate_manifests, '%s*-native.populate_sysroot' % fileprefix)):
+ with open(fn, 'r') as f:
+ pn = os.path.basename(fn).rsplit('.', 1)[0][len(fileprefix):]
+ for line in f:
+ if line.startswith(staging_bindir_native):
+ prog = os.path.basename(line.rstrip())
+ RecipeHandler.recipebinmap[prog] = pn
+
+ @staticmethod
+ def checkfiles(path, speclist, recursive=False, excludedirs=None):
results = []
- for spec in speclist:
- results.extend(glob.glob(os.path.join(path, spec)))
+ if recursive:
+ for root, dirs, files in os.walk(path, topdown=True):
+ if excludedirs:
+ dirs[:] = [d for d in dirs if d not in excludedirs]
+ for fn in files:
+ for spec in speclist:
+ if fnmatch.fnmatch(fn, spec):
+ results.append(os.path.join(root, fn))
+ else:
+ for spec in speclist:
+ results.extend(glob.glob(os.path.join(path, spec)))
return results
- def genfunction(self, outlines, funcname, content):
- outlines.append('%s () {' % funcname)
+ @staticmethod
+ def handle_depends(libdeps, pcdeps, deps, outlines, values, d):
+ if pcdeps:
+ recipemap = read_pkgconfig_provides(d)
+ if libdeps:
+ RecipeHandler.load_libmap(d)
+
+ ignorelibs = ['socket']
+ ignoredeps = ['gcc-runtime', 'glibc', 'uclibc', 'musl', 'tar-native', 'binutils-native', 'coreutils-native']
+
+ unmappedpc = []
+ pcdeps = list(set(pcdeps))
+ for pcdep in pcdeps:
+ if isinstance(pcdep, str):
+ recipe = recipemap.get(pcdep, None)
+ if recipe:
+ deps.append(recipe)
+ else:
+ if not pcdep.startswith('$'):
+ unmappedpc.append(pcdep)
+ else:
+ for item in pcdep:
+ recipe = recipemap.get(pcdep, None)
+ if recipe:
+ deps.append(recipe)
+ break
+ else:
+ unmappedpc.append('(%s)' % ' or '.join(pcdep))
+
+ unmappedlibs = []
+ for libdep in libdeps:
+ if isinstance(libdep, tuple):
+ lib, header = libdep
+ else:
+ lib = libdep
+ header = None
+
+ if lib in ignorelibs:
+ logger.debug('Ignoring library dependency %s' % lib)
+ continue
+
+ recipe = RecipeHandler.recipelibmap.get(lib, None)
+ if recipe:
+ deps.append(recipe)
+ elif recipe is None:
+ if header:
+ RecipeHandler.load_devel_filemap(d)
+ recipe = RecipeHandler.recipeheadermap.get(header, None)
+ if recipe:
+ deps.append(recipe)
+ elif recipe is None:
+ unmappedlibs.append(lib)
+ else:
+ unmappedlibs.append(lib)
+
+ deps = set(deps).difference(set(ignoredeps))
+
+ if unmappedpc:
+ outlines.append('# NOTE: unable to map the following pkg-config dependencies: %s' % ' '.join(unmappedpc))
+ outlines.append('# (this is based on recipes that have previously been built and packaged)')
+
+ if unmappedlibs:
+ outlines.append('# NOTE: the following library dependencies are unknown, ignoring: %s' % ' '.join(list(set(unmappedlibs))))
+ outlines.append('# (this is based on recipes that have previously been built and packaged)')
+
+ if deps:
+ values['DEPENDS'] = ' '.join(deps)
+
+ @staticmethod
+ def genfunction(outlines, funcname, content, python=False, forcespace=False):
+ if python:
+ prefix = 'python '
+ else:
+ prefix = ''
+ outlines.append('%s%s () {' % (prefix, funcname))
+ if python or forcespace:
+ indent = ' '
+ else:
+ indent = '\t'
+ addnoop = not python
for line in content:
- outlines.append('\t%s' % line)
+ outlines.append('%s%s' % (indent, line))
+ if addnoop:
+ strippedline = line.lstrip()
+ if strippedline and not strippedline.startswith('#'):
+ addnoop = False
+ if addnoop:
+ # Without this there'll be a syntax error
+ outlines.append('%s:' % indent)
outlines.append('}')
outlines.append('')
- def process(self, srctree, classes, lines_before, lines_after, handled):
+ def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
return False
+def validate_pv(pv):
+ if not pv or '_version' in pv.lower() or pv[0] not in '0123456789':
+ return False
+ return True
-def fetch_source(uri, destdir, srcrev):
- import bb.data
- bb.utils.mkdirhier(destdir)
- localdata = bb.data.createCopy(tinfoil.config_data)
- bb.data.update_data(localdata)
- localdata.setVar('BB_STRICT_CHECKSUM', '')
- localdata.setVar('SRCREV', srcrev)
- ret = (None, None)
- olddir = os.getcwd()
- try:
- fetcher = bb.fetch2.Fetch([uri], localdata)
- for u in fetcher.ud:
- ud = fetcher.ud[u]
- ud.ignore_checksums = True
- fetcher.download()
- fetcher.unpack(destdir)
- for u in fetcher.ud:
- ud = fetcher.ud[u]
- if ud.method.recommends_checksum(ud):
- md5value = bb.utils.md5_file(ud.localpath)
- sha256value = bb.utils.sha256_file(ud.localpath)
- ret = (md5value, sha256value)
- except bb.fetch2.BBFetchException, e:
- raise bb.build.FuncFailed(e)
- finally:
- os.chdir(olddir)
- return ret
+def determine_from_filename(srcfile):
+ """Determine name and version from a filename"""
+ if is_package(srcfile):
+ # Force getting the value from the package metadata
+ return None, None
+
+ if '.tar.' in srcfile:
+ namepart = srcfile.split('.tar.')[0]
+ else:
+ namepart = os.path.splitext(srcfile)[0]
+ namepart = namepart.lower().replace('_', '-')
+ if namepart.endswith('.src'):
+ namepart = namepart[:-4]
+ if namepart.endswith('.orig'):
+ namepart = namepart[:-5]
+ splitval = namepart.split('-')
+ logger.debug('determine_from_filename: split name %s into: %s' % (srcfile, splitval))
+
+ ver_re = re.compile('^v?[0-9]')
+
+ pv = None
+ pn = None
+ if len(splitval) == 1:
+ # Try to split the version out if there is no separator (or a .)
+ res = re.match('^([^0-9]+)([0-9.]+.*)$', namepart)
+ if res:
+ if len(res.group(1)) > 1 and len(res.group(2)) > 1:
+ pn = res.group(1).rstrip('.')
+ pv = res.group(2)
+ else:
+ pn = namepart
+ else:
+ if splitval[-1] in ['source', 'src']:
+ splitval.pop()
+ if len(splitval) > 2 and re.match('^(alpha|beta|stable|release|rc[0-9]|pre[0-9]|p[0-9]|[0-9]{8})', splitval[-1]) and ver_re.match(splitval[-2]):
+ pv = '-'.join(splitval[-2:])
+ if pv.endswith('-release'):
+ pv = pv[:-8]
+ splitval = splitval[:-2]
+ elif ver_re.match(splitval[-1]):
+ pv = splitval.pop()
+ pn = '-'.join(splitval)
+ if pv and pv.startswith('v'):
+ pv = pv[1:]
+ logger.debug('determine_from_filename: name = "%s" version = "%s"' % (pn, pv))
+ return (pn, pv)
+
+def determine_from_url(srcuri):
+ """Determine name and version from a URL"""
+ pn = None
+ pv = None
+ parseres = urlparse(srcuri.lower().split(';', 1)[0])
+ if parseres.path:
+ if 'github.com' in parseres.netloc:
+ res = re.search(r'.*/(.*?)/archive/(.*)-final\.(tar|zip)', parseres.path)
+ if res:
+ pn = res.group(1).strip().replace('_', '-')
+ pv = res.group(2).strip().replace('_', '.')
+ else:
+ res = re.search(r'.*/(.*?)/archive/v?(.*)\.(tar|zip)', parseres.path)
+ if res:
+ pn = res.group(1).strip().replace('_', '-')
+ pv = res.group(2).strip().replace('_', '.')
+ elif 'bitbucket.org' in parseres.netloc:
+ res = re.search(r'.*/(.*?)/get/[a-zA-Z_-]*([0-9][0-9a-zA-Z_.]*)\.(tar|zip)', parseres.path)
+ if res:
+ pn = res.group(1).strip().replace('_', '-')
+ pv = res.group(2).strip().replace('_', '.')
+
+ if not pn and not pv:
+ if parseres.scheme not in ['git', 'gitsm', 'svn', 'hg']:
+ srcfile = os.path.basename(parseres.path.rstrip('/'))
+ pn, pv = determine_from_filename(srcfile)
+ elif parseres.scheme in ['git', 'gitsm']:
+ pn = os.path.basename(parseres.path.rstrip('/')).lower().replace('_', '-')
+ if pn.endswith('.git'):
+ pn = pn[:-4]
+
+ logger.debug('Determined from source URL: name = "%s", version = "%s"' % (pn, pv))
+ return (pn, pv)
def supports_srcrev(uri):
localdata = bb.data.createCopy(tinfoil.config_data)
# This is a bit sad, but if you don't have this set there can be some
# odd interactions with the urldata cache which lead to errors
localdata.setVar('SRCREV', '${AUTOREV}')
- bb.data.update_data(localdata)
- fetcher = bb.fetch2.Fetch([uri], localdata)
- urldata = fetcher.ud
- for u in urldata:
- if urldata[u].method.supports_srcrev():
+ try:
+ fetcher = bb.fetch2.Fetch([uri], localdata)
+ urldata = fetcher.ud
+ for u in urldata:
+ if urldata[u].method.supports_srcrev():
+ return True
+ except bb.fetch2.FetchError as e:
+ logger.debug('FetchError in supports_srcrev: %s' % str(e))
+ # Fall back to basic check
+ if uri.startswith(('git://', 'gitsm://')):
return True
return False
+def reformat_git_uri(uri):
+ '''Convert any http[s]://....git URI into git://...;protocol=http[s]'''
+ checkuri = uri.split(';', 1)[0]
+ if checkuri.endswith('.git') or '/git/' in checkuri or re.match('https?://github.com/[^/]+/[^/]+/?$', checkuri):
+ # Appends scheme if the scheme is missing
+ if not '://' in uri:
+ uri = 'git://' + uri
+ scheme, host, path, user, pswd, parms = bb.fetch2.decodeurl(uri)
+ # Detection mechanism, this is required due to certain URL are formatter with ":" rather than "/"
+ # which causes decodeurl to fail getting the right host and path
+ if len(host.split(':')) > 1:
+ splitslash = host.split(':')
+ # Port number should not be split from host
+ if not re.match('^[0-9]+$', splitslash[1]):
+ host = splitslash[0]
+ path = '/' + splitslash[1] + path
+ #Algorithm:
+ # if user is defined, append protocol=ssh or if a protocol is defined, then honor the user-defined protocol
+ # if no user & password is defined, check for scheme type and append the protocol with the scheme type
+ # finally if protocols or if the url is well-formed, do nothing and rejoin everything back to normal
+ # Need to repackage the arguments for encodeurl, the format is: (scheme, host, path, user, password, OrderedDict([('key', 'value')]))
+ if user:
+ if not 'protocol' in parms:
+ parms.update({('protocol', 'ssh')})
+ elif (scheme == "http" or scheme == 'https' or scheme == 'ssh') and not ('protocol' in parms):
+ parms.update({('protocol', scheme)})
+ # We assume 'master' branch if not set
+ if not 'branch' in parms:
+ parms.update({('branch', 'master')})
+ # Always append 'git://'
+ fUrl = bb.fetch2.encodeurl(('git', host, path, user, pswd, parms))
+ return fUrl
+ else:
+ return uri
+
+def is_package(url):
+ '''Check if a URL points to a package'''
+ checkurl = url.split(';', 1)[0]
+ if checkurl.endswith(('.deb', '.ipk', '.rpm', '.srpm')):
+ return True
+ return False
+
def create_recipe(args):
import bb.process
import tempfile
import shutil
+ import oe.recipeutils
pkgarch = ""
if args.machine:
pkgarch = "${MACHINE_ARCH}"
- checksums = (None, None)
+ extravalues = {}
+ checksums = {}
tempsrc = ''
+ source = args.source
srcsubdir = ''
srcrev = '${AUTOREV}'
- if '://' in args.source:
+ srcbranch = ''
+ scheme = ''
+ storeTagName = ''
+ pv_srcpv = False
+
+ if os.path.isfile(source):
+ source = 'file://%s' % os.path.abspath(source)
+
+ if scriptutils.is_src_url(source):
+ # Warn about github archive URLs
+ if re.match(r'https?://github.com/[^/]+/[^/]+/archive/.+(\.tar\..*|\.zip)$', source):
+ logger.warning('github archive files are not guaranteed to be stable and may be re-generated over time. If the latter occurs, the checksums will likely change and the recipe will fail at do_fetch. It is recommended that you point to an actual commit or tag in the repository instead (using the repository URL in conjunction with the -S/--srcrev option).')
# Fetch a URL
- srcuri = args.source
+ fetchuri = reformat_git_uri(urldefrag(source)[0])
+ if args.binary:
+ # Assume the archive contains the directory structure verbatim
+ # so we need to extract to a subdirectory
+ fetchuri += ';subdir=${BP}'
+ srcuri = fetchuri
rev_re = re.compile(';rev=([^;]+)')
res = rev_re.search(srcuri)
if res:
+ if args.srcrev:
+ logger.error('rev= parameter and -S/--srcrev option cannot both be specified - use one or the other')
+ sys.exit(1)
+ if args.autorev:
+ logger.error('rev= parameter and -a/--autorev option cannot both be specified - use one or the other')
+ sys.exit(1)
srcrev = res.group(1)
srcuri = rev_re.sub('', srcuri)
- tempsrc = tempfile.mkdtemp(prefix='recipetool-')
- srctree = tempsrc
- logger.info('Fetching %s...' % srcuri)
- checksums = fetch_source(args.source, srctree, srcrev)
- dirlist = os.listdir(srctree)
- if 'git.indirectionsymlink' in dirlist:
- dirlist.remove('git.indirectionsymlink')
- if len(dirlist) == 1 and os.path.isdir(os.path.join(srctree, dirlist[0])):
- # We unpacked a single directory, so we should use that
- srcsubdir = dirlist[0]
- srctree = os.path.join(srctree, srcsubdir)
+ elif args.srcrev:
+ srcrev = args.srcrev
+
+ # Check whether users provides any branch info in fetchuri.
+ # If true, we will skip all branch checking process to honor all user's input.
+ scheme, network, path, user, passwd, params = bb.fetch2.decodeurl(fetchuri)
+ srcbranch = params.get('branch')
+ if args.srcbranch:
+ if srcbranch:
+ logger.error('branch= parameter and -B/--srcbranch option cannot both be specified - use one or the other')
+ sys.exit(1)
+ srcbranch = args.srcbranch
+ params['branch'] = srcbranch
+ nobranch = params.get('nobranch')
+ if nobranch and srcbranch:
+ logger.error('nobranch= cannot be used if you specify a branch')
+ sys.exit(1)
+ tag = params.get('tag')
+ if not srcbranch and not nobranch and srcrev != '${AUTOREV}':
+ # Append nobranch=1 in the following conditions:
+ # 1. User did not set 'branch=' in srcuri, and
+ # 2. User did not set 'nobranch=1' in srcuri, and
+ # 3. Source revision is not '${AUTOREV}'
+ params['nobranch'] = '1'
+ if tag:
+ # Keep a copy of tag and append nobranch=1 then remove tag from URL.
+ # Bitbake fetcher unable to fetch when {AUTOREV} and tag is set at the same time.
+ storeTagName = params['tag']
+ params['nobranch'] = '1'
+ del params['tag']
+ fetchuri = bb.fetch2.encodeurl((scheme, network, path, user, passwd, params))
+
+ tmpparent = tinfoil.config_data.getVar('BASE_WORKDIR')
+ bb.utils.mkdirhier(tmpparent)
+ tempsrc = tempfile.mkdtemp(prefix='recipetool-', dir=tmpparent)
+ srctree = os.path.join(tempsrc, 'source')
+
+ try:
+ checksums, ftmpdir = scriptutils.fetch_url(tinfoil, fetchuri, srcrev, srctree, logger, preserve_tmp=args.keep_temp)
+ except scriptutils.FetchUrlFailure as e:
+ logger.error(str(e))
+ sys.exit(1)
+
+ if ftmpdir and args.keep_temp:
+ logger.info('Fetch temp directory is %s' % ftmpdir)
+
+ dirlist = scriptutils.filter_src_subdirs(srctree)
+ logger.debug('Directory listing (excluding filtered out):\n %s' % '\n '.join(dirlist))
+ if len(dirlist) == 1:
+ singleitem = os.path.join(srctree, dirlist[0])
+ if os.path.isdir(singleitem):
+ # We unpacked a single directory, so we should use that
+ srcsubdir = dirlist[0]
+ srctree = os.path.join(srctree, srcsubdir)
+ else:
+ check_single_file(dirlist[0], fetchuri)
+ elif len(dirlist) == 0:
+ if '/' in fetchuri:
+ fn = os.path.join(tinfoil.config_data.getVar('DL_DIR'), fetchuri.split('/')[-1])
+ if os.path.isfile(fn):
+ check_single_file(fn, fetchuri)
+ # If we've got to here then there's no source so we might as well give up
+ logger.error('URL %s resulted in an empty source tree' % fetchuri)
+ sys.exit(1)
+
+ # We need this checking mechanism to improve the recipe created by recipetool and devtool
+ # is able to parse and build by bitbake.
+ # If there is no input for branch name, then check for branch name with SRCREV provided.
+ if not srcbranch and not nobranch and srcrev and (srcrev != '${AUTOREV}') and scheme in ['git', 'gitsm']:
+ try:
+ cmd = 'git branch -r --contains'
+ check_branch, check_branch_err = bb.process.run('%s %s' % (cmd, srcrev), cwd=srctree)
+ except bb.process.ExecutionError as err:
+ logger.error(str(err))
+ sys.exit(1)
+ get_branch = [x.strip() for x in check_branch.splitlines()]
+ # Remove HEAD reference point and drop remote prefix
+ get_branch = [x.split('/', 1)[1] for x in get_branch if not x.startswith('origin/HEAD')]
+ if 'master' in get_branch:
+ # If it is master, we do not need to append 'branch=master' as this is default.
+ # Even with the case where get_branch has multiple objects, if 'master' is one
+ # of them, we should default take from 'master'
+ srcbranch = ''
+ elif len(get_branch) == 1:
+ # If 'master' isn't in get_branch and get_branch contains only ONE object, then store result into 'srcbranch'
+ srcbranch = get_branch[0]
+ else:
+ # If get_branch contains more than one objects, then display error and exit.
+ mbrch = '\n ' + '\n '.join(get_branch)
+ logger.error('Revision %s was found on multiple branches: %s\nPlease provide the correct branch with -B/--srcbranch' % (srcrev, mbrch))
+ sys.exit(1)
+
+ # Since we might have a value in srcbranch, we need to
+ # recontruct the srcuri to include 'branch' in params.
+ scheme, network, path, user, passwd, params = bb.fetch2.decodeurl(srcuri)
+ if srcbranch:
+ params['branch'] = srcbranch
+
+ if storeTagName and scheme in ['git', 'gitsm']:
+ # Check srcrev using tag and check validity of the tag
+ cmd = ('git rev-parse --verify %s' % (storeTagName))
+ try:
+ check_tag, check_tag_err = bb.process.run('%s' % cmd, cwd=srctree)
+ srcrev = check_tag.split()[0]
+ except bb.process.ExecutionError as err:
+ logger.error(str(err))
+ logger.error("Possibly wrong tag name is provided")
+ sys.exit(1)
+ # Drop tag from srcuri as it will have conflicts with SRCREV during recipe parse.
+ del params['tag']
+ srcuri = bb.fetch2.encodeurl((scheme, network, path, user, passwd, params))
+
+ if os.path.exists(os.path.join(srctree, '.gitmodules')) and srcuri.startswith('git://'):
+ srcuri = 'gitsm://' + srcuri[6:]
+ logger.info('Fetching submodules...')
+ bb.process.run('git submodule update --init --recursive', cwd=srctree)
+
+ if is_package(fetchuri):
+ localdata = bb.data.createCopy(tinfoil.config_data)
+ pkgfile = bb.fetch2.localpath(fetchuri, localdata)
+ if pkgfile:
+ tmpfdir = tempfile.mkdtemp(prefix='recipetool-')
+ try:
+ if pkgfile.endswith(('.deb', '.ipk')):
+ stdout, _ = bb.process.run('ar x %s' % pkgfile, cwd=tmpfdir)
+ stdout, _ = bb.process.run('tar xf control.tar.gz', cwd=tmpfdir)
+ values = convert_debian(tmpfdir)
+ extravalues.update(values)
+ elif pkgfile.endswith(('.rpm', '.srpm')):
+ stdout, _ = bb.process.run('rpm -qp --xml %s > pkginfo.xml' % pkgfile, cwd=tmpfdir)
+ values = convert_rpm_xml(os.path.join(tmpfdir, 'pkginfo.xml'))
+ extravalues.update(values)
+ finally:
+ shutil.rmtree(tmpfdir)
else:
# Assume we're pointing to an existing source tree
if args.extract_to:
logger.error('--extract-to cannot be specified if source is a directory')
sys.exit(1)
- if not os.path.isdir(args.source):
- logger.error('Invalid source directory %s' % args.source)
+ if not os.path.isdir(source):
+ logger.error('Invalid source directory %s' % source)
sys.exit(1)
+ srctree = source
srcuri = ''
- srctree = args.source
+ if os.path.exists(os.path.join(srctree, '.git')):
+ # Try to get upstream repo location from origin remote
+ try:
+ stdout, _ = bb.process.run('git remote -v', cwd=srctree, shell=True)
+ except bb.process.ExecutionError as e:
+ stdout = None
+ if stdout:
+ for line in stdout.splitlines():
+ splitline = line.split()
+ if len(splitline) > 1:
+ if splitline[0] == 'origin' and scriptutils.is_src_url(splitline[1]):
+ srcuri = reformat_git_uri(splitline[1])
+ srcsubdir = 'git'
+ break
+
+ if args.src_subdir:
+ srcsubdir = os.path.join(srcsubdir, args.src_subdir)
+ srctree_use = os.path.abspath(os.path.join(srctree, args.src_subdir))
+ else:
+ srctree_use = os.path.abspath(srctree)
- outfile = args.outfile
+ if args.outfile and os.path.isdir(args.outfile):
+ outfile = None
+ outdir = args.outfile
+ else:
+ outfile = args.outfile
+ outdir = None
if outfile and outfile != '-':
if os.path.exists(outfile):
logger.error('Output file %s already exists' % outfile)
@@ -154,81 +633,78 @@ def create_recipe(args):
lines_before.append('# Recipe created by %s' % os.path.basename(sys.argv[0]))
lines_before.append('# This is the basis of a recipe and may need further editing in order to be fully functional.')
lines_before.append('# (Feel free to remove these comments when editing.)')
- lines_before.append('#')
-
- licvalues = guess_license(srctree)
- lic_files_chksum = []
- if licvalues:
- licenses = []
- for licvalue in licvalues:
- if not licvalue[0] in licenses:
- licenses.append(licvalue[0])
- lic_files_chksum.append('file://%s;md5=%s' % (licvalue[1], licvalue[2]))
- lines_before.append('# WARNING: the following LICENSE and LIC_FILES_CHKSUM values are best guesses - it is')
- lines_before.append('# your responsibility to verify that the values are complete and correct.')
- if len(licvalues) > 1:
- lines_before.append('#')
- lines_before.append('# NOTE: multiple licenses have been detected; if that is correct you should separate')
- lines_before.append('# these in the LICENSE value using & if the multiple licenses all apply, or | if there')
- lines_before.append('# is a choice between the multiple licenses. If in doubt, check the accompanying')
- lines_before.append('# documentation to determine which situation is applicable.')
- else:
- lines_before.append('# Unable to find any files that looked like license statements. Check the accompanying')
- lines_before.append('# documentation and source headers and set LICENSE and LIC_FILES_CHKSUM accordingly.')
- lines_before.append('#')
- lines_before.append('# NOTE: LICENSE is being set to "CLOSED" to allow you to at least start building - if')
- lines_before.append('# this is not accurate with respect to the licensing of the software being built (it')
- lines_before.append('# will not be in most cases) you must specify the correct value before using this')
- lines_before.append('# recipe for anything other than initial testing/development!')
- licenses = ['CLOSED']
- lines_before.append('LICENSE = "%s"' % ' '.join(licenses))
- lines_before.append('LIC_FILES_CHKSUM = "%s"' % ' \\\n '.join(lic_files_chksum))
+ # We need a blank line here so that patch_recipe_lines can rewind before the LICENSE comments
lines_before.append('')
+ # We'll come back and replace this later in handle_license_vars()
+ lines_before.append('##LICENSE_PLACEHOLDER##')
+
+ handled = []
+ classes = []
+
# FIXME This is kind of a hack, we probably ought to be using bitbake to do this
- # we'd also want a way to automatically set outfile based upon auto-detecting these values from the source if possible
- recipefn = os.path.splitext(os.path.basename(outfile))[0]
- fnsplit = recipefn.split('_')
- if len(fnsplit) > 1:
- pn = fnsplit[0]
- pv = fnsplit[1]
- else:
- pn = recipefn
- pv = None
+ pn = None
+ pv = None
+ if outfile:
+ recipefn = os.path.splitext(os.path.basename(outfile))[0]
+ fnsplit = recipefn.split('_')
+ if len(fnsplit) > 1:
+ pn = fnsplit[0]
+ pv = fnsplit[1]
+ else:
+ pn = recipefn
if args.version:
pv = args.version
+ if args.name:
+ pn = args.name
+ if args.name.endswith('-native'):
+ if args.also_native:
+ logger.error('--also-native cannot be specified for a recipe named *-native (*-native denotes a recipe that is already only for native) - either remove the -native suffix from the name or drop --also-native')
+ sys.exit(1)
+ classes.append('native')
+ elif args.name.startswith('nativesdk-'):
+ if args.also_native:
+ logger.error('--also-native cannot be specified for a recipe named nativesdk-* (nativesdk-* denotes a recipe that is already only for nativesdk)')
+ sys.exit(1)
+ classes.append('nativesdk')
+
if pv and pv not in 'git svn hg'.split():
realpv = pv
else:
realpv = None
- if srcuri:
- if realpv:
- srcuri = srcuri.replace(realpv, '${PV}')
- else:
+ if not srcuri:
lines_before.append('# No information for SRC_URI yet (only an external source tree was specified)')
lines_before.append('SRC_URI = "%s"' % srcuri)
- (md5value, sha256value) = checksums
- if md5value:
- lines_before.append('SRC_URI[md5sum] = "%s"' % md5value)
- if sha256value:
- lines_before.append('SRC_URI[sha256sum] = "%s"' % sha256value)
+ for key, value in sorted(checksums.items()):
+ lines_before.append('SRC_URI[%s] = "%s"' % (key, value))
if srcuri and supports_srcrev(srcuri):
lines_before.append('')
lines_before.append('# Modify these as desired')
- lines_before.append('PV = "%s+git${SRCPV}"' % (realpv or '1.0'))
+ # Note: we have code to replace realpv further down if it gets set to some other value
+ scheme, _, _, _, _, _ = bb.fetch2.decodeurl(srcuri)
+ if scheme in ['git', 'gitsm']:
+ srcpvprefix = 'git'
+ elif scheme == 'svn':
+ srcpvprefix = 'svnr'
+ else:
+ srcpvprefix = scheme
+ lines_before.append('PV = "%s+%s${SRCPV}"' % (realpv or '1.0', srcpvprefix))
+ pv_srcpv = True
+ if not args.autorev and srcrev == '${AUTOREV}':
+ if os.path.exists(os.path.join(srctree, '.git')):
+ (stdout, _) = bb.process.run('git rev-parse HEAD', cwd=srctree)
+ srcrev = stdout.rstrip()
lines_before.append('SRCREV = "%s"' % srcrev)
+ if args.provides:
+ lines_before.append('PROVIDES = "%s"' % args.provides)
lines_before.append('')
- if srcsubdir and pv:
- if srcsubdir == "%s-%s" % (pn, pv):
- # This would be the default, so we don't need to set S in the recipe
- srcsubdir = ''
- if srcsubdir:
- if pv and pv not in 'git svn hg'.split():
- srcsubdir = srcsubdir.replace(pv, '${PV}')
+ if srcsubdir and not args.binary:
+ # (for binary packages we explicitly specify subdir= when fetching to
+ # match the default value of S, so we don't need to set it in that case)
lines_before.append('S = "${WORKDIR}/%s"' % srcsubdir)
lines_before.append('')
@@ -236,98 +712,491 @@ def create_recipe(args):
lines_after.append('PACKAGE_ARCH = "%s"' % pkgarch)
lines_after.append('')
+ if args.binary:
+ lines_after.append('INSANE_SKIP:${PN} += "already-stripped"')
+ lines_after.append('')
+
+ if args.npm_dev:
+ extravalues['NPM_INSTALL_DEV'] = 1
+
# Find all plugins that want to register handlers
- handlers = []
+ logger.debug('Loading recipe handlers')
+ raw_handlers = []
for plugin in plugins:
if hasattr(plugin, 'register_recipe_handlers'):
- plugin.register_recipe_handlers(handlers)
+ plugin.register_recipe_handlers(raw_handlers)
+ # Sort handlers by priority
+ handlers = []
+ for i, handler in enumerate(raw_handlers):
+ if isinstance(handler, tuple):
+ handlers.append((handler[0], handler[1], i))
+ else:
+ handlers.append((handler, 0, i))
+ handlers.sort(key=lambda item: (item[1], -item[2]), reverse=True)
+ for handler, priority, _ in handlers:
+ logger.debug('Handler: %s (priority %d)' % (handler.__class__.__name__, priority))
+ setattr(handler, '_devtool', args.devtool)
+ handlers = [item[0] for item in handlers]
# Apply the handlers
- classes = []
- handled = []
+ if args.binary:
+ classes.append('bin_package')
+ handled.append('buildsystem')
+
for handler in handlers:
- handler.process(srctree, classes, lines_before, lines_after, handled)
+ handler.process(srctree_use, classes, lines_before, lines_after, handled, extravalues)
+
+ extrafiles = extravalues.pop('extrafiles', {})
+ extra_pn = extravalues.pop('PN', None)
+ extra_pv = extravalues.pop('PV', None)
+
+ if extra_pv and not realpv:
+ realpv = extra_pv
+ if not validate_pv(realpv):
+ realpv = None
+ else:
+ realpv = realpv.lower().split()[0]
+ if '_' in realpv:
+ realpv = realpv.replace('_', '-')
+ if extra_pn and not pn:
+ pn = extra_pn
+ if pn.startswith('GNU '):
+ pn = pn[4:]
+ if ' ' in pn:
+ # Probably a descriptive identifier rather than a proper name
+ pn = None
+ else:
+ pn = pn.lower()
+ if '_' in pn:
+ pn = pn.replace('_', '-')
+
+ if srcuri and not realpv or not pn:
+ name_pn, name_pv = determine_from_url(srcuri)
+ if name_pn and not pn:
+ pn = name_pn
+ if name_pv and not realpv:
+ realpv = name_pv
+
+ licvalues = handle_license_vars(srctree_use, lines_before, handled, extravalues, tinfoil.config_data)
+
+ if not outfile:
+ if not pn:
+ log_error_cond('Unable to determine short program name from source tree - please specify name with -N/--name or output file name with -o/--outfile', args.devtool)
+ # devtool looks for this specific exit code, so don't change it
+ sys.exit(15)
+ else:
+ if srcuri and srcuri.startswith(('gitsm://', 'git://', 'hg://', 'svn://')):
+ suffix = srcuri.split(':', 1)[0]
+ if suffix == 'gitsm':
+ suffix = 'git'
+ outfile = '%s_%s.bb' % (pn, suffix)
+ elif realpv:
+ outfile = '%s_%s.bb' % (pn, realpv)
+ else:
+ outfile = '%s.bb' % pn
+ if outdir:
+ outfile = os.path.join(outdir, outfile)
+ # We need to check this again
+ if os.path.exists(outfile):
+ logger.error('Output file %s already exists' % outfile)
+ sys.exit(1)
+
+ # Move any extra files the plugins created to a directory next to the recipe
+ if extrafiles:
+ if outfile == '-':
+ extraoutdir = pn
+ else:
+ extraoutdir = os.path.join(os.path.dirname(outfile), pn)
+ bb.utils.mkdirhier(extraoutdir)
+ for destfn, extrafile in extrafiles.items():
+ shutil.move(extrafile, os.path.join(extraoutdir, destfn))
+
+ lines = lines_before
+ lines_before = []
+ skipblank = True
+ for line in lines:
+ if skipblank:
+ skipblank = False
+ if not line:
+ continue
+ if line.startswith('S = '):
+ if realpv and pv not in 'git svn hg'.split():
+ line = line.replace(realpv, '${PV}')
+ if pn:
+ line = line.replace(pn, '${BPN}')
+ if line == 'S = "${WORKDIR}/${BPN}-${PV}"':
+ skipblank = True
+ continue
+ elif line.startswith('SRC_URI = '):
+ if realpv and not pv_srcpv:
+ line = line.replace(realpv, '${PV}')
+ elif line.startswith('PV = '):
+ if realpv:
+ # Replace the first part of the PV value
+ line = re.sub(r'"[^+]*\+', '"%s+' % realpv, line)
+ lines_before.append(line)
+
+ if args.also_native:
+ lines = lines_after
+ lines_after = []
+ bbclassextend = None
+ for line in lines:
+ if line.startswith('BBCLASSEXTEND ='):
+ splitval = line.split('"')
+ if len(splitval) > 1:
+ bbclassextend = splitval[1].split()
+ if not 'native' in bbclassextend:
+ bbclassextend.insert(0, 'native')
+ line = 'BBCLASSEXTEND = "%s"' % ' '.join(bbclassextend)
+ lines_after.append(line)
+ if not bbclassextend:
+ lines_after.append('BBCLASSEXTEND = "native"')
+
+ postinst = ("postinst", extravalues.pop('postinst', None))
+ postrm = ("postrm", extravalues.pop('postrm', None))
+ preinst = ("preinst", extravalues.pop('preinst', None))
+ prerm = ("prerm", extravalues.pop('prerm', None))
+ funcs = [postinst, postrm, preinst, prerm]
+ for func in funcs:
+ if func[1]:
+ RecipeHandler.genfunction(lines_after, 'pkg_%s_${PN}' % func[0], func[1])
outlines = []
outlines.extend(lines_before)
if classes:
+ if outlines[-1] and not outlines[-1].startswith('#'):
+ outlines.append('')
outlines.append('inherit %s' % ' '.join(classes))
outlines.append('')
outlines.extend(lines_after)
+ if extravalues:
+ _, outlines = oe.recipeutils.patch_recipe_lines(outlines, extravalues, trailing_newline=False)
+
if args.extract_to:
scriptutils.git_convert_standalone_clone(srctree)
+ if os.path.isdir(args.extract_to):
+ # If the directory exists we'll move the temp dir into it instead of
+ # its contents - of course, we could try to always move its contents
+ # but that is a pain if there are symlinks; the simplest solution is
+ # to just remove it first
+ os.rmdir(args.extract_to)
shutil.move(srctree, args.extract_to)
- logger.info('Source extracted to %s' % args.extract_to)
+ if tempsrc == srctree:
+ tempsrc = None
+ log_info_cond('Source extracted to %s' % args.extract_to, args.devtool)
if outfile == '-':
sys.stdout.write('\n'.join(outlines) + '\n')
else:
with open(outfile, 'w') as f:
- f.write('\n'.join(outlines) + '\n')
- logger.info('Recipe %s has been created; further editing may be required to make it fully functional' % outfile)
+ lastline = None
+ for line in outlines:
+ if not lastline and not line:
+ # Skip extra blank lines
+ continue
+ f.write('%s\n' % line)
+ lastline = line
+ log_info_cond('Recipe %s has been created; further editing may be required to make it fully functional' % outfile, args.devtool)
if tempsrc:
- shutil.rmtree(tempsrc)
+ if args.keep_temp:
+ logger.info('Preserving temporary directory %s' % tempsrc)
+ else:
+ shutil.rmtree(tempsrc)
return 0
-def get_license_md5sums(d, static_only=False):
+def check_single_file(fn, fetchuri):
+ """Determine if a single downloaded file is something we can't handle"""
+ with open(fn, 'r', errors='surrogateescape') as f:
+ if '<html' in f.read(100).lower():
+ logger.error('Fetching "%s" returned a single HTML page - check the URL is correct and functional' % fetchuri)
+ sys.exit(1)
+
+def split_value(value):
+ if isinstance(value, str):
+ return value.split()
+ else:
+ return value
+
+def handle_license_vars(srctree, lines_before, handled, extravalues, d):
+ lichandled = [x for x in handled if x[0] == 'license']
+ if lichandled:
+ # Someone else has already handled the license vars, just return their value
+ return lichandled[0][1]
+
+ licvalues = guess_license(srctree, d)
+ licenses = []
+ lic_files_chksum = []
+ lic_unknown = []
+ lines = []
+ if licvalues:
+ for licvalue in licvalues:
+ if not licvalue[0] in licenses:
+ licenses.append(licvalue[0])
+ lic_files_chksum.append('file://%s;md5=%s' % (licvalue[1], licvalue[2]))
+ if licvalue[0] == 'Unknown':
+ lic_unknown.append(licvalue[1])
+ if lic_unknown:
+ lines.append('#')
+ lines.append('# The following license files were not able to be identified and are')
+ lines.append('# represented as "Unknown" below, you will need to check them yourself:')
+ for licfile in lic_unknown:
+ lines.append('# %s' % licfile)
+
+ extra_license = split_value(extravalues.pop('LICENSE', []))
+ if '&' in extra_license:
+ extra_license.remove('&')
+ if extra_license:
+ if licenses == ['Unknown']:
+ licenses = extra_license
+ else:
+ for item in extra_license:
+ if item not in licenses:
+ licenses.append(item)
+ extra_lic_files_chksum = split_value(extravalues.pop('LIC_FILES_CHKSUM', []))
+ for item in extra_lic_files_chksum:
+ if item not in lic_files_chksum:
+ lic_files_chksum.append(item)
+
+ if lic_files_chksum:
+ # We are going to set the vars, so prepend the standard disclaimer
+ lines.insert(0, '# WARNING: the following LICENSE and LIC_FILES_CHKSUM values are best guesses - it is')
+ lines.insert(1, '# your responsibility to verify that the values are complete and correct.')
+ else:
+ # Without LIC_FILES_CHKSUM we set LICENSE = "CLOSED" to allow the
+ # user to get started easily
+ lines.append('# Unable to find any files that looked like license statements. Check the accompanying')
+ lines.append('# documentation and source headers and set LICENSE and LIC_FILES_CHKSUM accordingly.')
+ lines.append('#')
+ lines.append('# NOTE: LICENSE is being set to "CLOSED" to allow you to at least start building - if')
+ lines.append('# this is not accurate with respect to the licensing of the software being built (it')
+ lines.append('# will not be in most cases) you must specify the correct value before using this')
+ lines.append('# recipe for anything other than initial testing/development!')
+ licenses = ['CLOSED']
+
+ if extra_license and sorted(licenses) != sorted(extra_license):
+ lines.append('# NOTE: Original package / source metadata indicates license is: %s' % ' & '.join(extra_license))
+
+ if len(licenses) > 1:
+ lines.append('#')
+ lines.append('# NOTE: multiple licenses have been detected; they have been separated with &')
+ lines.append('# in the LICENSE value for now since it is a reasonable assumption that all')
+ lines.append('# of the licenses apply. If instead there is a choice between the multiple')
+ lines.append('# licenses then you should change the value to separate the licenses with |')
+ lines.append('# instead of &. If there is any doubt, check the accompanying documentation')
+ lines.append('# to determine which situation is applicable.')
+
+ lines.append('LICENSE = "%s"' % ' & '.join(licenses))
+ lines.append('LIC_FILES_CHKSUM = "%s"' % ' \\\n '.join(lic_files_chksum))
+ lines.append('')
+
+ # Replace the placeholder so we get the values in the right place in the recipe file
+ try:
+ pos = lines_before.index('##LICENSE_PLACEHOLDER##')
+ except ValueError:
+ pos = -1
+ if pos == -1:
+ lines_before.extend(lines)
+ else:
+ lines_before[pos:pos+1] = lines
+
+ handled.append(('license', licvalues))
+ return licvalues
+
+def get_license_md5sums(d, static_only=False, linenumbers=False):
import bb.utils
+ import csv
md5sums = {}
- if not static_only:
+ if not static_only and not linenumbers:
# Gather md5sums of license files in common license dir
- commonlicdir = d.getVar('COMMON_LICENSE_DIR', True)
+ commonlicdir = d.getVar('COMMON_LICENSE_DIR')
for fn in os.listdir(commonlicdir):
md5value = bb.utils.md5_file(os.path.join(commonlicdir, fn))
md5sums[md5value] = fn
+
# The following were extracted from common values in various recipes
# (double checking the license against the license file itself, not just
# the LICENSE value in the recipe)
- md5sums['94d55d512a9ba36caa9b7df079bae19f'] = 'GPLv2'
- md5sums['b234ee4d69f5fce4486a80fdaf4a4263'] = 'GPLv2'
- md5sums['59530bdf33659b29e73d4adb9f9f6552'] = 'GPLv2'
- md5sums['0636e73ff0215e8d672dc4c32c317bb3'] = 'GPLv2'
- md5sums['eb723b61539feef013de476e68b5c50a'] = 'GPLv2'
- md5sums['751419260aa954499f7abaabaa882bbe'] = 'GPLv2'
- md5sums['393a5ca445f6965873eca0259a17f833'] = 'GPLv2'
- md5sums['12f884d2ae1ff87c09e5b7ccc2c4ca7e'] = 'GPLv2'
- md5sums['8ca43cbc842c2336e835926c2166c28b'] = 'GPLv2'
- md5sums['ebb5c50ab7cab4baeffba14977030c07'] = 'GPLv2'
- md5sums['c93c0550bd3173f4504b2cbd8991e50b'] = 'GPLv2'
- md5sums['9ac2e7cff1ddaf48b6eab6028f23ef88'] = 'GPLv2'
- md5sums['4325afd396febcb659c36b49533135d4'] = 'GPLv2'
- md5sums['18810669f13b87348459e611d31ab760'] = 'GPLv2'
- md5sums['d7810fab7487fb0aad327b76f1be7cd7'] = 'GPLv2' # the Linux kernel's COPYING file
- md5sums['bbb461211a33b134d42ed5ee802b37ff'] = 'LGPLv2.1'
- md5sums['7fbc338309ac38fefcd64b04bb903e34'] = 'LGPLv2.1'
- md5sums['4fbd65380cdd255951079008b364516c'] = 'LGPLv2.1'
- md5sums['2d5025d4aa3495befef8f17206a5b0a1'] = 'LGPLv2.1'
- md5sums['fbc093901857fcd118f065f900982c24'] = 'LGPLv2.1'
- md5sums['a6f89e2100d9b6cdffcea4f398e37343'] = 'LGPLv2.1'
- md5sums['d8045f3b8f929c1cb29a1e3fd737b499'] = 'LGPLv2.1'
- md5sums['fad9b3332be894bab9bc501572864b29'] = 'LGPLv2.1'
- md5sums['3bf50002aefd002f49e7bb854063f7e7'] = 'LGPLv2'
- md5sums['9f604d8a4f8e74f4f5140845a21b6674'] = 'LGPLv2'
- md5sums['5f30f0716dfdd0d91eb439ebec522ec2'] = 'LGPLv2'
- md5sums['55ca817ccb7d5b5b66355690e9abc605'] = 'LGPLv2'
- md5sums['252890d9eee26aab7b432e8b8a616475'] = 'LGPLv2'
- md5sums['d32239bcb673463ab874e80d47fae504'] = 'GPLv3'
- md5sums['f27defe1e96c2e1ecd4e0c9be8967949'] = 'GPLv3'
- md5sums['6a6a8e020838b23406c81b19c1d46df6'] = 'LGPLv3'
- md5sums['3b83ef96387f14655fc854ddc3c6bd57'] = 'Apache-2.0'
- md5sums['385c55653886acac3821999a3ccd17b3'] = 'Artistic-1.0 | GPL-2.0' # some perl modules
+
+ # Read license md5sums from csv file
+ scripts_path = os.path.dirname(os.path.realpath(__file__))
+ for path in (d.getVar('BBPATH').split(':')
+ + [os.path.join(scripts_path, '..', '..')]):
+ csv_path = os.path.join(path, 'lib', 'recipetool', 'licenses.csv')
+ if os.path.isfile(csv_path):
+ with open(csv_path, newline='') as csv_file:
+ fieldnames = ['md5sum', 'license', 'beginline', 'endline', 'md5']
+ reader = csv.DictReader(csv_file, delimiter=',', fieldnames=fieldnames)
+ for row in reader:
+ if linenumbers:
+ md5sums[row['md5sum']] = (
+ row['license'], row['beginline'], row['endline'], row['md5'])
+ else:
+ md5sums[row['md5sum']] = row['license']
+
return md5sums
-def guess_license(srctree):
+def crunch_license(licfile):
+ '''
+ Remove non-material text from a license file and then check
+ its md5sum against a known list. This works well for licenses
+ which contain a copyright statement, but is also a useful way
+ to handle people's insistence upon reformatting the license text
+ slightly (with no material difference to the text of the
+ license).
+ '''
+
+ import oe.utils
+
+ # Note: these are carefully constructed!
+ license_title_re = re.compile(r'^#*\(? *(This is )?([Tt]he )?.{0,15} ?[Ll]icen[sc]e( \(.{1,10}\))?\)?[:\.]? ?#*$')
+ license_statement_re = re.compile(r'^((This (project|software)|.{1,10}) is( free software)? (released|licen[sc]ed)|(Released|Licen[cs]ed)) under the .{1,10} [Ll]icen[sc]e:?$')
+ copyright_re = re.compile('^ *[#\*]* *(Modified work |MIT LICENSED )?Copyright ?(\([cC]\))? .*$')
+ disclaimer_re = re.compile('^ *\*? ?All [Rr]ights [Rr]eserved\.$')
+ email_re = re.compile('^.*<[\w\.-]*@[\w\.\-]*>$')
+ header_re = re.compile('^(\/\**!?)? ?[\-=\*]* ?(\*\/)?$')
+ tag_re = re.compile('^ *@?\(?([Ll]icense|MIT)\)?$')
+ url_re = re.compile('^ *[#\*]* *https?:\/\/[\w\.\/\-]+$')
+
+ crunched_md5sums = {}
+
+ # common licenses
+ crunched_md5sums['89f3bf322f30a1dcfe952e09945842f0'] = 'Apache-2.0'
+ crunched_md5sums['13b6fe3075f8f42f2270a748965bf3a1'] = 'BSD-0-Clause'
+ crunched_md5sums['ba87a7d7c20719c8df4b8beed9b78c43'] = 'BSD-2-Clause'
+ crunched_md5sums['7f8892c03b72de419c27be4ebfa253f8'] = 'BSD-3-Clause'
+ crunched_md5sums['21128c0790b23a8a9f9e260d5f6b3619'] = 'BSL-1.0'
+ crunched_md5sums['975742a59ae1b8abdea63a97121f49f4'] = 'EDL-1.0'
+ crunched_md5sums['5322cee4433d84fb3aafc9e253116447'] = 'EPL-1.0'
+ crunched_md5sums['6922352e87de080f42419bed93063754'] = 'EPL-2.0'
+ crunched_md5sums['793475baa22295cae1d3d4046a3a0ceb'] = 'GPL-2.0-only'
+ crunched_md5sums['ff9047f969b02c20f0559470df5cb433'] = 'GPL-2.0-or-later'
+ crunched_md5sums['ea6de5453fcadf534df246e6cdafadcd'] = 'GPL-3.0-only'
+ crunched_md5sums['b419257d4d153a6fde92ddf96acf5b67'] = 'GPL-3.0-or-later'
+ crunched_md5sums['228737f4c49d3ee75b8fb3706b090b84'] = 'ISC'
+ crunched_md5sums['c6a782e826ca4e85bf7f8b89435a677d'] = 'LGPL-2.0-only'
+ crunched_md5sums['32d8f758a066752f0db09bd7624b8090'] = 'LGPL-2.0-or-later'
+ crunched_md5sums['4820937eb198b4f84c52217ed230be33'] = 'LGPL-2.1-only'
+ crunched_md5sums['db13fe9f3a13af7adab2dc7a76f9e44a'] = 'LGPL-2.1-or-later'
+ crunched_md5sums['d7a0f2e4e0950e837ac3eabf5bd1d246'] = 'LGPL-3.0-only'
+ crunched_md5sums['abbf328e2b434f9153351f06b9f79d02'] = 'LGPL-3.0-or-later'
+ crunched_md5sums['eecf6429523cbc9693547cf2db790b5c'] = 'MIT'
+ crunched_md5sums['b218b0e94290b9b818c4be67c8e1cc82'] = 'MIT-0'
+ crunched_md5sums['ddc18131d6748374f0f35a621c245b49'] = 'Unlicense'
+ crunched_md5sums['51f9570ff32571fc0a443102285c5e33'] = 'WTFPL'
+
+ # The following two were gleaned from the "forever" npm package
+ crunched_md5sums['0a97f8e4cbaf889d6fa51f84b89a79f6'] = 'ISC'
+ # https://github.com/waffle-gl/waffle/blob/master/LICENSE.txt
+ crunched_md5sums['50fab24ce589d69af8964fdbfe414c60'] = 'BSD-2-Clause'
+ # https://github.com/spigwitmer/fakeds1963s/blob/master/LICENSE
+ crunched_md5sums['88a4355858a1433fea99fae34a44da88'] = 'GPLv2'
+ # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
+ crunched_md5sums['063b5c3ebb5f3aa4c85a2ed18a31fbe7'] = 'GPLv2'
+ # https://github.com/FFmpeg/FFmpeg/blob/master/COPYING.LGPLv2.1
+ crunched_md5sums['7f5202f4d44ed15dcd4915f5210417d8'] = 'LGPLv2.1'
+ # unixODBC-2.3.4 COPYING
+ crunched_md5sums['3debde09238a8c8e1f6a847e1ec9055b'] = 'LGPLv2.1'
+ # https://github.com/FFmpeg/FFmpeg/blob/master/COPYING.LGPLv3
+ crunched_md5sums['f90c613c51aa35da4d79dd55fc724ceb'] = 'LGPLv3'
+ # https://raw.githubusercontent.com/eclipse/mosquitto/v1.4.14/epl-v10
+ crunched_md5sums['efe2cb9a35826992b9df68224e3c2628'] = 'EPL-1.0'
+
+ # https://raw.githubusercontent.com/jquery/esprima/3.1.3/LICENSE.BSD
+ crunched_md5sums['80fa7b56a28e8c902e6af194003220a5'] = 'BSD-2-Clause'
+ # https://raw.githubusercontent.com/npm/npm-install-checks/master/LICENSE
+ crunched_md5sums['e659f77bfd9002659e112d0d3d59b2c1'] = 'BSD-2-Clause'
+ # https://raw.githubusercontent.com/silverwind/default-gateway/4.2.0/LICENSE
+ crunched_md5sums['4c641f2d995c47f5cb08bdb4b5b6ea05'] = 'BSD-2-Clause'
+ # https://raw.githubusercontent.com/tad-lispy/node-damerau-levenshtein/v1.0.5/LICENSE
+ crunched_md5sums['2b8c039b2b9a25f0feb4410c4542d346'] = 'BSD-2-Clause'
+ # https://raw.githubusercontent.com/terser/terser/v3.17.0/LICENSE
+ crunched_md5sums['8bd23871802951c9ad63855151204c2c'] = 'BSD-2-Clause'
+ # https://raw.githubusercontent.com/alexei/sprintf.js/1.0.3/LICENSE
+ crunched_md5sums['008c22318c8ea65928bf730ddd0273e3'] = 'BSD-3-Clause'
+ # https://raw.githubusercontent.com/Caligatio/jsSHA/v3.2.0/LICENSE
+ crunched_md5sums['0e46634a01bfef056892949acaea85b1'] = 'BSD-3-Clause'
+ # https://raw.githubusercontent.com/d3/d3-path/v1.0.9/LICENSE
+ crunched_md5sums['b5f72aef53d3b2b432702c30b0215666'] = 'BSD-3-Clause'
+ # https://raw.githubusercontent.com/feross/ieee754/v1.1.13/LICENSE
+ crunched_md5sums['a39327c997c20da0937955192d86232d'] = 'BSD-3-Clause'
+ # https://raw.githubusercontent.com/joyent/node-extsprintf/v1.3.0/LICENSE
+ crunched_md5sums['721f23a96ff4161ca3a5f071bbe18108'] = 'MIT'
+ # https://raw.githubusercontent.com/pvorb/clone/v0.2.0/LICENSE
+ crunched_md5sums['b376d29a53c9573006b9970709231431'] = 'MIT'
+ # https://raw.githubusercontent.com/andris9/encoding/v0.1.12/LICENSE
+ crunched_md5sums['85d8a977ee9d7c5ab4ac03c9b95431c4'] = 'MIT-0'
+ # https://raw.githubusercontent.com/faye/websocket-driver-node/0.7.3/LICENSE.md
+ crunched_md5sums['b66384e7137e41a9b1904ef4d39703b6'] = 'Apache-2.0'
+ # https://raw.githubusercontent.com/less/less.js/v4.1.1/LICENSE
+ crunched_md5sums['b27575459e02221ccef97ec0bfd457ae'] = 'Apache-2.0'
+ # https://raw.githubusercontent.com/microsoft/TypeScript/v3.5.3/LICENSE.txt
+ crunched_md5sums['a54a1a6a39e7f9dbb4a23a42f5c7fd1c'] = 'Apache-2.0'
+ # https://raw.githubusercontent.com/request/request/v2.87.0/LICENSE
+ crunched_md5sums['1034431802e57486b393d00c5d262b8a'] = 'Apache-2.0'
+ # https://raw.githubusercontent.com/dchest/tweetnacl-js/v0.14.5/LICENSE
+ crunched_md5sums['75605e6bdd564791ab698fca65c94a4f'] = 'Unlicense'
+ # https://raw.githubusercontent.com/stackgl/gl-mat3/v2.0.0/LICENSE.md
+ crunched_md5sums['75512892d6f59dddb6d1c7e191957e9c'] = 'Zlib'
+
+ lictext = []
+ with open(licfile, 'r', errors='surrogateescape') as f:
+ for line in f:
+ # Drop opening statements
+ if copyright_re.match(line):
+ continue
+ elif disclaimer_re.match(line):
+ continue
+ elif email_re.match(line):
+ continue
+ elif header_re.match(line):
+ continue
+ elif tag_re.match(line):
+ continue
+ elif url_re.match(line):
+ continue
+ elif license_title_re.match(line):
+ continue
+ elif license_statement_re.match(line):
+ continue
+ # Strip comment symbols
+ line = line.replace('*', '') \
+ .replace('#', '')
+ # Unify spelling
+ line = line.replace('sub-license', 'sublicense')
+ # Squash spaces
+ line = oe.utils.squashspaces(line.strip())
+ # Replace smart quotes, double quotes and backticks with single quotes
+ line = line.replace(u"\u2018", "'").replace(u"\u2019", "'").replace(u"\u201c","'").replace(u"\u201d", "'").replace('"', '\'').replace('`', '\'')
+ # Unify brackets
+ line = line.replace("{", "[").replace("}", "]")
+ if line:
+ lictext.append(line)
+
+ m = hashlib.md5()
+ try:
+ m.update(' '.join(lictext).encode('utf-8'))
+ md5val = m.hexdigest()
+ except UnicodeEncodeError:
+ md5val = None
+ lictext = ''
+ license = crunched_md5sums.get(md5val, None)
+ return license, md5val, lictext
+
+def guess_license(srctree, d):
import bb
- md5sums = get_license_md5sums(tinfoil.config_data)
+ md5sums = get_license_md5sums(d)
licenses = []
- licspecs = ['LICENSE*', 'COPYING*', '*[Ll]icense*', 'LICENCE*', 'LEGAL*', '[Ll]egal*', '*GPL*', 'README.lic*', 'COPYRIGHT*', '[Cc]opyright*']
+ licspecs = ['*LICEN[CS]E*', 'COPYING*', '*[Ll]icense*', 'LEGAL*', '[Ll]egal*', '*GPL*', 'README.lic*', 'COPYRIGHT*', '[Cc]opyright*', 'e[dp]l-v10']
+ skip_extensions = (".html", ".js", ".json", ".svg", ".ts")
licfiles = []
for root, dirs, files in os.walk(srctree):
for fn in files:
+ if fn.endswith(skip_extensions):
+ continue
for spec in licspecs:
if fnmatch.fnmatch(fn, spec):
fullpath = os.path.join(root, fn)
@@ -335,22 +1204,57 @@ def guess_license(srctree):
licfiles.append(fullpath)
for licfile in licfiles:
md5value = bb.utils.md5_file(licfile)
- license = md5sums.get(md5value, 'Unknown')
- licenses.append((license, os.path.relpath(licfile, srctree), md5value))
+ license = md5sums.get(md5value, None)
+ if not license:
+ license, crunched_md5, lictext = crunch_license(licfile)
+ if lictext and not license:
+ license = 'Unknown'
+ logger.info("Please add the following line for '%s' to a 'lib/recipetool/licenses.csv' " \
+ "and replace `Unknown` with the license:\n" \
+ "%s,Unknown" % (os.path.relpath(licfile, srctree), md5value))
+ if license:
+ licenses.append((license, os.path.relpath(licfile, srctree), md5value))
# FIXME should we grab at least one source file with a license header and add that too?
return licenses
+def split_pkg_licenses(licvalues, packages, outlines, fallback_licenses=[], pn='${PN}'):
+ """
+ Given a list of (license, path, md5sum) as returned by guess_license(),
+ a dict of package name to path mappings, write out a set of
+ package-specific LICENSE values.
+ """
+ pkglicenses = {pn: []}
+ for license, licpath, _ in licvalues:
+ for pkgname, pkgpath in packages.items():
+ if licpath.startswith(pkgpath + '/'):
+ if pkgname in pkglicenses:
+ pkglicenses[pkgname].append(license)
+ else:
+ pkglicenses[pkgname] = [license]
+ break
+ else:
+ # Accumulate on the main package
+ pkglicenses[pn].append(license)
+ outlicenses = {}
+ for pkgname in packages:
+ license = ' '.join(list(set(pkglicenses.get(pkgname, ['Unknown'])))) or 'Unknown'
+ if license == 'Unknown' and pkgname in fallback_licenses:
+ license = fallback_licenses[pkgname]
+ outlines.append('LICENSE:%s = "%s"' % (pkgname, license))
+ outlicenses[pkgname] = license.split()
+ return outlicenses
+
def read_pkgconfig_provides(d):
- pkgdatadir = d.getVar('PKGDATA_DIR', True)
+ pkgdatadir = d.getVar('PKGDATA_DIR')
pkgmap = {}
for fn in glob.glob(os.path.join(pkgdatadir, 'shlibs2', '*.pclist')):
with open(fn, 'r') as f:
for line in f:
pkgmap[os.path.basename(line.rstrip())] = os.path.splitext(os.path.basename(fn))[0]
recipemap = {}
- for pc, pkg in pkgmap.iteritems():
+ for pc, pkg in pkgmap.items():
pkgdatafile = os.path.join(pkgdatadir, 'runtime', pkg)
if os.path.exists(pkgdatafile):
with open(pkgdatafile, 'r') as f:
@@ -359,82 +1263,120 @@ def read_pkgconfig_provides(d):
recipemap[pc] = line.split(':', 1)[1].strip()
return recipemap
-def convert_pkginfo(pkginfofile):
- values = {}
- with open(pkginfofile, 'r') as f:
- indesc = False
- for line in f:
- if indesc:
- if line.strip():
- values['DESCRIPTION'] += ' ' + line.strip()
- else:
- indesc = False
- else:
- splitline = line.split(': ', 1)
- key = line[0]
- value = line[1]
- if key == 'LICENSE':
- for dep in value.split(','):
- dep = dep.split()[0]
- mapped = depmap.get(dep, '')
- if mapped:
- depends.append(mapped)
- elif key == 'License':
- values['LICENSE'] = value
- elif key == 'Summary':
- values['SUMMARY'] = value
- elif key == 'Description':
- values['DESCRIPTION'] = value
- indesc = True
- return values
-
def convert_debian(debpath):
+ value_map = {'Package': 'PN',
+ 'Version': 'PV',
+ 'Section': 'SECTION',
+ 'License': 'LICENSE',
+ 'Homepage': 'HOMEPAGE'}
+
# FIXME extend this mapping - perhaps use distro_alias.inc?
depmap = {'libz-dev': 'zlib'}
values = {}
depends = []
- with open(os.path.join(debpath, 'control')) as f:
+ with open(os.path.join(debpath, 'control'), 'r', errors='surrogateescape') as f:
indesc = False
for line in f:
if indesc:
- if line.strip():
+ if line.startswith(' '):
if line.startswith(' This package contains'):
indesc = False
else:
- values['DESCRIPTION'] += ' ' + line.strip()
+ if 'DESCRIPTION' in values:
+ values['DESCRIPTION'] += ' ' + line.strip()
+ else:
+ values['DESCRIPTION'] = line.strip()
else:
indesc = False
- else:
+ if not indesc:
splitline = line.split(':', 1)
- key = line[0]
- value = line[1]
+ if len(splitline) < 2:
+ continue
+ key = splitline[0]
+ value = splitline[1].strip()
if key == 'Build-Depends':
for dep in value.split(','):
dep = dep.split()[0]
mapped = depmap.get(dep, '')
if mapped:
depends.append(mapped)
- elif key == 'Section':
- values['SECTION'] = value
elif key == 'Description':
values['SUMMARY'] = value
indesc = True
+ else:
+ varname = value_map.get(key, None)
+ if varname:
+ values[varname] = value
+ postinst = os.path.join(debpath, 'postinst')
+ postrm = os.path.join(debpath, 'postrm')
+ preinst = os.path.join(debpath, 'preinst')
+ prerm = os.path.join(debpath, 'prerm')
+ sfiles = [postinst, postrm, preinst, prerm]
+ for sfile in sfiles:
+ if os.path.isfile(sfile):
+ logger.info("Converting %s file to recipe function..." %
+ os.path.basename(sfile).upper())
+ content = []
+ with open(sfile) as f:
+ for line in f:
+ if "#!/" in line:
+ continue
+ line = line.rstrip("\n")
+ if line.strip():
+ content.append(line)
+ if content:
+ values[os.path.basename(f.name)] = content
+
+ #if depends:
+ # values['DEPENDS'] = ' '.join(depends)
- if depends:
- values['DEPENDS'] = ' '.join(depends)
+ return values
+def convert_rpm_xml(xmlfile):
+ '''Converts the output from rpm -qp --xml to a set of variable values'''
+ import xml.etree.ElementTree as ElementTree
+ rpmtag_map = {'Name': 'PN',
+ 'Version': 'PV',
+ 'Summary': 'SUMMARY',
+ 'Description': 'DESCRIPTION',
+ 'License': 'LICENSE',
+ 'Url': 'HOMEPAGE'}
+
+ values = {}
+ tree = ElementTree.parse(xmlfile)
+ root = tree.getroot()
+ for child in root:
+ if child.tag == 'rpmTag':
+ name = child.attrib.get('name', None)
+ if name:
+ varname = rpmtag_map.get(name, None)
+ if varname:
+ values[varname] = child[0].text
return values
-def register_command(subparsers):
+def register_commands(subparsers):
parser_create = subparsers.add_parser('create',
help='Create a new recipe',
description='Creates a new recipe from a source tree')
parser_create.add_argument('source', help='Path or URL to source')
- parser_create.add_argument('-o', '--outfile', help='Specify filename for recipe to create', required=True)
+ parser_create.add_argument('-o', '--outfile', help='Specify filename for recipe to create')
+ parser_create.add_argument('-p', '--provides', help='Specify an alias for the item provided by the recipe')
parser_create.add_argument('-m', '--machine', help='Make recipe machine-specific as opposed to architecture-specific', action='store_true')
parser_create.add_argument('-x', '--extract-to', metavar='EXTRACTPATH', help='Assuming source is a URL, fetch it and extract it to the directory specified as %(metavar)s')
+ parser_create.add_argument('-N', '--name', help='Name to use within recipe (PN)')
parser_create.add_argument('-V', '--version', help='Version to use within recipe (PV)')
+ parser_create.add_argument('-b', '--binary', help='Treat the source tree as something that should be installed verbatim (no compilation, same directory structure)', action='store_true')
+ parser_create.add_argument('--also-native', help='Also add native variant (i.e. support building recipe for the build host as well as the target machine)', action='store_true')
+ parser_create.add_argument('--src-subdir', help='Specify subdirectory within source tree to use', metavar='SUBDIR')
+ group = parser_create.add_mutually_exclusive_group()
+ group.add_argument('-a', '--autorev', help='When fetching from a git repository, set SRCREV in the recipe to a floating revision instead of fixed', action="store_true")
+ group.add_argument('-S', '--srcrev', help='Source revision to fetch if fetching from an SCM such as git (default latest)')
+ parser_create.add_argument('-B', '--srcbranch', help='Branch in source repository if fetching from an SCM such as git (default master)')
+ parser_create.add_argument('--keep-temp', action="store_true", help='Keep temporary directory (for debugging)')
+ parser_create.add_argument('--npm-dev', action="store_true", help='For npm, also fetch devDependencies')
+ parser_create.add_argument('--devtool', action="store_true", help=argparse.SUPPRESS)
+ parser_create.add_argument('--mirrors', action="store_true", help='Enable PREMIRRORS and MIRRORS for source tree fetching (disabled by default).')
parser_create.set_defaults(func=create_recipe)
diff --git a/scripts/lib/recipetool/create_buildsys.py b/scripts/lib/recipetool/create_buildsys.py
index 6c9e0efa2a..35a97c9345 100644
--- a/scripts/lib/recipetool/create_buildsys.py
+++ b/scripts/lib/recipetool/create_buildsys.py
@@ -1,39 +1,41 @@
# Recipe creation tool - create command build system handlers
#
-# Copyright (C) 2014 Intel Corporation
+# Copyright (C) 2014-2016 Intel Corporation
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
+# SPDX-License-Identifier: GPL-2.0-only
#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import re
import logging
-from recipetool.create import RecipeHandler, read_pkgconfig_provides
+import glob
+from recipetool.create import RecipeHandler, validate_pv
logger = logging.getLogger('recipetool')
tinfoil = None
+plugins = None
+
+def plugin_init(pluginlist):
+ # Take a reference to the list so we can use it later
+ global plugins
+ plugins = pluginlist
def tinfoil_init(instance):
global tinfoil
tinfoil = instance
+
class CmakeRecipeHandler(RecipeHandler):
- def process(self, srctree, classes, lines_before, lines_after, handled):
+ def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
if 'buildsystem' in handled:
return False
if RecipeHandler.checkfiles(srctree, ['CMakeLists.txt']):
classes.append('cmake')
+ values = CmakeRecipeHandler.extract_cmake_deps(lines_before, srctree, extravalues)
+ classes.extend(values.pop('inherit', '').split())
+ for var, value in values.items():
+ lines_before.append('%s = "%s"' % (var, value))
lines_after.append('# Specify any options you want to pass to cmake using EXTRA_OECMAKE:')
lines_after.append('EXTRA_OECMAKE = ""')
lines_after.append('')
@@ -41,8 +43,266 @@ class CmakeRecipeHandler(RecipeHandler):
return True
return False
+ @staticmethod
+ def extract_cmake_deps(outlines, srctree, extravalues, cmakelistsfile=None):
+ # Find all plugins that want to register handlers
+ logger.debug('Loading cmake handlers')
+ handlers = []
+ for plugin in plugins:
+ if hasattr(plugin, 'register_cmake_handlers'):
+ plugin.register_cmake_handlers(handlers)
+
+ values = {}
+ inherits = []
+
+ if cmakelistsfile:
+ srcfiles = [cmakelistsfile]
+ else:
+ srcfiles = RecipeHandler.checkfiles(srctree, ['CMakeLists.txt'])
+
+ # Note that some of these are non-standard, but probably better to
+ # be able to map them anyway if we see them
+ cmake_pkgmap = {'alsa': 'alsa-lib',
+ 'aspell': 'aspell',
+ 'atk': 'atk',
+ 'bison': 'bison-native',
+ 'boost': 'boost',
+ 'bzip2': 'bzip2',
+ 'cairo': 'cairo',
+ 'cups': 'cups',
+ 'curl': 'curl',
+ 'curses': 'ncurses',
+ 'cvs': 'cvs',
+ 'drm': 'libdrm',
+ 'dbus': 'dbus',
+ 'dbusglib': 'dbus-glib',
+ 'egl': 'virtual/egl',
+ 'expat': 'expat',
+ 'flex': 'flex-native',
+ 'fontconfig': 'fontconfig',
+ 'freetype': 'freetype',
+ 'gettext': '',
+ 'git': '',
+ 'gio': 'glib-2.0',
+ 'giounix': 'glib-2.0',
+ 'glew': 'glew',
+ 'glib': 'glib-2.0',
+ 'glib2': 'glib-2.0',
+ 'glu': 'libglu',
+ 'glut': 'freeglut',
+ 'gobject': 'glib-2.0',
+ 'gperf': 'gperf-native',
+ 'gnutls': 'gnutls',
+ 'gtk2': 'gtk+',
+ 'gtk3': 'gtk+3',
+ 'gtk': 'gtk+3',
+ 'harfbuzz': 'harfbuzz',
+ 'icu': 'icu',
+ 'intl': 'virtual/libintl',
+ 'jpeg': 'jpeg',
+ 'libarchive': 'libarchive',
+ 'libiconv': 'virtual/libiconv',
+ 'liblzma': 'xz',
+ 'libxml2': 'libxml2',
+ 'libxslt': 'libxslt',
+ 'opengl': 'virtual/libgl',
+ 'openmp': '',
+ 'openssl': 'openssl',
+ 'pango': 'pango',
+ 'perl': '',
+ 'perllibs': '',
+ 'pkgconfig': '',
+ 'png': 'libpng',
+ 'pthread': '',
+ 'pythoninterp': '',
+ 'pythonlibs': '',
+ 'ruby': 'ruby-native',
+ 'sdl': 'libsdl',
+ 'sdl2': 'libsdl2',
+ 'subversion': 'subversion-native',
+ 'swig': 'swig-native',
+ 'tcl': 'tcl-native',
+ 'threads': '',
+ 'tiff': 'tiff',
+ 'wget': 'wget',
+ 'x11': 'libx11',
+ 'xcb': 'libxcb',
+ 'xext': 'libxext',
+ 'xfixes': 'libxfixes',
+ 'zlib': 'zlib',
+ }
+
+ pcdeps = []
+ libdeps = []
+ deps = []
+ unmappedpkgs = []
+
+ proj_re = re.compile('project\s*\(([^)]*)\)', re.IGNORECASE)
+ pkgcm_re = re.compile('pkg_check_modules\s*\(\s*[a-zA-Z0-9-_]+\s*(REQUIRED)?\s+([^)\s]+)\s*\)', re.IGNORECASE)
+ pkgsm_re = re.compile('pkg_search_module\s*\(\s*[a-zA-Z0-9-_]+\s*(REQUIRED)?((\s+[^)\s]+)+)\s*\)', re.IGNORECASE)
+ findpackage_re = re.compile('find_package\s*\(\s*([a-zA-Z0-9-_]+)\s*.*', re.IGNORECASE)
+ findlibrary_re = re.compile('find_library\s*\(\s*[a-zA-Z0-9-_]+\s*(NAMES\s+)?([a-zA-Z0-9-_ ]+)\s*.*')
+ checklib_re = re.compile('check_library_exists\s*\(\s*([^\s)]+)\s*.*', re.IGNORECASE)
+ include_re = re.compile('include\s*\(\s*([^)\s]*)\s*\)', re.IGNORECASE)
+ subdir_re = re.compile('add_subdirectory\s*\(\s*([^)\s]*)\s*([^)\s]*)\s*\)', re.IGNORECASE)
+ dep_re = re.compile('([^ ><=]+)( *[<>=]+ *[^ ><=]+)?')
+
+ def find_cmake_package(pkg):
+ RecipeHandler.load_devel_filemap(tinfoil.config_data)
+ for fn, pn in RecipeHandler.recipecmakefilemap.items():
+ splitname = fn.split('/')
+ if len(splitname) > 1:
+ if splitname[0].lower().startswith(pkg.lower()):
+ if splitname[1] == '%s-config.cmake' % pkg.lower() or splitname[1] == '%sConfig.cmake' % pkg or splitname[1] == 'Find%s.cmake' % pkg:
+ return pn
+ return None
+
+ def interpret_value(value):
+ return value.strip('"')
+
+ def parse_cmake_file(fn, paths=None):
+ searchpaths = (paths or []) + [os.path.dirname(fn)]
+ logger.debug('Parsing file %s' % fn)
+ with open(fn, 'r', errors='surrogateescape') as f:
+ for line in f:
+ line = line.strip()
+ for handler in handlers:
+ if handler.process_line(srctree, fn, line, libdeps, pcdeps, deps, outlines, inherits, values):
+ continue
+ res = include_re.match(line)
+ if res:
+ includefn = bb.utils.which(':'.join(searchpaths), res.group(1))
+ if includefn:
+ parse_cmake_file(includefn, searchpaths)
+ else:
+ logger.debug('Unable to recurse into include file %s' % res.group(1))
+ continue
+ res = subdir_re.match(line)
+ if res:
+ subdirfn = os.path.join(os.path.dirname(fn), res.group(1), 'CMakeLists.txt')
+ if os.path.exists(subdirfn):
+ parse_cmake_file(subdirfn, searchpaths)
+ else:
+ logger.debug('Unable to recurse into subdirectory file %s' % subdirfn)
+ continue
+ res = proj_re.match(line)
+ if res:
+ extravalues['PN'] = interpret_value(res.group(1).split()[0])
+ continue
+ res = pkgcm_re.match(line)
+ if res:
+ res = dep_re.findall(res.group(2))
+ if res:
+ pcdeps.extend([interpret_value(x[0]) for x in res])
+ inherits.append('pkgconfig')
+ continue
+ res = pkgsm_re.match(line)
+ if res:
+ res = dep_re.findall(res.group(2))
+ if res:
+ # Note: appending a tuple here!
+ item = tuple((interpret_value(x[0]) for x in res))
+ if len(item) == 1:
+ item = item[0]
+ pcdeps.append(item)
+ inherits.append('pkgconfig')
+ continue
+ res = findpackage_re.match(line)
+ if res:
+ origpkg = res.group(1)
+ pkg = interpret_value(origpkg)
+ found = False
+ for handler in handlers:
+ if handler.process_findpackage(srctree, fn, pkg, deps, outlines, inherits, values):
+ logger.debug('Mapped CMake package %s via handler %s' % (pkg, handler.__class__.__name__))
+ found = True
+ break
+ if found:
+ continue
+ elif pkg == 'Gettext':
+ inherits.append('gettext')
+ elif pkg == 'Perl':
+ inherits.append('perlnative')
+ elif pkg == 'PkgConfig':
+ inherits.append('pkgconfig')
+ elif pkg == 'PythonInterp':
+ inherits.append('python3native')
+ elif pkg == 'PythonLibs':
+ inherits.append('python3-dir')
+ else:
+ # Try to map via looking at installed CMake packages in pkgdata
+ dep = find_cmake_package(pkg)
+ if dep:
+ logger.debug('Mapped CMake package %s to recipe %s via pkgdata' % (pkg, dep))
+ deps.append(dep)
+ else:
+ dep = cmake_pkgmap.get(pkg.lower(), None)
+ if dep:
+ logger.debug('Mapped CMake package %s to recipe %s via internal list' % (pkg, dep))
+ deps.append(dep)
+ elif dep is None:
+ unmappedpkgs.append(origpkg)
+ continue
+ res = checklib_re.match(line)
+ if res:
+ lib = interpret_value(res.group(1))
+ if not lib.startswith('$'):
+ libdeps.append(lib)
+ res = findlibrary_re.match(line)
+ if res:
+ libs = res.group(2).split()
+ for lib in libs:
+ if lib in ['HINTS', 'PATHS', 'PATH_SUFFIXES', 'DOC', 'NAMES_PER_DIR'] or lib.startswith(('NO_', 'CMAKE_', 'ONLY_CMAKE_')):
+ break
+ lib = interpret_value(lib)
+ if not lib.startswith('$'):
+ libdeps.append(lib)
+ if line.lower().startswith('useswig'):
+ deps.append('swig-native')
+ continue
+
+ parse_cmake_file(srcfiles[0])
+
+ if unmappedpkgs:
+ outlines.append('# NOTE: unable to map the following CMake package dependencies: %s' % ' '.join(list(set(unmappedpkgs))))
+
+ RecipeHandler.handle_depends(libdeps, pcdeps, deps, outlines, values, tinfoil.config_data)
+
+ for handler in handlers:
+ handler.post_process(srctree, libdeps, pcdeps, deps, outlines, inherits, values)
+
+ if inherits:
+ values['inherit'] = ' '.join(list(set(inherits)))
+
+ return values
+
+
+class CmakeExtensionHandler(object):
+ '''Base class for CMake extension handlers'''
+ def process_line(self, srctree, fn, line, libdeps, pcdeps, deps, outlines, inherits, values):
+ '''
+ Handle a line parsed out of an CMake file.
+ Return True if you've completely handled the passed in line, otherwise return False.
+ '''
+ return False
+
+ def process_findpackage(self, srctree, fn, pkg, deps, outlines, inherits, values):
+ '''
+ Handle a find_package package parsed out of a CMake file.
+ Return True if you've completely handled the passed in package, otherwise return False.
+ '''
+ return False
+
+ def post_process(self, srctree, fn, pkg, deps, outlines, inherits, values):
+ '''
+ Apply any desired post-processing on the output
+ '''
+ return
+
+
+
class SconsRecipeHandler(RecipeHandler):
- def process(self, srctree, classes, lines_before, lines_after, handled):
+ def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
if 'buildsystem' in handled:
return False
@@ -55,8 +315,9 @@ class SconsRecipeHandler(RecipeHandler):
return True
return False
+
class QmakeRecipeHandler(RecipeHandler):
- def process(self, srctree, classes, lines_before, lines_after, handled):
+ def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
if 'buildsystem' in handled:
return False
@@ -66,29 +327,47 @@ class QmakeRecipeHandler(RecipeHandler):
return True
return False
+
class AutotoolsRecipeHandler(RecipeHandler):
- def process(self, srctree, classes, lines_before, lines_after, handled):
+ def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
if 'buildsystem' in handled:
return False
autoconf = False
if RecipeHandler.checkfiles(srctree, ['configure.ac', 'configure.in']):
autoconf = True
- values = AutotoolsRecipeHandler.extract_autotools_deps(lines_before, srctree)
+ values = AutotoolsRecipeHandler.extract_autotools_deps(lines_before, srctree, extravalues)
classes.extend(values.pop('inherit', '').split())
- for var, value in values.iteritems():
+ for var, value in values.items():
lines_before.append('%s = "%s"' % (var, value))
else:
conffile = RecipeHandler.checkfiles(srctree, ['configure'])
if conffile:
# Check if this is just a pre-generated autoconf configure script
- with open(conffile[0], 'r') as f:
+ with open(conffile[0], 'r', errors='surrogateescape') as f:
for i in range(1, 10):
if 'Generated by GNU Autoconf' in f.readline():
autoconf = True
break
+ if autoconf and not ('PV' in extravalues and 'PN' in extravalues):
+ # Last resort
+ conffile = RecipeHandler.checkfiles(srctree, ['configure'])
+ if conffile:
+ with open(conffile[0], 'r', errors='surrogateescape') as f:
+ for line in f:
+ line = line.strip()
+ if line.startswith('VERSION=') or line.startswith('PACKAGE_VERSION='):
+ pv = line.split('=')[1].strip('"\'')
+ if pv and not 'PV' in extravalues and validate_pv(pv):
+ extravalues['PV'] = pv
+ elif line.startswith('PACKAGE_NAME=') or line.startswith('PACKAGE='):
+ pn = line.split('=')[1].strip('"\'')
+ if pn and not 'PN' in extravalues:
+ extravalues['PN'] = pn
+
if autoconf:
+ lines_before.append('')
lines_before.append('# NOTE: if this software is not capable of being built in a separate build directory')
lines_before.append('# from the source, you should replace autotools with autotools-brokensep in the')
lines_before.append('# inherit line')
@@ -102,136 +381,319 @@ class AutotoolsRecipeHandler(RecipeHandler):
return False
@staticmethod
- def extract_autotools_deps(outlines, srctree, acfile=None):
+ def extract_autotools_deps(outlines, srctree, extravalues=None, acfile=None):
import shlex
- import oe.package
+
+ # Find all plugins that want to register handlers
+ logger.debug('Loading autotools handlers')
+ handlers = []
+ for plugin in plugins:
+ if hasattr(plugin, 'register_autotools_handlers'):
+ plugin.register_autotools_handlers(handlers)
values = {}
inherits = []
- # FIXME this mapping is very thin
+ # Hardcoded map, we also use a dynamic one based on what's in the sysroot
progmap = {'flex': 'flex-native',
'bison': 'bison-native',
- 'm4': 'm4-native'}
+ 'm4': 'm4-native',
+ 'tar': 'tar-native',
+ 'ar': 'binutils-native',
+ 'ranlib': 'binutils-native',
+ 'ld': 'binutils-native',
+ 'strip': 'binutils-native',
+ 'libtool': '',
+ 'autoconf': '',
+ 'autoheader': '',
+ 'automake': '',
+ 'uname': '',
+ 'rm': '',
+ 'cp': '',
+ 'mv': '',
+ 'find': '',
+ 'awk': '',
+ 'sed': '',
+ }
progclassmap = {'gconftool-2': 'gconf',
- 'pkg-config': 'pkgconfig'}
-
- ignoredeps = ['gcc-runtime', 'glibc', 'uclibc']
-
- pkg_re = re.compile('PKG_CHECK_MODULES\(\[?[a-zA-Z0-9]*\]?, \[?([^,\]]*)[),].*')
- lib_re = re.compile('AC_CHECK_LIB\(\[?([a-zA-Z0-9]*)\]?, .*')
- progs_re = re.compile('_PROGS?\(\[?[a-zA-Z0-9]*\]?, \[?([^,\]]*)\]?[),].*')
+ 'pkg-config': 'pkgconfig',
+ 'python': 'python3native',
+ 'python3': 'python3native',
+ 'perl': 'perlnative',
+ 'makeinfo': 'texinfo',
+ }
+
+ pkg_re = re.compile('PKG_CHECK_MODULES\(\s*\[?[a-zA-Z0-9_]*\]?,\s*\[?([^,\]]*)\]?[),].*')
+ pkgce_re = re.compile('PKG_CHECK_EXISTS\(\s*\[?([^,\]]*)\]?[),].*')
+ lib_re = re.compile('AC_CHECK_LIB\(\s*\[?([^,\]]*)\]?,.*')
+ libx_re = re.compile('AX_CHECK_LIBRARY\(\s*\[?[^,\]]*\]?,\s*\[?([^,\]]*)\]?,\s*\[?([a-zA-Z0-9-]*)\]?,.*')
+ progs_re = re.compile('_PROGS?\(\s*\[?[a-zA-Z0-9_]*\]?,\s*\[?([^,\]]*)\]?[),].*')
dep_re = re.compile('([^ ><=]+)( [<>=]+ [^ ><=]+)?')
-
- # Build up lib library->package mapping
- shlib_providers = oe.package.read_shlib_providers(tinfoil.config_data)
- libdir = tinfoil.config_data.getVar('libdir', True)
- base_libdir = tinfoil.config_data.getVar('base_libdir', True)
- libpaths = list(set([base_libdir, libdir]))
- libname_re = re.compile('^lib(.+)\.so.*$')
- pkglibmap = {}
- for lib, item in shlib_providers.iteritems():
- for path, pkg in item.iteritems():
- if path in libpaths:
- res = libname_re.match(lib)
- if res:
- libname = res.group(1)
- if not libname in pkglibmap:
- pkglibmap[libname] = pkg[0]
- else:
- logger.debug('unable to extract library name from %s' % lib)
-
- # Now turn it into a library->recipe mapping
- recipelibmap = {}
- pkgdata_dir = tinfoil.config_data.getVar('PKGDATA_DIR', True)
- for libname, pkg in pkglibmap.iteritems():
- try:
- with open(os.path.join(pkgdata_dir, 'runtime', pkg)) as f:
- for line in f:
- if line.startswith('PN:'):
- recipelibmap[libname] = line.split(':', 1)[-1].strip()
- break
- except IOError as ioe:
- if ioe.errno == 2:
- logger.warn('unable to find a pkgdata file for package %s' % pkg)
- else:
- raise
+ ac_init_re = re.compile('AC_INIT\(\s*([^,]+),\s*([^,]+)[,)].*')
+ am_init_re = re.compile('AM_INIT_AUTOMAKE\(\s*([^,]+),\s*([^,]+)[,)].*')
+ define_re = re.compile('\s*(m4_)?define\(\s*([^,]+),\s*([^,]+)\)')
+ version_re = re.compile('([0-9.]+)')
+
+ defines = {}
+ def subst_defines(value):
+ newvalue = value
+ for define, defval in defines.items():
+ newvalue = newvalue.replace(define, defval)
+ if newvalue != value:
+ return subst_defines(newvalue)
+ return value
+
+ def process_value(value):
+ value = value.replace('[', '').replace(']', '')
+ if value.startswith('m4_esyscmd(') or value.startswith('m4_esyscmd_s('):
+ cmd = subst_defines(value[value.index('(')+1:-1])
+ try:
+ if '|' in cmd:
+ cmd = 'set -o pipefail; ' + cmd
+ stdout, _ = bb.process.run(cmd, cwd=srctree, shell=True)
+ ret = stdout.rstrip()
+ except bb.process.ExecutionError as e:
+ ret = ''
+ elif value.startswith('m4_'):
+ return None
+ ret = subst_defines(value)
+ if ret:
+ ret = ret.strip('"\'')
+ return ret
# Since a configure.ac file is essentially a program, this is only ever going to be
# a hack unfortunately; but it ought to be enough of an approximation
if acfile:
srcfiles = [acfile]
else:
- srcfiles = RecipeHandler.checkfiles(srctree, ['configure.ac', 'configure.in'])
+ srcfiles = RecipeHandler.checkfiles(srctree, ['acinclude.m4', 'configure.ac', 'configure.in'])
+
pcdeps = []
+ libdeps = []
deps = []
unmapped = []
- unmappedlibs = []
- with open(srcfiles[0], 'r') as f:
- for line in f:
- if 'PKG_CHECK_MODULES' in line:
- res = pkg_re.search(line)
+
+ RecipeHandler.load_binmap(tinfoil.config_data)
+
+ def process_macro(keyword, value):
+ for handler in handlers:
+ if handler.process_macro(srctree, keyword, value, process_value, libdeps, pcdeps, deps, outlines, inherits, values):
+ return
+ logger.debug('Found keyword %s with value "%s"' % (keyword, value))
+ if keyword == 'PKG_CHECK_MODULES':
+ res = pkg_re.search(value)
+ if res:
+ res = dep_re.findall(res.group(1))
if res:
- res = dep_re.findall(res.group(1))
- if res:
- pcdeps.extend([x[0] for x in res])
- inherits.append('pkgconfig')
- if line.lstrip().startswith('AM_GNU_GETTEXT'):
- inherits.append('gettext')
- elif 'AC_CHECK_PROG' in line or 'AC_PATH_PROG' in line:
- res = progs_re.search(line)
+ pcdeps.extend([x[0] for x in res])
+ inherits.append('pkgconfig')
+ elif keyword == 'PKG_CHECK_EXISTS':
+ res = pkgce_re.search(value)
+ if res:
+ res = dep_re.findall(res.group(1))
if res:
- for prog in shlex.split(res.group(1)):
- prog = prog.split()[0]
- progclass = progclassmap.get(prog, None)
- if progclass:
- inherits.append(progclass)
- else:
+ pcdeps.extend([x[0] for x in res])
+ inherits.append('pkgconfig')
+ elif keyword in ('AM_GNU_GETTEXT', 'AM_GLIB_GNU_GETTEXT', 'GETTEXT_PACKAGE'):
+ inherits.append('gettext')
+ elif keyword in ('AC_PROG_INTLTOOL', 'IT_PROG_INTLTOOL'):
+ deps.append('intltool-native')
+ elif keyword == 'AM_PATH_GLIB_2_0':
+ deps.append('glib-2.0')
+ elif keyword in ('AC_CHECK_PROG', 'AC_PATH_PROG', 'AX_WITH_PROG'):
+ res = progs_re.search(value)
+ if res:
+ for prog in shlex.split(res.group(1)):
+ prog = prog.split()[0]
+ for handler in handlers:
+ if handler.process_prog(srctree, keyword, value, prog, deps, outlines, inherits, values):
+ return
+ progclass = progclassmap.get(prog, None)
+ if progclass:
+ inherits.append(progclass)
+ else:
+ progdep = RecipeHandler.recipebinmap.get(prog, None)
+ if not progdep:
progdep = progmap.get(prog, None)
- if progdep:
- deps.append(progdep)
- else:
- if not prog.startswith('$'):
- unmapped.append(prog)
- elif 'AC_CHECK_LIB' in line:
- res = lib_re.search(line)
+ if progdep:
+ deps.append(progdep)
+ elif progdep is None:
+ if not prog.startswith('$'):
+ unmapped.append(prog)
+ elif keyword == 'AC_CHECK_LIB':
+ res = lib_re.search(value)
+ if res:
+ lib = res.group(1)
+ if not lib.startswith('$'):
+ libdeps.append(lib)
+ elif keyword == 'AX_CHECK_LIBRARY':
+ res = libx_re.search(value)
+ if res:
+ lib = res.group(2)
+ if not lib.startswith('$'):
+ header = res.group(1)
+ libdeps.append((lib, header))
+ elif keyword == 'AC_PATH_X':
+ deps.append('libx11')
+ elif keyword in ('AX_BOOST', 'BOOST_REQUIRE'):
+ deps.append('boost')
+ elif keyword in ('AC_PROG_LEX', 'AM_PROG_LEX', 'AX_PROG_FLEX'):
+ deps.append('flex-native')
+ elif keyword in ('AC_PROG_YACC', 'AX_PROG_BISON'):
+ deps.append('bison-native')
+ elif keyword == 'AX_CHECK_ZLIB':
+ deps.append('zlib')
+ elif keyword in ('AX_CHECK_OPENSSL', 'AX_LIB_CRYPTO'):
+ deps.append('openssl')
+ elif keyword == 'AX_LIB_CURL':
+ deps.append('curl')
+ elif keyword == 'AX_LIB_BEECRYPT':
+ deps.append('beecrypt')
+ elif keyword == 'AX_LIB_EXPAT':
+ deps.append('expat')
+ elif keyword == 'AX_LIB_GCRYPT':
+ deps.append('libgcrypt')
+ elif keyword == 'AX_LIB_NETTLE':
+ deps.append('nettle')
+ elif keyword == 'AX_LIB_READLINE':
+ deps.append('readline')
+ elif keyword == 'AX_LIB_SQLITE3':
+ deps.append('sqlite3')
+ elif keyword == 'AX_LIB_TAGLIB':
+ deps.append('taglib')
+ elif keyword in ['AX_PKG_SWIG', 'AC_PROG_SWIG']:
+ deps.append('swig-native')
+ elif keyword == 'AX_PROG_XSLTPROC':
+ deps.append('libxslt-native')
+ elif keyword in ['AC_PYTHON_DEVEL', 'AX_PYTHON_DEVEL', 'AM_PATH_PYTHON']:
+ pythonclass = 'python3native'
+ elif keyword == 'AX_WITH_CURSES':
+ deps.append('ncurses')
+ elif keyword == 'AX_PATH_BDB':
+ deps.append('db')
+ elif keyword == 'AX_PATH_LIB_PCRE':
+ deps.append('libpcre')
+ elif keyword == 'AC_INIT':
+ if extravalues is not None:
+ res = ac_init_re.match(value)
if res:
- lib = res.group(1)
- libdep = recipelibmap.get(lib, None)
- if libdep:
- deps.append(libdep)
- else:
- if libdep is None:
- if not lib.startswith('$'):
- unmappedlibs.append(lib)
- elif 'AC_PATH_X' in line:
- deps.append('libx11')
-
- if unmapped:
- outlines.append('# NOTE: the following prog dependencies are unknown, ignoring: %s' % ' '.join(unmapped))
-
- if unmappedlibs:
- outlines.append('# NOTE: the following library dependencies are unknown, ignoring: %s' % ' '.join(unmappedlibs))
- outlines.append('# (this is based on recipes that have previously been built and packaged)')
+ extravalues['PN'] = process_value(res.group(1))
+ pv = process_value(res.group(2))
+ if validate_pv(pv):
+ extravalues['PV'] = pv
+ elif keyword == 'AM_INIT_AUTOMAKE':
+ if extravalues is not None:
+ if 'PN' not in extravalues:
+ res = am_init_re.match(value)
+ if res:
+ if res.group(1) != 'AC_PACKAGE_NAME':
+ extravalues['PN'] = process_value(res.group(1))
+ pv = process_value(res.group(2))
+ if validate_pv(pv):
+ extravalues['PV'] = pv
+ elif keyword == 'define(':
+ res = define_re.match(value)
+ if res:
+ key = res.group(2).strip('[]')
+ value = process_value(res.group(3))
+ if value is not None:
+ defines[key] = value
+
+ keywords = ['PKG_CHECK_MODULES',
+ 'PKG_CHECK_EXISTS',
+ 'AM_GNU_GETTEXT',
+ 'AM_GLIB_GNU_GETTEXT',
+ 'GETTEXT_PACKAGE',
+ 'AC_PROG_INTLTOOL',
+ 'IT_PROG_INTLTOOL',
+ 'AM_PATH_GLIB_2_0',
+ 'AC_CHECK_PROG',
+ 'AC_PATH_PROG',
+ 'AX_WITH_PROG',
+ 'AC_CHECK_LIB',
+ 'AX_CHECK_LIBRARY',
+ 'AC_PATH_X',
+ 'AX_BOOST',
+ 'BOOST_REQUIRE',
+ 'AC_PROG_LEX',
+ 'AM_PROG_LEX',
+ 'AX_PROG_FLEX',
+ 'AC_PROG_YACC',
+ 'AX_PROG_BISON',
+ 'AX_CHECK_ZLIB',
+ 'AX_CHECK_OPENSSL',
+ 'AX_LIB_CRYPTO',
+ 'AX_LIB_CURL',
+ 'AX_LIB_BEECRYPT',
+ 'AX_LIB_EXPAT',
+ 'AX_LIB_GCRYPT',
+ 'AX_LIB_NETTLE',
+ 'AX_LIB_READLINE'
+ 'AX_LIB_SQLITE3',
+ 'AX_LIB_TAGLIB',
+ 'AX_PKG_SWIG',
+ 'AC_PROG_SWIG',
+ 'AX_PROG_XSLTPROC',
+ 'AC_PYTHON_DEVEL',
+ 'AX_PYTHON_DEVEL',
+ 'AM_PATH_PYTHON',
+ 'AX_WITH_CURSES',
+ 'AX_PATH_BDB',
+ 'AX_PATH_LIB_PCRE',
+ 'AC_INIT',
+ 'AM_INIT_AUTOMAKE',
+ 'define(',
+ ]
+
+ for handler in handlers:
+ handler.extend_keywords(keywords)
+
+ for srcfile in srcfiles:
+ nesting = 0
+ in_keyword = ''
+ partial = ''
+ with open(srcfile, 'r', errors='surrogateescape') as f:
+ for line in f:
+ if in_keyword:
+ partial += ' ' + line.strip()
+ if partial.endswith('\\'):
+ partial = partial[:-1]
+ nesting = nesting + line.count('(') - line.count(')')
+ if nesting == 0:
+ process_macro(in_keyword, partial)
+ partial = ''
+ in_keyword = ''
+ else:
+ for keyword in keywords:
+ if keyword in line:
+ nesting = line.count('(') - line.count(')')
+ if nesting > 0:
+ partial = line.strip()
+ if partial.endswith('\\'):
+ partial = partial[:-1]
+ in_keyword = keyword
+ else:
+ process_macro(keyword, line.strip())
+ break
- recipemap = read_pkgconfig_provides(tinfoil.config_data)
- unmapped = []
- for pcdep in pcdeps:
- recipe = recipemap.get(pcdep, None)
- if recipe:
- deps.append(recipe)
- else:
- if not pcdep.startswith('$'):
- unmapped.append(pcdep)
+ if in_keyword:
+ process_macro(in_keyword, partial)
- deps = set(deps).difference(set(ignoredeps))
+ if extravalues:
+ for k,v in list(extravalues.items()):
+ if v:
+ if v.startswith('$') or v.startswith('@') or v.startswith('%'):
+ del extravalues[k]
+ else:
+ extravalues[k] = v.strip('"\'').rstrip('()')
if unmapped:
- outlines.append('# NOTE: unable to map the following pkg-config dependencies: %s' % ' '.join(unmapped))
- outlines.append('# (this is based on recipes that have previously been built and packaged)')
+ outlines.append('# NOTE: the following prog dependencies are unknown, ignoring: %s' % ' '.join(list(set(unmapped))))
+
+ RecipeHandler.handle_depends(libdeps, pcdeps, deps, outlines, values, tinfoil.config_data)
- if deps:
- values['DEPENDS'] = ' '.join(deps)
+ for handler in handlers:
+ handler.post_process(srctree, libdeps, pcdeps, deps, outlines, inherits, values)
if inherits:
values['inherit'] = ' '.join(list(set(inherits)))
@@ -239,12 +701,41 @@ class AutotoolsRecipeHandler(RecipeHandler):
return values
+class AutotoolsExtensionHandler(object):
+ '''Base class for Autotools extension handlers'''
+ def process_macro(self, srctree, keyword, value, process_value, libdeps, pcdeps, deps, outlines, inherits, values):
+ '''
+ Handle a macro parsed out of an autotools file. Note that if you want this to be called
+ for any macro other than the ones AutotoolsRecipeHandler already looks for, you'll need
+ to add it to the keywords list in extend_keywords().
+ Return True if you've completely handled the passed in macro, otherwise return False.
+ '''
+ return False
+
+ def extend_keywords(self, keywords):
+ '''Adds keywords to be recognised by the parser (so that you get a call to process_macro)'''
+ return
+
+ def process_prog(self, srctree, keyword, value, prog, deps, outlines, inherits, values):
+ '''
+ Handle an AC_PATH_PROG, AC_CHECK_PROG etc. line
+ Return True if you've completely handled the passed in macro, otherwise return False.
+ '''
+ return False
+
+ def post_process(self, srctree, fn, pkg, deps, outlines, inherits, values):
+ '''
+ Apply any desired post-processing on the output
+ '''
+ return
+
+
class MakefileRecipeHandler(RecipeHandler):
- def process(self, srctree, classes, lines_before, lines_after, handled):
+ def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
if 'buildsystem' in handled:
return False
- makefile = RecipeHandler.checkfiles(srctree, ['Makefile'])
+ makefile = RecipeHandler.checkfiles(srctree, ['Makefile', 'makefile', 'GNUmakefile'])
if makefile:
lines_after.append('# NOTE: this is a Makefile-only piece of software, so we cannot generate much of the')
lines_after.append('# recipe automatically - you will need to examine the Makefile yourself and ensure')
@@ -260,7 +751,7 @@ class MakefileRecipeHandler(RecipeHandler):
if scanfile and os.path.exists(scanfile):
values = AutotoolsRecipeHandler.extract_autotools_deps(lines_before, srctree, acfile=scanfile)
classes.extend(values.pop('inherit', '').split())
- for var, value in values.iteritems():
+ for var, value in values.items():
if var == 'DEPENDS':
lines_before.append('# NOTE: some of these dependencies may be optional, check the Makefile and/or upstream documentation')
lines_before.append('%s = "%s"' % (var, value))
@@ -279,7 +770,7 @@ class MakefileRecipeHandler(RecipeHandler):
installtarget = True
try:
- stdout, stderr = bb.process.run('make -qn install', cwd=srctree, shell=True)
+ stdout, stderr = bb.process.run('make -n install', cwd=srctree, shell=True)
except bb.process.ExecutionError as e:
if e.exitcode != 1:
installtarget = False
@@ -287,7 +778,7 @@ class MakefileRecipeHandler(RecipeHandler):
if installtarget:
func.append('# This is a guess; additional arguments may be required')
makeargs = ''
- with open(makefile[0], 'r') as f:
+ with open(makefile[0], 'r', errors='surrogateescape') as f:
for i in range(1, 100):
if 'DESTDIR' in f.readline():
makeargs += " 'DESTDIR=${D}'"
@@ -307,13 +798,77 @@ class MakefileRecipeHandler(RecipeHandler):
self.genfunction(lines_after, 'do_install', ['# Specify install commands here'])
-def plugin_init(pluginlist):
- pass
+class VersionFileRecipeHandler(RecipeHandler):
+ def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
+ if 'PV' not in extravalues:
+ # Look for a VERSION or version file containing a single line consisting
+ # only of a version number
+ filelist = RecipeHandler.checkfiles(srctree, ['VERSION', 'version'])
+ version = None
+ for fileitem in filelist:
+ linecount = 0
+ with open(fileitem, 'r', errors='surrogateescape') as f:
+ for line in f:
+ line = line.rstrip().strip('"\'')
+ linecount += 1
+ if line:
+ if linecount > 1:
+ version = None
+ break
+ else:
+ if validate_pv(line):
+ version = line
+ if version:
+ extravalues['PV'] = version
+ break
+
+
+class SpecFileRecipeHandler(RecipeHandler):
+ def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
+ if 'PV' in extravalues and 'PN' in extravalues:
+ return
+ filelist = RecipeHandler.checkfiles(srctree, ['*.spec'], recursive=True)
+ valuemap = {'Name': 'PN',
+ 'Version': 'PV',
+ 'Summary': 'SUMMARY',
+ 'Url': 'HOMEPAGE',
+ 'License': 'LICENSE'}
+ foundvalues = {}
+ for fileitem in filelist:
+ linecount = 0
+ with open(fileitem, 'r', errors='surrogateescape') as f:
+ for line in f:
+ for value, varname in valuemap.items():
+ if line.startswith(value + ':') and not varname in foundvalues:
+ foundvalues[varname] = line.split(':', 1)[1].strip()
+ break
+ if len(foundvalues) == len(valuemap):
+ break
+ # Drop values containing unexpanded RPM macros
+ for k in list(foundvalues.keys()):
+ if '%' in foundvalues[k]:
+ del foundvalues[k]
+ if 'PV' in foundvalues:
+ if not validate_pv(foundvalues['PV']):
+ del foundvalues['PV']
+ license = foundvalues.pop('LICENSE', None)
+ if license:
+ liccomment = '# NOTE: spec file indicates the license may be "%s"' % license
+ for i, line in enumerate(lines_before):
+ if line.startswith('LICENSE ='):
+ lines_before.insert(i, liccomment)
+ break
+ else:
+ lines_before.append(liccomment)
+ extravalues.update(foundvalues)
def register_recipe_handlers(handlers):
- # These are in a specific order so that the right one is detected first
- handlers.append(CmakeRecipeHandler())
- handlers.append(AutotoolsRecipeHandler())
- handlers.append(SconsRecipeHandler())
- handlers.append(QmakeRecipeHandler())
- handlers.append(MakefileRecipeHandler())
+ # Set priorities with some gaps so that other plugins can insert
+ # their own handlers (so avoid changing these numbers)
+ handlers.append((CmakeRecipeHandler(), 50))
+ handlers.append((AutotoolsRecipeHandler(), 40))
+ handlers.append((SconsRecipeHandler(), 30))
+ handlers.append((QmakeRecipeHandler(), 20))
+ handlers.append((MakefileRecipeHandler(), 10))
+ handlers.append((VersionFileRecipeHandler(), -1))
+ handlers.append((SpecFileRecipeHandler(), -1))
diff --git a/scripts/lib/recipetool/create_buildsys_python.py b/scripts/lib/recipetool/create_buildsys_python.py
index f4f4212559..0b6b042ed1 100644
--- a/scripts/lib/recipetool/create_buildsys_python.py
+++ b/scripts/lib/recipetool/create_buildsys_python.py
@@ -2,18 +2,8 @@
#
# Copyright (C) 2015 Mentor Graphics Corporation
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
+# SPDX-License-Identifier: GPL-2.0-only
#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import ast
import codecs
@@ -41,11 +31,11 @@ def tinfoil_init(instance):
class PythonRecipeHandler(RecipeHandler):
- base_pkgdeps = ['python-core']
- excluded_pkgdeps = ['python-dbg']
- # os.path is provided by python-core
+ base_pkgdeps = ['python3-core']
+ excluded_pkgdeps = ['python3-dbg']
+ # os.path is provided by python3-core
assume_provided = ['builtins', 'os.path']
- # Assumes that the host python builtin_module_names is sane for target too
+ # Assumes that the host python3 builtin_module_names is sane for target too
assume_provided = assume_provided + list(sys.builtin_module_names)
bbvar_map = {
@@ -55,14 +45,12 @@ class PythonRecipeHandler(RecipeHandler):
'Summary': 'SUMMARY',
'Description': 'DESCRIPTION',
'License': 'LICENSE',
- 'Requires': 'RDEPENDS_${PN}',
- 'Provides': 'RPROVIDES_${PN}',
- 'Obsoletes': 'RREPLACES_${PN}',
+ 'Requires': 'RDEPENDS:${PN}',
+ 'Provides': 'RPROVIDES:${PN}',
+ 'Obsoletes': 'RREPLACES:${PN}',
}
# PN/PV are already set by recipetool core & desc can be extremely long
excluded_fields = [
- 'Name',
- 'Version',
'Description',
]
setup_parse_map = {
@@ -88,8 +76,11 @@ class PythonRecipeHandler(RecipeHandler):
]
setuparg_multi_line_values = ['Description']
replacements = [
+ ('License', r' +$', ''),
+ ('License', r'^ +', ''),
('License', r' ', '-'),
- ('License', r'-License$', ''),
+ ('License', r'^GNU-', ''),
+ ('License', r'-[Ll]icen[cs]e(,?-[Vv]ersion)?', ''),
('License', r'^UNKNOWN$', ''),
# Remove currently unhandled version numbers from these variables
@@ -110,7 +101,7 @@ class PythonRecipeHandler(RecipeHandler):
'License :: OSI Approved :: Apple Public Source License': 'APSL',
'License :: OSI Approved :: Artistic License': 'Artistic',
'License :: OSI Approved :: Attribution Assurance License': 'AAL',
- 'License :: OSI Approved :: BSD License': 'BSD',
+ 'License :: OSI Approved :: BSD License': 'BSD-3-Clause',
'License :: OSI Approved :: Common Public License': 'CPL',
'License :: OSI Approved :: Eiffel Forum License': 'EFL',
'License :: OSI Approved :: European Union Public Licence 1.0 (EUPL 1.0)': 'EUPL-1.0',
@@ -159,12 +150,17 @@ class PythonRecipeHandler(RecipeHandler):
def __init__(self):
pass
- def process(self, srctree, classes, lines_before, lines_after, handled):
+ def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
if 'buildsystem' in handled:
return False
- if not RecipeHandler.checkfiles(srctree, ['setup.py']):
- return
+ # Check for non-zero size setup.py files
+ setupfiles = RecipeHandler.checkfiles(srctree, ['setup.py'])
+ for fn in setupfiles:
+ if os.path.getsize(fn):
+ break
+ else:
+ return False
# setup.py is always parsed to get at certain required information, such as
# distutils vs setuptools
@@ -218,67 +214,63 @@ class PythonRecipeHandler(RecipeHandler):
else:
info = self.get_setup_args_info(setupscript)
+ # Grab the license value before applying replacements
+ license_str = info.get('License', '').strip()
+
self.apply_info_replacements(info)
if uses_setuptools:
- classes.append('setuptools')
+ classes.append('setuptools3')
else:
- classes.append('distutils')
+ classes.append('distutils3')
+
+ if license_str:
+ for i, line in enumerate(lines_before):
+ if line.startswith('LICENSE = '):
+ lines_before.insert(i, '# NOTE: License in setup.py/PKGINFO is: %s' % license_str)
+ break
if 'Classifier' in info:
+ existing_licenses = info.get('License', '')
licenses = []
for classifier in info['Classifier']:
if classifier in self.classifier_license_map:
license = self.classifier_license_map[classifier]
+ if license == 'Apache' and 'Apache-2.0' in existing_licenses:
+ license = 'Apache-2.0'
+ elif license == 'GPL':
+ if 'GPL-2.0' in existing_licenses or 'GPLv2' in existing_licenses:
+ license = 'GPL-2.0'
+ elif 'GPL-3.0' in existing_licenses or 'GPLv3' in existing_licenses:
+ license = 'GPL-3.0'
+ elif license == 'LGPL':
+ if 'LGPL-2.1' in existing_licenses or 'LGPLv2.1' in existing_licenses:
+ license = 'LGPL-2.1'
+ elif 'LGPL-2.0' in existing_licenses or 'LGPLv2' in existing_licenses:
+ license = 'LGPL-2.0'
+ elif 'LGPL-3.0' in existing_licenses or 'LGPLv3' in existing_licenses:
+ license = 'LGPL-3.0'
licenses.append(license)
if licenses:
info['License'] = ' & '.join(licenses)
-
# Map PKG-INFO & setup.py fields to bitbake variables
- bbinfo = {}
- for field, values in info.iteritems():
+ for field, values in info.items():
if field in self.excluded_fields:
continue
if field not in self.bbvar_map:
continue
- if isinstance(values, basestring):
+ if isinstance(values, str):
value = values
else:
value = ' '.join(str(v) for v in values if v)
bbvar = self.bbvar_map[field]
- if bbvar not in bbinfo and value:
- bbinfo[bbvar] = value
-
- comment_lic_line = None
- for pos, line in enumerate(list(lines_before)):
- if line.startswith('#') and 'LICENSE' in line:
- comment_lic_line = pos
- elif line.startswith('LICENSE =') and 'LICENSE' in bbinfo:
- if line in ('LICENSE = "Unknown"', 'LICENSE = "CLOSED"'):
- lines_before[pos] = 'LICENSE = "{}"'.format(bbinfo['LICENSE'])
- if line == 'LICENSE = "CLOSED"' and comment_lic_line:
- lines_before[comment_lic_line:pos] = [
- '# WARNING: the following LICENSE value is a best guess - it is your',
- '# responsibility to verify that the value is complete and correct.'
- ]
- del bbinfo['LICENSE']
-
- src_uri_line = None
- for pos, line in enumerate(lines_before):
- if line.startswith('SRC_URI ='):
- src_uri_line = pos
-
- if bbinfo:
- mdinfo = ['']
- for k in sorted(bbinfo):
- v = bbinfo[k]
- mdinfo.append('{} = "{}"'.format(k, v))
- lines_before[src_uri_line-1:src_uri_line-1] = mdinfo
+ if bbvar not in extravalues and value:
+ extravalues[bbvar] = value
mapped_deps, unmapped_deps = self.scan_setup_python_deps(srctree, setup_info, setup_non_literals)
@@ -291,11 +283,11 @@ class PythonRecipeHandler(RecipeHandler):
lines_after.append('# The upstream names may not correspond exactly to bitbake package names.')
lines_after.append('#')
lines_after.append('# Uncomment this line to enable all the optional features.')
- lines_after.append('#PACKAGECONFIG ?= "{}"'.format(' '.join(k.lower() for k in extras_req.iterkeys())))
- for feature, feature_reqs in extras_req.iteritems():
+ lines_after.append('#PACKAGECONFIG ?= "{}"'.format(' '.join(k.lower() for k in extras_req)))
+ for feature, feature_reqs in extras_req.items():
unmapped_deps.difference_update(feature_reqs)
- feature_req_deps = ('python-' + r.replace('.', '-').lower() for r in sorted(feature_reqs))
+ feature_req_deps = ('python3-' + r.replace('.', '-').lower() for r in sorted(feature_reqs))
lines_after.append('PACKAGECONFIG[{}] = ",,,{}"'.format(feature.lower(), ' '.join(feature_req_deps)))
inst_reqs = set()
@@ -306,10 +298,10 @@ class PythonRecipeHandler(RecipeHandler):
if inst_reqs:
unmapped_deps.difference_update(inst_reqs)
- inst_req_deps = ('python-' + r.replace('.', '-').lower() for r in sorted(inst_reqs))
+ inst_req_deps = ('python3-' + r.replace('.', '-').lower() for r in sorted(inst_reqs))
lines_after.append('# WARNING: the following rdepends are from setuptools install_requires. These')
lines_after.append('# upstream names may not correspond exactly to bitbake package names.')
- lines_after.append('RDEPENDS_${{PN}} += "{}"'.format(' '.join(inst_req_deps)))
+ lines_after.append('RDEPENDS:${{PN}} += "{}"'.format(' '.join(inst_req_deps)))
if mapped_deps:
name = info.get('Name')
@@ -321,7 +313,7 @@ class PythonRecipeHandler(RecipeHandler):
lines_after.append('')
lines_after.append('# WARNING: the following rdepends are determined through basic analysis of the')
lines_after.append('# python sources, and might not be 100% accurate.')
- lines_after.append('RDEPENDS_${{PN}} += "{}"'.format(' '.join(sorted(mapped_deps))))
+ lines_after.append('RDEPENDS:${{PN}} += "{}"'.format(' '.join(sorted(mapped_deps))))
unmapped_deps -= set(extensions)
unmapped_deps -= set(self.assume_provided)
@@ -358,7 +350,9 @@ class PythonRecipeHandler(RecipeHandler):
# Naive mapping of setup() arguments to PKG-INFO field names
for d in [info, non_literals]:
- for key, value in d.items():
+ for key, value in list(d.items()):
+ if key is None:
+ continue
new_key = _map(key)
if new_key != key:
del d[key]
@@ -367,7 +361,7 @@ class PythonRecipeHandler(RecipeHandler):
return info, 'setuptools' in imported_modules, non_literals, extensions
def get_setup_args_info(self, setupscript='./setup.py'):
- cmd = ['python', setupscript]
+ cmd = ['python3', setupscript]
info = {}
keys = set(self.bbvar_map.keys())
keys |= set(self.setuparg_list_fields)
@@ -401,7 +395,7 @@ class PythonRecipeHandler(RecipeHandler):
def get_setup_byline(self, fields, setupscript='./setup.py'):
info = {}
- cmd = ['python', setupscript]
+ cmd = ['python3', setupscript]
cmd.extend('--' + self.setuparg_map.get(f, f.lower()) for f in fields)
try:
info_lines = self.run_command(cmd, cwd=os.path.dirname(setupscript)).splitlines()
@@ -433,14 +427,14 @@ class PythonRecipeHandler(RecipeHandler):
return value
value = info[variable]
- if isinstance(value, basestring):
+ if isinstance(value, str):
new_value = replace_value(search, replace, value)
if new_value is None:
del info[variable]
elif new_value != value:
info[variable] = new_value
- elif hasattr(value, 'iteritems'):
- for dkey, dvalue in value.iteritems():
+ elif hasattr(value, 'items'):
+ for dkey, dvalue in list(value.items()):
new_list = []
for pos, a_value in enumerate(dvalue):
new_value = replace_value(search, replace, a_value)
@@ -501,8 +495,10 @@ class PythonRecipeHandler(RecipeHandler):
for dep in scanned_deps:
mapped = provided_packages.get(dep)
if mapped:
+ logger.debug('Mapped %s to %s' % (dep, mapped))
mapped_deps.add(mapped)
else:
+ logger.debug('Could not map %s' % dep)
unmapped_deps.add(dep)
return mapped_deps, unmapped_deps
@@ -533,11 +529,11 @@ class PythonRecipeHandler(RecipeHandler):
def parse_pkgdata_for_python_packages(self):
suffixes = [t[0] for t in imp.get_suffixes()]
- pkgdata_dir = tinfoil.config_data.getVar('PKGDATA_DIR', True)
+ pkgdata_dir = tinfoil.config_data.getVar('PKGDATA_DIR')
ldata = tinfoil.config_data.createCopy()
- bb.parse.handle('classes/python-dir.bbclass', ldata, True)
- python_sitedir = ldata.getVar('PYTHON_SITEPACKAGES_DIR', True)
+ bb.parse.handle('classes/python3-dir.bbclass', ldata, True)
+ python_sitedir = ldata.getVar('PYTHON_SITEPACKAGES_DIR')
dynload_dir = os.path.join(os.path.dirname(python_sitedir), 'lib-dynload')
python_dirs = [python_sitedir + os.sep,
@@ -549,13 +545,13 @@ class PythonRecipeHandler(RecipeHandler):
with open(pkgdatafile, 'r') as f:
for line in f.readlines():
field, value = line.split(': ', 1)
- if field == 'FILES_INFO':
+ if field.startswith('FILES_INFO'):
files_info = ast.literal_eval(value)
break
else:
continue
- for fn in files_info.iterkeys():
+ for fn in files_info:
for suffix in suffixes:
if fn.endswith(suffix):
break
@@ -563,6 +559,8 @@ class PythonRecipeHandler(RecipeHandler):
continue
if fn.startswith(dynload_dir + os.sep):
+ if '/.debug/' in fn:
+ continue
base = os.path.basename(fn)
provided = base.split('.', 1)[0]
packages[provided] = os.path.basename(pkgdatafile)
@@ -590,7 +588,7 @@ class PythonRecipeHandler(RecipeHandler):
if 'stderr' not in popenargs:
popenargs['stderr'] = subprocess.STDOUT
try:
- return subprocess.check_output(cmd, **popenargs)
+ return subprocess.check_output(cmd, **popenargs).decode('utf-8')
except OSError as exc:
logger.error('Unable to run `{}`: {}', ' '.join(cmd), exc)
raise
@@ -605,7 +603,7 @@ def gather_setup_info(fileobj):
visitor.visit(parsed)
non_literals, extensions = {}, []
- for key, value in visitor.keywords.items():
+ for key, value in list(visitor.keywords.items()):
if key == 'ext_modules':
if isinstance(value, list):
for ext in value:
@@ -637,7 +635,7 @@ class SetupScriptVisitor(ast.NodeVisitor):
def visit_setup(self, node):
call = LiteralAstTransform().visit(node)
self.keywords = call.keywords
- for k, v in self.keywords.iteritems():
+ for k, v in self.keywords.items():
if has_non_literals(v):
self.non_literals.append(k)
@@ -703,18 +701,14 @@ class LiteralAstTransform(ast.NodeTransformer):
def has_non_literals(value):
if isinstance(value, ast.AST):
return True
- elif isinstance(value, basestring):
+ elif isinstance(value, str):
return False
- elif hasattr(value, 'itervalues'):
- return any(has_non_literals(v) for v in value.itervalues())
+ elif hasattr(value, 'values'):
+ return any(has_non_literals(v) for v in value.values())
elif hasattr(value, '__iter__'):
return any(has_non_literals(v) for v in value)
-def plugin_init(pluginlist):
- pass
-
-
def register_recipe_handlers(handlers):
# We need to make sure this is ahead of the makefile fallback handler
- handlers.insert(0, PythonRecipeHandler())
+ handlers.append((PythonRecipeHandler(), 70))
diff --git a/scripts/lib/recipetool/create_kernel.py b/scripts/lib/recipetool/create_kernel.py
new file mode 100644
index 0000000000..5740589a68
--- /dev/null
+++ b/scripts/lib/recipetool/create_kernel.py
@@ -0,0 +1,89 @@
+# Recipe creation tool - kernel support plugin
+#
+# Copyright (C) 2016 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import re
+import logging
+from recipetool.create import RecipeHandler, read_pkgconfig_provides, validate_pv
+
+logger = logging.getLogger('recipetool')
+
+tinfoil = None
+
+def tinfoil_init(instance):
+ global tinfoil
+ tinfoil = instance
+
+
+class KernelRecipeHandler(RecipeHandler):
+ def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
+ import bb.process
+ if 'buildsystem' in handled:
+ return False
+
+ for tell in ['arch', 'firmware', 'Kbuild', 'Kconfig']:
+ if not os.path.exists(os.path.join(srctree, tell)):
+ return False
+
+ handled.append('buildsystem')
+ del lines_after[:]
+ del classes[:]
+ template = os.path.join(tinfoil.config_data.getVar('COREBASE'), 'meta-skeleton', 'recipes-kernel', 'linux', 'linux-yocto-custom.bb')
+ def handle_var(varname, origvalue, op, newlines):
+ if varname in ['SRCREV', 'SRCREV_machine']:
+ while newlines[-1].startswith('#'):
+ del newlines[-1]
+ try:
+ stdout, _ = bb.process.run('git rev-parse HEAD', cwd=srctree, shell=True)
+ except bb.process.ExecutionError as e:
+ stdout = None
+ if stdout:
+ return stdout.strip(), op, 0, True
+ elif varname == 'LINUX_VERSION':
+ makefile = os.path.join(srctree, 'Makefile')
+ if os.path.exists(makefile):
+ kversion = -1
+ kpatchlevel = -1
+ ksublevel = -1
+ kextraversion = ''
+ with open(makefile, 'r', errors='surrogateescape') as f:
+ for i, line in enumerate(f):
+ if i > 10:
+ break
+ if line.startswith('VERSION ='):
+ kversion = int(line.split('=')[1].strip())
+ elif line.startswith('PATCHLEVEL ='):
+ kpatchlevel = int(line.split('=')[1].strip())
+ elif line.startswith('SUBLEVEL ='):
+ ksublevel = int(line.split('=')[1].strip())
+ elif line.startswith('EXTRAVERSION ='):
+ kextraversion = line.split('=')[1].strip()
+ version = ''
+ if kversion > -1 and kpatchlevel > -1:
+ version = '%d.%d' % (kversion, kpatchlevel)
+ if ksublevel > -1:
+ version += '.%d' % ksublevel
+ version += kextraversion
+ if version:
+ return version, op, 0, True
+ elif varname == 'SRC_URI':
+ while newlines[-1].startswith('#'):
+ del newlines[-1]
+ elif varname == 'COMPATIBLE_MACHINE':
+ while newlines[-1].startswith('#'):
+ del newlines[-1]
+ machine = tinfoil.config_data.getVar('MACHINE')
+ return machine, op, 0, True
+ return origvalue, op, 0, True
+ with open(template, 'r') as f:
+ varlist = ['SRCREV', 'SRCREV_machine', 'SRC_URI', 'LINUX_VERSION', 'COMPATIBLE_MACHINE']
+ (_, newlines) = bb.utils.edit_metadata(f, varlist, handle_var)
+ lines_before[:] = [line.rstrip('\n') for line in newlines]
+
+ return True
+
+def register_recipe_handlers(handlers):
+ handlers.append((KernelRecipeHandler(), 100))
diff --git a/scripts/lib/recipetool/create_kmod.py b/scripts/lib/recipetool/create_kmod.py
new file mode 100644
index 0000000000..cc00106961
--- /dev/null
+++ b/scripts/lib/recipetool/create_kmod.py
@@ -0,0 +1,142 @@
+# Recipe creation tool - kernel module support plugin
+#
+# Copyright (C) 2016 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import re
+import logging
+from recipetool.create import RecipeHandler, read_pkgconfig_provides, validate_pv
+
+logger = logging.getLogger('recipetool')
+
+tinfoil = None
+
+def tinfoil_init(instance):
+ global tinfoil
+ tinfoil = instance
+
+
+class KernelModuleRecipeHandler(RecipeHandler):
+ def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
+ import bb.process
+ if 'buildsystem' in handled:
+ return False
+
+ module_inc_re = re.compile(r'^#include\s+<linux/module.h>$')
+ makefiles = []
+ is_module = False
+
+ makefiles = []
+
+ files = RecipeHandler.checkfiles(srctree, ['*.c', '*.h'], recursive=True, excludedirs=['contrib', 'test', 'examples'])
+ if files:
+ for cfile in files:
+ # Look in same dir or parent for Makefile
+ for makefile in [os.path.join(os.path.dirname(cfile), 'Makefile'), os.path.join(os.path.dirname(os.path.dirname(cfile)), 'Makefile')]:
+ if makefile in makefiles:
+ break
+ else:
+ if os.path.exists(makefile):
+ makefiles.append(makefile)
+ break
+ else:
+ continue
+ with open(cfile, 'r', errors='surrogateescape') as f:
+ for line in f:
+ if module_inc_re.match(line.strip()):
+ is_module = True
+ break
+ if is_module:
+ break
+
+ if is_module:
+ classes.append('module')
+ handled.append('buildsystem')
+ # module.bbclass and the classes it inherits do most of the hard
+ # work, but we need to tweak it slightly depending on what the
+ # Makefile does (and there is a range of those)
+ # Check the makefile for the appropriate install target
+ install_lines = []
+ compile_lines = []
+ in_install = False
+ in_compile = False
+ install_target = None
+ with open(makefile, 'r', errors='surrogateescape') as f:
+ for line in f:
+ if line.startswith('install:'):
+ if not install_lines:
+ in_install = True
+ install_target = 'install'
+ elif line.startswith('modules_install:'):
+ install_lines = []
+ in_install = True
+ install_target = 'modules_install'
+ elif line.startswith('modules:'):
+ compile_lines = []
+ in_compile = True
+ elif line.startswith(('all:', 'default:')):
+ if not compile_lines:
+ in_compile = True
+ elif line:
+ if line[0] == '\t':
+ if in_install:
+ install_lines.append(line)
+ elif in_compile:
+ compile_lines.append(line)
+ elif ':' in line:
+ in_install = False
+ in_compile = False
+
+ def check_target(lines, install):
+ kdirpath = ''
+ manual_install = False
+ for line in lines:
+ splitline = line.split()
+ if splitline[0] in ['make', 'gmake', '$(MAKE)']:
+ if '-C' in splitline:
+ idx = splitline.index('-C') + 1
+ if idx < len(splitline):
+ kdirpath = splitline[idx]
+ break
+ elif install and splitline[0] == 'install':
+ if '.ko' in line:
+ manual_install = True
+ return kdirpath, manual_install
+
+ kdirpath = None
+ manual_install = False
+ if install_lines:
+ kdirpath, manual_install = check_target(install_lines, install=True)
+ if compile_lines and not kdirpath:
+ kdirpath, _ = check_target(compile_lines, install=False)
+
+ if manual_install or not install_lines:
+ lines_after.append('EXTRA_OEMAKE:append:task-install = " -C ${STAGING_KERNEL_DIR} M=${S}"')
+ elif install_target and install_target != 'modules_install':
+ lines_after.append('MODULES_INSTALL_TARGET = "install"')
+
+ warnmsg = None
+ kdirvar = None
+ if kdirpath:
+ res = re.match(r'\$\(([^$)]+)\)', kdirpath)
+ if res:
+ kdirvar = res.group(1)
+ if kdirvar != 'KERNEL_SRC':
+ lines_after.append('EXTRA_OEMAKE += "%s=${STAGING_KERNEL_DIR}"' % kdirvar)
+ elif kdirpath.startswith('/lib/'):
+ warnmsg = 'Kernel path in install makefile is hardcoded - you will need to patch the makefile'
+ if not kdirvar and not warnmsg:
+ warnmsg = 'Unable to find means of passing kernel path into install makefile - if kernel path is hardcoded you will need to patch the makefile'
+ if warnmsg:
+ warnmsg += '. Note that the variable KERNEL_SRC will be passed in as the kernel source path.'
+ logger.warning(warnmsg)
+ lines_after.append('# %s' % warnmsg)
+
+ return True
+
+ return False
+
+def register_recipe_handlers(handlers):
+ handlers.append((KernelModuleRecipeHandler(), 15))
diff --git a/scripts/lib/recipetool/create_npm.py b/scripts/lib/recipetool/create_npm.py
new file mode 100644
index 0000000000..3394a89970
--- /dev/null
+++ b/scripts/lib/recipetool/create_npm.py
@@ -0,0 +1,299 @@
+# Copyright (C) 2016 Intel Corporation
+# Copyright (C) 2020 Savoir-Faire Linux
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+"""Recipe creation tool - npm module support plugin"""
+
+import json
+import logging
+import os
+import re
+import sys
+import tempfile
+import bb
+from bb.fetch2.npm import NpmEnvironment
+from bb.fetch2.npmsw import foreach_dependencies
+from recipetool.create import RecipeHandler
+from recipetool.create import get_license_md5sums
+from recipetool.create import guess_license
+from recipetool.create import split_pkg_licenses
+logger = logging.getLogger('recipetool')
+
+TINFOIL = None
+
+def tinfoil_init(instance):
+ """Initialize tinfoil"""
+ global TINFOIL
+ TINFOIL = instance
+
+class NpmRecipeHandler(RecipeHandler):
+ """Class to handle the npm recipe creation"""
+
+ @staticmethod
+ def _npm_name(name):
+ """Generate a Yocto friendly npm name"""
+ name = re.sub("/", "-", name)
+ name = name.lower()
+ name = re.sub(r"[^\-a-z0-9]", "", name)
+ name = name.strip("-")
+ return name
+
+ @staticmethod
+ def _get_registry(lines):
+ """Get the registry value from the 'npm://registry' url"""
+ registry = None
+
+ def _handle_registry(varname, origvalue, op, newlines):
+ nonlocal registry
+ if origvalue.startswith("npm://"):
+ registry = re.sub(r"^npm://", "http://", origvalue.split(";")[0])
+ return origvalue, None, 0, True
+
+ bb.utils.edit_metadata(lines, ["SRC_URI"], _handle_registry)
+
+ return registry
+
+ @staticmethod
+ def _ensure_npm():
+ """Check if the 'npm' command is available in the recipes"""
+ if not TINFOIL.recipes_parsed:
+ TINFOIL.parse_recipes()
+
+ try:
+ d = TINFOIL.parse_recipe("nodejs-native")
+ except bb.providers.NoProvider:
+ bb.error("Nothing provides 'nodejs-native' which is required for the build")
+ bb.note("You will likely need to add a layer that provides nodejs")
+ sys.exit(14)
+
+ bindir = d.getVar("STAGING_BINDIR_NATIVE")
+ npmpath = os.path.join(bindir, "npm")
+
+ if not os.path.exists(npmpath):
+ TINFOIL.build_targets("nodejs-native", "addto_recipe_sysroot")
+
+ if not os.path.exists(npmpath):
+ bb.error("Failed to add 'npm' to sysroot")
+ sys.exit(14)
+
+ return bindir
+
+ @staticmethod
+ def _npm_global_configs(dev):
+ """Get the npm global configuration"""
+ configs = []
+
+ if dev:
+ configs.append(("also", "development"))
+ else:
+ configs.append(("only", "production"))
+
+ configs.append(("save", "false"))
+ configs.append(("package-lock", "false"))
+ configs.append(("shrinkwrap", "false"))
+ return configs
+
+ def _run_npm_install(self, d, srctree, registry, dev):
+ """Run the 'npm install' command without building the addons"""
+ configs = self._npm_global_configs(dev)
+ configs.append(("ignore-scripts", "true"))
+
+ if registry:
+ configs.append(("registry", registry))
+
+ bb.utils.remove(os.path.join(srctree, "node_modules"), recurse=True)
+
+ env = NpmEnvironment(d, configs=configs)
+ env.run("npm install", workdir=srctree)
+
+ def _generate_shrinkwrap(self, d, srctree, dev):
+ """Check and generate the 'npm-shrinkwrap.json' file if needed"""
+ configs = self._npm_global_configs(dev)
+
+ env = NpmEnvironment(d, configs=configs)
+ env.run("npm shrinkwrap", workdir=srctree)
+
+ return os.path.join(srctree, "npm-shrinkwrap.json")
+
+ def _handle_licenses(self, srctree, shrinkwrap_file, dev):
+ """Return the extra license files and the list of packages"""
+ licfiles = []
+ packages = {}
+
+ # Handle the parent package
+ packages["${PN}"] = ""
+
+ def _licfiles_append_fallback_readme_files(destdir):
+ """Append README files as fallback to license files if a license files is missing"""
+
+ fallback = True
+ readmes = []
+ basedir = os.path.join(srctree, destdir)
+ for fn in os.listdir(basedir):
+ upper = fn.upper()
+ if upper.startswith("README"):
+ fullpath = os.path.join(basedir, fn)
+ readmes.append(fullpath)
+ if upper.startswith("COPYING") or "LICENCE" in upper or "LICENSE" in upper:
+ fallback = False
+ if fallback:
+ for readme in readmes:
+ licfiles.append(os.path.relpath(readme, srctree))
+
+ # Handle the dependencies
+ def _handle_dependency(name, params, deptree):
+ suffix = "-".join([self._npm_name(dep) for dep in deptree])
+ destdirs = [os.path.join("node_modules", dep) for dep in deptree]
+ destdir = os.path.join(*destdirs)
+ packages["${PN}-" + suffix] = destdir
+ _licfiles_append_fallback_readme_files(destdir)
+
+ with open(shrinkwrap_file, "r") as f:
+ shrinkwrap = json.load(f)
+
+ foreach_dependencies(shrinkwrap, _handle_dependency, dev)
+
+ return licfiles, packages
+
+ def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
+ """Handle the npm recipe creation"""
+
+ if "buildsystem" in handled:
+ return False
+
+ files = RecipeHandler.checkfiles(srctree, ["package.json"])
+
+ if not files:
+ return False
+
+ with open(files[0], "r") as f:
+ data = json.load(f)
+
+ if "name" not in data or "version" not in data:
+ return False
+
+ extravalues["PN"] = self._npm_name(data["name"])
+ extravalues["PV"] = data["version"]
+
+ if "description" in data:
+ extravalues["SUMMARY"] = data["description"]
+
+ if "homepage" in data:
+ extravalues["HOMEPAGE"] = data["homepage"]
+
+ dev = bb.utils.to_boolean(str(extravalues.get("NPM_INSTALL_DEV", "0")), False)
+ registry = self._get_registry(lines_before)
+
+ bb.note("Checking if npm is available ...")
+ # The native npm is used here (and not the host one) to ensure that the
+ # npm version is high enough to ensure an efficient dependency tree
+ # resolution and avoid issue with the shrinkwrap file format.
+ # Moreover the native npm is mandatory for the build.
+ bindir = self._ensure_npm()
+
+ d = bb.data.createCopy(TINFOIL.config_data)
+ d.prependVar("PATH", bindir + ":")
+ d.setVar("S", srctree)
+
+ bb.note("Generating shrinkwrap file ...")
+ # To generate the shrinkwrap file the dependencies have to be installed
+ # first. During the generation process some files may be updated /
+ # deleted. By default devtool tracks the diffs in the srctree and raises
+ # errors when finishing the recipe if some diffs are found.
+ git_exclude_file = os.path.join(srctree, ".git", "info", "exclude")
+ if os.path.exists(git_exclude_file):
+ with open(git_exclude_file, "r+") as f:
+ lines = f.readlines()
+ for line in ["/node_modules/", "/npm-shrinkwrap.json"]:
+ if line not in lines:
+ f.write(line + "\n")
+
+ lock_file = os.path.join(srctree, "package-lock.json")
+ lock_copy = lock_file + ".copy"
+ if os.path.exists(lock_file):
+ bb.utils.copyfile(lock_file, lock_copy)
+
+ self._run_npm_install(d, srctree, registry, dev)
+ shrinkwrap_file = self._generate_shrinkwrap(d, srctree, dev)
+
+ with open(shrinkwrap_file, "r") as f:
+ shrinkwrap = json.load(f)
+
+ if os.path.exists(lock_copy):
+ bb.utils.movefile(lock_copy, lock_file)
+
+ # Add the shrinkwrap file as 'extrafiles'
+ shrinkwrap_copy = shrinkwrap_file + ".copy"
+ bb.utils.copyfile(shrinkwrap_file, shrinkwrap_copy)
+ extravalues.setdefault("extrafiles", {})
+ extravalues["extrafiles"]["npm-shrinkwrap.json"] = shrinkwrap_copy
+
+ url_local = "npmsw://%s" % shrinkwrap_file
+ url_recipe= "npmsw://${THISDIR}/${BPN}/npm-shrinkwrap.json"
+
+ if dev:
+ url_local += ";dev=1"
+ url_recipe += ";dev=1"
+
+ # Add the npmsw url in the SRC_URI of the generated recipe
+ def _handle_srcuri(varname, origvalue, op, newlines):
+ """Update the version value and add the 'npmsw://' url"""
+ value = origvalue.replace("version=" + data["version"], "version=${PV}")
+ value = value.replace("version=latest", "version=${PV}")
+ values = [line.strip() for line in value.strip('\n').splitlines()]
+ if "dependencies" in shrinkwrap:
+ values.append(url_recipe)
+ return values, None, 4, False
+
+ (_, newlines) = bb.utils.edit_metadata(lines_before, ["SRC_URI"], _handle_srcuri)
+ lines_before[:] = [line.rstrip('\n') for line in newlines]
+
+ # In order to generate correct licence checksums in the recipe the
+ # dependencies have to be fetched again using the npmsw url
+ bb.note("Fetching npm dependencies ...")
+ bb.utils.remove(os.path.join(srctree, "node_modules"), recurse=True)
+ fetcher = bb.fetch2.Fetch([url_local], d)
+ fetcher.download()
+ fetcher.unpack(srctree)
+
+ bb.note("Handling licences ...")
+ (licfiles, packages) = self._handle_licenses(srctree, shrinkwrap_file, dev)
+
+ def _guess_odd_license(licfiles):
+ import bb
+
+ md5sums = get_license_md5sums(d, linenumbers=True)
+
+ chksums = []
+ licenses = []
+ for licfile in licfiles:
+ f = os.path.join(srctree, licfile)
+ md5value = bb.utils.md5_file(f)
+ (license, beginline, endline, md5) = md5sums.get(md5value,
+ (None, "", "", ""))
+ if not license:
+ license = "Unknown"
+ logger.info("Please add the following line for '%s' to a "
+ "'lib/recipetool/licenses.csv' and replace `Unknown`, "
+ "`X`, `Y` and `MD5` with the license, begin line, "
+ "end line and partial MD5 checksum:\n" \
+ "%s,Unknown,X,Y,MD5" % (licfile, md5value))
+ chksums.append("file://%s%s%s;md5=%s" % (licfile,
+ ";beginline=%s" % (beginline) if beginline else "",
+ ";endline=%s" % (endline) if endline else "",
+ md5 if md5 else md5value))
+ licenses.append((license, licfile, md5value))
+ return (licenses, chksums)
+
+ (licenses, extravalues["LIC_FILES_CHKSUM"]) = _guess_odd_license(licfiles)
+ split_pkg_licenses([*licenses, *guess_license(srctree, d)], packages, lines_after)
+
+ classes.append("npm")
+ handled.append("buildsystem")
+
+ return True
+
+def register_recipe_handlers(handlers):
+ """Register the npm handler"""
+ handlers.append((NpmRecipeHandler(), 60))
diff --git a/scripts/lib/recipetool/edit.py b/scripts/lib/recipetool/edit.py
new file mode 100644
index 0000000000..d5b980a1c0
--- /dev/null
+++ b/scripts/lib/recipetool/edit.py
@@ -0,0 +1,44 @@
+# Recipe creation tool - edit plugin
+#
+# This sub-command edits the recipe and appends for the specified target
+#
+# Example: recipetool edit busybox
+#
+# Copyright (C) 2018 Mentor Graphics Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import argparse
+import errno
+import logging
+import os
+import re
+import subprocess
+import sys
+import scriptutils
+
+
+logger = logging.getLogger('recipetool')
+tinfoil = None
+
+
+def tinfoil_init(instance):
+ global tinfoil
+ tinfoil = instance
+
+
+def edit(args):
+ import oe.recipeutils
+
+ recipe_path = tinfoil.get_recipe_file(args.target)
+ appends = tinfoil.get_file_appends(recipe_path)
+
+ return scriptutils.run_editor([recipe_path] + list(appends), logger)
+
+
+def register_commands(subparsers):
+ parser = subparsers.add_parser('edit',
+ help='Edit the recipe and appends for the specified target. This obeys $VISUAL if set, otherwise $EDITOR, otherwise vi.')
+ parser.add_argument('target', help='Target recipe/provide to edit')
+ parser.set_defaults(func=edit, parserecipes=True)
diff --git a/scripts/lib/recipetool/licenses.csv b/scripts/lib/recipetool/licenses.csv
new file mode 100644
index 0000000000..0d3fb0607b
--- /dev/null
+++ b/scripts/lib/recipetool/licenses.csv
@@ -0,0 +1,37 @@
+0636e73ff0215e8d672dc4c32c317bb3,GPLv2
+12f884d2ae1ff87c09e5b7ccc2c4ca7e,GPLv2
+18810669f13b87348459e611d31ab760,GPLv2
+252890d9eee26aab7b432e8b8a616475,LGPLv2
+2d5025d4aa3495befef8f17206a5b0a1,LGPLv2.1
+3214f080875748938ba060314b4f727d,LGPLv2
+385c55653886acac3821999a3ccd17b3,Artistic-1.0 | GPL-2.0
+393a5ca445f6965873eca0259a17f833,GPLv2
+3b83ef96387f14655fc854ddc3c6bd57,Apache-2.0
+3bf50002aefd002f49e7bb854063f7e7,LGPLv2
+4325afd396febcb659c36b49533135d4,GPLv2
+4fbd65380cdd255951079008b364516c,LGPLv2.1
+54c7042be62e169199200bc6477f04d1,BSD-3-Clause
+55ca817ccb7d5b5b66355690e9abc605,LGPLv2
+59530bdf33659b29e73d4adb9f9f6552,GPLv2
+5f30f0716dfdd0d91eb439ebec522ec2,LGPLv2
+6a6a8e020838b23406c81b19c1d46df6,LGPLv3
+751419260aa954499f7abaabaa882bbe,GPLv2
+7fbc338309ac38fefcd64b04bb903e34,LGPLv2.1
+8ca43cbc842c2336e835926c2166c28b,GPLv2
+94d55d512a9ba36caa9b7df079bae19f,GPLv2
+9ac2e7cff1ddaf48b6eab6028f23ef88,GPLv2
+9f604d8a4f8e74f4f5140845a21b6674,LGPLv2
+a6f89e2100d9b6cdffcea4f398e37343,LGPLv2.1
+b234ee4d69f5fce4486a80fdaf4a4263,GPLv2
+bbb461211a33b134d42ed5ee802b37ff,LGPLv2.1
+bfe1f75d606912a4111c90743d6c7325,MPL-1.1
+c93c0550bd3173f4504b2cbd8991e50b,GPLv2
+d32239bcb673463ab874e80d47fae504,GPLv3
+d7810fab7487fb0aad327b76f1be7cd7,GPLv2
+d8045f3b8f929c1cb29a1e3fd737b499,LGPLv2.1
+db979804f025cf55aabec7129cb671ed,LGPLv2
+eb723b61539feef013de476e68b5c50a,GPLv2
+ebb5c50ab7cab4baeffba14977030c07,GPLv2
+f27defe1e96c2e1ecd4e0c9be8967949,GPLv3
+fad9b3332be894bab9bc501572864b29,LGPLv2.1
+fbc093901857fcd118f065f900982c24,LGPLv2.1
diff --git a/scripts/lib/recipetool/newappend.py b/scripts/lib/recipetool/newappend.py
new file mode 100644
index 0000000000..08e2474dc4
--- /dev/null
+++ b/scripts/lib/recipetool/newappend.py
@@ -0,0 +1,79 @@
+# Recipe creation tool - newappend plugin
+#
+# This sub-command creates a bbappend for the specified target and prints the
+# path to the bbappend.
+#
+# Example: recipetool newappend meta-mylayer busybox
+#
+# Copyright (C) 2015 Christopher Larson <kergoth@gmail.com>
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import argparse
+import errno
+import logging
+import os
+import re
+import subprocess
+import sys
+import scriptutils
+
+
+logger = logging.getLogger('recipetool')
+tinfoil = None
+
+
+def tinfoil_init(instance):
+ global tinfoil
+ tinfoil = instance
+
+
+def layer(layerpath):
+ if not os.path.exists(os.path.join(layerpath, 'conf', 'layer.conf')):
+ raise argparse.ArgumentTypeError('{0!r} must be a path to a valid layer'.format(layerpath))
+ return layerpath
+
+
+def newappend(args):
+ import oe.recipeutils
+
+ recipe_path = tinfoil.get_recipe_file(args.target)
+
+ rd = tinfoil.config_data.createCopy()
+ rd.setVar('FILE', recipe_path)
+ append_path, path_ok = oe.recipeutils.get_bbappend_path(rd, args.destlayer, args.wildcard_version)
+ if not append_path:
+ logger.error('Unable to determine layer directory containing %s', recipe_path)
+ return 1
+
+ if not path_ok:
+ logger.warning('Unable to determine correct subdirectory path for bbappend file - check that what %s adds to BBFILES also matches .bbappend files. Using %s for now, but until you fix this the bbappend will not be applied.', os.path.join(args.destlayer, 'conf', 'layer.conf'), os.path.dirname(append_path))
+
+ layerdirs = [os.path.abspath(layerdir) for layerdir in rd.getVar('BBLAYERS').split()]
+ if not os.path.abspath(args.destlayer) in layerdirs:
+ logger.warning('Specified layer is not currently enabled in bblayers.conf, you will need to add it before this bbappend will be active')
+
+ if not os.path.exists(append_path):
+ bb.utils.mkdirhier(os.path.dirname(append_path))
+
+ try:
+ open(append_path, 'a').close()
+ except (OSError, IOError) as exc:
+ logger.critical(str(exc))
+ return 1
+
+ if args.edit:
+ return scriptutils.run_editor([append_path, recipe_path], logger)
+ else:
+ print(append_path)
+
+
+def register_commands(subparsers):
+ parser = subparsers.add_parser('newappend',
+ help='Create a bbappend for the specified target in the specified layer')
+ parser.add_argument('-e', '--edit', help='Edit the new append. This obeys $VISUAL if set, otherwise $EDITOR, otherwise vi.', action='store_true')
+ parser.add_argument('-w', '--wildcard-version', help='Use wildcard to make the bbappend apply to any recipe version', action='store_true')
+ parser.add_argument('destlayer', help='Base directory of the destination layer to write the bbappend to', type=layer)
+ parser.add_argument('target', help='Target recipe/provide to append')
+ parser.set_defaults(func=newappend, parserecipes=True)
diff --git a/scripts/lib/recipetool/setvar.py b/scripts/lib/recipetool/setvar.py
new file mode 100644
index 0000000000..f8e2ee75fb
--- /dev/null
+++ b/scripts/lib/recipetool/setvar.py
@@ -0,0 +1,65 @@
+# Recipe creation tool - set variable plugin
+#
+# Copyright (C) 2015 Intel Corporation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import sys
+import os
+import argparse
+import glob
+import fnmatch
+import re
+import logging
+import scriptutils
+
+logger = logging.getLogger('recipetool')
+
+tinfoil = None
+plugins = None
+
+def tinfoil_init(instance):
+ global tinfoil
+ tinfoil = instance
+
+def setvar(args):
+ import oe.recipeutils
+
+ if args.delete:
+ if args.value:
+ logger.error('-D/--delete and specifying a value are mutually exclusive')
+ return 1
+ value = None
+ else:
+ if args.value is None:
+ logger.error('You must specify a value if not using -D/--delete')
+ return 1
+ value = args.value
+ varvalues = {args.varname: value}
+
+ if args.recipe_only:
+ patches = [oe.recipeutils.patch_recipe_file(args.recipefile, varvalues, patch=args.patch)]
+ else:
+ rd = tinfoil.parse_recipe_file(args.recipefile, False)
+ if not rd:
+ return 1
+ patches = oe.recipeutils.patch_recipe(rd, args.recipefile, varvalues, patch=args.patch)
+ if args.patch:
+ for patch in patches:
+ for line in patch:
+ sys.stdout.write(line)
+ return 0
+
+
+def register_commands(subparsers):
+ parser_setvar = subparsers.add_parser('setvar',
+ help='Set a variable within a recipe',
+ description='Adds/updates the value a variable is set to in a recipe')
+ parser_setvar.add_argument('recipefile', help='Recipe file to update')
+ parser_setvar.add_argument('varname', help='Variable name to set')
+ parser_setvar.add_argument('value', nargs='?', help='New value to set the variable to')
+ parser_setvar.add_argument('--recipe-only', '-r', help='Do not set variable in any include file if present', action='store_true')
+ parser_setvar.add_argument('--patch', '-p', help='Create a patch to make the change instead of modifying the recipe', action='store_true')
+ parser_setvar.add_argument('--delete', '-D', help='Delete the specified value instead of setting it', action='store_true')
+ parser_setvar.set_defaults(func=setvar)
diff --git a/scripts/lib/wic/3rdparty/pykickstart/handlers/__init__.py b/scripts/lib/resulttool/__init__.py
index e69de29bb2..e69de29bb2 100644
--- a/scripts/lib/wic/3rdparty/pykickstart/handlers/__init__.py
+++ b/scripts/lib/resulttool/__init__.py
diff --git a/scripts/lib/resulttool/log.py b/scripts/lib/resulttool/log.py
new file mode 100644
index 0000000000..eb3927ec82
--- /dev/null
+++ b/scripts/lib/resulttool/log.py
@@ -0,0 +1,104 @@
+# resulttool - Show logs
+#
+# Copyright (c) 2019 Garmin International
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+import os
+import resulttool.resultutils as resultutils
+
+def show_ptest(result, ptest, logger):
+ logdata = resultutils.ptestresult_get_log(result, ptest)
+ if logdata is not None:
+ print(logdata)
+ return 0
+
+ print("ptest '%s' log not found" % ptest)
+ return 1
+
+def show_reproducible(result, reproducible, logger):
+ try:
+ print(result['reproducible'][reproducible]['diffoscope.text'])
+ return 0
+
+ except KeyError:
+ print("reproducible '%s' not found" % reproducible)
+ return 1
+
+def log(args, logger):
+ results = resultutils.load_resultsdata(args.source)
+
+ ptest_count = sum(1 for _, _, _, r in resultutils.test_run_results(results) if 'ptestresult.sections' in r)
+ if ptest_count > 1 and not args.prepend_run:
+ print("%i ptest sections found. '--prepend-run' is required" % ptest_count)
+ return 1
+
+ for _, run_name, _, r in resultutils.test_run_results(results):
+ if args.dump_ptest:
+ for sectname in ['ptestresult.sections', 'ltpposixresult.sections', 'ltpresult.sections']:
+ if sectname in r:
+ for name, ptest in r[sectname].items():
+ logdata = resultutils.generic_get_log(sectname, r, name)
+ if logdata is not None:
+ dest_dir = args.dump_ptest
+ if args.prepend_run:
+ dest_dir = os.path.join(dest_dir, run_name)
+ if not sectname.startswith("ptest"):
+ dest_dir = os.path.join(dest_dir, sectname.split(".")[0])
+
+ os.makedirs(dest_dir, exist_ok=True)
+ dest = os.path.join(dest_dir, '%s.log' % name)
+ print(dest)
+ with open(dest, 'w') as f:
+ f.write(logdata)
+
+ if args.raw_ptest:
+ found = False
+ for sectname in ['ptestresult.rawlogs', 'ltpposixresult.rawlogs', 'ltpresult.rawlogs']:
+ rawlog = resultutils.generic_get_rawlogs(sectname, r)
+ if rawlog is not None:
+ print(rawlog)
+ found = True
+ if not found:
+ print('Raw ptest logs not found')
+ return 1
+
+ if args.raw_reproducible:
+ if 'reproducible.rawlogs' in r:
+ print(r['reproducible.rawlogs']['log'])
+ else:
+ print('Raw reproducible logs not found')
+ return 1
+
+ for ptest in args.ptest:
+ if not show_ptest(r, ptest, logger):
+ return 1
+
+ for reproducible in args.reproducible:
+ if not show_reproducible(r, reproducible, logger):
+ return 1
+
+def register_commands(subparsers):
+ """Register subcommands from this plugin"""
+ parser = subparsers.add_parser('log', help='show logs',
+ description='show the logs from test results',
+ group='analysis')
+ parser.set_defaults(func=log)
+ parser.add_argument('source',
+ help='the results file/directory/URL to import')
+ parser.add_argument('--ptest', action='append', default=[],
+ help='show logs for a ptest')
+ parser.add_argument('--dump-ptest', metavar='DIR',
+ help='Dump all ptest log files to the specified directory.')
+ parser.add_argument('--reproducible', action='append', default=[],
+ help='show logs for a reproducible test')
+ parser.add_argument('--prepend-run', action='store_true',
+ help='''Dump ptest results to a subdirectory named after the test run when using --dump-ptest.
+ Required if more than one test run is present in the result file''')
+ parser.add_argument('--raw', action='store_true',
+ help='show raw (ptest) logs. Deprecated. Alias for "--raw-ptest"', dest='raw_ptest')
+ parser.add_argument('--raw-ptest', action='store_true',
+ help='show raw ptest log')
+ parser.add_argument('--raw-reproducible', action='store_true',
+ help='show raw reproducible build logs')
+
diff --git a/scripts/lib/resulttool/manualexecution.py b/scripts/lib/resulttool/manualexecution.py
new file mode 100755
index 0000000000..ecb27c5933
--- /dev/null
+++ b/scripts/lib/resulttool/manualexecution.py
@@ -0,0 +1,235 @@
+# test case management tool - manual execution from testopia test cases
+#
+# Copyright (c) 2018, Intel Corporation.
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import argparse
+import json
+import os
+import sys
+import datetime
+import re
+import copy
+from oeqa.core.runner import OETestResultJSONHelper
+
+
+def load_json_file(f):
+ with open(f, "r") as filedata:
+ return json.load(filedata)
+
+def write_json_file(f, json_data):
+ os.makedirs(os.path.dirname(f), exist_ok=True)
+ with open(f, 'w') as filedata:
+ filedata.write(json.dumps(json_data, sort_keys=True, indent=4))
+
+class ManualTestRunner(object):
+
+ def _get_test_module(self, case_file):
+ return os.path.basename(case_file).split('.')[0]
+
+ def _get_input(self, config):
+ while True:
+ output = input('{} = '.format(config))
+ if re.match('^[a-z0-9-.]+$', output):
+ break
+ print('Only lowercase alphanumeric, hyphen and dot are allowed. Please try again')
+ return output
+
+ def _get_available_config_options(self, config_options, test_module, target_config):
+ avail_config_options = None
+ if test_module in config_options:
+ avail_config_options = config_options[test_module].get(target_config)
+ return avail_config_options
+
+ def _choose_config_option(self, options):
+ while True:
+ output = input('{} = '.format('Option index number'))
+ if output in options:
+ break
+ print('Only integer index inputs from above available configuration options are allowed. Please try again.')
+ return options[output]
+
+ def _get_config(self, config_options, test_module):
+ from oeqa.utils.metadata import get_layers
+ from oeqa.utils.commands import get_bb_var
+ from resulttool.resultutils import store_map
+
+ layers = get_layers(get_bb_var('BBLAYERS'))
+ configurations = {}
+ configurations['LAYERS'] = layers
+ configurations['STARTTIME'] = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
+ configurations['TEST_TYPE'] = 'manual'
+ configurations['TEST_MODULE'] = test_module
+
+ extra_config = set(store_map['manual']) - set(configurations)
+ for config in sorted(extra_config):
+ avail_config_options = self._get_available_config_options(config_options, test_module, config)
+ if avail_config_options:
+ print('---------------------------------------------')
+ print('These are available configuration #%s options:' % config)
+ print('---------------------------------------------')
+ for option, _ in sorted(avail_config_options.items(), key=lambda x: int(x[0])):
+ print('%s: %s' % (option, avail_config_options[option]))
+ print('Please select configuration option, enter the integer index number.')
+ value_conf = self._choose_config_option(avail_config_options)
+ print('---------------------------------------------\n')
+ else:
+ print('---------------------------------------------')
+ print('This is configuration #%s. Please provide configuration value(use "None" if not applicable).' % config)
+ print('---------------------------------------------')
+ value_conf = self._get_input('Configuration Value')
+ print('---------------------------------------------\n')
+ configurations[config] = value_conf
+ return configurations
+
+ def _execute_test_steps(self, case):
+ test_result = {}
+ print('------------------------------------------------------------------------')
+ print('Executing test case: %s' % case['test']['@alias'])
+ print('------------------------------------------------------------------------')
+ print('You have total %s test steps to be executed.' % len(case['test']['execution']))
+ print('------------------------------------------------------------------------\n')
+ for step, _ in sorted(case['test']['execution'].items(), key=lambda x: int(x[0])):
+ print('Step %s: %s' % (step, case['test']['execution'][step]['action']))
+ expected_output = case['test']['execution'][step]['expected_results']
+ if expected_output:
+ print('Expected output: %s' % expected_output)
+ while True:
+ done = input('\nPlease provide test results: (P)assed/(F)ailed/(B)locked/(S)kipped? \n').lower()
+ result_types = {'p':'PASSED',
+ 'f':'FAILED',
+ 'b':'BLOCKED',
+ 's':'SKIPPED'}
+ if done in result_types:
+ for r in result_types:
+ if done == r:
+ res = result_types[r]
+ if res == 'FAILED':
+ log_input = input('\nPlease enter the error and the description of the log: (Ex:log:211 Error Bitbake)\n')
+ test_result.update({case['test']['@alias']: {'status': '%s' % res, 'log': '%s' % log_input}})
+ else:
+ test_result.update({case['test']['@alias']: {'status': '%s' % res}})
+ break
+ print('Invalid input!')
+ return test_result
+
+ def _get_write_dir(self):
+ return os.environ['BUILDDIR'] + '/tmp/log/manual/'
+
+ def run_test(self, case_file, config_options_file, testcase_config_file):
+ test_module = self._get_test_module(case_file)
+ cases = load_json_file(case_file)
+ config_options = {}
+ if config_options_file:
+ config_options = load_json_file(config_options_file)
+ configurations = self._get_config(config_options, test_module)
+ result_id = 'manual_%s_%s' % (test_module, configurations['STARTTIME'])
+ test_results = {}
+ if testcase_config_file:
+ test_case_config = load_json_file(testcase_config_file)
+ test_case_to_execute = test_case_config['testcases']
+ for case in copy.deepcopy(cases) :
+ if case['test']['@alias'] not in test_case_to_execute:
+ cases.remove(case)
+
+ print('\nTotal number of test cases in this test suite: %s\n' % len(cases))
+ for c in cases:
+ test_result = self._execute_test_steps(c)
+ test_results.update(test_result)
+ return configurations, result_id, self._get_write_dir(), test_results
+
+ def _get_true_false_input(self, input_message):
+ yes_list = ['Y', 'YES']
+ no_list = ['N', 'NO']
+ while True:
+ more_config_option = input(input_message).upper()
+ if more_config_option in yes_list or more_config_option in no_list:
+ break
+ print('Invalid input!')
+ if more_config_option in no_list:
+ return False
+ return True
+
+ def make_config_option_file(self, logger, case_file, config_options_file):
+ config_options = {}
+ if config_options_file:
+ config_options = load_json_file(config_options_file)
+ new_test_module = self._get_test_module(case_file)
+ print('Creating configuration options file for test module: %s' % new_test_module)
+ new_config_options = {}
+
+ while True:
+ config_name = input('\nPlease provide test configuration to create:\n').upper()
+ new_config_options[config_name] = {}
+ while True:
+ config_value = self._get_input('Configuration possible option value')
+ config_option_index = len(new_config_options[config_name]) + 1
+ new_config_options[config_name][config_option_index] = config_value
+ more_config_option = self._get_true_false_input('\nIs there more configuration option input: (Y)es/(N)o\n')
+ if not more_config_option:
+ break
+ more_config = self._get_true_false_input('\nIs there more configuration to create: (Y)es/(N)o\n')
+ if not more_config:
+ break
+
+ if new_config_options:
+ config_options[new_test_module] = new_config_options
+ if not config_options_file:
+ config_options_file = os.path.join(self._get_write_dir(), 'manual_config_options.json')
+ write_json_file(config_options_file, config_options)
+ logger.info('Configuration option file created at %s' % config_options_file)
+
+ def make_testcase_config_file(self, logger, case_file, testcase_config_file):
+ if testcase_config_file:
+ if os.path.exists(testcase_config_file):
+ print('\nTest configuration file with name %s already exists. Please provide a unique file name' % (testcase_config_file))
+ return 0
+
+ if not testcase_config_file:
+ testcase_config_file = os.path.join(self._get_write_dir(), "testconfig_new.json")
+
+ testcase_config = {}
+ cases = load_json_file(case_file)
+ new_test_module = self._get_test_module(case_file)
+ new_testcase_config = {}
+ new_testcase_config['testcases'] = []
+
+ print('\nAdd testcases for this configuration file:')
+ for case in cases:
+ print('\n' + case['test']['@alias'])
+ add_tc_config = self._get_true_false_input('\nDo you want to add this test case to test configuration : (Y)es/(N)o\n')
+ if add_tc_config:
+ new_testcase_config['testcases'].append(case['test']['@alias'])
+ write_json_file(testcase_config_file, new_testcase_config)
+ logger.info('Testcase Configuration file created at %s' % testcase_config_file)
+
+def manualexecution(args, logger):
+ testrunner = ManualTestRunner()
+ if args.make_config_options_file:
+ testrunner.make_config_option_file(logger, args.file, args.config_options_file)
+ return 0
+ if args.make_testcase_config_file:
+ testrunner.make_testcase_config_file(logger, args.file, args.testcase_config_file)
+ return 0
+ configurations, result_id, write_dir, test_results = testrunner.run_test(args.file, args.config_options_file, args.testcase_config_file)
+ resultjsonhelper = OETestResultJSONHelper()
+ resultjsonhelper.dump_testresult_file(write_dir, configurations, result_id, test_results)
+ return 0
+
+def register_commands(subparsers):
+ """Register subcommands from this plugin"""
+ parser_build = subparsers.add_parser('manualexecution', help='helper script for results populating during manual test execution.',
+ description='helper script for results populating during manual test execution. You can find manual test case JSON file in meta/lib/oeqa/manual/',
+ group='manualexecution')
+ parser_build.set_defaults(func=manualexecution)
+ parser_build.add_argument('file', help='specify path to manual test case JSON file.Note: Please use \"\" to encapsulate the file path.')
+ parser_build.add_argument('-c', '--config-options-file', default='',
+ help='the config options file to import and used as available configuration option selection or make config option file')
+ parser_build.add_argument('-m', '--make-config-options-file', action='store_true',
+ help='make the configuration options file based on provided inputs')
+ parser_build.add_argument('-t', '--testcase-config-file', default='',
+ help='the testcase configuration file to enable user to run a selected set of test case or make a testcase configuration file')
+ parser_build.add_argument('-d', '--make-testcase-config-file', action='store_true',
+ help='make the testcase configuration file to run a set of test cases based on user selection') \ No newline at end of file
diff --git a/scripts/lib/resulttool/merge.py b/scripts/lib/resulttool/merge.py
new file mode 100644
index 0000000000..18b4825a18
--- /dev/null
+++ b/scripts/lib/resulttool/merge.py
@@ -0,0 +1,46 @@
+# resulttool - merge multiple testresults.json files into a file or directory
+#
+# Copyright (c) 2019, Intel Corporation.
+# Copyright (c) 2019, Linux Foundation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import os
+import json
+import resulttool.resultutils as resultutils
+
+def merge(args, logger):
+ configvars = {}
+ if not args.not_add_testseries:
+ configvars = resultutils.extra_configvars.copy()
+ if args.executed_by:
+ configvars['EXECUTED_BY'] = args.executed_by
+ if resultutils.is_url(args.target_results) or os.path.isdir(args.target_results):
+ results = resultutils.load_resultsdata(args.target_results, configmap=resultutils.store_map, configvars=configvars)
+ resultutils.append_resultsdata(results, args.base_results, configmap=resultutils.store_map, configvars=configvars)
+ resultutils.save_resultsdata(results, args.target_results)
+ else:
+ results = resultutils.load_resultsdata(args.base_results, configmap=resultutils.flatten_map, configvars=configvars)
+ if os.path.exists(args.target_results):
+ resultutils.append_resultsdata(results, args.target_results, configmap=resultutils.flatten_map, configvars=configvars)
+ resultutils.save_resultsdata(results, os.path.dirname(args.target_results), fn=os.path.basename(args.target_results))
+
+ logger.info('Merged results to %s' % os.path.dirname(args.target_results))
+
+ return 0
+
+def register_commands(subparsers):
+ """Register subcommands from this plugin"""
+ parser_build = subparsers.add_parser('merge', help='merge test result files/directories/URLs',
+ description='merge the results from multiple files/directories/URLs into the target file or directory',
+ group='setup')
+ parser_build.set_defaults(func=merge)
+ parser_build.add_argument('base_results',
+ help='the results file/directory/URL to import')
+ parser_build.add_argument('target_results',
+ help='the target file or directory to merge the base_results with')
+ parser_build.add_argument('-t', '--not-add-testseries', action='store_true',
+ help='do not add testseries configuration to results')
+ parser_build.add_argument('-x', '--executed-by', default='',
+ help='add executed-by configuration to each result file')
diff --git a/scripts/lib/resulttool/regression.py b/scripts/lib/resulttool/regression.py
new file mode 100644
index 0000000000..9f952951b3
--- /dev/null
+++ b/scripts/lib/resulttool/regression.py
@@ -0,0 +1,186 @@
+# resulttool - regression analysis
+#
+# Copyright (c) 2019, Intel Corporation.
+# Copyright (c) 2019, Linux Foundation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import resulttool.resultutils as resultutils
+import json
+
+from oeqa.utils.git import GitRepo
+import oeqa.utils.gitarchive as gitarchive
+
+def compare_result(logger, base_name, target_name, base_result, target_result):
+ base_result = base_result.get('result')
+ target_result = target_result.get('result')
+ result = {}
+ if base_result and target_result:
+ for k in base_result:
+ base_testcase = base_result[k]
+ base_status = base_testcase.get('status')
+ if base_status:
+ target_testcase = target_result.get(k, {})
+ target_status = target_testcase.get('status')
+ if base_status != target_status:
+ result[k] = {'base': base_status, 'target': target_status}
+ else:
+ logger.error('Failed to retrieved base test case status: %s' % k)
+ if result:
+ resultstring = "Regression: %s\n %s\n" % (base_name, target_name)
+ for k in sorted(result):
+ resultstring += ' %s: %s -> %s\n' % (k, result[k]['base'], result[k]['target'])
+ else:
+ resultstring = "Match: %s\n %s" % (base_name, target_name)
+ return result, resultstring
+
+def get_results(logger, source):
+ return resultutils.load_resultsdata(source, configmap=resultutils.regression_map)
+
+def regression(args, logger):
+ base_results = get_results(logger, args.base_result)
+ target_results = get_results(logger, args.target_result)
+
+ regression_common(args, logger, base_results, target_results)
+
+def regression_common(args, logger, base_results, target_results):
+ if args.base_result_id:
+ base_results = resultutils.filter_resultsdata(base_results, args.base_result_id)
+ if args.target_result_id:
+ target_results = resultutils.filter_resultsdata(target_results, args.target_result_id)
+
+ matches = []
+ regressions = []
+ notfound = []
+
+ for a in base_results:
+ if a in target_results:
+ base = list(base_results[a].keys())
+ target = list(target_results[a].keys())
+ # We may have multiple base/targets which are for different configurations. Start by
+ # removing any pairs which match
+ for c in base.copy():
+ for b in target.copy():
+ res, resstr = compare_result(logger, c, b, base_results[a][c], target_results[a][b])
+ if not res:
+ matches.append(resstr)
+ base.remove(c)
+ target.remove(b)
+ break
+ # Should only now see regressions, we may not be able to match multiple pairs directly
+ for c in base:
+ for b in target:
+ res, resstr = compare_result(logger, c, b, base_results[a][c], target_results[a][b])
+ if res:
+ regressions.append(resstr)
+ else:
+ notfound.append("%s not found in target" % a)
+ print("\n".join(sorted(matches)))
+ print("\n".join(sorted(regressions)))
+ print("\n".join(sorted(notfound)))
+
+ return 0
+
+def regression_git(args, logger):
+ base_results = {}
+ target_results = {}
+
+ tag_name = "{branch}/{commit_number}-g{commit}/{tag_number}"
+ repo = GitRepo(args.repo)
+
+ revs = gitarchive.get_test_revs(logger, repo, tag_name, branch=args.branch)
+
+ if args.branch2:
+ revs2 = gitarchive.get_test_revs(logger, repo, tag_name, branch=args.branch2)
+ if not len(revs2):
+ logger.error("No revisions found to compare against")
+ return 1
+ if not len(revs):
+ logger.error("No revision to report on found")
+ return 1
+ else:
+ if len(revs) < 2:
+ logger.error("Only %d tester revisions found, unable to generate report" % len(revs))
+ return 1
+
+ # Pick revisions
+ if args.commit:
+ if args.commit_number:
+ logger.warning("Ignoring --commit-number as --commit was specified")
+ index1 = gitarchive.rev_find(revs, 'commit', args.commit)
+ elif args.commit_number:
+ index1 = gitarchive.rev_find(revs, 'commit_number', args.commit_number)
+ else:
+ index1 = len(revs) - 1
+
+ if args.branch2:
+ revs2.append(revs[index1])
+ index1 = len(revs2) - 1
+ revs = revs2
+
+ if args.commit2:
+ if args.commit_number2:
+ logger.warning("Ignoring --commit-number2 as --commit2 was specified")
+ index2 = gitarchive.rev_find(revs, 'commit', args.commit2)
+ elif args.commit_number2:
+ index2 = gitarchive.rev_find(revs, 'commit_number', args.commit_number2)
+ else:
+ if index1 > 0:
+ index2 = index1 - 1
+ # Find the closest matching commit number for comparision
+ # In future we could check the commit is a common ancestor and
+ # continue back if not but this good enough for now
+ while index2 > 0 and revs[index2].commit_number > revs[index1].commit_number:
+ index2 = index2 - 1
+ else:
+ logger.error("Unable to determine the other commit, use "
+ "--commit2 or --commit-number2 to specify it")
+ return 1
+
+ logger.info("Comparing:\n%s\nto\n%s\n" % (revs[index1], revs[index2]))
+
+ base_results = resultutils.git_get_result(repo, revs[index1][2])
+ target_results = resultutils.git_get_result(repo, revs[index2][2])
+
+ regression_common(args, logger, base_results, target_results)
+
+ return 0
+
+def register_commands(subparsers):
+ """Register subcommands from this plugin"""
+
+ parser_build = subparsers.add_parser('regression', help='regression file/directory analysis',
+ description='regression analysis comparing the base set of results to the target results',
+ group='analysis')
+ parser_build.set_defaults(func=regression)
+ parser_build.add_argument('base_result',
+ help='base result file/directory/URL for the comparison')
+ parser_build.add_argument('target_result',
+ help='target result file/directory/URL to compare with')
+ parser_build.add_argument('-b', '--base-result-id', default='',
+ help='(optional) filter the base results to this result ID')
+ parser_build.add_argument('-t', '--target-result-id', default='',
+ help='(optional) filter the target results to this result ID')
+
+ parser_build = subparsers.add_parser('regression-git', help='regression git analysis',
+ description='regression analysis comparing base result set to target '
+ 'result set',
+ group='analysis')
+ parser_build.set_defaults(func=regression_git)
+ parser_build.add_argument('repo',
+ help='the git repository containing the data')
+ parser_build.add_argument('-b', '--base-result-id', default='',
+ help='(optional) default select regression based on configurations unless base result '
+ 'id was provided')
+ parser_build.add_argument('-t', '--target-result-id', default='',
+ help='(optional) default select regression based on configurations unless target result '
+ 'id was provided')
+
+ parser_build.add_argument('--branch', '-B', default='master', help="Branch to find commit in")
+ parser_build.add_argument('--branch2', help="Branch to find comparision revisions in")
+ parser_build.add_argument('--commit', help="Revision to search for")
+ parser_build.add_argument('--commit-number', help="Revision number to search for, redundant if --commit is specified")
+ parser_build.add_argument('--commit2', help="Revision to compare with")
+ parser_build.add_argument('--commit-number2', help="Revision number to compare with, redundant if --commit2 is specified")
+
diff --git a/scripts/lib/resulttool/report.py b/scripts/lib/resulttool/report.py
new file mode 100644
index 0000000000..f0ca50ebe2
--- /dev/null
+++ b/scripts/lib/resulttool/report.py
@@ -0,0 +1,312 @@
+# test result tool - report text based test results
+#
+# Copyright (c) 2019, Intel Corporation.
+# Copyright (c) 2019, Linux Foundation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import os
+import glob
+import json
+import resulttool.resultutils as resultutils
+from oeqa.utils.git import GitRepo
+import oeqa.utils.gitarchive as gitarchive
+
+
+class ResultsTextReport(object):
+ def __init__(self):
+ self.ptests = {}
+ self.ltptests = {}
+ self.ltpposixtests = {}
+ self.result_types = {'passed': ['PASSED', 'passed', 'PASS', 'XFAIL'],
+ 'failed': ['FAILED', 'failed', 'FAIL', 'ERROR', 'error', 'UNKNOWN', 'XPASS'],
+ 'skipped': ['SKIPPED', 'skipped', 'UNSUPPORTED', 'UNTESTED', 'UNRESOLVED']}
+
+
+ def handle_ptest_result(self, k, status, result, machine):
+ if machine not in self.ptests:
+ self.ptests[machine] = {}
+
+ if k == 'ptestresult.sections':
+ # Ensure tests without any test results still show up on the report
+ for suite in result['ptestresult.sections']:
+ if suite not in self.ptests[machine]:
+ self.ptests[machine][suite] = {
+ 'passed': 0, 'failed': 0, 'skipped': 0, 'duration' : '-',
+ 'failed_testcases': [], "testcases": set(),
+ }
+ if 'duration' in result['ptestresult.sections'][suite]:
+ self.ptests[machine][suite]['duration'] = result['ptestresult.sections'][suite]['duration']
+ if 'timeout' in result['ptestresult.sections'][suite]:
+ self.ptests[machine][suite]['duration'] += " T"
+ return True
+
+ # process test result
+ try:
+ _, suite, test = k.split(".", 2)
+ except ValueError:
+ return True
+
+ # Handle 'glib-2.0'
+ if 'ptestresult.sections' in result and suite not in result['ptestresult.sections']:
+ try:
+ _, suite, suite1, test = k.split(".", 3)
+ if suite + "." + suite1 in result['ptestresult.sections']:
+ suite = suite + "." + suite1
+ except ValueError:
+ pass
+
+ if suite not in self.ptests[machine]:
+ self.ptests[machine][suite] = {
+ 'passed': 0, 'failed': 0, 'skipped': 0, 'duration' : '-',
+ 'failed_testcases': [], "testcases": set(),
+ }
+
+ # do not process duplicate results
+ if test in self.ptests[machine][suite]["testcases"]:
+ print("Warning duplicate ptest result '{}.{}' for {}".format(suite, test, machine))
+ return False
+
+ for tk in self.result_types:
+ if status in self.result_types[tk]:
+ self.ptests[machine][suite][tk] += 1
+ self.ptests[machine][suite]["testcases"].add(test)
+ return True
+
+ def handle_ltptest_result(self, k, status, result, machine):
+ if machine not in self.ltptests:
+ self.ltptests[machine] = {}
+
+ if k == 'ltpresult.sections':
+ # Ensure tests without any test results still show up on the report
+ for suite in result['ltpresult.sections']:
+ if suite not in self.ltptests[machine]:
+ self.ltptests[machine][suite] = {'passed': 0, 'failed': 0, 'skipped': 0, 'duration' : '-', 'failed_testcases': []}
+ if 'duration' in result['ltpresult.sections'][suite]:
+ self.ltptests[machine][suite]['duration'] = result['ltpresult.sections'][suite]['duration']
+ if 'timeout' in result['ltpresult.sections'][suite]:
+ self.ltptests[machine][suite]['duration'] += " T"
+ return
+ try:
+ _, suite, test = k.split(".", 2)
+ except ValueError:
+ return
+ # Handle 'glib-2.0'
+ if 'ltpresult.sections' in result and suite not in result['ltpresult.sections']:
+ try:
+ _, suite, suite1, test = k.split(".", 3)
+ if suite + "." + suite1 in result['ltpresult.sections']:
+ suite = suite + "." + suite1
+ except ValueError:
+ pass
+ if suite not in self.ltptests[machine]:
+ self.ltptests[machine][suite] = {'passed': 0, 'failed': 0, 'skipped': 0, 'duration' : '-', 'failed_testcases': []}
+ for tk in self.result_types:
+ if status in self.result_types[tk]:
+ self.ltptests[machine][suite][tk] += 1
+
+ def handle_ltpposixtest_result(self, k, status, result, machine):
+ if machine not in self.ltpposixtests:
+ self.ltpposixtests[machine] = {}
+
+ if k == 'ltpposixresult.sections':
+ # Ensure tests without any test results still show up on the report
+ for suite in result['ltpposixresult.sections']:
+ if suite not in self.ltpposixtests[machine]:
+ self.ltpposixtests[machine][suite] = {'passed': 0, 'failed': 0, 'skipped': 0, 'duration' : '-', 'failed_testcases': []}
+ if 'duration' in result['ltpposixresult.sections'][suite]:
+ self.ltpposixtests[machine][suite]['duration'] = result['ltpposixresult.sections'][suite]['duration']
+ return
+ try:
+ _, suite, test = k.split(".", 2)
+ except ValueError:
+ return
+ # Handle 'glib-2.0'
+ if 'ltpposixresult.sections' in result and suite not in result['ltpposixresult.sections']:
+ try:
+ _, suite, suite1, test = k.split(".", 3)
+ if suite + "." + suite1 in result['ltpposixresult.sections']:
+ suite = suite + "." + suite1
+ except ValueError:
+ pass
+ if suite not in self.ltpposixtests[machine]:
+ self.ltpposixtests[machine][suite] = {'passed': 0, 'failed': 0, 'skipped': 0, 'duration' : '-', 'failed_testcases': []}
+ for tk in self.result_types:
+ if status in self.result_types[tk]:
+ self.ltpposixtests[machine][suite][tk] += 1
+
+ def get_aggregated_test_result(self, logger, testresult, machine):
+ test_count_report = {'passed': 0, 'failed': 0, 'skipped': 0, 'failed_testcases': []}
+ result = testresult.get('result', [])
+ for k in result:
+ test_status = result[k].get('status', [])
+ if k.startswith("ptestresult."):
+ if not self.handle_ptest_result(k, test_status, result, machine):
+ continue
+ elif k.startswith("ltpresult."):
+ self.handle_ltptest_result(k, test_status, result, machine)
+ elif k.startswith("ltpposixresult."):
+ self.handle_ltpposixtest_result(k, test_status, result, machine)
+
+ # process result if it was not skipped by a handler
+ for tk in self.result_types:
+ if test_status in self.result_types[tk]:
+ test_count_report[tk] += 1
+ if test_status in self.result_types['failed']:
+ test_count_report['failed_testcases'].append(k)
+ return test_count_report
+
+ def print_test_report(self, template_file_name, test_count_reports):
+ from jinja2 import Environment, FileSystemLoader
+ script_path = os.path.dirname(os.path.realpath(__file__))
+ file_loader = FileSystemLoader(script_path + '/template')
+ env = Environment(loader=file_loader, trim_blocks=True)
+ template = env.get_template(template_file_name)
+ havefailed = False
+ reportvalues = []
+ machines = []
+ cols = ['passed', 'failed', 'skipped']
+ maxlen = {'passed' : 0, 'failed' : 0, 'skipped' : 0, 'result_id': 0, 'testseries' : 0, 'ptest' : 0 ,'ltptest': 0, 'ltpposixtest': 0}
+ for line in test_count_reports:
+ total_tested = line['passed'] + line['failed'] + line['skipped']
+ vals = {}
+ vals['result_id'] = line['result_id']
+ vals['testseries'] = line['testseries']
+ vals['sort'] = line['testseries'] + "_" + line['result_id']
+ vals['failed_testcases'] = line['failed_testcases']
+ for k in cols:
+ vals[k] = "%d (%s%%)" % (line[k], format(line[k] / total_tested * 100, '.0f'))
+ for k in maxlen:
+ if k in vals and len(vals[k]) > maxlen[k]:
+ maxlen[k] = len(vals[k])
+ reportvalues.append(vals)
+ if line['failed_testcases']:
+ havefailed = True
+ if line['machine'] not in machines:
+ machines.append(line['machine'])
+ reporttotalvalues = {}
+ for k in cols:
+ reporttotalvalues[k] = '%s' % sum([line[k] for line in test_count_reports])
+ reporttotalvalues['count'] = '%s' % len(test_count_reports)
+ for (machine, report) in self.ptests.items():
+ for ptest in self.ptests[machine]:
+ if len(ptest) > maxlen['ptest']:
+ maxlen['ptest'] = len(ptest)
+ for (machine, report) in self.ltptests.items():
+ for ltptest in self.ltptests[machine]:
+ if len(ltptest) > maxlen['ltptest']:
+ maxlen['ltptest'] = len(ltptest)
+ for (machine, report) in self.ltpposixtests.items():
+ for ltpposixtest in self.ltpposixtests[machine]:
+ if len(ltpposixtest) > maxlen['ltpposixtest']:
+ maxlen['ltpposixtest'] = len(ltpposixtest)
+ output = template.render(reportvalues=reportvalues,
+ reporttotalvalues=reporttotalvalues,
+ havefailed=havefailed,
+ machines=machines,
+ ptests=self.ptests,
+ ltptests=self.ltptests,
+ ltpposixtests=self.ltpposixtests,
+ maxlen=maxlen)
+ print(output)
+
+ def view_test_report(self, logger, source_dir, branch, commit, tag, use_regression_map, raw_test, selected_test_case_only):
+ def print_selected_testcase_result(testresults, selected_test_case_only):
+ for testsuite in testresults:
+ for resultid in testresults[testsuite]:
+ result = testresults[testsuite][resultid]['result']
+ test_case_result = result.get(selected_test_case_only, {})
+ if test_case_result.get('status'):
+ print('Found selected test case result for %s from %s' % (selected_test_case_only,
+ resultid))
+ print(test_case_result['status'])
+ else:
+ print('Could not find selected test case result for %s from %s' % (selected_test_case_only,
+ resultid))
+ if test_case_result.get('log'):
+ print(test_case_result['log'])
+ test_count_reports = []
+ configmap = resultutils.store_map
+ if use_regression_map:
+ configmap = resultutils.regression_map
+ if commit:
+ if tag:
+ logger.warning("Ignoring --tag as --commit was specified")
+ tag_name = "{branch}/{commit_number}-g{commit}/{tag_number}"
+ repo = GitRepo(source_dir)
+ revs = gitarchive.get_test_revs(logger, repo, tag_name, branch=branch)
+ rev_index = gitarchive.rev_find(revs, 'commit', commit)
+ testresults = resultutils.git_get_result(repo, revs[rev_index][2], configmap=configmap)
+ elif tag:
+ repo = GitRepo(source_dir)
+ testresults = resultutils.git_get_result(repo, [tag], configmap=configmap)
+ else:
+ testresults = resultutils.load_resultsdata(source_dir, configmap=configmap)
+ if raw_test:
+ raw_results = {}
+ for testsuite in testresults:
+ result = testresults[testsuite].get(raw_test, {})
+ if result:
+ raw_results[testsuite] = {raw_test: result}
+ if raw_results:
+ if selected_test_case_only:
+ print_selected_testcase_result(raw_results, selected_test_case_only)
+ else:
+ print(json.dumps(raw_results, sort_keys=True, indent=4))
+ else:
+ print('Could not find raw test result for %s' % raw_test)
+ return 0
+ if selected_test_case_only:
+ print_selected_testcase_result(testresults, selected_test_case_only)
+ return 0
+ for testsuite in testresults:
+ for resultid in testresults[testsuite]:
+ skip = False
+ result = testresults[testsuite][resultid]
+ machine = result['configuration']['MACHINE']
+
+ # Check to see if there is already results for these kinds of tests for the machine
+ for key in result['result'].keys():
+ testtype = str(key).split('.')[0]
+ if ((machine in self.ltptests and testtype == "ltpiresult" and self.ltptests[machine]) or
+ (machine in self.ltpposixtests and testtype == "ltpposixresult" and self.ltpposixtests[machine])):
+ print("Already have test results for %s on %s, skipping %s" %(str(key).split('.')[0], machine, resultid))
+ skip = True
+ break
+ if skip:
+ break
+
+ test_count_report = self.get_aggregated_test_result(logger, result, machine)
+ test_count_report['machine'] = machine
+ test_count_report['testseries'] = result['configuration']['TESTSERIES']
+ test_count_report['result_id'] = resultid
+ test_count_reports.append(test_count_report)
+ self.print_test_report('test_report_full_text.txt', test_count_reports)
+
+def report(args, logger):
+ report = ResultsTextReport()
+ report.view_test_report(logger, args.source_dir, args.branch, args.commit, args.tag, args.use_regression_map,
+ args.raw_test_only, args.selected_test_case_only)
+ return 0
+
+def register_commands(subparsers):
+ """Register subcommands from this plugin"""
+ parser_build = subparsers.add_parser('report', help='summarise test results',
+ description='print a text-based summary of the test results',
+ group='analysis')
+ parser_build.set_defaults(func=report)
+ parser_build.add_argument('source_dir',
+ help='source file/directory/URL that contain the test result files to summarise')
+ parser_build.add_argument('--branch', '-B', default='master', help="Branch to find commit in")
+ parser_build.add_argument('--commit', help="Revision to report")
+ parser_build.add_argument('-t', '--tag', default='',
+ help='source_dir is a git repository, report on the tag specified from that repository')
+ parser_build.add_argument('-m', '--use_regression_map', action='store_true',
+ help='instead of the default "store_map", use the "regression_map" for report')
+ parser_build.add_argument('-r', '--raw_test_only', default='',
+ help='output raw test result only for the user provided test result id')
+ parser_build.add_argument('-s', '--selected_test_case_only', default='',
+ help='output selected test case result for the user provided test case id, if both test '
+ 'result id and test case id are provided then output the selected test case result '
+ 'from the provided test result id')
diff --git a/scripts/lib/resulttool/resultutils.py b/scripts/lib/resulttool/resultutils.py
new file mode 100644
index 0000000000..8917022d36
--- /dev/null
+++ b/scripts/lib/resulttool/resultutils.py
@@ -0,0 +1,224 @@
+# resulttool - common library/utility functions
+#
+# Copyright (c) 2019, Intel Corporation.
+# Copyright (c) 2019, Linux Foundation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import os
+import base64
+import zlib
+import json
+import scriptpath
+import copy
+import urllib.request
+import posixpath
+scriptpath.add_oe_lib_path()
+
+flatten_map = {
+ "oeselftest": [],
+ "runtime": [],
+ "sdk": [],
+ "sdkext": [],
+ "manual": []
+}
+regression_map = {
+ "oeselftest": ['TEST_TYPE', 'MACHINE'],
+ "runtime": ['TESTSERIES', 'TEST_TYPE', 'IMAGE_BASENAME', 'MACHINE', 'IMAGE_PKGTYPE', 'DISTRO'],
+ "sdk": ['TESTSERIES', 'TEST_TYPE', 'IMAGE_BASENAME', 'MACHINE', 'SDKMACHINE'],
+ "sdkext": ['TESTSERIES', 'TEST_TYPE', 'IMAGE_BASENAME', 'MACHINE', 'SDKMACHINE'],
+ "manual": ['TEST_TYPE', 'TEST_MODULE', 'IMAGE_BASENAME', 'MACHINE']
+}
+store_map = {
+ "oeselftest": ['TEST_TYPE'],
+ "runtime": ['TEST_TYPE', 'DISTRO', 'MACHINE', 'IMAGE_BASENAME'],
+ "sdk": ['TEST_TYPE', 'MACHINE', 'SDKMACHINE', 'IMAGE_BASENAME'],
+ "sdkext": ['TEST_TYPE', 'MACHINE', 'SDKMACHINE', 'IMAGE_BASENAME'],
+ "manual": ['TEST_TYPE', 'TEST_MODULE', 'MACHINE', 'IMAGE_BASENAME']
+}
+
+def is_url(p):
+ """
+ Helper for determining if the given path is a URL
+ """
+ return p.startswith('http://') or p.startswith('https://')
+
+extra_configvars = {'TESTSERIES': ''}
+
+#
+# Load the json file and append the results data into the provided results dict
+#
+def append_resultsdata(results, f, configmap=store_map, configvars=extra_configvars):
+ if type(f) is str:
+ if is_url(f):
+ with urllib.request.urlopen(f) as response:
+ data = json.loads(response.read().decode('utf-8'))
+ url = urllib.parse.urlparse(f)
+ testseries = posixpath.basename(posixpath.dirname(url.path))
+ else:
+ with open(f, "r") as filedata:
+ data = json.load(filedata)
+ testseries = os.path.basename(os.path.dirname(f))
+ else:
+ data = f
+ for res in data:
+ if "configuration" not in data[res] or "result" not in data[res]:
+ raise ValueError("Test results data without configuration or result section?")
+ for config in configvars:
+ if config == "TESTSERIES" and "TESTSERIES" not in data[res]["configuration"]:
+ data[res]["configuration"]["TESTSERIES"] = testseries
+ continue
+ if config not in data[res]["configuration"]:
+ data[res]["configuration"][config] = configvars[config]
+ testtype = data[res]["configuration"].get("TEST_TYPE")
+ if testtype not in configmap:
+ raise ValueError("Unknown test type %s" % testtype)
+ testpath = "/".join(data[res]["configuration"].get(i) for i in configmap[testtype])
+ if testpath not in results:
+ results[testpath] = {}
+ results[testpath][res] = data[res]
+
+#
+# Walk a directory and find/load results data
+# or load directly from a file
+#
+def load_resultsdata(source, configmap=store_map, configvars=extra_configvars):
+ results = {}
+ if is_url(source) or os.path.isfile(source):
+ append_resultsdata(results, source, configmap, configvars)
+ return results
+ for root, dirs, files in os.walk(source):
+ for name in files:
+ f = os.path.join(root, name)
+ if name == "testresults.json":
+ append_resultsdata(results, f, configmap, configvars)
+ return results
+
+def filter_resultsdata(results, resultid):
+ newresults = {}
+ for r in results:
+ for i in results[r]:
+ if i == resultsid:
+ newresults[r] = {}
+ newresults[r][i] = results[r][i]
+ return newresults
+
+def strip_ptestresults(results):
+ newresults = copy.deepcopy(results)
+ #for a in newresults2:
+ # newresults = newresults2[a]
+ for res in newresults:
+ if 'result' not in newresults[res]:
+ continue
+ if 'ptestresult.rawlogs' in newresults[res]['result']:
+ del newresults[res]['result']['ptestresult.rawlogs']
+ if 'ptestresult.sections' in newresults[res]['result']:
+ for i in newresults[res]['result']['ptestresult.sections']:
+ if 'log' in newresults[res]['result']['ptestresult.sections'][i]:
+ del newresults[res]['result']['ptestresult.sections'][i]['log']
+ return newresults
+
+def decode_log(logdata):
+ if isinstance(logdata, str):
+ return logdata
+ elif isinstance(logdata, dict):
+ if "compressed" in logdata:
+ data = logdata.get("compressed")
+ data = base64.b64decode(data.encode("utf-8"))
+ data = zlib.decompress(data)
+ return data.decode("utf-8", errors='ignore')
+ return None
+
+def generic_get_log(sectionname, results, section):
+ if sectionname not in results:
+ return None
+ if section not in results[sectionname]:
+ return None
+
+ ptest = results[sectionname][section]
+ if 'log' not in ptest:
+ return None
+ return decode_log(ptest['log'])
+
+def ptestresult_get_log(results, section):
+ return generic_get_log('ptestresuls.sections', results, section)
+
+def generic_get_rawlogs(sectname, results):
+ if sectname not in results:
+ return None
+ if 'log' not in results[sectname]:
+ return None
+ return decode_log(results[sectname]['log'])
+
+def ptestresult_get_rawlogs(results):
+ return generic_get_rawlogs('ptestresult.rawlogs', results)
+
+def save_resultsdata(results, destdir, fn="testresults.json", ptestjson=False, ptestlogs=False):
+ for res in results:
+ if res:
+ dst = destdir + "/" + res + "/" + fn
+ else:
+ dst = destdir + "/" + fn
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
+ resultsout = results[res]
+ if not ptestjson:
+ resultsout = strip_ptestresults(results[res])
+ with open(dst, 'w') as f:
+ f.write(json.dumps(resultsout, sort_keys=True, indent=4))
+ for res2 in results[res]:
+ if ptestlogs and 'result' in results[res][res2]:
+ seriesresults = results[res][res2]['result']
+ rawlogs = ptestresult_get_rawlogs(seriesresults)
+ if rawlogs is not None:
+ with open(dst.replace(fn, "ptest-raw.log"), "w+") as f:
+ f.write(rawlogs)
+ if 'ptestresult.sections' in seriesresults:
+ for i in seriesresults['ptestresult.sections']:
+ sectionlog = ptestresult_get_log(seriesresults, i)
+ if sectionlog is not None:
+ with open(dst.replace(fn, "ptest-%s.log" % i), "w+") as f:
+ f.write(sectionlog)
+
+def git_get_result(repo, tags, configmap=store_map):
+ git_objs = []
+ for tag in tags:
+ files = repo.run_cmd(['ls-tree', "--name-only", "-r", tag]).splitlines()
+ git_objs.extend([tag + ':' + f for f in files if f.endswith("testresults.json")])
+
+ def parse_json_stream(data):
+ """Parse multiple concatenated JSON objects"""
+ objs = []
+ json_d = ""
+ for line in data.splitlines():
+ if line == '}{':
+ json_d += '}'
+ objs.append(json.loads(json_d))
+ json_d = '{'
+ else:
+ json_d += line
+ objs.append(json.loads(json_d))
+ return objs
+
+ # Optimize by reading all data with one git command
+ results = {}
+ for obj in parse_json_stream(repo.run_cmd(['show'] + git_objs + ['--'])):
+ append_resultsdata(results, obj, configmap=configmap)
+
+ return results
+
+def test_run_results(results):
+ """
+ Convenient generator function that iterates over all test runs that have a
+ result section.
+
+ Generates a tuple of:
+ (result json file path, test run name, test run (dict), test run "results" (dict))
+ for each test run that has a "result" section
+ """
+ for path in results:
+ for run_name, test_run in results[path].items():
+ if not 'result' in test_run:
+ continue
+ yield path, run_name, test_run, test_run['result']
+
diff --git a/scripts/lib/resulttool/store.py b/scripts/lib/resulttool/store.py
new file mode 100644
index 0000000000..e0951f0a8f
--- /dev/null
+++ b/scripts/lib/resulttool/store.py
@@ -0,0 +1,104 @@
+# resulttool - store test results
+#
+# Copyright (c) 2019, Intel Corporation.
+# Copyright (c) 2019, Linux Foundation
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+import tempfile
+import os
+import subprocess
+import json
+import shutil
+import scriptpath
+scriptpath.add_bitbake_lib_path()
+scriptpath.add_oe_lib_path()
+import resulttool.resultutils as resultutils
+import oeqa.utils.gitarchive as gitarchive
+
+
+def store(args, logger):
+ tempdir = tempfile.mkdtemp(prefix='testresults.')
+ try:
+ configvars = resultutils.extra_configvars.copy()
+ if args.executed_by:
+ configvars['EXECUTED_BY'] = args.executed_by
+ if args.extra_test_env:
+ configvars['EXTRA_TEST_ENV'] = args.extra_test_env
+ results = {}
+ logger.info('Reading files from %s' % args.source)
+ if resultutils.is_url(args.source) or os.path.isfile(args.source):
+ resultutils.append_resultsdata(results, args.source, configvars=configvars)
+ else:
+ for root, dirs, files in os.walk(args.source):
+ for name in files:
+ f = os.path.join(root, name)
+ if name == "testresults.json":
+ resultutils.append_resultsdata(results, f, configvars=configvars)
+ elif args.all:
+ dst = f.replace(args.source, tempdir + "/")
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
+ shutil.copyfile(f, dst)
+
+ revisions = {}
+
+ if not results and not args.all:
+ if args.allow_empty:
+ logger.info("No results found to store")
+ return 0
+ logger.error("No results found to store")
+ return 1
+
+ # Find the branch/commit/commit_count and ensure they all match
+ for suite in results:
+ for result in results[suite]:
+ config = results[suite][result]['configuration']['LAYERS']['meta']
+ revision = (config['commit'], config['branch'], str(config['commit_count']))
+ if revision not in revisions:
+ revisions[revision] = {}
+ if suite not in revisions[revision]:
+ revisions[revision][suite] = {}
+ revisions[revision][suite][result] = results[suite][result]
+
+ logger.info("Found %d revisions to store" % len(revisions))
+
+ for r in revisions:
+ results = revisions[r]
+ keywords = {'commit': r[0], 'branch': r[1], "commit_count": r[2]}
+ subprocess.check_call(["find", tempdir, "!", "-path", "./.git/*", "-delete"])
+ resultutils.save_resultsdata(results, tempdir, ptestlogs=True)
+
+ logger.info('Storing test result into git repository %s' % args.git_dir)
+
+ gitarchive.gitarchive(tempdir, args.git_dir, False, False,
+ "Results of {branch}:{commit}", "branch: {branch}\ncommit: {commit}", "{branch}",
+ False, "{branch}/{commit_count}-g{commit}/{tag_number}",
+ 'Test run #{tag_number} of {branch}:{commit}', '',
+ [], [], False, keywords, logger)
+
+ finally:
+ subprocess.check_call(["rm", "-rf", tempdir])
+
+ return 0
+
+def register_commands(subparsers):
+ """Register subcommands from this plugin"""
+ parser_build = subparsers.add_parser('store', help='store test results into a git repository',
+ description='takes a results file or directory of results files and stores '
+ 'them into the destination git repository, splitting out the results '
+ 'files as configured',
+ group='setup')
+ parser_build.set_defaults(func=store)
+ parser_build.add_argument('source',
+ help='source file/directory/URL that contain the test result files to be stored')
+ parser_build.add_argument('git_dir',
+ help='the location of the git repository to store the results in')
+ parser_build.add_argument('-a', '--all', action='store_true',
+ help='include all files, not just testresults.json files')
+ parser_build.add_argument('-e', '--allow-empty', action='store_true',
+ help='don\'t error if no results to store are found')
+ parser_build.add_argument('-x', '--executed-by', default='',
+ help='add executed-by configuration to each result file')
+ parser_build.add_argument('-t', '--extra-test-env', default='',
+ help='add extra test environment data to each result file configuration')
diff --git a/scripts/lib/resulttool/template/test_report_full_text.txt b/scripts/lib/resulttool/template/test_report_full_text.txt
new file mode 100644
index 0000000000..2efba2ef6f
--- /dev/null
+++ b/scripts/lib/resulttool/template/test_report_full_text.txt
@@ -0,0 +1,79 @@
+==============================================================================================================
+Test Result Status Summary (Counts/Percentages sorted by testseries, ID)
+==============================================================================================================
+--------------------------------------------------------------------------------------------------------------
+{{ 'Test Series'.ljust(maxlen['testseries']) }} | {{ 'ID'.ljust(maxlen['result_id']) }} | {{ 'Passed'.ljust(maxlen['passed']) }} | {{ 'Failed'.ljust(maxlen['failed']) }} | {{ 'Skipped'.ljust(maxlen['skipped']) }}
+--------------------------------------------------------------------------------------------------------------
+{% for report in reportvalues |sort(attribute='sort') %}
+{{ report.testseries.ljust(maxlen['testseries']) }} | {{ report.result_id.ljust(maxlen['result_id']) }} | {{ (report.passed|string).ljust(maxlen['passed']) }} | {{ (report.failed|string).ljust(maxlen['failed']) }} | {{ (report.skipped|string).ljust(maxlen['skipped']) }}
+{% endfor %}
+--------------------------------------------------------------------------------------------------------------
+{{ 'Total'.ljust(maxlen['testseries']) }} | {{ reporttotalvalues['count'].ljust(maxlen['result_id']) }} | {{ reporttotalvalues['passed'].ljust(maxlen['passed']) }} | {{ reporttotalvalues['failed'].ljust(maxlen['failed']) }} | {{ reporttotalvalues['skipped'].ljust(maxlen['skipped']) }}
+--------------------------------------------------------------------------------------------------------------
+
+{% for machine in machines %}
+{% if ptests[machine] %}
+==============================================================================================================
+{{ machine }} PTest Result Summary
+==============================================================================================================
+--------------------------------------------------------------------------------------------------------------
+{{ 'Recipe'.ljust(maxlen['ptest']) }} | {{ 'Passed'.ljust(maxlen['passed']) }} | {{ 'Failed'.ljust(maxlen['failed']) }} | {{ 'Skipped'.ljust(maxlen['skipped']) }} | {{ 'Time(s)'.ljust(10) }}
+--------------------------------------------------------------------------------------------------------------
+{% for ptest in ptests[machine] |sort %}
+{{ ptest.ljust(maxlen['ptest']) }} | {{ (ptests[machine][ptest]['passed']|string).ljust(maxlen['passed']) }} | {{ (ptests[machine][ptest]['failed']|string).ljust(maxlen['failed']) }} | {{ (ptests[machine][ptest]['skipped']|string).ljust(maxlen['skipped']) }} | {{ (ptests[machine][ptest]['duration']|string) }}
+{% endfor %}
+--------------------------------------------------------------------------------------------------------------
+
+{% endif %}
+{% endfor %}
+
+{% for machine in machines %}
+{% if ltptests[machine] %}
+==============================================================================================================
+{{ machine }} Ltp Test Result Summary
+==============================================================================================================
+--------------------------------------------------------------------------------------------------------------
+{{ 'Recipe'.ljust(maxlen['ltptest']) }} | {{ 'Passed'.ljust(maxlen['passed']) }} | {{ 'Failed'.ljust(maxlen['failed']) }} | {{ 'Skipped'.ljust(maxlen['skipped']) }} | {{ 'Time(s)'.ljust(10) }}
+--------------------------------------------------------------------------------------------------------------
+{% for ltptest in ltptests[machine] |sort %}
+{{ ltptest.ljust(maxlen['ltptest']) }} | {{ (ltptests[machine][ltptest]['passed']|string).ljust(maxlen['passed']) }} | {{ (ltptests[machine][ltptest]['failed']|string).ljust(maxlen['failed']) }} | {{ (ltptests[machine][ltptest]['skipped']|string).ljust(maxlen['skipped']) }} | {{ (ltptests[machine][ltptest]['duration']|string) }}
+{% endfor %}
+--------------------------------------------------------------------------------------------------------------
+
+{% endif %}
+{% endfor %}
+
+{% for machine in machines %}
+{% if ltpposixtests[machine] %}
+==============================================================================================================
+{{ machine }} Ltp Posix Result Summary
+==============================================================================================================
+--------------------------------------------------------------------------------------------------------------
+{{ 'Recipe'.ljust(maxlen['ltpposixtest']) }} | {{ 'Passed'.ljust(maxlen['passed']) }} | {{ 'Failed'.ljust(maxlen['failed']) }} | {{ 'Skipped'.ljust(maxlen['skipped']) }} | {{ 'Time(s)'.ljust(10) }}
+--------------------------------------------------------------------------------------------------------------
+{% for ltpposixtest in ltpposixtests[machine] |sort %}
+{{ ltpposixtest.ljust(maxlen['ltpposixtest']) }} | {{ (ltpposixtests[machine][ltpposixtest]['passed']|string).ljust(maxlen['passed']) }} | {{ (ltpposixtests[machine][ltpposixtest]['failed']|string).ljust(maxlen['failed']) }} | {{ (ltpposixtests[machine][ltpposixtest]['skipped']|string).ljust(maxlen['skipped']) }} | {{ (ltpposixtests[machine][ltpposixtest]['duration']|string) }}
+{% endfor %}
+--------------------------------------------------------------------------------------------------------------
+
+{% endif %}
+{% endfor %}
+
+
+==============================================================================================================
+Failed test cases (sorted by testseries, ID)
+==============================================================================================================
+{% if havefailed %}
+--------------------------------------------------------------------------------------------------------------
+{% for report in reportvalues |sort(attribute='sort') %}
+{% if report.failed_testcases %}
+testseries | result_id : {{ report.testseries }} | {{ report.result_id }}
+{% for testcase in report.failed_testcases %}
+ {{ testcase }}
+{% endfor %}
+{% endif %}
+{% endfor %}
+--------------------------------------------------------------------------------------------------------------
+{% else %}
+There were no test failures
+{% endif %}
diff --git a/scripts/lib/scriptpath.py b/scripts/lib/scriptpath.py
index d00317e18d..f32326db3a 100644
--- a/scripts/lib/scriptpath.py
+++ b/scripts/lib/scriptpath.py
@@ -3,18 +3,8 @@
# Copyright (C) 2012-2014 Intel Corporation
# Copyright (C) 2011 Mentor Graphics Corporation
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
+# SPDX-License-Identifier: GPL-2.0-only
#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import sys
import os
diff --git a/scripts/lib/scriptutils.py b/scripts/lib/scriptutils.py
index fdf4b5d55d..3164171eb2 100644
--- a/scripts/lib/scriptutils.py
+++ b/scripts/lib/scriptutils.py
@@ -2,27 +2,65 @@
#
# Copyright (C) 2014 Intel Corporation
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
+# SPDX-License-Identifier: GPL-2.0-only
#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-import sys
-import os
-import logging
+import argparse
import glob
+import logging
+import os
+import random
+import shlex
+import shutil
+import string
+import subprocess
+import sys
+import tempfile
+import threading
+import importlib
+from importlib import machinery
+
+class KeepAliveStreamHandler(logging.StreamHandler):
+ def __init__(self, keepalive=True, **kwargs):
+ super().__init__(**kwargs)
+ if keepalive is True:
+ keepalive = 5000 # default timeout
+ self._timeout = threading.Condition()
+ self._stop = False
+
+ # background thread waits on condition, if the condition does not
+ # happen emit a keep alive message
+ def thread():
+ while not self._stop:
+ with self._timeout:
+ if not self._timeout.wait(keepalive):
+ self.emit(logging.LogRecord("keepalive", logging.INFO,
+ None, None, "Keepalive message", None, None))
+
+ self._thread = threading.Thread(target = thread, daemon = True)
+ self._thread.start()
-def logger_create(name):
+ def close(self):
+ # mark the thread to stop and notify it
+ self._stop = True
+ with self._timeout:
+ self._timeout.notify()
+ # wait for it to join
+ self._thread.join()
+ super().close()
+
+ def emit(self, record):
+ super().emit(record)
+ # trigger timer reset
+ with self._timeout:
+ self._timeout.notify()
+
+def logger_create(name, stream=None, keepalive=None):
logger = logging.getLogger(name)
- loggerhandler = logging.StreamHandler()
+ if keepalive is not None:
+ loggerhandler = KeepAliveStreamHandler(stream=stream, keepalive=keepalive)
+ else:
+ loggerhandler = logging.StreamHandler(stream=stream)
loggerhandler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger.addHandler(loggerhandler)
logger.setLevel(logging.INFO)
@@ -30,34 +68,35 @@ def logger_create(name):
def logger_setup_color(logger, color='auto'):
from bb.msg import BBLogFormatter
- console = logging.StreamHandler(sys.stdout)
- formatter = BBLogFormatter("%(levelname)s: %(message)s")
- console.setFormatter(formatter)
- logger.handlers = [console]
- if color == 'always' or (color=='auto' and console.stream.isatty()):
- formatter.enable_color()
+
+ for handler in logger.handlers:
+ if (isinstance(handler, logging.StreamHandler) and
+ isinstance(handler.formatter, BBLogFormatter)):
+ if color == 'always' or (color == 'auto' and handler.stream.isatty()):
+ handler.formatter.enable_color()
def load_plugins(logger, plugins, pluginpath):
- import imp
def load_plugin(name):
logger.debug('Loading plugin %s' % name)
- fp, pathname, description = imp.find_module(name, [pluginpath])
- try:
- return imp.load_module(name, fp, pathname, description)
- finally:
- if fp:
- fp.close()
+ spec = importlib.machinery.PathFinder.find_spec(name, path=[pluginpath] )
+ if spec:
+ return spec.loader.load_module()
+ def plugin_name(filename):
+ return os.path.splitext(os.path.basename(filename))[0]
+
+ known_plugins = [plugin_name(p.__name__) for p in plugins]
logger.debug('Loading plugins from %s...' % pluginpath)
for fn in glob.glob(os.path.join(pluginpath, '*.py')):
- name = os.path.splitext(os.path.basename(fn))[0]
- if name != '__init__':
+ name = plugin_name(fn)
+ if name != '__init__' and name not in known_plugins:
plugin = load_plugin(name)
if hasattr(plugin, 'plugin_init'):
plugin.plugin_init(plugins)
- plugins.append(plugin)
+ plugins.append(plugin)
+
def git_convert_standalone_clone(repodir):
"""If specified directory is a git repository, ensure it's a standalone clone"""
@@ -69,3 +108,173 @@ def git_convert_standalone_clone(repodir):
# of the contents is shared
bb.process.run('git repack -a', cwd=repodir)
os.remove(alternatesfile)
+
+def _get_temp_recipe_dir(d):
+ # This is a little bit hacky but we need to find a place where we can put
+ # the recipe so that bitbake can find it. We're going to delete it at the
+ # end so it doesn't really matter where we put it.
+ bbfiles = d.getVar('BBFILES').split()
+ fetchrecipedir = None
+ for pth in bbfiles:
+ if pth.endswith('.bb'):
+ pthdir = os.path.dirname(pth)
+ if os.access(os.path.dirname(os.path.dirname(pthdir)), os.W_OK):
+ fetchrecipedir = pthdir.replace('*', 'recipetool')
+ if pthdir.endswith('workspace/recipes/*'):
+ # Prefer the workspace
+ break
+ return fetchrecipedir
+
+class FetchUrlFailure(Exception):
+ def __init__(self, url):
+ self.url = url
+ def __str__(self):
+ return "Failed to fetch URL %s" % self.url
+
+def fetch_url(tinfoil, srcuri, srcrev, destdir, logger, preserve_tmp=False, mirrors=False):
+ """
+ Fetch the specified URL using normal do_fetch and do_unpack tasks, i.e.
+ any dependencies that need to be satisfied in order to support the fetch
+ operation will be taken care of
+ """
+
+ import bb
+
+ checksums = {}
+ fetchrecipepn = None
+
+ # We need to put our temp directory under ${BASE_WORKDIR} otherwise
+ # we may have problems with the recipe-specific sysroot population
+ tmpparent = tinfoil.config_data.getVar('BASE_WORKDIR')
+ bb.utils.mkdirhier(tmpparent)
+ tmpdir = tempfile.mkdtemp(prefix='recipetool-', dir=tmpparent)
+ try:
+ tmpworkdir = os.path.join(tmpdir, 'work')
+ logger.debug('fetch_url: temp dir is %s' % tmpdir)
+
+ fetchrecipedir = _get_temp_recipe_dir(tinfoil.config_data)
+ if not fetchrecipedir:
+ logger.error('Searched BBFILES but unable to find a writeable place to put temporary recipe')
+ sys.exit(1)
+ fetchrecipe = None
+ bb.utils.mkdirhier(fetchrecipedir)
+ try:
+ # Generate a dummy recipe so we can follow more or less normal paths
+ # for do_fetch and do_unpack
+ # I'd use tempfile functions here but underscores can be produced by that and those
+ # aren't allowed in recipe file names except to separate the version
+ rndstring = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))
+ fetchrecipe = os.path.join(fetchrecipedir, 'tmp-recipetool-%s.bb' % rndstring)
+ fetchrecipepn = os.path.splitext(os.path.basename(fetchrecipe))[0]
+ logger.debug('Generating initial recipe %s for fetching' % fetchrecipe)
+ with open(fetchrecipe, 'w') as f:
+ # We don't want to have to specify LIC_FILES_CHKSUM
+ f.write('LICENSE = "CLOSED"\n')
+ # We don't need the cross-compiler
+ f.write('INHIBIT_DEFAULT_DEPS = "1"\n')
+ # We don't have the checksums yet so we can't require them
+ f.write('BB_STRICT_CHECKSUM = "ignore"\n')
+ f.write('SRC_URI = "%s"\n' % srcuri)
+ f.write('SRCREV = "%s"\n' % srcrev)
+ f.write('WORKDIR = "%s"\n' % tmpworkdir)
+ # Set S out of the way so it doesn't get created under the workdir
+ f.write('S = "%s"\n' % os.path.join(tmpdir, 'emptysrc'))
+ if not mirrors:
+ # We do not need PREMIRRORS since we are almost certainly
+ # fetching new source rather than something that has already
+ # been fetched. Hence, we disable them by default.
+ # However, we provide an option for users to enable it.
+ f.write('PREMIRRORS = ""\n')
+ f.write('MIRRORS = ""\n')
+
+ logger.info('Fetching %s...' % srcuri)
+
+ # FIXME this is too noisy at the moment
+
+ # Parse recipes so our new recipe gets picked up
+ tinfoil.parse_recipes()
+
+ def eventhandler(event):
+ if isinstance(event, bb.fetch2.MissingChecksumEvent):
+ checksums.update(event.checksums)
+ return True
+ return False
+
+ # Run the fetch + unpack tasks
+ res = tinfoil.build_targets(fetchrecipepn,
+ 'do_unpack',
+ handle_events=True,
+ extra_events=['bb.fetch2.MissingChecksumEvent'],
+ event_callback=eventhandler)
+ if not res:
+ raise FetchUrlFailure(srcuri)
+
+ # Remove unneeded directories
+ rd = tinfoil.parse_recipe(fetchrecipepn)
+ if rd:
+ pathvars = ['T', 'RECIPE_SYSROOT', 'RECIPE_SYSROOT_NATIVE']
+ for pathvar in pathvars:
+ path = rd.getVar(pathvar)
+ if os.path.exists(path):
+ shutil.rmtree(path)
+ finally:
+ if fetchrecipe:
+ try:
+ os.remove(fetchrecipe)
+ except FileNotFoundError:
+ pass
+ try:
+ os.rmdir(fetchrecipedir)
+ except OSError as e:
+ import errno
+ if e.errno != errno.ENOTEMPTY:
+ raise
+
+ bb.utils.mkdirhier(destdir)
+ for fn in os.listdir(tmpworkdir):
+ shutil.move(os.path.join(tmpworkdir, fn), destdir)
+
+ finally:
+ if not preserve_tmp:
+ shutil.rmtree(tmpdir)
+ tmpdir = None
+
+ return checksums, tmpdir
+
+
+def run_editor(fn, logger=None):
+ if isinstance(fn, str):
+ files = [fn]
+ else:
+ files = fn
+
+ editor = os.getenv('VISUAL', os.getenv('EDITOR', 'vi'))
+ try:
+ #print(shlex.split(editor) + files)
+ return subprocess.check_call(shlex.split(editor) + files)
+ except subprocess.CalledProcessError as exc:
+ logger.error("Execution of '%s' failed: %s" % (editor, exc))
+ return 1
+
+def is_src_url(param):
+ """
+ Check if a parameter is a URL and return True if so
+ NOTE: be careful about changing this as it will influence how devtool/recipetool command line handling works
+ """
+ if not param:
+ return False
+ elif '://' in param:
+ return True
+ elif param.startswith('git@') or ('@' in param and param.endswith('.git')):
+ return True
+ return False
+
+def filter_src_subdirs(pth):
+ """
+ Filter out subdirectories of initial unpacked source trees that we do not care about.
+ Used by devtool and recipetool.
+ """
+ dirlist = os.listdir(pth)
+ filterout = ['git.indirectionsymlink', 'source-date-epoch']
+ dirlist = [x for x in dirlist if x not in filterout]
+ return dirlist
diff --git a/scripts/lib/wic/3rdparty/pykickstart/base.py b/scripts/lib/wic/3rdparty/pykickstart/base.py
deleted file mode 100644
index e6c8f56f9d..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/base.py
+++ /dev/null
@@ -1,466 +0,0 @@
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# Copyright 2006, 2007, 2008 Red Hat, Inc.
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-"""
-Base classes for creating commands and syntax version object.
-
-This module exports several important base classes:
-
- BaseData - The base abstract class for all data objects. Data objects
- are contained within a BaseHandler object.
-
- BaseHandler - The base abstract class from which versioned kickstart
- handler are derived. Subclasses of BaseHandler hold
- BaseData and KickstartCommand objects.
-
- DeprecatedCommand - An abstract subclass of KickstartCommand that should
- be further subclassed by users of this module. When
- a subclass is used, a warning message will be
- printed.
-
- KickstartCommand - The base abstract class for all kickstart commands.
- Command objects are contained within a BaseHandler
- object.
-"""
-import gettext
-gettext.textdomain("pykickstart")
-_ = lambda x: gettext.ldgettext("pykickstart", x)
-
-import types
-import warnings
-from pykickstart.errors import *
-from pykickstart.ko import *
-from pykickstart.parser import Packages
-from pykickstart.version import versionToString
-
-###
-### COMMANDS
-###
-class KickstartCommand(KickstartObject):
- """The base class for all kickstart commands. This is an abstract class."""
- removedKeywords = []
- removedAttrs = []
-
- def __init__(self, writePriority=0, *args, **kwargs):
- """Create a new KickstartCommand instance. This method must be
- provided by all subclasses, but subclasses must call
- KickstartCommand.__init__ first. Instance attributes:
-
- currentCmd -- The name of the command in the input file that
- caused this handler to be run.
- currentLine -- The current unprocessed line from the input file
- that caused this handler to be run.
- handler -- A reference to the BaseHandler subclass this
- command is contained withing. This is needed to
- allow referencing of Data objects.
- lineno -- The current line number in the input file.
- writePriority -- An integer specifying when this command should be
- printed when iterating over all commands' __str__
- methods. The higher the number, the later this
- command will be written. All commands with the
- same priority will be written alphabetically.
- """
-
- # We don't want people using this class by itself.
- if self.__class__ is KickstartCommand:
- raise TypeError, "KickstartCommand is an abstract class."
-
- KickstartObject.__init__(self, *args, **kwargs)
-
- self.writePriority = writePriority
-
- # These will be set by the dispatcher.
- self.currentCmd = ""
- self.currentLine = ""
- self.handler = None
- self.lineno = 0
-
- # If a subclass provides a removedKeywords list, remove all the
- # members from the kwargs list before we start processing it. This
- # ensures that subclasses don't continue to recognize arguments that
- # were removed.
- for arg in filter(kwargs.has_key, self.removedKeywords):
- kwargs.pop(arg)
-
- def __call__(self, *args, **kwargs):
- """Set multiple attributes on a subclass of KickstartCommand at once
- via keyword arguments. Valid attributes are anything specified in
- a subclass, but unknown attributes will be ignored.
- """
- for (key, val) in kwargs.items():
- # Ignore setting attributes that were removed in a subclass, as
- # if they were unknown attributes.
- if key in self.removedAttrs:
- continue
-
- if hasattr(self, key):
- setattr(self, key, val)
-
- def __str__(self):
- """Return a string formatted for output to a kickstart file. This
- method must be provided by all subclasses.
- """
- return KickstartObject.__str__(self)
-
- def parse(self, args):
- """Parse the list of args and set data on the KickstartCommand object.
- This method must be provided by all subclasses.
- """
- raise TypeError, "parse() not implemented for KickstartCommand"
-
- def apply(self, instroot="/"):
- """Write out the configuration related to the KickstartCommand object.
- Subclasses which do not provide this method will not have their
- configuration written out.
- """
- return
-
- def dataList(self):
- """For commands that can occur multiple times in a single kickstart
- file (like network, part, etc.), return the list that we should
- append more data objects to.
- """
- return None
-
- def deleteRemovedAttrs(self):
- """Remove all attributes from self that are given in the removedAttrs
- list. This method should be called from __init__ in a subclass,
- but only after the superclass's __init__ method has been called.
- """
- for attr in filter(lambda k: hasattr(self, k), self.removedAttrs):
- delattr(self, attr)
-
- # Set the contents of the opts object (an instance of optparse.Values
- # returned by parse_args) as attributes on the KickstartCommand object.
- # It's useful to call this from KickstartCommand subclasses after parsing
- # the arguments.
- def _setToSelf(self, optParser, opts):
- self._setToObj(optParser, opts, self)
-
- # Sets the contents of the opts object (an instance of optparse.Values
- # returned by parse_args) as attributes on the provided object obj. It's
- # useful to call this from KickstartCommand subclasses that handle lists
- # of objects (like partitions, network devices, etc.) and need to populate
- # a Data object.
- def _setToObj(self, optParser, opts, obj):
- for key in filter (lambda k: getattr(opts, k) != None, optParser.keys()):
- setattr(obj, key, getattr(opts, key))
-
-class DeprecatedCommand(KickstartCommand):
- """Specify that a command is deprecated and no longer has any function.
- Any command that is deprecated should be subclassed from this class,
- only specifying an __init__ method that calls the superclass's __init__.
- This is an abstract class.
- """
- def __init__(self, writePriority=None, *args, **kwargs):
- # We don't want people using this class by itself.
- if self.__class__ is KickstartCommand:
- raise TypeError, "DeprecatedCommand is an abstract class."
-
- # Create a new DeprecatedCommand instance.
- KickstartCommand.__init__(self, writePriority, *args, **kwargs)
-
- def __str__(self):
- """Placeholder since DeprecatedCommands don't work anymore."""
- return ""
-
- def parse(self, args):
- """Print a warning message if the command is seen in the input file."""
- mapping = {"lineno": self.lineno, "cmd": self.currentCmd}
- warnings.warn(_("Ignoring deprecated command on line %(lineno)s: The %(cmd)s command has been deprecated and no longer has any effect. It may be removed from future releases, which will result in a fatal error from kickstart. Please modify your kickstart file to remove this command.") % mapping, DeprecationWarning)
-
-
-###
-### HANDLERS
-###
-class BaseHandler(KickstartObject):
- """Each version of kickstart syntax is provided by a subclass of this
- class. These subclasses are what users will interact with for parsing,
- extracting data, and writing out kickstart files. This is an abstract
- class.
-
- version -- The version this syntax handler supports. This is set by
- a class attribute of a BaseHandler subclass and is used to
- set up the command dict. It is for read-only use.
- """
- version = None
-
- def __init__(self, mapping=None, dataMapping=None, commandUpdates=None,
- dataUpdates=None, *args, **kwargs):
- """Create a new BaseHandler instance. This method must be provided by
- all subclasses, but subclasses must call BaseHandler.__init__ first.
-
- mapping -- A custom map from command strings to classes,
- useful when creating your own handler with
- special command objects. It is otherwise unused
- and rarely needed. If you give this argument,
- the mapping takes the place of the default one
- and so must include all commands you want
- recognized.
- dataMapping -- This is the same as mapping, but for data
- objects. All the same comments apply.
- commandUpdates -- This is similar to mapping, but does not take
- the place of the defaults entirely. Instead,
- this mapping is applied after the defaults and
- updates it with just the commands you want to
- modify.
- dataUpdates -- This is the same as commandUpdates, but for
- data objects.
-
-
- Instance attributes:
-
- commands -- A mapping from a string command to a KickstartCommand
- subclass object that handles it. Multiple strings can
- map to the same object, but only one instance of the
- command object should ever exist. Most users should
- never have to deal with this directly, as it is
- manipulated internally and called through dispatcher.
- currentLine -- The current unprocessed line from the input file
- that caused this handler to be run.
- packages -- An instance of pykickstart.parser.Packages which
- describes the packages section of the input file.
- platform -- A string describing the hardware platform, which is
- needed only by system-config-kickstart.
- scripts -- A list of pykickstart.parser.Script instances, which is
- populated by KickstartParser.addScript and describes the
- %pre/%post/%traceback script section of the input file.
- """
-
- # We don't want people using this class by itself.
- if self.__class__ is BaseHandler:
- raise TypeError, "BaseHandler is an abstract class."
-
- KickstartObject.__init__(self, *args, **kwargs)
-
- # This isn't really a good place for these, but it's better than
- # everything else I can think of.
- self.scripts = []
- self.packages = Packages()
- self.platform = ""
-
- # These will be set by the dispatcher.
- self.commands = {}
- self.currentLine = 0
-
- # A dict keyed by an integer priority number, with each value being a
- # list of KickstartCommand subclasses. This dict is maintained by
- # registerCommand and used in __str__. No one else should be touching
- # it.
- self._writeOrder = {}
-
- self._registerCommands(mapping, dataMapping, commandUpdates, dataUpdates)
-
- def __str__(self):
- """Return a string formatted for output to a kickstart file."""
- retval = ""
-
- if self.platform != "":
- retval += "#platform=%s\n" % self.platform
-
- retval += "#version=%s\n" % versionToString(self.version)
-
- lst = self._writeOrder.keys()
- lst.sort()
-
- for prio in lst:
- for obj in self._writeOrder[prio]:
- retval += obj.__str__()
-
- for script in self.scripts:
- retval += script.__str__()
-
- retval += self.packages.__str__()
-
- return retval
-
- def _insertSorted(self, lst, obj):
- length = len(lst)
- i = 0
-
- while i < length:
- # If the two classes have the same name, it's because we are
- # overriding an existing class with one from a later kickstart
- # version, so remove the old one in favor of the new one.
- if obj.__class__.__name__ > lst[i].__class__.__name__:
- i += 1
- elif obj.__class__.__name__ == lst[i].__class__.__name__:
- lst[i] = obj
- return
- elif obj.__class__.__name__ < lst[i].__class__.__name__:
- break
-
- if i >= length:
- lst.append(obj)
- else:
- lst.insert(i, obj)
-
- def _setCommand(self, cmdObj):
- # Add an attribute on this version object. We need this to provide a
- # way for clients to access the command objects. We also need to strip
- # off the version part from the front of the name.
- if cmdObj.__class__.__name__.find("_") != -1:
- name = unicode(cmdObj.__class__.__name__.split("_", 1)[1])
- else:
- name = unicode(cmdObj.__class__.__name__).lower()
-
- setattr(self, name.lower(), cmdObj)
-
- # Also, add the object into the _writeOrder dict in the right place.
- if cmdObj.writePriority is not None:
- if self._writeOrder.has_key(cmdObj.writePriority):
- self._insertSorted(self._writeOrder[cmdObj.writePriority], cmdObj)
- else:
- self._writeOrder[cmdObj.writePriority] = [cmdObj]
-
- def _registerCommands(self, mapping=None, dataMapping=None, commandUpdates=None,
- dataUpdates=None):
- if mapping == {} or mapping == None:
- from pykickstart.handlers.control import commandMap
- cMap = commandMap[self.version]
- else:
- cMap = mapping
-
- if dataMapping == {} or dataMapping == None:
- from pykickstart.handlers.control import dataMap
- dMap = dataMap[self.version]
- else:
- dMap = dataMapping
-
- if type(commandUpdates) == types.DictType:
- cMap.update(commandUpdates)
-
- if type(dataUpdates) == types.DictType:
- dMap.update(dataUpdates)
-
- for (cmdName, cmdClass) in cMap.iteritems():
- # First make sure we haven't instantiated this command handler
- # already. If we have, we just need to make another mapping to
- # it in self.commands.
- cmdObj = None
-
- for (key, val) in self.commands.iteritems():
- if val.__class__.__name__ == cmdClass.__name__:
- cmdObj = val
- break
-
- # If we didn't find an instance in self.commands, create one now.
- if cmdObj == None:
- cmdObj = cmdClass()
- self._setCommand(cmdObj)
-
- # Finally, add the mapping to the commands dict.
- self.commands[cmdName] = cmdObj
- self.commands[cmdName].handler = self
-
- # We also need to create attributes for the various data objects.
- # No checks here because dMap is a bijection. At least, that's what
- # the comment says. Hope no one screws that up.
- for (dataName, dataClass) in dMap.iteritems():
- setattr(self, dataName, dataClass)
-
- def dispatcher(self, args, lineno):
- """Call the appropriate KickstartCommand handler for the current line
- in the kickstart file. A handler for the current command should
- be registered, though a handler of None is not an error. Returns
- the data object returned by KickstartCommand.parse.
-
- args -- A list of arguments to the current command
- lineno -- The line number in the file, for error reporting
- """
- cmd = args[0]
-
- if not self.commands.has_key(cmd):
- raise KickstartParseError, formatErrorMsg(lineno, msg=_("Unknown command: %s" % cmd))
- elif self.commands[cmd] != None:
- self.commands[cmd].currentCmd = cmd
- self.commands[cmd].currentLine = self.currentLine
- self.commands[cmd].lineno = lineno
-
- # The parser returns the data object that was modified. This could
- # be a BaseData subclass that should be put into a list, or it
- # could be the command handler object itself.
- obj = self.commands[cmd].parse(args[1:])
- lst = self.commands[cmd].dataList()
- if lst is not None:
- lst.append(obj)
-
- return obj
-
- def maskAllExcept(self, lst):
- """Set all entries in the commands dict to None, except the ones in
- the lst. All other commands will not be processed.
- """
- self._writeOrder = {}
-
- for (key, val) in self.commands.iteritems():
- if not key in lst:
- self.commands[key] = None
-
- def hasCommand(self, cmd):
- """Return true if there is a handler for the string cmd."""
- return hasattr(self, cmd)
-
-
-###
-### DATA
-###
-class BaseData(KickstartObject):
- """The base class for all data objects. This is an abstract class."""
- removedKeywords = []
- removedAttrs = []
-
- def __init__(self, *args, **kwargs):
- """Create a new BaseData instance.
-
- lineno -- Line number in the ks-file where this object was defined
- """
-
- # We don't want people using this class by itself.
- if self.__class__ is BaseData:
- raise TypeError, "BaseData is an abstract class."
-
- KickstartObject.__init__(self, *args, **kwargs)
- self.lineno = 0
-
- def __str__(self):
- """Return a string formatted for output to a kickstart file."""
- return ""
-
- def __call__(self, *args, **kwargs):
- """Set multiple attributes on a subclass of BaseData at once via
- keyword arguments. Valid attributes are anything specified in a
- subclass, but unknown attributes will be ignored.
- """
- for (key, val) in kwargs.items():
- # Ignore setting attributes that were removed in a subclass, as
- # if they were unknown attributes.
- if key in self.removedAttrs:
- continue
-
- if hasattr(self, key):
- setattr(self, key, val)
-
- def deleteRemovedAttrs(self):
- """Remove all attributes from self that are given in the removedAttrs
- list. This method should be called from __init__ in a subclass,
- but only after the superclass's __init__ method has been called.
- """
- for attr in filter(lambda k: hasattr(self, k), self.removedAttrs):
- delattr(self, attr)
diff --git a/scripts/lib/wic/3rdparty/pykickstart/commands/__init__.py b/scripts/lib/wic/3rdparty/pykickstart/commands/__init__.py
deleted file mode 100644
index 2d94550935..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/commands/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# Copyright 2009 Red Hat, Inc.
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-import bootloader, partition
diff --git a/scripts/lib/wic/3rdparty/pykickstart/commands/bootloader.py b/scripts/lib/wic/3rdparty/pykickstart/commands/bootloader.py
deleted file mode 100644
index c2b552f689..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/commands/bootloader.py
+++ /dev/null
@@ -1,216 +0,0 @@
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# Copyright 2007 Red Hat, Inc.
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-from pykickstart.base import *
-from pykickstart.options import *
-
-class FC3_Bootloader(KickstartCommand):
- removedKeywords = KickstartCommand.removedKeywords
- removedAttrs = KickstartCommand.removedAttrs
-
- def __init__(self, writePriority=10, *args, **kwargs):
- KickstartCommand.__init__(self, writePriority, *args, **kwargs)
- self.op = self._getParser()
-
- self.driveorder = kwargs.get("driveorder", [])
- self.appendLine = kwargs.get("appendLine", "")
- self.forceLBA = kwargs.get("forceLBA", False)
- self.linear = kwargs.get("linear", True)
- self.location = kwargs.get("location", "")
- self.md5pass = kwargs.get("md5pass", "")
- self.password = kwargs.get("password", "")
- self.upgrade = kwargs.get("upgrade", False)
- self.useLilo = kwargs.get("useLilo", False)
-
- self.deleteRemovedAttrs()
-
- def _getArgsAsStr(self):
- retval = ""
-
- if self.appendLine != "":
- retval += " --append=\"%s\"" % self.appendLine
- if self.linear:
- retval += " --linear"
- if self.location:
- retval += " --location=%s" % self.location
- if hasattr(self, "forceLBA") and self.forceLBA:
- retval += " --lba32"
- if self.password != "":
- retval += " --password=\"%s\"" % self.password
- if self.md5pass != "":
- retval += " --md5pass=\"%s\"" % self.md5pass
- if self.upgrade:
- retval += " --upgrade"
- if self.useLilo:
- retval += " --useLilo"
- if len(self.driveorder) > 0:
- retval += " --driveorder=\"%s\"" % ",".join(self.driveorder)
-
- return retval
-
- def __str__(self):
- retval = KickstartCommand.__str__(self)
-
- if self.location != "":
- retval += "# System bootloader configuration\nbootloader"
- retval += self._getArgsAsStr() + "\n"
-
- return retval
-
- def _getParser(self):
- def driveorder_cb (option, opt_str, value, parser):
- for d in value.split(','):
- parser.values.ensure_value(option.dest, []).append(d)
-
- op = KSOptionParser()
- op.add_option("--append", dest="appendLine")
- op.add_option("--linear", dest="linear", action="store_true",
- default=True)
- op.add_option("--nolinear", dest="linear", action="store_false")
- op.add_option("--location", dest="location", type="choice",
- default="mbr",
- choices=["mbr", "partition", "none", "boot"])
- op.add_option("--lba32", dest="forceLBA", action="store_true",
- default=False)
- op.add_option("--password", dest="password", default="")
- op.add_option("--md5pass", dest="md5pass", default="")
- op.add_option("--upgrade", dest="upgrade", action="store_true",
- default=False)
- op.add_option("--useLilo", dest="useLilo", action="store_true",
- default=False)
- op.add_option("--driveorder", dest="driveorder", action="callback",
- callback=driveorder_cb, nargs=1, type="string")
- return op
-
- def parse(self, args):
- (opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
- self._setToSelf(self.op, opts)
-
- if self.currentCmd == "lilo":
- self.useLilo = True
-
- return self
-
-class FC4_Bootloader(FC3_Bootloader):
- removedKeywords = FC3_Bootloader.removedKeywords + ["linear", "useLilo"]
- removedAttrs = FC3_Bootloader.removedAttrs + ["linear", "useLilo"]
-
- def __init__(self, writePriority=10, *args, **kwargs):
- FC3_Bootloader.__init__(self, writePriority, *args, **kwargs)
-
- def _getArgsAsStr(self):
- retval = ""
- if self.appendLine != "":
- retval += " --append=\"%s\"" % self.appendLine
- if self.location:
- retval += " --location=%s" % self.location
- if hasattr(self, "forceLBA") and self.forceLBA:
- retval += " --lba32"
- if self.password != "":
- retval += " --password=\"%s\"" % self.password
- if self.md5pass != "":
- retval += " --md5pass=\"%s\"" % self.md5pass
- if self.upgrade:
- retval += " --upgrade"
- if len(self.driveorder) > 0:
- retval += " --driveorder=\"%s\"" % ",".join(self.driveorder)
- return retval
-
- def _getParser(self):
- op = FC3_Bootloader._getParser(self)
- op.remove_option("--linear")
- op.remove_option("--nolinear")
- op.remove_option("--useLilo")
- return op
-
- def parse(self, args):
- (opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
- self._setToSelf(self.op, opts)
- return self
-
-class F8_Bootloader(FC4_Bootloader):
- removedKeywords = FC4_Bootloader.removedKeywords
- removedAttrs = FC4_Bootloader.removedAttrs
-
- def __init__(self, writePriority=10, *args, **kwargs):
- FC4_Bootloader.__init__(self, writePriority, *args, **kwargs)
-
- self.timeout = kwargs.get("timeout", None)
- self.default = kwargs.get("default", "")
-
- def _getArgsAsStr(self):
- ret = FC4_Bootloader._getArgsAsStr(self)
-
- if self.timeout is not None:
- ret += " --timeout=%d" %(self.timeout,)
- if self.default:
- ret += " --default=%s" %(self.default,)
-
- return ret
-
- def _getParser(self):
- op = FC4_Bootloader._getParser(self)
- op.add_option("--timeout", dest="timeout", type="int")
- op.add_option("--default", dest="default")
- return op
-
-class F12_Bootloader(F8_Bootloader):
- removedKeywords = F8_Bootloader.removedKeywords
- removedAttrs = F8_Bootloader.removedAttrs
-
- def _getParser(self):
- op = F8_Bootloader._getParser(self)
- op.add_option("--lba32", dest="forceLBA", deprecated=1, action="store_true")
- return op
-
-class F14_Bootloader(F12_Bootloader):
- removedKeywords = F12_Bootloader.removedKeywords + ["forceLBA"]
- removedAttrs = F12_Bootloader.removedKeywords + ["forceLBA"]
-
- def _getParser(self):
- op = F12_Bootloader._getParser(self)
- op.remove_option("--lba32")
- return op
-
-class F15_Bootloader(F14_Bootloader):
- removedKeywords = F14_Bootloader.removedKeywords
- removedAttrs = F14_Bootloader.removedAttrs
-
- def __init__(self, writePriority=10, *args, **kwargs):
- F14_Bootloader.__init__(self, writePriority, *args, **kwargs)
-
- self.isCrypted = kwargs.get("isCrypted", False)
-
- def _getArgsAsStr(self):
- ret = F14_Bootloader._getArgsAsStr(self)
-
- if self.isCrypted:
- ret += " --iscrypted"
-
- return ret
-
- def _getParser(self):
- def password_cb(option, opt_str, value, parser):
- parser.values.isCrypted = True
- parser.values.password = value
-
- op = F14_Bootloader._getParser(self)
- op.add_option("--iscrypted", dest="isCrypted", action="store_true", default=False)
- op.add_option("--md5pass", action="callback", callback=password_cb, nargs=1, type="string")
- return op
diff --git a/scripts/lib/wic/3rdparty/pykickstart/commands/partition.py b/scripts/lib/wic/3rdparty/pykickstart/commands/partition.py
deleted file mode 100644
index b564b1a7ab..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/commands/partition.py
+++ /dev/null
@@ -1,314 +0,0 @@
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# Copyright 2005, 2006, 2007, 2008 Red Hat, Inc.
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-from pykickstart.base import *
-from pykickstart.errors import *
-from pykickstart.options import *
-
-import gettext
-import warnings
-_ = lambda x: gettext.ldgettext("pykickstart", x)
-
-class FC3_PartData(BaseData):
- removedKeywords = BaseData.removedKeywords
- removedAttrs = BaseData.removedAttrs
-
- def __init__(self, *args, **kwargs):
- BaseData.__init__(self, *args, **kwargs)
- self.active = kwargs.get("active", False)
- self.primOnly = kwargs.get("primOnly", False)
- self.end = kwargs.get("end", 0)
- self.fstype = kwargs.get("fstype", "")
- self.grow = kwargs.get("grow", False)
- self.maxSizeMB = kwargs.get("maxSizeMB", 0)
- self.format = kwargs.get("format", True)
- self.onbiosdisk = kwargs.get("onbiosdisk", "")
- self.disk = kwargs.get("disk", "")
- self.onPart = kwargs.get("onPart", "")
- self.recommended = kwargs.get("recommended", False)
- self.size = kwargs.get("size", None)
- self.start = kwargs.get("start", 0)
- self.mountpoint = kwargs.get("mountpoint", "")
-
- def __eq__(self, y):
- if self.mountpoint:
- return self.mountpoint == y.mountpoint
- else:
- return False
-
- def _getArgsAsStr(self):
- retval = ""
-
- if self.active:
- retval += " --active"
- if self.primOnly:
- retval += " --asprimary"
- if hasattr(self, "end") and self.end != 0:
- retval += " --end=%s" % self.end
- if self.fstype != "":
- retval += " --fstype=\"%s\"" % self.fstype
- if self.grow:
- retval += " --grow"
- if self.maxSizeMB > 0:
- retval += " --maxsize=%d" % self.maxSizeMB
- if not self.format:
- retval += " --noformat"
- if self.onbiosdisk != "":
- retval += " --onbiosdisk=%s" % self.onbiosdisk
- if self.disk != "":
- retval += " --ondisk=%s" % self.disk
- if self.onPart != "":
- retval += " --onpart=%s" % self.onPart
- if self.recommended:
- retval += " --recommended"
- if self.size and self.size != 0:
- retval += " --size=%sk" % self.size
- if hasattr(self, "start") and self.start != 0:
- retval += " --start=%s" % self.start
-
- return retval
-
- def __str__(self):
- retval = BaseData.__str__(self)
- if self.mountpoint:
- mountpoint_str = "%s" % self.mountpoint
- else:
- mountpoint_str = "(No mount point)"
- retval += "part %s%s\n" % (mountpoint_str, self._getArgsAsStr())
- return retval
-
-class FC4_PartData(FC3_PartData):
- removedKeywords = FC3_PartData.removedKeywords
- removedAttrs = FC3_PartData.removedAttrs
-
- def __init__(self, *args, **kwargs):
- FC3_PartData.__init__(self, *args, **kwargs)
- self.bytesPerInode = kwargs.get("bytesPerInode", 4096)
- self.fsopts = kwargs.get("fsopts", "")
- self.label = kwargs.get("label", "")
-
- def _getArgsAsStr(self):
- retval = FC3_PartData._getArgsAsStr(self)
-
- if hasattr(self, "bytesPerInode") and self.bytesPerInode != 0:
- retval += " --bytes-per-inode=%d" % self.bytesPerInode
- if self.fsopts != "":
- retval += " --fsoptions=\"%s\"" % self.fsopts
- if self.label != "":
- retval += " --label=%s" % self.label
-
- return retval
-
-class F9_PartData(FC4_PartData):
- removedKeywords = FC4_PartData.removedKeywords + ["bytesPerInode"]
- removedAttrs = FC4_PartData.removedAttrs + ["bytesPerInode"]
-
- def __init__(self, *args, **kwargs):
- FC4_PartData.__init__(self, *args, **kwargs)
- self.deleteRemovedAttrs()
-
- self.fsopts = kwargs.get("fsopts", "")
- self.label = kwargs.get("label", "")
- self.fsprofile = kwargs.get("fsprofile", "")
- self.encrypted = kwargs.get("encrypted", False)
- self.passphrase = kwargs.get("passphrase", "")
-
- def _getArgsAsStr(self):
- retval = FC4_PartData._getArgsAsStr(self)
-
- if self.fsprofile != "":
- retval += " --fsprofile=\"%s\"" % self.fsprofile
- if self.encrypted:
- retval += " --encrypted"
-
- if self.passphrase != "":
- retval += " --passphrase=\"%s\"" % self.passphrase
-
- return retval
-
-class F11_PartData(F9_PartData):
- removedKeywords = F9_PartData.removedKeywords + ["start", "end"]
- removedAttrs = F9_PartData.removedAttrs + ["start", "end"]
-
-class F12_PartData(F11_PartData):
- removedKeywords = F11_PartData.removedKeywords
- removedAttrs = F11_PartData.removedAttrs
-
- def __init__(self, *args, **kwargs):
- F11_PartData.__init__(self, *args, **kwargs)
-
- self.escrowcert = kwargs.get("escrowcert", "")
- self.backuppassphrase = kwargs.get("backuppassphrase", False)
-
- def _getArgsAsStr(self):
- retval = F11_PartData._getArgsAsStr(self)
-
- if self.encrypted and self.escrowcert != "":
- retval += " --escrowcert=\"%s\"" % self.escrowcert
-
- if self.backuppassphrase:
- retval += " --backuppassphrase"
-
- return retval
-
-F14_PartData = F12_PartData
-
-class FC3_Partition(KickstartCommand):
- removedKeywords = KickstartCommand.removedKeywords
- removedAttrs = KickstartCommand.removedAttrs
-
- def __init__(self, writePriority=130, *args, **kwargs):
- KickstartCommand.__init__(self, writePriority, *args, **kwargs)
- self.op = self._getParser()
-
- self.partitions = kwargs.get("partitions", [])
-
- def __str__(self):
- retval = ""
-
- for part in self.partitions:
- retval += part.__str__()
-
- if retval != "":
- return "# Disk partitioning information\n" + retval
- else:
- return ""
-
- def _getParser(self):
- def part_cb (option, opt_str, value, parser):
- if value.startswith("/dev/"):
- parser.values.ensure_value(option.dest, value[5:])
- else:
- parser.values.ensure_value(option.dest, value)
-
- op = KSOptionParser()
- op.add_option("--active", dest="active", action="store_true",
- default=False)
- op.add_option("--asprimary", dest="primOnly", action="store_true",
- default=False)
- op.add_option("--end", dest="end", action="store", type="int",
- nargs=1)
- op.add_option("--fstype", "--type", dest="fstype")
- op.add_option("--grow", dest="grow", action="store_true", default=False)
- op.add_option("--maxsize", dest="maxSizeMB", action="store", type="int",
- nargs=1)
- op.add_option("--noformat", dest="format", action="store_false",
- default=True)
- op.add_option("--onbiosdisk", dest="onbiosdisk")
- op.add_option("--ondisk", "--ondrive", dest="disk")
- op.add_option("--onpart", "--usepart", dest="onPart", action="callback",
- callback=part_cb, nargs=1, type="string")
- op.add_option("--recommended", dest="recommended", action="store_true",
- default=False)
- op.add_option("--size", dest="size", action="store", type="size",
- nargs=1)
- op.add_option("--start", dest="start", action="store", type="int",
- nargs=1)
- return op
-
- def parse(self, args):
- (opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
-
- pd = self.handler.PartData()
- self._setToObj(self.op, opts, pd)
- pd.lineno = self.lineno
- if extra:
- pd.mountpoint = extra[0]
- if pd in self.dataList():
- warnings.warn(_("A partition with the mountpoint %s has already been defined.") % pd.mountpoint)
- else:
- pd.mountpoint = None
-
- return pd
-
- def dataList(self):
- return self.partitions
-
-class FC4_Partition(FC3_Partition):
- removedKeywords = FC3_Partition.removedKeywords
- removedAttrs = FC3_Partition.removedAttrs
-
- def __init__(self, writePriority=130, *args, **kwargs):
- FC3_Partition.__init__(self, writePriority, *args, **kwargs)
-
- def part_cb (option, opt_str, value, parser):
- if value.startswith("/dev/"):
- parser.values.ensure_value(option.dest, value[5:])
- else:
- parser.values.ensure_value(option.dest, value)
-
- def _getParser(self):
- op = FC3_Partition._getParser(self)
- op.add_option("--bytes-per-inode", dest="bytesPerInode", action="store",
- type="int", nargs=1)
- op.add_option("--fsoptions", dest="fsopts")
- op.add_option("--label", dest="label")
- return op
-
-class F9_Partition(FC4_Partition):
- removedKeywords = FC4_Partition.removedKeywords
- removedAttrs = FC4_Partition.removedAttrs
-
- def __init__(self, writePriority=130, *args, **kwargs):
- FC4_Partition.__init__(self, writePriority, *args, **kwargs)
-
- def part_cb (option, opt_str, value, parser):
- if value.startswith("/dev/"):
- parser.values.ensure_value(option.dest, value[5:])
- else:
- parser.values.ensure_value(option.dest, value)
-
- def _getParser(self):
- op = FC4_Partition._getParser(self)
- op.add_option("--bytes-per-inode", deprecated=1)
- op.add_option("--fsprofile")
- op.add_option("--encrypted", action="store_true", default=False)
- op.add_option("--passphrase")
- return op
-
-class F11_Partition(F9_Partition):
- removedKeywords = F9_Partition.removedKeywords
- removedAttrs = F9_Partition.removedAttrs
-
- def _getParser(self):
- op = F9_Partition._getParser(self)
- op.add_option("--start", deprecated=1)
- op.add_option("--end", deprecated=1)
- return op
-
-class F12_Partition(F11_Partition):
- removedKeywords = F11_Partition.removedKeywords
- removedAttrs = F11_Partition.removedAttrs
-
- def _getParser(self):
- op = F11_Partition._getParser(self)
- op.add_option("--escrowcert")
- op.add_option("--backuppassphrase", action="store_true", default=False)
- return op
-
-class F14_Partition(F12_Partition):
- removedKeywords = F12_Partition.removedKeywords
- removedAttrs = F12_Partition.removedAttrs
-
- def _getParser(self):
- op = F12_Partition._getParser(self)
- op.remove_option("--bytes-per-inode")
- op.remove_option("--start")
- op.remove_option("--end")
- return op
diff --git a/scripts/lib/wic/3rdparty/pykickstart/constants.py b/scripts/lib/wic/3rdparty/pykickstart/constants.py
deleted file mode 100644
index 5e12fc80ec..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/constants.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# Copyright 2005-2007 Red Hat, Inc.
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-CLEARPART_TYPE_LINUX = 0
-CLEARPART_TYPE_ALL = 1
-CLEARPART_TYPE_NONE = 2
-
-DISPLAY_MODE_CMDLINE = 0
-DISPLAY_MODE_GRAPHICAL = 1
-DISPLAY_MODE_TEXT = 2
-
-FIRSTBOOT_DEFAULT = 0
-FIRSTBOOT_SKIP = 1
-FIRSTBOOT_RECONFIG = 2
-
-KS_MISSING_PROMPT = 0
-KS_MISSING_IGNORE = 1
-
-SELINUX_DISABLED = 0
-SELINUX_ENFORCING = 1
-SELINUX_PERMISSIVE = 2
-
-KS_SCRIPT_PRE = 0
-KS_SCRIPT_POST = 1
-KS_SCRIPT_TRACEBACK = 2
-
-KS_WAIT = 0
-KS_REBOOT = 1
-KS_SHUTDOWN = 2
-
-KS_INSTKEY_SKIP = -99
-
-BOOTPROTO_DHCP = "dhcp"
-BOOTPROTO_BOOTP = "bootp"
-BOOTPROTO_STATIC = "static"
-BOOTPROTO_QUERY = "query"
-BOOTPROTO_IBFT = "ibft"
-
-GROUP_REQUIRED = 0
-GROUP_DEFAULT = 1
-GROUP_ALL = 2
diff --git a/scripts/lib/wic/3rdparty/pykickstart/errors.py b/scripts/lib/wic/3rdparty/pykickstart/errors.py
deleted file mode 100644
index a234d99d43..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/errors.py
+++ /dev/null
@@ -1,103 +0,0 @@
-#
-# errors.py: Kickstart error handling.
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-"""
-Error handling classes and functions.
-
-This module exports a single function:
-
- formatErrorMsg - Properly formats an error message.
-
-It also exports several exception classes:
-
- KickstartError - A generic exception class.
-
- KickstartParseError - An exception for errors relating to parsing.
-
- KickstartValueError - An exception for errors relating to option
- processing.
-
- KickstartVersionError - An exception for errors relating to unsupported
- syntax versions.
-"""
-import gettext
-_ = lambda x: gettext.ldgettext("pykickstart", x)
-
-def formatErrorMsg(lineno, msg=""):
- """Properly format the error message msg for inclusion in an exception."""
- if msg != "":
- mapping = {"lineno": lineno, "msg": msg}
- return _("The following problem occurred on line %(lineno)s of the kickstart file:\n\n%(msg)s\n") % mapping
- else:
- return _("There was a problem reading from line %s of the kickstart file") % lineno
-
-class KickstartError(Exception):
- """A generic exception class for unspecific error conditions."""
- def __init__(self, val = ""):
- """Create a new KickstartError exception instance with the descriptive
- message val. val should be the return value of formatErrorMsg.
- """
- Exception.__init__(self)
- self.value = val
-
- def __str__ (self):
- return self.value
-
-class KickstartParseError(KickstartError):
- """An exception class for errors when processing the input file, such as
- unknown options, commands, or sections.
- """
- def __init__(self, msg):
- """Create a new KickstartParseError exception instance with the
- descriptive message val. val should be the return value of
- formatErrorMsg.
- """
- KickstartError.__init__(self, msg)
-
- def __str__(self):
- return self.value
-
-class KickstartValueError(KickstartError):
- """An exception class for errors when processing arguments to commands,
- such as too many arguments, too few arguments, or missing required
- arguments.
- """
- def __init__(self, msg):
- """Create a new KickstartValueError exception instance with the
- descriptive message val. val should be the return value of
- formatErrorMsg.
- """
- KickstartError.__init__(self, msg)
-
- def __str__ (self):
- return self.value
-
-class KickstartVersionError(KickstartError):
- """An exception class for errors related to using an incorrect version of
- kickstart syntax.
- """
- def __init__(self, msg):
- """Create a new KickstartVersionError exception instance with the
- descriptive message val. val should be the return value of
- formatErrorMsg.
- """
- KickstartError.__init__(self, msg)
-
- def __str__ (self):
- return self.value
diff --git a/scripts/lib/wic/3rdparty/pykickstart/handlers/control.py b/scripts/lib/wic/3rdparty/pykickstart/handlers/control.py
deleted file mode 100644
index 8dc80d1ebe..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/handlers/control.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# Copyright 2007, 2008, 2009, 2010 Red Hat, Inc.
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-from pykickstart.version import *
-from pykickstart.commands import *
-
-# This map is keyed on kickstart syntax version as provided by
-# pykickstart.version. Within each sub-dict is a mapping from command name
-# to the class that handles it. This is an onto mapping - that is, multiple
-# command names can map to the same class. However, the Handler will ensure
-# that only one instance of each class ever exists.
-commandMap = {
- # based on f15
- F16: {
- "bootloader": bootloader.F15_Bootloader,
- "part": partition.F14_Partition,
- "partition": partition.F14_Partition,
- },
-}
-
-# This map is keyed on kickstart syntax version as provided by
-# pykickstart.version. Within each sub-dict is a mapping from a data object
-# name to the class that provides it. This is a bijective mapping - that is,
-# each name maps to exactly one data class and all data classes have a name.
-# More than one instance of each class is allowed to exist, however.
-dataMap = {
- F16: {
- "PartData": partition.F14_PartData,
- },
-}
diff --git a/scripts/lib/wic/3rdparty/pykickstart/handlers/f16.py b/scripts/lib/wic/3rdparty/pykickstart/handlers/f16.py
deleted file mode 100644
index 3c52f8d754..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/handlers/f16.py
+++ /dev/null
@@ -1,24 +0,0 @@
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# Copyright 2011 Red Hat, Inc.
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-from pykickstart.base import *
-from pykickstart.version import *
-
-class F16Handler(BaseHandler):
- version = F16
diff --git a/scripts/lib/wic/3rdparty/pykickstart/ko.py b/scripts/lib/wic/3rdparty/pykickstart/ko.py
deleted file mode 100644
index 1350d19c70..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/ko.py
+++ /dev/null
@@ -1,37 +0,0 @@
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# Copyright 2009 Red Hat, Inc.
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-"""
-Base classes for internal pykickstart use.
-
-The module exports the following important classes:
-
- KickstartObject - The base class for all classes in pykickstart
-"""
-
-class KickstartObject(object):
- """The base class for all other classes in pykickstart."""
- def __init__(self, *args, **kwargs):
- """Create a new KickstartObject instance. All other classes in
- pykickstart should be derived from this one. Instance attributes:
- """
- pass
-
- def __str__(self):
- return ""
diff --git a/scripts/lib/wic/3rdparty/pykickstart/options.py b/scripts/lib/wic/3rdparty/pykickstart/options.py
deleted file mode 100644
index ebc23eda63..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/options.py
+++ /dev/null
@@ -1,223 +0,0 @@
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# Copyright 2005, 2006, 2007 Red Hat, Inc.
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-"""
-Specialized option handling.
-
-This module exports two classes:
-
- KSOptionParser - A specialized subclass of OptionParser to be used
- in BaseHandler subclasses.
-
- KSOption - A specialized subclass of Option.
-"""
-import warnings
-from copy import copy
-from optparse import *
-
-from constants import *
-from errors import *
-from version import *
-
-import gettext
-_ = lambda x: gettext.ldgettext("pykickstart", x)
-
-class KSOptionParser(OptionParser):
- """A specialized subclass of optparse.OptionParser to handle extra option
- attribute checking, work error reporting into the KickstartParseError
- framework, and to turn off the default help.
- """
- def exit(self, status=0, msg=None):
- pass
-
- def error(self, msg):
- if self.lineno != None:
- raise KickstartParseError, formatErrorMsg(self.lineno, msg=msg)
- else:
- raise KickstartParseError, msg
-
- def keys(self):
- retval = []
-
- for opt in self.option_list:
- if opt not in retval:
- retval.append(opt.dest)
-
- return retval
-
- def _init_parsing_state (self):
- OptionParser._init_parsing_state(self)
- self.option_seen = {}
-
- def check_values (self, values, args):
- def seen(self, option):
- return self.option_seen.has_key(option)
-
- def usedTooNew(self, option):
- return option.introduced and option.introduced > self.version
-
- def usedDeprecated(self, option):
- return option.deprecated
-
- def usedRemoved(self, option):
- return option.removed and option.removed <= self.version
-
- for option in filter(lambda o: isinstance(o, Option), self.option_list):
- if option.required and not seen(self, option):
- raise KickstartValueError, formatErrorMsg(self.lineno, _("Option %s is required") % option)
- elif seen(self, option) and usedTooNew(self, option):
- mapping = {"option": option, "intro": versionToString(option.introduced),
- "version": versionToString(self.version)}
- self.error(_("The %(option)s option was introduced in version %(intro)s, but you are using kickstart syntax version %(version)s.") % mapping)
- elif seen(self, option) and usedRemoved(self, option):
- mapping = {"option": option, "removed": versionToString(option.removed),
- "version": versionToString(self.version)}
-
- if option.removed == self.version:
- self.error(_("The %(option)s option is no longer supported.") % mapping)
- else:
- self.error(_("The %(option)s option was removed in version %(removed)s, but you are using kickstart syntax version %(version)s.") % mapping)
- elif seen(self, option) and usedDeprecated(self, option):
- mapping = {"lineno": self.lineno, "option": option}
- warnings.warn(_("Ignoring deprecated option on line %(lineno)s: The %(option)s option has been deprecated and no longer has any effect. It may be removed from future releases, which will result in a fatal error from kickstart. Please modify your kickstart file to remove this option.") % mapping, DeprecationWarning)
-
- return (values, args)
-
- def parse_args(self, *args, **kwargs):
- if kwargs.has_key("lineno"):
- self.lineno = kwargs.pop("lineno")
-
- return OptionParser.parse_args(self, **kwargs)
-
- def __init__(self, mapping=None, version=None):
- """Create a new KSOptionParser instance. Each KickstartCommand
- subclass should create one instance of KSOptionParser, providing
- at least the lineno attribute. mapping and version are not required.
- Instance attributes:
-
- mapping -- A mapping from option strings to different values.
- version -- The version of the kickstart syntax we are checking
- against.
- """
- OptionParser.__init__(self, option_class=KSOption,
- add_help_option=False,
- conflict_handler="resolve")
- if mapping is None:
- self.map = {}
- else:
- self.map = mapping
-
- self.lineno = None
- self.option_seen = {}
- self.version = version
-
-def _check_ksboolean(option, opt, value):
- if value.lower() in ("on", "yes", "true", "1"):
- return True
- elif value.lower() in ("off", "no", "false", "0"):
- return False
- else:
- mapping = {"opt": opt, "value": value}
- raise OptionValueError(_("Option %(opt)s: invalid boolean value: %(value)r") % mapping)
-
-def _check_string(option, opt, value):
- if len(value) > 2 and value.startswith("--"):
- mapping = {"opt": opt, "value": value}
- raise OptionValueError(_("Option %(opt)s: invalid string value: %(value)r") % mapping)
- else:
- return value
-
-def _check_size(option, opt, value):
- # Former default was MB
- if value.isdigit():
- return int(value) * 1024L
-
- mapping = {"opt": opt, "value": value}
- if not value[:-1].isdigit():
- raise OptionValueError(_("Option %(opt)s: invalid size value: %(value)r") % mapping)
-
- size = int(value[:-1])
- if value.endswith("k") or value.endswith("K"):
- return size
- if value.endswith("M"):
- return size * 1024L
- if value.endswith("G"):
- return size * 1024L * 1024L
- raise OptionValueError(_("Option %(opt)s: invalid size value: %(value)r") % mapping)
-
-# Creates a new Option class that supports several new attributes:
-# - required: any option with this attribute must be supplied or an exception
-# is thrown
-# - introduced: the kickstart syntax version that this option first appeared
-# in - an exception will be raised if the option is used and
-# the specified syntax version is less than the value of this
-# attribute
-# - deprecated: the kickstart syntax version that this option was deprecated
-# in - a DeprecationWarning will be thrown if the option is
-# used and the specified syntax version is greater than the
-# value of this attribute
-# - removed: the kickstart syntax version that this option was removed in - an
-# exception will be raised if the option is used and the specified
-# syntax version is greated than the value of this attribute
-# Also creates a new type:
-# - ksboolean: support various kinds of boolean values on an option
-# And two new actions:
-# - map : allows you to define an opt -> val mapping such that dest gets val
-# when opt is seen
-# - map_extend: allows you to define an opt -> [val1, ... valn] mapping such
-# that dest gets a list of vals built up when opt is seen
-class KSOption (Option):
- ATTRS = Option.ATTRS + ['introduced', 'deprecated', 'removed', 'required']
- ACTIONS = Option.ACTIONS + ("map", "map_extend",)
- STORE_ACTIONS = Option.STORE_ACTIONS + ("map", "map_extend",)
-
- TYPES = Option.TYPES + ("ksboolean", "string", "size")
- TYPE_CHECKER = copy(Option.TYPE_CHECKER)
- TYPE_CHECKER["ksboolean"] = _check_ksboolean
- TYPE_CHECKER["string"] = _check_string
- TYPE_CHECKER["size"] = _check_size
-
- def _check_required(self):
- if self.required and not self.takes_value():
- raise OptionError(_("Required flag set for option that doesn't take a value"), self)
-
- # Make sure _check_required() is called from the constructor!
- CHECK_METHODS = Option.CHECK_METHODS + [_check_required]
-
- def process (self, opt, value, values, parser):
- Option.process(self, opt, value, values, parser)
- parser.option_seen[self] = 1
-
- # Override default take_action method to handle our custom actions.
- def take_action(self, action, dest, opt, value, values, parser):
- if action == "map":
- values.ensure_value(dest, parser.map[opt.lstrip('-')])
- elif action == "map_extend":
- values.ensure_value(dest, []).extend(parser.map[opt.lstrip('-')])
- else:
- Option.take_action(self, action, dest, opt, value, values, parser)
-
- def takes_value(self):
- # Deprecated options don't take a value.
- return Option.takes_value(self) and not self.deprecated
-
- def __init__(self, *args, **kwargs):
- self.deprecated = False
- self.required = False
- Option.__init__(self, *args, **kwargs)
diff --git a/scripts/lib/wic/3rdparty/pykickstart/parser.py b/scripts/lib/wic/3rdparty/pykickstart/parser.py
deleted file mode 100644
index 9c9674bf73..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/parser.py
+++ /dev/null
@@ -1,619 +0,0 @@
-#
-# parser.py: Kickstart file parser.
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# Copyright 2005, 2006, 2007, 2008, 2011 Red Hat, Inc.
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-"""
-Main kickstart file processing module.
-
-This module exports several important classes:
-
- Script - Representation of a single %pre, %post, or %traceback script.
-
- Packages - Representation of the %packages section.
-
- KickstartParser - The kickstart file parser state machine.
-"""
-
-from collections import Iterator
-import os
-import shlex
-import sys
-import tempfile
-from copy import copy
-from optparse import *
-
-import constants
-from errors import KickstartError, KickstartParseError, KickstartValueError, formatErrorMsg
-from ko import KickstartObject
-from sections import *
-import version
-
-import gettext
-_ = lambda x: gettext.ldgettext("pykickstart", x)
-
-STATE_END = "end"
-STATE_COMMANDS = "commands"
-
-ver = version.DEVEL
-
-
-class PutBackIterator(Iterator):
- def __init__(self, iterable):
- self._iterable = iter(iterable)
- self._buf = None
-
- def __iter__(self):
- return self
-
- def put(self, s):
- self._buf = s
-
- def next(self):
- if self._buf:
- retval = self._buf
- self._buf = None
- return retval
- else:
- return self._iterable.next()
-
-###
-### SCRIPT HANDLING
-###
-class Script(KickstartObject):
- """A class representing a single kickstart script. If functionality beyond
- just a data representation is needed (for example, a run method in
- anaconda), Script may be subclassed. Although a run method is not
- provided, most of the attributes of Script have to do with running the
- script. Instances of Script are held in a list by the Version object.
- """
- def __init__(self, script, *args , **kwargs):
- """Create a new Script instance. Instance attributes:
-
- errorOnFail -- If execution of the script fails, should anaconda
- stop, display an error, and then reboot without
- running any other scripts?
- inChroot -- Does the script execute in anaconda's chroot
- environment or not?
- interp -- The program that should be used to interpret this
- script.
- lineno -- The line number this script starts on.
- logfile -- Where all messages from the script should be logged.
- script -- A string containing all the lines of the script.
- type -- The type of the script, which can be KS_SCRIPT_* from
- pykickstart.constants.
- """
- KickstartObject.__init__(self, *args, **kwargs)
- self.script = "".join(script)
-
- self.interp = kwargs.get("interp", "/bin/sh")
- self.inChroot = kwargs.get("inChroot", False)
- self.lineno = kwargs.get("lineno", None)
- self.logfile = kwargs.get("logfile", None)
- self.errorOnFail = kwargs.get("errorOnFail", False)
- self.type = kwargs.get("type", constants.KS_SCRIPT_PRE)
-
- def __str__(self):
- """Return a string formatted for output to a kickstart file."""
- retval = ""
-
- if self.type == constants.KS_SCRIPT_PRE:
- retval += '\n%pre'
- elif self.type == constants.KS_SCRIPT_POST:
- retval += '\n%post'
- elif self.type == constants.KS_SCRIPT_TRACEBACK:
- retval += '\n%traceback'
-
- if self.interp != "/bin/sh" and self.interp != "":
- retval += " --interpreter=%s" % self.interp
- if self.type == constants.KS_SCRIPT_POST and not self.inChroot:
- retval += " --nochroot"
- if self.logfile != None:
- retval += " --logfile %s" % self.logfile
- if self.errorOnFail:
- retval += " --erroronfail"
-
- if self.script.endswith("\n"):
- if ver >= version.F8:
- return retval + "\n%s%%end\n" % self.script
- else:
- return retval + "\n%s\n" % self.script
- else:
- if ver >= version.F8:
- return retval + "\n%s\n%%end\n" % self.script
- else:
- return retval + "\n%s\n" % self.script
-
-
-##
-## PACKAGE HANDLING
-##
-class Group:
- """A class representing a single group in the %packages section."""
- def __init__(self, name="", include=constants.GROUP_DEFAULT):
- """Create a new Group instance. Instance attributes:
-
- name -- The group's identifier
- include -- The level of how much of the group should be included.
- Values can be GROUP_* from pykickstart.constants.
- """
- self.name = name
- self.include = include
-
- def __str__(self):
- """Return a string formatted for output to a kickstart file."""
- if self.include == constants.GROUP_REQUIRED:
- return "@%s --nodefaults" % self.name
- elif self.include == constants.GROUP_ALL:
- return "@%s --optional" % self.name
- else:
- return "@%s" % self.name
-
- def __cmp__(self, other):
- if self.name < other.name:
- return -1
- elif self.name > other.name:
- return 1
- return 0
-
-class Packages(KickstartObject):
- """A class representing the %packages section of the kickstart file."""
- def __init__(self, *args, **kwargs):
- """Create a new Packages instance. Instance attributes:
-
- addBase -- Should the Base group be installed even if it is
- not specified?
- default -- Should the default package set be selected?
- excludedList -- A list of all the packages marked for exclusion in
- the %packages section, without the leading minus
- symbol.
- excludeDocs -- Should documentation in each package be excluded?
- groupList -- A list of Group objects representing all the groups
- specified in the %packages section. Names will be
- stripped of the leading @ symbol.
- excludedGroupList -- A list of Group objects representing all the
- groups specified for removal in the %packages
- section. Names will be stripped of the leading
- -@ symbols.
- handleMissing -- If unknown packages are specified in the %packages
- section, should it be ignored or not? Values can
- be KS_MISSING_* from pykickstart.constants.
- packageList -- A list of all the packages specified in the
- %packages section.
- instLangs -- A list of languages to install.
- """
- KickstartObject.__init__(self, *args, **kwargs)
-
- self.addBase = True
- self.default = False
- self.excludedList = []
- self.excludedGroupList = []
- self.excludeDocs = False
- self.groupList = []
- self.handleMissing = constants.KS_MISSING_PROMPT
- self.packageList = []
- self.instLangs = None
-
- def __str__(self):
- """Return a string formatted for output to a kickstart file."""
- pkgs = ""
-
- if not self.default:
- grps = self.groupList
- grps.sort()
- for grp in grps:
- pkgs += "%s\n" % grp.__str__()
-
- p = self.packageList
- p.sort()
- for pkg in p:
- pkgs += "%s\n" % pkg
-
- grps = self.excludedGroupList
- grps.sort()
- for grp in grps:
- pkgs += "-%s\n" % grp.__str__()
-
- p = self.excludedList
- p.sort()
- for pkg in p:
- pkgs += "-%s\n" % pkg
-
- if pkgs == "":
- return ""
-
- retval = "\n%packages"
-
- if self.default:
- retval += " --default"
- if self.excludeDocs:
- retval += " --excludedocs"
- if not self.addBase:
- retval += " --nobase"
- if self.handleMissing == constants.KS_MISSING_IGNORE:
- retval += " --ignoremissing"
- if self.instLangs:
- retval += " --instLangs=%s" % self.instLangs
-
- if ver >= version.F8:
- return retval + "\n" + pkgs + "\n%end\n"
- else:
- return retval + "\n" + pkgs + "\n"
-
- def _processGroup (self, line):
- op = OptionParser()
- op.add_option("--nodefaults", action="store_true", default=False)
- op.add_option("--optional", action="store_true", default=False)
-
- (opts, extra) = op.parse_args(args=line.split())
-
- if opts.nodefaults and opts.optional:
- raise KickstartValueError, _("Group cannot specify both --nodefaults and --optional")
-
- # If the group name has spaces in it, we have to put it back together
- # now.
- grp = " ".join(extra)
-
- if opts.nodefaults:
- self.groupList.append(Group(name=grp, include=constants.GROUP_REQUIRED))
- elif opts.optional:
- self.groupList.append(Group(name=grp, include=constants.GROUP_ALL))
- else:
- self.groupList.append(Group(name=grp, include=constants.GROUP_DEFAULT))
-
- def add (self, pkgList):
- """Given a list of lines from the input file, strip off any leading
- symbols and add the result to the appropriate list.
- """
- existingExcludedSet = set(self.excludedList)
- existingPackageSet = set(self.packageList)
- newExcludedSet = set()
- newPackageSet = set()
-
- excludedGroupList = []
-
- for pkg in pkgList:
- stripped = pkg.strip()
-
- if stripped[0] == "@":
- self._processGroup(stripped[1:])
- elif stripped[0] == "-":
- if stripped[1] == "@":
- excludedGroupList.append(Group(name=stripped[2:]))
- else:
- newExcludedSet.add(stripped[1:])
- else:
- newPackageSet.add(stripped)
-
- # Groups have to be excluded in two different ways (note: can't use
- # sets here because we have to store objects):
- excludedGroupNames = map(lambda g: g.name, excludedGroupList)
-
- # First, an excluded group may be cancelling out a previously given
- # one. This is often the case when using %include. So there we should
- # just remove the group from the list.
- self.groupList = filter(lambda g: g.name not in excludedGroupNames, self.groupList)
-
- # Second, the package list could have included globs which are not
- # processed by pykickstart. In that case we need to preserve a list of
- # excluded groups so whatever tool doing package/group installation can
- # take appropriate action.
- self.excludedGroupList.extend(excludedGroupList)
-
- existingPackageSet = (existingPackageSet - newExcludedSet) | newPackageSet
- existingExcludedSet = (existingExcludedSet - existingPackageSet) | newExcludedSet
-
- self.packageList = list(existingPackageSet)
- self.excludedList = list(existingExcludedSet)
-
-
-###
-### PARSER
-###
-class KickstartParser:
- """The kickstart file parser class as represented by a basic state
- machine. To create a specialized parser, make a subclass and override
- any of the methods you care about. Methods that don't need to do
- anything may just pass. However, _stateMachine should never be
- overridden.
- """
- def __init__ (self, handler, followIncludes=True, errorsAreFatal=True,
- missingIncludeIsFatal=True):
- """Create a new KickstartParser instance. Instance attributes:
-
- errorsAreFatal -- Should errors cause processing to halt, or
- just print a message to the screen? This
- is most useful for writing syntax checkers
- that may want to continue after an error is
- encountered.
- followIncludes -- If %include is seen, should the included
- file be checked as well or skipped?
- handler -- An instance of a BaseHandler subclass. If
- None, the input file will still be parsed
- but no data will be saved and no commands
- will be executed.
- missingIncludeIsFatal -- Should missing include files be fatal, even
- if errorsAreFatal is False?
- """
- self.errorsAreFatal = errorsAreFatal
- self.followIncludes = followIncludes
- self.handler = handler
- self.currentdir = {}
- self.missingIncludeIsFatal = missingIncludeIsFatal
-
- self._state = STATE_COMMANDS
- self._includeDepth = 0
- self._line = ""
-
- self.version = self.handler.version
-
- global ver
- ver = self.version
-
- self._sections = {}
- self.setupSections()
-
- def _reset(self):
- """Reset the internal variables of the state machine for a new kickstart file."""
- self._state = STATE_COMMANDS
- self._includeDepth = 0
-
- def getSection(self, s):
- """Return a reference to the requested section (s must start with '%'s),
- or raise KeyError if not found.
- """
- return self._sections[s]
-
- def handleCommand (self, lineno, args):
- """Given the list of command and arguments, call the Version's
- dispatcher method to handle the command. Returns the command or
- data object returned by the dispatcher. This method may be
- overridden in a subclass if necessary.
- """
- if self.handler:
- self.handler.currentCmd = args[0]
- self.handler.currentLine = self._line
- retval = self.handler.dispatcher(args, lineno)
-
- return retval
-
- def registerSection(self, obj):
- """Given an instance of a Section subclass, register the new section
- with the parser. Calling this method means the parser will
- recognize your new section and dispatch into the given object to
- handle it.
- """
- if not obj.sectionOpen:
- raise TypeError, "no sectionOpen given for section %s" % obj
-
- if not obj.sectionOpen.startswith("%"):
- raise TypeError, "section %s tag does not start with a %%" % obj.sectionOpen
-
- self._sections[obj.sectionOpen] = obj
-
- def _finalize(self, obj):
- """Called at the close of a kickstart section to take any required
- actions. Internally, this is used to add scripts once we have the
- whole body read.
- """
- obj.finalize()
- self._state = STATE_COMMANDS
-
- def _handleSpecialComments(self, line):
- """Kickstart recognizes a couple special comments."""
- if self._state != STATE_COMMANDS:
- return
-
- # Save the platform for s-c-kickstart.
- if line[:10] == "#platform=":
- self.handler.platform = self._line[11:]
-
- def _readSection(self, lineIter, lineno):
- obj = self._sections[self._state]
-
- while True:
- try:
- line = lineIter.next()
- if line == "":
- # This section ends at the end of the file.
- if self.version >= version.F8:
- raise KickstartParseError, formatErrorMsg(lineno, msg=_("Section does not end with %%end."))
-
- self._finalize(obj)
- except StopIteration:
- break
-
- lineno += 1
-
- # Throw away blank lines and comments, unless the section wants all
- # lines.
- if self._isBlankOrComment(line) and not obj.allLines:
- continue
-
- if line.startswith("%"):
- args = shlex.split(line)
-
- if args and args[0] == "%end":
- # This is a properly terminated section.
- self._finalize(obj)
- break
- elif args and args[0] == "%ksappend":
- continue
- elif args and (self._validState(args[0]) or args[0] in ["%include", "%ksappend"]):
- # This is an unterminated section.
- if self.version >= version.F8:
- raise KickstartParseError, formatErrorMsg(lineno, msg=_("Section does not end with %%end."))
-
- # Finish up. We do not process the header here because
- # kicking back out to STATE_COMMANDS will ensure that happens.
- lineIter.put(line)
- lineno -= 1
- self._finalize(obj)
- break
- else:
- # This is just a line within a section. Pass it off to whatever
- # section handles it.
- obj.handleLine(line)
-
- return lineno
-
- def _validState(self, st):
- """Is the given section tag one that has been registered with the parser?"""
- return st in self._sections.keys()
-
- def _tryFunc(self, fn):
- """Call the provided function (which doesn't take any arguments) and
- do the appropriate error handling. If errorsAreFatal is False, this
- function will just print the exception and keep going.
- """
- try:
- fn()
- except Exception, msg:
- if self.errorsAreFatal:
- raise
- else:
- print msg
-
- def _isBlankOrComment(self, line):
- return line.isspace() or line == "" or line.lstrip()[0] == '#'
-
- def _stateMachine(self, lineIter):
- # For error reporting.
- lineno = 0
-
- while True:
- # Get the next line out of the file, quitting if this is the last line.
- try:
- self._line = lineIter.next()
- if self._line == "":
- break
- except StopIteration:
- break
-
- lineno += 1
-
- # Eliminate blank lines, whitespace-only lines, and comments.
- if self._isBlankOrComment(self._line):
- self._handleSpecialComments(self._line)
- continue
-
- # Remove any end-of-line comments.
- sanitized = self._line.split("#")[0]
-
- # Then split the line.
- args = shlex.split(sanitized.rstrip())
-
- if args[0] == "%include":
- # This case comes up primarily in ksvalidator.
- if not self.followIncludes:
- continue
-
- if len(args) == 1 or not args[1]:
- raise KickstartParseError, formatErrorMsg(lineno)
-
- self._includeDepth += 1
-
- try:
- self.readKickstart(args[1], reset=False)
- except KickstartError:
- # Handle the include file being provided over the
- # network in a %pre script. This case comes up in the
- # early parsing in anaconda.
- if self.missingIncludeIsFatal:
- raise
-
- self._includeDepth -= 1
- continue
-
- # Now on to the main event.
- if self._state == STATE_COMMANDS:
- if args[0] == "%ksappend":
- # This is handled by the preprocess* functions, so continue.
- continue
- elif args[0][0] == '%':
- # This is the beginning of a new section. Handle its header
- # here.
- newSection = args[0]
- if not self._validState(newSection):
- raise KickstartParseError, formatErrorMsg(lineno, msg=_("Unknown kickstart section: %s" % newSection))
-
- self._state = newSection
- obj = self._sections[self._state]
- self._tryFunc(lambda: obj.handleHeader(lineno, args))
-
- # This will handle all section processing, kicking us back
- # out to STATE_COMMANDS at the end with the current line
- # being the next section header, etc.
- lineno = self._readSection(lineIter, lineno)
- else:
- # This is a command in the command section. Dispatch to it.
- self._tryFunc(lambda: self.handleCommand(lineno, args))
- elif self._state == STATE_END:
- break
-
- def readKickstartFromString (self, s, reset=True):
- """Process a kickstart file, provided as the string str."""
- if reset:
- self._reset()
-
- # Add a "" to the end of the list so the string reader acts like the
- # file reader and we only get StopIteration when we're after the final
- # line of input.
- i = PutBackIterator(s.splitlines(True) + [""])
- self._stateMachine (i)
-
- def readKickstart(self, f, reset=True):
- """Process a kickstart file, given by the filename f."""
- if reset:
- self._reset()
-
- # an %include might not specify a full path. if we don't try to figure
- # out what the path should have been, then we're unable to find it
- # requiring full path specification, though, sucks. so let's make
- # the reading "smart" by keeping track of what the path is at each
- # include depth.
- if not os.path.exists(f):
- if self.currentdir.has_key(self._includeDepth - 1):
- if os.path.exists(os.path.join(self.currentdir[self._includeDepth - 1], f)):
- f = os.path.join(self.currentdir[self._includeDepth - 1], f)
-
- cd = os.path.dirname(f)
- if not cd.startswith("/"):
- cd = os.path.abspath(cd)
- self.currentdir[self._includeDepth] = cd
-
- try:
- s = file(f).read()
- except IOError, e:
- raise KickstartError, formatErrorMsg(0, msg=_("Unable to open input kickstart file: %s") % e.strerror)
-
- self.readKickstartFromString(s, reset=False)
-
- def setupSections(self):
- """Install the sections all kickstart files support. You may override
- this method in a subclass, but should avoid doing so unless you know
- what you're doing.
- """
- self._sections = {}
-
- # Install the sections all kickstart files support.
- self.registerSection(PreScriptSection(self.handler, dataObj=Script))
- self.registerSection(PostScriptSection(self.handler, dataObj=Script))
- self.registerSection(TracebackScriptSection(self.handler, dataObj=Script))
- self.registerSection(PackageSection(self.handler))
diff --git a/scripts/lib/wic/3rdparty/pykickstart/sections.py b/scripts/lib/wic/3rdparty/pykickstart/sections.py
deleted file mode 100644
index 44df856b8d..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/sections.py
+++ /dev/null
@@ -1,244 +0,0 @@
-#
-# sections.py: Kickstart file sections.
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# Copyright 2011 Red Hat, Inc.
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-"""
-This module exports the classes that define a section of a kickstart file. A
-section is a chunk of the file starting with a %tag and ending with a %end.
-Examples of sections include %packages, %pre, and %post.
-
-You may use this module to define your own custom sections which will be
-treated just the same as a predefined one by the kickstart parser. All that
-is necessary is to create a new subclass of Section and call
-parser.registerSection with an instance of your new class.
-"""
-from constants import *
-from options import KSOptionParser
-from version import *
-
-class Section(object):
- """The base class for defining kickstart sections. You are free to
- subclass this as appropriate.
-
- Class attributes:
-
- allLines -- Does this section require the parser to call handleLine
- for every line in the section, even blanks and comments?
- sectionOpen -- The string that denotes the start of this section. You
- must start your tag with a percent sign.
- timesSeen -- This attribute is for informational purposes only. It is
- incremented every time handleHeader is called to keep
- track of the number of times a section of this type is
- seen.
- """
- allLines = False
- sectionOpen = ""
- timesSeen = 0
-
- def __init__(self, handler, **kwargs):
- """Create a new Script instance. At the least, you must pass in an
- instance of a baseHandler subclass.
-
- Valid kwargs:
-
- dataObj --
- """
- self.handler = handler
-
- self.version = self.handler.version
-
- self.dataObj = kwargs.get("dataObj", None)
-
- def finalize(self):
- """This method is called when the %end tag for a section is seen. It
- is not required to be provided.
- """
- pass
-
- def handleLine(self, line):
- """This method is called for every line of a section. Take whatever
- action is appropriate. While this method is not required to be
- provided, not providing it does not make a whole lot of sense.
-
- Arguments:
-
- line -- The complete line, with any trailing newline.
- """
- pass
-
- def handleHeader(self, lineno, args):
- """This method is called when the opening tag for a section is seen.
- Not all sections will need this method, though all provided with
- kickstart include one.
-
- Arguments:
-
- args -- A list of all strings passed as arguments to the section
- opening tag.
- """
- self.timesSeen += 1
-
-class NullSection(Section):
- """This defines a section that pykickstart will recognize but do nothing
- with. If the parser runs across a %section that has no object registered,
- it will raise an error. Sometimes, you may want to simply ignore those
- sections instead. This class is useful for that purpose.
- """
- def __init__(self, *args, **kwargs):
- """Create a new NullSection instance. You must pass a sectionOpen
- parameter (including a leading '%') for the section you wish to
- ignore.
- """
- Section.__init__(self, *args, **kwargs)
- self.sectionOpen = kwargs.get("sectionOpen")
-
-class ScriptSection(Section):
- allLines = True
-
- def __init__(self, *args, **kwargs):
- Section.__init__(self, *args, **kwargs)
- self._script = {}
- self._resetScript()
-
- def _getParser(self):
- op = KSOptionParser(self.version)
- op.add_option("--erroronfail", dest="errorOnFail", action="store_true",
- default=False)
- op.add_option("--interpreter", dest="interpreter", default="/bin/sh")
- op.add_option("--log", "--logfile", dest="log")
- return op
-
- def _resetScript(self):
- self._script = {"interp": "/bin/sh", "log": None, "errorOnFail": False,
- "lineno": None, "chroot": False, "body": []}
-
- def handleLine(self, line):
- self._script["body"].append(line)
-
- def finalize(self):
- if " ".join(self._script["body"]).strip() == "":
- return
-
- kwargs = {"interp": self._script["interp"],
- "inChroot": self._script["chroot"],
- "lineno": self._script["lineno"],
- "logfile": self._script["log"],
- "errorOnFail": self._script["errorOnFail"],
- "type": self._script["type"]}
-
- s = self.dataObj (self._script["body"], **kwargs)
- self._resetScript()
-
- if self.handler:
- self.handler.scripts.append(s)
-
- def handleHeader(self, lineno, args):
- """Process the arguments to a %pre/%post/%traceback header for later
- setting on a Script instance once the end of the script is found.
- This method may be overridden in a subclass if necessary.
- """
- Section.handleHeader(self, lineno, args)
- op = self._getParser()
-
- (opts, extra) = op.parse_args(args=args[1:], lineno=lineno)
-
- self._script["interp"] = opts.interpreter
- self._script["lineno"] = lineno
- self._script["log"] = opts.log
- self._script["errorOnFail"] = opts.errorOnFail
- if hasattr(opts, "nochroot"):
- self._script["chroot"] = not opts.nochroot
-
-class PreScriptSection(ScriptSection):
- sectionOpen = "%pre"
-
- def _resetScript(self):
- ScriptSection._resetScript(self)
- self._script["type"] = KS_SCRIPT_PRE
-
-class PostScriptSection(ScriptSection):
- sectionOpen = "%post"
-
- def _getParser(self):
- op = ScriptSection._getParser(self)
- op.add_option("--nochroot", dest="nochroot", action="store_true",
- default=False)
- return op
-
- def _resetScript(self):
- ScriptSection._resetScript(self)
- self._script["chroot"] = True
- self._script["type"] = KS_SCRIPT_POST
-
-class TracebackScriptSection(ScriptSection):
- sectionOpen = "%traceback"
-
- def _resetScript(self):
- ScriptSection._resetScript(self)
- self._script["type"] = KS_SCRIPT_TRACEBACK
-
-class PackageSection(Section):
- sectionOpen = "%packages"
-
- def handleLine(self, line):
- if not self.handler:
- return
-
- (h, s, t) = line.partition('#')
- line = h.rstrip()
-
- self.handler.packages.add([line])
-
- def handleHeader(self, lineno, args):
- """Process the arguments to the %packages header and set attributes
- on the Version's Packages instance appropriate. This method may be
- overridden in a subclass if necessary.
- """
- Section.handleHeader(self, lineno, args)
- op = KSOptionParser(version=self.version)
- op.add_option("--excludedocs", dest="excludedocs", action="store_true",
- default=False)
- op.add_option("--ignoremissing", dest="ignoremissing",
- action="store_true", default=False)
- op.add_option("--nobase", dest="nobase", action="store_true",
- default=False)
- op.add_option("--ignoredeps", dest="resolveDeps", action="store_false",
- deprecated=FC4, removed=F9)
- op.add_option("--resolvedeps", dest="resolveDeps", action="store_true",
- deprecated=FC4, removed=F9)
- op.add_option("--default", dest="defaultPackages", action="store_true",
- default=False, introduced=F7)
- op.add_option("--instLangs", dest="instLangs", type="string",
- default="", introduced=F9)
-
- (opts, extra) = op.parse_args(args=args[1:], lineno=lineno)
-
- self.handler.packages.excludeDocs = opts.excludedocs
- self.handler.packages.addBase = not opts.nobase
- if opts.ignoremissing:
- self.handler.packages.handleMissing = KS_MISSING_IGNORE
- else:
- self.handler.packages.handleMissing = KS_MISSING_PROMPT
-
- if opts.defaultPackages:
- self.handler.packages.default = True
-
- if opts.instLangs:
- self.handler.packages.instLangs = opts.instLangs
diff --git a/scripts/lib/wic/3rdparty/pykickstart/version.py b/scripts/lib/wic/3rdparty/pykickstart/version.py
deleted file mode 100644
index 8a8e6aad22..0000000000
--- a/scripts/lib/wic/3rdparty/pykickstart/version.py
+++ /dev/null
@@ -1,168 +0,0 @@
-#
-# Chris Lumens <clumens@redhat.com>
-#
-# Copyright 2006, 2007, 2008, 2009, 2010 Red Hat, Inc.
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties 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
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
-# trademarks that are incorporated in the source code or documentation are not
-# subject to the GNU General Public License and may only be used or replicated
-# with the express permission of Red Hat, Inc.
-#
-"""
-Methods for working with kickstart versions.
-
-This module defines several symbolic constants that specify kickstart syntax
-versions. Each version corresponds roughly to one release of Red Hat Linux,
-Red Hat Enterprise Linux, or Fedora Core as these are where most syntax
-changes take place.
-
-This module also exports several functions:
-
- makeVersion - Given a version number, return an instance of the
- matching handler class.
-
- returnClassForVersion - Given a version number, return the matching
- handler class. This does not return an
- instance of that class, however.
-
- stringToVersion - Convert a string representation of a version number
- into the symbolic constant.
-
- versionToString - Perform the reverse mapping.
-
- versionFromFile - Read a kickstart file and determine the version of
- syntax it uses. This requires the kickstart file to
- have a version= comment in it.
-"""
-import imputil, re, sys
-
-import gettext
-_ = lambda x: gettext.ldgettext("pykickstart", x)
-
-from pykickstart.errors import KickstartVersionError
-
-# Symbolic names for internal version numbers.
-RHEL3 = 900
-FC3 = 1000
-RHEL4 = 1100
-FC4 = 2000
-FC5 = 3000
-FC6 = 4000
-RHEL5 = 4100
-F7 = 5000
-F8 = 6000
-F9 = 7000
-F10 = 8000
-F11 = 9000
-F12 = 10000
-F13 = 11000
-RHEL6 = 11100
-F14 = 12000
-F15 = 13000
-F16 = 14000
-
-# This always points at the latest version and is the default.
-DEVEL = F16
-
-# A one-to-one mapping from string representations to version numbers.
-versionMap = {
- "DEVEL": DEVEL,
- "FC3": FC3, "FC4": FC4, "FC5": FC5, "FC6": FC6, "F7": F7, "F8": F8,
- "F9": F9, "F10": F10, "F11": F11, "F12": F12, "F13": F13,
- "F14": F14, "F15": F15, "F16": F16,
- "RHEL3": RHEL3, "RHEL4": RHEL4, "RHEL5": RHEL5, "RHEL6": RHEL6
-}
-
-def stringToVersion(s):
- """Convert string into one of the provided version constants. Raises
- KickstartVersionError if string does not match anything.
- """
- # First try these short forms.
- try:
- return versionMap[s.upper()]
- except KeyError:
- pass
-
- # Now try the Fedora versions.
- m = re.match("^fedora.* (\d+)$", s, re.I)
-
- if m and m.group(1):
- if versionMap.has_key("FC" + m.group(1)):
- return versionMap["FC" + m.group(1)]
- elif versionMap.has_key("F" + m.group(1)):
- return versionMap["F" + m.group(1)]
- else:
- raise KickstartVersionError(_("Unsupported version specified: %s") % s)
-
- # Now try the RHEL versions.
- m = re.match("^red hat enterprise linux.* (\d+)([\.\d]*)$", s, re.I)
-
- if m and m.group(1):
- if versionMap.has_key("RHEL" + m.group(1)):
- return versionMap["RHEL" + m.group(1)]
- else:
- raise KickstartVersionError(_("Unsupported version specified: %s") % s)
-
- # If nothing else worked, we're out of options.
- raise KickstartVersionError(_("Unsupported version specified: %s") % s)
-
-def versionToString(version, skipDevel=False):
- """Convert version into a string representation of the version number.
- This is the reverse operation of stringToVersion. Raises
- KickstartVersionError if version does not match anything.
- """
- if not skipDevel and version == versionMap["DEVEL"]:
- return "DEVEL"
-
- for (key, val) in versionMap.iteritems():
- if key == "DEVEL":
- continue
- elif val == version:
- return key
-
- raise KickstartVersionError(_("Unsupported version specified: %s") % version)
-
-def returnClassForVersion(version=DEVEL):
- """Return the class of the syntax handler for version. version can be
- either a string or the matching constant. Raises KickstartValueError
- if version does not match anything.
- """
- try:
- version = int(version)
- module = "%s" % versionToString(version, skipDevel=True)
- except ValueError:
- module = "%s" % version
- version = stringToVersion(version)
-
- module = module.lower()
-
- try:
- import pykickstart.handlers
- sys.path.extend(pykickstart.handlers.__path__)
- found = imputil.imp.find_module(module)
- loaded = imputil.imp.load_module(module, found[0], found[1], found[2])
-
- for (k, v) in loaded.__dict__.iteritems():
- if k.lower().endswith("%shandler" % module):
- return v
- except:
- raise KickstartVersionError(_("Unsupported version specified: %s") % version)
-
-def makeVersion(version=DEVEL):
- """Return a new instance of the syntax handler for version. version can be
- either a string or the matching constant. This function is useful for
- standalone programs which just need to handle a specific version of
- kickstart syntax (as provided by a command line argument, for example)
- and need to instantiate the correct object.
- """
- cl = returnClassForVersion(version)
- return cl()
diff --git a/scripts/lib/wic/__init__.py b/scripts/lib/wic/__init__.py
index 63c1d9c846..85567934ae 100644
--- a/scripts/lib/wic/__init__.py
+++ b/scripts/lib/wic/__init__.py
@@ -1,4 +1,10 @@
-import os, sys
+#!/usr/bin/env python3
+#
+# Copyright (c) 2007 Red Hat, Inc.
+# Copyright (c) 2011 Intel, Inc.
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
-cur_path = os.path.dirname(__file__) or '.'
-sys.path.insert(0, cur_path + '/3rdparty')
+class WicError(Exception):
+ pass
diff --git a/scripts/lib/wic/__version__.py b/scripts/lib/wic/__version__.py
deleted file mode 100644
index 5452a46712..0000000000
--- a/scripts/lib/wic/__version__.py
+++ /dev/null
@@ -1 +0,0 @@
-VERSION = "2.00"
diff --git a/scripts/lib/wic/canned-wks/common.wks.inc b/scripts/lib/wic/canned-wks/common.wks.inc
new file mode 100644
index 0000000000..89880b417b
--- /dev/null
+++ b/scripts/lib/wic/canned-wks/common.wks.inc
@@ -0,0 +1,3 @@
+# This file is included into 3 canned wks files from this directory
+part /boot --source bootimg-pcbios --ondisk sda --label boot --active --align 1024
+part / --source rootfs --use-uuid --fstype=ext4 --label platform --align 1024
diff --git a/scripts/lib/wic/canned-wks/directdisk-bootloader-config.cfg b/scripts/lib/wic/canned-wks/directdisk-bootloader-config.cfg
new file mode 100644
index 0000000000..c58e74a853
--- /dev/null
+++ b/scripts/lib/wic/canned-wks/directdisk-bootloader-config.cfg
@@ -0,0 +1,27 @@
+# This is an example configuration file for syslinux.
+TIMEOUT 50
+ALLOWOPTIONS 1
+SERIAL 0 115200
+PROMPT 0
+
+UI vesamenu.c32
+menu title Select boot options
+menu tabmsg Press [Tab] to edit, [Return] to select
+
+DEFAULT Graphics console boot
+
+LABEL Graphics console boot
+KERNEL /vmlinuz
+APPEND label=boot rootwait
+
+LABEL Serial console boot
+KERNEL /vmlinuz
+APPEND label=boot rootwait console=ttyS0,115200
+
+LABEL Graphics console install
+KERNEL /vmlinuz
+APPEND label=install rootwait
+
+LABEL Serial console install
+KERNEL /vmlinuz
+APPEND label=install rootwait console=ttyS0,115200
diff --git a/scripts/lib/wic/canned-wks/directdisk-bootloader-config.wks b/scripts/lib/wic/canned-wks/directdisk-bootloader-config.wks
new file mode 100644
index 0000000000..3529e05c87
--- /dev/null
+++ b/scripts/lib/wic/canned-wks/directdisk-bootloader-config.wks
@@ -0,0 +1,8 @@
+# short-description: Create a 'pcbios' direct disk image with custom bootloader config
+# long-description: Creates a partitioned legacy BIOS disk image that the user
+# can directly dd to boot media. The bootloader configuration source is a user file.
+
+include common.wks.inc
+
+bootloader --configfile="directdisk-bootloader-config.cfg"
+
diff --git a/scripts/lib/wic/canned-wks/directdisk-gpt.wks b/scripts/lib/wic/canned-wks/directdisk-gpt.wks
index ea01cf3752..8d7d8de6ea 100644
--- a/scripts/lib/wic/canned-wks/directdisk-gpt.wks
+++ b/scripts/lib/wic/canned-wks/directdisk-gpt.wks
@@ -6,5 +6,5 @@
part /boot --source bootimg-pcbios --ondisk sda --label boot --active --align 1024
part / --source rootfs --ondisk sda --fstype=ext4 --label platform --align 1024 --use-uuid
-bootloader --ptable gpt --timeout=0 --append="rootwait rootfstype=ext4 video=vesafb vga=0x318 console=tty0"
+bootloader --ptable gpt --timeout=0 --append="rootwait rootfstype=ext4 video=vesafb vga=0x318 console=tty0 console=ttyS0,115200n8"
diff --git a/scripts/lib/wic/canned-wks/directdisk-multi-rootfs.wks b/scripts/lib/wic/canned-wks/directdisk-multi-rootfs.wks
index 8a81f8f519..f61d941d6d 100644
--- a/scripts/lib/wic/canned-wks/directdisk-multi-rootfs.wks
+++ b/scripts/lib/wic/canned-wks/directdisk-multi-rootfs.wks
@@ -19,5 +19,5 @@ part /boot --source bootimg-pcbios --ondisk sda --label boot --active --align 10
part / --source rootfs --rootfs-dir=rootfs1 --ondisk sda --fstype=ext4 --label platform --align 1024
part /rescue --source rootfs --rootfs-dir=rootfs2 --ondisk sda --fstype=ext4 --label secondary --align 1024
-bootloader --timeout=0 --append="rootwait rootfstype=ext4 video=vesafb vga=0x318 console=tty0"
+bootloader --timeout=0 --append="rootwait rootfstype=ext4 video=vesafb vga=0x318 console=tty0 console=ttyS0,115200n8"
diff --git a/scripts/lib/wic/canned-wks/directdisk.wks b/scripts/lib/wic/canned-wks/directdisk.wks
index af4c9eadaf..8c8e06b02c 100644
--- a/scripts/lib/wic/canned-wks/directdisk.wks
+++ b/scripts/lib/wic/canned-wks/directdisk.wks
@@ -2,9 +2,7 @@
# long-description: Creates a partitioned legacy BIOS disk image that the user
# can directly dd to boot media.
+include common.wks.inc
-part /boot --source bootimg-pcbios --ondisk sda --label boot --active --align 1024
-part / --source rootfs --ondisk sda --fstype=ext4 --label platform --align 1024
-
-bootloader --timeout=0 --append="rootwait rootfstype=ext4 video=vesafb vga=0x318 console=tty0"
+bootloader --timeout=0 --append="rootwait rootfstype=ext4 video=vesafb vga=0x318 console=tty0 console=ttyS0,115200n8"
diff --git a/scripts/lib/wic/canned-wks/efi-bootdisk.wks.in b/scripts/lib/wic/canned-wks/efi-bootdisk.wks.in
new file mode 100644
index 0000000000..7300e65e32
--- /dev/null
+++ b/scripts/lib/wic/canned-wks/efi-bootdisk.wks.in
@@ -0,0 +1,3 @@
+bootloader --ptable gpt
+part /boot --source rootfs --rootfs-dir=${IMAGE_ROOTFS}/boot --fstype=vfat --label boot --active --align 1024 --use-uuid --overhead-factor 1.0
+part / --source rootfs --fstype=ext4 --label root --align 1024 --exclude-path boot/
diff --git a/scripts/lib/wic/canned-wks/mkefidisk.wks b/scripts/lib/wic/canned-wks/mkefidisk.wks
index 696e94e3d7..9f534fe184 100644
--- a/scripts/lib/wic/canned-wks/mkefidisk.wks
+++ b/scripts/lib/wic/canned-wks/mkefidisk.wks
@@ -4,8 +4,8 @@
part /boot --source bootimg-efi --sourceparams="loader=grub-efi" --ondisk sda --label msdos --active --align 1024
-part / --source rootfs --ondisk sda --fstype=ext4 --label platform --align 1024
+part / --source rootfs --ondisk sda --fstype=ext4 --label platform --align 1024 --use-uuid
part swap --ondisk sda --size 44 --label swap1 --fstype=swap
-bootloader --timeout=10 --append="rootwait rootfstype=ext4 console=ttyPCH0,115200 console=tty0 vmalloc=256MB snd-hda-intel.enable_msi=0"
+bootloader --ptable gpt --timeout=5 --append="rootfstype=ext4 console=ttyS0,115200 console=tty0"
diff --git a/scripts/lib/wic/canned-wks/mkgummidisk.wks b/scripts/lib/wic/canned-wks/mkgummidisk.wks
deleted file mode 100644
index 66a22f60bd..0000000000
--- a/scripts/lib/wic/canned-wks/mkgummidisk.wks
+++ /dev/null
@@ -1,11 +0,0 @@
-# short-description: Create an EFI disk image
-# long-description: Creates a partitioned EFI disk image that the user
-# can directly dd to boot media.
-
-part /boot --source bootimg-efi --sourceparams="loader=gummiboot" --ondisk sda --label msdos --active --align 1024
-
-part / --source rootfs --ondisk sda --fstype=ext4 --label platform --align 1024
-
-part swap --ondisk sda --size 44 --label swap1 --fstype=swap
-
-bootloader --timeout=10 --append="rootwait rootfstype=ext4 console=ttyPCH0,115200 console=tty0 vmalloc=256MB snd-hda-intel.enable_msi=0"
diff --git a/scripts/lib/wic/canned-wks/mkhybridiso.wks b/scripts/lib/wic/canned-wks/mkhybridiso.wks
index 9d34e9b477..48c5ac4791 100644
--- a/scripts/lib/wic/canned-wks/mkhybridiso.wks
+++ b/scripts/lib/wic/canned-wks/mkhybridiso.wks
@@ -2,6 +2,6 @@
# long-description: Creates an EFI and legacy bootable hybrid ISO image
# which can be used on optical media as well as USB media.
-part /boot --source isoimage-isohybrid --sourceparams="loader=grub-efi,image_name=HYBRID_ISO_IMG" --ondisk cd --label HYBRIDISO --fstype=ext4
+part /boot --source isoimage-isohybrid --sourceparams="loader=grub-efi,image_name=HYBRID_ISO_IMG" --ondisk cd --label HYBRIDISO
bootloader --timeout=15 --append=""
diff --git a/scripts/lib/wic/canned-wks/qemuriscv.wks b/scripts/lib/wic/canned-wks/qemuriscv.wks
new file mode 100644
index 0000000000..12c68b7069
--- /dev/null
+++ b/scripts/lib/wic/canned-wks/qemuriscv.wks
@@ -0,0 +1,3 @@
+# short-description: Create qcow2 image for RISC-V QEMU machines
+
+part / --source rootfs --fstype=ext4 --label root --align 4096 --size 5G
diff --git a/scripts/lib/wic/canned-wks/qemux86-directdisk.wks b/scripts/lib/wic/canned-wks/qemux86-directdisk.wks
index 8fc38b54d0..22b45217f1 100644
--- a/scripts/lib/wic/canned-wks/qemux86-directdisk.wks
+++ b/scripts/lib/wic/canned-wks/qemux86-directdisk.wks
@@ -2,9 +2,7 @@
# long-description: Creates a partitioned legacy BIOS disk image that the user
# can directly use to boot a qemu machine.
+include common.wks.inc
-part /boot --source bootimg-pcbios --ondisk sda --label boot --active --align 1024
-part / --source rootfs --ondisk sda --fstype=ext4 --label platform --align 1024
-
-bootloader --timeout=0 --append="vga=0 uvesafb.mode_option=640x480-32 root=/dev/vda2 rw mem=256M ip=192.168.7.2::192.168.7.1:255.255.255.0 oprofile.timer=1 rootfstype=ext4 "
+bootloader --timeout=0 --append="rw oprofile.timer=1 rootfstype=ext4 "
diff --git a/scripts/lib/wic/canned-wks/sdimage-bootpart.wks b/scripts/lib/wic/canned-wks/sdimage-bootpart.wks
index 7ffd632f4a..63bc4dab6a 100644
--- a/scripts/lib/wic/canned-wks/sdimage-bootpart.wks
+++ b/scripts/lib/wic/canned-wks/sdimage-bootpart.wks
@@ -2,5 +2,5 @@
# long-description: Creates a partitioned SD card image. Boot files
# are located in the first vfat partition.
-part /boot --source bootimg-partition --ondisk mmcblk --fstype=vfat --label boot --active --align 4 --size 16
-part / --source rootfs --ondisk mmcblk --fstype=ext4 --label root --align 4
+part /boot --source bootimg-partition --ondisk mmcblk0 --fstype=vfat --label boot --active --align 4 --size 16
+part / --source rootfs --ondisk mmcblk0 --fstype=ext4 --label root --align 4
diff --git a/scripts/lib/wic/canned-wks/systemd-bootdisk.wks b/scripts/lib/wic/canned-wks/systemd-bootdisk.wks
new file mode 100644
index 0000000000..95d7b97a60
--- /dev/null
+++ b/scripts/lib/wic/canned-wks/systemd-bootdisk.wks
@@ -0,0 +1,11 @@
+# short-description: Create an EFI disk image with systemd-boot
+# long-description: Creates a partitioned EFI disk image that the user
+# can directly dd to boot media. The selected bootloader is systemd-boot.
+
+part /boot --source bootimg-efi --sourceparams="loader=systemd-boot" --ondisk sda --label msdos --active --align 1024 --use-uuid
+
+part / --source rootfs --ondisk sda --fstype=ext4 --label platform --align 1024 --use-uuid
+
+part swap --ondisk sda --size 44 --label swap1 --fstype=swap --use-uuid
+
+bootloader --ptable gpt --timeout=5 --append="rootwait rootfstype=ext4 console=ttyS0,115200 console=tty0"
diff --git a/scripts/lib/wic/conf.py b/scripts/lib/wic/conf.py
deleted file mode 100644
index 1d4363a526..0000000000
--- a/scripts/lib/wic/conf.py
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/env python -tt
-#
-# Copyright (c) 2011 Intel, Inc.
-#
-# This program 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; version 2 of the License
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-import os
-
-from wic import msger
-from wic import kickstart
-from wic.utils import misc
-
-
-def get_siteconf():
- wic_path = os.path.dirname(__file__)
- eos = wic_path.find('scripts') + len('scripts')
- scripts_path = wic_path[:eos]
-
- return scripts_path + "/lib/image/config/wic.conf"
-
-class ConfigMgr(object):
- DEFAULTS = {
- 'common': {
- "distro_name": "Default Distribution",
- "plugin_dir": "/usr/lib/wic/plugins"}, # TODO use prefix also?
- 'create': {
- "tmpdir": '/var/tmp/wic',
- "outdir": './wic-output',
- "release": None,
- "logfile": None,
- "name_prefix": None,
- "name_suffix": None}
- }
-
- # make the manager class as singleton
- _instance = None
- def __new__(cls, *args, **kwargs):
- if not cls._instance:
- cls._instance = super(ConfigMgr, cls).__new__(cls, *args, **kwargs)
-
- return cls._instance
-
- def __init__(self, ksconf=None, siteconf=None):
- # reset config options
- self.reset()
-
- if not siteconf:
- siteconf = get_siteconf()
-
- # initial options from siteconf
- self._siteconf = siteconf
-
- if ksconf:
- self._ksconf = ksconf
-
- def reset(self):
- self.__ksconf = None
- self.__siteconf = None
- self.create = {}
-
- # initialize the values with defaults
- for sec, vals in self.DEFAULTS.iteritems():
- setattr(self, sec, vals)
-
- def __set_ksconf(self, ksconf):
- if not os.path.isfile(ksconf):
- msger.error('Cannot find ks file: %s' % ksconf)
-
- self.__ksconf = ksconf
- self._parse_kickstart(ksconf)
- def __get_ksconf(self):
- return self.__ksconf
- _ksconf = property(__get_ksconf, __set_ksconf)
-
- def _parse_kickstart(self, ksconf=None):
- if not ksconf:
- return
-
- ksobj = kickstart.read_kickstart(ksconf)
-
- self.create['ks'] = ksobj
- self.create['name'] = os.path.splitext(os.path.basename(ksconf))[0]
-
- self.create['name'] = misc.build_name(ksconf,
- self.create['release'],
- self.create['name_prefix'],
- self.create['name_suffix'])
-
-configmgr = ConfigMgr()
diff --git a/scripts/lib/wic/config/wic.conf b/scripts/lib/wic/config/wic.conf
deleted file mode 100644
index a51bcb55eb..0000000000
--- a/scripts/lib/wic/config/wic.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-[common]
-; general settings
-distro_name = OpenEmbedded
-
-[create]
-; settings for create subcommand
diff --git a/scripts/lib/wic/creator.py b/scripts/lib/wic/creator.py
deleted file mode 100644
index 5231297282..0000000000
--- a/scripts/lib/wic/creator.py
+++ /dev/null
@@ -1,124 +0,0 @@
-#!/usr/bin/env python -tt
-#
-# Copyright (c) 2011 Intel, Inc.
-#
-# This program 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; version 2 of the License
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-import os, sys
-from optparse import OptionParser, SUPPRESS_HELP
-
-from wic import msger
-from wic.utils import errors
-from wic.conf import configmgr
-from wic.plugin import pluginmgr
-
-
-class Creator(object):
- """${name}: create an image
-
- Usage:
- ${name} SUBCOMMAND <ksfile> [OPTS]
-
- ${command_list}
- ${option_list}
- """
-
- name = 'wic create(cr)'
-
- def __init__(self, *args, **kwargs):
- self._subcmds = {}
-
- # get cmds from pluginmgr
- # mix-in do_subcmd interface
- for subcmd, klass in pluginmgr.get_plugins('imager').iteritems():
- if not hasattr(klass, 'do_create'):
- msger.warning("Unsupported subcmd: %s" % subcmd)
- continue
-
- func = getattr(klass, 'do_create')
- self._subcmds[subcmd] = func
-
- def get_optparser(self):
- optparser = OptionParser()
- optparser.add_option('-d', '--debug', action='store_true',
- dest='debug',
- help=SUPPRESS_HELP)
- optparser.add_option('-v', '--verbose', action='store_true',
- dest='verbose',
- help=SUPPRESS_HELP)
- optparser.add_option('', '--logfile', type='string', dest='logfile',
- default=None,
- help='Path of logfile')
- optparser.add_option('-c', '--config', type='string', dest='config',
- default=None,
- help='Specify config file for wic')
- optparser.add_option('-o', '--outdir', type='string', action='store',
- dest='outdir', default=None,
- help='Output directory')
- optparser.add_option('', '--tmpfs', action='store_true', dest='enabletmpfs',
- help='Setup tmpdir as tmpfs to accelerate, experimental'
- ' feature, use it if you have more than 4G memory')
- return optparser
-
- def postoptparse(self, options):
- abspath = lambda pth: os.path.abspath(os.path.expanduser(pth))
-
- if options.verbose:
- msger.set_loglevel('verbose')
- if options.debug:
- msger.set_loglevel('debug')
-
- if options.logfile:
- logfile_abs_path = abspath(options.logfile)
- if os.path.isdir(logfile_abs_path):
- raise errors.Usage("logfile's path %s should be file"
- % options.logfile)
- if not os.path.exists(os.path.dirname(logfile_abs_path)):
- os.makedirs(os.path.dirname(logfile_abs_path))
- msger.set_interactive(False)
- msger.set_logfile(logfile_abs_path)
- configmgr.create['logfile'] = options.logfile
-
- if options.config:
- configmgr.reset()
- configmgr._siteconf = options.config
-
- if options.outdir is not None:
- configmgr.create['outdir'] = abspath(options.outdir)
-
- cdir = 'outdir'
- if os.path.exists(configmgr.create[cdir]) \
- and not os.path.isdir(configmgr.create[cdir]):
- msger.error('Invalid directory specified: %s' \
- % configmgr.create[cdir])
-
- if options.enabletmpfs:
- configmgr.create['enabletmpfs'] = options.enabletmpfs
-
- def main(self, argv=None):
- if argv is None:
- argv = sys.argv
- else:
- argv = argv[:] # don't modify caller's list
-
- pname = argv[0]
- if pname not in self._subcmds:
- msger.error('Unknown plugin: %s' % pname)
-
- optparser = self.get_optparser()
- options, args = optparser.parse_args(argv)
-
- self.postoptparse(options)
-
- return self._subcmds[pname](options, *args[1:])
diff --git a/scripts/lib/wic/engine.py b/scripts/lib/wic/engine.py
index 76b93e82f2..018815b966 100644
--- a/scripts/lib/wic/engine.py
+++ b/scripts/lib/wic/engine.py
@@ -1,21 +1,7 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# Copyright (c) 2013, Intel Corporation.
-# All rights reserved.
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# SPDX-License-Identifier: GPL-2.0-only
#
# DESCRIPTION
@@ -28,14 +14,22 @@
# Tom Zanussi <tom.zanussi (at] linux.intel.com>
#
+import logging
import os
-import sys
+import tempfile
+import json
+import subprocess
+import re
+
+from collections import namedtuple, OrderedDict
+from distutils.spawn import find_executable
-from wic import msger, creator
-from wic.utils import misc
-from wic.plugin import pluginmgr
-from wic.utils.oe import misc
+from wic import WicError
+from wic.filemap import sparse_copy
+from wic.pluginbase import PluginMgr
+from wic.misc import get_bitbake_var, exec_cmd
+logger = logging.getLogger('wic')
def verify_build_env():
"""
@@ -44,23 +38,25 @@ def verify_build_env():
Returns True if it is, false otherwise
"""
if not os.environ.get("BUILDDIR"):
- print "BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)"
- sys.exit(1)
+ raise WicError("BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)")
return True
CANNED_IMAGE_DIR = "lib/wic/canned-wks" # relative to scripts
SCRIPTS_CANNED_IMAGE_DIR = "scripts/" + CANNED_IMAGE_DIR
+WIC_DIR = "wic"
def build_canned_image_list(path):
- layers_path = misc.get_bitbake_var("BBLAYERS")
+ layers_path = get_bitbake_var("BBLAYERS")
canned_wks_layer_dirs = []
if layers_path is not None:
for layer_path in layers_path.split():
- cpath = os.path.join(layer_path, SCRIPTS_CANNED_IMAGE_DIR)
- canned_wks_layer_dirs.append(cpath)
+ for wks_path in (WIC_DIR, SCRIPTS_CANNED_IMAGE_DIR):
+ cpath = os.path.join(layer_path, wks_path)
+ if os.path.isdir(cpath):
+ canned_wks_layer_dirs.append(cpath)
cpath = os.path.join(path, CANNED_IMAGE_DIR)
canned_wks_layer_dirs.append(cpath)
@@ -80,7 +76,8 @@ def find_canned_image(scripts_path, wks_file):
for fname in files:
if fname.endswith("~") or fname.endswith("#"):
continue
- if fname.endswith(".wks") and wks_file + ".wks" == fname:
+ if ((fname.endswith(".wks") and wks_file + ".wks" == fname) or \
+ (fname.endswith(".wks.in") and wks_file + ".wks.in" == fname)):
fullpath = os.path.join(canned_wks_dir, fname)
return fullpath
return None
@@ -97,7 +94,7 @@ def list_canned_images(scripts_path):
for fname in files:
if fname.endswith("~") or fname.endswith("#"):
continue
- if fname.endswith(".wks"):
+ if fname.endswith(".wks") or fname.endswith(".wks.in"):
fullpath = os.path.join(canned_wks_dir, fname)
with open(fullpath) as wks:
for line in wks:
@@ -106,8 +103,8 @@ def list_canned_images(scripts_path):
if idx != -1:
desc = line[idx + len("short-description:"):].strip()
break
- basename = os.path.splitext(fname)[0]
- print " %s\t\t%s" % (basename.ljust(30), desc)
+ basename = fname.split('.')[0]
+ print(" %s\t\t%s" % (basename.ljust(30), desc))
def list_canned_image_help(scripts_path, fullpath):
@@ -120,15 +117,15 @@ def list_canned_image_help(scripts_path, fullpath):
if not found:
idx = line.find("long-description:")
if idx != -1:
- print
- print line[idx + len("long-description:"):].strip()
+ print()
+ print(line[idx + len("long-description:"):].strip())
found = True
continue
if not line.strip():
break
idx = line.find("#")
if idx != -1:
- print line[idx + len("#:"):].rstrip()
+ print(line[idx + len("#:"):].rstrip())
else:
break
@@ -137,25 +134,24 @@ def list_source_plugins():
"""
List the available source plugins i.e. plugins available for --source.
"""
- plugins = pluginmgr.get_source_plugins()
+ plugins = PluginMgr.get_plugins('source')
for plugin in plugins:
- print " %s" % plugin
+ print(" %s" % plugin)
def wic_create(wks_file, rootfs_dir, bootimg_dir, kernel_dir,
- native_sysroot, scripts_path, image_output_dir,
- compressor, debug):
- """Create image
+ native_sysroot, options):
+ """
+ Create image
wks_file - user-defined OE kickstart file
rootfs_dir - absolute path to the build's /rootfs dir
bootimg_dir - absolute path to the build's boot artifacts directory
kernel_dir - absolute path to the build's kernel directory
native_sysroot - absolute path to the build's native sysroots dir
- scripts_path - absolute path to /scripts dir
image_output_dir - dirname to create for image
- compressor - compressor utility to compress the image
+ options - wic command line options (debug, bmap, etc)
Normally, the values for the build artifacts values are determined
by 'wic -e' from the output of the 'bitbake -e' command given an
@@ -178,43 +174,455 @@ def wic_create(wks_file, rootfs_dir, bootimg_dir, kernel_dir,
try:
oe_builddir = os.environ["BUILDDIR"]
except KeyError:
- print "BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)"
- sys.exit(1)
+ raise WicError("BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)")
+
+ if not os.path.exists(options.outdir):
+ os.makedirs(options.outdir)
- if debug:
- msger.set_loglevel('debug')
+ pname = options.imager
+ plugin_class = PluginMgr.get_plugins('imager').get(pname)
+ if not plugin_class:
+ raise WicError('Unknown plugin: %s' % pname)
- crobj = creator.Creator()
+ plugin = plugin_class(wks_file, rootfs_dir, bootimg_dir, kernel_dir,
+ native_sysroot, oe_builddir, options)
- crobj.main(["direct", native_sysroot, kernel_dir, bootimg_dir, rootfs_dir,
- wks_file, image_output_dir, oe_builddir, compressor or ""])
+ plugin.do_create()
- print "\nThe image(s) were created using OE kickstart file:\n %s" % wks_file
+ logger.info("The image(s) were created using OE kickstart file:\n %s", wks_file)
def wic_list(args, scripts_path):
"""
Print the list of images or source plugins.
"""
- if len(args) < 1:
+ if args.list_type is None:
return False
- if args == ["images"]:
+ if args.list_type == "images":
+
list_canned_images(scripts_path)
return True
- elif args == ["source-plugins"]:
+ elif args.list_type == "source-plugins":
list_source_plugins()
return True
- elif len(args) == 2 and args[1] == "help":
- wks_file = args[0]
+ elif len(args.help_for) == 1 and args.help_for[0] == 'help':
+ wks_file = args.list_type
fullpath = find_canned_image(scripts_path, wks_file)
if not fullpath:
- print "No image named %s found, exiting. "\
- "(Use 'wic list images' to list available images, or "\
- "specify a fully-qualified OE kickstart (.wks) "\
- "filename)\n" % wks_file
- sys.exit(1)
+ raise WicError("No image named %s found, exiting. "
+ "(Use 'wic list images' to list available images, "
+ "or specify a fully-qualified OE kickstart (.wks) "
+ "filename)" % wks_file)
+
list_canned_image_help(scripts_path, fullpath)
return True
return False
+
+
+class Disk:
+ def __init__(self, imagepath, native_sysroot, fstypes=('fat', 'ext')):
+ self.imagepath = imagepath
+ self.native_sysroot = native_sysroot
+ self.fstypes = fstypes
+ self._partitions = None
+ self._partimages = {}
+ self._lsector_size = None
+ self._psector_size = None
+ self._ptable_format = None
+
+ # find parted
+ # read paths from $PATH environment variable
+ # if it fails, use hardcoded paths
+ pathlist = "/bin:/usr/bin:/usr/sbin:/sbin/"
+ try:
+ self.paths = os.environ['PATH'] + ":" + pathlist
+ except KeyError:
+ self.paths = pathlist
+
+ if native_sysroot:
+ for path in pathlist.split(':'):
+ self.paths = "%s%s:%s" % (native_sysroot, path, self.paths)
+
+ self.parted = find_executable("parted", self.paths)
+ if not self.parted:
+ raise WicError("Can't find executable parted")
+
+ self.partitions = self.get_partitions()
+
+ def __del__(self):
+ for path in self._partimages.values():
+ os.unlink(path)
+
+ def get_partitions(self):
+ if self._partitions is None:
+ self._partitions = OrderedDict()
+ out = exec_cmd("%s -sm %s unit B print" % (self.parted, self.imagepath))
+ parttype = namedtuple("Part", "pnum start end size fstype")
+ splitted = out.splitlines()
+ # skip over possible errors in exec_cmd output
+ try:
+ idx =splitted.index("BYT;")
+ except ValueError:
+ raise WicError("Error getting partition information from %s" % (self.parted))
+ lsector_size, psector_size, self._ptable_format = splitted[idx + 1].split(":")[3:6]
+ self._lsector_size = int(lsector_size)
+ self._psector_size = int(psector_size)
+ for line in splitted[idx + 2:]:
+ pnum, start, end, size, fstype = line.split(':')[:5]
+ partition = parttype(int(pnum), int(start[:-1]), int(end[:-1]),
+ int(size[:-1]), fstype)
+ self._partitions[pnum] = partition
+
+ return self._partitions
+
+ def __getattr__(self, name):
+ """Get path to the executable in a lazy way."""
+ if name in ("mdir", "mcopy", "mdel", "mdeltree", "sfdisk", "e2fsck",
+ "resize2fs", "mkswap", "mkdosfs", "debugfs","blkid"):
+ aname = "_%s" % name
+ if aname not in self.__dict__:
+ setattr(self, aname, find_executable(name, self.paths))
+ if aname not in self.__dict__ or self.__dict__[aname] is None:
+ raise WicError("Can't find executable '{}'".format(name))
+ return self.__dict__[aname]
+ return self.__dict__[name]
+
+ def _get_part_image(self, pnum):
+ if pnum not in self.partitions:
+ raise WicError("Partition %s is not in the image" % pnum)
+ part = self.partitions[pnum]
+ # check if fstype is supported
+ for fstype in self.fstypes:
+ if part.fstype.startswith(fstype):
+ break
+ else:
+ raise WicError("Not supported fstype: {}".format(part.fstype))
+ if pnum not in self._partimages:
+ tmpf = tempfile.NamedTemporaryFile(prefix="wic-part")
+ dst_fname = tmpf.name
+ tmpf.close()
+ sparse_copy(self.imagepath, dst_fname, skip=part.start, length=part.size)
+ self._partimages[pnum] = dst_fname
+
+ return self._partimages[pnum]
+
+ def _put_part_image(self, pnum):
+ """Put partition image into partitioned image."""
+ sparse_copy(self._partimages[pnum], self.imagepath,
+ seek=self.partitions[pnum].start)
+
+ def dir(self, pnum, path):
+ if pnum not in self.partitions:
+ raise WicError("Partition %s is not in the image" % pnum)
+
+ if self.partitions[pnum].fstype.startswith('ext'):
+ return exec_cmd("{} {} -R 'ls -l {}'".format(self.debugfs,
+ self._get_part_image(pnum),
+ path), as_shell=True)
+ else: # fat
+ return exec_cmd("{} -i {} ::{}".format(self.mdir,
+ self._get_part_image(pnum),
+ path))
+
+ def copy(self, src, dest):
+ """Copy partition image into wic image."""
+ pnum = dest.part if isinstance(src, str) else src.part
+
+ if self.partitions[pnum].fstype.startswith('ext'):
+ if isinstance(src, str):
+ cmd = "printf 'cd {}\nwrite {} {}\n' | {} -w {}".\
+ format(os.path.dirname(dest.path), src, os.path.basename(src),
+ self.debugfs, self._get_part_image(pnum))
+ else: # copy from wic
+ # run both dump and rdump to support both files and directory
+ cmd = "printf 'cd {}\ndump /{} {}\nrdump /{} {}\n' | {} {}".\
+ format(os.path.dirname(src.path), src.path,
+ dest, src.path, dest, self.debugfs,
+ self._get_part_image(pnum))
+ else: # fat
+ if isinstance(src, str):
+ cmd = "{} -i {} -snop {} ::{}".format(self.mcopy,
+ self._get_part_image(pnum),
+ src, dest.path)
+ else:
+ cmd = "{} -i {} -snop ::{} {}".format(self.mcopy,
+ self._get_part_image(pnum),
+ src.path, dest)
+
+ exec_cmd(cmd, as_shell=True)
+ self._put_part_image(pnum)
+
+ def remove_ext(self, pnum, path, recursive):
+ """
+ Remove files/dirs and their contents from the partition.
+ This only applies to ext* partition.
+ """
+ abs_path = re.sub('\/\/+', '/', path)
+ cmd = "{} {} -wR 'rm \"{}\"'".format(self.debugfs,
+ self._get_part_image(pnum),
+ abs_path)
+ out = exec_cmd(cmd , as_shell=True)
+ for line in out.splitlines():
+ if line.startswith("rm:"):
+ if "file is a directory" in line:
+ if recursive:
+ # loop through content and delete them one by one if
+ # flaged with -r
+ subdirs = iter(self.dir(pnum, abs_path).splitlines())
+ next(subdirs)
+ for subdir in subdirs:
+ dir = subdir.split(':')[1].split(" ", 1)[1]
+ if not dir == "." and not dir == "..":
+ self.remove_ext(pnum, "%s/%s" % (abs_path, dir), recursive)
+
+ rmdir_out = exec_cmd("{} {} -wR 'rmdir \"{}\"'".format(self.debugfs,
+ self._get_part_image(pnum),
+ abs_path.rstrip('/'))
+ , as_shell=True)
+
+ for rmdir_line in rmdir_out.splitlines():
+ if "directory not empty" in rmdir_line:
+ raise WicError("Could not complete operation: \n%s \n"
+ "use -r to remove non-empty directory" % rmdir_line)
+ if rmdir_line.startswith("rmdir:"):
+ raise WicError("Could not complete operation: \n%s "
+ "\n%s" % (str(line), rmdir_line))
+
+ else:
+ raise WicError("Could not complete operation: \n%s "
+ "\nUnable to remove %s" % (str(line), abs_path))
+
+ def remove(self, pnum, path, recursive):
+ """Remove files/dirs from the partition."""
+ partimg = self._get_part_image(pnum)
+ if self.partitions[pnum].fstype.startswith('ext'):
+ self.remove_ext(pnum, path, recursive)
+
+ else: # fat
+ cmd = "{} -i {} ::{}".format(self.mdel, partimg, path)
+ try:
+ exec_cmd(cmd)
+ except WicError as err:
+ if "not found" in str(err) or "non empty" in str(err):
+ # mdel outputs 'File ... not found' or 'directory .. non empty"
+ # try to use mdeltree as path could be a directory
+ cmd = "{} -i {} ::{}".format(self.mdeltree,
+ partimg, path)
+ exec_cmd(cmd)
+ else:
+ raise err
+ self._put_part_image(pnum)
+
+ def write(self, target, expand):
+ """Write disk image to the media or file."""
+ def write_sfdisk_script(outf, parts):
+ for key, val in parts['partitiontable'].items():
+ if key in ("partitions", "device", "firstlba", "lastlba"):
+ continue
+ if key == "id":
+ key = "label-id"
+ outf.write("{}: {}\n".format(key, val))
+ outf.write("\n")
+ for part in parts['partitiontable']['partitions']:
+ line = ''
+ for name in ('attrs', 'name', 'size', 'type', 'uuid'):
+ if name == 'size' and part['type'] == 'f':
+ # don't write size for extended partition
+ continue
+ val = part.get(name)
+ if val:
+ line += '{}={}, '.format(name, val)
+ if line:
+ line = line[:-2] # strip ', '
+ if part.get('bootable'):
+ line += ' ,bootable'
+ outf.write("{}\n".format(line))
+ outf.flush()
+
+ def read_ptable(path):
+ out = exec_cmd("{} -J {}".format(self.sfdisk, path))
+ return json.loads(out)
+
+ def write_ptable(parts, target):
+ with tempfile.NamedTemporaryFile(prefix="wic-sfdisk-", mode='w') as outf:
+ write_sfdisk_script(outf, parts)
+ cmd = "{} --no-reread {} < {} ".format(self.sfdisk, target, outf.name)
+ exec_cmd(cmd, as_shell=True)
+
+ if expand is None:
+ sparse_copy(self.imagepath, target)
+ else:
+ # copy first sectors that may contain bootloader
+ sparse_copy(self.imagepath, target, length=2048 * self._lsector_size)
+
+ # copy source partition table to the target
+ parts = read_ptable(self.imagepath)
+ write_ptable(parts, target)
+
+ # get size of unpartitioned space
+ free = None
+ for line in exec_cmd("{} -F {}".format(self.sfdisk, target)).splitlines():
+ if line.startswith("Unpartitioned space ") and line.endswith("sectors"):
+ free = int(line.split()[-2])
+ # Align free space to a 2048 sector boundary. YOCTO #12840.
+ free = free - (free % 2048)
+ if free is None:
+ raise WicError("Can't get size of unpartitioned space")
+
+ # calculate expanded partitions sizes
+ sizes = {}
+ num_auto_resize = 0
+ for num, part in enumerate(parts['partitiontable']['partitions'], 1):
+ if num in expand:
+ if expand[num] != 0: # don't resize partition if size is set to 0
+ sectors = expand[num] // self._lsector_size
+ free -= sectors - part['size']
+ part['size'] = sectors
+ sizes[num] = sectors
+ elif part['type'] != 'f':
+ sizes[num] = -1
+ num_auto_resize += 1
+
+ for num, part in enumerate(parts['partitiontable']['partitions'], 1):
+ if sizes.get(num) == -1:
+ part['size'] += free // num_auto_resize
+
+ # write resized partition table to the target
+ write_ptable(parts, target)
+
+ # read resized partition table
+ parts = read_ptable(target)
+
+ # copy partitions content
+ for num, part in enumerate(parts['partitiontable']['partitions'], 1):
+ pnum = str(num)
+ fstype = self.partitions[pnum].fstype
+
+ # copy unchanged partition
+ if part['size'] == self.partitions[pnum].size // self._lsector_size:
+ logger.info("copying unchanged partition {}".format(pnum))
+ sparse_copy(self._get_part_image(pnum), target, seek=part['start'] * self._lsector_size)
+ continue
+
+ # resize or re-create partitions
+ if fstype.startswith('ext') or fstype.startswith('fat') or \
+ fstype.startswith('linux-swap'):
+
+ partfname = None
+ with tempfile.NamedTemporaryFile(prefix="wic-part{}-".format(pnum)) as partf:
+ partfname = partf.name
+
+ if fstype.startswith('ext'):
+ logger.info("resizing ext partition {}".format(pnum))
+ partimg = self._get_part_image(pnum)
+ sparse_copy(partimg, partfname)
+ exec_cmd("{} -pf {}".format(self.e2fsck, partfname))
+ exec_cmd("{} {} {}s".format(\
+ self.resize2fs, partfname, part['size']))
+ elif fstype.startswith('fat'):
+ logger.info("copying content of the fat partition {}".format(pnum))
+ with tempfile.TemporaryDirectory(prefix='wic-fatdir-') as tmpdir:
+ # copy content to the temporary directory
+ cmd = "{} -snompi {} :: {}".format(self.mcopy,
+ self._get_part_image(pnum),
+ tmpdir)
+ exec_cmd(cmd)
+ # create new msdos partition
+ label = part.get("name")
+ label_str = "-n {}".format(label) if label else ''
+
+ cmd = "{} {} -C {} {}".format(self.mkdosfs, label_str, partfname,
+ part['size'])
+ exec_cmd(cmd)
+ # copy content from the temporary directory to the new partition
+ cmd = "{} -snompi {} {}/* ::".format(self.mcopy, partfname, tmpdir)
+ exec_cmd(cmd, as_shell=True)
+ elif fstype.startswith('linux-swap'):
+ logger.info("creating swap partition {}".format(pnum))
+ label = part.get("name")
+ label_str = "-L {}".format(label) if label else ''
+ out = exec_cmd("{} --probe {}".format(self.blkid, self._get_part_image(pnum)))
+ uuid = out[out.index("UUID=\"")+6:out.index("UUID=\"")+42]
+ uuid_str = "-U {}".format(uuid) if uuid else ''
+ with open(partfname, 'w') as sparse:
+ os.ftruncate(sparse.fileno(), part['size'] * self._lsector_size)
+ exec_cmd("{} {} {} {}".format(self.mkswap, label_str, uuid_str, partfname))
+ sparse_copy(partfname, target, seek=part['start'] * self._lsector_size)
+ os.unlink(partfname)
+ elif part['type'] != 'f':
+ logger.warning("skipping partition {}: unsupported fstype {}".format(pnum, fstype))
+
+def wic_ls(args, native_sysroot):
+ """List contents of partitioned image or vfat partition."""
+ disk = Disk(args.path.image, native_sysroot)
+ if not args.path.part:
+ if disk.partitions:
+ print('Num Start End Size Fstype')
+ for part in disk.partitions.values():
+ print("{:2d} {:12d} {:12d} {:12d} {}".format(\
+ part.pnum, part.start, part.end,
+ part.size, part.fstype))
+ else:
+ path = args.path.path or '/'
+ print(disk.dir(args.path.part, path))
+
+def wic_cp(args, native_sysroot):
+ """
+ Copy file or directory to/from the vfat/ext partition of
+ partitioned image.
+ """
+ if isinstance(args.dest, str):
+ disk = Disk(args.src.image, native_sysroot)
+ else:
+ disk = Disk(args.dest.image, native_sysroot)
+ disk.copy(args.src, args.dest)
+
+
+def wic_rm(args, native_sysroot):
+ """
+ Remove files or directories from the vfat partition of
+ partitioned image.
+ """
+ disk = Disk(args.path.image, native_sysroot)
+ disk.remove(args.path.part, args.path.path, args.recursive_delete)
+
+def wic_write(args, native_sysroot):
+ """
+ Write image to a target device.
+ """
+ disk = Disk(args.image, native_sysroot, ('fat', 'ext', 'linux-swap'))
+ disk.write(args.target, args.expand)
+
+def find_canned(scripts_path, file_name):
+ """
+ Find a file either by its path or by name in the canned files dir.
+
+ Return None if not found
+ """
+ if os.path.exists(file_name):
+ return file_name
+
+ layers_canned_wks_dir = build_canned_image_list(scripts_path)
+ for canned_wks_dir in layers_canned_wks_dir:
+ for root, dirs, files in os.walk(canned_wks_dir):
+ for fname in files:
+ if fname == file_name:
+ fullpath = os.path.join(canned_wks_dir, fname)
+ return fullpath
+
+def get_custom_config(boot_file):
+ """
+ Get the custom configuration to be used for the bootloader.
+
+ Return None if the file can't be found.
+ """
+ # Get the scripts path of poky
+ scripts_path = os.path.abspath("%s/../.." % os.path.dirname(__file__))
+
+ cfg_file = find_canned(scripts_path, boot_file)
+ if cfg_file:
+ with open(cfg_file, "r") as f:
+ config = f.read()
+ return config
diff --git a/scripts/lib/wic/filemap.py b/scripts/lib/wic/filemap.py
new file mode 100644
index 0000000000..4d9da28172
--- /dev/null
+++ b/scripts/lib/wic/filemap.py
@@ -0,0 +1,576 @@
+#
+# Copyright (c) 2012 Intel, Inc.
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+"""
+This module implements python implements a way to get file block. Two methods
+are supported - the FIEMAP ioctl and the 'SEEK_HOLE / SEEK_DATA' features of
+the file seek syscall. The former is implemented by the 'FilemapFiemap' class,
+the latter is implemented by the 'FilemapSeek' class. Both classes provide the
+same API. The 'filemap' function automatically selects which class can be used
+and returns an instance of the class.
+"""
+
+# Disable the following pylint recommendations:
+# * Too many instance attributes (R0902)
+# pylint: disable=R0902
+
+import errno
+import os
+import struct
+import array
+import fcntl
+import tempfile
+import logging
+
+def get_block_size(file_obj):
+ """
+ Returns block size for file object 'file_obj'. Errors are indicated by the
+ 'IOError' exception.
+ """
+ # Get the block size of the host file-system for the image file by calling
+ # the FIGETBSZ ioctl (number 2).
+ try:
+ binary_data = fcntl.ioctl(file_obj, 2, struct.pack('I', 0))
+ bsize = struct.unpack('I', binary_data)[0]
+ except OSError:
+ bsize = None
+
+ # If ioctl causes OSError or give bsize to zero failback to os.fstat
+ if not bsize:
+ import os
+ stat = os.fstat(file_obj.fileno())
+ if hasattr(stat, 'st_blksize'):
+ bsize = stat.st_blksize
+ else:
+ raise IOError("Unable to determine block size")
+ return bsize
+
+class ErrorNotSupp(Exception):
+ """
+ An exception of this type is raised when the 'FIEMAP' or 'SEEK_HOLE' feature
+ is not supported either by the kernel or the file-system.
+ """
+ pass
+
+class Error(Exception):
+ """A class for all the other exceptions raised by this module."""
+ pass
+
+
+class _FilemapBase(object):
+ """
+ This is a base class for a couple of other classes in this module. This
+ class simply performs the common parts of the initialization process: opens
+ the image file, gets its size, etc. The 'log' parameter is the logger object
+ to use for printing messages.
+ """
+
+ def __init__(self, image, log=None):
+ """
+ Initialize a class instance. The 'image' argument is full path to the
+ file or file object to operate on.
+ """
+
+ self._log = log
+ if self._log is None:
+ self._log = logging.getLogger(__name__)
+
+ self._f_image_needs_close = False
+
+ if hasattr(image, "fileno"):
+ self._f_image = image
+ self._image_path = image.name
+ else:
+ self._image_path = image
+ self._open_image_file()
+
+ try:
+ self.image_size = os.fstat(self._f_image.fileno()).st_size
+ except IOError as err:
+ raise Error("cannot get information about file '%s': %s"
+ % (self._f_image.name, err))
+
+ try:
+ self.block_size = get_block_size(self._f_image)
+ except IOError as err:
+ raise Error("cannot get block size for '%s': %s"
+ % (self._image_path, err))
+
+ self.blocks_cnt = self.image_size + self.block_size - 1
+ self.blocks_cnt //= self.block_size
+
+ try:
+ self._f_image.flush()
+ except IOError as err:
+ raise Error("cannot flush image file '%s': %s"
+ % (self._image_path, err))
+
+ try:
+ os.fsync(self._f_image.fileno()),
+ except OSError as err:
+ raise Error("cannot synchronize image file '%s': %s "
+ % (self._image_path, err.strerror))
+
+ self._log.debug("opened image \"%s\"" % self._image_path)
+ self._log.debug("block size %d, blocks count %d, image size %d"
+ % (self.block_size, self.blocks_cnt, self.image_size))
+
+ def __del__(self):
+ """The class destructor which just closes the image file."""
+ if self._f_image_needs_close:
+ self._f_image.close()
+
+ def _open_image_file(self):
+ """Open the image file."""
+ try:
+ self._f_image = open(self._image_path, 'rb')
+ except IOError as err:
+ raise Error("cannot open image file '%s': %s"
+ % (self._image_path, err))
+
+ self._f_image_needs_close = True
+
+ def block_is_mapped(self, block): # pylint: disable=W0613,R0201
+ """
+ This method has has to be implemented by child classes. It returns
+ 'True' if block number 'block' of the image file is mapped and 'False'
+ otherwise.
+ """
+
+ raise Error("the method is not implemented")
+
+ def get_mapped_ranges(self, start, count): # pylint: disable=W0613,R0201
+ """
+ This method has has to be implemented by child classes. This is a
+ generator which yields ranges of mapped blocks in the file. The ranges
+ are tuples of 2 elements: [first, last], where 'first' is the first
+ mapped block and 'last' is the last mapped block.
+
+ The ranges are yielded for the area of the file of size 'count' blocks,
+ starting from block 'start'.
+ """
+
+ raise Error("the method is not implemented")
+
+
+# The 'SEEK_HOLE' and 'SEEK_DATA' options of the file seek system call
+_SEEK_DATA = 3
+_SEEK_HOLE = 4
+
+def _lseek(file_obj, offset, whence):
+ """This is a helper function which invokes 'os.lseek' for file object
+ 'file_obj' and with specified 'offset' and 'whence'. The 'whence'
+ argument is supposed to be either '_SEEK_DATA' or '_SEEK_HOLE'. When
+ there is no more data or hole starting from 'offset', this function
+ returns '-1'. Otherwise the data or hole position is returned."""
+
+ try:
+ return os.lseek(file_obj.fileno(), offset, whence)
+ except OSError as err:
+ # The 'lseek' system call returns the ENXIO if there is no data or
+ # hole starting from the specified offset.
+ if err.errno == errno.ENXIO:
+ return -1
+ elif err.errno == errno.EINVAL:
+ raise ErrorNotSupp("the kernel or file-system does not support "
+ "\"SEEK_HOLE\" and \"SEEK_DATA\"")
+ else:
+ raise
+
+class FilemapSeek(_FilemapBase):
+ """
+ This class uses the 'SEEK_HOLE' and 'SEEK_DATA' to find file block mapping.
+ Unfortunately, the current implementation requires the caller to have write
+ access to the image file.
+ """
+
+ def __init__(self, image, log=None):
+ """Refer the '_FilemapBase' class for the documentation."""
+
+ # Call the base class constructor first
+ _FilemapBase.__init__(self, image, log)
+ self._log.debug("FilemapSeek: initializing")
+
+ self._probe_seek_hole()
+
+ def _probe_seek_hole(self):
+ """
+ Check whether the system implements 'SEEK_HOLE' and 'SEEK_DATA'.
+ Unfortunately, there seems to be no clean way for detecting this,
+ because often the system just fakes them by just assuming that all
+ files are fully mapped, so 'SEEK_HOLE' always returns EOF and
+ 'SEEK_DATA' always returns the requested offset.
+
+ I could not invent a better way of detecting the fake 'SEEK_HOLE'
+ implementation than just to create a temporary file in the same
+ directory where the image file resides. It would be nice to change this
+ to something better.
+ """
+
+ directory = os.path.dirname(self._image_path)
+
+ try:
+ tmp_obj = tempfile.TemporaryFile("w+", dir=directory)
+ except IOError as err:
+ raise ErrorNotSupp("cannot create a temporary in \"%s\": %s" \
+ % (directory, err))
+
+ try:
+ os.ftruncate(tmp_obj.fileno(), self.block_size)
+ except OSError as err:
+ raise ErrorNotSupp("cannot truncate temporary file in \"%s\": %s"
+ % (directory, err))
+
+ offs = _lseek(tmp_obj, 0, _SEEK_HOLE)
+ if offs != 0:
+ # We are dealing with the stub 'SEEK_HOLE' implementation which
+ # always returns EOF.
+ self._log.debug("lseek(0, SEEK_HOLE) returned %d" % offs)
+ raise ErrorNotSupp("the file-system does not support "
+ "\"SEEK_HOLE\" and \"SEEK_DATA\" but only "
+ "provides a stub implementation")
+
+ tmp_obj.close()
+
+ def block_is_mapped(self, block):
+ """Refer the '_FilemapBase' class for the documentation."""
+ offs = _lseek(self._f_image, block * self.block_size, _SEEK_DATA)
+ if offs == -1:
+ result = False
+ else:
+ result = (offs // self.block_size == block)
+
+ self._log.debug("FilemapSeek: block_is_mapped(%d) returns %s"
+ % (block, result))
+ return result
+
+ def _get_ranges(self, start, count, whence1, whence2):
+ """
+ This function implements 'get_mapped_ranges()' depending
+ on what is passed in the 'whence1' and 'whence2' arguments.
+ """
+
+ assert whence1 != whence2
+ end = start * self.block_size
+ limit = end + count * self.block_size
+
+ while True:
+ start = _lseek(self._f_image, end, whence1)
+ if start == -1 or start >= limit or start == self.image_size:
+ break
+
+ end = _lseek(self._f_image, start, whence2)
+ if end == -1 or end == self.image_size:
+ end = self.blocks_cnt * self.block_size
+ if end > limit:
+ end = limit
+
+ start_blk = start // self.block_size
+ end_blk = end // self.block_size - 1
+ self._log.debug("FilemapSeek: yielding range (%d, %d)"
+ % (start_blk, end_blk))
+ yield (start_blk, end_blk)
+
+ def get_mapped_ranges(self, start, count):
+ """Refer the '_FilemapBase' class for the documentation."""
+ self._log.debug("FilemapSeek: get_mapped_ranges(%d, %d(%d))"
+ % (start, count, start + count - 1))
+ return self._get_ranges(start, count, _SEEK_DATA, _SEEK_HOLE)
+
+
+# Below goes the FIEMAP ioctl implementation, which is not very readable
+# because it deals with the rather complex FIEMAP ioctl. To understand the
+# code, you need to know the FIEMAP interface, which is documented in the
+# "Documentation/filesystems/fiemap.txt" file in the Linux kernel sources.
+
+# Format string for 'struct fiemap'
+_FIEMAP_FORMAT = "=QQLLLL"
+# sizeof(struct fiemap)
+_FIEMAP_SIZE = struct.calcsize(_FIEMAP_FORMAT)
+# Format string for 'struct fiemap_extent'
+_FIEMAP_EXTENT_FORMAT = "=QQQQQLLLL"
+# sizeof(struct fiemap_extent)
+_FIEMAP_EXTENT_SIZE = struct.calcsize(_FIEMAP_EXTENT_FORMAT)
+# The FIEMAP ioctl number
+_FIEMAP_IOCTL = 0xC020660B
+# This FIEMAP ioctl flag which instructs the kernel to sync the file before
+# reading the block map
+_FIEMAP_FLAG_SYNC = 0x00000001
+# Size of the buffer for 'struct fiemap_extent' elements which will be used
+# when invoking the FIEMAP ioctl. The larger is the buffer, the less times the
+# FIEMAP ioctl will be invoked.
+_FIEMAP_BUFFER_SIZE = 256 * 1024
+
+class FilemapFiemap(_FilemapBase):
+ """
+ This class provides API to the FIEMAP ioctl. Namely, it allows to iterate
+ over all mapped blocks and over all holes.
+
+ This class synchronizes the image file every time it invokes the FIEMAP
+ ioctl in order to work-around early FIEMAP implementation kernel bugs.
+ """
+
+ def __init__(self, image, log=None):
+ """
+ Initialize a class instance. The 'image' argument is full the file
+ object to operate on.
+ """
+
+ # Call the base class constructor first
+ _FilemapBase.__init__(self, image, log)
+ self._log.debug("FilemapFiemap: initializing")
+
+ self._buf_size = _FIEMAP_BUFFER_SIZE
+
+ # Calculate how many 'struct fiemap_extent' elements fit the buffer
+ self._buf_size -= _FIEMAP_SIZE
+ self._fiemap_extent_cnt = self._buf_size // _FIEMAP_EXTENT_SIZE
+ assert self._fiemap_extent_cnt > 0
+ self._buf_size = self._fiemap_extent_cnt * _FIEMAP_EXTENT_SIZE
+ self._buf_size += _FIEMAP_SIZE
+
+ # Allocate a mutable buffer for the FIEMAP ioctl
+ self._buf = array.array('B', [0] * self._buf_size)
+
+ # Check if the FIEMAP ioctl is supported
+ self.block_is_mapped(0)
+
+ def _invoke_fiemap(self, block, count):
+ """
+ Invoke the FIEMAP ioctl for 'count' blocks of the file starting from
+ block number 'block'.
+
+ The full result of the operation is stored in 'self._buf' on exit.
+ Returns the unpacked 'struct fiemap' data structure in form of a python
+ list (just like 'struct.upack()').
+ """
+
+ if self.blocks_cnt != 0 and (block < 0 or block >= self.blocks_cnt):
+ raise Error("bad block number %d, should be within [0, %d]"
+ % (block, self.blocks_cnt))
+
+ # Initialize the 'struct fiemap' part of the buffer. We use the
+ # '_FIEMAP_FLAG_SYNC' flag in order to make sure the file is
+ # synchronized. The reason for this is that early FIEMAP
+ # implementations had many bugs related to cached dirty data, and
+ # synchronizing the file is a necessary work-around.
+ struct.pack_into(_FIEMAP_FORMAT, self._buf, 0, block * self.block_size,
+ count * self.block_size, _FIEMAP_FLAG_SYNC, 0,
+ self._fiemap_extent_cnt, 0)
+
+ try:
+ fcntl.ioctl(self._f_image, _FIEMAP_IOCTL, self._buf, 1)
+ except IOError as err:
+ # Note, the FIEMAP ioctl is supported by the Linux kernel starting
+ # from version 2.6.28 (year 2008).
+ if err.errno == errno.EOPNOTSUPP:
+ errstr = "FilemapFiemap: the FIEMAP ioctl is not supported " \
+ "by the file-system"
+ self._log.debug(errstr)
+ raise ErrorNotSupp(errstr)
+ if err.errno == errno.ENOTTY:
+ errstr = "FilemapFiemap: the FIEMAP ioctl is not supported " \
+ "by the kernel"
+ self._log.debug(errstr)
+ raise ErrorNotSupp(errstr)
+ raise Error("the FIEMAP ioctl failed for '%s': %s"
+ % (self._image_path, err))
+
+ return struct.unpack(_FIEMAP_FORMAT, self._buf[:_FIEMAP_SIZE])
+
+ def block_is_mapped(self, block):
+ """Refer the '_FilemapBase' class for the documentation."""
+ struct_fiemap = self._invoke_fiemap(block, 1)
+
+ # The 3rd element of 'struct_fiemap' is the 'fm_mapped_extents' field.
+ # If it contains zero, the block is not mapped, otherwise it is
+ # mapped.
+ result = bool(struct_fiemap[3])
+ self._log.debug("FilemapFiemap: block_is_mapped(%d) returns %s"
+ % (block, result))
+ return result
+
+ def _unpack_fiemap_extent(self, index):
+ """
+ Unpack a 'struct fiemap_extent' structure object number 'index' from
+ the internal 'self._buf' buffer.
+ """
+
+ offset = _FIEMAP_SIZE + _FIEMAP_EXTENT_SIZE * index
+ return struct.unpack(_FIEMAP_EXTENT_FORMAT,
+ self._buf[offset : offset + _FIEMAP_EXTENT_SIZE])
+
+ def _do_get_mapped_ranges(self, start, count):
+ """
+ Implements most the functionality for the 'get_mapped_ranges()'
+ generator: invokes the FIEMAP ioctl, walks through the mapped extents
+ and yields mapped block ranges. However, the ranges may be consecutive
+ (e.g., (1, 100), (100, 200)) and 'get_mapped_ranges()' simply merges
+ them.
+ """
+
+ block = start
+ while block < start + count:
+ struct_fiemap = self._invoke_fiemap(block, count)
+
+ mapped_extents = struct_fiemap[3]
+ if mapped_extents == 0:
+ # No more mapped blocks
+ return
+
+ extent = 0
+ while extent < mapped_extents:
+ fiemap_extent = self._unpack_fiemap_extent(extent)
+
+ # Start of the extent
+ extent_start = fiemap_extent[0]
+ # Starting block number of the extent
+ extent_block = extent_start // self.block_size
+ # Length of the extent
+ extent_len = fiemap_extent[2]
+ # Count of blocks in the extent
+ extent_count = extent_len // self.block_size
+
+ # Extent length and offset have to be block-aligned
+ assert extent_start % self.block_size == 0
+ assert extent_len % self.block_size == 0
+
+ if extent_block > start + count - 1:
+ return
+
+ first = max(extent_block, block)
+ last = min(extent_block + extent_count, start + count) - 1
+ yield (first, last)
+
+ extent += 1
+
+ block = extent_block + extent_count
+
+ def get_mapped_ranges(self, start, count):
+ """Refer the '_FilemapBase' class for the documentation."""
+ self._log.debug("FilemapFiemap: get_mapped_ranges(%d, %d(%d))"
+ % (start, count, start + count - 1))
+ iterator = self._do_get_mapped_ranges(start, count)
+ first_prev, last_prev = next(iterator)
+
+ for first, last in iterator:
+ if last_prev == first - 1:
+ last_prev = last
+ else:
+ self._log.debug("FilemapFiemap: yielding range (%d, %d)"
+ % (first_prev, last_prev))
+ yield (first_prev, last_prev)
+ first_prev, last_prev = first, last
+
+ self._log.debug("FilemapFiemap: yielding range (%d, %d)"
+ % (first_prev, last_prev))
+ yield (first_prev, last_prev)
+
+class FilemapNobmap(_FilemapBase):
+ """
+ This class is used when both the 'SEEK_DATA/HOLE' and FIEMAP are not
+ supported by the filesystem or kernel.
+ """
+
+ def __init__(self, image, log=None):
+ """Refer the '_FilemapBase' class for the documentation."""
+
+ # Call the base class constructor first
+ _FilemapBase.__init__(self, image, log)
+ self._log.debug("FilemapNobmap: initializing")
+
+ def block_is_mapped(self, block):
+ """Refer the '_FilemapBase' class for the documentation."""
+ return True
+
+ def get_mapped_ranges(self, start, count):
+ """Refer the '_FilemapBase' class for the documentation."""
+ self._log.debug("FilemapNobmap: get_mapped_ranges(%d, %d(%d))"
+ % (start, count, start + count - 1))
+ yield (start, start + count -1)
+
+def filemap(image, log=None):
+ """
+ Create and return an instance of a Filemap class - 'FilemapFiemap' or
+ 'FilemapSeek', depending on what the system we run on supports. If the
+ FIEMAP ioctl is supported, an instance of the 'FilemapFiemap' class is
+ returned. Otherwise, if 'SEEK_HOLE' is supported an instance of the
+ 'FilemapSeek' class is returned. If none of these are supported, the
+ function generates an 'Error' type exception.
+ """
+
+ try:
+ return FilemapFiemap(image, log)
+ except ErrorNotSupp:
+ try:
+ return FilemapSeek(image, log)
+ except ErrorNotSupp:
+ return FilemapNobmap(image, log)
+
+def sparse_copy(src_fname, dst_fname, skip=0, seek=0,
+ length=0, api=None):
+ """
+ Efficiently copy sparse file to or into another file.
+
+ src_fname: path to source file
+ dst_fname: path to destination file
+ skip: skip N bytes at thestart of src
+ seek: seek N bytes from the start of dst
+ length: read N bytes from src and write them to dst
+ api: FilemapFiemap or FilemapSeek object
+ """
+ if not api:
+ api = filemap
+ fmap = api(src_fname)
+ try:
+ dst_file = open(dst_fname, 'r+b')
+ except IOError:
+ dst_file = open(dst_fname, 'wb')
+ if length:
+ dst_size = length + seek
+ else:
+ dst_size = os.path.getsize(src_fname) + seek - skip
+ dst_file.truncate(dst_size)
+
+ written = 0
+ for first, last in fmap.get_mapped_ranges(0, fmap.blocks_cnt):
+ start = first * fmap.block_size
+ end = (last + 1) * fmap.block_size
+
+ if skip >= end:
+ continue
+
+ if start < skip < end:
+ start = skip
+
+ fmap._f_image.seek(start, os.SEEK_SET)
+
+ written += start - skip - written
+ if length and written >= length:
+ dst_file.seek(seek + length, os.SEEK_SET)
+ dst_file.close()
+ return
+
+ dst_file.seek(seek + start - skip, os.SEEK_SET)
+
+ chunk_size = 1024 * 1024
+ to_read = end - start
+ read = 0
+
+ while read < to_read:
+ if read + chunk_size > to_read:
+ chunk_size = to_read - read
+ size = chunk_size
+ if length and written + size > length:
+ size = length - written
+ chunk = fmap._f_image.read(size)
+ dst_file.write(chunk)
+ read += size
+ written += size
+ if written == length:
+ dst_file.close()
+ return
+ dst_file.close()
diff --git a/scripts/lib/wic/help.py b/scripts/lib/wic/help.py
index 9a778b69da..991907d3f5 100644
--- a/scripts/lib/wic/help.py
+++ b/scripts/lib/wic/help.py
@@ -1,21 +1,6 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
-#
# Copyright (c) 2013, Intel Corporation.
-# All rights reserved.
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# SPDX-License-Identifier: GPL-2.0-only
#
# DESCRIPTION
# This module implements some basic help invocation functions along
@@ -28,10 +13,12 @@
import subprocess
import logging
-from wic.plugin import pluginmgr, PLUGIN_TYPES
+from wic.pluginbase import PluginMgr, PLUGIN_TYPES
+
+logger = logging.getLogger('wic')
def subcommand_error(args):
- logging.info("invalid subcommand %s" % args[0])
+ logger.info("invalid subcommand %s", args[0])
def display_help(subcommand, subcommands):
@@ -45,7 +32,7 @@ def display_help(subcommand, subcommands):
if callable(hlp):
hlp = hlp()
pager = subprocess.Popen('less', stdin=subprocess.PIPE)
- pager.communicate(hlp)
+ pager.communicate(hlp.encode('utf-8'))
return True
@@ -54,8 +41,8 @@ def wic_help(args, usage_str, subcommands):
"""
Subcommand help dispatcher.
"""
- if len(args) == 1 or not display_help(args[1], subcommands):
- print usage_str
+ if args.help_topic == None or not display_help(args.help_topic, subcommands):
+ print(usage_str)
def get_wic_plugins_help():
@@ -66,7 +53,7 @@ def get_wic_plugins_help():
result = wic_plugins_help
for plugin_type in PLUGIN_TYPES:
result += '\n\n%s PLUGINS\n\n' % plugin_type.upper()
- for name, plugin in pluginmgr.get_plugins(plugin_type).iteritems():
+ for name, plugin in PluginMgr.get_plugins(plugin_type).items():
result += "\n %s plugin:\n" % name
if plugin.__doc__:
result += plugin.__doc__
@@ -80,19 +67,20 @@ def invoke_subcommand(args, parser, main_command_usage, subcommands):
Dispatch to subcommand handler borrowed from combo-layer.
Should use argparse, but has to work in 2.6.
"""
- if not args:
- logging.error("No subcommand specified, exiting")
+ if not args.command:
+ logger.error("No subcommand specified, exiting")
parser.print_help()
return 1
- elif args[0] == "help":
+ elif args.command == "help":
wic_help(args, main_command_usage, subcommands)
- elif args[0] not in subcommands:
- logging.error("Unsupported subcommand %s, exiting\n" % (args[0]))
+ elif args.command not in subcommands:
+ logger.error("Unsupported subcommand %s, exiting\n", args.command)
parser.print_help()
return 1
else:
- usage = subcommands.get(args[0], subcommand_error)[1]
- subcommands.get(args[0], subcommand_error)[0](args[1:], usage)
+ subcmd = subcommands.get(args.command, subcommand_error)
+ usage = subcmd[1]
+ subcmd[0](args, usage)
##
@@ -128,10 +116,10 @@ wic_create_usage = """
Create a new OpenEmbedded image
usage: wic create <wks file or image name> [-o <DIRNAME> | --outdir <DIRNAME>]
- [-i <JSON PROPERTY FILE> | --infile <JSON PROPERTY_FILE>]
[-e | --image-name] [-s, --skip-build-check] [-D, --debug]
[-r, --rootfs-dir] [-b, --bootimg-dir]
[-k, --kernel-dir] [-n, --native-sysroot] [-f, --build-rootfs]
+ [-c, --compress-with] [-m, --bmap]
This command creates an OpenEmbedded image based on the 'OE kickstart
commands' found in the <wks file>.
@@ -152,7 +140,7 @@ SYNOPSIS
[-e | --image-name] [-s, --skip-build-check] [-D, --debug]
[-r, --rootfs-dir] [-b, --bootimg-dir]
[-k, --kernel-dir] [-n, --native-sysroot] [-f, --build-rootfs]
- [-c, --compress-with]
+ [-c, --compress-with] [-m, --bmap] [--no-fstab-update]
DESCRIPTION
This command creates an OpenEmbedded image based on the 'OE
@@ -221,6 +209,14 @@ DESCRIPTION
The -c option is used to specify compressor utility to compress
an image. gzip, bzip2 and xz compressors are supported.
+
+ The -m option is used to produce .bmap file for the image. This file
+ can be used to flash image using bmaptool utility.
+
+ The --no-fstab-update option is used to doesn't change fstab file. When
+ using this option the final fstab file will be same that in rootfs and
+ wic doesn't update file, e.g adding a new mount point. User can control
+ the fstab file content in base-files recipe.
"""
wic_list_usage = """
@@ -278,6 +274,243 @@ DESCRIPTION
details.
"""
+wic_ls_usage = """
+
+ List content of a partitioned image
+
+ usage: wic ls <image>[:<partition>[<path>]] [--native-sysroot <path>]
+
+ This command outputs either list of image partitions or directory contents
+ of vfat and ext* partitions.
+
+ See 'wic help ls' for more detailed instructions.
+
+"""
+
+wic_ls_help = """
+
+NAME
+ wic ls - List contents of partitioned image or partition
+
+SYNOPSIS
+ wic ls <image>
+ wic ls <image>:<vfat or ext* partition>
+ wic ls <image>:<vfat or ext* partition><path>
+ wic ls <image>:<vfat or ext* partition><path> --native-sysroot <path>
+
+DESCRIPTION
+ This command lists either partitions of the image or directory contents
+ of vfat or ext* partitions.
+
+ The first form it lists partitions of the image.
+ For example:
+ $ wic ls tmp/deploy/images/qemux86-64/core-image-minimal-qemux86-64.wic
+ Num Start End Size Fstype
+ 1 1048576 24438783 23390208 fat16
+ 2 25165824 50315263 25149440 ext4
+
+ Second and third form list directory content of the partition:
+ $ wic ls tmp/deploy/images/qemux86-64/core-image-minimal-qemux86-64.wic:1
+ Volume in drive : is boot
+ Volume Serial Number is 2DF2-5F02
+ Directory for ::/
+
+ efi <DIR> 2017-05-11 10:54
+ startup nsh 26 2017-05-11 10:54
+ vmlinuz 6922288 2017-05-11 10:54
+ 3 files 6 922 314 bytes
+ 15 818 752 bytes free
+
+
+ $ wic ls tmp/deploy/images/qemux86-64/core-image-minimal-qemux86-64.wic:1/EFI/boot/
+ Volume in drive : is boot
+ Volume Serial Number is 2DF2-5F02
+ Directory for ::/EFI/boot
+
+ . <DIR> 2017-05-11 10:54
+ .. <DIR> 2017-05-11 10:54
+ grub cfg 679 2017-05-11 10:54
+ bootx64 efi 571392 2017-05-11 10:54
+ 4 files 572 071 bytes
+ 15 818 752 bytes free
+
+ The -n option is used to specify the path to the native sysroot
+ containing the tools(parted and mtools) to use.
+
+"""
+
+wic_cp_usage = """
+
+ Copy files and directories to/from the vfat or ext* partition
+
+ usage: wic cp <src> <dest> [--native-sysroot <path>]
+
+ source/destination image in format <image>:<partition>[<path>]
+
+ This command copies files or directories either
+ - from local to vfat or ext* partitions of partitioned image
+ - from vfat or ext* partitions of partitioned image to local
+
+ See 'wic help cp' for more detailed instructions.
+
+"""
+
+wic_cp_help = """
+
+NAME
+ wic cp - copy files and directories to/from the vfat or ext* partitions
+
+SYNOPSIS
+ wic cp <src> <dest>:<partition>
+ wic cp <src>:<partition> <dest>
+ wic cp <src> <dest-image>:<partition><path>
+ wic cp <src> <dest-image>:<partition><path> --native-sysroot <path>
+
+DESCRIPTION
+ This command copies files or directories either
+ - from local to vfat or ext* partitions of partitioned image
+ - from vfat or ext* partitions of partitioned image to local
+
+ The first form of it copies file or directory to the root directory of
+ the partition:
+ $ wic cp test.wks tmp/deploy/images/qemux86-64/core-image-minimal-qemux86-64.wic:1
+ $ wic ls tmp/deploy/images/qemux86-64/core-image-minimal-qemux86-64.wic:1
+ Volume in drive : is boot
+ Volume Serial Number is DB4C-FD4C
+ Directory for ::/
+
+ efi <DIR> 2017-05-24 18:15
+ loader <DIR> 2017-05-24 18:15
+ startup nsh 26 2017-05-24 18:15
+ vmlinuz 6926384 2017-05-24 18:15
+ test wks 628 2017-05-24 21:22
+ 5 files 6 927 038 bytes
+ 15 677 440 bytes free
+
+ The second form of the command copies file or directory to the specified directory
+ on the partition:
+ $ wic cp test tmp/deploy/images/qemux86-64/core-image-minimal-qemux86-64.wic:1/efi/
+ $ wic ls tmp/deploy/images/qemux86-64/core-image-minimal-qemux86-64.wic:1/efi/
+ Volume in drive : is boot
+ Volume Serial Number is DB4C-FD4C
+ Directory for ::/efi
+
+ . <DIR> 2017-05-24 18:15
+ .. <DIR> 2017-05-24 18:15
+ boot <DIR> 2017-05-24 18:15
+ test <DIR> 2017-05-24 21:27
+ 4 files 0 bytes
+ 15 675 392 bytes free
+
+ The third form of the command copies file or directory from the specified directory
+ on the partition to local:
+ $ wic cp tmp/deploy/images/qemux86-64/core-image-minimal-qemux86-64.wic:1/vmlinuz test
+
+ The -n option is used to specify the path to the native sysroot
+ containing the tools(parted and mtools) to use.
+"""
+
+wic_rm_usage = """
+
+ Remove files or directories from the vfat or ext* partitions
+
+ usage: wic rm <image>:<partition><path> [--native-sysroot <path>]
+
+ This command removes files or directories from the vfat or ext* partitions of
+ the partitioned image.
+
+ See 'wic help rm' for more detailed instructions.
+
+"""
+
+wic_rm_help = """
+
+NAME
+ wic rm - remove files or directories from the vfat or ext* partitions
+
+SYNOPSIS
+ wic rm <src> <image>:<partition><path>
+ wic rm <src> <image>:<partition><path> --native-sysroot <path>
+ wic rm -r <image>:<partition><path>
+
+DESCRIPTION
+ This command removes files or directories from the vfat or ext* partition of the
+ partitioned image:
+
+ $ wic ls ./tmp/deploy/images/qemux86-64/core-image-minimal-qemux86-64.wic:1
+ Volume in drive : is boot
+ Volume Serial Number is 11D0-DE21
+ Directory for ::/
+
+ libcom32 c32 186500 2017-06-02 15:15
+ libutil c32 24148 2017-06-02 15:15
+ syslinux cfg 209 2017-06-02 15:15
+ vesamenu c32 27104 2017-06-02 15:15
+ vmlinuz 6926384 2017-06-02 15:15
+ 5 files 7 164 345 bytes
+ 16 582 656 bytes free
+
+ $ wic rm ./tmp/deploy/images/qemux86-64/core-image-minimal-qemux86-64.wic:1/libutil.c32
+
+ $ wic ls ./tmp/deploy/images/qemux86-64/core-image-minimal-qemux86-64.wic:1
+ Volume in drive : is boot
+ Volume Serial Number is 11D0-DE21
+ Directory for ::/
+
+ libcom32 c32 186500 2017-06-02 15:15
+ syslinux cfg 209 2017-06-02 15:15
+ vesamenu c32 27104 2017-06-02 15:15
+ vmlinuz 6926384 2017-06-02 15:15
+ 4 files 7 140 197 bytes
+ 16 607 232 bytes free
+
+ The -n option is used to specify the path to the native sysroot
+ containing the tools(parted and mtools) to use.
+
+ The -r option is used to remove directories and their contents
+ recursively,this only applies to ext* partition.
+"""
+
+wic_write_usage = """
+
+ Write image to a device
+
+ usage: wic write <image> <target device> [--expand [rules]] [--native-sysroot <path>]
+
+ This command writes partitioned image to a target device (USB stick, SD card etc).
+
+ See 'wic help write' for more detailed instructions.
+
+"""
+
+wic_write_help = """
+
+NAME
+ wic write - write an image to a device
+
+SYNOPSIS
+ wic write <image> <target>
+ wic write <image> <target> --expand auto
+ wic write <image> <target> --expand 1:100M,2:300M
+ wic write <image> <target> --native-sysroot <path>
+
+DESCRIPTION
+ This command writes an image to a target device (USB stick, SD card etc)
+
+ $ wic write ./tmp/deploy/images/qemux86-64/core-image-minimal-qemux86-64.wic /dev/sdb
+
+ The --expand option is used to resize image partitions.
+ --expand auto expands partitions to occupy all free space available on the target device.
+ It's also possible to specify expansion rules in a format
+ <partition>:<size>[,<partition>:<size>...] for one or more partitions.
+ Specifying size 0 will keep partition unmodified.
+ Note: Resizing boot partition can result in non-bootable image for non-EFI images. It is
+ recommended to use size 0 for boot partition to keep image bootable.
+
+ The --native-sysroot option is used to specify the path to the native sysroot
+ containing the tools(parted, resize2fs) to use.
+"""
+
wic_plugins_help = """
NAME
@@ -303,7 +536,8 @@ DESCRIPTION
Source plugins can also be implemented and added by external
layers - any plugins found in a scripts/lib/wic/plugins/source/
- directory in an external layer will also be made available.
+ or lib/wic/plugins/source/ directory in an external layer will
+ also be made available.
When the wic implementation needs to invoke a partition-specific
implementation, it looks for the plugin that has the same name as
@@ -341,6 +575,10 @@ DESCRIPTION
partition. In other words, it 'prepares' the final partition
image which will be incorporated into the disk image.
+ do_post_partition()
+ Called after the partition is created. It is useful to add post
+ operations e.g. signing the partition.
+
do_configure_partition()
Called before do_prepare_partition(), typically used to
create custom configuration files for a partition, for
@@ -368,12 +606,7 @@ DESCRIPTION
This scheme is extensible - adding more hooks is a simple matter
of adding more plugin methods to SourcePlugin and derived classes.
- The code that then needs to call the plugin methods uses
- plugin.get_source_plugin_methods() to find the method(s) needed by
- the call; this is done by filling up a dict with keys containing
- the method names of interest - on success, these will be filled in
- with the actual methods. Please see the implementation for
- examples and details.
+ Please see the implementation for details.
"""
wic_overview_help = """
@@ -404,7 +637,7 @@ DESCRIPTION
oe-core: directdisk.bbclass and mkefidisk.sh. The difference
between wic and those examples is that with wic the functionality
of those scripts is implemented by a general-purpose partitioning
- 'language' based on Redhat kickstart syntax).
+ 'language' based on Red Hat kickstart syntax).
The initial motivation and design considerations that lead to the
current tool are described exhaustively in Yocto Bug #3847
@@ -617,7 +850,7 @@ DESCRIPTION
This command creates a partition on the system and uses the
following syntax:
- part <mountpoint>
+ part [<mountpoint>]
The <mountpoint> is where the partition will be mounted and
must take of one of the following forms:
@@ -626,6 +859,19 @@ DESCRIPTION
swap: The partition will be used as swap space.
+ If a <mountpoint> is not specified the partition will be created
+ but will not be mounted.
+
+ Partitions with a <mountpoint> specified will be automatically mounted.
+ This is achieved by wic adding entries to the fstab during image
+ generation. In order for a valid fstab to be generated one of the
+ --ondrive, --ondisk, --use-uuid or --use-label partition options must
+ be used for each partition that specifies a mountpoint. Note that with
+ --use-{uuid,label} and non-root <mountpoint>, including swap, the mount
+ program must understand the PARTUUID or LABEL syntax. This currently
+ excludes the busybox versions of these applications.
+
+
The following are supported 'part' options:
--size: The minimum partition size. Specify an integer value
@@ -633,6 +879,12 @@ DESCRIPTION
not specified, the size is in MB.
You do not need this option if you use --source.
+ --fixed-size: Exact partition size. Value format is the same
+ as for --size option. This option cannot be
+ specified along with --size. If partition data
+ is larger than --fixed-size and error will be
+ raised when assembling disk image.
+
--source: This option is a wic-specific option that names the
source of the data that will populate the
partition. The most common value for this option
@@ -671,11 +923,14 @@ DESCRIPTION
apply to partitions created using '--source rootfs' (see
--source above). Valid values are:
+ vfat
+ msdos
ext2
ext3
ext4
btrfs
squashfs
+ erofs
swap
--fsoptions: Specifies a free-form string of options to be
@@ -690,6 +945,14 @@ DESCRIPTION
label is already in use by another filesystem,
a new label is created for the partition.
+ --use-label: This option is specific to wic. It makes wic to use the
+ label in /etc/fstab to specify a partition. If the
+ --use-label and --use-uuid are used at the same time,
+ we prefer the uuid because it is less likely to cause
+ name confliction. We don't support using this parameter
+ on the root partition since it requires an initramfs to
+ parse this value and we do not currently support that.
+
--active: Marks the partition as active.
--align (in KBytes): This option is specific to wic and says
@@ -702,17 +965,50 @@ DESCRIPTION
partition table. It may be useful for
bootloaders.
+ --exclude-path: This option is specific to wic. It excludes the given
+ relative path from the resulting image. If the path
+ ends with a slash, only the content of the directory
+ is omitted, not the directory itself. This option only
+ has an effect with the rootfs source plugin.
+
+ --include-path: This option is specific to wic. It adds the contents
+ of the given path or a rootfs to the resulting image.
+ The option contains two fields, the origin and the
+ destination. When the origin is a rootfs, it follows
+ the same logic as the rootfs-dir argument and the
+ permissions and owners are kept. When the origin is a
+ path, it is relative to the directory in which wic is
+ running not the rootfs itself so use of an absolute
+ path is recommended, and the owner and group is set to
+ root:root. If no destination is given it is
+ automatically set to the root of the rootfs. This
+ option only has an effect with the rootfs source
+ plugin.
+
+ --change-directory: This option is specific to wic. It changes to the
+ given directory before copying the files. This
+ option is useful when we want to split a rootfs in
+ multiple partitions and we want to keep the right
+ permissions and usernames in all the partitions.
+
+ --no-fstab-update: This option is specific to wic. It does not update the
+ '/etc/fstab' stock file for the given partition.
+
--extra-space: This option is specific to wic. It adds extra
space after the space filled by the content
of the partition. The final size can go
beyond the size specified by --size.
- By default, 10MB.
+ By default, 10MB. This option cannot be used
+ with --fixed-size option.
--overhead-factor: This option is specific to wic. The
size of the partition is multiplied by
this factor. It has to be greater than or
- equal to 1.
- The default value is 1.3.
+ equal to 1. The default value is 1.3.
+ This option cannot be used with --fixed-size
+ option.
+
+ --part-name: This option is specific to wic. It specifies name for GPT partitions.
--part-type: This option is specific to wic. It specifies partition
type GUID for GPT partitions.
@@ -728,6 +1024,21 @@ DESCRIPTION
in bootloader configuration before running wic. In this case .wks file can
be generated or modified to set preconfigured parition UUID using this option.
+ --fsuuid: This option is specific to wic. It specifies filesystem UUID.
+ It's useful if preconfigured filesystem UUID is added to kernel command line
+ in bootloader configuration before running wic. In this case .wks file can
+ be generated or modified to set preconfigured filesystem UUID using this option.
+
+ --system-id: This option is specific to wic. It specifies partition system id. It's useful
+ for the harware that requires non-default partition system ids. The parameter
+ in one byte long hex number either with 0x prefix or without it.
+
+ --mkfs-extraopts: This option specifies extra options to pass to mkfs utility.
+ NOTE, that wic uses default options for some filesystems, for example
+ '-S 512' for mkfs.fat or '-F -i 8192' for mkfs.ext. Those options will
+ not take effect when --mkfs-extraopts is used. This should be taken into
+ account when using --mkfs-extraopts.
+
* bootloader
This command allows the user to specify various bootloader
@@ -740,8 +1051,92 @@ DESCRIPTION
bootloader command-line - for example, the syslinux
APPEND or grub kernel command line.
+ --configfile: Specifies a user defined configuration file for
+ the bootloader. This file must be located in the
+ canned-wks folder or could be the full path to the
+ file. Using this option will override any other
+ bootloader option.
+
Note that bootloader functionality and boot partitions are
implemented by the various --source plugins that implement
bootloader functionality; the bootloader command essentially
provides a means of modifying bootloader configuration.
+
+ * include
+
+ This command allows the user to include the content of .wks file
+ into original .wks file.
+
+ Command uses the following syntax:
+
+ include <file>
+
+ The <file> is either path to the file or its name. If name is
+ specified wic will try to find file in the directories with canned
+ .wks files.
+
+"""
+
+wic_help_help = """
+NAME
+ wic help - display a help topic
+
+DESCRIPTION
+ Specify a help topic to display it. Topics are shown above.
+"""
+
+
+wic_help = """
+Creates a customized OpenEmbedded image.
+
+Usage: wic [--version]
+ wic help [COMMAND or TOPIC]
+ wic COMMAND [ARGS]
+
+ usage 1: Returns the current version of Wic
+ usage 2: Returns detailed help for a COMMAND or TOPIC
+ usage 3: Executes COMMAND
+
+
+COMMAND:
+
+ list - List available canned images and source plugins
+ ls - List contents of partitioned image or partition
+ rm - Remove files or directories from the vfat or ext* partitions
+ help - Show help for a wic COMMAND or TOPIC
+ write - Write an image to a device
+ cp - Copy files and directories to the vfat or ext* partitions
+ create - Create a new OpenEmbedded image
+
+
+TOPIC:
+ overview - Presents an overall overview of Wic
+ plugins - Presents an overview and API for Wic plugins
+ kickstart - Presents a Wic kicstart file reference
+
+
+Examples:
+
+ $ wic --version
+
+ Returns the current version of Wic
+
+
+ $ wic help cp
+
+ Returns the SYNOPSIS and DESCRIPTION for the Wic "cp" command.
+
+
+ $ wic list images
+
+ Returns the list of canned images (i.e. *.wks files located in
+ the /scripts/lib/wic/canned-wks directory.
+
+
+ $ wic create mkefidisk -e core-image-minimal
+
+ Creates an EFI disk image from artifacts used in a previous
+ core-image-minimal build in standard BitBake locations
+ (e.g. Cooked Mode).
+
"""
diff --git a/scripts/lib/wic/imager/__init__.py b/scripts/lib/wic/imager/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
--- a/scripts/lib/wic/imager/__init__.py
+++ /dev/null
diff --git a/scripts/lib/wic/imager/baseimager.py b/scripts/lib/wic/imager/baseimager.py
deleted file mode 100644
index acbe948584..0000000000
--- a/scripts/lib/wic/imager/baseimager.py
+++ /dev/null
@@ -1,192 +0,0 @@
-#!/usr/bin/env python -tt
-#
-# Copyright (c) 2007 Red Hat Inc.
-# Copyright (c) 2009, 2010, 2011 Intel, Inc.
-#
-# This program 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; version 2 of the License
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-from __future__ import with_statement
-import os
-import tempfile
-import shutil
-
-from wic import msger
-from wic.utils.errors import CreatorError
-from wic.utils import runner
-
-class BaseImageCreator(object):
- """Base class for image creation.
-
- BaseImageCreator is the simplest creator class available; it will
- create a system image according to the supplied kickstart file.
-
- e.g.
-
- import wic.imgcreate as imgcreate
- ks = imgcreate.read_kickstart("foo.ks")
- imgcreate.ImageCreator(ks, "foo").create()
- """
-
- def __del__(self):
- self.cleanup()
-
- def __init__(self, createopts=None):
- """Initialize an ImageCreator instance.
-
- ks -- a pykickstart.KickstartParser instance; this instance will be
- used to drive the install by e.g. providing the list of packages
- to be installed, the system configuration and %post scripts
-
- name -- a name for the image; used for e.g. image filenames or
- filesystem labels
- """
-
- self.__builddir = None
-
- self.ks = None
- self.name = "target"
- self.tmpdir = "/var/tmp/wic"
- self.workdir = "/var/tmp/wic/build"
-
- # setup tmpfs tmpdir when enabletmpfs is True
- self.enabletmpfs = False
-
- if createopts:
- # Mapping table for variables that have different names.
- optmap = {"outdir" : "destdir",
- }
-
- # update setting from createopts
- for key in createopts.keys():
- if key in optmap:
- option = optmap[key]
- else:
- option = key
- setattr(self, option, createopts[key])
-
- self.destdir = os.path.abspath(os.path.expanduser(self.destdir))
-
- self._dep_checks = ["ls", "bash", "cp", "echo"]
-
- # Output image file names
- self.outimage = []
-
- # No ks provided when called by convertor, so skip the dependency check
- if self.ks:
- # If we have btrfs partition we need to check necessary tools
- for part in self.ks.handler.partition.partitions:
- if part.fstype and part.fstype == "btrfs":
- self._dep_checks.append("mkfs.btrfs")
- break
-
- # make sure the specified tmpdir and cachedir exist
- if not os.path.exists(self.tmpdir):
- os.makedirs(self.tmpdir)
-
-
- #
- # Hooks for subclasses
- #
- def _create(self):
- """Create partitions for the disk image(s)
-
- This is the hook where subclasses may create the partitions
- that will be assembled into disk image(s).
-
- There is no default implementation.
- """
- pass
-
- def _cleanup(self):
- """Undo anything performed in _create().
-
- This is the hook where subclasses must undo anything which was
- done in _create().
-
- There is no default implementation.
-
- """
- pass
-
- #
- # Actual implementation
- #
- def __ensure_builddir(self):
- if not self.__builddir is None:
- return
-
- try:
- self.workdir = os.path.join(self.tmpdir, "build")
- if not os.path.exists(self.workdir):
- os.makedirs(self.workdir)
- self.__builddir = tempfile.mkdtemp(dir=self.workdir,
- prefix="imgcreate-")
- except OSError as err:
- raise CreatorError("Failed create build directory in %s: %s" %
- (self.tmpdir, err))
-
- def __setup_tmpdir(self):
- if not self.enabletmpfs:
- return
-
- runner.show('mount -t tmpfs -o size=4G tmpfs %s' % self.workdir)
-
- def __clean_tmpdir(self):
- if not self.enabletmpfs:
- return
-
- runner.show('umount -l %s' % self.workdir)
-
- def create(self):
- """Create partitions for the disk image(s)
-
- Create the partitions that will be assembled into disk
- image(s).
- """
- self.__setup_tmpdir()
- self.__ensure_builddir()
-
- self._create()
-
- def cleanup(self):
- """Undo anything performed in create().
-
- Note, make sure to call this method once finished with the creator
- instance in order to ensure no stale files are left on the host e.g.:
-
- creator = ImageCreator(ks, name)
- try:
- creator.create()
- finally:
- creator.cleanup()
-
- """
- if not self.__builddir:
- return
-
- self._cleanup()
-
- shutil.rmtree(self.__builddir, ignore_errors=True)
- self.__builddir = None
-
- self.__clean_tmpdir()
-
-
- def print_outimage_info(self):
- msg = "The new image can be found here:\n"
- self.outimage.sort()
- for path in self.outimage:
- msg += ' %s\n' % os.path.abspath(path)
-
- msger.info(msg)
diff --git a/scripts/lib/wic/imager/direct.py b/scripts/lib/wic/imager/direct.py
deleted file mode 100644
index 31c0edc7d3..0000000000
--- a/scripts/lib/wic/imager/direct.py
+++ /dev/null
@@ -1,378 +0,0 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
-#
-# Copyright (c) 2013, Intel Corporation.
-# All rights reserved.
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# DESCRIPTION
-# This implements the 'direct' image creator class for 'wic'
-#
-# AUTHORS
-# Tom Zanussi <tom.zanussi (at] linux.intel.com>
-#
-
-import os
-import shutil
-
-from wic import kickstart, msger
-from wic.utils import fs_related
-from wic.utils.oe.misc import get_bitbake_var
-from wic.utils.partitionedfs import Image
-from wic.utils.errors import CreatorError, ImageError
-from wic.imager.baseimager import BaseImageCreator
-from wic.plugin import pluginmgr
-from wic.utils.oe.misc import exec_cmd
-
-disk_methods = {
- "do_install_disk":None,
-}
-
-class DirectImageCreator(BaseImageCreator):
- """
- Installs a system into a file containing a partitioned disk image.
-
- DirectImageCreator is an advanced ImageCreator subclass; an image
- file is formatted with a partition table, each partition created
- from a rootfs or other OpenEmbedded build artifact and dd'ed into
- the virtual disk. The disk image can subsequently be dd'ed onto
- media and used on actual hardware.
- """
-
- def __init__(self, oe_builddir, image_output_dir, rootfs_dir, bootimg_dir,
- kernel_dir, native_sysroot, compressor, creatoropts=None):
- """
- Initialize a DirectImageCreator instance.
-
- This method takes the same arguments as ImageCreator.__init__()
- """
- BaseImageCreator.__init__(self, creatoropts)
-
- self.__image = None
- self.__disks = {}
- self.__disk_format = "direct"
- self._disk_names = []
- self.ptable_format = self.ks.handler.bootloader.ptable
-
- self.oe_builddir = oe_builddir
- if image_output_dir:
- self.tmpdir = image_output_dir
- self.rootfs_dir = rootfs_dir
- self.bootimg_dir = bootimg_dir
- self.kernel_dir = kernel_dir
- self.native_sysroot = native_sysroot
- self.compressor = compressor
-
- def __get_part_num(self, num, parts):
- """calculate the real partition number, accounting for partitions not
- in the partition table and logical partitions
- """
- realnum = 0
- for pnum, part in enumerate(parts, 1):
- if not part.no_table:
- realnum += 1
- if pnum == num:
- if part.no_table:
- return 0
- if self.ptable_format == 'msdos' and realnum > 3:
- # account for logical partition numbering, ex. sda5..
- return realnum + 1
- return realnum
-
- def _write_fstab(self, image_rootfs):
- """overriden to generate fstab (temporarily) in rootfs. This is called
- from _create, make sure it doesn't get called from
- BaseImage.create()
- """
- if not image_rootfs:
- return
-
- fstab_path = image_rootfs + "/etc/fstab"
- if not os.path.isfile(fstab_path):
- return
-
- with open(fstab_path) as fstab:
- fstab_lines = fstab.readlines()
-
- if self._update_fstab(fstab_lines, self._get_parts()):
- shutil.copyfile(fstab_path, fstab_path + ".orig")
-
- with open(fstab_path, "w") as fstab:
- fstab.writelines(fstab_lines)
-
- return fstab_path
-
- def _update_fstab(self, fstab_lines, parts):
- """Assume partition order same as in wks"""
- updated = False
- for num, part in enumerate(parts, 1):
- pnum = self.__get_part_num(num, parts)
- if not pnum or not part.mountpoint \
- or part.mountpoint in ("/", "/boot"):
- continue
-
- # mmc device partitions are named mmcblk0p1, mmcblk0p2..
- prefix = 'p' if part.disk.startswith('mmcblk') else ''
- device_name = "/dev/%s%s%d" % (part.disk, prefix, pnum)
-
- opts = part.fsopts if part.fsopts else "defaults"
- line = "\t".join([device_name, part.mountpoint, part.fstype,
- opts, "0", "0"]) + "\n"
-
- fstab_lines.append(line)
- updated = True
-
- return updated
-
- def set_bootimg_dir(self, bootimg_dir):
- """
- Accessor for bootimg_dir, the actual location used for the source
- of the bootimg. Should be set by source plugins (only if they
- change the default bootimg source) so the correct info gets
- displayed for print_outimage_info().
- """
- self.bootimg_dir = bootimg_dir
-
- def _get_parts(self):
- if not self.ks:
- raise CreatorError("Failed to get partition info, "
- "please check your kickstart setting.")
-
- # Set a default partition if no partition is given out
- if not self.ks.handler.partition.partitions:
- partstr = "part / --size 1900 --ondisk sda --fstype=ext3"
- args = partstr.split()
- part = self.ks.handler.partition.parse(args[1:])
- if part not in self.ks.handler.partition.partitions:
- self.ks.handler.partition.partitions.append(part)
-
- # partitions list from kickstart file
- return kickstart.get_partitions(self.ks)
-
- def get_disk_names(self):
- """ Returns a list of physical target disk names (e.g., 'sdb') which
- will be created. """
-
- if self._disk_names:
- return self._disk_names
-
- #get partition info from ks handler
- parts = self._get_parts()
-
- for i in range(len(parts)):
- if parts[i].disk:
- disk_name = parts[i].disk
- else:
- raise CreatorError("Failed to create disks, no --ondisk "
- "specified in partition line of ks file")
-
- if parts[i].mountpoint and not parts[i].fstype:
- raise CreatorError("Failed to create disks, no --fstype "
- "specified for partition with mountpoint "
- "'%s' in the ks file")
-
- self._disk_names.append(disk_name)
-
- return self._disk_names
-
- def _full_name(self, name, extention):
- """ Construct full file name for a file we generate. """
- return "%s-%s.%s" % (self.name, name, extention)
-
- def _full_path(self, path, name, extention):
- """ Construct full file path to a file we generate. """
- return os.path.join(path, self._full_name(name, extention))
-
- def get_default_source_plugin(self):
- """
- The default source plugin i.e. the plugin that's consulted for
- overall image generation tasks outside of any particular
- partition. For convenience, we just hang it off the
- bootloader handler since it's the one non-partition object in
- any setup. By default the default plugin is set to the same
- plugin as the /boot partition; since we hang it off the
- bootloader object, the default can be explicitly set using the
- --source bootloader param.
- """
- return self.ks.handler.bootloader.source
-
- #
- # Actual implemention
- #
- def _create(self):
- """
- For 'wic', we already have our build artifacts - we just create
- filesystems from the artifacts directly and combine them into
- a partitioned image.
- """
- parts = self._get_parts()
-
- self.__image = Image(self.native_sysroot)
-
- for part in parts:
- # as a convenience, set source to the boot partition source
- # instead of forcing it to be set via bootloader --source
- if not self.ks.handler.bootloader.source and part.mountpoint == "/boot":
- self.ks.handler.bootloader.source = part.source
-
- fstab_path = self._write_fstab(self.rootfs_dir.get("ROOTFS_DIR"))
-
- for part in parts:
- # get rootfs size from bitbake variable if it's not set in .ks file
- if not part.size:
- # and if rootfs name is specified for the partition
- image_name = part.get_rootfs()
- if image_name:
- # Bitbake variable ROOTFS_SIZE is calculated in
- # Image._get_rootfs_size method from meta/lib/oe/image.py
- # using IMAGE_ROOTFS_SIZE, IMAGE_ROOTFS_ALIGNMENT,
- # IMAGE_OVERHEAD_FACTOR and IMAGE_ROOTFS_EXTRA_SPACE
- rsize_bb = get_bitbake_var('ROOTFS_SIZE', image_name)
- if rsize_bb:
- # convert from Kb to Mb
- part.size = int(rsize_bb) / 1024
- # need to create the filesystems in order to get their
- # sizes before we can add them and do the layout.
- # Image.create() actually calls __format_disks() to create
- # the disk images and carve out the partitions, then
- # self.assemble() calls Image.assemble() which calls
- # __write_partitition() for each partition to dd the fs
- # into the partitions.
- part.prepare(self, self.workdir, self.oe_builddir, self.rootfs_dir,
- self.bootimg_dir, self.kernel_dir, self.native_sysroot)
-
-
- self.__image.add_partition(int(part.size),
- part.disk,
- part.mountpoint,
- part.source_file,
- part.fstype,
- part.label,
- fsopts=part.fsopts,
- boot=part.active,
- align=part.align,
- no_table=part.no_table,
- part_type=part.part_type,
- uuid=part.uuid)
-
- if fstab_path:
- shutil.move(fstab_path + ".orig", fstab_path)
-
- self.__image.layout_partitions(self.ptable_format)
-
- self.__imgdir = self.workdir
- for disk_name, disk in self.__image.disks.items():
- full_path = self._full_path(self.__imgdir, disk_name, "direct")
- msger.debug("Adding disk %s as %s with size %s bytes" \
- % (disk_name, full_path, disk['min_size']))
- disk_obj = fs_related.DiskImage(full_path, disk['min_size'])
- self.__disks[disk_name] = disk_obj
- self.__image.add_disk(disk_name, disk_obj)
-
- self.__image.create()
-
- def assemble(self):
- """
- Assemble partitions into disk image(s)
- """
- for disk_name, disk in self.__image.disks.items():
- full_path = self._full_path(self.__imgdir, disk_name, "direct")
- msger.debug("Assembling disk %s as %s with size %s bytes" \
- % (disk_name, full_path, disk['min_size']))
- self.__image.assemble(full_path)
-
- def finalize(self):
- """
- Finalize the disk image.
-
- For example, prepare the image to be bootable by e.g.
- creating and installing a bootloader configuration.
-
- """
- source_plugin = self.get_default_source_plugin()
- if source_plugin:
- self._source_methods = pluginmgr.get_source_plugin_methods(source_plugin, disk_methods)
- for disk_name, disk in self.__image.disks.items():
- self._source_methods["do_install_disk"](disk, disk_name, self,
- self.workdir,
- self.oe_builddir,
- self.bootimg_dir,
- self.kernel_dir,
- self.native_sysroot)
- # Compress the image
- if self.compressor:
- for disk_name, disk in self.__image.disks.items():
- full_path = self._full_path(self.__imgdir, disk_name, "direct")
- msger.debug("Compressing disk %s with %s" % \
- (disk_name, self.compressor))
- exec_cmd("%s %s" % (self.compressor, full_path))
-
- def print_outimage_info(self):
- """
- Print the image(s) and artifacts used, for the user.
- """
- msg = "The new image(s) can be found here:\n"
-
- parts = self._get_parts()
-
- for disk_name in self.__image.disks:
- extension = "direct" + {"gzip": ".gz",
- "bzip2": ".bz2",
- "xz": ".xz",
- "": ""}.get(self.compressor)
- full_path = self._full_path(self.__imgdir, disk_name, extension)
- msg += ' %s\n\n' % full_path
-
- msg += 'The following build artifacts were used to create the image(s):\n'
- for part in parts:
- if part.get_rootfs() is None:
- continue
- if part.mountpoint == '/':
- suffix = ':'
- else:
- suffix = '["%s"]:' % (part.mountpoint or part.label)
- msg += ' ROOTFS_DIR%s%s\n' % (suffix.ljust(20), part.get_rootfs())
-
- msg += ' BOOTIMG_DIR: %s\n' % self.bootimg_dir
- msg += ' KERNEL_DIR: %s\n' % self.kernel_dir
- msg += ' NATIVE_SYSROOT: %s\n' % self.native_sysroot
-
- msger.info(msg)
-
- @property
- def rootdev(self):
- """
- Get root device name to use as a 'root' parameter
- in kernel command line.
-
- Assume partition order same as in wks
- """
- parts = self._get_parts()
- for num, part in enumerate(parts, 1):
- if part.mountpoint == "/":
- if part.uuid:
- return "PARTUUID=%s" % part.uuid
- else:
- suffix = 'p' if part.disk.startswith('mmcblk') else ''
- pnum = self.__get_part_num(num, parts)
- return "/dev/%s%s%-d" % (part.disk, suffix, pnum)
-
- def _cleanup(self):
- if not self.__image is None:
- try:
- self.__image.cleanup()
- except ImageError, err:
- msger.warning("%s" % err)
-
diff --git a/scripts/lib/wic/kickstart/__init__.py b/scripts/lib/wic/kickstart/__init__.py
deleted file mode 100644
index c9b0e51f3c..0000000000
--- a/scripts/lib/wic/kickstart/__init__.py
+++ /dev/null
@@ -1,122 +0,0 @@
-#!/usr/bin/env python -tt
-#
-# Copyright (c) 2007 Red Hat, Inc.
-# Copyright (c) 2009, 2010, 2011 Intel, Inc.
-#
-# This program 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; version 2 of the License
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-import os, sys, re
-import shutil
-import subprocess
-import string
-
-import pykickstart.sections as kssections
-import pykickstart.commands as kscommands
-import pykickstart.constants as ksconstants
-import pykickstart.errors as kserrors
-import pykickstart.parser as ksparser
-import pykickstart.version as ksversion
-from pykickstart.handlers.control import commandMap
-from pykickstart.handlers.control import dataMap
-
-from wic import msger
-from wic.utils import errors, misc, runner, fs_related as fs
-from custom_commands import wicboot, partition
-
-def read_kickstart(path):
- """Parse a kickstart file and return a KickstartParser instance.
-
- This is a simple utility function which takes a path to a kickstart file,
- parses it and returns a pykickstart KickstartParser instance which can
- be then passed to an ImageCreator constructor.
-
- If an error occurs, a CreatorError exception is thrown.
- """
-
- #version = ksversion.makeVersion()
- #ks = ksparser.KickstartParser(version)
-
- using_version = ksversion.DEVEL
- commandMap[using_version]["bootloader"] = wicboot.Wic_Bootloader
- commandMap[using_version]["part"] = partition.Wic_Partition
- commandMap[using_version]["partition"] = partition.Wic_Partition
- dataMap[using_version]["PartData"] = partition.Wic_PartData
- superclass = ksversion.returnClassForVersion(version=using_version)
-
- class KSHandlers(superclass):
- def __init__(self):
- superclass.__init__(self, mapping=commandMap[using_version])
-
- kickstart = ksparser.KickstartParser(KSHandlers(), errorsAreFatal=True)
-
- try:
- kickstart.readKickstart(path)
- except (kserrors.KickstartParseError, kserrors.KickstartError), err:
- msger.warning("Errors occurred when parsing kickstart file: %s\n" % path)
- msger.error("%s" % err)
-
- return kickstart
-
-def get_image_size(kickstart, default=None):
- __size = 0
- for part in kickstart.handler.partition.partitions:
- if part.mountpoint == "/" and part.size:
- __size = part.size
- if __size > 0:
- return int(__size) * 1024L
- else:
- return default
-
-def get_image_fstype(kickstart, default=None):
- for part in kickstart.handler.partition.partitions:
- if part.mountpoint == "/" and part.fstype:
- return part.fstype
- return default
-
-def get_image_fsopts(kickstart, default=None):
- for part in kickstart.handler.partition.partitions:
- if part.mountpoint == "/" and part.fsopts:
- return part.fsopts
- return default
-
-def get_timeout(kickstart, default=None):
- if not hasattr(kickstart.handler.bootloader, "timeout"):
- return default
- if kickstart.handler.bootloader.timeout is None:
- return default
- return int(kickstart.handler.bootloader.timeout)
-
-def get_kernel_args(kickstart, default="ro rd.live.image"):
- if not hasattr(kickstart.handler.bootloader, "appendLine"):
- return default
- if kickstart.handler.bootloader.appendLine is None:
- return default
- return "%s %s" %(default, kickstart.handler.bootloader.appendLine)
-
-def get_menu_args(kickstart, default=""):
- if not hasattr(kickstart.handler.bootloader, "menus"):
- return default
- if kickstart.handler.bootloader.menus in (None, ""):
- return default
- return "%s" % kickstart.handler.bootloader.menus
-
-def get_default_kernel(kickstart, default=None):
- if not hasattr(kickstart.handler.bootloader, "default"):
- return default
- if not kickstart.handler.bootloader.default:
- return default
- return kickstart.handler.bootloader.default
-
-def get_partitions(kickstart):
- return kickstart.handler.partition.partitions
diff --git a/scripts/lib/wic/kickstart/custom_commands/__init__.py b/scripts/lib/wic/kickstart/custom_commands/__init__.py
deleted file mode 100644
index e4ae40622c..0000000000
--- a/scripts/lib/wic/kickstart/custom_commands/__init__.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from partition import Wic_Partition
-from partition import Wic_PartData
-
-__all__ = (
- "Wic_Partition",
- "Wic_PartData",
-)
diff --git a/scripts/lib/wic/kickstart/custom_commands/partition.py b/scripts/lib/wic/kickstart/custom_commands/partition.py
deleted file mode 100644
index eee25a493d..0000000000
--- a/scripts/lib/wic/kickstart/custom_commands/partition.py
+++ /dev/null
@@ -1,526 +0,0 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
-#
-# Copyright (c) 2013, Intel Corporation.
-# All rights reserved.
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# DESCRIPTION
-# This module provides the OpenEmbedded partition object definitions.
-#
-# AUTHORS
-# Tom Zanussi <tom.zanussi (at] linux.intel.com>
-#
-
-import os
-import tempfile
-import uuid
-from optparse import OptionValueError
-
-from pykickstart.commands.partition import FC4_PartData, FC4_Partition
-from wic.utils.oe.misc import msger, parse_sourceparams
-from wic.utils.oe.misc import exec_cmd, exec_native_cmd
-from wic.plugin import pluginmgr
-
-partition_methods = {
- "do_stage_partition":None,
- "do_prepare_partition":None,
- "do_configure_partition":None,
-}
-
-class Wic_PartData(FC4_PartData):
- removedKeywords = FC4_PartData.removedKeywords
- removedAttrs = FC4_PartData.removedAttrs
-
- def __init__(self, *args, **kwargs):
- FC4_PartData.__init__(self, *args, **kwargs)
- self.deleteRemovedAttrs()
- self.align = kwargs.get("align", None)
- self.extopts = kwargs.get("extopts", None)
- self.part_type = kwargs.get("part_type", None)
- self.source = kwargs.get("source", None)
- self.sourceparams = kwargs.get("sourceparams", None)
- self.rootfs = kwargs.get("rootfs-dir", None)
- self.no_table = kwargs.get("no-table", False)
- self.extra_space = kwargs.get("extra-space", "10M")
- self.overhead_factor = kwargs.get("overhead-factor", 1.3)
- self._use_uuid = False
- self.uuid = kwargs.get("uuid", None)
- self.use_uuid = kwargs.get("use-uuid", False)
- self.source_file = ""
- self.size = 0
-
- def _getArgsAsStr(self):
- retval = FC4_PartData._getArgsAsStr(self)
-
- if self.align:
- retval += " --align=%d" % self.align
- if self.extopts:
- retval += " --extoptions=%s" % self.extopts
- if self.part_type:
- retval += " --part-type=%s" % self.part_type
- if self.source:
- retval += " --source=%s" % self.source
- if self.sourceparams:
- retval += " --sourceparams=%s" % self.sourceparams
- if self.rootfs:
- retval += " --rootfs-dir=%s" % self.rootfs
- if self.no_table:
- retval += " --no-table"
- if self.use_uuid:
- retval += " --use-uuid"
- if self.uuid:
- retval += " --uuid=%s" % self.uuid
- retval += " --extra-space=%s" % self.extra_space
- retval += " --overhead-factor=%f" % self.overhead_factor
-
- return retval
-
- @property
- def use_uuid(self):
- return self._use_uuid
-
- @use_uuid.setter
- def use_uuid(self, value):
- self._use_uuid = value
- if value and not self.uuid:
- self.uuid = str(uuid.uuid4())
-
- def get_rootfs(self):
- """
- Acessor for rootfs dir
- """
- return self.rootfs
-
- def set_rootfs(self, rootfs):
- """
- Acessor for actual rootfs dir, which must be set by source
- plugins.
- """
- self.rootfs = rootfs
-
- def get_size(self):
- """
- Accessor for partition size, 0 or --size before set_size().
- """
- return self.size
-
- def set_size(self, size):
- """
- Accessor for actual partition size, which must be set by source
- plugins.
- """
- self.size = size
-
- def set_source_file(self, source_file):
- """
- Accessor for source_file, the location of the generated partition
- image, which must be set by source plugins.
- """
- self.source_file = source_file
-
- def get_extra_block_count(self, current_blocks):
- """
- The --size param is reflected in self.size (in kB), and we already
- have current_blocks (1k) blocks, calculate and return the
- number of (1k) blocks we need to add to get to --size, 0 if
- we're already there or beyond.
- """
- msger.debug("Requested partition size for %s: %d" % \
- (self.mountpoint, self.size))
-
- if not self.size:
- return 0
-
- requested_blocks = self.size
-
- msger.debug("Requested blocks %d, current_blocks %d" % \
- (requested_blocks, current_blocks))
-
- if requested_blocks > current_blocks:
- return requested_blocks - current_blocks
- else:
- return 0
-
- def prepare(self, creator, cr_workdir, oe_builddir, rootfs_dir, bootimg_dir,
- kernel_dir, native_sysroot):
- """
- Prepare content for individual partitions, depending on
- partition command parameters.
- """
- self.sourceparams_dict = {}
-
- if self.sourceparams:
- self.sourceparams_dict = parse_sourceparams(self.sourceparams)
-
- if not self.source:
- if not self.size:
- msger.error("The %s partition has a size of zero. Please "
- "specify a non-zero --size for that partition." % \
- self.mountpoint)
- if self.fstype and self.fstype == "swap":
- self.prepare_swap_partition(cr_workdir, oe_builddir,
- native_sysroot)
- elif self.fstype:
- rootfs = "%s/fs_%s.%s.%s" % (cr_workdir, self.label,
- self.lineno, self.fstype)
- if os.path.isfile(rootfs):
- os.remove(rootfs)
- for prefix in ("ext", "btrfs", "vfat", "squashfs"):
- if self.fstype.startswith(prefix):
- method = getattr(self,
- "prepare_empty_partition_" + prefix)
- method(rootfs, oe_builddir, native_sysroot)
- self.source_file = rootfs
- break
- return
-
- plugins = pluginmgr.get_source_plugins()
-
- if self.source not in plugins:
- msger.error("The '%s' --source specified for %s doesn't exist.\n\t"
- "See 'wic list source-plugins' for a list of available"
- " --sources.\n\tSee 'wic help source-plugins' for "
- "details on adding a new source plugin." % \
- (self.source, self.mountpoint))
-
- self._source_methods = pluginmgr.get_source_plugin_methods(\
- self.source, partition_methods)
- self._source_methods["do_configure_partition"](self, self.sourceparams_dict,
- creator, cr_workdir,
- oe_builddir,
- bootimg_dir,
- kernel_dir,
- native_sysroot)
- self._source_methods["do_stage_partition"](self, self.sourceparams_dict,
- creator, cr_workdir,
- oe_builddir,
- bootimg_dir, kernel_dir,
- native_sysroot)
- self._source_methods["do_prepare_partition"](self, self.sourceparams_dict,
- creator, cr_workdir,
- oe_builddir,
- bootimg_dir, kernel_dir, rootfs_dir,
- native_sysroot)
-
- def prepare_rootfs_from_fs_image(self, cr_workdir, oe_builddir,
- rootfs_dir):
- """
- Handle an already-created partition e.g. xxx.ext3
- """
- rootfs = oe_builddir
- du_cmd = "du -Lbks %s" % rootfs
- out = exec_cmd(du_cmd)
- rootfs_size = out.split()[0]
-
- self.size = rootfs_size
- self.source_file = rootfs
-
- def prepare_rootfs(self, cr_workdir, oe_builddir, rootfs_dir,
- native_sysroot):
- """
- Prepare content for a rootfs partition i.e. create a partition
- and fill it from a /rootfs dir.
-
- Currently handles ext2/3/4, btrfs and vfat.
- """
- p_prefix = os.environ.get("PSEUDO_PREFIX", "%s/usr" % native_sysroot)
- p_localstatedir = os.environ.get("PSEUDO_LOCALSTATEDIR",
- "%s/../pseudo" % rootfs_dir)
- p_passwd = os.environ.get("PSEUDO_PASSWD", rootfs_dir)
- p_nosymlinkexp = os.environ.get("PSEUDO_NOSYMLINKEXP", "1")
- pseudo = "export PSEUDO_PREFIX=%s;" % p_prefix
- pseudo += "export PSEUDO_LOCALSTATEDIR=%s;" % p_localstatedir
- pseudo += "export PSEUDO_PASSWD=%s;" % p_passwd
- pseudo += "export PSEUDO_NOSYMLINKEXP=%s;" % p_nosymlinkexp
- pseudo += "%s/usr/bin/pseudo " % native_sysroot
-
- rootfs = "%s/rootfs_%s.%s.%s" % (cr_workdir, self.label,
- self.lineno, self.fstype)
- if os.path.isfile(rootfs):
- os.remove(rootfs)
-
- for prefix in ("ext", "btrfs", "vfat", "squashfs"):
- if self.fstype.startswith(prefix):
- method = getattr(self, "prepare_rootfs_" + prefix)
- method(rootfs, oe_builddir, rootfs_dir, native_sysroot, pseudo)
-
- self.source_file = rootfs
-
- # get the rootfs size in the right units for kickstart (kB)
- du_cmd = "du -Lbks %s" % rootfs
- out = exec_cmd(du_cmd)
- self.size = out.split()[0]
-
- break
-
- def prepare_rootfs_ext(self, rootfs, oe_builddir, rootfs_dir,
- native_sysroot, pseudo):
- """
- Prepare content for an ext2/3/4 rootfs partition.
- """
- du_cmd = "du -ks %s" % rootfs_dir
- out = exec_cmd(du_cmd)
- actual_rootfs_size = int(out.split()[0])
-
- extra_blocks = self.get_extra_block_count(actual_rootfs_size)
- if extra_blocks < self.extra_space:
- extra_blocks = self.extra_space
-
- rootfs_size = actual_rootfs_size + extra_blocks
- rootfs_size *= self.overhead_factor
-
- msger.debug("Added %d extra blocks to %s to get to %d total blocks" % \
- (extra_blocks, self.mountpoint, rootfs_size))
-
- dd_cmd = "dd if=/dev/zero of=%s bs=1024 seek=%d count=0 bs=1k" % \
- (rootfs, rootfs_size)
- exec_cmd(dd_cmd)
-
- extra_imagecmd = "-i 8192"
-
- label_str = ""
- if self.label:
- label_str = "-L %s" % self.label
-
- mkfs_cmd = "mkfs.%s -F %s %s %s -d %s" % \
- (self.fstype, extra_imagecmd, rootfs, label_str, rootfs_dir)
- exec_native_cmd(pseudo + mkfs_cmd, native_sysroot)
-
- def prepare_rootfs_btrfs(self, rootfs, oe_builddir, rootfs_dir,
- native_sysroot, pseudo):
- """
- Prepare content for a btrfs rootfs partition.
-
- Currently handles ext2/3/4 and btrfs.
- """
- du_cmd = "du -ks %s" % rootfs_dir
- out = exec_cmd(du_cmd)
- actual_rootfs_size = int(out.split()[0])
-
- extra_blocks = self.get_extra_block_count(actual_rootfs_size)
- if extra_blocks < self.extra_space:
- extra_blocks = self.extra_space
-
- rootfs_size = actual_rootfs_size + extra_blocks
- rootfs_size *= self.overhead_factor
-
- msger.debug("Added %d extra blocks to %s to get to %d total blocks" % \
- (extra_blocks, self.mountpoint, rootfs_size))
-
- dd_cmd = "dd if=/dev/zero of=%s bs=1024 seek=%d count=0 bs=1k" % \
- (rootfs, rootfs_size)
- exec_cmd(dd_cmd)
-
- label_str = ""
- if self.label:
- label_str = "-L %s" % self.label
-
- mkfs_cmd = "mkfs.%s -b %d -r %s %s %s" % \
- (self.fstype, rootfs_size * 1024, rootfs_dir, label_str, rootfs)
- exec_native_cmd(pseudo + mkfs_cmd, native_sysroot)
-
- def prepare_rootfs_vfat(self, rootfs, oe_builddir, rootfs_dir,
- native_sysroot, pseudo):
- """
- Prepare content for a vfat rootfs partition.
- """
- du_cmd = "du -bks %s" % rootfs_dir
- out = exec_cmd(du_cmd)
- blocks = int(out.split()[0])
-
- extra_blocks = self.get_extra_block_count(blocks)
- if extra_blocks < self.extra_space:
- extra_blocks = self.extra_space
-
- blocks += extra_blocks
-
- msger.debug("Added %d extra blocks to %s to get to %d total blocks" % \
- (extra_blocks, self.mountpoint, blocks))
-
- # Ensure total sectors is an integral number of sectors per
- # track or mcopy will complain. Sectors are 512 bytes, and we
- # generate images with 32 sectors per track. This calculation
- # is done in blocks, thus the mod by 16 instead of 32. Apply
- # sector count fix only when needed.
- if blocks % 16 != 0:
- blocks += (16 - (blocks % 16))
-
- label_str = "-n boot"
- if self.label:
- label_str = "-n %s" % self.label
-
- dosfs_cmd = "mkdosfs %s -S 512 -C %s %d" % (label_str, rootfs, blocks)
- exec_native_cmd(dosfs_cmd, native_sysroot)
-
- mcopy_cmd = "mcopy -i %s -s %s/* ::/" % (rootfs, rootfs_dir)
- exec_native_cmd(mcopy_cmd, native_sysroot)
-
- chmod_cmd = "chmod 644 %s" % rootfs
- exec_cmd(chmod_cmd)
-
- def prepare_rootfs_squashfs(self, rootfs, oe_builddir, rootfs_dir,
- native_sysroot, pseudo):
- """
- Prepare content for a squashfs rootfs partition.
- """
- squashfs_cmd = "mksquashfs %s %s -noappend" % \
- (rootfs_dir, rootfs)
- exec_native_cmd(pseudo + squashfs_cmd, native_sysroot)
-
- def prepare_empty_partition_ext(self, rootfs, oe_builddir,
- native_sysroot):
- """
- Prepare an empty ext2/3/4 partition.
- """
- dd_cmd = "dd if=/dev/zero of=%s bs=1k seek=%d count=0" % \
- (rootfs, self.size)
- exec_cmd(dd_cmd)
-
- extra_imagecmd = "-i 8192"
-
- label_str = ""
- if self.label:
- label_str = "-L %s" % self.label
-
- mkfs_cmd = "mkfs.%s -F %s %s %s" % \
- (self.fstype, extra_imagecmd, label_str, rootfs)
- exec_native_cmd(mkfs_cmd, native_sysroot)
-
- def prepare_empty_partition_btrfs(self, rootfs, oe_builddir,
- native_sysroot):
- """
- Prepare an empty btrfs partition.
- """
- dd_cmd = "dd if=/dev/zero of=%s bs=1k seek=%d count=0" % \
- (rootfs, self.size)
- exec_cmd(dd_cmd)
-
- label_str = ""
- if self.label:
- label_str = "-L %s" % self.label
-
- mkfs_cmd = "mkfs.%s -b %d %s %s" % \
- (self.fstype, self.size * 1024, label_str, rootfs)
- exec_native_cmd(mkfs_cmd, native_sysroot)
-
- def prepare_empty_partition_vfat(self, rootfs, oe_builddir,
- native_sysroot):
- """
- Prepare an empty vfat partition.
- """
- blocks = self.size
-
- label_str = "-n boot"
- if self.label:
- label_str = "-n %s" % self.label
-
- dosfs_cmd = "mkdosfs %s -S 512 -C %s %d" % (label_str, rootfs, blocks)
- exec_native_cmd(dosfs_cmd, native_sysroot)
-
- chmod_cmd = "chmod 644 %s" % rootfs
- exec_cmd(chmod_cmd)
-
- def prepare_empty_partition_squashfs(self, cr_workdir, oe_builddir,
- native_sysroot):
- """
- Prepare an empty squashfs partition.
- """
- msger.warning("Creating of an empty squashfs %s partition was attempted. " \
- "Proceeding as requested." % self.mountpoint)
-
- path = "%s/fs_%s.%s" % (cr_workdir, self.label, self.fstype)
- os.path.isfile(path) and os.remove(path)
-
- # it is not possible to create a squashfs without source data,
- # thus prepare an empty temp dir that is used as source
- tmpdir = tempfile.mkdtemp()
-
- squashfs_cmd = "mksquashfs %s %s -noappend" % \
- (tmpdir, path)
- exec_native_cmd(squashfs_cmd, native_sysroot)
-
- os.rmdir(tmpdir)
-
- # get the rootfs size in the right units for kickstart (kB)
- du_cmd = "du -Lbks %s" % path
- out = exec_cmd(du_cmd)
- fs_size = out.split()[0]
-
- self.size = fs_size
-
- def prepare_swap_partition(self, cr_workdir, oe_builddir, native_sysroot):
- """
- Prepare a swap partition.
- """
- path = "%s/fs.%s" % (cr_workdir, self.fstype)
-
- dd_cmd = "dd if=/dev/zero of=%s bs=1k seek=%d count=0" % \
- (path, self.size)
- exec_cmd(dd_cmd)
-
- import uuid
- label_str = ""
- if self.label:
- label_str = "-L %s" % self.label
- mkswap_cmd = "mkswap %s -U %s %s" % (label_str, str(uuid.uuid1()), path)
- exec_native_cmd(mkswap_cmd, native_sysroot)
-
-
-class Wic_Partition(FC4_Partition):
- removedKeywords = FC4_Partition.removedKeywords
- removedAttrs = FC4_Partition.removedAttrs
-
- def _getParser(self):
- def overhead_cb(option, opt_str, value, parser):
- if value < 1:
- raise OptionValueError("Option %s: invalid value: %r" % \
- (option, value))
- setattr(parser.values, option.dest, value)
-
- parser = FC4_Partition._getParser(self)
-
- # The alignment value is given in kBytes. e.g., value 8 means that
- # the partition is aligned to start from 8096 byte boundary.
- parser.add_option("--align", type="int", action="store", dest="align",
- default=None)
- parser.add_option("--extoptions", type="string", action="store", dest="extopts",
- default=None)
- parser.add_option("--part-type", type="string", action="store", dest="part_type",
- default=None)
- # use specified source file to fill the partition
- # and calculate partition size
- parser.add_option("--source", type="string", action="store",
- dest="source", default=None)
- # comma-separated list of param=value pairs
- parser.add_option("--sourceparams", type="string", action="store",
- dest="sourceparams", default=None)
- # use specified rootfs path to fill the partition
- parser.add_option("--rootfs-dir", type="string", action="store",
- dest="rootfs", default=None)
- # wether to add the partition in the partition table
- parser.add_option("--no-table", dest="no_table", action="store_true",
- default=False)
- # extra space beyond the partition size
- parser.add_option("--extra-space", dest="extra_space", action="store",
- type="size", nargs=1, default="10M")
- parser.add_option("--overhead-factor", dest="overhead_factor",
- action="callback", callback=overhead_cb, type="float",
- nargs=1, default=1.3)
- parser.add_option("--use-uuid", dest="use_uuid", action="store_true",
- default=False)
- parser.add_option("--uuid")
-
- return parser
diff --git a/scripts/lib/wic/kickstart/custom_commands/wicboot.py b/scripts/lib/wic/kickstart/custom_commands/wicboot.py
deleted file mode 100644
index a3e1852be2..0000000000
--- a/scripts/lib/wic/kickstart/custom_commands/wicboot.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
-#
-# Copyright (c) 2014, Intel Corporation.
-# All rights reserved.
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# DESCRIPTION
-# This module provides the OpenEmbedded bootloader object definitions.
-#
-# AUTHORS
-# Tom Zanussi <tom.zanussi (at] linux.intel.com>
-#
-from pykickstart.commands.bootloader import F8_Bootloader
-
-class Wic_Bootloader(F8_Bootloader):
- def __init__(self, writePriority=10, appendLine="", driveorder=None,
- forceLBA=False, location="", md5pass="", password="",
- upgrade=False, menus=""):
- F8_Bootloader.__init__(self, writePriority, appendLine, driveorder,
- forceLBA, location, md5pass, password, upgrade)
-
- self.menus = ""
- self.ptable = "msdos"
- self.source = ""
-
- def _getArgsAsStr(self):
- retval = F8_Bootloader._getArgsAsStr(self)
-
- if self.menus == "":
- retval += " --menus=%s" %(self.menus,)
- if self.ptable:
- retval += " --ptable=\"%s\"" %(self.ptable,)
- if self.source:
- retval += " --source=%s" % self.source
-
- return retval
-
- def _getParser(self):
- parser = F8_Bootloader._getParser(self)
- parser.add_option("--menus", dest="menus")
- parser.add_option("--ptable", dest="ptable", choices=("msdos", "gpt"),
- default="msdos")
- # use specified source plugin to implement bootloader-specific methods
- parser.add_option("--source", type="string", action="store",
- dest="source", default=None)
- return parser
-
diff --git a/scripts/lib/wic/ksparser.py b/scripts/lib/wic/ksparser.py
new file mode 100644
index 0000000000..0df9eb0d05
--- /dev/null
+++ b/scripts/lib/wic/ksparser.py
@@ -0,0 +1,295 @@
+#!/usr/bin/env python3
+#
+# Copyright (c) 2016 Intel, Inc.
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# DESCRIPTION
+# This module provides parser for kickstart format
+#
+# AUTHORS
+# Ed Bartosh <ed.bartosh> (at] linux.intel.com>
+
+"""Kickstart parser module."""
+
+import os
+import shlex
+import logging
+import re
+
+from argparse import ArgumentParser, ArgumentError, ArgumentTypeError
+
+from wic.engine import find_canned
+from wic.partition import Partition
+from wic.misc import get_bitbake_var
+
+logger = logging.getLogger('wic')
+
+__expand_var_regexp__ = re.compile(r"\${[^{}@\n\t :]+}")
+
+def expand_line(line):
+ while True:
+ m = __expand_var_regexp__.search(line)
+ if not m:
+ return line
+ key = m.group()[2:-1]
+ val = get_bitbake_var(key)
+ if val is None:
+ logger.warning("cannot expand variable %s" % key)
+ return line
+ line = line[:m.start()] + val + line[m.end():]
+
+class KickStartError(Exception):
+ """Custom exception."""
+ pass
+
+class KickStartParser(ArgumentParser):
+ """
+ This class overwrites error method to throw exception
+ instead of producing usage message(default argparse behavior).
+ """
+ def error(self, message):
+ raise ArgumentError(None, message)
+
+def sizetype(default, size_in_bytes=False):
+ def f(arg):
+ """
+ Custom type for ArgumentParser
+ Converts size string in <num>[S|s|K|k|M|G] format into the integer value
+ """
+ try:
+ suffix = default
+ size = int(arg)
+ except ValueError:
+ try:
+ suffix = arg[-1:]
+ size = int(arg[:-1])
+ except ValueError:
+ raise ArgumentTypeError("Invalid size: %r" % arg)
+
+
+ if size_in_bytes:
+ if suffix == 's' or suffix == 'S':
+ return size * 512
+ mult = 1024
+ else:
+ mult = 1
+
+ if suffix == "k" or suffix == "K":
+ return size * mult
+ if suffix == "M":
+ return size * mult * 1024
+ if suffix == "G":
+ return size * mult * 1024 * 1024
+
+ raise ArgumentTypeError("Invalid size: %r" % arg)
+ return f
+
+def overheadtype(arg):
+ """
+ Custom type for ArgumentParser
+ Converts overhead string to float and checks if it's bigger than 1.0
+ """
+ try:
+ result = float(arg)
+ except ValueError:
+ raise ArgumentTypeError("Invalid value: %r" % arg)
+
+ if result < 1.0:
+ raise ArgumentTypeError("Overhead factor should be > 1.0" % arg)
+
+ return result
+
+def cannedpathtype(arg):
+ """
+ Custom type for ArgumentParser
+ Tries to find file in the list of canned wks paths
+ """
+ scripts_path = os.path.abspath(os.path.dirname(__file__) + '../../..')
+ result = find_canned(scripts_path, arg)
+ if not result:
+ raise ArgumentTypeError("file not found: %s" % arg)
+ return result
+
+def systemidtype(arg):
+ """
+ Custom type for ArgumentParser
+ Checks if the argument sutisfies system id requirements,
+ i.e. if it's one byte long integer > 0
+ """
+ error = "Invalid system type: %s. must be hex "\
+ "between 0x1 and 0xFF" % arg
+ try:
+ result = int(arg, 16)
+ except ValueError:
+ raise ArgumentTypeError(error)
+
+ if result <= 0 or result > 0xff:
+ raise ArgumentTypeError(error)
+
+ return arg
+
+class KickStart():
+ """Kickstart parser implementation."""
+
+ DEFAULT_EXTRA_SPACE = 10*1024
+ DEFAULT_OVERHEAD_FACTOR = 1.3
+
+ def __init__(self, confpath):
+
+ self.partitions = []
+ self.bootloader = None
+ self.lineno = 0
+ self.partnum = 0
+
+ parser = KickStartParser()
+ subparsers = parser.add_subparsers()
+
+ part = subparsers.add_parser('part')
+ part.add_argument('mountpoint', nargs='?')
+ part.add_argument('--active', action='store_true')
+ part.add_argument('--align', type=int)
+ part.add_argument('--offset', type=sizetype("K", True))
+ part.add_argument('--exclude-path', nargs='+')
+ part.add_argument('--include-path', nargs='+', action='append')
+ part.add_argument('--change-directory')
+ part.add_argument("--extra-space", type=sizetype("M"))
+ part.add_argument('--fsoptions', dest='fsopts')
+ part.add_argument('--fstype', default='vfat',
+ choices=('ext2', 'ext3', 'ext4', 'btrfs',
+ 'squashfs', 'vfat', 'msdos', 'erofs',
+ 'swap'))
+ part.add_argument('--mkfs-extraopts', default='')
+ part.add_argument('--label')
+ part.add_argument('--use-label', action='store_true')
+ part.add_argument('--no-table', action='store_true')
+ part.add_argument('--ondisk', '--ondrive', dest='disk', default='sda')
+ part.add_argument("--overhead-factor", type=overheadtype)
+ part.add_argument('--part-name')
+ part.add_argument('--part-type')
+ part.add_argument('--rootfs-dir')
+ part.add_argument('--type', default='primary',
+ choices = ('primary', 'logical'))
+
+ # --size and --fixed-size cannot be specified together; options
+ # ----extra-space and --overhead-factor should also raise a parser
+ # --error, but since nesting mutually exclusive groups does not work,
+ # ----extra-space/--overhead-factor are handled later
+ sizeexcl = part.add_mutually_exclusive_group()
+ sizeexcl.add_argument('--size', type=sizetype("M"), default=0)
+ sizeexcl.add_argument('--fixed-size', type=sizetype("M"), default=0)
+
+ part.add_argument('--source')
+ part.add_argument('--sourceparams')
+ part.add_argument('--system-id', type=systemidtype)
+ part.add_argument('--use-uuid', action='store_true')
+ part.add_argument('--uuid')
+ part.add_argument('--fsuuid')
+ part.add_argument('--no-fstab-update', action='store_true')
+
+ bootloader = subparsers.add_parser('bootloader')
+ bootloader.add_argument('--append')
+ bootloader.add_argument('--configfile')
+ bootloader.add_argument('--ptable', choices=('msdos', 'gpt'),
+ default='msdos')
+ bootloader.add_argument('--timeout', type=int)
+ bootloader.add_argument('--source')
+
+ include = subparsers.add_parser('include')
+ include.add_argument('path', type=cannedpathtype)
+
+ self._parse(parser, confpath)
+ if not self.bootloader:
+ logger.warning('bootloader config not specified, using defaults\n')
+ self.bootloader = bootloader.parse_args([])
+
+ def _parse(self, parser, confpath):
+ """
+ Parse file in .wks format using provided parser.
+ """
+ with open(confpath) as conf:
+ lineno = 0
+ for line in conf:
+ line = line.strip()
+ lineno += 1
+ if line and line[0] != '#':
+ line = expand_line(line)
+ try:
+ line_args = shlex.split(line)
+ parsed = parser.parse_args(line_args)
+ except ArgumentError as err:
+ raise KickStartError('%s:%d: %s' % \
+ (confpath, lineno, err))
+ if line.startswith('part'):
+ # SquashFS does not support filesystem UUID
+ if parsed.fstype == 'squashfs':
+ if parsed.fsuuid:
+ err = "%s:%d: SquashFS does not support UUID" \
+ % (confpath, lineno)
+ raise KickStartError(err)
+ if parsed.label:
+ err = "%s:%d: SquashFS does not support LABEL" \
+ % (confpath, lineno)
+ raise KickStartError(err)
+ # erofs does not support filesystem labels
+ if parsed.fstype == 'erofs' and parsed.label:
+ err = "%s:%d: erofs does not support LABEL" % (confpath, lineno)
+ raise KickStartError(err)
+ if parsed.fstype == 'msdos' or parsed.fstype == 'vfat':
+ if parsed.fsuuid:
+ if parsed.fsuuid.upper().startswith('0X'):
+ if len(parsed.fsuuid) > 10:
+ err = "%s:%d: fsuuid %s given in wks kickstart file " \
+ "exceeds the length limit for %s filesystem. " \
+ "It should be in the form of a 32 bit hexadecimal" \
+ "number (for example, 0xABCD1234)." \
+ % (confpath, lineno, parsed.fsuuid, parsed.fstype)
+ raise KickStartError(err)
+ elif len(parsed.fsuuid) > 8:
+ err = "%s:%d: fsuuid %s given in wks kickstart file " \
+ "exceeds the length limit for %s filesystem. " \
+ "It should be in the form of a 32 bit hexadecimal" \
+ "number (for example, 0xABCD1234)." \
+ % (confpath, lineno, parsed.fsuuid, parsed.fstype)
+ raise KickStartError(err)
+ if parsed.use_label and not parsed.label:
+ err = "%s:%d: Must set the label with --label" \
+ % (confpath, lineno)
+ raise KickStartError(err)
+ # using ArgumentParser one cannot easily tell if option
+ # was passed as argument, if said option has a default
+ # value; --overhead-factor/--extra-space cannot be used
+ # with --fixed-size, so at least detect when these were
+ # passed with non-0 values ...
+ if parsed.fixed_size:
+ if parsed.overhead_factor or parsed.extra_space:
+ err = "%s:%d: arguments --overhead-factor and --extra-space not "\
+ "allowed with argument --fixed-size" \
+ % (confpath, lineno)
+ raise KickStartError(err)
+ else:
+ # ... and provide defaults if not using
+ # --fixed-size iff given option was not used
+ # (again, one cannot tell if option was passed but
+ # with value equal to 0)
+ if '--overhead-factor' not in line_args:
+ parsed.overhead_factor = self.DEFAULT_OVERHEAD_FACTOR
+ if '--extra-space' not in line_args:
+ parsed.extra_space = self.DEFAULT_EXTRA_SPACE
+
+ self.partnum += 1
+ self.partitions.append(Partition(parsed, self.partnum))
+ elif line.startswith('include'):
+ self._parse(parser, parsed.path)
+ elif line.startswith('bootloader'):
+ if not self.bootloader:
+ self.bootloader = parsed
+ # Concatenate the strings set in APPEND
+ append_var = get_bitbake_var("APPEND")
+ if append_var:
+ self.bootloader.append = ' '.join(filter(None, \
+ (self.bootloader.append, append_var)))
+ else:
+ err = "%s:%d: more than one bootloader specified" \
+ % (confpath, lineno)
+ raise KickStartError(err)
diff --git a/scripts/lib/wic/misc.py b/scripts/lib/wic/misc.py
new file mode 100644
index 0000000000..57c042c503
--- /dev/null
+++ b/scripts/lib/wic/misc.py
@@ -0,0 +1,264 @@
+#
+# Copyright (c) 2013, Intel Corporation.
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# DESCRIPTION
+# This module provides a place to collect various wic-related utils
+# for the OpenEmbedded Image Tools.
+#
+# AUTHORS
+# Tom Zanussi <tom.zanussi (at] linux.intel.com>
+#
+"""Miscellaneous functions."""
+
+import logging
+import os
+import re
+import subprocess
+
+from collections import defaultdict
+from distutils import spawn
+
+from wic import WicError
+
+logger = logging.getLogger('wic')
+
+# executable -> recipe pairs for exec_native_cmd
+NATIVE_RECIPES = {"bmaptool": "bmap-tools",
+ "dumpe2fs": "e2fsprogs",
+ "grub-mkimage": "grub-efi",
+ "isohybrid": "syslinux",
+ "mcopy": "mtools",
+ "mdel" : "mtools",
+ "mdeltree" : "mtools",
+ "mdir" : "mtools",
+ "mkdosfs": "dosfstools",
+ "mkisofs": "cdrtools",
+ "mkfs.btrfs": "btrfs-tools",
+ "mkfs.ext2": "e2fsprogs",
+ "mkfs.ext3": "e2fsprogs",
+ "mkfs.ext4": "e2fsprogs",
+ "mkfs.vfat": "dosfstools",
+ "mksquashfs": "squashfs-tools",
+ "mkswap": "util-linux",
+ "mmd": "mtools",
+ "parted": "parted",
+ "sfdisk": "util-linux",
+ "sgdisk": "gptfdisk",
+ "syslinux": "syslinux",
+ "tar": "tar"
+ }
+
+def runtool(cmdln_or_args):
+ """ wrapper for most of the subprocess calls
+ input:
+ cmdln_or_args: can be both args and cmdln str (shell=True)
+ return:
+ rc, output
+ """
+ if isinstance(cmdln_or_args, list):
+ cmd = cmdln_or_args[0]
+ shell = False
+ else:
+ import shlex
+ cmd = shlex.split(cmdln_or_args)[0]
+ shell = True
+
+ sout = subprocess.PIPE
+ serr = subprocess.STDOUT
+
+ try:
+ process = subprocess.Popen(cmdln_or_args, stdout=sout,
+ stderr=serr, shell=shell)
+ sout, serr = process.communicate()
+ # combine stdout and stderr, filter None out and decode
+ out = ''.join([out.decode('utf-8') for out in [sout, serr] if out])
+ except OSError as err:
+ if err.errno == 2:
+ # [Errno 2] No such file or directory
+ raise WicError('Cannot run command: %s, lost dependency?' % cmd)
+ else:
+ raise # relay
+
+ return process.returncode, out
+
+def _exec_cmd(cmd_and_args, as_shell=False):
+ """
+ Execute command, catching stderr, stdout
+
+ Need to execute as_shell if the command uses wildcards
+ """
+ logger.debug("_exec_cmd: %s", cmd_and_args)
+ args = cmd_and_args.split()
+ logger.debug(args)
+
+ if as_shell:
+ ret, out = runtool(cmd_and_args)
+ else:
+ ret, out = runtool(args)
+ out = out.strip()
+ if ret != 0:
+ raise WicError("_exec_cmd: %s returned '%s' instead of 0\noutput: %s" % \
+ (cmd_and_args, ret, out))
+
+ logger.debug("_exec_cmd: output for %s (rc = %d): %s",
+ cmd_and_args, ret, out)
+
+ return ret, out
+
+
+def exec_cmd(cmd_and_args, as_shell=False):
+ """
+ Execute command, return output
+ """
+ return _exec_cmd(cmd_and_args, as_shell)[1]
+
+def find_executable(cmd, paths):
+ recipe = cmd
+ if recipe in NATIVE_RECIPES:
+ recipe = NATIVE_RECIPES[recipe]
+ provided = get_bitbake_var("ASSUME_PROVIDED")
+ if provided and "%s-native" % recipe in provided:
+ return True
+
+ return spawn.find_executable(cmd, paths)
+
+def exec_native_cmd(cmd_and_args, native_sysroot, pseudo=""):
+ """
+ Execute native command, catching stderr, stdout
+
+ Need to execute as_shell if the command uses wildcards
+
+ Always need to execute native commands as_shell
+ """
+ # The reason -1 is used is because there may be "export" commands.
+ args = cmd_and_args.split(';')[-1].split()
+ logger.debug(args)
+
+ if pseudo:
+ cmd_and_args = pseudo + cmd_and_args
+
+ hosttools_dir = get_bitbake_var("HOSTTOOLS_DIR")
+
+ native_paths = "%s/sbin:%s/usr/sbin:%s/usr/bin:%s/bin:%s" % \
+ (native_sysroot, native_sysroot,
+ native_sysroot, native_sysroot,
+ hosttools_dir)
+
+ native_cmd_and_args = "export PATH=%s:$PATH;%s" % \
+ (native_paths, cmd_and_args)
+ logger.debug("exec_native_cmd: %s", native_cmd_and_args)
+
+ # If the command isn't in the native sysroot say we failed.
+ if find_executable(args[0], native_paths):
+ ret, out = _exec_cmd(native_cmd_and_args, True)
+ else:
+ ret = 127
+ out = "can't find native executable %s in %s" % (args[0], native_paths)
+
+ prog = args[0]
+ # shell command-not-found
+ if ret == 127 \
+ or (pseudo and ret == 1 and out == "Can't find '%s' in $PATH." % prog):
+ msg = "A native program %s required to build the image "\
+ "was not found (see details above).\n\n" % prog
+ recipe = NATIVE_RECIPES.get(prog)
+ if recipe:
+ msg += "Please make sure wic-tools have %s-native in its DEPENDS, "\
+ "build it with 'bitbake wic-tools' and try again.\n" % recipe
+ else:
+ msg += "Wic failed to find a recipe to build native %s. Please "\
+ "file a bug against wic.\n" % prog
+ raise WicError(msg)
+
+ return ret, out
+
+BOOTDD_EXTRA_SPACE = 16384
+
+class BitbakeVars(defaultdict):
+ """
+ Container for Bitbake variables.
+ """
+ def __init__(self):
+ defaultdict.__init__(self, dict)
+
+ # default_image and vars_dir attributes should be set from outside
+ self.default_image = None
+ self.vars_dir = None
+
+ def _parse_line(self, line, image, matcher=re.compile(r"^([a-zA-Z0-9\-_+./~]+)=(.*)")):
+ """
+ Parse one line from bitbake -e output or from .env file.
+ Put result key-value pair into the storage.
+ """
+ if "=" not in line:
+ return
+ match = matcher.match(line)
+ if not match:
+ return
+ key, val = match.groups()
+ self[image][key] = val.strip('"')
+
+ def get_var(self, var, image=None, cache=True):
+ """
+ Get bitbake variable from 'bitbake -e' output or from .env file.
+ This is a lazy method, i.e. it runs bitbake or parses file only when
+ only when variable is requested. It also caches results.
+ """
+ if not image:
+ image = self.default_image
+
+ if image not in self:
+ if image and self.vars_dir:
+ fname = os.path.join(self.vars_dir, image + '.env')
+ if os.path.isfile(fname):
+ # parse .env file
+ with open(fname) as varsfile:
+ for line in varsfile:
+ self._parse_line(line, image)
+ else:
+ print("Couldn't get bitbake variable from %s." % fname)
+ print("File %s doesn't exist." % fname)
+ return
+ else:
+ # Get bitbake -e output
+ cmd = "bitbake -e"
+ if image:
+ cmd += " %s" % image
+
+ log_level = logger.getEffectiveLevel()
+ logger.setLevel(logging.INFO)
+ ret, lines = _exec_cmd(cmd)
+ logger.setLevel(log_level)
+
+ if ret:
+ logger.error("Couldn't get '%s' output.", cmd)
+ logger.error("Bitbake failed with error:\n%s\n", lines)
+ return
+
+ # Parse bitbake -e output
+ for line in lines.split('\n'):
+ self._parse_line(line, image)
+
+ # Make first image a default set of variables
+ if cache:
+ images = [key for key in self if key]
+ if len(images) == 1:
+ self[None] = self[image]
+
+ result = self[image].get(var)
+ if not cache:
+ self.pop(image, None)
+
+ return result
+
+# Create BB_VARS singleton
+BB_VARS = BitbakeVars()
+
+def get_bitbake_var(var, image=None, cache=True):
+ """
+ Provide old get_bitbake_var API by wrapping
+ get_var method of BB_VARS singleton.
+ """
+ return BB_VARS.get_var(var, image, cache)
diff --git a/scripts/lib/wic/msger.py b/scripts/lib/wic/msger.py
deleted file mode 100644
index b737554228..0000000000
--- a/scripts/lib/wic/msger.py
+++ /dev/null
@@ -1,309 +0,0 @@
-#!/usr/bin/env python -tt
-# vim: ai ts=4 sts=4 et sw=4
-#
-# Copyright (c) 2009, 2010, 2011 Intel, Inc.
-#
-# This program 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; version 2 of the License
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-import os
-import sys
-import re
-import time
-
-__ALL__ = ['set_mode',
- 'get_loglevel',
- 'set_loglevel',
- 'set_logfile',
- 'raw',
- 'debug',
- 'verbose',
- 'info',
- 'warning',
- 'error',
- 'ask',
- 'pause',
- ]
-
-# COLORs in ANSI
-INFO_COLOR = 32 # green
-WARN_COLOR = 33 # yellow
-ERR_COLOR = 31 # red
-ASK_COLOR = 34 # blue
-NO_COLOR = 0
-
-PREFIX_RE = re.compile('^<(.*?)>\s*(.*)', re.S)
-
-INTERACTIVE = True
-
-LOG_LEVEL = 1
-LOG_LEVELS = {
- 'quiet': 0,
- 'normal': 1,
- 'verbose': 2,
- 'debug': 3,
- 'never': 4,
-}
-
-LOG_FILE_FP = None
-LOG_CONTENT = ''
-CATCHERR_BUFFILE_FD = -1
-CATCHERR_BUFFILE_PATH = None
-CATCHERR_SAVED_2 = -1
-
-def _general_print(head, color, msg=None, stream=None, level='normal'):
- global LOG_CONTENT
- if not stream:
- stream = sys.stdout
-
- if LOG_LEVELS[level] > LOG_LEVEL:
- # skip
- return
-
- # encode raw 'unicode' str to utf8 encoded str
- if msg and isinstance(msg, unicode):
- msg = msg.encode('utf-8', 'ignore')
-
- errormsg = ''
- if CATCHERR_BUFFILE_FD > 0:
- size = os.lseek(CATCHERR_BUFFILE_FD, 0, os.SEEK_END)
- os.lseek(CATCHERR_BUFFILE_FD, 0, os.SEEK_SET)
- errormsg = os.read(CATCHERR_BUFFILE_FD, size)
- os.ftruncate(CATCHERR_BUFFILE_FD, 0)
-
- # append error msg to LOG
- if errormsg:
- LOG_CONTENT += errormsg
-
- # append normal msg to LOG
- save_msg = msg.strip() if msg else None
- if save_msg:
- timestr = time.strftime("[%m/%d %H:%M:%S %Z] ", time.localtime())
- LOG_CONTENT += timestr + save_msg + '\n'
-
- if errormsg:
- _color_print('', NO_COLOR, errormsg, stream, level)
-
- _color_print(head, color, msg, stream, level)
-
-def _color_print(head, color, msg, stream, level):
- colored = True
- if color == NO_COLOR or \
- not stream.isatty() or \
- os.getenv('ANSI_COLORS_DISABLED') is not None:
- colored = False
-
- if head.startswith('\r'):
- # need not \n at last
- newline = False
- else:
- newline = True
-
- if colored:
- head = '\033[%dm%s:\033[0m ' %(color, head)
- if not newline:
- # ESC cmd to clear line
- head = '\033[2K' + head
- else:
- if head:
- head += ': '
- if head.startswith('\r'):
- head = head.lstrip()
- newline = True
-
- if msg is not None:
- if isinstance(msg, unicode):
- msg = msg.encode('utf8', 'ignore')
-
- stream.write('%s%s' % (head, msg))
- if newline:
- stream.write('\n')
-
- stream.flush()
-
-def _color_perror(head, color, msg, level='normal'):
- if CATCHERR_BUFFILE_FD > 0:
- _general_print(head, color, msg, sys.stdout, level)
- else:
- _general_print(head, color, msg, sys.stderr, level)
-
-def _split_msg(head, msg):
- if isinstance(msg, list):
- msg = '\n'.join(map(str, msg))
-
- if msg.startswith('\n'):
- # means print \n at first
- msg = msg.lstrip()
- head = '\n' + head
-
- elif msg.startswith('\r'):
- # means print \r at first
- msg = msg.lstrip()
- head = '\r' + head
-
- match = PREFIX_RE.match(msg)
- if match:
- head += ' <%s>' % match.group(1)
- msg = match.group(2)
-
- return head, msg
-
-def get_loglevel():
- return (k for k, v in LOG_LEVELS.items() if v == LOG_LEVEL).next()
-
-def set_loglevel(level):
- global LOG_LEVEL
- if level not in LOG_LEVELS:
- # no effect
- return
-
- LOG_LEVEL = LOG_LEVELS[level]
-
-def set_interactive(mode=True):
- global INTERACTIVE
- if mode:
- INTERACTIVE = True
- else:
- INTERACTIVE = False
-
-def log(msg=''):
- # log msg to LOG_CONTENT then save to logfile
- global LOG_CONTENT
- if msg:
- LOG_CONTENT += msg
-
-def raw(msg=''):
- _general_print('', NO_COLOR, msg)
-
-def info(msg):
- head, msg = _split_msg('Info', msg)
- _general_print(head, INFO_COLOR, msg)
-
-def verbose(msg):
- head, msg = _split_msg('Verbose', msg)
- _general_print(head, INFO_COLOR, msg, level='verbose')
-
-def warning(msg):
- head, msg = _split_msg('Warning', msg)
- _color_perror(head, WARN_COLOR, msg)
-
-def debug(msg):
- head, msg = _split_msg('Debug', msg)
- _color_perror(head, ERR_COLOR, msg, level='debug')
-
-def error(msg):
- head, msg = _split_msg('Error', msg)
- _color_perror(head, ERR_COLOR, msg)
- sys.exit(1)
-
-def ask(msg, default=True):
- _general_print('\rQ', ASK_COLOR, '')
- try:
- if default:
- msg += '(Y/n) '
- else:
- msg += '(y/N) '
- if INTERACTIVE:
- while True:
- repl = raw_input(msg)
- if repl.lower() == 'y':
- return True
- elif repl.lower() == 'n':
- return False
- elif not repl.strip():
- # <Enter>
- return default
-
- # else loop
- else:
- if default:
- msg += ' Y'
- else:
- msg += ' N'
- _general_print('', NO_COLOR, msg)
-
- return default
- except KeyboardInterrupt:
- sys.stdout.write('\n')
- sys.exit(2)
-
-def choice(msg, choices, default=0):
- if default >= len(choices):
- return None
- _general_print('\rQ', ASK_COLOR, '')
- try:
- msg += " [%s] " % '/'.join(choices)
- if INTERACTIVE:
- while True:
- repl = raw_input(msg)
- if repl in choices:
- return repl
- elif not repl.strip():
- return choices[default]
- else:
- msg += choices[default]
- _general_print('', NO_COLOR, msg)
-
- return choices[default]
- except KeyboardInterrupt:
- sys.stdout.write('\n')
- sys.exit(2)
-
-def pause(msg=None):
- if INTERACTIVE:
- _general_print('\rQ', ASK_COLOR, '')
- if msg is None:
- msg = 'press <ENTER> to continue ...'
- raw_input(msg)
-
-def set_logfile(fpath):
- global LOG_FILE_FP
-
- def _savelogf():
- if LOG_FILE_FP:
- with open(LOG_FILE_FP, 'w') as log:
- log.write(LOG_CONTENT)
-
- if LOG_FILE_FP is not None:
- warning('duplicate log file configuration')
-
- LOG_FILE_FP = fpath
-
- import atexit
- atexit.register(_savelogf)
-
-def enable_logstderr(fpath):
- global CATCHERR_BUFFILE_FD
- global CATCHERR_BUFFILE_PATH
- global CATCHERR_SAVED_2
-
- if os.path.exists(fpath):
- os.remove(fpath)
- CATCHERR_BUFFILE_PATH = fpath
- CATCHERR_BUFFILE_FD = os.open(CATCHERR_BUFFILE_PATH, os.O_RDWR|os.O_CREAT)
- CATCHERR_SAVED_2 = os.dup(2)
- os.dup2(CATCHERR_BUFFILE_FD, 2)
-
-def disable_logstderr():
- global CATCHERR_BUFFILE_FD
- global CATCHERR_BUFFILE_PATH
- global CATCHERR_SAVED_2
-
- raw(msg=None) # flush message buffer and print it.
- os.dup2(CATCHERR_SAVED_2, 2)
- os.close(CATCHERR_SAVED_2)
- os.close(CATCHERR_BUFFILE_FD)
- os.unlink(CATCHERR_BUFFILE_PATH)
- CATCHERR_BUFFILE_FD = -1
- CATCHERR_BUFFILE_PATH = None
- CATCHERR_SAVED_2 = -1
diff --git a/scripts/lib/wic/partition.py b/scripts/lib/wic/partition.py
new file mode 100644
index 0000000000..a25834048e
--- /dev/null
+++ b/scripts/lib/wic/partition.py
@@ -0,0 +1,496 @@
+#
+# Copyright (c) 2013-2016 Intel Corporation.
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# DESCRIPTION
+# This module provides the OpenEmbedded partition object definitions.
+#
+# AUTHORS
+# Tom Zanussi <tom.zanussi (at] linux.intel.com>
+# Ed Bartosh <ed.bartosh> (at] linux.intel.com>
+
+import logging
+import os
+import uuid
+
+from wic import WicError
+from wic.misc import exec_cmd, exec_native_cmd, get_bitbake_var
+from wic.pluginbase import PluginMgr
+
+logger = logging.getLogger('wic')
+
+class Partition():
+
+ def __init__(self, args, lineno):
+ self.args = args
+ self.active = args.active
+ self.align = args.align
+ self.disk = args.disk
+ self.device = None
+ self.extra_space = args.extra_space
+ self.exclude_path = args.exclude_path
+ self.include_path = args.include_path
+ self.change_directory = args.change_directory
+ self.fsopts = args.fsopts
+ self.fstype = args.fstype
+ self.label = args.label
+ self.use_label = args.use_label
+ self.mkfs_extraopts = args.mkfs_extraopts
+ self.mountpoint = args.mountpoint
+ self.no_table = args.no_table
+ self.num = None
+ self.offset = args.offset
+ self.overhead_factor = args.overhead_factor
+ self.part_name = args.part_name
+ self.part_type = args.part_type
+ self.rootfs_dir = args.rootfs_dir
+ self.size = args.size
+ self.fixed_size = args.fixed_size
+ self.source = args.source
+ self.sourceparams = args.sourceparams
+ self.system_id = args.system_id
+ self.use_uuid = args.use_uuid
+ self.uuid = args.uuid
+ self.fsuuid = args.fsuuid
+ self.type = args.type
+ self.no_fstab_update = args.no_fstab_update
+ self.updated_fstab_path = None
+ self.has_fstab = False
+ self.update_fstab_in_rootfs = False
+
+ self.lineno = lineno
+ self.source_file = ""
+
+ def get_extra_block_count(self, current_blocks):
+ """
+ The --size param is reflected in self.size (in kB), and we already
+ have current_blocks (1k) blocks, calculate and return the
+ number of (1k) blocks we need to add to get to --size, 0 if
+ we're already there or beyond.
+ """
+ logger.debug("Requested partition size for %s: %d",
+ self.mountpoint, self.size)
+
+ if not self.size:
+ return 0
+
+ requested_blocks = self.size
+
+ logger.debug("Requested blocks %d, current_blocks %d",
+ requested_blocks, current_blocks)
+
+ if requested_blocks > current_blocks:
+ return requested_blocks - current_blocks
+ else:
+ return 0
+
+ def get_rootfs_size(self, actual_rootfs_size=0):
+ """
+ Calculate the required size of rootfs taking into consideration
+ --size/--fixed-size flags as well as overhead and extra space, as
+ specified in kickstart file. Raises an error if the
+ `actual_rootfs_size` is larger than fixed-size rootfs.
+
+ """
+ if self.fixed_size:
+ rootfs_size = self.fixed_size
+ if actual_rootfs_size > rootfs_size:
+ raise WicError("Actual rootfs size (%d kB) is larger than "
+ "allowed size %d kB" %
+ (actual_rootfs_size, rootfs_size))
+ else:
+ extra_blocks = self.get_extra_block_count(actual_rootfs_size)
+ if extra_blocks < self.extra_space:
+ extra_blocks = self.extra_space
+
+ rootfs_size = actual_rootfs_size + extra_blocks
+ rootfs_size = int(rootfs_size * self.overhead_factor)
+
+ logger.debug("Added %d extra blocks to %s to get to %d total blocks",
+ extra_blocks, self.mountpoint, rootfs_size)
+
+ return rootfs_size
+
+ @property
+ def disk_size(self):
+ """
+ Obtain on-disk size of partition taking into consideration
+ --size/--fixed-size options.
+
+ """
+ return self.fixed_size if self.fixed_size else self.size
+
+ def prepare(self, creator, cr_workdir, oe_builddir, rootfs_dir,
+ bootimg_dir, kernel_dir, native_sysroot, updated_fstab_path):
+ """
+ Prepare content for individual partitions, depending on
+ partition command parameters.
+ """
+ self.updated_fstab_path = updated_fstab_path
+ if self.updated_fstab_path and not (self.fstype.startswith("ext") or self.fstype == "msdos"):
+ self.update_fstab_in_rootfs = True
+
+ if not self.source:
+ if not self.size and not self.fixed_size:
+ raise WicError("The %s partition has a size of zero. Please "
+ "specify a non-zero --size/--fixed-size for that "
+ "partition." % self.mountpoint)
+
+ if self.fstype == "swap":
+ self.prepare_swap_partition(cr_workdir, oe_builddir,
+ native_sysroot)
+ self.source_file = "%s/fs.%s" % (cr_workdir, self.fstype)
+ else:
+ if self.fstype in ('squashfs', 'erofs'):
+ raise WicError("It's not possible to create empty %s "
+ "partition '%s'" % (self.fstype, self.mountpoint))
+
+ rootfs = "%s/fs_%s.%s.%s" % (cr_workdir, self.label,
+ self.lineno, self.fstype)
+ if os.path.isfile(rootfs):
+ os.remove(rootfs)
+
+ prefix = "ext" if self.fstype.startswith("ext") else self.fstype
+ method = getattr(self, "prepare_empty_partition_" + prefix)
+ method(rootfs, oe_builddir, native_sysroot)
+ self.source_file = rootfs
+ return
+
+ plugins = PluginMgr.get_plugins('source')
+
+ if self.source not in plugins:
+ raise WicError("The '%s' --source specified for %s doesn't exist.\n\t"
+ "See 'wic list source-plugins' for a list of available"
+ " --sources.\n\tSee 'wic help source-plugins' for "
+ "details on adding a new source plugin." %
+ (self.source, self.mountpoint))
+
+ srcparams_dict = {}
+ if self.sourceparams:
+ # Split sourceparams string of the form key1=val1[,key2=val2,...]
+ # into a dict. Also accepts valueless keys i.e. without =
+ splitted = self.sourceparams.split(',')
+ srcparams_dict = dict(par.split('=', 1) for par in splitted if par)
+
+ plugin = PluginMgr.get_plugins('source')[self.source]
+ plugin.do_configure_partition(self, srcparams_dict, creator,
+ cr_workdir, oe_builddir, bootimg_dir,
+ kernel_dir, native_sysroot)
+ plugin.do_stage_partition(self, srcparams_dict, creator,
+ cr_workdir, oe_builddir, bootimg_dir,
+ kernel_dir, native_sysroot)
+ plugin.do_prepare_partition(self, srcparams_dict, creator,
+ cr_workdir, oe_builddir, bootimg_dir,
+ kernel_dir, rootfs_dir, native_sysroot)
+ plugin.do_post_partition(self, srcparams_dict, creator,
+ cr_workdir, oe_builddir, bootimg_dir,
+ kernel_dir, rootfs_dir, native_sysroot)
+
+ # further processing required Partition.size to be an integer, make
+ # sure that it is one
+ if not isinstance(self.size, int):
+ raise WicError("Partition %s internal size is not an integer. "
+ "This a bug in source plugin %s and needs to be fixed." %
+ (self.mountpoint, self.source))
+
+ if self.fixed_size and self.size > self.fixed_size:
+ raise WicError("File system image of partition %s is "
+ "larger (%d kB) than its allowed size %d kB" %
+ (self.mountpoint, self.size, self.fixed_size))
+
+ def prepare_rootfs(self, cr_workdir, oe_builddir, rootfs_dir,
+ native_sysroot, real_rootfs = True, pseudo_dir = None):
+ """
+ Prepare content for a rootfs partition i.e. create a partition
+ and fill it from a /rootfs dir.
+
+ Currently handles ext2/3/4, btrfs, vfat and squashfs.
+ """
+
+ rootfs = "%s/rootfs_%s.%s.%s" % (cr_workdir, self.label,
+ self.lineno, self.fstype)
+ if os.path.isfile(rootfs):
+ os.remove(rootfs)
+
+ p_prefix = os.environ.get("PSEUDO_PREFIX", "%s/usr" % native_sysroot)
+ if (pseudo_dir):
+ # Canonicalize the ignore paths. This corresponds to
+ # calling oe.path.canonicalize(), which is used in bitbake.conf.
+ ignore_paths = [rootfs] + (get_bitbake_var("PSEUDO_IGNORE_PATHS") or "").split(",")
+ canonical_paths = []
+ for path in ignore_paths:
+ if "$" not in path:
+ trailing_slash = path.endswith("/") and "/" or ""
+ canonical_paths.append(os.path.realpath(path) + trailing_slash)
+ ignore_paths = ",".join(canonical_paths)
+
+ pseudo = "export PSEUDO_PREFIX=%s;" % p_prefix
+ pseudo += "export PSEUDO_LOCALSTATEDIR=%s;" % pseudo_dir
+ pseudo += "export PSEUDO_PASSWD=%s;" % rootfs_dir
+ pseudo += "export PSEUDO_NOSYMLINKEXP=1;"
+ pseudo += "export PSEUDO_IGNORE_PATHS=%s;" % ignore_paths
+ pseudo += "%s " % get_bitbake_var("FAKEROOTCMD")
+ else:
+ pseudo = None
+
+ if not self.size and real_rootfs:
+ # The rootfs size is not set in .ks file so try to get it
+ # from bitbake variable
+ rsize_bb = get_bitbake_var('ROOTFS_SIZE')
+ rdir = get_bitbake_var('IMAGE_ROOTFS')
+ if rsize_bb and rdir == rootfs_dir:
+ # Bitbake variable ROOTFS_SIZE is calculated in
+ # Image._get_rootfs_size method from meta/lib/oe/image.py
+ # using IMAGE_ROOTFS_SIZE, IMAGE_ROOTFS_ALIGNMENT,
+ # IMAGE_OVERHEAD_FACTOR and IMAGE_ROOTFS_EXTRA_SPACE
+ self.size = int(round(float(rsize_bb)))
+ else:
+ # Bitbake variable ROOTFS_SIZE is not defined so compute it
+ # from the rootfs_dir size using the same logic found in
+ # get_rootfs_size() from meta/classes/image.bbclass
+ du_cmd = "du -ks %s" % rootfs_dir
+ out = exec_cmd(du_cmd)
+ self.size = int(out.split()[0])
+
+ prefix = "ext" if self.fstype.startswith("ext") else self.fstype
+ method = getattr(self, "prepare_rootfs_" + prefix)
+ method(rootfs, cr_workdir, oe_builddir, rootfs_dir, native_sysroot, pseudo)
+ self.source_file = rootfs
+
+ # get the rootfs size in the right units for kickstart (kB)
+ du_cmd = "du -Lbks %s" % rootfs
+ out = exec_cmd(du_cmd)
+ self.size = int(out.split()[0])
+
+ def prepare_rootfs_ext(self, rootfs, cr_workdir, oe_builddir, rootfs_dir,
+ native_sysroot, pseudo):
+ """
+ Prepare content for an ext2/3/4 rootfs partition.
+ """
+ du_cmd = "du -ks %s" % rootfs_dir
+ out = exec_cmd(du_cmd)
+ actual_rootfs_size = int(out.split()[0])
+
+ rootfs_size = self.get_rootfs_size(actual_rootfs_size)
+
+ with open(rootfs, 'w') as sparse:
+ os.ftruncate(sparse.fileno(), rootfs_size * 1024)
+
+ extraopts = self.mkfs_extraopts or "-F -i 8192"
+
+ label_str = ""
+ if self.label:
+ label_str = "-L %s" % self.label
+
+ mkfs_cmd = "mkfs.%s %s %s %s -U %s -d %s" % \
+ (self.fstype, extraopts, rootfs, label_str, self.fsuuid, rootfs_dir)
+ exec_native_cmd(mkfs_cmd, native_sysroot, pseudo=pseudo)
+
+ if self.updated_fstab_path and self.has_fstab and not self.no_fstab_update:
+ debugfs_script_path = os.path.join(cr_workdir, "debugfs_script")
+ with open(debugfs_script_path, "w") as f:
+ f.write("cd etc\n")
+ f.write("rm fstab\n")
+ f.write("write %s fstab\n" % (self.updated_fstab_path))
+ debugfs_cmd = "debugfs -w -f %s %s" % (debugfs_script_path, rootfs)
+ exec_native_cmd(debugfs_cmd, native_sysroot)
+
+ mkfs_cmd = "fsck.%s -pvfD %s" % (self.fstype, rootfs)
+ exec_native_cmd(mkfs_cmd, native_sysroot, pseudo=pseudo)
+
+ self.check_for_Y2038_problem(rootfs, native_sysroot)
+
+ def prepare_rootfs_btrfs(self, rootfs, cr_workdir, oe_builddir, rootfs_dir,
+ native_sysroot, pseudo):
+ """
+ Prepare content for a btrfs rootfs partition.
+ """
+ du_cmd = "du -ks %s" % rootfs_dir
+ out = exec_cmd(du_cmd)
+ actual_rootfs_size = int(out.split()[0])
+
+ rootfs_size = self.get_rootfs_size(actual_rootfs_size)
+
+ with open(rootfs, 'w') as sparse:
+ os.ftruncate(sparse.fileno(), rootfs_size * 1024)
+
+ label_str = ""
+ if self.label:
+ label_str = "-L %s" % self.label
+
+ mkfs_cmd = "mkfs.%s -b %d -r %s %s %s -U %s %s" % \
+ (self.fstype, rootfs_size * 1024, rootfs_dir, label_str,
+ self.mkfs_extraopts, self.fsuuid, rootfs)
+ exec_native_cmd(mkfs_cmd, native_sysroot, pseudo=pseudo)
+
+ def prepare_rootfs_msdos(self, rootfs, cr_workdir, oe_builddir, rootfs_dir,
+ native_sysroot, pseudo):
+ """
+ Prepare content for a msdos/vfat rootfs partition.
+ """
+ du_cmd = "du -bks %s" % rootfs_dir
+ out = exec_cmd(du_cmd)
+ blocks = int(out.split()[0])
+
+ rootfs_size = self.get_rootfs_size(blocks)
+
+ label_str = "-n boot"
+ if self.label:
+ label_str = "-n %s" % self.label
+
+ size_str = ""
+
+ extraopts = self.mkfs_extraopts or '-S 512'
+
+ dosfs_cmd = "mkdosfs %s -i %s %s %s -C %s %d" % \
+ (label_str, self.fsuuid, size_str, extraopts, rootfs,
+ rootfs_size)
+ exec_native_cmd(dosfs_cmd, native_sysroot)
+
+ mcopy_cmd = "mcopy -i %s -s %s/* ::/" % (rootfs, rootfs_dir)
+ exec_native_cmd(mcopy_cmd, native_sysroot)
+
+ if self.updated_fstab_path and self.has_fstab and not self.no_fstab_update:
+ mcopy_cmd = "mcopy -i %s %s ::/etc/fstab" % (rootfs, self.updated_fstab_path)
+ exec_native_cmd(mcopy_cmd, native_sysroot)
+
+ chmod_cmd = "chmod 644 %s" % rootfs
+ exec_cmd(chmod_cmd)
+
+ prepare_rootfs_vfat = prepare_rootfs_msdos
+
+ def prepare_rootfs_squashfs(self, rootfs, cr_workdir, oe_builddir, rootfs_dir,
+ native_sysroot, pseudo):
+ """
+ Prepare content for a squashfs rootfs partition.
+ """
+ extraopts = self.mkfs_extraopts or '-noappend'
+ squashfs_cmd = "mksquashfs %s %s %s" % \
+ (rootfs_dir, rootfs, extraopts)
+ exec_native_cmd(squashfs_cmd, native_sysroot, pseudo=pseudo)
+
+ def prepare_rootfs_erofs(self, rootfs, cr_workdir, oe_builddir, rootfs_dir,
+ native_sysroot, pseudo):
+ """
+ Prepare content for a erofs rootfs partition.
+ """
+ extraopts = self.mkfs_extraopts or ''
+ erofs_cmd = "mkfs.erofs %s -U %s %s %s" % \
+ (extraopts, self.fsuuid, rootfs, rootfs_dir)
+ exec_native_cmd(erofs_cmd, native_sysroot, pseudo=pseudo)
+
+ def prepare_empty_partition_ext(self, rootfs, oe_builddir,
+ native_sysroot):
+ """
+ Prepare an empty ext2/3/4 partition.
+ """
+ size = self.disk_size
+ with open(rootfs, 'w') as sparse:
+ os.ftruncate(sparse.fileno(), size * 1024)
+
+ extraopts = self.mkfs_extraopts or "-i 8192"
+
+ label_str = ""
+ if self.label:
+ label_str = "-L %s" % self.label
+
+ mkfs_cmd = "mkfs.%s -F %s %s -U %s %s" % \
+ (self.fstype, extraopts, label_str, self.fsuuid, rootfs)
+ exec_native_cmd(mkfs_cmd, native_sysroot)
+
+ self.check_for_Y2038_problem(rootfs, native_sysroot)
+
+ def prepare_empty_partition_btrfs(self, rootfs, oe_builddir,
+ native_sysroot):
+ """
+ Prepare an empty btrfs partition.
+ """
+ size = self.disk_size
+ with open(rootfs, 'w') as sparse:
+ os.ftruncate(sparse.fileno(), size * 1024)
+
+ label_str = ""
+ if self.label:
+ label_str = "-L %s" % self.label
+
+ mkfs_cmd = "mkfs.%s -b %d %s -U %s %s %s" % \
+ (self.fstype, self.size * 1024, label_str, self.fsuuid,
+ self.mkfs_extraopts, rootfs)
+ exec_native_cmd(mkfs_cmd, native_sysroot)
+
+ def prepare_empty_partition_msdos(self, rootfs, oe_builddir,
+ native_sysroot):
+ """
+ Prepare an empty vfat partition.
+ """
+ blocks = self.disk_size
+
+ label_str = "-n boot"
+ if self.label:
+ label_str = "-n %s" % self.label
+
+ size_str = ""
+
+ extraopts = self.mkfs_extraopts or '-S 512'
+
+ dosfs_cmd = "mkdosfs %s -i %s %s %s -C %s %d" % \
+ (label_str, self.fsuuid, extraopts, size_str, rootfs,
+ blocks)
+
+ exec_native_cmd(dosfs_cmd, native_sysroot)
+
+ chmod_cmd = "chmod 644 %s" % rootfs
+ exec_cmd(chmod_cmd)
+
+ prepare_empty_partition_vfat = prepare_empty_partition_msdos
+
+ def prepare_swap_partition(self, cr_workdir, oe_builddir, native_sysroot):
+ """
+ Prepare a swap partition.
+ """
+ path = "%s/fs.%s" % (cr_workdir, self.fstype)
+
+ with open(path, 'w') as sparse:
+ os.ftruncate(sparse.fileno(), self.size * 1024)
+
+ label_str = ""
+ if self.label:
+ label_str = "-L %s" % self.label
+
+ mkswap_cmd = "mkswap %s -U %s %s" % (label_str, self.fsuuid, path)
+ exec_native_cmd(mkswap_cmd, native_sysroot)
+
+ def check_for_Y2038_problem(self, rootfs, native_sysroot):
+ """
+ Check if the filesystem is affected by the Y2038 problem
+ (Y2038 problem = 32 bit time_t overflow in January 2038)
+ """
+ def get_err_str(part):
+ err = "The {} filesystem {} has no Y2038 support."
+ if part.mountpoint:
+ args = [part.fstype, "mounted at %s" % part.mountpoint]
+ elif part.label:
+ args = [part.fstype, "labeled '%s'" % part.label]
+ elif part.part_name:
+ args = [part.fstype, "in partition '%s'" % part.part_name]
+ else:
+ args = [part.fstype, "in partition %s" % part.num]
+ return err.format(*args)
+
+ # ext2 and ext3 are always affected by the Y2038 problem
+ if self.fstype in ["ext2", "ext3"]:
+ logger.warn(get_err_str(self))
+ return
+
+ ret, out = exec_native_cmd("dumpe2fs %s" % rootfs, native_sysroot)
+
+ # if ext4 is affected by the Y2038 problem depends on the inode size
+ for line in out.splitlines():
+ if line.startswith("Inode size:"):
+ size = int(line.split(":")[1].strip())
+ if size < 256:
+ logger.warn("%s Inodes (of size %d) are too small." %
+ (get_err_str(self), size))
+ break
+
diff --git a/scripts/lib/wic/plugin.py b/scripts/lib/wic/plugin.py
deleted file mode 100644
index ccfdfcb934..0000000000
--- a/scripts/lib/wic/plugin.py
+++ /dev/null
@@ -1,150 +0,0 @@
-#!/usr/bin/env python -tt
-#
-# Copyright (c) 2011 Intel, Inc.
-#
-# This program 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; version 2 of the License
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-import os, sys
-
-from wic import msger
-from wic import pluginbase
-from wic.utils import errors
-from wic.utils.oe.misc import get_bitbake_var
-
-__ALL__ = ['PluginMgr', 'pluginmgr']
-
-PLUGIN_TYPES = ["imager", "source"]
-
-PLUGIN_DIR = "/lib/wic/plugins" # relative to scripts
-SCRIPTS_PLUGIN_DIR = "scripts" + PLUGIN_DIR
-
-class PluginMgr(object):
- plugin_dirs = {}
-
- # make the manager class as singleton
- _instance = None
- def __new__(cls, *args, **kwargs):
- if not cls._instance:
- cls._instance = super(PluginMgr, cls).__new__(cls, *args, **kwargs)
-
- return cls._instance
-
- def __init__(self):
- wic_path = os.path.dirname(__file__)
- eos = wic_path.find('scripts') + len('scripts')
- scripts_path = wic_path[:eos]
- self.scripts_path = scripts_path
- self.plugin_dir = scripts_path + PLUGIN_DIR
- self.layers_path = None
-
- def _build_plugin_dir_list(self, plugin_dir, ptype):
- if self.layers_path is None:
- self.layers_path = get_bitbake_var("BBLAYERS")
- layer_dirs = []
-
- if self.layers_path is not None:
- for layer_path in self.layers_path.split():
- path = os.path.join(layer_path, SCRIPTS_PLUGIN_DIR, ptype)
- layer_dirs.append(path)
-
- path = os.path.join(plugin_dir, ptype)
- layer_dirs.append(path)
-
- return layer_dirs
-
- def append_dirs(self, dirs):
- for path in dirs:
- self._add_plugindir(path)
-
- # load all the plugins AGAIN
- self._load_all()
-
- def _add_plugindir(self, path):
- path = os.path.abspath(os.path.expanduser(path))
-
- if not os.path.isdir(path):
- return
-
- if path not in self.plugin_dirs:
- self.plugin_dirs[path] = False
- # the value True/False means "loaded"
-
- def _load_all(self):
- for (pdir, loaded) in self.plugin_dirs.iteritems():
- if loaded:
- continue
-
- sys.path.insert(0, pdir)
- for mod in [x[:-3] for x in os.listdir(pdir) if x.endswith(".py")]:
- if mod and mod != '__init__':
- if mod in sys.modules:
- #self.plugin_dirs[pdir] = True
- msger.warning("Module %s already exists, skip" % mod)
- else:
- try:
- pymod = __import__(mod)
- self.plugin_dirs[pdir] = True
- msger.debug("Plugin module %s:%s imported"\
- % (mod, pymod.__file__))
- except ImportError, err:
- msg = 'Failed to load plugin %s/%s: %s' \
- % (os.path.basename(pdir), mod, err)
- msger.warning(msg)
-
- del sys.path[0]
-
- def get_plugins(self, ptype):
- """ the return value is dict of name:class pairs """
-
- if ptype not in PLUGIN_TYPES:
- raise errors.CreatorError('%s is not valid plugin type' % ptype)
-
- plugins_dir = self._build_plugin_dir_list(self.plugin_dir, ptype)
-
- self.append_dirs(plugins_dir)
-
- return pluginbase.get_plugins(ptype)
-
- def get_source_plugins(self):
- """
- Return list of available source plugins.
- """
- plugins_dir = self._build_plugin_dir_list(self.plugin_dir, 'source')
-
- self.append_dirs(plugins_dir)
-
- return self.get_plugins('source')
-
-
- def get_source_plugin_methods(self, source_name, methods):
- """
- The methods param is a dict with the method names to find. On
- return, the dict values will be filled in with pointers to the
- corresponding methods. If one or more methods are not found,
- None is returned.
- """
- return_methods = None
- for _source_name, klass in self.get_plugins('source').iteritems():
- if _source_name == source_name:
- for _method_name in methods.keys():
- if not hasattr(klass, _method_name):
- msger.warning("Unimplemented %s source interface for: %s"\
- % (_method_name, _source_name))
- return None
- func = getattr(klass, _method_name)
- methods[_method_name] = func
- return_methods = methods
- return return_methods
-
-pluginmgr = PluginMgr()
diff --git a/scripts/lib/wic/pluginbase.py b/scripts/lib/wic/pluginbase.py
index ee8fe95c6f..d9b4e57747 100644
--- a/scripts/lib/wic/pluginbase.py
+++ b/scripts/lib/wic/pluginbase.py
@@ -1,48 +1,79 @@
-#!/usr/bin/env python -tt
+#!/usr/bin/env python3
#
# Copyright (c) 2011 Intel, Inc.
#
-# This program 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; version 2 of the License
+# SPDX-License-Identifier: GPL-2.0-only
#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-from wic import msger
+__all__ = ['ImagerPlugin', 'SourcePlugin']
+
+import os
+import logging
+
+from collections import defaultdict
+from importlib.machinery import SourceFileLoader
-class _Plugin(object):
- class __metaclass__(type):
- def __init__(cls, name, bases, attrs):
- if not hasattr(cls, 'plugins'):
- cls.plugins = {}
+from wic import WicError
+from wic.misc import get_bitbake_var
- elif 'wic_plugin_type' in attrs:
- if attrs['wic_plugin_type'] not in cls.plugins:
- cls.plugins[attrs['wic_plugin_type']] = {}
+PLUGIN_TYPES = ["imager", "source"]
- elif hasattr(cls, 'wic_plugin_type') and 'name' in attrs:
- cls.plugins[cls.wic_plugin_type][attrs['name']] = cls
+SCRIPTS_PLUGIN_DIR = ["scripts/lib/wic/plugins", "lib/wic/plugins"]
- def show_plugins(cls):
- for cls in cls.plugins[cls.wic_plugin_type]:
- print cls
+logger = logging.getLogger('wic')
- def get_plugins(cls):
- return cls.plugins
+PLUGINS = defaultdict(dict)
+class PluginMgr:
+ _plugin_dirs = []
-class ImagerPlugin(_Plugin):
+ @classmethod
+ def get_plugins(cls, ptype):
+ """Get dictionary of <plugin_name>:<class> pairs."""
+ if ptype not in PLUGIN_TYPES:
+ raise WicError('%s is not valid plugin type' % ptype)
+
+ # collect plugin directories
+ if not cls._plugin_dirs:
+ cls._plugin_dirs = [os.path.join(os.path.dirname(__file__), 'plugins')]
+ layers = get_bitbake_var("BBLAYERS") or ''
+ for layer_path in layers.split():
+ for script_plugin_dir in SCRIPTS_PLUGIN_DIR:
+ path = os.path.join(layer_path, script_plugin_dir)
+ path = os.path.abspath(os.path.expanduser(path))
+ if path not in cls._plugin_dirs and os.path.isdir(path):
+ cls._plugin_dirs.insert(0, path)
+
+ if ptype not in PLUGINS:
+ # load all ptype plugins
+ for pdir in cls._plugin_dirs:
+ ppath = os.path.join(pdir, ptype)
+ if os.path.isdir(ppath):
+ for fname in os.listdir(ppath):
+ if fname.endswith('.py'):
+ mname = fname[:-3]
+ mpath = os.path.join(ppath, fname)
+ logger.debug("loading plugin module %s", mpath)
+ SourceFileLoader(mname, mpath).load_module()
+
+ return PLUGINS.get(ptype)
+
+class PluginMeta(type):
+ def __new__(cls, name, bases, attrs):
+ class_type = type.__new__(cls, name, bases, attrs)
+ if 'name' in attrs:
+ PLUGINS[class_type.wic_plugin_type][attrs['name']] = class_type
+
+ return class_type
+
+class ImagerPlugin(metaclass=PluginMeta):
wic_plugin_type = "imager"
+ def do_create(self):
+ raise WicError("Method %s.do_create is not implemented" %
+ self.__class__.__name__)
-class SourcePlugin(_Plugin):
+class SourcePlugin(metaclass=PluginMeta):
wic_plugin_type = "source"
"""
The methods that can be implemented by --source plugins.
@@ -58,7 +89,7 @@ class SourcePlugin(_Plugin):
disk image. This provides a hook to allow finalization of a
disk image e.g. to write an MBR to it.
"""
- msger.debug("SourcePlugin: do_install_disk: disk: %s" % disk_name)
+ logger.debug("SourcePlugin: do_install_disk: disk: %s", disk_name)
@classmethod
def do_stage_partition(cls, part, source_params, creator, cr_workdir,
@@ -75,7 +106,7 @@ class SourcePlugin(_Plugin):
Not that get_bitbake_var() allows you to acces non-standard
variables that you might want to use for this.
"""
- msger.debug("SourcePlugin: do_stage_partition: part: %s" % part)
+ logger.debug("SourcePlugin: do_stage_partition: part: %s", part)
@classmethod
def do_configure_partition(cls, part, source_params, creator, cr_workdir,
@@ -86,7 +117,7 @@ class SourcePlugin(_Plugin):
custom configuration files for a partition, for example
syslinux or grub config files.
"""
- msger.debug("SourcePlugin: do_configure_partition: part: %s" % part)
+ logger.debug("SourcePlugin: do_configure_partition: part: %s", part)
@classmethod
def do_prepare_partition(cls, part, source_params, creator, cr_workdir,
@@ -96,13 +127,14 @@ class SourcePlugin(_Plugin):
Called to do the actual content population for a partition i.e. it
'prepares' the partition to be incorporated into the image.
"""
- msger.debug("SourcePlugin: do_prepare_partition: part: %s" % part)
-
-def get_plugins(typen):
- plugins = ImagerPlugin.get_plugins()
- if typen in plugins:
- return plugins[typen]
- else:
- return None
+ logger.debug("SourcePlugin: do_prepare_partition: part: %s", part)
-__all__ = ['ImagerPlugin', 'SourcePlugin', 'get_plugins']
+ @classmethod
+ def do_post_partition(cls, part, source_params, creator, cr_workdir,
+ oe_builddir, bootimg_dir, kernel_dir, rootfs_dir,
+ native_sysroot):
+ """
+ Called after the partition is created. It is useful to add post
+ operations e.g. security signing the partition.
+ """
+ logger.debug("SourcePlugin: do_post_partition: part: %s", part)
diff --git a/scripts/lib/wic/plugins/imager/direct.py b/scripts/lib/wic/plugins/imager/direct.py
new file mode 100644
index 0000000000..495518fac8
--- /dev/null
+++ b/scripts/lib/wic/plugins/imager/direct.py
@@ -0,0 +1,623 @@
+#
+# Copyright (c) 2013, Intel Corporation.
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# DESCRIPTION
+# This implements the 'direct' imager plugin class for 'wic'
+#
+# AUTHORS
+# Tom Zanussi <tom.zanussi (at] linux.intel.com>
+#
+
+import logging
+import os
+import random
+import shutil
+import tempfile
+import uuid
+
+from time import strftime
+
+from oe.path import copyhardlinktree
+
+from wic import WicError
+from wic.filemap import sparse_copy
+from wic.ksparser import KickStart, KickStartError
+from wic.pluginbase import PluginMgr, ImagerPlugin
+from wic.misc import get_bitbake_var, exec_cmd, exec_native_cmd
+
+logger = logging.getLogger('wic')
+
+class DirectPlugin(ImagerPlugin):
+ """
+ Install a system into a file containing a partitioned disk image.
+
+ An image file is formatted with a partition table, each partition
+ created from a rootfs or other OpenEmbedded build artifact and dd'ed
+ into the virtual disk. The disk image can subsequently be dd'ed onto
+ media and used on actual hardware.
+ """
+ name = 'direct'
+
+ def __init__(self, wks_file, rootfs_dir, bootimg_dir, kernel_dir,
+ native_sysroot, oe_builddir, options):
+ try:
+ self.ks = KickStart(wks_file)
+ except KickStartError as err:
+ raise WicError(str(err))
+
+ # parse possible 'rootfs=name' items
+ self.rootfs_dir = dict(rdir.split('=') for rdir in rootfs_dir.split(' '))
+ self.bootimg_dir = bootimg_dir
+ self.kernel_dir = kernel_dir
+ self.native_sysroot = native_sysroot
+ self.oe_builddir = oe_builddir
+
+ self.debug = options.debug
+ self.outdir = options.outdir
+ self.compressor = options.compressor
+ self.bmap = options.bmap
+ self.no_fstab_update = options.no_fstab_update
+ self.updated_fstab_path = None
+
+ self.name = "%s-%s" % (os.path.splitext(os.path.basename(wks_file))[0],
+ strftime("%Y%m%d%H%M"))
+ self.workdir = self.setup_workdir(options.workdir)
+ self._image = None
+ self.ptable_format = self.ks.bootloader.ptable
+ self.parts = self.ks.partitions
+
+ # as a convenience, set source to the boot partition source
+ # instead of forcing it to be set via bootloader --source
+ for part in self.parts:
+ if not self.ks.bootloader.source and part.mountpoint == "/boot":
+ self.ks.bootloader.source = part.source
+ break
+
+ image_path = self._full_path(self.workdir, self.parts[0].disk, "direct")
+ self._image = PartitionedImage(image_path, self.ptable_format,
+ self.parts, self.native_sysroot,
+ options.extra_space)
+
+ def setup_workdir(self, workdir):
+ if workdir:
+ if os.path.exists(workdir):
+ raise WicError("Internal workdir '%s' specified in wic arguments already exists!" % (workdir))
+
+ os.makedirs(workdir)
+ return workdir
+ else:
+ return tempfile.mkdtemp(dir=self.outdir, prefix='tmp.wic.')
+
+ def do_create(self):
+ """
+ Plugin entry point.
+ """
+ try:
+ self.create()
+ self.assemble()
+ self.finalize()
+ self.print_info()
+ finally:
+ self.cleanup()
+
+ def update_fstab(self, image_rootfs):
+ """Assume partition order same as in wks"""
+ if not image_rootfs:
+ return
+
+ fstab_path = image_rootfs + "/etc/fstab"
+ if not os.path.isfile(fstab_path):
+ return
+
+ with open(fstab_path) as fstab:
+ fstab_lines = fstab.readlines()
+
+ updated = False
+ for part in self.parts:
+ if not part.realnum or not part.mountpoint \
+ or part.mountpoint == "/" or not part.mountpoint.startswith('/'):
+ continue
+
+ if part.use_uuid:
+ if part.fsuuid:
+ # FAT UUID is different from others
+ if len(part.fsuuid) == 10:
+ device_name = "UUID=%s-%s" % \
+ (part.fsuuid[2:6], part.fsuuid[6:])
+ else:
+ device_name = "UUID=%s" % part.fsuuid
+ else:
+ device_name = "PARTUUID=%s" % part.uuid
+ elif part.use_label:
+ device_name = "LABEL=%s" % part.label
+ else:
+ # mmc device partitions are named mmcblk0p1, mmcblk0p2..
+ prefix = 'p' if part.disk.startswith('mmcblk') else ''
+ device_name = "/dev/%s%s%d" % (part.disk, prefix, part.realnum)
+
+ opts = part.fsopts if part.fsopts else "defaults"
+ line = "\t".join([device_name, part.mountpoint, part.fstype,
+ opts, "0", "0"]) + "\n"
+
+ fstab_lines.append(line)
+ updated = True
+
+ if updated:
+ self.updated_fstab_path = os.path.join(self.workdir, "fstab")
+ with open(self.updated_fstab_path, "w") as f:
+ f.writelines(fstab_lines)
+
+ def _full_path(self, path, name, extention):
+ """ Construct full file path to a file we generate. """
+ return os.path.join(path, "%s-%s.%s" % (self.name, name, extention))
+
+ #
+ # Actual implemention
+ #
+ def create(self):
+ """
+ For 'wic', we already have our build artifacts - we just create
+ filesystems from the artifacts directly and combine them into
+ a partitioned image.
+ """
+ if not self.no_fstab_update:
+ self.update_fstab(self.rootfs_dir.get("ROOTFS_DIR"))
+
+ for part in self.parts:
+ # get rootfs size from bitbake variable if it's not set in .ks file
+ if not part.size:
+ # and if rootfs name is specified for the partition
+ image_name = self.rootfs_dir.get(part.rootfs_dir)
+ if image_name and os.path.sep not in image_name:
+ # Bitbake variable ROOTFS_SIZE is calculated in
+ # Image._get_rootfs_size method from meta/lib/oe/image.py
+ # using IMAGE_ROOTFS_SIZE, IMAGE_ROOTFS_ALIGNMENT,
+ # IMAGE_OVERHEAD_FACTOR and IMAGE_ROOTFS_EXTRA_SPACE
+ rsize_bb = get_bitbake_var('ROOTFS_SIZE', image_name)
+ if rsize_bb:
+ part.size = int(round(float(rsize_bb)))
+
+ self._image.prepare(self)
+ self._image.layout_partitions()
+ self._image.create()
+
+ def assemble(self):
+ """
+ Assemble partitions into disk image
+ """
+ self._image.assemble()
+
+ def finalize(self):
+ """
+ Finalize the disk image.
+
+ For example, prepare the image to be bootable by e.g.
+ creating and installing a bootloader configuration.
+ """
+ source_plugin = self.ks.bootloader.source
+ disk_name = self.parts[0].disk
+ if source_plugin:
+ plugin = PluginMgr.get_plugins('source')[source_plugin]
+ plugin.do_install_disk(self._image, disk_name, self, self.workdir,
+ self.oe_builddir, self.bootimg_dir,
+ self.kernel_dir, self.native_sysroot)
+
+ full_path = self._image.path
+ # Generate .bmap
+ if self.bmap:
+ logger.debug("Generating bmap file for %s", disk_name)
+ python = os.path.join(self.native_sysroot, 'usr/bin/python3-native/python3')
+ bmaptool = os.path.join(self.native_sysroot, 'usr/bin/bmaptool')
+ exec_native_cmd("%s %s create %s -o %s.bmap" % \
+ (python, bmaptool, full_path, full_path), self.native_sysroot)
+ # Compress the image
+ if self.compressor:
+ logger.debug("Compressing disk %s with %s", disk_name, self.compressor)
+ exec_cmd("%s %s" % (self.compressor, full_path))
+
+ def print_info(self):
+ """
+ Print the image(s) and artifacts used, for the user.
+ """
+ msg = "The new image(s) can be found here:\n"
+
+ extension = "direct" + {"gzip": ".gz",
+ "bzip2": ".bz2",
+ "xz": ".xz",
+ None: ""}.get(self.compressor)
+ full_path = self._full_path(self.outdir, self.parts[0].disk, extension)
+ msg += ' %s\n\n' % full_path
+
+ msg += 'The following build artifacts were used to create the image(s):\n'
+ for part in self.parts:
+ if part.rootfs_dir is None:
+ continue
+ if part.mountpoint == '/':
+ suffix = ':'
+ else:
+ suffix = '["%s"]:' % (part.mountpoint or part.label)
+ rootdir = part.rootfs_dir
+ msg += ' ROOTFS_DIR%s%s\n' % (suffix.ljust(20), rootdir)
+
+ msg += ' BOOTIMG_DIR: %s\n' % self.bootimg_dir
+ msg += ' KERNEL_DIR: %s\n' % self.kernel_dir
+ msg += ' NATIVE_SYSROOT: %s\n' % self.native_sysroot
+
+ logger.info(msg)
+
+ @property
+ def rootdev(self):
+ """
+ Get root device name to use as a 'root' parameter
+ in kernel command line.
+
+ Assume partition order same as in wks
+ """
+ for part in self.parts:
+ if part.mountpoint == "/":
+ if part.uuid:
+ return "PARTUUID=%s" % part.uuid
+ else:
+ suffix = 'p' if part.disk.startswith('mmcblk') else ''
+ return "/dev/%s%s%-d" % (part.disk, suffix, part.realnum)
+
+ def cleanup(self):
+ if self._image:
+ self._image.cleanup()
+
+ # Move results to the output dir
+ if not os.path.exists(self.outdir):
+ os.makedirs(self.outdir)
+
+ for fname in os.listdir(self.workdir):
+ path = os.path.join(self.workdir, fname)
+ if os.path.isfile(path):
+ shutil.move(path, os.path.join(self.outdir, fname))
+
+ # remove work directory when it is not in debugging mode
+ if not self.debug:
+ shutil.rmtree(self.workdir, ignore_errors=True)
+
+# Overhead of the MBR partitioning scheme (just one sector)
+MBR_OVERHEAD = 1
+
+# Overhead of the GPT partitioning scheme
+GPT_OVERHEAD = 34
+
+# Size of a sector in bytes
+SECTOR_SIZE = 512
+
+class PartitionedImage():
+ """
+ Partitioned image in a file.
+ """
+
+ def __init__(self, path, ptable_format, partitions, native_sysroot=None, extra_space=0):
+ self.path = path # Path to the image file
+ self.numpart = 0 # Number of allocated partitions
+ self.realpart = 0 # Number of partitions in the partition table
+ self.primary_part_num = 0 # Number of primary partitions (msdos)
+ self.extendedpart = 0 # Create extended partition before this logical partition (msdos)
+ self.extended_size_sec = 0 # Size of exteded partition (msdos)
+ self.logical_part_cnt = 0 # Number of total logical paritions (msdos)
+ self.offset = 0 # Offset of next partition (in sectors)
+ self.min_size = 0 # Minimum required disk size to fit
+ # all partitions (in bytes)
+ self.ptable_format = ptable_format # Partition table format
+ # Disk system identifier
+ self.identifier = random.SystemRandom().randint(1, 0xffffffff)
+
+ self.partitions = partitions
+ self.partimages = []
+ # Size of a sector used in calculations
+ self.sector_size = SECTOR_SIZE
+ self.native_sysroot = native_sysroot
+ num_real_partitions = len([p for p in self.partitions if not p.no_table])
+ self.extra_space = extra_space
+
+ # calculate the real partition number, accounting for partitions not
+ # in the partition table and logical partitions
+ realnum = 0
+ for part in self.partitions:
+ if part.no_table:
+ part.realnum = 0
+ else:
+ realnum += 1
+ if self.ptable_format == 'msdos' and realnum > 3 and num_real_partitions > 4:
+ part.realnum = realnum + 1
+ continue
+ part.realnum = realnum
+
+ # generate parition and filesystem UUIDs
+ for part in self.partitions:
+ if not part.uuid and part.use_uuid:
+ if self.ptable_format == 'gpt':
+ part.uuid = str(uuid.uuid4())
+ else: # msdos partition table
+ part.uuid = '%08x-%02d' % (self.identifier, part.realnum)
+ if not part.fsuuid:
+ if part.fstype == 'vfat' or part.fstype == 'msdos':
+ part.fsuuid = '0x' + str(uuid.uuid4())[:8].upper()
+ else:
+ part.fsuuid = str(uuid.uuid4())
+ else:
+ #make sure the fsuuid for vfat/msdos align with format 0xYYYYYYYY
+ if part.fstype == 'vfat' or part.fstype == 'msdos':
+ if part.fsuuid.upper().startswith("0X"):
+ part.fsuuid = '0x' + part.fsuuid.upper()[2:].rjust(8,"0")
+ else:
+ part.fsuuid = '0x' + part.fsuuid.upper().rjust(8,"0")
+
+ def prepare(self, imager):
+ """Prepare an image. Call prepare method of all image partitions."""
+ for part in self.partitions:
+ # need to create the filesystems in order to get their
+ # sizes before we can add them and do the layout.
+ part.prepare(imager, imager.workdir, imager.oe_builddir,
+ imager.rootfs_dir, imager.bootimg_dir,
+ imager.kernel_dir, imager.native_sysroot,
+ imager.updated_fstab_path)
+
+ # Converting kB to sectors for parted
+ part.size_sec = part.disk_size * 1024 // self.sector_size
+
+ def layout_partitions(self):
+ """ Layout the partitions, meaning calculate the position of every
+ partition on the disk. The 'ptable_format' parameter defines the
+ partition table format and may be "msdos". """
+
+ logger.debug("Assigning %s partitions to disks", self.ptable_format)
+
+ # The number of primary and logical partitions. Extended partition and
+ # partitions not listed in the table are not included.
+ num_real_partitions = len([p for p in self.partitions if not p.no_table])
+
+ # Go through partitions in the order they are added in .ks file
+ for num in range(len(self.partitions)):
+ part = self.partitions[num]
+
+ if self.ptable_format == 'msdos' and part.part_name:
+ raise WicError("setting custom partition name is not " \
+ "implemented for msdos partitions")
+
+ if self.ptable_format == 'msdos' and part.part_type:
+ # The --part-type can also be implemented for MBR partitions,
+ # in which case it would map to the 1-byte "partition type"
+ # filed at offset 3 of the partition entry.
+ raise WicError("setting custom partition type is not " \
+ "implemented for msdos partitions")
+
+ # Get the disk where the partition is located
+ self.numpart += 1
+ if not part.no_table:
+ self.realpart += 1
+
+ if self.numpart == 1:
+ if self.ptable_format == "msdos":
+ overhead = MBR_OVERHEAD
+ elif self.ptable_format == "gpt":
+ overhead = GPT_OVERHEAD
+
+ # Skip one sector required for the partitioning scheme overhead
+ self.offset += overhead
+
+ if self.ptable_format == "msdos":
+ if self.primary_part_num > 3 or \
+ (self.extendedpart == 0 and self.primary_part_num >= 3 and num_real_partitions > 4):
+ part.type = 'logical'
+ # Reserve a sector for EBR for every logical partition
+ # before alignment is performed.
+ if part.type == 'logical':
+ self.offset += 2
+
+ align_sectors = 0
+ if part.align:
+ # If not first partition and we do have alignment set we need
+ # to align the partition.
+ # FIXME: This leaves a empty spaces to the disk. To fill the
+ # gaps we could enlargea the previous partition?
+
+ # Calc how much the alignment is off.
+ align_sectors = self.offset % (part.align * 1024 // self.sector_size)
+
+ if align_sectors:
+ # If partition is not aligned as required, we need
+ # to move forward to the next alignment point
+ align_sectors = (part.align * 1024 // self.sector_size) - align_sectors
+
+ logger.debug("Realignment for %s%s with %s sectors, original"
+ " offset %s, target alignment is %sK.",
+ part.disk, self.numpart, align_sectors,
+ self.offset, part.align)
+
+ # increase the offset so we actually start the partition on right alignment
+ self.offset += align_sectors
+
+ if part.offset is not None:
+ offset = part.offset // self.sector_size
+
+ if offset * self.sector_size != part.offset:
+ raise WicError("Could not place %s%s at offset %d with sector size %d" % (part.disk, self.numpart, part.offset, self.sector_size))
+
+ delta = offset - self.offset
+ if delta < 0:
+ raise WicError("Could not place %s%s at offset %d: next free sector is %d (delta: %d)" % (part.disk, self.numpart, part.offset, self.offset, delta))
+
+ logger.debug("Skipping %d sectors to place %s%s at offset %dK",
+ delta, part.disk, self.numpart, part.offset)
+
+ self.offset = offset
+
+ part.start = self.offset
+ self.offset += part.size_sec
+
+ if not part.no_table:
+ part.num = self.realpart
+ else:
+ part.num = 0
+
+ if self.ptable_format == "msdos" and not part.no_table:
+ if part.type == 'logical':
+ self.logical_part_cnt += 1
+ part.num = self.logical_part_cnt + 4
+ if self.extendedpart == 0:
+ # Create extended partition as a primary partition
+ self.primary_part_num += 1
+ self.extendedpart = part.num
+ else:
+ self.extended_size_sec += align_sectors
+ self.extended_size_sec += part.size_sec + 2
+ else:
+ self.primary_part_num += 1
+ part.num = self.primary_part_num
+
+ logger.debug("Assigned %s to %s%d, sectors range %d-%d size %d "
+ "sectors (%d bytes).", part.mountpoint, part.disk,
+ part.num, part.start, self.offset - 1, part.size_sec,
+ part.size_sec * self.sector_size)
+
+ # Once all the partitions have been layed out, we can calculate the
+ # minumim disk size
+ self.min_size = self.offset
+ if self.ptable_format == "gpt":
+ self.min_size += GPT_OVERHEAD
+
+ self.min_size *= self.sector_size
+ self.min_size += self.extra_space
+
+ def _create_partition(self, device, parttype, fstype, start, size):
+ """ Create a partition on an image described by the 'device' object. """
+
+ # Start is included to the size so we need to substract one from the end.
+ end = start + size - 1
+ logger.debug("Added '%s' partition, sectors %d-%d, size %d sectors",
+ parttype, start, end, size)
+
+ cmd = "parted -s %s unit s mkpart %s" % (device, parttype)
+ if fstype:
+ cmd += " %s" % fstype
+ cmd += " %d %d" % (start, end)
+
+ return exec_native_cmd(cmd, self.native_sysroot)
+
+ def create(self):
+ logger.debug("Creating sparse file %s", self.path)
+ with open(self.path, 'w') as sparse:
+ os.ftruncate(sparse.fileno(), self.min_size)
+
+ logger.debug("Initializing partition table for %s", self.path)
+ exec_native_cmd("parted -s %s mklabel %s" %
+ (self.path, self.ptable_format), self.native_sysroot)
+
+ logger.debug("Set disk identifier %x", self.identifier)
+ with open(self.path, 'r+b') as img:
+ img.seek(0x1B8)
+ img.write(self.identifier.to_bytes(4, 'little'))
+
+ logger.debug("Creating partitions")
+
+ for part in self.partitions:
+ if part.num == 0:
+ continue
+
+ if self.ptable_format == "msdos" and part.num == self.extendedpart:
+ # Create an extended partition (note: extended
+ # partition is described in MBR and contains all
+ # logical partitions). The logical partitions save a
+ # sector for an EBR just before the start of a
+ # partition. The extended partition must start one
+ # sector before the start of the first logical
+ # partition. This way the first EBR is inside of the
+ # extended partition. Since the extended partitions
+ # starts a sector before the first logical partition,
+ # add a sector at the back, so that there is enough
+ # room for all logical partitions.
+ self._create_partition(self.path, "extended",
+ None, part.start - 2,
+ self.extended_size_sec)
+
+ if part.fstype == "swap":
+ parted_fs_type = "linux-swap"
+ elif part.fstype == "vfat":
+ parted_fs_type = "fat32"
+ elif part.fstype == "msdos":
+ parted_fs_type = "fat16"
+ if not part.system_id:
+ part.system_id = '0x6' # FAT16
+ else:
+ # Type for ext2/ext3/ext4/btrfs
+ parted_fs_type = "ext2"
+
+ # Boot ROM of OMAP boards require vfat boot partition to have an
+ # even number of sectors.
+ if part.mountpoint == "/boot" and part.fstype in ["vfat", "msdos"] \
+ and part.size_sec % 2:
+ logger.debug("Subtracting one sector from '%s' partition to "
+ "get even number of sectors for the partition",
+ part.mountpoint)
+ part.size_sec -= 1
+
+ self._create_partition(self.path, part.type,
+ parted_fs_type, part.start, part.size_sec)
+
+ if part.part_name:
+ logger.debug("partition %d: set name to %s",
+ part.num, part.part_name)
+ exec_native_cmd("sgdisk --change-name=%d:%s %s" % \
+ (part.num, part.part_name,
+ self.path), self.native_sysroot)
+
+ if part.part_type:
+ logger.debug("partition %d: set type UID to %s",
+ part.num, part.part_type)
+ exec_native_cmd("sgdisk --typecode=%d:%s %s" % \
+ (part.num, part.part_type,
+ self.path), self.native_sysroot)
+
+ if part.uuid and self.ptable_format == "gpt":
+ logger.debug("partition %d: set UUID to %s",
+ part.num, part.uuid)
+ exec_native_cmd("sgdisk --partition-guid=%d:%s %s" % \
+ (part.num, part.uuid, self.path),
+ self.native_sysroot)
+
+ if part.label and self.ptable_format == "gpt":
+ logger.debug("partition %d: set name to %s",
+ part.num, part.label)
+ exec_native_cmd("parted -s %s name %d %s" % \
+ (self.path, part.num, part.label),
+ self.native_sysroot)
+
+ if part.active:
+ flag_name = "legacy_boot" if self.ptable_format == 'gpt' else "boot"
+ logger.debug("Set '%s' flag for partition '%s' on disk '%s'",
+ flag_name, part.num, self.path)
+ exec_native_cmd("parted -s %s set %d %s on" % \
+ (self.path, part.num, flag_name),
+ self.native_sysroot)
+ if part.system_id:
+ exec_native_cmd("sfdisk --part-type %s %s %s" % \
+ (self.path, part.num, part.system_id),
+ self.native_sysroot)
+
+ def cleanup(self):
+ pass
+
+ def assemble(self):
+ logger.debug("Installing partitions")
+
+ for part in self.partitions:
+ source = part.source_file
+ if source:
+ # install source_file contents into a partition
+ sparse_copy(source, self.path, seek=part.start * self.sector_size)
+
+ logger.debug("Installed %s in partition %d, sectors %d-%d, "
+ "size %d sectors", source, part.num, part.start,
+ part.start + part.size_sec - 1, part.size_sec)
+
+ partimage = self.path + '.p%d' % part.num
+ bb.utils.rename(source, partimage)
+ self.partimages.append(partimage)
diff --git a/scripts/lib/wic/plugins/imager/direct_plugin.py b/scripts/lib/wic/plugins/imager/direct_plugin.py
deleted file mode 100644
index 6d3f46cc61..0000000000
--- a/scripts/lib/wic/plugins/imager/direct_plugin.py
+++ /dev/null
@@ -1,102 +0,0 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
-#
-# Copyright (c) 2013, Intel Corporation.
-# All rights reserved.
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# DESCRIPTION
-# This implements the 'direct' imager plugin class for 'wic'
-#
-# AUTHORS
-# Tom Zanussi <tom.zanussi (at] linux.intel.com>
-#
-
-from wic.utils import errors
-from wic.conf import configmgr
-
-import wic.imager.direct as direct
-from wic.pluginbase import ImagerPlugin
-
-class DirectPlugin(ImagerPlugin):
- """
- Install a system into a file containing a partitioned disk image.
-
- An image file is formatted with a partition table, each partition
- created from a rootfs or other OpenEmbedded build artifact and dd'ed
- into the virtual disk. The disk image can subsequently be dd'ed onto
- media and used on actual hardware.
- """
-
- name = 'direct'
-
- @classmethod
- def __rootfs_dir_to_dict(cls, rootfs_dirs):
- """
- Gets a string that contain 'connection=dir' splitted by
- space and return a dict
- """
- krootfs_dir = {}
- for rootfs_dir in rootfs_dirs.split(' '):
- key, val = rootfs_dir.split('=')
- krootfs_dir[key] = val
-
- return krootfs_dir
-
- @classmethod
- def do_create(cls, opts, *args):
- """
- Create direct image, called from creator as 'direct' cmd
- """
- if len(args) != 8:
- raise errors.Usage("Extra arguments given")
-
- native_sysroot = args[0]
- kernel_dir = args[1]
- bootimg_dir = args[2]
- rootfs_dir = args[3]
-
- creatoropts = configmgr.create
- ksconf = args[4]
-
- image_output_dir = args[5]
- oe_builddir = args[6]
- compressor = args[7]
-
- krootfs_dir = cls.__rootfs_dir_to_dict(rootfs_dir)
-
- configmgr._ksconf = ksconf
-
- creator = direct.DirectImageCreator(oe_builddir,
- image_output_dir,
- krootfs_dir,
- bootimg_dir,
- kernel_dir,
- native_sysroot,
- compressor,
- creatoropts)
-
- try:
- creator.create()
- creator.assemble()
- creator.finalize()
- creator.print_outimage_info()
-
- except errors.CreatorError:
- raise
- finally:
- creator.cleanup()
-
- return 0
diff --git a/scripts/lib/wic/plugins/source/bootimg-biosplusefi.py b/scripts/lib/wic/plugins/source/bootimg-biosplusefi.py
new file mode 100644
index 0000000000..5bd7390680
--- /dev/null
+++ b/scripts/lib/wic/plugins/source/bootimg-biosplusefi.py
@@ -0,0 +1,213 @@
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# DESCRIPTION
+# This implements the 'bootimg-biosplusefi' source plugin class for 'wic'
+#
+# AUTHORS
+# William Bourque <wbourque [at) gmail.com>
+
+import types
+
+from wic.pluginbase import SourcePlugin
+from importlib.machinery import SourceFileLoader
+
+class BootimgBiosPlusEFIPlugin(SourcePlugin):
+ """
+ Create MBR + EFI boot partition
+
+ This plugin creates a boot partition that contains both
+ legacy BIOS and EFI content. It will be able to boot from both.
+ This is useful when managing PC fleet with some older machines
+ without EFI support.
+
+ Note it is possible to create an image that can boot from both
+ legacy BIOS and EFI by defining two partitions : one with arg
+ --source bootimg-efi and another one with --source bootimg-pcbios.
+ However, this method has the obvious downside that it requires TWO
+ partitions to be created on the storage device.
+ Both partitions will also be marked as "bootable" which does not work on
+ most BIOS, has BIOS often uses the "bootable" flag to determine
+ what to boot. If you have such a BIOS, you need to manually remove the
+ "bootable" flag from the EFI partition for the drive to be bootable.
+ Having two partitions also seems to confuse wic : the content of
+ the first partition will be duplicated into the second, even though it
+ will not be used at all.
+
+ Also, unlike "isoimage-isohybrid" that also does BIOS and EFI, this plugin
+ allows you to have more than only a single rootfs partitions and does
+ not turn the rootfs into an initramfs RAM image.
+
+ This plugin is made to put everything into a single /boot partition so it
+ does not have the limitations listed above.
+
+ The plugin is made so it does tries not to reimplement what's already
+ been done in other plugins; as such it imports "bootimg-pcbios"
+ and "bootimg-efi".
+ Plugin "bootimg-pcbios" is used to generate legacy BIOS boot.
+ Plugin "bootimg-efi" is used to generate the UEFI boot. Note that it
+ requires a --sourceparams argument to know which loader to use; refer
+ to "bootimg-efi" code/documentation for the list of loader.
+
+ Imports are handled with "SourceFileLoader" from importlib as it is
+ otherwise very difficult to import module that has hyphen "-" in their
+ filename.
+ The SourcePlugin() methods used in the plugins (do_install_disk,
+ do_configure_partition, do_prepare_partition) are then called on both,
+ beginning by "bootimg-efi".
+
+ Plugin options, such as "--sourceparams" can still be passed to a
+ plugin, as long they does not cause issue in the other plugin.
+
+ Example wic configuration:
+ part /boot --source bootimg-biosplusefi --sourceparams="loader=grub-efi"\\
+ --ondisk sda --label os_boot --active --align 1024 --use-uuid
+ """
+
+ name = 'bootimg-biosplusefi'
+
+ __PCBIOS_MODULE_NAME = "bootimg-pcbios"
+ __EFI_MODULE_NAME = "bootimg-efi"
+
+ __imgEFIObj = None
+ __imgBiosObj = None
+
+ @classmethod
+ def __init__(cls):
+ """
+ Constructor (init)
+ """
+
+ # XXX
+ # For some reasons, __init__ constructor is never called.
+ # Something to do with how pluginbase works?
+ cls.__instanciateSubClasses()
+
+ @classmethod
+ def __instanciateSubClasses(cls):
+ """
+
+ """
+
+ # Import bootimg-pcbios (class name "BootimgPcbiosPlugin")
+ modulePath = os.path.join(os.path.dirname(os.path.realpath(__file__)),
+ cls.__PCBIOS_MODULE_NAME + ".py")
+ loader = SourceFileLoader(cls.__PCBIOS_MODULE_NAME, modulePath)
+ mod = types.ModuleType(loader.name)
+ loader.exec_module(mod)
+ cls.__imgBiosObj = mod.BootimgPcbiosPlugin()
+
+ # Import bootimg-efi (class name "BootimgEFIPlugin")
+ modulePath = os.path.join(os.path.dirname(os.path.realpath(__file__)),
+ cls.__EFI_MODULE_NAME + ".py")
+ loader = SourceFileLoader(cls.__EFI_MODULE_NAME, modulePath)
+ mod = types.ModuleType(loader.name)
+ loader.exec_module(mod)
+ cls.__imgEFIObj = mod.BootimgEFIPlugin()
+
+ @classmethod
+ def do_install_disk(cls, disk, disk_name, creator, workdir, oe_builddir,
+ bootimg_dir, kernel_dir, native_sysroot):
+ """
+ Called after all partitions have been prepared and assembled into a
+ disk image.
+ """
+
+ if ( (not cls.__imgEFIObj) or (not cls.__imgBiosObj) ):
+ cls.__instanciateSubClasses()
+
+ cls.__imgEFIObj.do_install_disk(
+ disk,
+ disk_name,
+ creator,
+ workdir,
+ oe_builddir,
+ bootimg_dir,
+ kernel_dir,
+ native_sysroot)
+
+ cls.__imgBiosObj.do_install_disk(
+ disk,
+ disk_name,
+ creator,
+ workdir,
+ oe_builddir,
+ bootimg_dir,
+ kernel_dir,
+ native_sysroot)
+
+ @classmethod
+ def do_configure_partition(cls, part, source_params, creator, cr_workdir,
+ oe_builddir, bootimg_dir, kernel_dir,
+ native_sysroot):
+ """
+ Called before do_prepare_partition()
+ """
+
+ if ( (not cls.__imgEFIObj) or (not cls.__imgBiosObj) ):
+ cls.__instanciateSubClasses()
+
+ cls.__imgEFIObj.do_configure_partition(
+ part,
+ source_params,
+ creator,
+ cr_workdir,
+ oe_builddir,
+ bootimg_dir,
+ kernel_dir,
+ native_sysroot)
+
+ cls.__imgBiosObj.do_configure_partition(
+ part,
+ source_params,
+ creator,
+ cr_workdir,
+ oe_builddir,
+ bootimg_dir,
+ kernel_dir,
+ native_sysroot)
+
+ @classmethod
+ def do_prepare_partition(cls, part, source_params, creator, cr_workdir,
+ oe_builddir, bootimg_dir, kernel_dir,
+ rootfs_dir, native_sysroot):
+ """
+ Called to do the actual content population for a partition i.e. it
+ 'prepares' the partition to be incorporated into the image.
+ """
+
+ if ( (not cls.__imgEFIObj) or (not cls.__imgBiosObj) ):
+ cls.__instanciateSubClasses()
+
+ cls.__imgEFIObj.do_prepare_partition(
+ part,
+ source_params,
+ creator,
+ cr_workdir,
+ oe_builddir,
+ bootimg_dir,
+ kernel_dir,
+ rootfs_dir,
+ native_sysroot)
+
+ cls.__imgBiosObj.do_prepare_partition(
+ part,
+ source_params,
+ creator,
+ cr_workdir,
+ oe_builddir,
+ bootimg_dir,
+ kernel_dir,
+ rootfs_dir,
+ native_sysroot)
diff --git a/scripts/lib/wic/plugins/source/bootimg-efi.py b/scripts/lib/wic/plugins/source/bootimg-efi.py
index fa63c6abda..0391aebdc8 100644
--- a/scripts/lib/wic/plugins/source/bootimg-efi.py
+++ b/scripts/lib/wic/plugins/source/bootimg-efi.py
@@ -1,21 +1,7 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# Copyright (c) 2014, Intel Corporation.
-# All rights reserved.
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# SPDX-License-Identifier: GPL-2.0-only
#
# DESCRIPTION
# This implements the 'bootimg-efi' source plugin class for 'wic'
@@ -24,54 +10,106 @@
# Tom Zanussi <tom.zanussi (at] linux.intel.com>
#
+import logging
import os
+import tempfile
import shutil
+import re
-from wic import kickstart, msger
+from glob import glob
+
+from wic import WicError
+from wic.engine import get_custom_config
from wic.pluginbase import SourcePlugin
-from wic.utils.oe.misc import exec_cmd, exec_native_cmd, get_bitbake_var, \
- BOOTDD_EXTRA_SPACE
+from wic.misc import (exec_cmd, exec_native_cmd,
+ get_bitbake_var, BOOTDD_EXTRA_SPACE)
+
+logger = logging.getLogger('wic')
class BootimgEFIPlugin(SourcePlugin):
"""
Create EFI boot partition.
- This plugin supports GRUB 2 and gummiboot bootloaders.
+ This plugin supports GRUB 2 and systemd-boot bootloaders.
"""
name = 'bootimg-efi'
@classmethod
- def do_configure_grubefi(cls, hdddir, creator, cr_workdir):
+ def do_configure_grubefi(cls, hdddir, creator, cr_workdir, source_params):
"""
Create loader-specific (grub-efi) config
"""
- options = creator.ks.handler.bootloader.appendLine
-
- grubefi_conf = ""
- grubefi_conf += "serial --unit=0 --speed=115200 --word=8 --parity=no --stop=1\n"
- grubefi_conf += "default=boot\n"
- timeout = kickstart.get_timeout(creator.ks)
- if not timeout:
- timeout = 0
- grubefi_conf += "timeout=%s\n" % timeout
- grubefi_conf += "menuentry 'boot'{\n"
+ configfile = creator.ks.bootloader.configfile
+ custom_cfg = None
+ if configfile:
+ custom_cfg = get_custom_config(configfile)
+ if custom_cfg:
+ # Use a custom configuration for grub
+ grubefi_conf = custom_cfg
+ logger.debug("Using custom configuration file "
+ "%s for grub.cfg", configfile)
+ else:
+ raise WicError("configfile is specified but failed to "
+ "get it from %s." % configfile)
- kernel = "/bzImage"
+ initrd = source_params.get('initrd')
- grubefi_conf += "linux %s root=%s rootwait %s\n" \
- % (kernel, creator.rootdev, options)
- grubefi_conf += "}\n"
+ if initrd:
+ bootimg_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
+ if not bootimg_dir:
+ raise WicError("Couldn't find DEPLOY_DIR_IMAGE, exiting")
- msger.debug("Writing grubefi config %s/hdd/boot/EFI/BOOT/grub.cfg" \
- % cr_workdir)
+ initrds = initrd.split(';')
+ for rd in initrds:
+ cp_cmd = "cp %s/%s %s" % (bootimg_dir, rd, hdddir)
+ exec_cmd(cp_cmd, True)
+ else:
+ logger.debug("Ignoring missing initrd")
+
+ if not custom_cfg:
+ # Create grub configuration using parameters from wks file
+ bootloader = creator.ks.bootloader
+ title = source_params.get('title')
+
+ grubefi_conf = ""
+ grubefi_conf += "serial --unit=0 --speed=115200 --word=8 --parity=no --stop=1\n"
+ grubefi_conf += "default=boot\n"
+ grubefi_conf += "timeout=%s\n" % bootloader.timeout
+ grubefi_conf += "menuentry '%s'{\n" % (title if title else "boot")
+
+ kernel = get_bitbake_var("KERNEL_IMAGETYPE")
+ if get_bitbake_var("INITRAMFS_IMAGE_BUNDLE") == "1":
+ if get_bitbake_var("INITRAMFS_IMAGE"):
+ kernel = "%s-%s.bin" % \
+ (get_bitbake_var("KERNEL_IMAGETYPE"), get_bitbake_var("INITRAMFS_LINK_NAME"))
+
+ label = source_params.get('label')
+ label_conf = "root=%s" % creator.rootdev
+ if label:
+ label_conf = "LABEL=%s" % label
+
+ grubefi_conf += "linux /%s %s rootwait %s\n" \
+ % (kernel, label_conf, bootloader.append)
+
+ if initrd:
+ initrds = initrd.split(';')
+ grubefi_conf += "initrd"
+ for rd in initrds:
+ grubefi_conf += " /%s" % rd
+ grubefi_conf += "\n"
+
+ grubefi_conf += "}\n"
+
+ logger.debug("Writing grubefi config %s/hdd/boot/EFI/BOOT/grub.cfg",
+ cr_workdir)
cfg = open("%s/hdd/boot/EFI/BOOT/grub.cfg" % cr_workdir, "w")
cfg.write(grubefi_conf)
cfg.close()
@classmethod
- def do_configure_gummiboot(cls, hdddir, creator, cr_workdir):
+ def do_configure_systemdboot(cls, hdddir, creator, cr_workdir, source_params):
"""
- Create loader-specific (gummiboot) config
+ Create loader-specific systemd-boot/gummiboot config
"""
install_cmd = "install -d %s/loader" % hdddir
exec_cmd(install_cmd)
@@ -79,34 +117,80 @@ class BootimgEFIPlugin(SourcePlugin):
install_cmd = "install -d %s/loader/entries" % hdddir
exec_cmd(install_cmd)
- options = creator.ks.handler.bootloader.appendLine
-
- timeout = kickstart.get_timeout(creator.ks)
- if not timeout:
- timeout = 0
+ bootloader = creator.ks.bootloader
loader_conf = ""
- loader_conf += "default boot\n"
- loader_conf += "timeout %d\n" % timeout
+ if source_params.get('create-unified-kernel-image') != "true":
+ loader_conf += "default boot\n"
+ loader_conf += "timeout %d\n" % bootloader.timeout
+
+ initrd = source_params.get('initrd')
+
+ if initrd and source_params.get('create-unified-kernel-image') != "true":
+ # obviously we need to have a common common deploy var
+ bootimg_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
+ if not bootimg_dir:
+ raise WicError("Couldn't find DEPLOY_DIR_IMAGE, exiting")
- msger.debug("Writing gummiboot config %s/hdd/boot/loader/loader.conf" \
- % cr_workdir)
+ initrds = initrd.split(';')
+ for rd in initrds:
+ cp_cmd = "cp %s/%s %s" % (bootimg_dir, rd, hdddir)
+ exec_cmd(cp_cmd, True)
+ else:
+ logger.debug("Ignoring missing initrd")
+
+ logger.debug("Writing systemd-boot config "
+ "%s/hdd/boot/loader/loader.conf", cr_workdir)
cfg = open("%s/hdd/boot/loader/loader.conf" % cr_workdir, "w")
cfg.write(loader_conf)
cfg.close()
- kernel = "/bzImage"
+ configfile = creator.ks.bootloader.configfile
+ custom_cfg = None
+ if configfile:
+ custom_cfg = get_custom_config(configfile)
+ if custom_cfg:
+ # Use a custom configuration for systemd-boot
+ boot_conf = custom_cfg
+ logger.debug("Using custom configuration file "
+ "%s for systemd-boots's boot.conf", configfile)
+ else:
+ raise WicError("configfile is specified but failed to "
+ "get it from %s.", configfile)
- boot_conf = ""
- boot_conf += "title boot\n"
- boot_conf += "linux %s\n" % kernel
- boot_conf += "options LABEL=Boot root=%s %s\n" % (creator.rootdev, options)
+ if not custom_cfg:
+ # Create systemd-boot configuration using parameters from wks file
+ kernel = get_bitbake_var("KERNEL_IMAGETYPE")
+ if get_bitbake_var("INITRAMFS_IMAGE_BUNDLE") == "1":
+ if get_bitbake_var("INITRAMFS_IMAGE"):
+ kernel = "%s-%s.bin" % \
+ (get_bitbake_var("KERNEL_IMAGETYPE"), get_bitbake_var("INITRAMFS_LINK_NAME"))
- msger.debug("Writing gummiboot config %s/hdd/boot/loader/entries/boot.conf" \
- % cr_workdir)
- cfg = open("%s/hdd/boot/loader/entries/boot.conf" % cr_workdir, "w")
- cfg.write(boot_conf)
- cfg.close()
+ title = source_params.get('title')
+
+ boot_conf = ""
+ boot_conf += "title %s\n" % (title if title else "boot")
+ boot_conf += "linux /%s\n" % kernel
+
+ label = source_params.get('label')
+ label_conf = "LABEL=Boot root=%s" % creator.rootdev
+ if label:
+ label_conf = "LABEL=%s" % label
+
+ boot_conf += "options %s %s\n" % \
+ (label_conf, bootloader.append)
+
+ if initrd:
+ initrds = initrd.split(';')
+ for rd in initrds:
+ boot_conf += "initrd /%s\n" % rd
+
+ if source_params.get('create-unified-kernel-image') != "true":
+ logger.debug("Writing systemd-boot config "
+ "%s/hdd/boot/loader/entries/boot.conf", cr_workdir)
+ cfg = open("%s/hdd/boot/loader/entries/boot.conf" % cr_workdir, "w")
+ cfg.write(boot_conf)
+ cfg.close()
@classmethod
@@ -117,22 +201,71 @@ class BootimgEFIPlugin(SourcePlugin):
Called before do_prepare_partition(), creates loader-specific config
"""
hdddir = "%s/hdd/boot" % cr_workdir
- rm_cmd = "rm -rf %s" % cr_workdir
- exec_cmd(rm_cmd)
install_cmd = "install -d %s/EFI/BOOT" % hdddir
exec_cmd(install_cmd)
try:
if source_params['loader'] == 'grub-efi':
- cls.do_configure_grubefi(hdddir, creator, cr_workdir)
- elif source_params['loader'] == 'gummiboot':
- cls.do_configure_gummiboot(hdddir, creator, cr_workdir)
+ cls.do_configure_grubefi(hdddir, creator, cr_workdir, source_params)
+ elif source_params['loader'] == 'systemd-boot':
+ cls.do_configure_systemdboot(hdddir, creator, cr_workdir, source_params)
else:
- msger.error("unrecognized bootimg-efi loader: %s" % source_params['loader'])
+ raise WicError("unrecognized bootimg-efi loader: %s" % source_params['loader'])
except KeyError:
- msger.error("bootimg-efi requires a loader, none specified")
-
+ raise WicError("bootimg-efi requires a loader, none specified")
+
+ if get_bitbake_var("IMAGE_EFI_BOOT_FILES") is None:
+ logger.debug('No boot files defined in IMAGE_EFI_BOOT_FILES')
+ else:
+ boot_files = None
+ for (fmt, id) in (("_uuid-%s", part.uuid), ("_label-%s", part.label), (None, None)):
+ if fmt:
+ var = fmt % id
+ else:
+ var = ""
+
+ boot_files = get_bitbake_var("IMAGE_EFI_BOOT_FILES" + var)
+ if boot_files:
+ break
+
+ logger.debug('Boot files: %s', boot_files)
+
+ # list of tuples (src_name, dst_name)
+ deploy_files = []
+ for src_entry in re.findall(r'[\w;\-\./\*]+', boot_files):
+ if ';' in src_entry:
+ dst_entry = tuple(src_entry.split(';'))
+ if not dst_entry[0] or not dst_entry[1]:
+ raise WicError('Malformed boot file entry: %s' % src_entry)
+ else:
+ dst_entry = (src_entry, src_entry)
+
+ logger.debug('Destination entry: %r', dst_entry)
+ deploy_files.append(dst_entry)
+
+ cls.install_task = [];
+ for deploy_entry in deploy_files:
+ src, dst = deploy_entry
+ if '*' in src:
+ # by default install files under their basename
+ entry_name_fn = os.path.basename
+ if dst != src:
+ # unless a target name was given, then treat name
+ # as a directory and append a basename
+ entry_name_fn = lambda name: \
+ os.path.join(dst,
+ os.path.basename(name))
+
+ srcs = glob(os.path.join(kernel_dir, src))
+
+ logger.debug('Globbed sources: %s', ', '.join(srcs))
+ for entry in srcs:
+ src = os.path.relpath(entry, kernel_dir)
+ entry_dst_name = entry_name_fn(entry)
+ cls.install_task.append((src, entry_dst_name))
+ else:
+ cls.install_task.append((src, dst))
@classmethod
def do_prepare_partition(cls, part, source_params, creator, cr_workdir,
@@ -143,36 +276,106 @@ class BootimgEFIPlugin(SourcePlugin):
'prepares' the partition to be incorporated into the image.
In this case, prepare content for an EFI (grub) boot partition.
"""
- if not bootimg_dir:
- bootimg_dir = get_bitbake_var("HDDDIR")
- if not bootimg_dir:
- msger.error("Couldn't find HDDDIR, exiting\n")
- # just so the result notes display it
- creator.set_bootimg_dir(bootimg_dir)
+ if not kernel_dir:
+ kernel_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
+ if not kernel_dir:
+ raise WicError("Couldn't find DEPLOY_DIR_IMAGE, exiting")
staging_kernel_dir = kernel_dir
hdddir = "%s/hdd/boot" % cr_workdir
- install_cmd = "install -m 0644 %s/bzImage %s/bzImage" % \
- (staging_kernel_dir, hdddir)
- exec_cmd(install_cmd)
+ kernel = get_bitbake_var("KERNEL_IMAGETYPE")
+ if get_bitbake_var("INITRAMFS_IMAGE_BUNDLE") == "1":
+ if get_bitbake_var("INITRAMFS_IMAGE"):
+ kernel = "%s-%s.bin" % \
+ (get_bitbake_var("KERNEL_IMAGETYPE"), get_bitbake_var("INITRAMFS_LINK_NAME"))
+
+ if source_params.get('create-unified-kernel-image') == "true":
+ initrd = source_params.get('initrd')
+ if not initrd:
+ raise WicError("initrd= must be specified when create-unified-kernel-image=true, exiting")
+
+ deploy_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
+ efi_stub = glob("%s/%s" % (deploy_dir, "linux*.efi.stub"))
+ if len(efi_stub) == 0:
+ raise WicError("Unified Kernel Image EFI stub not found, exiting")
+ efi_stub = efi_stub[0]
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ label = source_params.get('label')
+ label_conf = "root=%s" % creator.rootdev
+ if label:
+ label_conf = "LABEL=%s" % label
+
+ bootloader = creator.ks.bootloader
+ cmdline = open("%s/cmdline" % tmp_dir, "w")
+ cmdline.write("%s %s" % (label_conf, bootloader.append))
+ cmdline.close()
+
+ initrds = initrd.split(';')
+ initrd = open("%s/initrd" % tmp_dir, "wb")
+ for f in initrds:
+ with open("%s/%s" % (deploy_dir, f), 'rb') as in_file:
+ shutil.copyfileobj(in_file, initrd)
+ initrd.close()
+
+ # Searched by systemd-boot:
+ # https://systemd.io/BOOT_LOADER_SPECIFICATION/#type-2-efi-unified-kernel-images
+ install_cmd = "install -d %s/EFI/Linux" % hdddir
+ exec_cmd(install_cmd)
+
+ staging_dir_host = get_bitbake_var("STAGING_DIR_HOST")
+
+ # https://www.freedesktop.org/software/systemd/man/systemd-stub.html
+ objcopy_cmd = "objcopy \
+ --add-section .osrel=%s --change-section-vma .osrel=0x20000 \
+ --add-section .cmdline=%s --change-section-vma .cmdline=0x30000 \
+ --add-section .linux=%s --change-section-vma .linux=0x2000000 \
+ --add-section .initrd=%s --change-section-vma .initrd=0x3000000 \
+ %s %s" % \
+ ("%s/usr/lib/os-release" % staging_dir_host,
+ cmdline.name,
+ "%s/%s" % (staging_kernel_dir, kernel),
+ initrd.name,
+ efi_stub,
+ "%s/EFI/Linux/linux.efi" % hdddir)
+ exec_cmd(objcopy_cmd)
+ else:
+ install_cmd = "install -m 0644 %s/%s %s/%s" % \
+ (staging_kernel_dir, kernel, hdddir, kernel)
+ exec_cmd(install_cmd)
+
+ if get_bitbake_var("IMAGE_EFI_BOOT_FILES"):
+ for src_path, dst_path in cls.install_task:
+ install_cmd = "install -m 0644 -D %s %s" \
+ % (os.path.join(kernel_dir, src_path),
+ os.path.join(hdddir, dst_path))
+ exec_cmd(install_cmd)
try:
if source_params['loader'] == 'grub-efi':
shutil.copyfile("%s/hdd/boot/EFI/BOOT/grub.cfg" % cr_workdir,
"%s/grub.cfg" % cr_workdir)
- cp_cmd = "cp %s/EFI/BOOT/* %s/EFI/BOOT" % (bootimg_dir, hdddir)
- exec_cmd(cp_cmd, True)
+ for mod in [x for x in os.listdir(kernel_dir) if x.startswith("grub-efi-")]:
+ cp_cmd = "cp %s/%s %s/EFI/BOOT/%s" % (kernel_dir, mod, hdddir, mod[9:])
+ exec_cmd(cp_cmd, True)
shutil.move("%s/grub.cfg" % cr_workdir,
"%s/hdd/boot/EFI/BOOT/grub.cfg" % cr_workdir)
- elif source_params['loader'] == 'gummiboot':
- cp_cmd = "cp %s/EFI/BOOT/* %s/EFI/BOOT" % (bootimg_dir, hdddir)
- exec_cmd(cp_cmd, True)
+ elif source_params['loader'] == 'systemd-boot':
+ for mod in [x for x in os.listdir(kernel_dir) if x.startswith("systemd-")]:
+ cp_cmd = "cp %s/%s %s/EFI/BOOT/%s" % (kernel_dir, mod, hdddir, mod[8:])
+ exec_cmd(cp_cmd, True)
else:
- msger.error("unrecognized bootimg-efi loader: %s" % source_params['loader'])
+ raise WicError("unrecognized bootimg-efi loader: %s" %
+ source_params['loader'])
except KeyError:
- msger.error("bootimg-efi requires a loader, none specified")
+ raise WicError("bootimg-efi requires a loader, none specified")
+
+ startup = os.path.join(kernel_dir, "startup.nsh")
+ if os.path.exists(startup):
+ cp_cmd = "cp %s %s/" % (startup, hdddir)
+ exec_cmd(cp_cmd, True)
du_cmd = "du -bks %s" % hdddir
out = exec_cmd(du_cmd)
@@ -185,19 +388,16 @@ class BootimgEFIPlugin(SourcePlugin):
blocks += extra_blocks
- msger.debug("Added %d extra blocks to %s to get to %d total blocks" % \
- (extra_blocks, part.mountpoint, blocks))
-
- # Ensure total sectors is an integral number of sectors per
- # track or mcopy will complain. Sectors are 512 bytes, and we
- # generate images with 32 sectors per track. This calculation is
- # done in blocks, thus the mod by 16 instead of 32.
- blocks += (16 - (blocks % 16))
+ logger.debug("Added %d extra blocks to %s to get to %d total blocks",
+ extra_blocks, part.mountpoint, blocks)
# dosfs image, created by mkdosfs
bootimg = "%s/boot.img" % cr_workdir
- dosfs_cmd = "mkdosfs -n efi -C %s %d" % (bootimg, blocks)
+ label = part.label if part.label else "ESP"
+
+ dosfs_cmd = "mkdosfs -n %s -i %s -C %s %d" % \
+ (label, part.fsuuid, bootimg, blocks)
exec_native_cmd(dosfs_cmd, native_sysroot)
mcopy_cmd = "mcopy -i %s -s %s/* ::/" % (bootimg, hdddir)
@@ -210,5 +410,5 @@ class BootimgEFIPlugin(SourcePlugin):
out = exec_cmd(du_cmd)
bootimg_size = out.split()[0]
- part.set_size(bootimg_size)
- part.set_source_file(bootimg)
+ part.size = int(bootimg_size)
+ part.source_file = bootimg
diff --git a/scripts/lib/wic/plugins/source/bootimg-partition.py b/scripts/lib/wic/plugins/source/bootimg-partition.py
index bc2ca0f6fa..5dbe2558d2 100644
--- a/scripts/lib/wic/plugins/source/bootimg-partition.py
+++ b/scripts/lib/wic/plugins/source/bootimg-partition.py
@@ -1,18 +1,5 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# SPDX-License-Identifier: GPL-2.0-only
#
# DESCRIPTION
# This implements the 'bootimg-partition' source plugin class for
@@ -23,14 +10,19 @@
# Maciej Borzecki <maciej.borzecki (at] open-rnd.pl>
#
+import logging
import os
import re
-from wic import msger
-from wic.pluginbase import SourcePlugin
-from wic.utils.oe.misc import exec_cmd, get_bitbake_var
from glob import glob
+from wic import WicError
+from wic.engine import get_custom_config
+from wic.pluginbase import SourcePlugin
+from wic.misc import exec_cmd, get_bitbake_var
+
+logger = logging.getLogger('wic')
+
class BootimgPartitionPlugin(SourcePlugin):
"""
Create an image of boot partition, copying over files
@@ -40,56 +32,36 @@ class BootimgPartitionPlugin(SourcePlugin):
name = 'bootimg-partition'
@classmethod
- def do_install_disk(cls, disk, disk_name, cr, workdir, oe_builddir,
- bootimg_dir, kernel_dir, native_sysroot):
- """
- Called after all partitions have been prepared and assembled into a
- disk image. Do nothing.
- """
- pass
-
- @classmethod
def do_configure_partition(cls, part, source_params, cr, cr_workdir,
- oe_builddir, bootimg_dir, kernel_dir,
- native_sysroot):
- """
- Called before do_prepare_partition(). Possibly prepare
- configuration files of some sort.
-
- """
- pass
-
- @classmethod
- def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
- rootfs_dir, native_sysroot):
+ native_sysroot):
"""
- Called to do the actual content population for a partition i.e. it
- 'prepares' the partition to be incorporated into the image.
- In this case, does the following:
- - sets up a vfat partition
- - copies all files listed in IMAGE_BOOT_FILES variable
+ Called before do_prepare_partition(), create u-boot specific boot config
"""
- hdddir = "%s/boot" % cr_workdir
- rm_cmd = "rm -rf %s/boot" % cr_workdir
- exec_cmd(rm_cmd)
-
+ hdddir = "%s/boot.%d" % (cr_workdir, part.lineno)
install_cmd = "install -d %s" % hdddir
exec_cmd(install_cmd)
- if not bootimg_dir:
- bootimg_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
- if not bootimg_dir:
- msger.error("Couldn't find DEPLOY_DIR_IMAGE, exiting\n")
+ if not kernel_dir:
+ kernel_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
+ if not kernel_dir:
+ raise WicError("Couldn't find DEPLOY_DIR_IMAGE, exiting")
- msger.debug('Bootimg dir: %s' % bootimg_dir)
+ boot_files = None
+ for (fmt, id) in (("_uuid-%s", part.uuid), ("_label-%s", part.label), (None, None)):
+ if fmt:
+ var = fmt % id
+ else:
+ var = ""
- boot_files = get_bitbake_var("IMAGE_BOOT_FILES")
+ boot_files = get_bitbake_var("IMAGE_BOOT_FILES" + var)
+ if boot_files is not None:
+ break
- if not boot_files:
- msger.error('No boot files defined, IMAGE_BOOT_FILES unset')
+ if boot_files is None:
+ raise WicError('No boot files defined, IMAGE_BOOT_FILES unset for entry #%d' % part.lineno)
- msger.debug('Boot files: %s' % boot_files)
+ logger.debug('Boot files: %s', boot_files)
# list of tuples (src_name, dst_name)
deploy_files = []
@@ -97,16 +69,16 @@ class BootimgPartitionPlugin(SourcePlugin):
if ';' in src_entry:
dst_entry = tuple(src_entry.split(';'))
if not dst_entry[0] or not dst_entry[1]:
- msger.error('Malformed boot file entry: %s' % (src_entry))
+ raise WicError('Malformed boot file entry: %s' % src_entry)
else:
dst_entry = (src_entry, src_entry)
- msger.debug('Destination entry: %r' % (dst_entry,))
+ logger.debug('Destination entry: %r', dst_entry)
deploy_files.append(dst_entry)
+ cls.install_task = [];
for deploy_entry in deploy_files:
src, dst = deploy_entry
- install_task = []
if '*' in src:
# by default install files under their basename
entry_name_fn = os.path.basename
@@ -117,27 +89,106 @@ class BootimgPartitionPlugin(SourcePlugin):
os.path.join(dst,
os.path.basename(name))
- srcs = glob(os.path.join(bootimg_dir, src))
+ srcs = glob(os.path.join(kernel_dir, src))
- msger.debug('Globbed sources: %s' % (', '.join(srcs)))
+ logger.debug('Globbed sources: %s', ', '.join(srcs))
for entry in srcs:
+ src = os.path.relpath(entry, kernel_dir)
entry_dst_name = entry_name_fn(entry)
- install_task.append((entry,
- os.path.join(hdddir,
- entry_dst_name)))
+ cls.install_task.append((src, entry_dst_name))
else:
- install_task = [(os.path.join(bootimg_dir, src),
- os.path.join(hdddir, dst))]
-
- for task in install_task:
- src_path, dst_path = task
- msger.debug('Install %s as %s' % (os.path.basename(src_path),
- dst_path))
- install_cmd = "install -m 0644 -D %s %s" \
- % (src_path, dst_path)
- exec_cmd(install_cmd)
-
- msger.debug('Prepare boot partition using rootfs in %s' % (hdddir))
- part.prepare_rootfs(cr_workdir, oe_builddir, hdddir,
- native_sysroot)
+ cls.install_task.append((src, dst))
+
+ if source_params.get('loader') != "u-boot":
+ return
+
+ configfile = cr.ks.bootloader.configfile
+ custom_cfg = None
+ if configfile:
+ custom_cfg = get_custom_config(configfile)
+ if custom_cfg:
+ # Use a custom configuration for extlinux.conf
+ extlinux_conf = custom_cfg
+ logger.debug("Using custom configuration file "
+ "%s for extlinux.cfg", configfile)
+ else:
+ raise WicError("configfile is specified but failed to "
+ "get it from %s." % configfile)
+
+ if not custom_cfg:
+ # The kernel types supported by the sysboot of u-boot
+ kernel_types = ["zImage", "Image", "fitImage", "uImage", "vmlinux"]
+ has_dtb = False
+ fdt_dir = '/'
+ kernel_name = None
+
+ # Find the kernel image name, from the highest precedence to lowest
+ for image in kernel_types:
+ for task in cls.install_task:
+ src, dst = task
+ if re.match(image, src):
+ kernel_name = os.path.join('/', dst)
+ break
+ if kernel_name:
+ break
+
+ for task in cls.install_task:
+ src, dst = task
+ # We suppose that all the dtb are in the same directory
+ if re.search(r'\.dtb', src) and fdt_dir == '/':
+ has_dtb = True
+ fdt_dir = os.path.join(fdt_dir, os.path.dirname(dst))
+ break
+
+ if not kernel_name:
+ raise WicError('No kernel file found')
+
+ # Compose the extlinux.conf
+ extlinux_conf = "default Yocto\n"
+ extlinux_conf += "label Yocto\n"
+ extlinux_conf += " kernel %s\n" % kernel_name
+ if has_dtb:
+ extlinux_conf += " fdtdir %s\n" % fdt_dir
+ bootloader = cr.ks.bootloader
+ extlinux_conf += "append root=%s rootwait %s\n" \
+ % (cr.rootdev, bootloader.append if bootloader.append else '')
+
+ install_cmd = "install -d %s/extlinux/" % hdddir
+ exec_cmd(install_cmd)
+ cfg = open("%s/extlinux/extlinux.conf" % hdddir, "w")
+ cfg.write(extlinux_conf)
+ cfg.close()
+
+
+ @classmethod
+ def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
+ oe_builddir, bootimg_dir, kernel_dir,
+ rootfs_dir, native_sysroot):
+ """
+ Called to do the actual content population for a partition i.e. it
+ 'prepares' the partition to be incorporated into the image.
+ In this case, does the following:
+ - sets up a vfat partition
+ - copies all files listed in IMAGE_BOOT_FILES variable
+ """
+ hdddir = "%s/boot.%d" % (cr_workdir, part.lineno)
+ if not kernel_dir:
+ kernel_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
+ if not kernel_dir:
+ raise WicError("Couldn't find DEPLOY_DIR_IMAGE, exiting")
+
+ logger.debug('Kernel dir: %s', bootimg_dir)
+
+
+ for task in cls.install_task:
+ src_path, dst_path = task
+ logger.debug('Install %s as %s', src_path, dst_path)
+ install_cmd = "install -m 0644 -D %s %s" \
+ % (os.path.join(kernel_dir, src_path),
+ os.path.join(hdddir, dst_path))
+ exec_cmd(install_cmd)
+
+ logger.debug('Prepare boot partition using rootfs in %s', hdddir)
+ part.prepare_rootfs(cr_workdir, oe_builddir, hdddir,
+ native_sysroot, False)
diff --git a/scripts/lib/wic/plugins/source/bootimg-pcbios.py b/scripts/lib/wic/plugins/source/bootimg-pcbios.py
index 96ed54dbad..32e47f1831 100644
--- a/scripts/lib/wic/plugins/source/bootimg-pcbios.py
+++ b/scripts/lib/wic/plugins/source/bootimg-pcbios.py
@@ -1,21 +1,7 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# Copyright (c) 2014, Intel Corporation.
-# All rights reserved.
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# SPDX-License-Identifier: GPL-2.0-only
#
# DESCRIPTION
# This implements the 'bootimg-pcbios' source plugin class for 'wic'
@@ -24,14 +10,17 @@
# Tom Zanussi <tom.zanussi (at] linux.intel.com>
#
+import logging
import os
+import re
-from wic.utils.errors import ImageError
-from wic import kickstart, msger
-from wic.utils import runner
+from wic import WicError
+from wic.engine import get_custom_config
from wic.pluginbase import SourcePlugin
-from wic.utils.oe.misc import exec_cmd, exec_native_cmd, \
- get_bitbake_var, BOOTDD_EXTRA_SPACE
+from wic.misc import (exec_cmd, exec_native_cmd,
+ get_bitbake_var, BOOTDD_EXTRA_SPACE)
+
+logger = logging.getLogger('wic')
class BootimgPcbiosPlugin(SourcePlugin):
"""
@@ -41,33 +30,51 @@ class BootimgPcbiosPlugin(SourcePlugin):
name = 'bootimg-pcbios'
@classmethod
+ def _get_bootimg_dir(cls, bootimg_dir, dirname):
+ """
+ Check if dirname exists in default bootimg_dir or in STAGING_DIR.
+ """
+ staging_datadir = get_bitbake_var("STAGING_DATADIR")
+ for result in (bootimg_dir, staging_datadir):
+ if os.path.exists("%s/%s" % (result, dirname)):
+ return result
+
+ # STAGING_DATADIR is expanded with MLPREFIX if multilib is enabled
+ # but dependency syslinux is still populated to original STAGING_DATADIR
+ nonarch_datadir = re.sub('/[^/]*recipe-sysroot', '/recipe-sysroot', staging_datadir)
+ if os.path.exists(os.path.join(nonarch_datadir, dirname)):
+ return nonarch_datadir
+
+ raise WicError("Couldn't find correct bootimg_dir, exiting")
+
+ @classmethod
def do_install_disk(cls, disk, disk_name, creator, workdir, oe_builddir,
bootimg_dir, kernel_dir, native_sysroot):
"""
Called after all partitions have been prepared and assembled into a
disk image. In this case, we install the MBR.
"""
+ bootimg_dir = cls._get_bootimg_dir(bootimg_dir, 'syslinux')
mbrfile = "%s/syslinux/" % bootimg_dir
if creator.ptable_format == 'msdos':
mbrfile += "mbr.bin"
elif creator.ptable_format == 'gpt':
mbrfile += "gptmbr.bin"
else:
- msger.error("Unsupported partition table: %s" % creator.ptable_format)
+ raise WicError("Unsupported partition table: %s" %
+ creator.ptable_format)
if not os.path.exists(mbrfile):
- msger.error("Couldn't find %s. If using the -e option, do you "
- "have the right MACHINE set in local.conf? If not, "
- "is the bootimg_dir path correct?" % mbrfile)
+ raise WicError("Couldn't find %s. If using the -e option, do you "
+ "have the right MACHINE set in local.conf? If not, "
+ "is the bootimg_dir path correct?" % mbrfile)
full_path = creator._full_path(workdir, disk_name, "direct")
- msger.debug("Installing MBR on disk %s as %s with size %s bytes" \
- % (disk_name, full_path, disk['min_size']))
+ logger.debug("Installing MBR on disk %s as %s with size %s bytes",
+ disk_name, full_path, disk.min_size)
- rcode = runner.show(['dd', 'if=%s' % mbrfile,
- 'of=%s' % full_path, 'conv=notrunc'])
- if rcode != 0:
- raise ImageError("Unable to set MBR to %s" % full_path)
+ dd_cmd = "dd if=%s of=%s conv=notrunc" % (mbrfile, full_path)
+ exec_cmd(dd_cmd, native_sysroot)
@classmethod
def do_configure_partition(cls, part, source_params, creator, cr_workdir,
@@ -77,43 +84,52 @@ class BootimgPcbiosPlugin(SourcePlugin):
Called before do_prepare_partition(), creates syslinux config
"""
hdddir = "%s/hdd/boot" % cr_workdir
- rm_cmd = "rm -rf " + cr_workdir
- exec_cmd(rm_cmd)
install_cmd = "install -d %s" % hdddir
exec_cmd(install_cmd)
- splash = os.path.join(cr_workdir, "/hdd/boot/splash.jpg")
- if os.path.exists(splash):
- splashline = "menu background splash.jpg"
- else:
- splashline = ""
-
- options = creator.ks.handler.bootloader.appendLine
-
- syslinux_conf = ""
- syslinux_conf += "PROMPT 0\n"
- timeout = kickstart.get_timeout(creator.ks)
- if not timeout:
- timeout = 0
- syslinux_conf += "TIMEOUT " + str(timeout) + "\n"
- syslinux_conf += "\n"
- syslinux_conf += "ALLOWOPTIONS 1\n"
- syslinux_conf += "SERIAL 0 115200\n"
- syslinux_conf += "\n"
- if splashline:
- syslinux_conf += "%s\n" % splashline
- syslinux_conf += "DEFAULT boot\n"
- syslinux_conf += "LABEL boot\n"
-
- kernel = "/vmlinuz"
- syslinux_conf += "KERNEL " + kernel + "\n"
-
- syslinux_conf += "APPEND label=boot root=%s %s\n" % \
- (creator.rootdev, options)
-
- msger.debug("Writing syslinux config %s/hdd/boot/syslinux.cfg" \
- % cr_workdir)
+ bootloader = creator.ks.bootloader
+
+ custom_cfg = None
+ if bootloader.configfile:
+ custom_cfg = get_custom_config(bootloader.configfile)
+ if custom_cfg:
+ # Use a custom configuration for grub
+ syslinux_conf = custom_cfg
+ logger.debug("Using custom configuration file %s "
+ "for syslinux.cfg", bootloader.configfile)
+ else:
+ raise WicError("configfile is specified but failed to "
+ "get it from %s." % bootloader.configfile)
+
+ if not custom_cfg:
+ # Create syslinux configuration using parameters from wks file
+ splash = os.path.join(cr_workdir, "/hdd/boot/splash.jpg")
+ if os.path.exists(splash):
+ splashline = "menu background splash.jpg"
+ else:
+ splashline = ""
+
+ syslinux_conf = ""
+ syslinux_conf += "PROMPT 0\n"
+ syslinux_conf += "TIMEOUT " + str(bootloader.timeout) + "\n"
+ syslinux_conf += "\n"
+ syslinux_conf += "ALLOWOPTIONS 1\n"
+ syslinux_conf += "SERIAL 0 115200\n"
+ syslinux_conf += "\n"
+ if splashline:
+ syslinux_conf += "%s\n" % splashline
+ syslinux_conf += "DEFAULT boot\n"
+ syslinux_conf += "LABEL boot\n"
+
+ kernel = "/vmlinuz"
+ syslinux_conf += "KERNEL " + kernel + "\n"
+
+ syslinux_conf += "APPEND label=boot root=%s %s\n" % \
+ (creator.rootdev, bootloader.append)
+
+ logger.debug("Writing syslinux config %s/hdd/boot/syslinux.cfg",
+ cr_workdir)
cfg = open("%s/hdd/boot/syslinux.cfg" % cr_workdir, "w")
cfg.write(syslinux_conf)
cfg.close()
@@ -127,33 +143,31 @@ class BootimgPcbiosPlugin(SourcePlugin):
'prepares' the partition to be incorporated into the image.
In this case, prepare content for legacy bios boot partition.
"""
- def _has_syslinux(dirname):
- if dirname:
- syslinux = "%s/syslinux" % dirname
- if os.path.exists(syslinux):
- return True
- return False
-
- if not _has_syslinux(bootimg_dir):
- bootimg_dir = get_bitbake_var("STAGING_DATADIR")
- if not bootimg_dir:
- msger.error("Couldn't find STAGING_DATADIR, exiting\n")
- if not _has_syslinux(bootimg_dir):
- msger.error("Please build syslinux first\n")
- # just so the result notes display it
- creator.set_bootimg_dir(bootimg_dir)
+ bootimg_dir = cls._get_bootimg_dir(bootimg_dir, 'syslinux')
staging_kernel_dir = kernel_dir
hdddir = "%s/hdd/boot" % cr_workdir
- install_cmd = "install -m 0644 %s/bzImage %s/vmlinuz" \
- % (staging_kernel_dir, hdddir)
- exec_cmd(install_cmd)
-
- install_cmd = "install -m 444 %s/syslinux/ldlinux.sys %s/ldlinux.sys" \
- % (bootimg_dir, hdddir)
- exec_cmd(install_cmd)
+ kernel = get_bitbake_var("KERNEL_IMAGETYPE")
+ if get_bitbake_var("INITRAMFS_IMAGE_BUNDLE") == "1":
+ if get_bitbake_var("INITRAMFS_IMAGE"):
+ kernel = "%s-%s.bin" % \
+ (get_bitbake_var("KERNEL_IMAGETYPE"), get_bitbake_var("INITRAMFS_LINK_NAME"))
+
+ cmds = ("install -m 0644 %s/%s %s/vmlinuz" %
+ (staging_kernel_dir, kernel, hdddir),
+ "install -m 444 %s/syslinux/ldlinux.sys %s/ldlinux.sys" %
+ (bootimg_dir, hdddir),
+ "install -m 0644 %s/syslinux/vesamenu.c32 %s/vesamenu.c32" %
+ (bootimg_dir, hdddir),
+ "install -m 444 %s/syslinux/libcom32.c32 %s/libcom32.c32" %
+ (bootimg_dir, hdddir),
+ "install -m 444 %s/syslinux/libutil.c32 %s/libutil.c32" %
+ (bootimg_dir, hdddir))
+
+ for install_cmd in cmds:
+ exec_cmd(install_cmd)
du_cmd = "du -bks %s" % hdddir
out = exec_cmd(du_cmd)
@@ -166,19 +180,16 @@ class BootimgPcbiosPlugin(SourcePlugin):
blocks += extra_blocks
- msger.debug("Added %d extra blocks to %s to get to %d total blocks" % \
- (extra_blocks, part.mountpoint, blocks))
-
- # Ensure total sectors is an integral number of sectors per
- # track or mcopy will complain. Sectors are 512 bytes, and we
- # generate images with 32 sectors per track. This calculation is
- # done in blocks, thus the mod by 16 instead of 32.
- blocks += (16 - (blocks % 16))
+ logger.debug("Added %d extra blocks to %s to get to %d total blocks",
+ extra_blocks, part.mountpoint, blocks)
# dosfs image, created by mkdosfs
- bootimg = "%s/boot.img" % cr_workdir
+ bootimg = "%s/boot%s.img" % (cr_workdir, part.lineno)
+
+ label = part.label if part.label else "boot"
- dosfs_cmd = "mkdosfs -n boot -S 512 -C %s %d" % (bootimg, blocks)
+ dosfs_cmd = "mkdosfs -n %s -i %s -S 512 -C %s %d" % \
+ (label, part.fsuuid, bootimg, blocks)
exec_native_cmd(dosfs_cmd, native_sysroot)
mcopy_cmd = "mcopy -i %s -s %s/* ::/" % (bootimg, hdddir)
@@ -194,7 +205,5 @@ class BootimgPcbiosPlugin(SourcePlugin):
out = exec_cmd(du_cmd)
bootimg_size = out.split()[0]
- part.set_size(bootimg_size)
- part.set_source_file(bootimg)
-
-
+ part.size = int(bootimg_size)
+ part.source_file = bootimg
diff --git a/scripts/lib/wic/plugins/source/empty.py b/scripts/lib/wic/plugins/source/empty.py
new file mode 100644
index 0000000000..041617d648
--- /dev/null
+++ b/scripts/lib/wic/plugins/source/empty.py
@@ -0,0 +1,32 @@
+#
+# SPDX-License-Identifier: MIT
+#
+
+# The empty wic plugin is used to create unformatted empty partitions for wic
+# images.
+# To use it you must pass "empty" as argument for the "--source" parameter in
+# the wks file. For example:
+# part foo --source empty --ondisk sda --size="1024" --align 1024
+
+import logging
+
+from wic.pluginbase import SourcePlugin
+
+logger = logging.getLogger('wic')
+
+class EmptyPartitionPlugin(SourcePlugin):
+ """
+ Populate unformatted empty partition.
+ """
+
+ name = 'empty'
+
+ @classmethod
+ def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
+ oe_builddir, bootimg_dir, kernel_dir,
+ rootfs_dir, native_sysroot):
+ """
+ Called to do the actual content population for a partition i.e. it
+ 'prepares' the partition to be incorporated into the image.
+ """
+ return
diff --git a/scripts/lib/wic/plugins/source/fsimage.py b/scripts/lib/wic/plugins/source/fsimage.py
deleted file mode 100644
index f894e89367..0000000000
--- a/scripts/lib/wic/plugins/source/fsimage.py
+++ /dev/null
@@ -1,73 +0,0 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-
-import os
-
-from wic import msger
-from wic.pluginbase import SourcePlugin
-from wic.utils.oe.misc import get_bitbake_var
-
-class FSImagePlugin(SourcePlugin):
- """
- Add an already existing filesystem image to the partition layout.
- """
-
- name = 'fsimage'
-
- @classmethod
- def do_install_disk(cls, disk, disk_name, cr, workdir, oe_builddir,
- bootimg_dir, kernel_dir, native_sysroot):
- """
- Called after all partitions have been prepared and assembled into a
- disk image. Do nothing.
- """
- pass
-
- @classmethod
- def do_configure_partition(cls, part, source_params, cr, cr_workdir,
- oe_builddir, bootimg_dir, kernel_dir,
- native_sysroot):
- """
- Called before do_prepare_partition(). Possibly prepare
- configuration files of some sort.
- """
- pass
-
- @classmethod
- def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
- oe_builddir, bootimg_dir, kernel_dir,
- rootfs_dir, native_sysroot):
- """
- Called to do the actual content population for a partition i.e. it
- 'prepares' the partition to be incorporated into the image.
- """
- if not bootimg_dir:
- bootimg_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
- if not bootimg_dir:
- msger.error("Couldn't find DEPLOY_DIR_IMAGE, exiting\n")
-
- msger.debug('Bootimg dir: %s' % bootimg_dir)
-
- if 'file' not in source_params:
- msger.error("No file specified\n")
- return
-
- src = os.path.join(bootimg_dir, source_params['file'])
-
-
- msger.debug('Preparing partition using image %s' % (src))
- part.prepare_rootfs_from_fs_image(cr_workdir, src, "")
diff --git a/scripts/lib/wic/plugins/source/isoimage-isohybrid.py b/scripts/lib/wic/plugins/source/isoimage-isohybrid.py
index 9472d8abb9..afc9ea0f8f 100644
--- a/scripts/lib/wic/plugins/source/isoimage-isohybrid.py
+++ b/scripts/lib/wic/plugins/source/isoimage-isohybrid.py
@@ -1,18 +1,5 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# SPDX-License-Identifier: GPL-2.0-only
#
# DESCRIPTION
# This implements the 'isoimage-isohybrid' source plugin class for 'wic'
@@ -20,13 +7,18 @@
# AUTHORS
# Mihaly Varga <mihaly.varga (at] ni.com>
+import glob
+import logging
import os
import re
import shutil
-from wic import kickstart, msger
+from wic import WicError
+from wic.engine import get_custom_config
from wic.pluginbase import SourcePlugin
-from wic.utils.oe.misc import exec_cmd, exec_native_cmd, get_bitbake_var
+from wic.misc import exec_cmd, exec_native_cmd, get_bitbake_var
+
+logger = logging.getLogger('wic')
class IsoImagePlugin(SourcePlugin):
"""
@@ -42,7 +34,7 @@ class IsoImagePlugin(SourcePlugin):
Example kickstart file:
part /boot --source isoimage-isohybrid --sourceparams="loader=grub-efi, \\
- image_name= IsoImage" --ondisk cd --label LIVECD --fstype=ext2
+ image_name= IsoImage" --ondisk cd --label LIVECD
bootloader --timeout=10 --append=" "
In --sourceparams "loader" specifies the bootloader used for booting in EFI
@@ -58,19 +50,17 @@ class IsoImagePlugin(SourcePlugin):
"""
Create loader-specific (syslinux) config
"""
- splash = os.path.join(cr_workdir, "/ISO/boot/splash.jpg")
+ splash = os.path.join(cr_workdir, "ISO/boot/splash.jpg")
if os.path.exists(splash):
splashline = "menu background splash.jpg"
else:
splashline = ""
- options = creator.ks.handler.bootloader.appendLine
-
- timeout = kickstart.get_timeout(creator.ks, 10)
+ bootloader = creator.ks.bootloader
syslinux_conf = ""
syslinux_conf += "PROMPT 0\n"
- syslinux_conf += "TIMEOUT %s \n" % timeout
+ syslinux_conf += "TIMEOUT %s \n" % (bootloader.timeout or 10)
syslinux_conf += "\n"
syslinux_conf += "ALLOWOPTIONS 1\n"
syslinux_conf += "SERIAL 0 115200\n"
@@ -80,52 +70,73 @@ class IsoImagePlugin(SourcePlugin):
syslinux_conf += "DEFAULT boot\n"
syslinux_conf += "LABEL boot\n"
- kernel = "/bzImage"
- syslinux_conf += "KERNEL " + kernel + "\n"
- syslinux_conf += "APPEND initrd=/initrd LABEL=boot %s\n" % options
+ kernel = get_bitbake_var("KERNEL_IMAGETYPE")
+ if get_bitbake_var("INITRAMFS_IMAGE_BUNDLE") == "1":
+ if get_bitbake_var("INITRAMFS_IMAGE"):
+ kernel = "%s-%s.bin" % \
+ (get_bitbake_var("KERNEL_IMAGETYPE"), get_bitbake_var("INITRAMFS_LINK_NAME"))
+
+ syslinux_conf += "KERNEL /" + kernel + "\n"
+ syslinux_conf += "APPEND initrd=/initrd LABEL=boot %s\n" \
+ % bootloader.append
+
+ logger.debug("Writing syslinux config %s/ISO/isolinux/isolinux.cfg",
+ cr_workdir)
- msger.debug("Writing syslinux config %s/ISO/isolinux/isolinux.cfg" \
- % cr_workdir)
with open("%s/ISO/isolinux/isolinux.cfg" % cr_workdir, "w") as cfg:
cfg.write(syslinux_conf)
@classmethod
- def do_configure_grubefi(cls, part, creator, cr_workdir):
+ def do_configure_grubefi(cls, part, creator, target_dir):
"""
Create loader-specific (grub-efi) config
"""
- splash = os.path.join(cr_workdir, "/EFI/boot/splash.jpg")
- if os.path.exists(splash):
- splashline = "menu background splash.jpg"
+ configfile = creator.ks.bootloader.configfile
+ if configfile:
+ grubefi_conf = get_custom_config(configfile)
+ if grubefi_conf:
+ logger.debug("Using custom configuration file %s for grub.cfg",
+ configfile)
+ else:
+ raise WicError("configfile is specified "
+ "but failed to get it from %s", configfile)
else:
- splashline = ""
-
- options = creator.ks.handler.bootloader.appendLine
-
- grubefi_conf = ""
- grubefi_conf += "serial --unit=0 --speed=115200 --word=8 "
- grubefi_conf += "--parity=no --stop=1\n"
- grubefi_conf += "default=boot\n"
- timeout = kickstart.get_timeout(creator.ks, 10)
- grubefi_conf += "timeout=%s\n" % timeout
- grubefi_conf += "\n"
- grubefi_conf += "search --set=root --label %s " % part.label
- grubefi_conf += "\n"
- grubefi_conf += "menuentry 'boot'{\n"
-
- kernel = "/bzImage"
-
- grubefi_conf += "linux %s rootwait %s\n" \
- % (kernel, options)
- grubefi_conf += "initrd /initrd \n"
- grubefi_conf += "}\n"
-
- if splashline:
- grubefi_conf += "%s\n" % splashline
-
- msger.debug("Writing grubefi config %s/EFI/BOOT/grub.cfg" \
- % cr_workdir)
- with open("%s/EFI/BOOT/grub.cfg" % cr_workdir, "w") as cfg:
+ splash = os.path.join(target_dir, "splash.jpg")
+ if os.path.exists(splash):
+ splashline = "menu background splash.jpg"
+ else:
+ splashline = ""
+
+ bootloader = creator.ks.bootloader
+
+ grubefi_conf = ""
+ grubefi_conf += "serial --unit=0 --speed=115200 --word=8 "
+ grubefi_conf += "--parity=no --stop=1\n"
+ grubefi_conf += "default=boot\n"
+ grubefi_conf += "timeout=%s\n" % (bootloader.timeout or 10)
+ grubefi_conf += "\n"
+ grubefi_conf += "search --set=root --label %s " % part.label
+ grubefi_conf += "\n"
+ grubefi_conf += "menuentry 'boot'{\n"
+
+ kernel = get_bitbake_var("KERNEL_IMAGETYPE")
+ if get_bitbake_var("INITRAMFS_IMAGE_BUNDLE") == "1":
+ if get_bitbake_var("INITRAMFS_IMAGE"):
+ kernel = "%s-%s.bin" % \
+ (get_bitbake_var("KERNEL_IMAGETYPE"), get_bitbake_var("INITRAMFS_LINK_NAME"))
+
+ grubefi_conf += "linux /%s rootwait %s\n" \
+ % (kernel, bootloader.append)
+ grubefi_conf += "initrd /initrd \n"
+ grubefi_conf += "}\n"
+
+ if splashline:
+ grubefi_conf += "%s\n" % splashline
+
+ cfg_path = os.path.join(target_dir, "grub.cfg")
+ logger.debug("Writing grubefi config %s", cfg_path)
+
+ with open(cfg_path, "w") as cfg:
cfg.write(grubefi_conf)
@staticmethod
@@ -134,28 +145,28 @@ class IsoImagePlugin(SourcePlugin):
Create path for initramfs image
"""
- initrd = get_bitbake_var("INITRD")
+ initrd = get_bitbake_var("INITRD_LIVE") or get_bitbake_var("INITRD")
if not initrd:
initrd_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
if not initrd_dir:
- msger.error("Couldn't find DEPLOY_DIR_IMAGE, exiting.\n")
+ raise WicError("Couldn't find DEPLOY_DIR_IMAGE, exiting.")
image_name = get_bitbake_var("IMAGE_BASENAME")
if not image_name:
- msger.error("Couldn't find IMAGE_BASENAME, exiting.\n")
+ raise WicError("Couldn't find IMAGE_BASENAME, exiting.")
image_type = get_bitbake_var("INITRAMFS_FSTYPES")
if not image_type:
- msger.error("Couldn't find INITRAMFS_FSTYPES, exiting.\n")
+ raise WicError("Couldn't find INITRAMFS_FSTYPES, exiting.")
- machine_arch = get_bitbake_var("MACHINE_ARCH")
- if not machine_arch:
- msger.error("Couldn't find MACHINE_ARCH, exiting.\n")
+ machine = os.path.basename(initrd_dir)
- initrd = "%s/%s-initramfs-%s.%s" \
- % (initrd_dir, image_name, machine_arch, image_type)
+ pattern = '%s/%s*%s.%s' % (initrd_dir, image_name, machine, image_type)
+ files = glob.glob(pattern)
+ if files:
+ initrd = files[0]
- if not os.path.exists(initrd):
+ if not initrd or not os.path.exists(initrd):
# Create initrd from rootfs directory
initrd = "%s/initrd.cpio.gz" % cr_workdir
initrd_dir = "%s/INITRD" % cr_workdir
@@ -174,63 +185,16 @@ class IsoImagePlugin(SourcePlugin):
os.symlink(os.readlink("%s/sbin/init" % rootfs_dir), \
"%s/init" % initrd_dir)
else:
- msger.error("Couldn't find or build initrd, exiting.\n")
+ raise WicError("Couldn't find or build initrd, exiting.")
- exec_cmd("cd %s && find . | cpio -o -H newc >%s/initrd.cpio " \
- % (initrd_dir, cr_workdir), as_shell=True)
- exec_cmd("gzip -f -9 -c %s/initrd.cpio > %s" \
- % (cr_workdir, initrd), as_shell=True)
+ exec_cmd("cd %s && find . | cpio -o -H newc -R root:root >%s/initrd.cpio " \
+ % (initrd_dir, cr_workdir), as_shell=True)
+ exec_cmd("gzip -f -9 %s/initrd.cpio" % cr_workdir, as_shell=True)
shutil.rmtree(initrd_dir)
return initrd
@classmethod
- def do_stage_partition(cls, part, source_params, creator, cr_workdir,
- oe_builddir, bootimg_dir, kernel_dir,
- native_sysroot):
- """
- Special content staging called before do_prepare_partition().
- It cheks if all necessary tools are available, if not
- tries to instal them.
- """
- # Make sure parted is available in native sysroot
- if not os.path.isfile("%s/usr/sbin/parted" % native_sysroot):
- msger.info("Building parted-native...\n")
- exec_cmd("bitbake parted-native")
-
- # Make sure mkfs.ext2/3/4 is available in native sysroot
- if not os.path.isfile("%s/sbin/mkfs.ext2" % native_sysroot):
- msger.info("Building e2fsprogs-native...\n")
- exec_cmd("bitbake e2fsprogs-native")
-
- # Make sure syslinux is available in sysroot and in native sysroot
- syslinux_dir = get_bitbake_var("STAGING_DATADIR")
- if not syslinux_dir:
- msger.error("Couldn't find STAGING_DATADIR, exiting.\n")
- if not os.path.exists("%s/syslinux" % syslinux_dir):
- msger.info("Building syslinux...\n")
- exec_cmd("bitbake syslinux")
- msger.info("Building syslinux-native...\n")
- exec_cmd("bitbake syslinux-native")
- if not os.path.exists("%s/syslinux" % syslinux_dir):
- msger.error("Please build syslinux first\n")
-
- #Make sure mkisofs is available in native sysroot
- if not os.path.isfile("%s/usr/bin/mkisofs" % native_sysroot):
- msger.info("Building cdrtools-native...\n")
- exec_cmd("bitbake cdrtools-native")
-
- # Make sure mkfs.vfat is available in native sysroot
- if not os.path.isfile("%s/sbin/mkfs.vfat" % native_sysroot):
- msger.info("Building dosfstools-native...\n")
- exec_cmd("bitbake dosfstools-native")
-
- # Make sure mtools is available in native sysroot
- if not os.path.isfile("%s/usr/bin/mcopy" % native_sysroot):
- msger.info("Building mtools-native...\n")
- exec_cmd("bitbake mtools-native")
-
- @classmethod
def do_configure_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
native_sysroot):
@@ -239,18 +203,30 @@ class IsoImagePlugin(SourcePlugin):
"""
isodir = "%s/ISO/" % cr_workdir
- if os.path.exists(cr_workdir):
- shutil.rmtree(cr_workdir)
+ if os.path.exists(isodir):
+ shutil.rmtree(isodir)
install_cmd = "install -d %s " % isodir
exec_cmd(install_cmd)
# Overwrite the name of the created image
- msger.debug("%s" % source_params)
+ logger.debug(source_params)
if 'image_name' in source_params and \
source_params['image_name'].strip():
creator.name = source_params['image_name'].strip()
- msger.debug("The name of the image is: %s" % creator.name)
+ logger.debug("The name of the image is: %s", creator.name)
+
+ @staticmethod
+ def _install_payload(source_params, iso_dir):
+ """
+ Copies contents of payload directory (as specified in 'payload_dir' param) into iso_dir
+ """
+
+ if source_params.get('payload_dir'):
+ payload_dir = source_params['payload_dir']
+
+ logger.debug("Payload directory: %s", payload_dir)
+ shutil.copytree(payload_dir, iso_dir, symlinks=True, dirs_exist_ok=True)
@classmethod
def do_prepare_partition(cls, part, source_params, creator, cr_workdir,
@@ -264,154 +240,108 @@ class IsoImagePlugin(SourcePlugin):
isodir = "%s/ISO" % cr_workdir
- if part.rootfs is None:
+ cls._install_payload(source_params, isodir)
+
+ if part.rootfs_dir is None:
if not 'ROOTFS_DIR' in rootfs_dir:
- msger.error("Couldn't find --rootfs-dir, exiting.\n")
+ raise WicError("Couldn't find --rootfs-dir, exiting.")
rootfs_dir = rootfs_dir['ROOTFS_DIR']
else:
- if part.rootfs in rootfs_dir:
- rootfs_dir = rootfs_dir[part.rootfs]
- elif part.rootfs:
- rootfs_dir = part.rootfs
+ if part.rootfs_dir in rootfs_dir:
+ rootfs_dir = rootfs_dir[part.rootfs_dir]
+ elif part.rootfs_dir:
+ rootfs_dir = part.rootfs_dir
else:
- msg = "Couldn't find --rootfs-dir=%s connection "
- msg += "or it is not a valid path, exiting.\n"
- msger.error(msg % part.rootfs)
+ raise WicError("Couldn't find --rootfs-dir=%s connection "
+ "or it is not a valid path, exiting." %
+ part.rootfs_dir)
if not os.path.isdir(rootfs_dir):
rootfs_dir = get_bitbake_var("IMAGE_ROOTFS")
if not os.path.isdir(rootfs_dir):
- msger.error("Couldn't find IMAGE_ROOTFS, exiting.\n")
+ raise WicError("Couldn't find IMAGE_ROOTFS, exiting.")
- part.set_rootfs(rootfs_dir)
-
- # Prepare rootfs.img
- hdd_dir = get_bitbake_var("HDDDIR")
+ part.rootfs_dir = rootfs_dir
+ deploy_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
img_iso_dir = get_bitbake_var("ISODIR")
- rootfs_img = "%s/rootfs.img" % hdd_dir
- if not os.path.isfile(rootfs_img):
- rootfs_img = "%s/rootfs.img" % img_iso_dir
- if not os.path.isfile(rootfs_img):
- # check if rootfs.img is in deploydir
- deploy_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
- image_name = get_bitbake_var("IMAGE_LINK_NAME")
- rootfs_img = "%s/%s.%s" \
- % (deploy_dir, image_name, part.fstype)
-
- if not os.path.isfile(rootfs_img):
- # create image file with type specified by --fstype
- # which contains rootfs
- du_cmd = "du -bks %s" % rootfs_dir
- out = exec_cmd(du_cmd)
- part.set_size(int(out.split()[0]))
- part.extra_space = 0
- part.overhead_factor = 1.2
- part.prepare_rootfs(cr_workdir, oe_builddir, rootfs_dir, \
- native_sysroot)
- rootfs_img = part.source_file
-
- install_cmd = "install -m 0644 %s %s/rootfs.img" \
- % (rootfs_img, isodir)
- exec_cmd(install_cmd)
-
# Remove the temporary file created by part.prepare_rootfs()
if os.path.isfile(part.source_file):
os.remove(part.source_file)
- # Prepare initial ramdisk
- initrd = "%s/initrd" % hdd_dir
- if not os.path.isfile(initrd):
- initrd = "%s/initrd" % img_iso_dir
- if not os.path.isfile(initrd):
- initrd = cls._build_initramfs_path(rootfs_dir, cr_workdir)
-
- install_cmd = "install -m 0644 %s %s/initrd" \
- % (initrd, isodir)
+ # Support using a different initrd other than default
+ if source_params.get('initrd'):
+ initrd = source_params['initrd']
+ if not deploy_dir:
+ raise WicError("Couldn't find DEPLOY_DIR_IMAGE, exiting")
+ cp_cmd = "cp %s/%s %s" % (deploy_dir, initrd, cr_workdir)
+ exec_cmd(cp_cmd)
+ else:
+ # Prepare initial ramdisk
+ initrd = "%s/initrd" % deploy_dir
+ if not os.path.isfile(initrd):
+ initrd = "%s/initrd" % img_iso_dir
+ if not os.path.isfile(initrd):
+ initrd = cls._build_initramfs_path(rootfs_dir, cr_workdir)
+
+ install_cmd = "install -m 0644 %s %s/initrd" % (initrd, isodir)
exec_cmd(install_cmd)
# Remove the temporary file created by _build_initramfs_path function
if os.path.isfile("%s/initrd.cpio.gz" % cr_workdir):
os.remove("%s/initrd.cpio.gz" % cr_workdir)
- # Install bzImage
- install_cmd = "install -m 0644 %s/bzImage %s/bzImage" % \
- (kernel_dir, isodir)
+ kernel = get_bitbake_var("KERNEL_IMAGETYPE")
+ if get_bitbake_var("INITRAMFS_IMAGE_BUNDLE") == "1":
+ if get_bitbake_var("INITRAMFS_IMAGE"):
+ kernel = "%s-%s.bin" % \
+ (get_bitbake_var("KERNEL_IMAGETYPE"), get_bitbake_var("INITRAMFS_LINK_NAME"))
+
+ install_cmd = "install -m 0644 %s/%s %s/%s" % \
+ (kernel_dir, kernel, isodir, kernel)
exec_cmd(install_cmd)
#Create bootloader for efi boot
try:
- if source_params['loader'] == 'grub-efi':
- # Builds grub.cfg if ISODIR didn't exist or
- # didn't contains grub.cfg
- bootimg_dir = img_iso_dir
- if not os.path.exists("%s/EFI/BOOT" % bootimg_dir):
- bootimg_dir = "%s/bootimg" % cr_workdir
- if os.path.exists(bootimg_dir):
- shutil.rmtree(bootimg_dir)
- install_cmd = "install -d %s/EFI/BOOT" % bootimg_dir
- exec_cmd(install_cmd)
-
- if not os.path.isfile("%s/EFI/BOOT/boot.cfg" % bootimg_dir):
- cls.do_configure_grubefi(part, creator, bootimg_dir)
+ target_dir = "%s/EFI/BOOT" % isodir
+ if os.path.exists(target_dir):
+ shutil.rmtree(target_dir)
+
+ os.makedirs(target_dir)
+ if source_params['loader'] == 'grub-efi':
# Builds bootx64.efi/bootia32.efi if ISODIR didn't exist or
# didn't contains it
target_arch = get_bitbake_var("TARGET_SYS")
if not target_arch:
- msger.error("Coludn't find target architecture\n")
+ raise WicError("Coludn't find target architecture")
if re.match("x86_64", target_arch):
- grub_target = 'x86_64-efi'
- grub_image = "bootx64.efi"
+ grub_src_image = "grub-efi-bootx64.efi"
+ grub_dest_image = "bootx64.efi"
elif re.match('i.86', target_arch):
- grub_target = 'i386-efi'
- grub_image = "bootia32.efi"
+ grub_src_image = "grub-efi-bootia32.efi"
+ grub_dest_image = "bootia32.efi"
else:
- msger.error("grub-efi is incompatible with target %s\n" \
- % target_arch)
-
- if not os.path.isfile("%s/EFI/BOOT/%s" \
- % (bootimg_dir, grub_image)):
- grub_path = get_bitbake_var("STAGING_LIBDIR")
- if not grub_path:
- msger.error("Couldn't find STAGING_LIBDIR, exiting.\n")
-
- grub_core = "%s/grub/%s" % (grub_path, grub_target)
- if not os.path.exists(grub_core):
- msger.info("Building grub-efi...\n")
- exec_cmd("bitbake grub-efi")
- if not os.path.exists(grub_core):
- msger.error("Please build grub-efi first\n")
-
- grub_cmd = "grub-mkimage -p '/EFI/BOOT' "
- grub_cmd += "-d %s " % grub_core
- grub_cmd += "-O %s -o %s/EFI/BOOT/%s " \
- % (grub_target, bootimg_dir, grub_image)
- grub_cmd += "part_gpt part_msdos ntfs ntfscomp fat ext2 "
- grub_cmd += "normal chain boot configfile linux multiboot "
- grub_cmd += "search efi_gop efi_uga font gfxterm gfxmenu "
- grub_cmd += "terminal minicmd test iorw loadenv echo help "
- grub_cmd += "reboot serial terminfo iso9660 loopback tar "
- grub_cmd += "memdisk ls search_fs_uuid udf btrfs xfs lvm "
- grub_cmd += "reiserfs ata "
- exec_native_cmd(grub_cmd, native_sysroot)
-
- else:
- # TODO: insert gummiboot stuff
- msger.error("unrecognized bootimg-efi loader: %s" \
- % source_params['loader'])
- except KeyError:
- msger.error("bootimg-efi requires a loader, none specified")
+ raise WicError("grub-efi is incompatible with target %s" %
+ target_arch)
- if os.path.exists("%s/EFI/BOOT" % isodir):
- shutil.rmtree("%s/EFI/BOOT" % isodir)
+ grub_target = os.path.join(target_dir, grub_dest_image)
+ if not os.path.isfile(grub_target):
+ grub_src = os.path.join(deploy_dir, grub_src_image)
+ if not os.path.exists(grub_src):
+ raise WicError("Grub loader %s is not found in %s. "
+ "Please build grub-efi first" % (grub_src_image, deploy_dir))
+ shutil.copy(grub_src, grub_target)
- shutil.copytree(bootimg_dir+"/EFI/BOOT", isodir+"/EFI/BOOT")
+ if not os.path.isfile(os.path.join(target_dir, "boot.cfg")):
+ cls.do_configure_grubefi(part, creator, target_dir)
- # If exists, remove cr_workdir/bootimg temporary folder
- if os.path.exists("%s/bootimg" % cr_workdir):
- shutil.rmtree("%s/bootimg" % cr_workdir)
+ else:
+ raise WicError("unrecognized bootimg-efi loader: %s" %
+ source_params['loader'])
+ except KeyError:
+ raise WicError("bootimg-efi requires a loader, none specified")
# Create efi.img that contains bootloader files for EFI booting
# if ISODIR didn't exist or didn't contains it
@@ -420,26 +350,23 @@ class IsoImagePlugin(SourcePlugin):
(img_iso_dir, isodir)
exec_cmd(install_cmd)
else:
+ # Default to 100 blocks of extra space for file system overhead
+ esp_extra_blocks = int(source_params.get('esp_extra_blocks', '100'))
+
du_cmd = "du -bks %s/EFI" % isodir
out = exec_cmd(du_cmd)
blocks = int(out.split()[0])
- # Add some extra space for file system overhead
- blocks += 100
- msg = "Added 100 extra blocks to %s to get to %d total blocks" \
- % (part.mountpoint, blocks)
- msger.debug(msg)
-
- # Ensure total sectors is an integral number of sectors per
- # track or mcopy will complain. Sectors are 512 bytes, and we
- # generate images with 32 sectors per track. This calculation is
- # done in blocks, thus the mod by 16 instead of 32.
- blocks += (16 - (blocks % 16))
+ blocks += esp_extra_blocks
+ logger.debug("Added 100 extra blocks to %s to get to %d "
+ "total blocks", part.mountpoint, blocks)
# dosfs image for EFI boot
bootimg = "%s/efi.img" % isodir
- dosfs_cmd = 'mkfs.vfat -n "EFIimg" -S 512 -C %s %d' \
- % (bootimg, blocks)
+ esp_label = source_params.get('esp_label', 'EFIimg')
+
+ dosfs_cmd = 'mkfs.vfat -n \'%s\' -S 512 -C %s %d' \
+ % (esp_label, bootimg, blocks)
exec_native_cmd(dosfs_cmd, native_sysroot)
mmd_cmd = "mmd -i %s ::/EFI" % bootimg
@@ -455,7 +382,7 @@ class IsoImagePlugin(SourcePlugin):
# Prepare files for legacy boot
syslinux_dir = get_bitbake_var("STAGING_DATADIR")
if not syslinux_dir:
- msger.error("Couldn't find STAGING_DATADIR, exiting.\n")
+ raise WicError("Couldn't find STAGING_DATADIR, exiting.")
if os.path.exists("%s/isolinux" % isodir):
shutil.rmtree("%s/isolinux" % isodir)
@@ -495,7 +422,7 @@ class IsoImagePlugin(SourcePlugin):
mkisofs_cmd += "-eltorito-platform 0xEF -eltorito-boot %s " % efi_img
mkisofs_cmd += "-no-emul-boot %s " % isodir
- msger.debug("running command: %s" % mkisofs_cmd)
+ logger.debug("running command: %s", mkisofs_cmd)
exec_native_cmd(mkisofs_cmd, native_sysroot)
shutil.rmtree(isodir)
@@ -504,8 +431,8 @@ class IsoImagePlugin(SourcePlugin):
out = exec_cmd(du_cmd)
isoimg_size = int(out.split()[0])
- part.set_size(isoimg_size)
- part.set_source_file(iso_img)
+ part.size = isoimg_size
+ part.source_file = iso_img
@classmethod
def do_install_disk(cls, disk, disk_name, creator, workdir, oe_builddir,
@@ -516,23 +443,19 @@ class IsoImagePlugin(SourcePlugin):
utility for booting via BIOS from disk storage devices.
"""
+ iso_img = "%s.p1" % disk.path
full_path = creator._full_path(workdir, disk_name, "direct")
- iso_img = "%s.p1" % full_path
full_path_iso = creator._full_path(workdir, disk_name, "iso")
isohybrid_cmd = "isohybrid -u %s" % iso_img
- msger.debug("running command: %s" % \
- isohybrid_cmd)
+ logger.debug("running command: %s", isohybrid_cmd)
exec_native_cmd(isohybrid_cmd, native_sysroot)
# Replace the image created by direct plugin with the one created by
# mkisofs command. This is necessary because the iso image created by
# mkisofs has a very specific MBR is system area of the ISO image, and
# direct plugin adds and configures an another MBR.
- msger.debug("Replaceing the image created by direct plugin\n")
- os.remove(full_path)
+ logger.debug("Replaceing the image created by direct plugin\n")
+ os.remove(disk.path)
shutil.copy2(iso_img, full_path_iso)
shutil.copy2(full_path_iso, full_path)
-
- # Remove temporary ISO file
- os.remove(iso_img)
diff --git a/scripts/lib/wic/plugins/source/rawcopy.py b/scripts/lib/wic/plugins/source/rawcopy.py
index f0691baa91..fa7b1eb8ac 100644
--- a/scripts/lib/wic/plugins/source/rawcopy.py
+++ b/scripts/lib/wic/plugins/source/rawcopy.py
@@ -1,25 +1,16 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# SPDX-License-Identifier: GPL-2.0-only
#
+import logging
import os
-from wic import msger
+from wic import WicError
from wic.pluginbase import SourcePlugin
-from wic.utils.oe.misc import exec_cmd, get_bitbake_var
+from wic.misc import exec_cmd, get_bitbake_var
+from wic.filemap import sparse_copy
+
+logger = logging.getLogger('wic')
class RawCopyPlugin(SourcePlugin):
"""
@@ -28,24 +19,24 @@ class RawCopyPlugin(SourcePlugin):
name = 'rawcopy'
- @classmethod
- def do_install_disk(cls, disk, disk_name, cr, workdir, oe_builddir,
- bootimg_dir, kernel_dir, native_sysroot):
- """
- Called after all partitions have been prepared and assembled into a
- disk image. Do nothing.
- """
- pass
+ @staticmethod
+ def do_image_label(fstype, dst, label):
+ if fstype.startswith('ext'):
+ cmd = 'tune2fs -L %s %s' % (label, dst)
+ elif fstype in ('msdos', 'vfat'):
+ cmd = 'dosfslabel %s %s' % (dst, label)
+ elif fstype == 'btrfs':
+ cmd = 'btrfs filesystem label %s %s' % (dst, label)
+ elif fstype == 'swap':
+ cmd = 'mkswap -L %s %s' % (label, dst)
+ elif fstype in ('squashfs', 'erofs'):
+ raise WicError("It's not possible to update a %s "
+ "filesystem label '%s'" % (fstype, label))
+ else:
+ raise WicError("Cannot update filesystem label: "
+ "Unknown fstype: '%s'" % (fstype))
- @classmethod
- def do_configure_partition(cls, part, source_params, cr, cr_workdir,
- oe_builddir, bootimg_dir, kernel_dir,
- native_sysroot):
- """
- Called before do_prepare_partition(). Possibly prepare
- configuration files of some sort.
- """
- pass
+ exec_cmd(cmd)
@classmethod
def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
@@ -55,33 +46,36 @@ class RawCopyPlugin(SourcePlugin):
Called to do the actual content population for a partition i.e. it
'prepares' the partition to be incorporated into the image.
"""
- if not bootimg_dir:
- bootimg_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
- if not bootimg_dir:
- msger.error("Couldn't find DEPLOY_DIR_IMAGE, exiting\n")
+ if not kernel_dir:
+ kernel_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
+ if not kernel_dir:
+ raise WicError("Couldn't find DEPLOY_DIR_IMAGE, exiting")
- msger.debug('Bootimg dir: %s' % bootimg_dir)
+ logger.debug('Kernel dir: %s', kernel_dir)
if 'file' not in source_params:
- msger.error("No file specified\n")
- return
+ raise WicError("No file specified")
- src = os.path.join(bootimg_dir, source_params['file'])
- dst = src
+ src = os.path.join(kernel_dir, source_params['file'])
+ dst = os.path.join(cr_workdir, "%s.%s" % (os.path.basename(source_params['file']), part.lineno))
+
+ if not os.path.exists(os.path.dirname(dst)):
+ os.makedirs(os.path.dirname(dst))
if 'skip' in source_params:
- dst = os.path.join(cr_workdir, source_params['file'])
- dd_cmd = "dd if=%s of=%s ibs=%s skip=1 conv=notrunc" % \
- (src, dst, source_params['skip'])
- exec_cmd(dd_cmd)
+ sparse_copy(src, dst, skip=int(source_params['skip']))
+ else:
+ sparse_copy(src, dst)
# get the size in the right units for kickstart (kB)
du_cmd = "du -Lbks %s" % dst
out = exec_cmd(du_cmd)
- filesize = out.split()[0]
+ filesize = int(out.split()[0])
- if int(filesize) > int(part.size):
+ if filesize > part.size:
part.size = filesize
- part.source_file = dst
+ if part.label:
+ RawCopyPlugin.do_image_label(part.fstype, dst, part.label)
+ part.source_file = dst
diff --git a/scripts/lib/wic/plugins/source/rootfs.py b/scripts/lib/wic/plugins/source/rootfs.py
index a90712b247..2e34e715ca 100644
--- a/scripts/lib/wic/plugins/source/rootfs.py
+++ b/scripts/lib/wic/plugins/source/rootfs.py
@@ -1,21 +1,7 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# Copyright (c) 2014, Intel Corporation.
-# All rights reserved.
#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# SPDX-License-Identifier: GPL-2.0-only
#
# DESCRIPTION
# This implements the 'rootfs' source plugin class for 'wic'
@@ -25,11 +11,19 @@
# Joao Henrique Ferreira de Freitas <joaohf (at] gmail.com>
#
+import logging
import os
+import shutil
+import sys
-from wic import msger
+from oe.path import copyhardlinktree
+from pathlib import Path
+
+from wic import WicError
from wic.pluginbase import SourcePlugin
-from wic.utils.oe.misc import get_bitbake_var
+from wic.misc import get_bitbake_var, exec_native_cmd
+
+logger = logging.getLogger('wic')
class RootfsPlugin(SourcePlugin):
"""
@@ -39,18 +33,42 @@ class RootfsPlugin(SourcePlugin):
name = 'rootfs'
@staticmethod
+ def __validate_path(cmd, rootfs_dir, path):
+ if os.path.isabs(path):
+ logger.error("%s: Must be relative: %s" % (cmd, orig_path))
+ sys.exit(1)
+
+ # Disallow climbing outside of parent directory using '..',
+ # because doing so could be quite disastrous (we will delete the
+ # directory, or modify a directory outside OpenEmbedded).
+ full_path = os.path.realpath(os.path.join(rootfs_dir, path))
+ if not full_path.startswith(os.path.realpath(rootfs_dir)):
+ logger.error("%s: Must point inside the rootfs:" % (cmd, path))
+ sys.exit(1)
+
+ return full_path
+
+ @staticmethod
def __get_rootfs_dir(rootfs_dir):
if os.path.isdir(rootfs_dir):
- return rootfs_dir
+ return os.path.realpath(rootfs_dir)
image_rootfs_dir = get_bitbake_var("IMAGE_ROOTFS", rootfs_dir)
if not os.path.isdir(image_rootfs_dir):
- msg = "No valid artifact IMAGE_ROOTFS from image named"
- msg += " %s has been found at %s, exiting.\n" % \
- (rootfs_dir, image_rootfs_dir)
- msger.error(msg)
+ raise WicError("No valid artifact IMAGE_ROOTFS from image "
+ "named %s has been found at %s, exiting." %
+ (rootfs_dir, image_rootfs_dir))
+
+ return os.path.realpath(image_rootfs_dir)
- return image_rootfs_dir
+ @staticmethod
+ def __get_pseudo(native_sysroot, rootfs, pseudo_dir):
+ pseudo = "export PSEUDO_PREFIX=%s/usr;" % native_sysroot
+ pseudo += "export PSEUDO_LOCALSTATEDIR=%s;" % pseudo_dir
+ pseudo += "export PSEUDO_PASSWD=%s;" % rootfs
+ pseudo += "export PSEUDO_NOSYMLINKEXP=1;"
+ pseudo += "%s " % get_bitbake_var("FAKEROOTCMD")
+ return pseudo
@classmethod
def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
@@ -61,23 +79,155 @@ class RootfsPlugin(SourcePlugin):
'prepares' the partition to be incorporated into the image.
In this case, prepare content for legacy bios boot partition.
"""
- if part.rootfs is None:
+ if part.rootfs_dir is None:
if not 'ROOTFS_DIR' in krootfs_dir:
- msg = "Couldn't find --rootfs-dir, exiting"
- msger.error(msg)
+ raise WicError("Couldn't find --rootfs-dir, exiting")
+
rootfs_dir = krootfs_dir['ROOTFS_DIR']
else:
- if part.rootfs in krootfs_dir:
- rootfs_dir = krootfs_dir[part.rootfs]
- elif part.rootfs:
- rootfs_dir = part.rootfs
+ if part.rootfs_dir in krootfs_dir:
+ rootfs_dir = krootfs_dir[part.rootfs_dir]
+ elif part.rootfs_dir:
+ rootfs_dir = part.rootfs_dir
else:
- msg = "Couldn't find --rootfs-dir=%s connection"
- msg += " or it is not a valid path, exiting"
- msger.error(msg % part.rootfs)
+ raise WicError("Couldn't find --rootfs-dir=%s connection or "
+ "it is not a valid path, exiting" % part.rootfs_dir)
+
+ part.rootfs_dir = cls.__get_rootfs_dir(rootfs_dir)
+ part.has_fstab = os.path.exists(os.path.join(part.rootfs_dir, "etc/fstab"))
+ pseudo_dir = os.path.join(part.rootfs_dir, "../pseudo")
+ if not os.path.lexists(pseudo_dir):
+ logger.warn("%s folder does not exist. "
+ "Usernames and permissions will be invalid " % pseudo_dir)
+ pseudo_dir = None
+
+ new_rootfs = None
+ new_pseudo = None
+ # Handle excluded paths.
+ if part.exclude_path or part.include_path or part.change_directory or part.update_fstab_in_rootfs:
+ # We need a new rootfs directory we can safely modify without
+ # interfering with other tasks. Copy to workdir.
+ new_rootfs = os.path.realpath(os.path.join(cr_workdir, "rootfs%d" % part.lineno))
+
+ if os.path.lexists(new_rootfs):
+ shutil.rmtree(os.path.join(new_rootfs))
+
+ if part.change_directory:
+ cd = part.change_directory
+ if cd[-1] == '/':
+ cd = cd[:-1]
+ orig_dir = cls.__validate_path("--change-directory", part.rootfs_dir, cd)
+ else:
+ orig_dir = part.rootfs_dir
+ copyhardlinktree(orig_dir, new_rootfs)
+
+ # Convert the pseudo directory to its new location
+ if (pseudo_dir):
+ new_pseudo = os.path.realpath(
+ os.path.join(cr_workdir, "pseudo%d" % part.lineno))
+ if os.path.lexists(new_pseudo):
+ shutil.rmtree(new_pseudo)
+ os.mkdir(new_pseudo)
+ shutil.copy(os.path.join(pseudo_dir, "files.db"),
+ os.path.join(new_pseudo, "files.db"))
+
+ pseudo_cmd = "%s -B -m %s -M %s" % (cls.__get_pseudo(native_sysroot,
+ new_rootfs,
+ new_pseudo),
+ orig_dir, new_rootfs)
+ exec_native_cmd(pseudo_cmd, native_sysroot)
+
+ for in_path in part.include_path or []:
+ #parse arguments
+ include_path = in_path[0]
+ if len(in_path) > 2:
+ logger.error("'Invalid number of arguments for include-path")
+ sys.exit(1)
+ if len(in_path) == 2:
+ path = in_path[1]
+ else:
+ path = None
+
+ # Pack files to be included into a tar file.
+ # We need to create a tar file, because that way we can keep the
+ # permissions from the files even when they belong to different
+ # pseudo enviroments.
+ # If we simply copy files using copyhardlinktree/copytree... the
+ # copied files will belong to the user running wic.
+ tar_file = os.path.realpath(
+ os.path.join(cr_workdir, "include-path%d.tar" % part.lineno))
+ if os.path.isfile(include_path):
+ parent = os.path.dirname(os.path.realpath(include_path))
+ tar_cmd = "tar c --owner=root --group=root -f %s -C %s %s" % (
+ tar_file, parent, os.path.relpath(include_path, parent))
+ exec_native_cmd(tar_cmd, native_sysroot)
+ else:
+ if include_path in krootfs_dir:
+ include_path = krootfs_dir[include_path]
+ include_path = cls.__get_rootfs_dir(include_path)
+ include_pseudo = os.path.join(include_path, "../pseudo")
+ if os.path.lexists(include_pseudo):
+ pseudo = cls.__get_pseudo(native_sysroot, include_path,
+ include_pseudo)
+ tar_cmd = "tar cf %s -C %s ." % (tar_file, include_path)
+ else:
+ pseudo = None
+ tar_cmd = "tar c --owner=root --group=root -f %s -C %s ." % (
+ tar_file, include_path)
+ exec_native_cmd(tar_cmd, native_sysroot, pseudo)
+
+ #create destination
+ if path:
+ destination = cls.__validate_path("--include-path", new_rootfs, path)
+ Path(destination).mkdir(parents=True, exist_ok=True)
+ else:
+ destination = new_rootfs
+
+ #extract destination
+ untar_cmd = "tar xf %s -C %s" % (tar_file, destination)
+ if new_pseudo:
+ pseudo = cls.__get_pseudo(native_sysroot, new_rootfs, new_pseudo)
+ else:
+ pseudo = None
+ exec_native_cmd(untar_cmd, native_sysroot, pseudo)
+ os.remove(tar_file)
+
+ for orig_path in part.exclude_path or []:
+ path = orig_path
+
+ full_path = cls.__validate_path("--exclude-path", new_rootfs, path)
+
+ if not os.path.lexists(full_path):
+ continue
- real_rootfs_dir = cls.__get_rootfs_dir(rootfs_dir)
+ if new_pseudo:
+ pseudo = cls.__get_pseudo(native_sysroot, new_rootfs, new_pseudo)
+ else:
+ pseudo = None
+ if path.endswith(os.sep):
+ # Delete content only.
+ for entry in os.listdir(full_path):
+ full_entry = os.path.join(full_path, entry)
+ rm_cmd = "rm -rf %s" % (full_entry)
+ exec_native_cmd(rm_cmd, native_sysroot, pseudo)
+ else:
+ # Delete whole directory.
+ rm_cmd = "rm -rf %s" % (full_path)
+ exec_native_cmd(rm_cmd, native_sysroot, pseudo)
- part.set_rootfs(real_rootfs_dir)
- part.prepare_rootfs(cr_workdir, oe_builddir, real_rootfs_dir, native_sysroot)
+ # Update part.has_fstab here as fstab may have been added or
+ # removed by the above modifications.
+ part.has_fstab = os.path.exists(os.path.join(new_rootfs, "etc/fstab"))
+ if part.update_fstab_in_rootfs and part.has_fstab and not part.no_fstab_update:
+ fstab_path = os.path.join(new_rootfs, "etc/fstab")
+ # Assume that fstab should always be owned by root with fixed permissions
+ install_cmd = "install -m 0644 %s %s" % (part.updated_fstab_path, fstab_path)
+ if new_pseudo:
+ pseudo = cls.__get_pseudo(native_sysroot, new_rootfs, new_pseudo)
+ else:
+ pseudo = None
+ exec_native_cmd(install_cmd, native_sysroot, pseudo)
+ part.prepare_rootfs(cr_workdir, oe_builddir,
+ new_rootfs or part.rootfs_dir, native_sysroot,
+ pseudo_dir = new_pseudo or pseudo_dir)
diff --git a/scripts/lib/wic/plugins/source/rootfs_pcbios_ext.py b/scripts/lib/wic/plugins/source/rootfs_pcbios_ext.py
deleted file mode 100644
index 76e7b033fb..0000000000
--- a/scripts/lib/wic/plugins/source/rootfs_pcbios_ext.py
+++ /dev/null
@@ -1,181 +0,0 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
-#
-# This program is free software; you can distribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 mo details.
-#
-# You should have received a copy of the GNU General Public License along
-# with this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# AUTHOR
-# Adrian Freihofer <adrian.freihofer (at] neratec.com>
-#
-
-import os
-from wic import kickstart
-from wic import msger
-from wic.utils import syslinux
-from wic.utils import runner
-from wic.utils.oe import misc
-from wic.utils.errors import ImageError
-from wic.pluginbase import SourcePlugin
-
-
-# pylint: disable=no-init
-class RootfsPlugin(SourcePlugin):
- """
- Create root partition and install syslinux bootloader
-
- This plugin creates a disk image containing a bootable root partition with
- syslinux installed. The filesystem is ext2/3/4, no extra boot partition is
- required.
-
- Example kickstart file:
- part / --source rootfs-pcbios-ext --ondisk sda --fstype=ext4 --label rootfs --align 1024
- bootloader --source rootfs-pcbios-ext --timeout=0 --append="rootwait rootfstype=ext4"
-
- The first line generates a root file system including a syslinux.cfg file
- The "--source rootfs-pcbios-ext" in the second line triggers the installation
- of ldlinux.sys into the image.
- """
-
- name = 'rootfs-pcbios-ext'
-
- @staticmethod
- def _get_rootfs_dir(rootfs_dir):
- """
- Find rootfs pseudo dir
-
- If rootfs_dir is a directory consider it as rootfs directory.
- Otherwise ask bitbake about the IMAGE_ROOTFS directory.
- """
- if os.path.isdir(rootfs_dir):
- return rootfs_dir
-
- image_rootfs_dir = misc.get_bitbake_var("IMAGE_ROOTFS", rootfs_dir)
- if not os.path.isdir(image_rootfs_dir):
- msg = "No valid artifact IMAGE_ROOTFS from image named"
- msg += " %s has been found at %s, exiting.\n" % \
- (rootfs_dir, image_rootfs_dir)
- msger.error(msg)
-
- return image_rootfs_dir
-
- # pylint: disable=unused-argument
- @classmethod
- def do_configure_partition(cls, part, source_params, image_creator,
- image_creator_workdir, oe_builddir, bootimg_dir,
- kernel_dir, native_sysroot):
- """
- Creates syslinux config in rootfs directory
-
- Called before do_prepare_partition()
- """
- options = image_creator.ks.handler.bootloader.appendLine
-
- syslinux_conf = ""
- syslinux_conf += "PROMPT 0\n"
-
- timeout = kickstart.get_timeout(image_creator.ks)
- if not timeout:
- timeout = 0
- syslinux_conf += "TIMEOUT " + str(timeout) + "\n"
- syslinux_conf += "ALLOWOPTIONS 1\n"
-
- # Derive SERIAL... line from from kernel boot parameters
- syslinux_conf += syslinux.serial_console_form_kargs(options) + "\n"
-
- syslinux_conf += "DEFAULT linux\n"
- syslinux_conf += "LABEL linux\n"
- syslinux_conf += " KERNEL /boot/bzImage\n"
-
- syslinux_conf += " APPEND label=boot root=%s %s\n" % \
- (image_creator.rootdev, options)
-
- syslinux_cfg = os.path.join(image_creator.rootfs_dir['ROOTFS_DIR'], "boot", "syslinux.cfg")
- msger.debug("Writing syslinux config %s" % syslinux_cfg)
- with open(syslinux_cfg, "w") as cfg:
- cfg.write(syslinux_conf)
-
- @classmethod
- def do_prepare_partition(cls, part, source_params, image_creator,
- image_creator_workdir, oe_builddir, bootimg_dir,
- kernel_dir, krootfs_dir, native_sysroot):
- """
- Creates partition out of rootfs directory
-
- Prepare content for a rootfs partition i.e. create a partition
- and fill it from a /rootfs dir.
- Install syslinux bootloader into root partition image file
- """
- def is_exe(exepath):
- """Verify exepath is an executable file"""
- return os.path.isfile(exepath) and os.access(exepath, os.X_OK)
-
- # Make sure syslinux-nomtools is available in native sysroot or fail
- native_syslinux_nomtools = os.path.join(native_sysroot, "usr/bin/syslinux-nomtools")
- if not is_exe(native_syslinux_nomtools):
- msger.info("building syslinux-native...")
- misc.exec_cmd("bitbake syslinux-native")
- if not is_exe(native_syslinux_nomtools):
- msger.error("Couldn't find syslinux-nomtools (%s), exiting\n" %
- native_syslinux_nomtools)
-
- if part.rootfs is None:
- if 'ROOTFS_DIR' not in krootfs_dir:
- msger.error("Couldn't find --rootfs-dir, exiting")
- rootfs_dir = krootfs_dir['ROOTFS_DIR']
- else:
- if part.rootfs in krootfs_dir:
- rootfs_dir = krootfs_dir[part.rootfs]
- elif part.rootfs:
- rootfs_dir = part.rootfs
- else:
- msg = "Couldn't find --rootfs-dir=%s connection"
- msg += " or it is not a valid path, exiting"
- msger.error(msg % part.rootfs)
-
- real_rootfs_dir = cls._get_rootfs_dir(rootfs_dir)
-
- part.set_rootfs(real_rootfs_dir)
- part.prepare_rootfs(image_creator_workdir, oe_builddir, real_rootfs_dir, native_sysroot)
-
- # install syslinux into rootfs partition
- syslinux_cmd = "syslinux-nomtools -d /boot -i %s" % part.source_file
- misc.exec_native_cmd(syslinux_cmd, native_sysroot)
-
- @classmethod
- def do_install_disk(cls, disk, disk_name, image_creator, workdir, oe_builddir,
- bootimg_dir, kernel_dir, native_sysroot):
- """
- Assemble partitions to disk image
-
- Called after all partitions have been prepared and assembled into a
- disk image. In this case, we install the MBR.
- """
- mbrfile = os.path.join(native_sysroot, "usr/share/syslinux/")
- if image_creator.ptable_format == 'msdos':
- mbrfile += "mbr.bin"
- elif image_creator.ptable_format == 'gpt':
- mbrfile += "gptmbr.bin"
- else:
- msger.error("Unsupported partition table: %s" % \
- image_creator.ptable_format)
-
- if not os.path.exists(mbrfile):
- msger.error("Couldn't find %s. Has syslinux-native been baked?" % mbrfile)
-
- full_path = disk['disk'].device
- msger.debug("Installing MBR on disk %s as %s with size %s bytes" \
- % (disk_name, full_path, disk['min_size']))
-
- ret_code = runner.show(['dd', 'if=%s' % mbrfile, 'of=%s' % full_path, 'conv=notrunc'])
- if ret_code != 0:
- raise ImageError("Unable to set MBR to %s" % full_path)
diff --git a/scripts/lib/wic/test b/scripts/lib/wic/test
deleted file mode 100644
index 9daeafb986..0000000000
--- a/scripts/lib/wic/test
+++ /dev/null
@@ -1 +0,0 @@
-test
diff --git a/scripts/lib/wic/utils/__init__.py b/scripts/lib/wic/utils/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
--- a/scripts/lib/wic/utils/__init__.py
+++ /dev/null
diff --git a/scripts/lib/wic/utils/errors.py b/scripts/lib/wic/utils/errors.py
deleted file mode 100644
index d1b514dd9d..0000000000
--- a/scripts/lib/wic/utils/errors.py
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/usr/bin/env python -tt
-#
-# Copyright (c) 2007 Red Hat, Inc.
-# Copyright (c) 2011 Intel, Inc.
-#
-# This program 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; version 2 of the License
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-class WicError(Exception):
- pass
-
-class CreatorError(WicError):
- pass
-
-class Usage(WicError):
- pass
-
-class ImageError(WicError):
- pass
diff --git a/scripts/lib/wic/utils/fs_related.py b/scripts/lib/wic/utils/fs_related.py
deleted file mode 100644
index 2e74461a40..0000000000
--- a/scripts/lib/wic/utils/fs_related.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/env python -tt
-#
-# Copyright (c) 2007, Red Hat, Inc.
-# Copyright (c) 2009, 2010, 2011 Intel, Inc.
-#
-# This program 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; version 2 of the License
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-from __future__ import with_statement
-import os
-import errno
-
-from wic.utils.oe.misc import exec_cmd
-
-def makedirs(dirname):
- """A version of os.makedirs() that doesn't throw an
- exception if the leaf directory already exists.
- """
- try:
- os.makedirs(dirname)
- except OSError, err:
- if err.errno != errno.EEXIST:
- raise
-
-class Disk:
- """
- Generic base object for a disk.
- """
- def __init__(self, size, device=None):
- self._device = device
- self._size = size
-
- def create(self):
- pass
-
- def cleanup(self):
- pass
-
- def get_device(self):
- return self._device
- def set_device(self, path):
- self._device = path
- device = property(get_device, set_device)
-
- def get_size(self):
- return self._size
- size = property(get_size)
-
-
-class DiskImage(Disk):
- """
- A Disk backed by a file.
- """
- def __init__(self, image_file, size):
- Disk.__init__(self, size)
- self.image_file = image_file
-
- def exists(self):
- return os.path.exists(self.image_file)
-
- def create(self):
- if self.device is not None:
- return
-
- blocks = self.size / 1024
- if self.size - blocks * 1024:
- blocks += 1
-
- # create disk image
- dd_cmd = "dd if=/dev/zero of=%s bs=1024 seek=%d count=1" % \
- (self.image_file, blocks)
- exec_cmd(dd_cmd)
-
- self.device = self.image_file
diff --git a/scripts/lib/wic/utils/misc.py b/scripts/lib/wic/utils/misc.py
deleted file mode 100644
index 9d750694df..0000000000
--- a/scripts/lib/wic/utils/misc.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/env python -tt
-#
-# Copyright (c) 2010, 2011 Intel Inc.
-#
-# This program 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; version 2 of the License
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-import os
-import time
-
-def build_name(kscfg, release=None, prefix=None, suffix=None):
- """Construct and return an image name string.
-
- This is a utility function to help create sensible name and fslabel
- strings. The name is constructed using the sans-prefix-and-extension
- kickstart filename and the supplied prefix and suffix.
-
- kscfg -- a path to a kickstart file
- release -- a replacement to suffix for image release
- prefix -- a prefix to prepend to the name; defaults to None, which causes
- no prefix to be used
- suffix -- a suffix to append to the name; defaults to None, which causes
- a YYYYMMDDHHMM suffix to be used
-
- Note, if maxlen is less then the len(suffix), you get to keep both pieces.
-
- """
- name = os.path.basename(kscfg)
- idx = name.rfind('.')
- if idx >= 0:
- name = name[:idx]
-
- if release is not None:
- suffix = ""
- if prefix is None:
- prefix = ""
- if suffix is None:
- suffix = time.strftime("%Y%m%d%H%M")
-
- if name.startswith(prefix):
- name = name[len(prefix):]
-
- prefix = "%s-" % prefix if prefix else ""
- suffix = "-%s" % suffix if suffix else ""
-
- ret = prefix + name + suffix
-
- return ret
diff --git a/scripts/lib/wic/utils/oe/__init__.py b/scripts/lib/wic/utils/oe/__init__.py
deleted file mode 100644
index 0a81575a74..0000000000
--- a/scripts/lib/wic/utils/oe/__init__.py
+++ /dev/null
@@ -1,22 +0,0 @@
-#
-# OpenEmbedded wic utils library
-#
-# Copyright (c) 2013, Intel Corporation.
-# All rights reserved.
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# AUTHORS
-# Tom Zanussi <tom.zanussi (at] linux.intel.com>
-#
diff --git a/scripts/lib/wic/utils/oe/misc.py b/scripts/lib/wic/utils/oe/misc.py
deleted file mode 100644
index 7370d93136..0000000000
--- a/scripts/lib/wic/utils/oe/misc.py
+++ /dev/null
@@ -1,234 +0,0 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
-#
-# Copyright (c) 2013, Intel Corporation.
-# All rights reserved.
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# DESCRIPTION
-# This module provides a place to collect various wic-related utils
-# for the OpenEmbedded Image Tools.
-#
-# AUTHORS
-# Tom Zanussi <tom.zanussi (at] linux.intel.com>
-#
-"""Miscellaneous functions."""
-
-import os
-from collections import defaultdict
-
-from wic import msger
-from wic.utils import runner
-
-# executable -> recipe pairs for exec_native_cmd
-NATIVE_RECIPES = {"mcopy": "mtools",
- "mkdosfs": "dosfstools",
- "mkfs.btrfs": "btrfs-tools",
- "mkfs.ext2": "e2fsprogs",
- "mkfs.ext3": "e2fsprogs",
- "mkfs.ext4": "e2fsprogs",
- "mkfs.vfat": "dosfstools",
- "mksquashfs": "squashfs-tools",
- "mkswap": "util-linux",
- "parted": "parted",
- "sgdisk": "gptfdisk",
- "syslinux": "syslinux"
- }
-
-def _exec_cmd(cmd_and_args, as_shell=False, catch=3):
- """
- Execute command, catching stderr, stdout
-
- Need to execute as_shell if the command uses wildcards
- """
- msger.debug("_exec_cmd: %s" % cmd_and_args)
- args = cmd_and_args.split()
- msger.debug(args)
-
- if as_shell:
- ret, out = runner.runtool(cmd_and_args, catch)
- else:
- ret, out = runner.runtool(args, catch)
- out = out.strip()
- msger.debug("_exec_cmd: output for %s (rc = %d): %s" % \
- (cmd_and_args, ret, out))
-
- return (ret, out)
-
-
-def exec_cmd(cmd_and_args, as_shell=False, catch=3):
- """
- Execute command, catching stderr, stdout
-
- Exits if rc non-zero
- """
- ret, out = _exec_cmd(cmd_and_args, as_shell, catch)
-
- if ret != 0:
- msger.error("exec_cmd: %s returned '%s' instead of 0" % \
- (cmd_and_args, ret))
-
- return out
-
-
-def exec_native_cmd(cmd_and_args, native_sysroot, catch=3):
- """
- Execute native command, catching stderr, stdout
-
- Need to execute as_shell if the command uses wildcards
-
- Always need to execute native commands as_shell
- """
- native_paths = \
- "export PATH=%s/sbin:%s/usr/sbin:%s/usr/bin" % \
- (native_sysroot, native_sysroot, native_sysroot)
- native_cmd_and_args = "%s;%s" % (native_paths, cmd_and_args)
- msger.debug("exec_native_cmd: %s" % cmd_and_args)
-
- args = cmd_and_args.split()
- msger.debug(args)
-
- ret, out = _exec_cmd(native_cmd_and_args, True, catch)
-
- if ret == 127: # shell command-not-found
- prog = args[0]
- msg = "A native program %s required to build the image "\
- "was not found (see details above).\n\n" % prog
- recipe = NATIVE_RECIPES.get(prog)
- if recipe:
- msg += "Please bake it with 'bitbake %s-native' "\
- "and try again.\n" % recipe
- else:
- msg += "Wic failed to find a recipe to build native %s. Please "\
- "file a bug against wic.\n" % prog
- msger.error(msg)
- if out:
- msger.debug('"%s" output: %s' % (args[0], out))
-
- if ret != 0:
- msger.error("exec_cmd: '%s' returned '%s' instead of 0" % \
- (cmd_and_args, ret))
-
- return ret, out
-
-BOOTDD_EXTRA_SPACE = 16384
-
-class BitbakeVars(defaultdict):
- """
- Container for Bitbake variables.
- """
- def __init__(self):
- defaultdict.__init__(self, dict)
-
- # default_image and vars_dir attributes should be set from outside
- self.default_image = None
- self.vars_dir = None
-
- def _parse_line(self, line, image):
- """
- Parse one line from bitbake -e output or from .env file.
- Put result key-value pair into the storage.
- """
- if "=" not in line:
- return
- try:
- key, val = line.split("=")
- except ValueError:
- return
- key = key.strip()
- val = val.strip()
- if key.replace('_', '').isalnum():
- self[image][key] = val.strip('"')
-
- def get_var(self, var, image=None):
- """
- Get bitbake variable from 'bitbake -e' output or from .env file.
- This is a lazy method, i.e. it runs bitbake or parses file only when
- only when variable is requested. It also caches results.
- """
- if not image:
- image = self.default_image
-
- if image not in self:
- if image and self.vars_dir:
- fname = os.path.join(self.vars_dir, image + '.env')
- if os.path.isfile(fname):
- # parse .env file
- with open(fname) as varsfile:
- for line in varsfile:
- self._parse_line(line, image)
- else:
- print "Couldn't get bitbake variable from %s." % fname
- print "File %s doesn't exist." % fname
- return
- else:
- # Get bitbake -e output
- cmd = "bitbake -e"
- if image:
- cmd += " %s" % image
-
- log_level = msger.get_loglevel()
- msger.set_loglevel('normal')
- ret, lines = _exec_cmd(cmd)
- msger.set_loglevel(log_level)
-
- if ret:
- print "Couldn't get '%s' output." % cmd
- print "Bitbake failed with error:\n%s\n" % lines
- return
-
- # Parse bitbake -e output
- for line in lines.split('\n'):
- self._parse_line(line, image)
-
- # Make first image a default set of variables
- images = [key for key in self if key]
- if len(images) == 1:
- self[None] = self[image]
-
- return self[image].get(var)
-
-# Create BB_VARS singleton
-BB_VARS = BitbakeVars()
-
-def get_bitbake_var(var, image=None):
- """
- Provide old get_bitbake_var API by wrapping
- get_var method of BB_VARS singleton.
- """
- return BB_VARS.get_var(var, image)
-
-def parse_sourceparams(sourceparams):
- """
- Split sourceparams string of the form key1=val1[,key2=val2,...]
- into a dict. Also accepts valueless keys i.e. without =.
-
- Returns dict of param key/val pairs (note that val may be None).
- """
- params_dict = {}
-
- params = sourceparams.split(',')
- if params:
- for par in params:
- if not par:
- continue
- if not '=' in par:
- key = par
- val = None
- else:
- key, val = par.split('=')
- params_dict[key] = val
-
- return params_dict
diff --git a/scripts/lib/wic/utils/partitionedfs.py b/scripts/lib/wic/utils/partitionedfs.py
deleted file mode 100644
index 5a103bbc7e..0000000000
--- a/scripts/lib/wic/utils/partitionedfs.py
+++ /dev/null
@@ -1,362 +0,0 @@
-#!/usr/bin/env python -tt
-#
-# Copyright (c) 2009, 2010, 2011 Intel, Inc.
-# Copyright (c) 2007, 2008 Red Hat, Inc.
-# Copyright (c) 2008 Daniel P. Berrange
-# Copyright (c) 2008 David P. Huff
-#
-# This program 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; version 2 of the License
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-import os
-from wic import msger
-from wic.utils.errors import ImageError
-from wic.utils.oe.misc import exec_cmd, exec_native_cmd
-
-# Overhead of the MBR partitioning scheme (just one sector)
-MBR_OVERHEAD = 1
-
-# Overhead of the GPT partitioning scheme
-GPT_OVERHEAD = 34
-
-# Size of a sector in bytes
-SECTOR_SIZE = 512
-
-class Image(object):
- """
- Generic base object for an image.
-
- An Image is a container for a set of DiskImages and associated
- partitions.
- """
- def __init__(self, native_sysroot=None):
- self.disks = {}
- self.partitions = []
- # Size of a sector used in calculations
- self.sector_size = SECTOR_SIZE
- self._partitions_layed_out = False
- self.native_sysroot = native_sysroot
-
- def __add_disk(self, disk_name):
- """ Add a disk 'disk_name' to the internal list of disks. Note,
- 'disk_name' is the name of the disk in the target system
- (e.g., sdb). """
-
- if disk_name in self.disks:
- # We already have this disk
- return
-
- assert not self._partitions_layed_out
-
- self.disks[disk_name] = \
- {'disk': None, # Disk object
- 'numpart': 0, # Number of allocate partitions
- 'realpart': 0, # Number of partitions in the partition table
- 'partitions': [], # Indexes to self.partitions
- 'offset': 0, # Offset of next partition (in sectors)
- # Minimum required disk size to fit all partitions (in bytes)
- 'min_size': 0,
- 'ptable_format': "msdos"} # Partition table format
-
- def add_disk(self, disk_name, disk_obj):
- """ Add a disk object which have to be partitioned. More than one disk
- can be added. In case of multiple disks, disk partitions have to be
- added for each disk separately with 'add_partition()". """
-
- self.__add_disk(disk_name)
- self.disks[disk_name]['disk'] = disk_obj
-
- def __add_partition(self, part):
- """ This is a helper function for 'add_partition()' which adds a
- partition to the internal list of partitions. """
-
- assert not self._partitions_layed_out
-
- self.partitions.append(part)
- self.__add_disk(part['disk_name'])
-
- def add_partition(self, size, disk_name, mountpoint, source_file=None, fstype=None,
- label=None, fsopts=None, boot=False, align=None, no_table=False,
- part_type=None, uuid=None):
- """ Add the next partition. Prtitions have to be added in the
- first-to-last order. """
-
- ks_pnum = len(self.partitions)
-
- # Converting kB to sectors for parted
- size = size * 1024 / self.sector_size
-
- # We still need partition for "/" or non-subvolume
- if mountpoint == "/" or not fsopts:
- part = {'ks_pnum': ks_pnum, # Partition number in the KS file
- 'size': size, # In sectors
- 'mountpoint': mountpoint, # Mount relative to chroot
- 'source_file': source_file, # partition contents
- 'fstype': fstype, # Filesystem type
- 'fsopts': fsopts, # Filesystem mount options
- 'label': label, # Partition label
- 'disk_name': disk_name, # physical disk name holding partition
- 'device': None, # kpartx device node for partition
- 'num': None, # Partition number
- 'boot': boot, # Bootable flag
- 'align': align, # Partition alignment
- 'no_table' : no_table, # Partition does not appear in partition table
- 'part_type' : part_type, # Partition type
- 'uuid': uuid} # Partition UUID
-
- self.__add_partition(part)
-
- def layout_partitions(self, ptable_format="msdos"):
- """ Layout the partitions, meaning calculate the position of every
- partition on the disk. The 'ptable_format' parameter defines the
- partition table format and may be "msdos". """
-
- msger.debug("Assigning %s partitions to disks" % ptable_format)
-
- if self._partitions_layed_out:
- return
-
- self._partitions_layed_out = True
-
- # Go through partitions in the order they are added in .ks file
- for num in range(len(self.partitions)):
- part = self.partitions[num]
-
- if not self.disks.has_key(part['disk_name']):
- raise ImageError("No disk %s for partition %s" \
- % (part['disk_name'], part['mountpoint']))
-
- if ptable_format == 'msdos' and part['part_type']:
- # The --part-type can also be implemented for MBR partitions,
- # in which case it would map to the 1-byte "partition type"
- # filed at offset 3 of the partition entry.
- raise ImageError("setting custom partition type is not " \
- "implemented for msdos partitions")
-
- # Get the disk where the partition is located
- disk = self.disks[part['disk_name']]
- disk['numpart'] += 1
- if not part['no_table']:
- disk['realpart'] += 1
- disk['ptable_format'] = ptable_format
-
- if disk['numpart'] == 1:
- if ptable_format == "msdos":
- overhead = MBR_OVERHEAD
- elif ptable_format == "gpt":
- overhead = GPT_OVERHEAD
-
- # Skip one sector required for the partitioning scheme overhead
- disk['offset'] += overhead
-
- if disk['realpart'] > 3:
- # Reserve a sector for EBR for every logical partition
- # before alignment is performed.
- if ptable_format == "msdos":
- disk['offset'] += 1
-
-
- if part['align']:
- # If not first partition and we do have alignment set we need
- # to align the partition.
- # FIXME: This leaves a empty spaces to the disk. To fill the
- # gaps we could enlargea the previous partition?
-
- # Calc how much the alignment is off.
- align_sectors = disk['offset'] % (part['align'] * 1024 / self.sector_size)
-
- if align_sectors:
- # If partition is not aligned as required, we need
- # to move forward to the next alignment point
- align_sectors = (part['align'] * 1024 / self.sector_size) - align_sectors
-
- msger.debug("Realignment for %s%s with %s sectors, original"
- " offset %s, target alignment is %sK." %
- (part['disk_name'], disk['numpart'], align_sectors,
- disk['offset'], part['align']))
-
- # increase the offset so we actually start the partition on right alignment
- disk['offset'] += align_sectors
-
- part['start'] = disk['offset']
- disk['offset'] += part['size']
-
- part['type'] = 'primary'
- if not part['no_table']:
- part['num'] = disk['realpart']
- else:
- part['num'] = 0
-
- if disk['ptable_format'] == "msdos":
- if disk['realpart'] > 3:
- part['type'] = 'logical'
- part['num'] = disk['realpart'] + 1
-
- disk['partitions'].append(num)
- msger.debug("Assigned %s to %s%d, sectors range %d-%d size %d "
- "sectors (%d bytes)." \
- % (part['mountpoint'], part['disk_name'], part['num'],
- part['start'], part['start'] + part['size'] - 1,
- part['size'], part['size'] * self.sector_size))
-
- # Once all the partitions have been layed out, we can calculate the
- # minumim disk sizes.
- for disk in self.disks.values():
- disk['min_size'] = disk['offset']
- if disk['ptable_format'] == "gpt":
- disk['min_size'] += GPT_OVERHEAD
-
- disk['min_size'] *= self.sector_size
-
- def __create_partition(self, device, parttype, fstype, start, size):
- """ Create a partition on an image described by the 'device' object. """
-
- # Start is included to the size so we need to substract one from the end.
- end = start + size - 1
- msger.debug("Added '%s' partition, sectors %d-%d, size %d sectors" %
- (parttype, start, end, size))
-
- cmd = "parted -s %s unit s mkpart %s" % (device, parttype)
- if fstype:
- cmd += " %s" % fstype
- cmd += " %d %d" % (start, end)
-
- return exec_native_cmd(cmd, self.native_sysroot)
-
- def __format_disks(self):
- self.layout_partitions()
-
- for dev in self.disks.keys():
- disk = self.disks[dev]
- msger.debug("Initializing partition table for %s" % \
- (disk['disk'].device))
- exec_native_cmd("parted -s %s mklabel %s" % \
- (disk['disk'].device, disk['ptable_format']),
- self.native_sysroot)
-
- msger.debug("Creating partitions")
-
- for part in self.partitions:
- if part['num'] == 0:
- continue
-
- disk = self.disks[part['disk_name']]
- if disk['ptable_format'] == "msdos" and part['num'] == 5:
- # Create an extended partition (note: extended
- # partition is described in MBR and contains all
- # logical partitions). The logical partitions save a
- # sector for an EBR just before the start of a
- # partition. The extended partition must start one
- # sector before the start of the first logical
- # partition. This way the first EBR is inside of the
- # extended partition. Since the extended partitions
- # starts a sector before the first logical partition,
- # add a sector at the back, so that there is enough
- # room for all logical partitions.
- self.__create_partition(disk['disk'].device, "extended",
- None, part['start'] - 1,
- disk['offset'] - part['start'] + 1)
-
- if part['fstype'] == "swap":
- parted_fs_type = "linux-swap"
- elif part['fstype'] == "vfat":
- parted_fs_type = "fat32"
- elif part['fstype'] == "msdos":
- parted_fs_type = "fat16"
- elif part['fstype'] == "ontrackdm6aux3":
- parted_fs_type = "ontrackdm6aux3"
- else:
- # Type for ext2/ext3/ext4/btrfs
- parted_fs_type = "ext2"
-
- # Boot ROM of OMAP boards require vfat boot partition to have an
- # even number of sectors.
- if part['mountpoint'] == "/boot" and part['fstype'] in ["vfat", "msdos"] \
- and part['size'] % 2:
- msger.debug("Substracting one sector from '%s' partition to " \
- "get even number of sectors for the partition" % \
- part['mountpoint'])
- part['size'] -= 1
-
- self.__create_partition(disk['disk'].device, part['type'],
- parted_fs_type, part['start'], part['size'])
-
- if part['part_type']:
- msger.debug("partition %d: set type UID to %s" % \
- (part['num'], part['part_type']))
- exec_native_cmd("sgdisk --typecode=%d:%s %s" % \
- (part['num'], part['part_type'],
- disk['disk'].device), self.native_sysroot)
-
- if part['uuid']:
- msger.debug("partition %d: set UUID to %s" % \
- (part['num'], part['uuid']))
- exec_native_cmd("sgdisk --partition-guid=%d:%s %s" % \
- (part['num'], part['uuid'], disk['disk'].device),
- self.native_sysroot)
-
- if part['boot']:
- flag_name = "legacy_boot" if disk['ptable_format'] == 'gpt' else "boot"
- msger.debug("Set '%s' flag for partition '%s' on disk '%s'" % \
- (flag_name, part['num'], disk['disk'].device))
- exec_native_cmd("parted -s %s set %d %s on" % \
- (disk['disk'].device, part['num'], flag_name),
- self.native_sysroot)
-
- # Parted defaults to enabling the lba flag for fat16 partitions,
- # which causes compatibility issues with some firmware (and really
- # isn't necessary).
- if parted_fs_type == "fat16":
- if disk['ptable_format'] == 'msdos':
- msger.debug("Disable 'lba' flag for partition '%s' on disk '%s'" % \
- (part['num'], disk['disk'].device))
- exec_native_cmd("parted -s %s set %d lba off" % \
- (disk['disk'].device, part['num']),
- self.native_sysroot)
-
- def cleanup(self):
- if self.disks:
- for dev in self.disks:
- disk = self.disks[dev]
- try:
- disk['disk'].cleanup()
- except:
- pass
-
- def assemble(self, image_file):
- msger.debug("Installing partitions")
-
- for part in self.partitions:
- source = part['source_file']
- if source:
- # install source_file contents into a partition
- cmd = "dd if=%s of=%s bs=%d seek=%d count=%d conv=notrunc" % \
- (source, image_file, self.sector_size,
- part['start'], part['size'])
- exec_cmd(cmd)
-
- msger.debug("Installed %s in partition %d, sectors %d-%d, "
- "size %d sectors" % \
- (source, part['num'], part['start'],
- part['start'] + part['size'] - 1, part['size']))
-
- os.rename(source, image_file + '.p%d' % part['num'])
-
- def create(self):
- for dev in self.disks.keys():
- disk = self.disks[dev]
- disk['disk'].create()
-
- self.__format_disks()
-
- return
diff --git a/scripts/lib/wic/utils/runner.py b/scripts/lib/wic/utils/runner.py
deleted file mode 100644
index 7431917ff0..0000000000
--- a/scripts/lib/wic/utils/runner.py
+++ /dev/null
@@ -1,110 +0,0 @@
-#!/usr/bin/env python -tt
-#
-# Copyright (c) 2011 Intel, Inc.
-#
-# This program 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; version 2 of the License
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-import os
-import subprocess
-
-from wic import msger
-
-def runtool(cmdln_or_args, catch=1):
- """ wrapper for most of the subprocess calls
- input:
- cmdln_or_args: can be both args and cmdln str (shell=True)
- catch: 0, quitely run
- 1, only STDOUT
- 2, only STDERR
- 3, both STDOUT and STDERR
- return:
- (rc, output)
- if catch==0: the output will always None
- """
-
- if catch not in (0, 1, 2, 3):
- # invalid catch selection, will cause exception, that's good
- return None
-
- if isinstance(cmdln_or_args, list):
- cmd = cmdln_or_args[0]
- shell = False
- else:
- import shlex
- cmd = shlex.split(cmdln_or_args)[0]
- shell = True
-
- if catch != 3:
- dev_null = os.open("/dev/null", os.O_WRONLY)
-
- if catch == 0:
- sout = dev_null
- serr = dev_null
- elif catch == 1:
- sout = subprocess.PIPE
- serr = dev_null
- elif catch == 2:
- sout = dev_null
- serr = subprocess.PIPE
- elif catch == 3:
- sout = subprocess.PIPE
- serr = subprocess.STDOUT
-
- try:
- process = subprocess.Popen(cmdln_or_args, stdout=sout,
- stderr=serr, shell=shell)
- (sout, serr) = process.communicate()
- # combine stdout and stderr, filter None out
- out = ''.join(filter(None, [sout, serr]))
- except OSError, err:
- if err.errno == 2:
- # [Errno 2] No such file or directory
- msger.error('Cannot run command: %s, lost dependency?' % cmd)
- else:
- raise # relay
- finally:
- if catch != 3:
- os.close(dev_null)
-
- return (process.returncode, out)
-
-def show(cmdln_or_args):
- # show all the message using msger.verbose
-
- rcode, out = runtool(cmdln_or_args, catch=3)
-
- if isinstance(cmdln_or_args, list):
- cmd = ' '.join(cmdln_or_args)
- else:
- cmd = cmdln_or_args
-
- msg = 'running command: "%s"' % cmd
- if out:
- out = out.strip()
- if out:
- msg += ', with output::'
- msg += '\n +----------------'
- for line in out.splitlines():
- msg += '\n | %s' % line
- msg += '\n +----------------'
-
- msger.verbose(msg)
- return rcode
-
-def outs(cmdln_or_args, catch=1):
- # get the outputs of tools
- return runtool(cmdln_or_args, catch)[1].strip()
-
-def quiet(cmdln_or_args):
- return runtool(cmdln_or_args, catch=0)[0]
diff --git a/scripts/lib/wic/utils/syslinux.py b/scripts/lib/wic/utils/syslinux.py
deleted file mode 100644
index aace2863c1..0000000000
--- a/scripts/lib/wic/utils/syslinux.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# ex:ts=4:sw=4:sts=4:et
-# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
-#
-# This program 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; version 2 of the License
-#
-# This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# AUTHOR
-# Adrian Freihofer <adrian.freihofer (at] neratec.com>
-
-
-import re
-from wic import msger
-
-
-def serial_console_form_kargs(kernel_args):
- """
- Create SERIAL... line from kernel parameters
-
- syslinux needs a line SERIAL port [baudrate [flowcontrol]]
- in the syslinux.cfg file. The config line is generated based
- on kernel boot parameters. The the parameters of the first
- ttyS console are considered for syslinux config.
- @param kernel_args kernel command line
- @return line for syslinux config file e.g. "SERIAL 0 115200"
- """
- syslinux_conf = ""
- for param in kernel_args.split():
- param_match = re.match("console=ttyS([0-9]+),?([0-9]*)([noe]?)([0-9]?)(r?)", param)
- if param_match:
- syslinux_conf += "SERIAL " + param_match.group(1)
- # baudrate
- if param_match.group(2):
- syslinux_conf += " " + param_match.group(2)
- # parity
- if param_match.group(3) and param_match.group(3) != 'n':
- msger.warning("syslinux does not support parity for console. {} is ignored."
- .format(param_match.group(3)))
- # number of bits
- if param_match.group(4) and param_match.group(4) != '8':
- msger.warning("syslinux supports 8 bit console configuration only. {} is ignored."
- .format(param_match.group(4)))
- # flow control
- if param_match.group(5) and param_match.group(5) != '':
- msger.warning("syslinux console flowcontrol configuration. {} is ignored."
- .format(param_match.group(5)))
- break
-
- return syslinux_conf