summaryrefslogtreecommitdiffstats
path: root/scripts/lib/recipetool/create_go.py
diff options
context:
space:
mode:
Diffstat (limited to 'scripts/lib/recipetool/create_go.py')
-rw-r--r--scripts/lib/recipetool/create_go.py172
1 files changed, 0 insertions, 172 deletions
diff --git a/scripts/lib/recipetool/create_go.py b/scripts/lib/recipetool/create_go.py
deleted file mode 100644
index 1b2e5a03d5..0000000000
--- a/scripts/lib/recipetool/create_go.py
+++ /dev/null
@@ -1,172 +0,0 @@
1# Recipe creation tool - go support plugin
2#
3# The code is based on golang internals. See the afftected
4# methods for further reference and information.
5#
6# Copyright (C) 2023 Weidmueller GmbH & Co KG
7# Author: Lukas Funke <lukas.funke@weidmueller.com>
8#
9# SPDX-License-Identifier: GPL-2.0-only
10#
11
12
13from recipetool.create import RecipeHandler, handle_license_vars
14
15import bb.utils
16import json
17import logging
18import os
19import re
20import subprocess
21import sys
22import tempfile
23
24
25logger = logging.getLogger('recipetool')
26
27tinfoil = None
28
29
30def tinfoil_init(instance):
31 global tinfoil
32 tinfoil = instance
33
34
35class GoRecipeHandler(RecipeHandler):
36 """Class to handle the go recipe creation"""
37
38 @staticmethod
39 def __ensure_go():
40 """Check if the 'go' command is available in the recipes"""
41 recipe = "go-native"
42 if not tinfoil.recipes_parsed:
43 tinfoil.parse_recipes()
44 try:
45 rd = tinfoil.parse_recipe(recipe)
46 except bb.providers.NoProvider:
47 bb.error(
48 "Nothing provides '%s' which is required for the build" % (recipe))
49 bb.note(
50 "You will likely need to add a layer that provides '%s'" % (recipe))
51 return None
52
53 bindir = rd.getVar('STAGING_BINDIR_NATIVE')
54 gopath = os.path.join(bindir, 'go')
55
56 if not os.path.exists(gopath):
57 tinfoil.build_targets(recipe, 'addto_recipe_sysroot')
58
59 if not os.path.exists(gopath):
60 logger.error(
61 '%s required to process specified source, but %s did not seem to populate it' % 'go', recipe)
62 return None
63
64 return bindir
65
66 def process(self, srctree, classes, lines_before,
67 lines_after, handled, extravalues):
68
69 if 'buildsystem' in handled:
70 return False
71
72 files = RecipeHandler.checkfiles(srctree, ['go.mod'])
73 if not files:
74 return False
75
76 go_bindir = self.__ensure_go()
77 if not go_bindir:
78 sys.exit(14)
79
80 handled.append('buildsystem')
81 classes.append("go-mod")
82
83 # Use go-mod-update-modules to set the full SRC_URI and LICENSE
84 classes.append("go-mod-update-modules")
85 extravalues["run_tasks"] = "update_modules"
86
87 env = dict(os.environ)
88 env["PATH"] += f":{go_bindir}"
89
90 stdout = subprocess.check_output(("go", "mod", "edit", "-json"),
91 cwd=srctree, env=env, text=True)
92 go_mod = json.loads(stdout)
93 go_import = re.sub(r'/v([0-9]+)$', '', go_mod['Module']['Path'])
94
95 localfilesdir = tempfile.mkdtemp(prefix='recipetool-go-')
96 extravalues.setdefault('extrafiles', {})
97
98 # Write the stub ${BPN}-licenses.inc and ${BPN}-go-mods.inc files
99 basename = "{pn}-licenses.inc"
100 filename = os.path.join(localfilesdir, basename)
101 with open(filename, "w") as f:
102 f.write("# FROM RECIPETOOL\n")
103 extravalues['extrafiles'][f"../{basename}"] = filename
104
105 basename = "{pn}-go-mods.inc"
106 filename = os.path.join(localfilesdir, basename)
107 with open(filename, "w") as f:
108 f.write("# FROM RECIPETOOL\n")
109 extravalues['extrafiles'][f"../{basename}"] = filename
110
111 # Do generic license handling
112 d = bb.data.createCopy(tinfoil.config_data)
113 handle_license_vars(srctree, lines_before, handled, extravalues, d)
114 self.__rewrite_lic_vars(lines_before)
115
116 self.__rewrite_src_uri(lines_before)
117
118 lines_before.append('require ${BPN}-licenses.inc')
119 lines_before.append('require ${BPN}-go-mods.inc')
120 lines_before.append(f'GO_IMPORT = "{go_import}"')
121
122 def __update_lines_before(self, updated, newlines, lines_before):
123 if updated:
124 del lines_before[:]
125 for line in newlines:
126 # Hack to avoid newlines that edit_metadata inserts
127 if line.endswith('\n'):
128 line = line[:-1]
129 lines_before.append(line)
130 return updated
131
132 def __rewrite_lic_vars(self, lines_before):
133 def varfunc(varname, origvalue, op, newlines):
134 import urllib.parse
135 if varname == 'LIC_FILES_CHKSUM':
136 new_licenses = []
137 licenses = origvalue.split('\\')
138 for license in licenses:
139 if not license:
140 logger.warning("No license file was detected for the main module!")
141 # the license list of the main recipe must be empty
142 # this can happen for example in case of CLOSED license
143 # Fall through to complete recipe generation
144 continue
145 license = license.strip()
146 uri, chksum = license.split(';', 1)
147 url = urllib.parse.urlparse(uri)
148 new_uri = os.path.join(
149 url.scheme + "://", "src", "${GO_IMPORT}", url.netloc + url.path) + ";" + chksum
150 new_licenses.append(new_uri)
151
152 return new_licenses, None, -1, True
153 return origvalue, None, 0, True
154
155 updated, newlines = bb.utils.edit_metadata(
156 lines_before, ['LIC_FILES_CHKSUM'], varfunc)
157 return self.__update_lines_before(updated, newlines, lines_before)
158
159 def __rewrite_src_uri(self, lines_before):
160
161 def varfunc(varname, origvalue, op, newlines):
162 if varname == 'SRC_URI':
163 src_uri = ['git://${GO_IMPORT};protocol=https;nobranch=1;destsuffix=${GO_SRCURI_DESTSUFFIX}']
164 return src_uri, None, -1, True
165 return origvalue, None, 0, True
166
167 updated, newlines = bb.utils.edit_metadata(lines_before, ['SRC_URI'], varfunc)
168 return self.__update_lines_before(updated, newlines, lines_before)
169
170
171def register_recipe_handlers(handlers):
172 handlers.append((GoRecipeHandler(), 60))