CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
orangepi-xunlong

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: orangepi-xunlong/orangepi-build
Path: blob/next/scripts/extensions.sh
Views: 3960
1
# global variables managing the state of the extension manager. treat as private.
2
declare -A extension_function_info # maps a function name to a string with KEY=VALUEs information about the defining extension
3
declare -i initialize_extension_manager_counter=0 # how many times has the extension manager initialized?
4
declare -A defined_hook_point_functions # keeps a map of hook point functions that were defined and their extension info
5
declare -A hook_point_function_trace_sources # keeps a map of hook point functions that were actually called and their source
6
declare -A hook_point_function_trace_lines # keeps a map of hook point functions that were actually called and their source
7
declare fragment_manager_cleanup_file # this is a file used to cleanup the manager's produced functions, for build_all_ng
8
# configuration.
9
export DEBUG_EXTENSION_CALLS=no # set to yes to log every hook function called to the main build log
10
export LOG_ENABLE_EXTENSION=yes # colorful logs with stacktrace when enable_extension is called.
11
12
# This is a helper function for calling hooks.
13
# It follows the pattern long used in the codebase for hook-like behaviour:
14
# [[ $(type -t name_of_hook_function) == function ]] && name_of_hook_function
15
# but with the following added behaviors:
16
# 1) it allows for many arguments, and will treat each as a hook point.
17
# this allows for easily kept backwards compatibility when renaming hooks, for example.
18
# 2) it will read the stdin and assume it's (Markdown) documentation for the hook point.
19
# combined with heredoc in the call site, it allows for "inline" documentation about the hook
20
# notice: this is not involved in how the hook functions came to be. read below for that.
21
call_extension_method() {
22
# First, consume the stdin and write metadata about the call.
23
write_hook_point_metadata "$@" || true
24
25
# @TODO: hack to handle stdin again, possibly with '< /dev/tty'
26
27
# Then a sanity check, hook points should only be invoked after the manager has initialized.
28
if [[ ${initialize_extension_manager_counter} -lt 1 ]]; then
29
display_alert "Extension problem" "Call to call_extension_method() (in ${BASH_SOURCE[1]- $(get_extension_hook_stracktrace "${BASH_SOURCE[*]}" "${BASH_LINENO[*]}")}) before extension manager is initialized." "err"
30
fi
31
32
# With DEBUG_EXTENSION_CALLS, log the hook call. Users might be wondering what/when is a good hook point to use, and this is visual aid.
33
[[ "${DEBUG_EXTENSION_CALLS}" == "yes" ]] &&
34
display_alert "--> Extension Method '${1}' being called from" "$(get_extension_hook_stracktrace "${BASH_SOURCE[*]}" "${BASH_LINENO[*]}")" ""
35
36
# Then call the hooks, if they are defined.
37
for hook_name in "$@"; do
38
echo "-- Extension Method being called: ${hook_name}" >>"${EXTENSION_MANAGER_LOG_FILE}"
39
# shellcheck disable=SC2086
40
[[ $(type -t ${hook_name}) == function ]] && { ${hook_name}; }
41
done
42
}
43
44
# what this does is a lot of bash mumbo-jumbo to find all board-,family-,config- or user-defined hook points.
45
# the meat of this is 'compgen -A function', which is bash builtin that lists all defined functions.
46
# it will then compose a full hook point (function) that calls all the implementing hooks.
47
# this centralized function will then be called by the regular Armbian build system, which is oblivious to how
48
# it came to be. (although it is encouraged to call hook points via call_extension_method() above)
49
# to avoid hard coding the list of hook-points (eg: user_config, image_tweaks_pre_customize, etc) we use
50
# a marker in the function names, namely "__" (two underscores) to determine the hook point.
51
initialize_extension_manager() {
52
# before starting, auto-add extensions specified (eg, on the command-line) via the ENABLE_EXTENSIONS env var. Do it only once.
53
[[ ${initialize_extension_manager_counter} -lt 1 ]] && [[ "${ENABLE_EXTENSIONS}" != "" ]] && {
54
local auto_extension
55
for auto_extension in $(echo "${ENABLE_EXTENSIONS}" | tr "," " "); do
56
ENABLE_EXTENSION_TRACE_HINT="ENABLE_EXTENSIONS -> " enable_extension "${auto_extension}"
57
done
58
}
59
60
# This marks the manager as initialized, no more extensions are allowed to load after this.
61
export initialize_extension_manager_counter=$((initialize_extension_manager_counter + 1))
62
63
# Have a unique temporary dir, even if being built concurrently by build_all_ng.
64
export EXTENSION_MANAGER_TMP_DIR="${SRC}/.tmp/.extensions/${LOG_SUBPATH}"
65
mkdir -p "${EXTENSION_MANAGER_TMP_DIR}"
66
67
# Log destination.
68
export EXTENSION_MANAGER_LOG_FILE="${EXTENSION_MANAGER_TMP_DIR}/extensions.log"
69
echo -n "" >"${EXTENSION_MANAGER_TMP_DIR}/hook_point_calls.txt"
70
71
# globally initialize the extensions log.
72
echo "-- lib/extensions.sh included. logs will be below, followed by the debug generated by the initialize_extension_manager() function." >"${EXTENSION_MANAGER_LOG_FILE}"
73
74
# log whats happening.
75
echo "-- initialize_extension_manager() called." >>"${EXTENSION_MANAGER_LOG_FILE}"
76
77
# this is the all-important separator.
78
local hook_extension_delimiter="__"
79
80
# list all defined functions. filter only the ones that have the delimiter. get only the part before the delimiter.
81
# sort them, and make them unique. the sorting is required for uniq to work, and does not affect the ordering of execution.
82
# get them on a single line, space separated.
83
local all_hook_points
84
all_hook_points="$(compgen -A function | grep "${hook_extension_delimiter}" | awk -F "${hook_extension_delimiter}" '{print $1}' | sort | uniq | xargs echo -n)"
85
86
declare -i hook_points_counter=0 hook_functions_counter=0 hook_point_functions_counter=0
87
88
# initialize the cleanups file.
89
fragment_manager_cleanup_file="${SRC}"/.tmp/extension_function_cleanup.sh
90
echo "# cleanups: " >"${fragment_manager_cleanup_file}"
91
92
local FUNCTION_SORT_OPTIONS="--general-numeric-sort --ignore-case" # --random-sort could be used to introduce chaos
93
local hook_point=""
94
# now loop over the hook_points.
95
for hook_point in ${all_hook_points}; do
96
echo "-- hook_point ${hook_point}" >>"${EXTENSION_MANAGER_LOG_FILE}"
97
98
# check if the hook point is already defined as a function.
99
# that can happen for example with user_config(), that can be implemented itself directly by a userpatches config.
100
# for now, just warn, but we could devise a way to actually integrate it in the call list.
101
# or: advise the user to rename their user_config() function to something like user_config__make_it_awesome()
102
local existing_hook_point_function
103
existing_hook_point_function="$(compgen -A function | grep "^${hook_point}\$")"
104
if [[ "${existing_hook_point_function}" == "${hook_point}" ]]; then
105
echo "--- hook_point_functions (final sorted realnames): ${hook_point_functions}" >>"${EXTENSION_MANAGER_LOG_FILE}"
106
display_alert "Extension conflict" "function ${hook_point} already defined! ignoring functions: $(compgen -A function | grep "^${hook_point}${hook_extension_delimiter}")" "wrn"
107
continue
108
fi
109
110
# for each hook_point, obtain the list of implementing functions.
111
# the sort order here is (very) relevant, since it determines final execution order.
112
# so the name of the functions actually determine the ordering.
113
local hook_point_functions hook_point_functions_pre_sort hook_point_functions_sorted_by_sort_id
114
115
# Sorting. Multiple extensions (or even the same extension twice) can implement the same hook point
116
# as long as they have different function names (the part after the double underscore __).
117
# the order those will be called depends on the name; eg:
118
# 'hook_point__033_be_awesome()' would be caller sooner than 'hook_point__799_be_even_more_awesome()'
119
# independent from where they were defined or in which order the extensions containing them were added.
120
# since requiring specific ordering could hamper portability, we reward extension authors who
121
# don't mind ordering for writing just: 'hook_point__be_just_awesome()' which is automatically rewritten
122
# as 'hook_point__500_be_just_awesome()'.
123
# extension authors who care about ordering can use the 3-digit number, and use the context variables
124
# HOOK_ORDER and HOOK_POINT_TOTAL_FUNCS to confirm in which order they're being run.
125
126
# gather the real names of the functions (after the delimiter).
127
hook_point_functions_pre_sort="$(compgen -A function | grep "^${hook_point}${hook_extension_delimiter}" | awk -F "${hook_extension_delimiter}" '{print $2}' | xargs echo -n)"
128
echo "--- hook_point_functions_pre_sort: ${hook_point_functions_pre_sort}" >>"${EXTENSION_MANAGER_LOG_FILE}"
129
130
# add "500_" to the names of function that do NOT start with a number.
131
# keep a reference from the new names to the old names (we'll sort on the new, but invoke the old)
132
declare -A hook_point_functions_sortname_to_realname
133
declare -A hook_point_functions_realname_to_sortname
134
for hook_point_function_realname in ${hook_point_functions_pre_sort}; do
135
local sort_id="${hook_point_function_realname}"
136
[[ ! $sort_id =~ ^[0-9] ]] && sort_id="500_${sort_id}"
137
hook_point_functions_sortname_to_realname[${sort_id}]="${hook_point_function_realname}"
138
hook_point_functions_realname_to_sortname[${hook_point_function_realname}]="${sort_id}"
139
done
140
141
# actually sort the sort_id's...
142
# shellcheck disable=SC2086
143
hook_point_functions_sorted_by_sort_id="$(echo "${hook_point_functions_realname_to_sortname[*]}" | tr " " "\n" | LC_ALL=C sort ${FUNCTION_SORT_OPTIONS} | xargs echo -n)"
144
echo "--- hook_point_functions_sorted_by_sort_id: ${hook_point_functions_sorted_by_sort_id}" >>"${EXTENSION_MANAGER_LOG_FILE}"
145
146
# then map back to the real names, keeping the order..
147
hook_point_functions=""
148
for hook_point_function_sortname in ${hook_point_functions_sorted_by_sort_id}; do
149
hook_point_functions="${hook_point_functions} ${hook_point_functions_sortname_to_realname[${hook_point_function_sortname}]}"
150
done
151
# shellcheck disable=SC2086
152
hook_point_functions="$(echo -n ${hook_point_functions})"
153
echo "--- hook_point_functions (final sorted realnames): ${hook_point_functions}" >>"${EXTENSION_MANAGER_LOG_FILE}"
154
155
hook_point_functions_counter=0
156
hook_points_counter=$((hook_points_counter + 1))
157
158
# determine the variables we'll pass to the hook function during execution.
159
# this helps the extension author create extensions that are portable between userpatches and official Armbian.
160
# shellcheck disable=SC2089
161
local common_function_vars="HOOK_POINT=\"${hook_point}\""
162
163
# loop over the functions for this hook_point (keep a total for the hook point and a grand running total)
164
for hook_point_function in ${hook_point_functions}; do
165
hook_point_functions_counter=$((hook_point_functions_counter + 1))
166
hook_functions_counter=$((hook_functions_counter + 1))
167
done
168
common_function_vars="${common_function_vars} HOOK_POINT_TOTAL_FUNCS=\"${hook_point_functions_counter}\""
169
170
echo "-- hook_point: ${hook_point} will run ${hook_point_functions_counter} functions: ${hook_point_functions}" >>"${EXTENSION_MANAGER_LOG_FILE}"
171
local temp_source_file_for_hook_point="${EXTENSION_MANAGER_TMP_DIR}/extension_function_definition.sh"
172
173
hook_point_functions_loop_counter=0
174
175
# prepare the cleanup for the function, so we can remove our mess at the end of the build.
176
cat <<-FUNCTION_CLEANUP_FOR_HOOK_POINT >>"${fragment_manager_cleanup_file}"
177
unset ${hook_point}
178
FUNCTION_CLEANUP_FOR_HOOK_POINT
179
180
# now compose a function definition. notice the heredoc. it will be written to tmp file, logged, then sourced.
181
# theres a lot of opportunities here, but for now I keep it simple:
182
# - execute functions in the order defined by ${hook_point_functions} above
183
# - define call-specific environment variables, to help extension authors to write portable extensions (eg: EXTENSION_DIR)
184
cat <<-FUNCTION_DEFINITION_HEADER >"${temp_source_file_for_hook_point}"
185
${hook_point}() {
186
echo "*** Extension-managed hook starting '${hook_point}': will run ${hook_point_functions_counter} functions: '${hook_point_functions}'" >>"\${EXTENSION_MANAGER_LOG_FILE}"
187
FUNCTION_DEFINITION_HEADER
188
189
for hook_point_function in ${hook_point_functions}; do
190
hook_point_functions_loop_counter=$((hook_point_functions_loop_counter + 1))
191
192
# store the full name in a hash, so we can track which were actually called later.
193
defined_hook_point_functions["${hook_point}${hook_extension_delimiter}${hook_point_function}"]="DEFINED=yes ${extension_function_info["${hook_point}${hook_extension_delimiter}${hook_point_function}"]}"
194
195
# prepare the call context
196
local hook_point_function_variables="${common_function_vars}" # start with common vars... (eg: HOOK_POINT_TOTAL_FUNCS)
197
# add the contextual extension info for the function (eg, EXTENSION_DIR)
198
hook_point_function_variables="${hook_point_function_variables} ${extension_function_info["${hook_point}${hook_extension_delimiter}${hook_point_function}"]}"
199
# add the current execution counter, so the extension author can know in which order it is being actually called
200
hook_point_function_variables="${hook_point_function_variables} HOOK_ORDER=\"${hook_point_functions_loop_counter}\""
201
202
# add it to our (not the call site!) environment. if we export those in the call site, the stack is corrupted.
203
eval "${hook_point_function_variables}"
204
205
# output the call, passing arguments, and also logging the output to the extensions log.
206
# attention: don't pipe here (eg, capture output), otherwise hook function cant modify the environment (which is mostly the point)
207
# @TODO: better error handling. we have a good opportunity to 'set -e' here, and 'set +e' after, so that extension authors are encouraged to write error-free handling code
208
cat <<-FUNCTION_DEFINITION_CALLSITE >>"${temp_source_file_for_hook_point}"
209
hook_point_function_trace_sources["${hook_point}${hook_extension_delimiter}${hook_point_function}"]="\${BASH_SOURCE[*]}"
210
hook_point_function_trace_lines["${hook_point}${hook_extension_delimiter}${hook_point_function}"]="\${BASH_LINENO[*]}"
211
[[ "\${DEBUG_EXTENSION_CALLS}" == "yes" ]] && display_alert "---> Extension Method ${hook_point}" "${hook_point_functions_loop_counter}/${hook_point_functions_counter} (ext:${EXTENSION:-built-in}) ${hook_point_function}" ""
212
echo "*** *** Extension-managed hook starting ${hook_point_functions_loop_counter}/${hook_point_functions_counter} '${hook_point}${hook_extension_delimiter}${hook_point_function}':" >>"\${EXTENSION_MANAGER_LOG_FILE}"
213
${hook_point_function_variables} ${hook_point}${hook_extension_delimiter}${hook_point_function} "\$@"
214
echo "*** *** Extension-managed hook finished ${hook_point_functions_loop_counter}/${hook_point_functions_counter} '${hook_point}${hook_extension_delimiter}${hook_point_function}':" >>"\${EXTENSION_MANAGER_LOG_FILE}"
215
FUNCTION_DEFINITION_CALLSITE
216
217
# output the cleanup for the implementation as well.
218
cat <<-FUNCTION_CLEANUP_FOR_HOOK_POINT_IMPLEMENTATION >>"${fragment_manager_cleanup_file}"
219
unset ${hook_point}${hook_extension_delimiter}${hook_point_function}
220
FUNCTION_CLEANUP_FOR_HOOK_POINT_IMPLEMENTATION
221
222
# unset extension vars for the next loop.
223
unset EXTENSION EXTENSION_DIR EXTENSION_FILE EXTENSION_ADDED_BY
224
done
225
226
cat <<-FUNCTION_DEFINITION_FOOTER >>"${temp_source_file_for_hook_point}"
227
echo "*** Extension-managed hook ending '${hook_point}': completed." >>"\${EXTENSION_MANAGER_LOG_FILE}"
228
} # end ${hook_point}() function
229
FUNCTION_DEFINITION_FOOTER
230
231
# unsets, lest the next loop inherits them
232
unset hook_point_functions hook_point_functions_sortname_to_realname hook_point_functions_realname_to_sortname
233
234
# log what was produced in our own debug logfile
235
cat "${temp_source_file_for_hook_point}" >>"${EXTENSION_MANAGER_LOG_FILE}"
236
cat "${fragment_manager_cleanup_file}" >>"${EXTENSION_MANAGER_LOG_FILE}"
237
238
# source the generated function.
239
# shellcheck disable=SC1090
240
source "${temp_source_file_for_hook_point}"
241
242
rm -f "${temp_source_file_for_hook_point}"
243
done
244
245
# Dont show any output until we have more than 1 hook function (we implement one already, below)
246
[[ ${hook_functions_counter} -gt 0 ]] &&
247
display_alert "Extension manager" "processed ${hook_points_counter} Extension Methods calls and ${hook_functions_counter} Extension Method implementations" "info" | tee -a "${EXTENSION_MANAGER_LOG_FILE}"
248
}
249
250
cleanup_extension_manager() {
251
if [[ -f "${fragment_manager_cleanup_file}" ]]; then
252
display_alert "Cleaning up" "extension manager" "info"
253
# this will unset all the functions.
254
# shellcheck disable=SC1090 # dynamic source, thanks, shellcheck
255
source "${fragment_manager_cleanup_file}"
256
fi
257
# reset/unset the variables used
258
initialize_extension_manager_counter=0
259
unset extension_function_info defined_hook_point_functions hook_point_function_trace_sources hook_point_function_trace_lines fragment_manager_cleanup_file
260
}
261
262
# why not eat our own dog food?
263
# process everything that happened during extension related activities
264
# and write it to the log. also, move the log from the .tmp dir to its
265
# final location. this will make run_after_build() "hot" (eg, emit warnings)
266
run_after_build__999_finish_extension_manager() {
267
# export these maps, so the hook can access them and produce useful stuff.
268
export defined_hook_point_functions hook_point_function_trace_sources
269
270
# eat our own dog food, pt2.
271
call_extension_method "extension_metadata_ready" <<'EXTENSION_METADATA_READY'
272
*meta-Meta time!*
273
Implement this hook to work with/on the meta-data made available by the extension manager.
274
Interesting stuff to process:
275
- `"${EXTENSION_MANAGER_TMP_DIR}/hook_point_calls.txt"` contains a list of all hook points called, in order.
276
- For each hook_point in the list, more files will have metadata about that hook point.
277
- `${EXTENSION_MANAGER_TMP_DIR}/hook_point.orig.md` contains the hook documentation at the call site (inline docs), hopefully in Markdown format.
278
- `${EXTENSION_MANAGER_TMP_DIR}/hook_point.compat` contains the compatibility names for the hooks.
279
- `${EXTENSION_MANAGER_TMP_DIR}/hook_point.exports` contains _exported_ environment variables.
280
- `${EXTENSION_MANAGER_TMP_DIR}/hook_point.vars` contains _all_ environment variables.
281
- `${defined_hook_point_functions}` is a map of _all_ the defined hook point functions and their extension information.
282
- `${hook_point_function_trace_sources}` is a map of all the hook point functions _that were really called during the build_ and their BASH_SOURCE information.
283
- `${hook_point_function_trace_lines}` is the same, but BASH_LINENO info.
284
After this hook is done, the `${EXTENSION_MANAGER_TMP_DIR}` will be removed.
285
EXTENSION_METADATA_READY
286
287
# Move temporary log file over to final destination, and start writing to it instead (although 999 is pretty late in the game)
288
mv "${EXTENSION_MANAGER_LOG_FILE}" "${DEST}/${LOG_SUBPATH:-debug}/extensions.log"
289
export EXTENSION_MANAGER_LOG_FILE="${DEST}/${LOG_SUBPATH:-debug}/extensions.log"
290
291
# Cleanup. Leave no trace...
292
[[ -d "${EXTENSION_MANAGER_TMP_DIR}" ]] && rm -rf "${EXTENSION_MANAGER_TMP_DIR}"
293
}
294
295
# This is called by call_extension_method(). To say the truth, this should be in an extension. But then it gets too meta for anyone's head.
296
write_hook_point_metadata() {
297
local main_hook_point_name="$1"
298
299
[[ ! -d "${EXTENSION_MANAGER_TMP_DIR}" ]] && mkdir -p "${EXTENSION_MANAGER_TMP_DIR}"
300
cat - >"${EXTENSION_MANAGER_TMP_DIR}/${main_hook_point_name}.orig.md" # Write the hook point documentation received via stdin to a tmp file for later processing.
301
shift
302
echo -n "$@" >"${EXTENSION_MANAGER_TMP_DIR}/${main_hook_point_name}.compat" # log the 2nd+ arguments too (those are the alternative/compatibility names), separate file.
303
compgen -A export >"${EXTENSION_MANAGER_TMP_DIR}/${main_hook_point_name}.exports" # capture the exported env vars.
304
compgen -A variable >"${EXTENSION_MANAGER_TMP_DIR}/${main_hook_point_name}.vars" # capture all env vars.
305
306
# add to the list of hook points called, in order.
307
echo "${main_hook_point_name}" >>"${EXTENSION_MANAGER_TMP_DIR}/hook_point_calls.txt"
308
}
309
310
# Helper function, to get clean "stack traces" that do not include the hook/extension infrastructure code.
311
get_extension_hook_stracktrace() {
312
local sources_str="$1" # Give this ${BASH_SOURCE[*]} - expanded
313
local lines_str="$2" # And this # Give this ${BASH_LINENO[*]} - expanded
314
local sources lines index final_stack=""
315
IFS=' ' read -r -a sources <<<"${sources_str}"
316
IFS=' ' read -r -a lines <<<"${lines_str}"
317
for index in "${!sources[@]}"; do
318
local source="${sources[index]}" line="${lines[((index - 1))]}"
319
# skip extension infrastructure sources, these only pollute the trace and add no insight to users
320
[[ ${source} == */.tmp/extension_function_definition.sh ]] && continue
321
[[ ${source} == *lib/extensions.sh ]] && continue
322
[[ ${source} == */compile.sh ]] && continue
323
# relativize the source, otherwise too long to display
324
source="${source#"${SRC}/"}"
325
# remove 'lib/'. hope this is not too confusing.
326
source="${source#"lib/"}"
327
# add to the list
328
arrow="$([[ "$final_stack" != "" ]] && echo "-> ")"
329
final_stack="${source}:${line} ${arrow} ${final_stack} "
330
done
331
# output the result, no newline
332
# shellcheck disable=SC2086 # I wanna suppress double spacing, thanks
333
echo -n $final_stack
334
}
335
336
show_caller_full() {
337
local frame=0
338
while caller $frame; do
339
((frame++))
340
done
341
}
342
# can be called by board, family, config or user to make sure an extension is included.
343
# single argument is the extension name.
344
# will look for it in /userpatches/extensions first.
345
# if not found there will look in /extensions
346
# if not found will exit 17
347
declare -i enable_extension_recurse_counter=0
348
declare -a enable_extension_recurse_stack
349
enable_extension() {
350
local extension_name="$1"
351
local extension_dir extension_file extension_file_in_dir extension_floating_file
352
local stacktrace
353
354
# capture the stack leading to this, possibly with a hint in front.
355
stacktrace="${ENABLE_EXTENSION_TRACE_HINT}$(get_extension_hook_stracktrace "${BASH_SOURCE[*]}" "${BASH_LINENO[*]}")"
356
357
# if LOG_ENABLE_EXTENSION, output useful stack, so user can figure out which extensions are being added where
358
[[ "${LOG_ENABLE_EXTENSION}" == "yes" ]] &&
359
display_alert "Extension being added" "${extension_name} :: added by ${stacktrace}" ""
360
361
# first a check, has the extension manager already initialized? then it is too late to enable_extension(). bail.
362
if [[ ${initialize_extension_manager_counter} -gt 0 ]]; then
363
display_alert "Extension problem" "already initialized -- too late to add '${extension_name}' (trace: ${stacktrace})" "err"
364
exit 2
365
fi
366
367
# check the counter. if recurring, add to the stack and return success
368
if [[ $enable_extension_recurse_counter -gt 1 ]]; then
369
enable_extension_recurse_stack+=("${extension_name}")
370
return 0
371
fi
372
373
# increment the counter
374
enable_extension_recurse_counter=$((enable_extension_recurse_counter + 1))
375
376
# there are many opportunities here. too many, actually. let userpatches override just some functions, etc.
377
for extension_base_path in "${SRC}/userpatches/extensions" "${EXTER}/extensions"; do
378
extension_dir="${extension_base_path}/${extension_name}"
379
extension_file_in_dir="${extension_dir}/${extension_name}.sh"
380
extension_floating_file="${extension_base_path}/${extension_name}.sh"
381
382
if [[ -d "${extension_dir}" ]] && [[ -f "${extension_file_in_dir}" ]]; then
383
extension_file="${extension_file_in_dir}"
384
break
385
elif [[ -f "${extension_floating_file}" ]]; then
386
extension_dir="${extension_base_path}" # this is misleading. only directory-based extensions should have this.
387
extension_file="${extension_floating_file}"
388
break
389
fi
390
done
391
392
# After that, we should either have extension_file and extension_dir, or throw.
393
if [[ ! -f "${extension_file}" ]]; then
394
echo "ERR: Extension problem -- cant find extension '${extension_name}' anywhere - called by ${BASH_SOURCE[1]}"
395
exit 17 # exit, forcibly. no way we can recover from this, and next extensions will get bogus errors as well.
396
fi
397
398
local before_function_list after_function_list new_function_list
399
400
# store a list of existing functions at this point, before sourcing the extension.
401
before_function_list="$(compgen -A function)"
402
403
# error handling during a 'source' call is quite insane in bash after 4.3.
404
# to be able to catch errors in sourced scripts the only way is to trap
405
declare -i extension_source_generated_error=0
406
trap 'extension_source_generated_error=1;' ERR
407
408
# source the file. extensions are not supposed to do anything except export variables and define functions, so nothing should happen here.
409
# there is no way to enforce it though, short of static analysis.
410
# we could punish the extension authors who violate it by removing some essential variables temporarily from the environment during this source, and restore them later.
411
# shellcheck disable=SC1090
412
source "${extension_file}"
413
414
# remove the trap we set.
415
trap - ERR
416
417
# decrement the recurse counter, so calls to this method are allowed again.
418
enable_extension_recurse_counter=$((enable_extension_recurse_counter - 1))
419
420
# test if it fell into the trap, and abort immediately with an error.
421
if [[ $extension_source_generated_error != 0 ]]; then
422
display_alert "Extension failed to load" "${extension_file}" "err"
423
exit 4
424
fi
425
426
# get a new list of functions after sourcing the extension
427
after_function_list="$(compgen -A function)"
428
429
# compare before and after, thus getting the functions defined by the extension.
430
# comm is oldskool. we like it. go "man comm" to understand -13 below
431
new_function_list="$(comm -13 <(echo "$before_function_list" | sort) <(echo "$after_function_list" | sort))"
432
433
# iterate over defined functions, store them in global associative array extension_function_info
434
for newly_defined_function in ${new_function_list}; do
435
extension_function_info["${newly_defined_function}"]="EXTENSION=\"${extension_name}\" EXTENSION_DIR=\"${extension_dir}\" EXTENSION_FILE=\"${extension_file}\" EXTENSION_ADDED_BY=\"${stacktrace}\""
436
done
437
438
# snapshot, then clear, the stack
439
local -a stack_snapshot=("${enable_extension_recurse_stack[@]}")
440
enable_extension_recurse_stack=()
441
442
# process the stacked snapshot, finally enabling the extensions
443
for stacked_extension in "${stack_snapshot[@]}"; do
444
ENABLE_EXTENSION_TRACE_HINT="RECURSE ${stacktrace} ->" enable_extension "${stacked_extension}"
445
done
446
447
}
448
449