forked from raven-computing/project-init
-
Notifications
You must be signed in to change notification settings - Fork 0
/
libinit.sh
5574 lines (5310 loc) · 205 KB
/
libinit.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# Copyright (C) 2024 Raven Computing
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# #***************************************************************************#
# * *
# * *** Project Init Core Libraries *** *
# * *
# #***************************************************************************#
#
# This file defines common functions and global variables used in the Project
# Init system. It contains the core code upon which the system is built.
#
# Not all functions defined in this file are considered as API functions.
# Functions which can be called as an API are designated as such in their
# source documentation. Concretely, all API functions will have the
# symbol "[API function]" put as the first line comment of their respective
# source documentation. The conventional regulations with regard to API
# stability and backwards compatibility apply. Functions which are not
# considered as an API do not have to guarantee stability with regard to
# their signature. Such functions are allowed to change in any way, or be
# removed completely without the application of any standard deprecation
# policy. The consumption of non-API functions is exclusively intended by
# the Project Init system itself. Therefore, developers writting add-ons are
# strongly advised to only use API functions in their code.
#
# All global variables defined in this file should be considered read-only by
# API users if their identifying name is written in all caps, unless the
# corresponding documentation states that the variable can be used otherwise.
# Do not manually assign a value to read-only global variables.
# The values of variables whose identifying name starts with an underscore
# should only be changed by functions defined in this file or init system code.
#
# The Project Init system divides the initialization into separate steps,
# so called init levels. These levels do not have to be visually
# distinguishable by the end user. They are simply used to hierarchically
# lay out the initialization code in a logical order. The general rule is
# that code in higher init levels is common to all lower init levels. However,
# the reverse is not true. For example, the highest init level is 0 (zero),
# which will typically involve code to retrieve the name and description of the
# project to initialize and the language to be used. The next init level (1)
# will then consider the steps to be taken in order to initialize a project
# with the given language, i.e. all things common to projects for that
# language or technology.
# Each init level is defined by a directory containing an "init.sh" file, a
# so called init script. Such a directory is usually located under a higher
# init level directory.
#
# Although an init script can in principle contain arbitrary shell code, the
# common practice is to ask the underlying user questions relevant to the
# particular init level context and set internal variables. In this way,
# the user is presented with a continuous form of questions in order to set
# up a new project according to his needs.
# The following functions can be used to gather the answer from the user for
# various types of questions:
# * read_user_input_text()
# * read_user_input_selection()
# * read_user_input_yes_no()
#
# Questions, informative text, warnings and errors can be shown at any time
# in a consistent way by means of the log*() family of functions.
#
# The answers provided by the user are in the end usually saved in so called
# substitution variables. These are defined as global shell variables with
# a "var_"-prefix. They should be defined as all lower-case. Substitution
# variables usually have a counterpart in one or more project template
# source files. Those counterparts have the pattern "${{VAR_*}}", where
# the "*" is the unique identifier of that substitution variable, in all caps.
# A standard mechanism is provided by which substitution variables defined in
# project source template files are replaced by the concrete value set in the
# corresponding shell variable. The replace_var() function implements
# this mechanism.
#
# Once an init script has completed its task and gathered all relevant
# information from the user, there are two distinct situations to consider.
# If a subsequent init level exists, then the active init level signals to
# the Project Init system that it can move on to the next lower init level.
# This is done by a call to the proceed_next_level() function, usually placed
# as the last line of code in an init script. This procedure recursively calls
# the init scripts in the right order, until the final init level is reached.
# The final init level usually also has a "source" subdirectory which contains
# the project source template files. Those can be any type of files which are
# used by the concrete project type to be initialized.
#
# The actual project initialization is executed by calling the corresponding
# API functions in the right order. The initialization is a three-step process.
# First, the project source template files are copied as is to the
# project target directory. Second, the licensing and copyright information is
# set up based on the information provided by the user. Third, all copied
# project source files are processed and potentially changed, renamed or moved.
# The actually initialization is therefore executed when the last init script
# calls the following functions in this specific order:
# * project_init_copy()
# * project_init_license()
# * project_init_process()
#
# In principle, any custom shell code can be inserted in between the above
# three function calls. The convention is, however, that these functions are
# the last lines of code in the last init script within the lowermost
# init level. The project_init_process() function is responsible for
# processing the project source template files in such a way, that
# the initialized project contains syntactically correct source code and can
# be built and used practically out of the box. In doing so, all encountered
# substitution variables are replaced by the value set in the corresponding
# init script code. Any init script can introduce and define new substitution
# variables, which must be present in the underlying project source template
# files in order to have an effect. Each substitution variable is processed
# by a call to the replace_var() function.
# Substitution variables should generally not be processed before
# the project_init_process() function is called, although it is possible.
# To adhere to the general init level processing order, each init level script
# can define a process_files_lvl_*() function, where the "*" is the number of
# the init level that the underlying init script implements. These functions
# will be called by the init system at the right time and in the right order,
# from higher init levels (lower level number) to lower init levels
# (higher level number). The convention is that the function implementations
# take care of processing all substitution variables, which are defined or set
# in the underlying init script, by calling the replace_var() function.
# Usually, the process_files_lvl_*() functions are placed as the first function
# inside the corresponding init script.
#
# An irrecoverable error can be signaled at any time by calling the failure()
# function. This will gracefully terminate the initialization process and
# inform the user about the occurred error. If the user should only be
# informed about an issue, without terminating the program, the warning()
# function should be used instead. Warnings are accumulated and shown to
# the user at the end of a successful project initialization.
#
# The library code in this file does not implement the concrete form to
# be shown to the user. This has to be provided separately. However, as part
# of the API contract, any consuming component must ensure that the library
# lifecycle functions are called in the appropriate order. That is:
# * project_init_start()
# * project_init_finish()
#
# In between these function calls, a consuming component may use any
# provided API function to implement a concrete project initialization form
# and descend into more init levels.
#
# When the arguments given to the project_init_start() lifecycle function
# result in the activation of the Quickstart mode,
# the PROJECT_INIT_QUICKSTART_REQUESTED global variable is set to true and
# the consuming component may proceed by calling the
# project_init_process_quickstart() function to load and execute
# the requested Quickstart function.
#
# The developer documentation is available on GitHub:
# https://github.com/raven-computing/project-init/wiki
#
# Please consult the docs for further information on the Init System and
# the provided APIs. The system and its behaviour is customizable by
# an add-on mechanism without having to change the core code of the system.
# Minimum required Bash major version
readonly REQUIREMENT_BASH_VERSION=4;
# [API Exit Code]
# Used when a project is successfully initialized
# and the program has finished without fatal errors.
readonly EXIT_SUCCESS=0;
# [API Exit Code]
# Used when the program encounters any kind of error.
readonly EXIT_FAILURE=1;
# [API Exit Code]
# Used when the program is terminated by an interrupt signal,
# e.g. when cancelling by means of Ctrl+C, or when the user
# does not confirm the project initialization.
readonly EXIT_CANCELLED=5;
# [API Global]
# The status code a Quickstart function should return in the
# case of a successful operation.
# Since:
# 1.4.0
readonly QUICKSTART_STATUS_OK=$EXIT_SUCCESS;
# [API Global]
# The status code a Quickstart function should return in the case of a
# failed operation. This indicates to the system that the entire operation,
# which might consist of multiple chained functions, should be cancelled.
# A warning is shown to the user about the failed operation.
# Use $QUICKSTART_STATUS_NOWARN instead to suppress that warning.
# Since:
# 1.4.0
readonly QUICKSTART_STATUS_FAILURE=$EXIT_FAILURE;
# [API Global]
# The status code a Quickstart function should return in the case of a
# failed operation, suppressing some warnings emitted by the system. This status
# code is the same as $QUICKSTART_STATUS_FAILURE but gives the underlying function
# the opportunity to show its own warning messages to the user before returning.
# Please note that the system will still emit other warnings and errors not related
# to the returned status of the Quickstart function.
# Since:
# 1.4.0
readonly QUICKSTART_STATUS_NOWARN=50;
# [API Global]
# Holds the version identifier of the Project Init system.
# The format is 'major.minor.patch'.
PROJECT_INIT_VERSION="";
# [API Global]
# Holds the version identifier of the addons resources if applicable.
# This is the version as specified in the VERSION file of the addons
# resource directory. The format of the value of this variable
# is 'major.minor.patch', or '?.?.?' if the VERSION file contains an
# invalid format. If no VERSION file is found, this variable will be empty.
PROJECT_INIT_ADDONS_VERSION="";
# [API Global]
# Indicates whether the running version of the Project Init system is
# a development version or a release version. This global variable
# is either true or false.
PROJECT_INIT_IS_DEV_VERSION="";
# [API Global]
# Indicates whether the loaded addons resource of the running Project Init
# system is a development version or a release version. This global variable
# is either true or false.
PROJECT_INIT_ADDONS_IS_DEV_VERSION="";
# [API Global]
# The path to the loaded addon resource directory. This is only set if an addon
# is available and loaded, otherwise it remains empty. It indicates the source
# root of the addon within the local filesystem, which may or may not be
# a temporary location.
# This variable must be regarded as read-only.
# Since:
# 1.4.0
PROJECT_INIT_ADDONS_PATH="";
# [API Global]
# The path of the current working directory of the user when he
# started Project Init.
# This variable must be regarded as read-only.
# Since:
# 1.4.0
USER_CWD="";
# [API Global]
# Contains the absolute path to the directory of
# the current active init level. As the user progresses
# through the forms of the various init levels, this
# variable is automatically adjusted to always point to
# the init level directory the system is currently in.
CURRENT_LVL_PATH="";
# [API Global]
# Contains the number of the currently active init level.
# The start (entry point) of the Project Init system,
# i.e. the source root of the system itself, is defined
# as level 0 (zero). As the user progresses through the
# forms, each directory in which the system descends into
# represents a separate init level, for which a greater
# level number is assigned. This variable is automatically
# adjusted to always equal the number of the init level
# the system is currently in.
CURRENT_LVL_NUMBER=0;
# [API Global]
# Contains the user-entered string from the last call
# to the read_user_input_text() function.
USER_INPUT_ENTERED_TEXT="";
# [API Global]
# Used by the read_user_input_text() function to determine the text value to use
# by default when a user does not provide an answer in the text prompt.
# Since:
# 1.7.0
USER_INPUT_DEFAULT_TEXT="";
# [API Global]
# Contains the selection index of the user choice from
# the last call to the read_user_input_selection() function.
# Please note that this index is always zero-based, even when
# the selection numbers shown to the user within the
# form selections exhibit a different behaviour.
USER_INPUT_ENTERED_INDEX="";
# [API Global]
# Used by the read_user_input_selection() function to determine the
# zero-based index of the item to use by default when a user does not
# provide an answer in the item selection prompt.
# Since:
# 1.7.0
USER_INPUT_DEFAULT_INDEX="";
# [API Global]
# Contains the boolean user answer of the yes/no question
# from the last call to the read_user_input_yes_no() function.
# This variable contains either true or false.
USER_INPUT_ENTERED_BOOL="";
# [API Global]
# The name of the project type selected by the user.
# This global var holds one of the two results of
# the select_project_type() function.
FORM_PROJECT_TYPE_NAME="";
# [API Global]
# The path to the directory of the project type
# selected by the user. This global var holds one of
# the two results of the select_project_type() function.
FORM_PROJECT_TYPE_DIR="";
# [API Global]
# The identifier of the question for which form input is requested.
# This variable can be set before calling the read_user_input_selection() ,
# read_user_input_text() or read_user_input_yes_no() function to make the form
# question that follows assignable by a unique identifier. Currently, this is
# only used during testing. When a value is set before calling any of the
# aforementioned functions, it instructs those functions to read the
# user-provided answer from a prepared internal data structure.
# Since:
# 1.2.0
FORM_QUESTION_ID="";
# [API Global]
# Holds the name of the directory representing
# the next init level that was selected by the user. Please note
# that this is not the absolute path to the selected directory,
# but rather only the name of the directory within the filesystem.
# Represents the first return value of
# the select_next_level_directory() function.
SELECTED_NEXT_LEVEL_DIR="";
# [API Global]
# Holds the display name of the directory that was selected by
# the user. This is not the directory name on the filesystem, but
# rather the name as it is shown to the user within the form,
# i.e. as specified by the accompanying 'name.txt' file.
# Represents the second return value of
# the select_next_level_directory() function.
SELECTED_NEXT_LEVEL_DIR_NAME="";
# [API Global]
# Holds the property value set by the get_property()
# and get_boolean_property() functions.
PROPERTY_VALUE="";
# [API Global]
# Holds the value computed and set by the make_hyperlink() function.
# The string value might contain terminal escape codes.
# Since:
# 1.1.0
HYPERLINK_VALUE="";
# [API Global]
# Holds the value loaded and set by the load_var_from_file() function.
# The string value might contain arbitrary characters, including special
# characters. It might be empty if no corresponding var file was found.
# Since:
# 1.3.0
VAR_FILE_VALUE="";
# [API Global]
# The message to show when a project is successfully initialized.
# This text is shown in the terminal and in the desktop notification.
# A new value can be set to this variable to change the success message.
# Since:
# 1.1.0
PROJECT_INIT_SUCCESS_MESSAGE="Project has been initialized";
# [API Global]
# The name of the file which is generated for the legal text of
# the selected license. A new value can be set to this variable to
# change the file name.
# Since:
# 1.6.0
PROJECT_INIT_LICENSE_FILE_NAME="LICENSE";
# [API Global]
# Indicates whether the user has requested a quickstart.
# Is either true or false.
# This variable must be regarded as read-only.
# Since:
# 1.4.0
PROJECT_INIT_QUICKSTART_REQUESTED=false;
# [API Global]
# Indicates the path to the project source template directory used
# to initialize a new project. This variable is only set after project
# initialization process has started and the source template files have
# been copied to the project target directory by means of
# the project_init_copy() function.
# This variable must be regarded as read-only.
# Since:
# 1.4.0
PROJECT_INIT_USED_SOURCE="";
# [API Global]
# Can be set to `true` in order to suppress the printing of a deprecation
# warning for the next call of any deprecated function. This variable is
# automatically reset to `false` by a deprecated function once it returns.
# Thus, code using deprecated functions must set this variable before each
# call if deprecation warnings should be suppressed for all of them. Please
# note that the automatic reset of the variable value only applies if the
# underlying deprecated function is called within the same shell environment.
# Since:
# 1.3.0
SUPPRESS_DEPRECATION_WARNING=false;
# The path to the target directory where to save files in Quickstart mode.
_PROJECT_INIT_QUICKSTART_OUTPUT_DIR="";
# An array for holding all supported language version
# numbers/identifiers
SUPPORTED_LANG_VERSIONS_IDS=();
# An array for holding the corresponding labels for all
# supported language versions
SUPPORTED_LANG_VERSIONS_LABELS=();
# The associative array for the data in project.properties files.
declare -A PROPERTIES;
# The associative array for the data in extension_map.txt files.
declare -A COPYRIGHT_HEADER_EXT_MAP;
# The paths to the directories of all available project licenses.
# Is set by the _load_available_licenses() function.
# The order of the paths is in sync with the names.
_PROJECT_AVAILABLE_LICENSES_PATHS=();
# The names of all project licenses.
# Is set by the _load_available_licenses() function.
# The order of the names is in sync with the paths.
_PROJECT_AVAILABLE_LICENSES_NAMES=();
# The path to the license resource selected in the active process.
_PROJECT_SELECTED_LICENSE_PATH="";
# The name of the license resource selected in the active process.
_PROJECT_SELECTED_LICENSE_NAME="";
# An array holding names of commands that are required
# by the init system. Is filled by the _read_dependencies() function.
SYS_DEPENDENCIES=();
# An array where all summary warning messages are saved.
# Use the warning() function to add a new message.
_WARNING_LOG=();
# Holds the number of issued warnings. This corresponds to
# the number of occurred warning-level log statements.
_N_WARNINGS=0;
# Holds the number of issued errors. This corresponds to
# the number of occurred error-level log statements.
_N_ERRORS=0;
# The list of all entries in 'files.txt' files.
LIST_FILES_TXT=();
# The array of files which are created by Project Init
# in a target location.
CACHE_ALL_FILES=();
# Used by the _find_files_impl() function to store
# the found files as a separate item in this array.
_FOUND_FILES=();
# Used by the _find_subst_vars() function to store
# the found substitution variables.
_FOUND_SUBST_VARS=();
# A literal new line character. Can be used in values
# for variable substitutions.
readonly _NL="
";
# The absolute path to the location where
# Project Init resources, including addons, are cached.
readonly RES_CACHE_LOCATION="/tmp";
# The base URL pointing to the Project Init source repository.
readonly PROJECT_BASE_URL="https://github.com/raven-computing/project-init";
# The base URL to be used when creating hyperlinks
# to the Project Init documentation, e.g. for help texts.
readonly DOCS_BASE_URL="${PROJECT_BASE_URL}/wiki";
# Contains the absolute path to the directory of the current theoretic
# init level within the addons resource. This is essentially the addons
# counterpart to $CURRENT_LVL_PATH, but the path is always pointing
# to the addons resource directory. This variable is automatically
# adjusted to always point to the init level directory of the addons
# resource that is or would be applicable, even when no such directory
# is provided by the addon. If no addon is active, then this variable
# will be left empty.
_ADDONS_CURRENT_LVL_PATH="";
# An associative array used to track which deprecated functions
# have already been called. Maps function names (without any '()' at the end)
# to constant values. This is effectively used as a set.
declare -A _DEPRECATED_FUNCTIONS;
# Indicates whether some deprecated feature/behaviour was used by any code.
# Does not track the calling of deprecated functions.
_FLAG_DEPRECATED_FEATURE_USED=false;
# Special deprecation file used by the load_var() function.
_FILE_DEPRECATED_FN_LOAD_VAR_USED="$RES_CACHE_LOCATION/pi_deprfnloadvarused";
# Indicates whether the file cache is invalidated.
_FLAG_FCACHE_ERR=false;
# Indicates whether the selected project language comes exclusively
# from an addons resource.
_FLAG_PROJECT_LANG_IS_FROM_ADDONS=false;
# Indicates whether the project_init_copy() function was called.
_FLAG_PROJECT_FILES_COPIED=false;
# Indicates whether the project_init_license() function was called.
_FLAG_PROJECT_LICENSE_PROCESSED=false;
# Indicates whether the project_init_process() function was called.
_FLAG_PROJECT_FILES_PROCESSED=false;
# Indicates whether the directory where the new project should be
# initialized in is polluted, i.e. it already exists and was not empty
# when the init system checked it.
_FLAG_PROJECT_DIR_POLLUTED=false;
# Indicates whether the system configuration has been loaded.
_FLAG_CONFIGURATION_LOADED=false;
# The timeout of the success notification, in milliseconds.
_INT_NOTIF_SUCCESS_TIMEOUT=3000;
# The path to the icon to be used by the success notification.
# Is set dynamically as the program progesses.
_STR_NOTIF_SUCCESS_ICON="";
# Indicates whether a success notification icon was specified by an addon.
_FLAG_NOTIF_SUCCESS_ICON_ADDON=false;
# Terminal color flag may be set as env var
if [[ "$TERMINAL_USE_ANSI_COLORS" == "0" ]]; then
readonly TERMINAL_USE_ANSI_COLORS=false;
# Disable colors
readonly COLOR_RED="";
readonly COLOR_GREEN="";
readonly COLOR_BLUE="";
readonly COLOR_CYAN="";
readonly COLOR_ORANGE="";
readonly COLOR_NC="";
else
readonly TERMINAL_USE_ANSI_COLORS=true;
# Terminal colors
readonly COLOR_RED="\033[0;31m";
readonly COLOR_GREEN="\033[1;32m";
readonly COLOR_BLUE="\033[1;34m";
readonly COLOR_CYAN="\033[1;36m";
readonly COLOR_ORANGE="\033[1;33m";
readonly COLOR_NC="\033[0m";
fi
# The text shown in prompts when requesting user input.
_READ_FN_INPUT_PROMPT="$(echo -e "[${COLOR_CYAN}INPUT${COLOR_NC}] ")";
readonly _READ_FN_INPUT_PROMPT;
# [API function]
# Prints an INFO level statement on stdout.
#
# All given info strings are logged on one line.
#
# Args:
# $* - An arbitrary number of string messages to log
#
# Stdout:
# An INFO level statement.
#
function logI() {
if [[ $TERMINAL_USE_ANSI_COLORS == true ]]; then
echo -e "[${COLOR_BLUE}INFO${COLOR_NC}] $*";
else
echo "[INFO] $*";
fi
}
# [API function]
# Prints a WARNING level statement on stdout.
#
# All given warning strings are logged on one line.
#
# Args:
# $* - An arbitrary number of string messages to log
#
# Stdout:
# A WARNING level statement.
#
function logW() {
if [[ $TERMINAL_USE_ANSI_COLORS == true ]]; then
echo -e "[${COLOR_ORANGE}WARN${COLOR_NC}] $*";
else
echo "[WARN] $*";
fi
((++_N_WARNINGS));
}
# [API function]
# Prints an ERROR level statement on stdout.
#
# All given error strings are logged on one line.
#
# Args:
# $* - An arbitrary number of string messages to log
#
# Stdout:
# An ERROR level statement.
#
function logE() {
if [[ $TERMINAL_USE_ANSI_COLORS == true ]]; then
echo -e "[${COLOR_RED}ERROR${COLOR_NC}] $*";
else
echo "[ERROR] $*";
fi
((++_N_ERRORS));
}
# [API function]
# Adds a warning to the project initialization summary.
#
# This function adds the given warning message to the list of warnings
# shown at the end after a project has been successfully initialized.
# Only one string can be given to this function per call. Each message
# will be shown on a separate line.
#
# Args:
# $1 - A string message to log
#
function warning() {
_WARNING_LOG+=("$1");
}
# Prints a statement indicating a successful operation.
#
# This function shows a success message and prints saved warnings.
# The program will not be terminated by this function.
#
function _log_success() {
local max_lines=20;
logI "";
if [[ $TERMINAL_USE_ANSI_COLORS == true ]]; then
echo -ne "[${COLOR_BLUE}INFO${COLOR_NC}] ";
for i in $(seq 1 $max_lines); do
echo -n "-";
done
echo -ne " [${COLOR_GREEN}SUCCESS${COLOR_NC}] ";
else
echo -n "[INFO] ";
for i in $(seq 1 $max_lines); do
echo -n "-";
done
echo -n " [SUCCESS] ";
fi
for i in $(seq 1 $max_lines); do
echo -n "-";
done
echo "";
logI "${PROJECT_INIT_SUCCESS_MESSAGE}";
logI "";
# Check logged warning messages
local warn_size=${#_WARNING_LOG[@]};
if (( warn_size > 0 )); then
local warning_msg="";
for warning_msg in "${_WARNING_LOG[@]}"; do
logW "${COLOR_ORANGE}Warning:${COLOR_NC}";
logW "$warning_msg";
logI "";
done
fi
}
# Shows a system notification indicating a successful operation.
#
# This function will try to display a desktop notification if
# the notify-send command is available. It returns exit status 1
# if the notify-send command is not available, otherwise it returns
# the exit status of notify-send.
#
function _show_notif_success() {
if _command_dependency "notify-send"; then
local _project_name="New Project";
if [ -n "$var_project_name" ]; then
_project_name="$var_project_name";
fi
local _has_icon=false;
if [ -n "${_STR_NOTIF_SUCCESS_ICON}" ]; then
if [ -r "${_STR_NOTIF_SUCCESS_ICON}" ]; then
_has_icon=true;
fi
fi
if [[ ${_has_icon} == true ]]; then
notify-send -i "${_STR_NOTIF_SUCCESS_ICON}" \
-t ${_INT_NOTIF_SUCCESS_TIMEOUT} \
"${_project_name}" \
"${PROJECT_INIT_SUCCESS_MESSAGE}";
else
notify-send -t ${_INT_NOTIF_SUCCESS_TIMEOUT} \
"${_project_name}" \
"${PROJECT_INIT_SUCCESS_MESSAGE}";
fi
return $?;
fi
return 1;
}
# Prints a help text statement with the specified log level.
#
# Is used to guide the user to some specific part of the official documentation.
# The help text is directly printed with the specified log level. Therefore a call
# to this function needs to be placed at the right location.
#
# Args:
# $1 - The log level to use when printing the help text.
# Must be one of 'I' (Info), 'W' (Warning), 'E' (Error).
# $2 - The documentation link relative to the base URL as indicated
# by the $DOCS_BASE_URL global variable.
#
# Globals:
# DOCS_BASE_URL - Is used by this function to determine the base part of the created
# hyperlink, which points to the official documentation.
#
# Stdout:
# Help text information with the specified log level.
#
function _show_helptext() {
local _log_lvl="$1";
local _doc_res="$2";
if [ -z "${_log_lvl}" ]; then
logE "Programming error: No log level specified in call to _show_helptext()";
logE "at: '${BASH_SOURCE[1]}' (line ${BASH_LINENO[0]})";
return 1;
fi
if [ -z "${_doc_res}" ]; then
logE "Programming error: No resource name specified in call to _show_helptext()";
logE "at: '${BASH_SOURCE[1]}' (line ${BASH_LINENO[0]})";
return 1;
fi
make_hyperlink "${DOCS_BASE_URL}/${_doc_res}" "documentation";
local _helptext="[HELP]: See the $HYPERLINK_VALUE for more information";
if [[ "${_log_lvl}" == "I" ]]; then
logI "";
logI "${_helptext}";
logI "";
elif [[ "${_log_lvl}" == "W" ]]; then
logW "";
logW "${_helptext}";
logW "";
elif [[ "${_log_lvl}" == "E" ]]; then
logE "";
logE "${_helptext}";
logE "";
else
logE "Programming error: Invalid log level specified in call to _show_helptext()";
logE "at: '${BASH_SOURCE[1]}' (line ${BASH_LINENO[0]})";
return 1;
fi
return 0;
}
# Makes a hyperlink value which points to an API function
# description within the official documentation.
#
# Is used to display a link to a specific API function within the official
# documentation. The hyperlink value is created by using the make_hyperlink() function.
# Therefore, the result is saved in the $HYPERLINK_VALUE global variable.
#
# Args:
# $1 - The function name to make a link for. Must not contain any brackets.
#
# Globals:
# DOCS_BASE_URL - Is used by this function to determine the base part of the created
# hyperlink, which points to the official documentation.
# HYPERLINK_VALUE - Holds the string value of the created hyperlink.
# Is set as a result of a call to this function.
#
function _make_func_hl() {
local _func_name="$1";
if [ -z "${_func_name}" ]; then
logE "Programming error: No function name specified in call to _make_func_hl()";
logE "at: '${BASH_SOURCE[1]}' (line ${BASH_LINENO[0]})";
HYPERLINK_VALUE="";
return 1;
fi
# shellcheck disable=SC2206
local version_spec=( ${PROJECT_INIT_VERSION//./ } );
local _m="${version_spec[0]}"; # Major version
make_hyperlink "${DOCS_BASE_URL}/API-Reference-v${_m}#${_func_name}" "${_func_name}()";
return $?;
}
# Safely change the active working directory or fail with an error message.
#
# Args:
# $1 - The path to the directory to change to. This is a mandatory argument.
#
function _cd_or_die() {
local _target_path="$1";
if ! cd "${_target_path}"; then
failure "Failed to change active working directory to '${_target_path}'";
fi
}
# [API function]
# Prints a statement indicating a failed operation.
#
# This function shows a failure message and prints all given error messages.
# The program will be terminated by this function with exit code indicated
# by the global variable $EXIT_FAILURE.
#
# Args:
# $@ - Optional strings indicating all error messages.
# Each message is printed on its own line.
#
# Stdout:
# Error information.
#
function failure() {
local max_lines=20;
logI "";
local i;
if [[ $TERMINAL_USE_ANSI_COLORS == true ]]; then
echo -ne "[${COLOR_BLUE}INFO${COLOR_NC}] ";
for i in $(seq 1 $max_lines); do
echo -ne "-";
done
echo -ne " [${COLOR_RED}FAILURE${COLOR_NC}] ";
else
echo -n "[INFO] ";
for i in $(seq 1 $max_lines); do
echo -n "-";
done
echo -n " [FAILURE] ";
fi
for i in $(seq 1 $max_lines); do
echo -n "-";
done
echo "";
logI "";
if (( $# == 0 )); then
logE "An error has occurred";
else
for msg in "$@"; do
logE "$msg";
done
fi
if [[ ${_FLAG_PROJECT_FILES_COPIED} == true ]]; then
# Source files have already been copied to the target directory.
# Try to clean it up safely
if [ -d "$var_project_dir" ]; then
if [[ ${_FLAG_PROJECT_DIR_POLLUTED} == false ]]; then
var_project_dir="${var_project_dir%/}";
if [[ "$var_project_dir" != "$HOME" ]]; then
rm -r "$var_project_dir";
if (( $? != 0 )); then
logW "Failed to clean up already created project directory.";
logW "Check '$var_project_dir' for remnant files";
fi
fi
else
logW "Unable to clean up already created project directory: Polluted directory.";
logW "Check '$var_project_dir' for remnant files";
fi
fi
fi
if [[ $PROJECT_INIT_QUICKSTART_REQUESTED == true ]]; then
_cancel_quickstart;
fi
# Play bell alert sound if applicable
if [[ ${_FLAG_CONFIGURATION_LOADED} == true ]]; then
get_boolean_property "sys.output.sound.onfail" "true";
if [[ "$PROPERTY_VALUE" == "true" ]]; then
echo -ne "\a";
fi
fi
exit $EXIT_FAILURE;
}
# Cancels a Quickstart operation.
#
# This function potentially cleans up already copied resources in the project
# target directory. If no argument is given, then this function returns
# normally, otherwise it exits the entire application with the exit code
# specified by the first argument.
# If not in Quickstart mode, then this function has no effect.
#
# Args:
# $1 - Optional exit status of the application.
#
# Returns:
# 0 - If no exit status was specified as an argument and the Quickstart
# operation was successfully cancelled.
# 1 - If no Quickstart operation is active at the time this
# function was called. This means that this function call was a NO-OP.
#
# Globals:
# CACHE_ALL_FILES - The files already copied to the project target directory.
#
function _cancel_quickstart() {
local arg_do_exit_with_status="$1";
if [[ $PROJECT_INIT_QUICKSTART_REQUESTED == false ]]; then
return 1;
fi
if (( ${#CACHE_ALL_FILES[@]} > 0 )); then
local f="";
for f in "${CACHE_ALL_FILES[@]}"; do
if [ -d "$f" ]; then
if ! rm -rf "$f"; then
logW "Failed to clean up directory created by quickstart function.";
logW "Check directory '$f'";
fi
elif [ -f "$f" ]; then
if ! rm "$f"; then
logW "Failed to clean up file created by quickstart function.";
logW "Check file '$f'";
fi
fi
done
fi
if [ -n "$arg_do_exit_with_status" ]; then
exit $arg_do_exit_with_status;
fi
return 0;
}
# [API function]
# Creates a hyperlink from the specified URL.
#
# This function can be used to create a clickable hyperlink leading
# to a web resource. The hyperlink might be embedded in a series of
# terminal escape codes if this is an activated feature, in which case
# the specified label is used as the display string for the created hyperlink.
# If the corresponding feature is disabled, the provided URL might be used
# as is in the computed value. Please note that this function does not check
# whether the underlying terminal emulator in use supports displaying
# clickable labeled hyperlinks.
# The result of this function is not printed directly but instead stored
# in the $HYPERLINK_VALUE global variable.
#
# Since:
# 1.1.0
#
# Args:
# $1 - The URL of the hyperlink. This is a mandatory argument.
# $2 - The label of the hyperlink. This argument is optional.
#
# Globals:
# HYPERLINK_VALUE - Holds the string value of the created hyperlink.
# Is set by this function.
#
# Returns:
# 0 - If the hypelink was successfully created.
# 1 - If an error occurred.
#
# Examples:
# make_hyperlink "http://www.example.com" "Example Link";
# logI "Please see this $HYPERLINK_VALUE";
#
function make_hyperlink() {
local _hl_url="$1";
local _hl_label="$2";
if [ -z "${_hl_url}" ]; then
logE "Programming error: No URL specified in call to make_hyperlink()";
logE "at: '${BASH_SOURCE[1]}' (line ${BASH_LINENO[0]})";
HYPERLINK_VALUE="";
return 1;
fi
if [ -z "${_hl_label}" ]; then
_hl_label="${_hl_url}";
fi
get_boolean_property "sys.output.hyperlinks.escape" "true";
if [[ "$PROPERTY_VALUE" == "true" ]]; then
HYPERLINK_VALUE="\e]8;;${_hl_url}\e\\\\${_hl_label}\e]8;;\e\\\\";
else
if [[ "${_hl_label}" != "${_hl_url}" ]]; then
_hl_url="${_hl_label} (${_hl_url})";
fi
HYPERLINK_VALUE="${_hl_url}";
fi
return 0;
}
# Loads the version information for the Project Init base system.
#
# Globals:
# PROJECT_INIT_VERSION - Holds the version identifier string.
# Is set by this function.