-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdcq-install.sh
More file actions
2493 lines (2225 loc) · 73.6 KB
/
dcq-install.sh
File metadata and controls
2493 lines (2225 loc) · 73.6 KB
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
#!/usr/bin/env bash
# Installer for DDEV Drupal Code Quality add-on assets and tooling hints.
# Phases:
# 1) Copy Drupal.org GitLab CI template default configs and shims into the project (with conflict handling).
# 2) Offer to install PHP tooling via ddev composer (core-dev).
# 3) Offer to install JS tooling (project root) using the detected package manager.
# 4) Offer to install VS Code/Codium settings/extensions (merge/overwrite/skip).
#
# Key env vars (see README for full list):
# - DCQ_INSTALL_MODE: replace|skip|abort (conflict strategy for files)
# - DCQ_NONINTERACTIVE / DDEV_NONINTERACTIVE: disable prompts
# - DCQ_INSTALL_DEPS: install|skip (PHP dev tools)
# - DCQ_INSTALL_NODE_DEPS: root|install|skip (JS tooling)
# - DCQ_INSTALL_GITIGNORE: add|skip (dcq-reports entry)
# - DCQ_INSTALL_IDE_SETTINGS: merge|overwrite|skip (IDE settings)
# - DCQ_VERBOSE: 1|true (enable debug WRITE output, default: disabled)
set -euo pipefail
string_lower() {
printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]'
}
truthy() {
local value
value="$(string_lower "${1:-}")"
case "$value" in
1|true|yes|on) return 0 ;;
esac
return 1
}
detect_docroot() {
local config_path="$1"
local value=""
if [ -f "$config_path" ]; then
value="$(awk -F: '/^[[:space:]]*docroot:/ {
val=$2
sub(/^[[:space:]]+/, "", val)
sub(/[[:space:]]+$/, "", val)
gsub(/^"|"$/, "", val)
gsub(/^'\''|'\''$/, "", val)
print val
exit
}' "$config_path")"
fi
value="${value#/}"
value="${value%/}"
if [ -z "$value" ]; then
value="web"
fi
printf '%s' "$value"
}
prompt_setup() {
# Detect a usable TTY for prompts. Falls back to /dev/tty when stdin/stdout
# are redirected (e.g., running from automation).
PROMPT_AVAILABLE=0
PROMPT_IN_FD=
PROMPT_OUT_FD=
# Prefer /dev/tty so prompts remain interactive even inside loops that
# temporarily redirect stdin.
if [ -e /dev/tty ]; then
if exec 3</dev/tty 2>/dev/null && exec 4>/dev/tty 2>/dev/null; then
PROMPT_IN_FD=3
PROMPT_OUT_FD=4
PROMPT_AVAILABLE=1
return
fi
fi
if [ -t 0 ] && [ -t 1 ]; then
PROMPT_IN_FD=0
PROMPT_OUT_FD=1
PROMPT_AVAILABLE=1
return
fi
}
emit() {
# Print to the prompt TTY when available so context appears before prompts.
if [ "${non_interactive:-0}" -eq 1 ]; then
printf "$@"
elif [ "${PROMPT_AVAILABLE:-0}" -eq 1 ]; then
printf "$@" >&"$PROMPT_OUT_FD"
else
printf "$@"
fi
}
emit_copy() {
# Only emit WRITE debug lines when DCQ_VERBOSE is enabled
if truthy "${DCQ_VERBOSE:-0}"; then
emit "$@"
fi
}
prompt_choice() {
# Conflict prompt for file installs; sets PROMPT_CHOICE_RESULT for callers.
local path="$1"
local warn_parity="$2"
local answer=""
PROMPT_CHOICE_RESULT="s"
if [ "${PROMPT_AVAILABLE:-0}" -ne 1 ]; then
printf 'No interactive terminal detected; skipping conflict prompt for %s (default: skip). Set DCQ_INSTALL_MODE=replace|skip|abort to control behavior.\n' "$path" >&2
return
fi
if [ "$warn_parity" = "true" ]; then
printf 'Skipping this file may diverge from Drupal.org GitLab CI template defaults.\n' >&"$PROMPT_OUT_FD"
fi
printf '\n' >&"$PROMPT_OUT_FD"
printf 'Conflict at %s. Choose: [r]eplace (backup), [s]kip, [a]bort, [ra] replace all, [sa] skip all (default: skip): ' "$path" >&"$PROMPT_OUT_FD"
if ! IFS= read -r -u "$PROMPT_IN_FD" answer; then
answer=""
fi
answer="$(printf '%s' "$answer" | tr -d '\r\n')"
if [ -z "$answer" ]; then
return
fi
PROMPT_CHOICE_RESULT="$answer"
}
create_root_package_json() {
# Create a project-root package.json based on Drupal core's package.json.
# Uses PHP inside the DDEV container to read core dependencies.
local ddev_cmd="$1"
local app_root="$2"
local container_package_json="/var/www/html/package.json"
local php_code
local php_payload
local output
local status
php_code=$(cat <<'PHP'
$path = "__DOCROOT_CORE__/package.json";
$data = json_decode(file_get_contents($path), true);
if (!is_array($data)) {
fwrite(STDERR, "Failed to read core package.json\n");
exit(1);
}
$projectName = null;
$configPath = "/var/www/html/.ddev/config.yaml";
if (is_readable($configPath)) {
$lines = file($configPath, FILE_IGNORE_NEW_LINES);
if ($lines !== false) {
foreach ($lines as $line) {
if (preg_match('/^\s*name:\s*(.+?)\s*$/', $line, $matches)) {
$projectName = trim($matches[1], " \t\"'");
break;
}
}
}
}
$out = [
"name" => $projectName ?: ($data["name"] ?? "drupal-project"),
"private" => true,
];
if (isset($data["description"])) {
$out["description"] = $data["description"];
}
if (isset($data["license"])) {
$out["license"] = $data["license"];
}
if (isset($data["engines"])) {
$out["engines"] = $data["engines"];
}
if (isset($data["dependencies"])) {
$out["dependencies"] = $data["dependencies"];
}
if (isset($data["devDependencies"])) {
$out["devDependencies"] = $data["devDependencies"];
}
echo json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
PHP
)
php_code="${php_code//__DOCROOT_CORE__/${DOCROOT_CORE}}"
php_payload="$(printf '%s' "$php_code" | base64 | tr -d '\n')"
# Use bash -lc so the php -r argument stays quoted; ddev exec can reparse
# complex arguments and break on parentheses/semicolons.
output="$("$ddev_cmd" exec bash -lc "php -r 'eval(base64_decode(\"${php_payload}\"));'" 2>&1)"
status=$?
if [ "$status" -ne 0 ] || [ -z "$output" ]; then
printf 'Unable to create project package.json from core.\n' >&2
printf 'Helper status: %s\n' "$status" >&2
if [ -n "$output" ]; then
printf '%s\n' "$output" >&2
else
printf 'No output from helper.\n' >&2
fi
return 1
fi
if ! printf '%s' "$output" | grep -q '^{'; then
printf 'Unable to create project package.json from core (invalid output).\n' >&2
printf '%s\n' "$output" >&2
return 1
fi
printf '%s\n' "$output" > "${app_root%/}/package.json"
emit 'WRITE: %s\n' "${app_root%/}/package.json"
if command_available "$ddev_cmd"; then
if ! printf '%s\n' "$output" | "$ddev_cmd" exec bash -lc "cat > ${container_package_json}"; then
printf 'Failed to write %s in container; Node install may fail.\n' "$container_package_json" >&2
fi
if ! "$ddev_cmd" exec test -f "$container_package_json" >/dev/null 2>&1; then
printf '%s not visible in container; Node install may fail.\n' "$container_package_json" >&2
fi
fi
emit 'Created package.json from Drupal core devDependencies; review and customize as needed.\n'
return 0
}
find_missing_node_deps() {
# Determine missing JS tooling deps by comparing root package.json to
# Drupal core + add-on config requirements (via a PHP helper in the container).
local ddev_cmd="$1"
local php_code
local php_payload
local output
local status
php_code=$(cat <<'PHP'
$rootPath = "/var/www/html/package.json";
$corePath = "__DOCROOT_CORE__/package.json";
$assetsRoot = "/var/www/html/.ddev/drupal-code-quality/assets";
function read_json_file(string $path): ?array {
if (!is_readable($path)) {
return null;
}
$lines = file($path, FILE_IGNORE_NEW_LINES);
if ($lines === false) {
return null;
}
$filtered = [];
foreach ($lines as $line) {
if ($line !== "" && $line[0] === "#") {
continue;
}
$filtered[] = $line;
}
$json = implode("\n", $filtered);
$data = json_decode($json, true);
return is_array($data) ? $data : null;
}
function merge_deps(array $data): array {
$deps = [];
foreach (["dependencies", "devDependencies"] as $key) {
if (isset($data[$key]) && is_array($data[$key])) {
$deps += $data[$key];
}
}
return $deps;
}
function add_required(array &$required, string $name, array $coreDeps): void {
if (!array_key_exists($name, $required)) {
$required[$name] = $coreDeps[$name] ?? "";
}
}
function eslint_plugin_package(string $plugin): string {
if ($plugin === "") {
return "";
}
if ($plugin[0] === "@") {
$parts = explode("/", $plugin, 2);
if (count($parts) === 1) {
return $plugin . "/eslint-plugin";
}
return $parts[0] . "/eslint-plugin-" . $parts[1];
}
return "eslint-plugin-" . $plugin;
}
function eslint_config_package(string $config): string {
if ($config === "") {
return "";
}
if ($config[0] === "@") {
$parts = explode("/", $config, 2);
if (count($parts) === 1) {
return $config . "/eslint-config";
}
return $parts[0] . "/eslint-config-" . $parts[1];
}
return "eslint-config-" . $config;
}
$root = read_json_file($rootPath);
$core = read_json_file($corePath);
if (!is_array($root) || !is_array($core)) {
exit(0);
}
$rootDeps = merge_deps($root);
$coreDeps = merge_deps($core);
$required = $coreDeps;
$basePackages = ["eslint", "prettier", "stylelint", "cspell"];
foreach ($basePackages as $pkg) {
add_required($required, $pkg, $coreDeps);
}
$eslintConfigs = [
$assetsRoot . "/.eslintrc.json",
$assetsRoot . "/.eslintrc.jquery.json",
$assetsRoot . "/.eslintrc.passing.json",
];
foreach ($eslintConfigs as $path) {
$config = read_json_file($path);
if (!is_array($config)) {
continue;
}
if (isset($config["plugins"]) && is_array($config["plugins"])) {
foreach ($config["plugins"] as $plugin) {
if (!is_string($plugin)) {
continue;
}
$pkg = eslint_plugin_package($plugin);
if ($pkg !== "") {
add_required($required, $pkg, $coreDeps);
}
}
}
if (isset($config["extends"]) && is_array($config["extends"])) {
foreach ($config["extends"] as $extend) {
if (!is_string($extend) || $extend === "") {
continue;
}
if ($extend[0] === "." || $extend[0] === "/") {
continue;
}
if (strpos($extend, "eslint:") === 0) {
continue;
}
if (preg_match("/^plugin:([^\\/]+)\\//", $extend, $matches)) {
$pluginName = $matches[1];
$pkg = eslint_plugin_package($pluginName);
if ($pkg !== "") {
add_required($required, $pkg, $coreDeps);
}
continue;
}
$pkg = eslint_config_package($extend);
if ($pkg !== "") {
add_required($required, $pkg, $coreDeps);
}
}
}
}
$stylelintConfig = read_json_file($assetsRoot . "/.stylelintrc.json");
if (is_array($stylelintConfig)) {
if (isset($stylelintConfig["plugins"]) && is_array($stylelintConfig["plugins"])) {
foreach ($stylelintConfig["plugins"] as $plugin) {
if (is_string($plugin) && $plugin !== "") {
add_required($required, $plugin, $coreDeps);
}
}
}
if (isset($stylelintConfig["extends"]) && is_array($stylelintConfig["extends"])) {
foreach ($stylelintConfig["extends"] as $extend) {
if (!is_string($extend) || $extend === "") {
continue;
}
if ($extend[0] === "." || $extend[0] === "/") {
continue;
}
$pkg = $extend;
if (strpos($extend, "/") !== false) {
$pkg = explode("/", $extend, 2)[0];
}
add_required($required, $pkg, $coreDeps);
}
}
}
$missing = [];
foreach ($required as $name => $version) {
if (!array_key_exists($name, $rootDeps)) {
$missing[$name] = $version;
}
}
if (!$missing) {
exit(0);
}
foreach ($missing as $name => $version) {
$suffix = $version ? "@".$version : "";
echo $name . $suffix . PHP_EOL;
}
PHP
)
php_code="${php_code//__DOCROOT_CORE__/${DOCROOT_CORE}}"
php_payload="$(printf '%s' "$php_code" | base64 | tr -d '\n')"
# Use bash -lc so the php -r argument stays quoted; ddev exec can reparse
# complex arguments and break on parentheses/semicolons.
output="$("$ddev_cmd" exec bash -lc "php -r 'eval(base64_decode(\"${php_payload}\"));'" 2>&1)"
status=$?
if [ "$status" -ne 0 ]; then
return 1
fi
printf '%s' "$output"
}
maybe_install_missing_root_deps() {
# Prompt to add missing root devDependencies when root package.json exists.
local ddev_cmd="$1"
local non_interactive="$2"
local package_manager="$3"
local auto_add="${4:-0}"
local suppress_list="${5:-0}"
local missing_node_deps
if ! missing_node_deps="$(find_missing_node_deps "$ddev_cmd")"; then
return 1
fi
if [ -z "$missing_node_deps" ]; then
return 1
fi
# Avoid mapfile (requires bash 4+; macOS ships bash 3.2).
missing_node_deps_array=()
while IFS= read -r _line; do
[ -n "$_line" ] && missing_node_deps_array+=("$_line")
done <<< "$missing_node_deps"
if [ "$suppress_list" -ne 1 ]; then
emit 'Detected missing Drupal JS tooling dependencies in package.json (%d):\n' "${#missing_node_deps_array[@]}"
for dep in "${missing_node_deps_array[@]}"; do
[ -n "$dep" ] || continue
emit ' %s\n' "$dep"
done
fi
if [ "$package_manager" = "npm" ]; then
prompt_msg="Add missing dependencies with 'npm install --save-dev' in the project root? This updates package.json and package-lock.json."
else
prompt_msg="Add missing dependencies with 'yarn add -D' in the project root? This updates package.json and yarn.lock."
fi
should_add=0
if [ "$auto_add" -eq 1 ]; then
should_add=1
elif [ "$non_interactive" -eq 1 ]; then
emit 'Skipping dependency add (non-interactive). Install the missing packages to avoid lint errors.\n'
return 1
elif prompt_yes_no "$prompt_msg" 1; then
should_add=1
fi
if [ "$should_add" -eq 1 ]; then
deps_cmd=""
for dep in "${missing_node_deps_array[@]}"; do
deps_cmd+=" $(printf '%q' "$dep")"
done
if [ "$package_manager" = "npm" ]; then
cmd=( "$ddev_cmd" "exec" "bash" "-lc" "cd /var/www/html && npm install --save-dev --package-lock${deps_cmd}" )
if ! run_command "${cmd[@]}"; then
emit 'npm install --save-dev failed. You can retry manually.\n'
return 1
fi
emit 'Node dependencies added (project root).\n'
cmd=( "$ddev_cmd" "exec" "bash" "-lc" "cd /var/www/html && npm install --package-lock" )
if ! run_command "${cmd[@]}"; then
emit 'npm install failed. You can retry manually.\n'
return 1
fi
else
cmd=( "$ddev_cmd" "exec" "bash" "-lc" "cd /var/www/html && yarn add -D${deps_cmd}" )
if ! run_command "${cmd[@]}"; then
emit 'yarn add failed. You can retry manually.\n'
return 1
fi
emit 'Node dependencies added (project root).\n'
fi
return 0
fi
emit 'Skipping missing dependency install. ESLint plugins may be unavailable.\n'
return 1
}
prompt_node_install_action() {
local has_root="$1"
local missing_deps="$2"
local choice
local first_char
NODE_INSTALL_ACTION="install"
if [ "${PROMPT_AVAILABLE:-0}" -ne 1 ]; then
return
fi
if [ "$has_root" -eq 0 ]; then
emit 'No project package.json found.\n'
fi
if [ -n "$missing_deps" ]; then
emit 'Some required node modules are missing:\n'
while IFS= read -r dep; do
[ -n "$dep" ] || continue
emit ' %s\n' "$dep"
done <<< "$missing_deps"
fi
emit 'ESLint, Prettier, and Stylelint require several packages to function properly.\n'
emit '\n'
emit '[i]nstall in the project root, [s]kip (default: install): '
if ! IFS= read -r -u "$PROMPT_IN_FD" choice; then
choice=""
fi
# Normalize prompt input to avoid silent fall-through on CR/LF/whitespace.
choice="${choice//$'\r'/}"
choice="${choice//$'\n'/}"
choice="$(printf '%s' "$choice" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
choice="$(string_lower "$choice")"
if [ -z "$choice" ]; then
return
fi
first_char="${choice:0:1}"
case "$first_char" in
i) NODE_INSTALL_ACTION="install" ;;
s) NODE_INSTALL_ACTION="skip" ;;
*) NODE_INSTALL_ACTION="install" ;;
esac
}
emit_node_install_command() {
local package_manager="$1"
local missing_deps="$2"
local has_root="$3"
local deps_cmd=""
local cmd=""
if [ -n "$missing_deps" ]; then
while IFS= read -r dep; do
[ -n "$dep" ] || continue
deps_cmd+=" $(printf '%q' "$dep")"
done <<< "$missing_deps"
fi
if [ -n "$deps_cmd" ]; then
if [ "$package_manager" = "npm" ]; then
cmd="ddev exec bash -lc \"cd /var/www/html && npm install --save-dev${deps_cmd}\""
else
cmd="ddev exec bash -lc \"cd /var/www/html && yarn add -D${deps_cmd}\""
fi
else
if [ "$package_manager" = "npm" ]; then
cmd="ddev exec bash -lc \"cd /var/www/html && npm install\""
else
cmd="ddev exec bash -lc \"cd /var/www/html && yarn install\""
fi
fi
if [ "$has_root" -eq 0 ]; then
emit 'No project package.json found. The install requires one at the project root.\n'
fi
emit 'Run:\n %s\n' "$cmd"
}
prompt_yes_no() {
# Standard yes/no prompt with default behavior.
local question="$1"
local default_no="$2"
local suffix
if [ "${PROMPT_AVAILABLE:-0}" -ne 1 ]; then
printf 'No interactive terminal detected; skipping prompt. Use DCQ_INSTALL_* env vars to control behavior.\n' >&2
if [ "$default_no" -eq 1 ]; then
return 1
fi
return 0
fi
if [ "$default_no" -eq 1 ]; then
suffix='[y/N]'
else
suffix='[Y/n]'
fi
printf '%s %s ' "$question" "$suffix" >&"$PROMPT_OUT_FD"
local answer=""
if ! IFS= read -r -u "$PROMPT_IN_FD" answer; then
answer=""
fi
answer="$(string_lower "$answer")"
if [ -z "$answer" ]; then
if [ "$default_no" -eq 1 ]; then
return 1
fi
return 0
fi
case "$answer" in
y|yes) return 0 ;;
esac
return 1
}
prompt_recommended_settings() {
# Prompt for accepting recommended settings (default: yes).
if [ "${PROMPT_AVAILABLE:-0}" -ne 1 ]; then
return 1
fi
if prompt_yes_no "Accept recommended settings for this install?" 0; then
return 0
fi
return 1
}
print_recommended_settings_summary() {
# Show what the one-step recommended install will do before prompting.
if [ "${PROMPT_AVAILABLE:-0}" -ne 1 ]; then
return
fi
emit '\nRecommended defaults for this install:\n'
emit ' - If a copied config file already exists, the installer will create a backup and then replace the file.\n'
emit ' - Install missing PHP tooling via drupal/core-dev, including PHPStan, PHPCS, PHPCBF, and Drupal coding standards.\n'
emit ' - Install Node tooling in the project root, including ESLint, Stylelint, Prettier, and CSpell dependencies.\n'
emit ' - Set phpstan.neon level to 3 as a practical local default.\n'
emit ' - Merge DCQ VS Code/Codium settings into .vscode/settings.json and extension recommendations into .vscode/extensions.json.\n'
emit " - Add 'dcq-reports/' to .gitignore so generated check logs and patch previews are not committed.\n"
}
set_default_env() {
local name="$1"
local value="$2"
if [ -z "${!name:-}" ]; then
printf -v "$name" '%s' "$value"
if [ "$non_interactive" -eq 1 ]; then
emit 'Using recommended default: %s=%s (override with env var)\n' "$name" "$value"
fi
fi
# Always return success - this is just setting defaults
return 0
}
prompt_ide_settings_mode() {
# Prompt for IDE settings merge/overwrite/skip mode; sets PROMPT_IDE_MODE_RESULT.
local choice
PROMPT_IDE_MODE_RESULT="skip"
if [ "${PROMPT_AVAILABLE:-0}" -ne 1 ]; then
return
fi
printf 'VS Code/Codium settings/extensions: [m]erge, [o]verwrite (backup), [s]kip (default: skip): ' >&"$PROMPT_OUT_FD"
if ! IFS= read -r -u "$PROMPT_IN_FD" choice; then
choice=""
fi
choice="$(string_lower "$choice")"
if [ -z "$choice" ]; then
return
fi
case "$choice" in
m|merge) PROMPT_IDE_MODE_RESULT="merge" ;;
o|overwrite|replace) PROMPT_IDE_MODE_RESULT="overwrite" ;;
s|skip|manual) PROMPT_IDE_MODE_RESULT="skip" ;;
*) PROMPT_IDE_MODE_RESULT="skip" ;;
esac
}
set_phpstan_level() {
local config_path="$1"
local level="$2"
local tmp
local replaced=0
local inserted=0
if [ ! -f "$config_path" ]; then
return 1
fi
tmp="$(mktemp "${TMPDIR:-/tmp}/dcq-phpstan-XXXXXX")"
while IFS= read -r line; do
if [[ "$line" =~ ^[[:space:]]*level:[[:space:]]*[0-9]+ ]]; then
if [ "$replaced" -eq 0 ]; then
printf ' level: %s\n' "$level" >>"$tmp"
replaced=1
else
printf '%s\n' "$line" >>"$tmp"
fi
continue
fi
printf '%s\n' "$line" >>"$tmp"
done <"$config_path"
if [ "$replaced" -eq 0 ]; then
tmp2="$(mktemp "${TMPDIR:-/tmp}/dcq-phpstan-XXXXXX")"
while IFS= read -r line; do
printf '%s\n' "$line" >>"$tmp2"
if [ "$inserted" -eq 0 ] && [[ "$line" =~ ^parameters: ]]; then
printf ' level: %s\n' "$level" >>"$tmp2"
inserted=1
fi
done <"$tmp"
if [ "$inserted" -eq 0 ]; then
printf '\nparameters:\n level: %s\n' "$level" >>"$tmp2"
fi
mv "$tmp2" "$tmp"
fi
cat "$tmp" >"$config_path"
rm -f "$tmp"
return 0
}
prompt_phpstan_level() {
local app_root="$1"
local config_path="${app_root%/}/phpstan.neon"
local baseline_path="${app_root%/}/phpstan-baseline.neon"
local answer
local env_level
emit '\n==> PHPStan defaults\n'
emit 'The GitLab CI template defaults to PHPStan level 0, which only catches obvious syntax errors. You can keep level 0 or set a higher level for your project.\n'
emit 'Recommended starting point: level 3.\n'
if [ ! -f "$config_path" ]; then
printf 'phpstan.neon not found in project root; skipping level update.\n'
return 0
fi
env_level="$(string_lower "${DCQ_PHPSTAN_LEVEL:-}")"
# env_level should now always be set via set_default_env or user override
if [[ "$env_level" =~ ^([0-9]|10)$ ]]; then
if set_phpstan_level "$config_path" "$env_level"; then
emit 'WRITE: %s (level %s)\n' "$config_path" "$env_level"
else
printf 'Unable to update phpstan.neon level.\n' >&2
fi
elif [ "$non_interactive" -eq 0 ] && [ "${PROMPT_AVAILABLE:-0}" -eq 1 ]; then
# Interactive mode with invalid/missing level - prompt user
printf '\n'
emit 'Set phpstan.neon level (0-10) (default: 0): '
if ! IFS= read -r -u "$PROMPT_IN_FD" answer; then
answer=""
fi
answer="$(string_lower "$answer")"
if [ "$answer" = "s" ] || [ "$answer" = "skip" ]; then
answer=""
elif [ -z "$answer" ]; then
answer="0"
fi
if [ -n "$answer" ]; then
if [[ "$answer" =~ ^([0-9]|10)$ ]]; then
if set_phpstan_level "$config_path" "$answer"; then
emit 'WRITE: %s (level %s)\n' "$config_path" "$answer"
else
printf 'Unable to update phpstan.neon level.\n' >&2
fi
else
printf 'Invalid level "%s"; keeping current phpstan.neon level.\n' "$answer" >&2
fi
fi
fi
if [ ! -f "$baseline_path" ]; then
emit 'No phpstan-baseline.neon found. Baselines let you focus on new errors while you fix existing ones over time.\n'
emit 'Generate one with:\n'
emit ' ddev phpstan --generate-baseline\n'
fi
return 0
}
maybe_add_gitignore_reports() {
local app_root="$1"
local mode_raw
local mode
local gitignore="${app_root%/}/.gitignore"
local entry="dcq-reports/"
mode_raw="$(string_lower "${2:-}")"
if [ -z "$mode_raw" ]; then
if [ "$non_interactive" -eq 1 ]; then
mode="add"
else
mode="prompt"
fi
else
case "$mode_raw" in
1|true|yes|on|add|install|auto) mode="add" ;;
0|false|no|off|skip) mode="skip" ;;
*) mode="add" ;;
esac
fi
if [ -f "$gitignore" ] && grep -q "^${entry}$" "$gitignore"; then
printf 'OK: %s already lists %s\n' "$gitignore" "$entry"
return 0
fi
if [ "$mode" = "add" ]; then
if [ -f "$gitignore" ]; then
printf '\n%s\n' "$entry" >>"$gitignore"
else
printf '%s\n' "$entry" >"$gitignore"
fi
emit 'WRITE: %s\n' "$gitignore"
return 0
fi
if [ "$mode" = "skip" ]; then
emit 'Skipping .gitignore update for %s.\n' "$entry"
return 0
fi
emit 'Add %s to .gitignore to avoid committing report logs.\n' "$entry"
printf '\n'
if prompt_yes_no "Add '${entry}' to .gitignore?" 0; then
if [ -f "$gitignore" ]; then
printf '\n%s\n' "$entry" >>"$gitignore"
else
printf '%s\n' "$entry" >"$gitignore"
fi
emit 'WRITE: %s\n' "$gitignore"
else
emit 'Skipping .gitignore update for %s.\n' "$entry"
fi
return 0
}
strip_generated_header() {
# Remove ddev-generated header if present to keep target files clean.
local source="$1"
local dest="$2"
if [ "$(head -n 1 "$source")" = "#ddev-generated" ]; then
tail -n +2 "$source" >"$dest"
else
cat "$source" >"$dest"
fi
}
rewrite_docroot_config() {
local source="$1"
local target="$2"
local tmp
if [ "${DCQ_DOCROOT:-web}" = "web" ]; then
return 0
fi
case "$source" in
*/assets/.cspell.json|*/assets/.phpcs.xml)
tmp="$(mktemp "${TMPDIR:-/tmp}/dcq-docroot-XXXXXX")"
sed "s|web/|${DCQ_DOCROOT}/|g" "$target" >"$tmp"
mv "$tmp" "$target"
;;
esac
}
merge_phpstan_config() {
# Merge phpstan.neon with phpstan.dcq.neon and substitute docroot placeholders.
local phpstan_source="$1"
local phpstan_dcq_source="$2"
local target="$3"
local docroot="${DCQ_DOCROOT:-web}"
local tmp
if [ ! -f "$phpstan_dcq_source" ]; then
# If dcq amendments don't exist, just use the base config
return 0
fi
# Append DCQ amendments to the target (already contains base phpstan.neon).
tmp="$(mktemp "${TMPDIR:-/tmp}/dcq-phpstan-XXXXXX")"
cat "$target" > "$tmp"
printf '\n' >> "$tmp"
tail -n +2 "$phpstan_dcq_source" | awk 'BEGIN { seen = 0 }
{
if (seen == 0 && $0 ~ /^[[:space:]]*parameters:/) {
seen = 1
next
}
if (seen == 1) {
print
}
}' >> "$tmp"
# Substitute __DOCROOT__ placeholder with actual docroot.
sed "s|__DOCROOT__|${docroot}|g" "$tmp" > "$target"
rm -f "$tmp"
}
merge_phpcs_config() {
local phpcs_source="$1"
local phpcs_dcq_source="$2"
local target="$3"
local docroot="${DCQ_DOCROOT:-web}"
local tmp
if [ ! -f "$phpcs_dcq_source" ]; then
# If dcq amendments don't exist, just use the base config
return 0
fi
# NOTE: $target already has the cleaned base config (header stripped, docroot substituted)
# from the main copy loop. We just need to merge in the amendments.
# Prepare amendments with docroot substitution
tmp="$(mktemp "${TMPDIR:-/tmp}/dcq-phpcs-XXXXXX")"
tail -n +2 "$phpcs_dcq_source" | sed "s|__DOCROOT__|${docroot}|g" > "$tmp"
# Insert amendments before the closing </ruleset> tag
# Create a new temp file with the merged content
local merged
merged="$(mktemp "${TMPDIR:-/tmp}/dcq-phpcs-merged-XXXXXX")"
# Copy everything except the closing </ruleset> tag
sed '/<\/ruleset>/d' "$target" > "$merged"
# Append our amendments
cat "$tmp" >> "$merged"
# Add closing tag back
printf '\n</ruleset>\n' >> "$merged"
# Move merged content to target
cat "$merged" > "$target"
# Cleanup
rm -f "$tmp" "$merged"
}
append_unique_lines_from_file() {
local target="$1"
local source="$2"
local tmp
local line
if [ ! -f "$source" ]; then
return 0
fi
tmp="$(mktemp "${TMPDIR:-/tmp}/dcq-lines-XXXXXX")"
if [ -f "$target" ]; then
cat "$target" >"$tmp"
else
: >"$tmp"
fi
while IFS= read -r line || [ -n "$line" ]; do
if [ "$line" = "#ddev-generated" ]; then
continue
fi
if grep -Fxq "$line" "$tmp"; then
continue
fi
printf '%s\n' "$line" >>"$tmp"
done <"$source"
if [ ! -f "$target" ] || ! cmp -s "$target" "$tmp"; then
cat "$tmp" >"$target"
emit_copy 'WRITE: %s\n' "$target"
fi
rm -f "$tmp"
}
expand_cspell_config() {
local app_root="$1"
local ddev_approot="${DDEV_APPROOT:-$app_root}"
local prepare_script="${ddev_approot}/.ddev/drupal-code-quality/tooling/scripts/prepare-cspell.php"
local cspell_config="${app_root%/}/.cspell.json"
local docroot="${DCQ_DOCROOT:-web}"
local ddev_cmd="${DDEV_EXECUTABLE:-ddev}"
local container_cspell="/var/www/html/.cspell.json"
local container_core_cspell_dir="/var/www/html/${docroot}/core/misc/cspell"
local container_prepare_script="/mnt/ddev_config/drupal-code-quality/tooling/scripts/prepare-cspell.php"
# Check if CSpell config exists
if [ ! -f "$cspell_config" ]; then
emit 'No .cspell.json found; skipping CSpell expansion.\n'
return 0
fi
# Check if prepare-cspell.php exists
if [ ! -f "$prepare_script" ]; then
emit 'prepare-cspell.php not found; skipping CSpell expansion.\n'