blob: 74a6b77357d0b968459bb80c87cce299fb030bad [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001# Copyright (C) 2017 Mediatek
2# Author: Richard Sun
3# Some code and influence taken from externalsrc.bbclass:
4# Copyright (C) 2012 Linux Foundation
5# Author: Richard Purdie
6# Some code and influence taken from srctree.bbclass:
7# Copyright (C) 2009 Chris Larson <clarson@kergoth.com>
8# Released under the MIT license (see COPYING.MIT for the terms)
9#
10# workonsrc.bbclass enables use of an existing source tree, usually workon to
11# the build system to build a piece of software rather than the usual fetch/unpack/patch
12# process.
13#
14# To use, add workonsrc to the global inherit and set WORKONSRC to point at the
15# directory you want to use containing the sources e.g. from local.conf for a recipe
16# called "myrecipe" you would do:
17#
18# INHERIT += "workonsrc"
19# WORKONSRC_pn-myrecipe = "/path/to/my/source/tree"
20#
21# In order to make this class work for both target and native versions (or with
22# multilibs/cross or other BBCLASSEXTEND variants), B is set to point to a separate
23# directory under the work directory (split source and build directories). This is
24# the default, but the build directory can be set to the source directory if
25# circumstances dictate by setting WORKONSRC_BUILD to the same value, e.g.:
26#
27# WORKONSRC_BUILD_pn-myrecipe = "/path/to/my/source/tree"
28#
29
30SRCTREECOVEREDTASKS ?= "do_patch do_unpack do_fetch"
31EXTERNALSRC_SYMLINKS ?= "oe-workdir:${WORKDIR} oe-logs:${T}"
32
33python () {
34 import subprocess, os.path
35
36 depends = d.getVar("DEPENDS")
37 depends = "%s rsync-native" % depends
38 d.setVar("DEPENDS", depends)
39
40 pn = d.getVar('PN')
41 d.appendVarFlag('do_populate_lic', 'depends', ' %s:do_configure' % pn)
42 workonsrc = d.getVar('WORKONSRC')
43 workonprebuilt = workonsrc.replace("build/../src/", "build/../prebuilt/")
44 if not os.path.exists(workonsrc):
45 if os.path.exists(workonprebuilt):
46 workonsrc = workonprebuilt
47 else:
48 bb.warn("Both %s and %s aren't existed" % (workonsrc, workonprebuilt) )
49
50 # If this is the base recipe and WORKONSRC is set for it or any of its
51 # derivatives, then enable BB_DONT_CACHE to force the recipe to always be
52 # re-parsed so that the file-checksums function for do_compile is run every
53 # time.
54 bpn = d.getVar('BPN')
55 if bpn == d.getVar('PN'):
56 classextend = (d.getVar('BBCLASSEXTEND') or '').split()
57 if (workonsrc or
58 ('native' in classextend and
59 d.getVar('WORKONSRC_pn-%s-native' % bpn)) or
60 ('nativesdk' in classextend and
61 d.getVar('WORKONSRC_pn-nativesdk-%s' % bpn)) or
62 ('cross' in classextend and
63 d.getVar('WORKONSRC_pn-%s-cross' % bpn))):
64 d.setVar('BB_DONT_CACHE', '1')
65
66 if workonsrc:
67 d.setVar('S', workonsrc)
68 workonsrcbuild = d.getVar('WORKONSRC_BUILD')
69 if workonsrcbuild:
70 d.setVar('B', workonsrcbuild)
71 else:
72 d.setVar('B', '${WORKDIR}/${BPN}-${PV}/')
73 workonsrcbuild = d.getVar('B')
74
75 if workonsrc != workonsrcbuild:
76 d.setVar('S', workonsrcbuild)
77
78 local_srcuri = []
79 fetch = bb.fetch2.Fetch((d.getVar('SRC_URI') or '').split(), d)
80 for url in fetch.urls:
81 url_data = fetch.ud[url]
82 parm = url_data.parm
83 if (url_data.type == 'file' or
84 'type' in parm and parm['type'] == 'kmeta'):
85 local_srcuri.append(url)
86
87 d.setVar('SRC_URI', ' '.join(local_srcuri))
88
89 if '{SRCPV}' in d.getVar('PV', False):
90 # Dummy value because the default function can't be called with blank SRC_URI
91 d.setVar('SRCPV', '999')
92
93 tasks = filter(lambda k: d.getVarFlag(k, "task"), d.keys())
94
95 for task in tasks:
96 if task.endswith("_setscene"):
97 # sstate is never going to work for workon source trees, disable it
98 bb.build.deltask(task, d)
99 else:
100 # Since configure will likely touch ${S}, ensure only we lock so one task has access at a time
101 d.appendVarFlag(task, "lockfiles", " ${S}/singletask.lock")
102
103 # We do not want our source to be wiped out, ever (kernel.bbclass does this for do_clean)
104 cleandirs = (d.getVarFlag(task, 'cleandirs', False) or '').split()
105 setvalue = False
106 for cleandir in cleandirs[:]:
107 if d.expand(cleandir) == workonsrc:
108 cleandirs.remove(cleandir)
109 setvalue = True
110 if setvalue:
111 d.setVarFlag(task, 'cleandirs', ' '.join(cleandirs))
112
113 fetch_tasks = ['do_fetch', 'do_unpack']
114 # If we deltask do_patch, there's no dependency to ensure do_unpack gets run, so add one
115 # Note that we cannot use d.appendVarFlag() here because deps is expected to be a list object, not a string
116 d.setVarFlag('do_configure', 'deps', (d.getVarFlag('do_configure', 'deps', False) or []) + ['do_unpack'])
117
118 for task in d.getVar("SRCTREECOVEREDTASKS").split():
119 if local_srcuri and task in fetch_tasks:
120 continue
121 bb.build.deltask(task, d)
122
123 d.prependVarFlag('do_compile', 'prefuncs', "workonsrc_compile_prefunc ")
124 d.prependVarFlag('do_configure', 'prefuncs', "workonsrc_configure_prefunc ")
125
126 d.setVarFlag('do_compile', 'file-checksums', '${@srctree_hash_files(d)}')
127 d.setVarFlag('do_configure', 'file-checksums', '${@srctree_configure_hash_files(d)}')
128
129 # We don't want the workdir to go away
130 d.appendVar('RM_WORK_EXCLUDE', ' ' + d.getVar('PN'))
131
132 bb.build.addtask('do_buildclean',
133 'do_clean' if d.getVar('S') == d.getVar('B') else None,
134 None, d)
135
136
137 # If B=S the same builddir is used even for different architectures.
138 # Thus, use a shared CONFIGURESTAMPFILE and STAMP directory so that
139 # change of do_configure task hash is correctly detected and stamps are
140 # invalidated if e.g. MACHINE changes.
141 if d.getVar('S') == d.getVar('B'):
142 configstamp = '${TMPDIR}/work-shared/${PN}/${EXTENDPE}${PV}-${PR}/configure.sstate'
143 d.setVar('CONFIGURESTAMPFILE', configstamp)
144 d.setVar('STAMP', '${STAMPS_DIR}/work-shared/${PN}/${EXTENDPE}${PV}-${PR}')
145 d.setVar('STAMPCLEAN', '${STAMPS_DIR}/work-shared/${PN}/*-*')
146}
147
148python workonsrc_configure_prefunc() {
149 srctree_rsync_files(d)
150 s_dir = d.getVar('S')
151 # Create desired symlinks
152 symlinks = (d.getVar('EXTERNALSRC_SYMLINKS') or '').split()
153 newlinks = []
154 for symlink in symlinks:
155 symsplit = symlink.split(':', 1)
156 lnkfile = os.path.join(s_dir, symsplit[0])
157 target = d.expand(symsplit[1])
158 if len(symsplit) > 1:
159 if os.path.islink(lnkfile):
160 # Link already exists, leave it if it points to the right location already
161 if os.readlink(lnkfile) == target:
162 continue
163 os.unlink(lnkfile)
164 elif os.path.exists(lnkfile):
165 # File/dir exists with same name as link, just leave it alone
166 continue
167 os.symlink(target, lnkfile)
168 newlinks.append(symsplit[0])
169 # Hide the symlinks from git
170 try:
171 git_exclude_file = os.path.join(s_dir, '.git/info/exclude')
172 if os.path.exists(git_exclude_file):
173 with open(git_exclude_file, 'r+') as efile:
174 elines = efile.readlines()
175 for link in newlinks:
176 if link in elines or '/'+link in elines:
177 continue
178 efile.write('/' + link + '\n')
179 except IOError as ioe:
180 bb.note('Failed to hide EXTERNALSRC_SYMLINKS from git')
181}
182
183python workonsrc_compile_prefunc() {
184 srctree_rsync_files(d)
185 # Make it obvious that this is happening, since forgetting about it could lead to much confusion
186 bb.plain('NOTE: %s: compiling from workon source tree %s' % (d.getVar('PN'), d.getVar('WORKONSRC')))
187}
188
189do_buildclean[dirs] = "${S} ${B}"
190do_buildclean[nostamp] = "1"
191do_buildclean[doc] = "Call 'make clean' or equivalent in ${B}"
192workonsrc_do_buildclean() {
193 if [ -e Makefile -o -e makefile -o -e GNUmakefile ]; then
194 oe_runmake clean || die "make failed"
195 else
196 bbnote "nothing to do - no makefile found"
197 fi
198}
199
200def srctree_rsync_files(d):
201 import subprocess, os.path
202
203 workonsrc = d.getVar('WORKONSRC')
204 workonprebuilt = workonsrc.replace("build/../src/", "build/../prebuilt/")
205 if not os.path.exists(workonsrc):
206 if os.path.exists(workonprebuilt):
207 workonsrc = workonprebuilt
208 else:
209 bb.warn("Both %s and %s aren't existed" % (workonsrc, workonprebuilt) )
210
211 if workonsrc:
212 d.setVar('S', workonsrc)
213 workonsrcbuild = d.getVar('WORKONSRC_BUILD')
214 if workonsrcbuild:
215 d.setVar('B', workonsrcbuild)
216 else:
217 d.setVar('B', '${WORKDIR}/${BPN}-${PV}/')
218 workonsrcbuild = d.getVar('B')
219
220 if workonsrc != workonsrcbuild:
221 cmd = "mkdir -p %s" % (workonsrcbuild)
222 subprocess.call(cmd, shell=True)
223
224 if os.path.exists(workonsrc):
225 workonsrc_rsync_appended_flag = d.getVar('WORKONSRC_RSYNC_APPENDED_FLAG')
226 if workonsrc_rsync_appended_flag is None:
227 workonsrc_rsync_appended_flag=""
228 cmd = "rsync -aL %s %s/* %s" % (workonsrc_rsync_appended_flag, workonsrc, workonsrcbuild)
229 ret = subprocess.call(cmd, shell=True)
230 if ret != 0:
231 bb.fatal("rsync -aL %s %s/* %s failed." % (workonsrc_rsync_appended_flag, workonsrc, workonsrcbuild))
232 d.setVar('S', workonsrcbuild)
233
234def srctree_hash_files(d, srcdir=None):
235 import shutil
236 import subprocess
237 import tempfile
238
239 s_dir = srcdir or d.getVar('WORKONSRC')
240 git_dir = os.path.join(s_dir, '.git')
241 oe_hash_file = os.path.join(git_dir, 'oe-devtool-tree-sha1')
242
243 ret = " "
244 if os.path.exists(git_dir):
245 with tempfile.NamedTemporaryFile(dir=git_dir, prefix='oe-devtool-index') as tmp_index:
246 # Clone index
247 shutil.copy2(os.path.join(git_dir, 'index'), tmp_index.name)
248 # Update our custom index
249 env = os.environ.copy()
250 env['GIT_INDEX_FILE'] = tmp_index.name
251 subprocess.check_output(['git', 'add', '-A', '.'], cwd=s_dir, env=env)
252 sha1 = subprocess.check_output(['git', 'write-tree'], cwd=s_dir, env=env).decode("utf-8")
253 with open(oe_hash_file, 'w') as fobj:
254 fobj.write(sha1)
255 ret = oe_hash_file + ':True'
256 else:
257 ret = s_dir + '/*:True'
258 return ret
259
260def srctree_configure_hash_files(d):
261 """
262 Get the list of files that should trigger do_configure to re-execute,
263 based on the value of CONFIGURE_FILES
264 """
265 in_files = (d.getVar('CONFIGURE_FILES') or '').split()
266 out_items = []
267 search_files = []
268 for entry in in_files:
269 if entry.startswith('/'):
270 out_items.append('%s:%s' % (entry, os.path.exists(entry)))
271 else:
272 search_files.append(entry)
273 if search_files:
274 s_dir = d.getVar('WORKONSRC')
275 for root, _, files in os.walk(s_dir):
276 for f in files:
277 if f in search_files:
278 out_items.append('%s:True' % os.path.join(root, f))
279 return ' '.join(out_items)
280
281EXPORT_FUNCTIONS do_buildclean