Repository navigation
Expand file tree
/
Copy pathmage
More file actions
executable file
·4341 lines (3566 loc) · 125 KB
/
Copy pathmage
File metadata and controls
executable file
·4341 lines (3566 loc) · 125 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
# Mage is a collection of easy commands and aliases for bin/magento
# For those who hate typing long shell commands
set -o pipefail
MAGE_VERSION="3.0.0"
MAGE_SELF="${BASH_SOURCE[0]}"
# --- core/output.sh
RESET=""
BOLD=""
ITALIC=""
RED=""
GREEN=""
YELLOW=""
BLUE=""
if [[ -t 1 ]] && [[ -z "${NO_COLOR:-}" ]]; then
RESET=$'\033[0m'
BOLD=$'\033[1m'
ITALIC=$'\033[3m'
RED=$'\033[31m'
GREEN=$'\033[32m'
YELLOW=$'\033[33m'
BLUE=$'\033[34m'
fi
function mage_info() {
printf '%s\n' "$*"
}
# Notices go to stderr, so they never end up in piped command output
function mage_notice() {
printf '%s\n' "${BLUE}$*${RESET}" >&2
}
function mage_warn() {
printf '%s\n' "${YELLOW}$*${RESET}" >&2
}
function mage_error() {
printf '%s\n' "${RED}$*${RESET}" >&2
}
# Print a checklist line, marked as done or failed by the first argument
function mage_check() {
if [[ "$1" == 0 ]]; then
printf ' [%s] %s\n' "${GREEN}✓${RESET}" "$2"
else
printf ' [%s] %s\n' "${RED}✗${RESET}" "$2"
fi
}
# --- core/config.sh
# Defaults, any of these can be overridden in ~/.config/mage/config
MAGE_CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/mage"
MAGE_CONFIG_FILE="${MAGE_CONFIG_DIR}/config"
MAGE_UPDATE_URL="https://raw.githubusercontent.com/GrimLink/mage/main/mage"
# The templates folder of this archive is synced to the config folder
MAGE_TEMPLATES_ARCHIVE="https://github.com/GrimLink/mage/tarball/main"
# The placeholders are replaced by your git user, see mage_system_user
MAGE_ADMIN_USER="acme"
MAGE_ADMIN_FIRSTNAME="acme"
MAGE_ADMIN_LASTNAME="admin"
MAGE_ADMIN_EMAIL="info@example.com"
MAGE_ADMIN_PASS="magento_123$"
# Take the defaults and confirm without asking, as -y does, such as for scripts and agents
MAGE_YES="${MAGE_YES:-0}"
# The edition 'mage create' defaults to: mage-os, community or enterprise
MAGE_EDITION="mage-os"
# Stores are served as https://<project>.<MAGE_DOMAIN>/
MAGE_DOMAIN="test"
# The mail catcher 'mage open mail' opens on your machine, Mailpit by default
MAGE_MAIL_URL="http://localhost:8025"
# An empty MAGE_DB_NAME uses the project folder name
MAGE_DB_HOST="localhost"
MAGE_DB_NAME=""
MAGE_DB_USER="root"
MAGE_DB_PASS="root"
MAGE_SEARCH_HOST="localhost"
MAGE_SEARCH_PORT="9200"
MAGE_REDIS_HOST="127.0.0.1"
MAGE_PACKAGES=(
cweagans/composer-patches
yireo/magento2-theme-commands
swissup/module-ignition
community-engineering/language-nl_nl
)
MAGE_DEV_PACKAGES=(
avstudnitz/scopehint2
spatie/ray
siteation/magento2-debugbar
)
# The modules mage setup disables, when the install has them: two factor auth,
# and the bfcache of Mage-OS, which conflicts with the BFCache patches and Hyva
MAGE_DISABLE_MODULES=(
Magento_AdminAdobeImsTwoFactorAuth
Magento_TwoFactorAuth
MageOS_ThemeOptimization
)
# The npm scripts 'mage build' runs, and with --watch
MAGE_BUILD_SCRIPT="build"
MAGE_WATCH_SCRIPT="watch"
# Magento pins these, so they would always show as outdated
MAGE_OUTDATED_IGNORE=(
symfony/finder
symfony/process
)
# The handlers 'mage clean all' and 'mage purge' run, in order
MAGE_CLEAN_ALL="files redis varnish"
# Where 'mage backup' writes to, relative to the Magento root
MAGE_BACKUP_DIR="var/backups"
# The magerun2 table groups 'mage backup' leaves out of the dump, empty for none
MAGE_BACKUP_STRIP="@stripped"
# The Magento root on the server 'mage sync' pulls from, the one of Hypernode by default
MAGE_SYNC_PATH="/data/web/magento2"
# Each entry is 'path value', an entry without a value sets it empty
MAGE_STORE_CONFIG=(
"currency/options/base EUR"
"currency/options/default EUR"
"currency/options/allow EUR,GBP"
"general/country/default NL"
"general/country/allow AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,CH,NO,IS,LI,GB"
"admin/usage/enabled 0"
"admin/security/session_lifetime 86400"
"admin/security/password_lifetime"
"admin/security/password_is_forced 0"
"catalog/seo/category_canonical_tag 1"
"catalog/seo/product_canonical_tag 1"
"siteation_debugbar/general/enabled 1"
)
# Defaults for the {{NAME}} placeholders in json files for 'mage add' go in the
# config as MAGE_VAR_<NAME>, such as MAGE_VAR_HYVA_PROJECT="my-project"
# The config runs as code, so like ssh with its config, refuse one that someone
# else could have changed: not owned by you, or writable by group or others
if [[ -f "$MAGE_CONFIG_FILE" ]]; then
if [[ ! -O "$MAGE_CONFIG_FILE" ]] || [[ ! -O "$MAGE_CONFIG_DIR" ]] ||
[[ -n "$(find "$MAGE_CONFIG_DIR" "$MAGE_CONFIG_FILE" -maxdepth 0 \( -perm -g=w -o -perm -o=w \) 2> /dev/null)" ]]; then
mage_error "Not loading ${MAGE_CONFIG_FILE}, it is not owned by you or others can change it"
mage_error "Fix it with: chmod 600 \"${MAGE_CONFIG_FILE}\" && chmod go-w \"${MAGE_CONFIG_DIR}\""
exit 1
fi
# shellcheck source=/dev/null
source "$MAGE_CONFIG_FILE"
fi
# Replace the placeholders of the admin user with your git user, the system user,
# for the commands that create one. A value set in the config is kept, and
# without a git user, such as on a CI runner, the placeholders stay.
function mage_system_user() {
local name
local email
if [[ "$MAGE_ADMIN_FIRSTNAME" == "acme" ]] && name="$(git config --global --get user.name 2> /dev/null)"; then
MAGE_ADMIN_FIRSTNAME="${name%% *}"
fi
if [[ "$MAGE_ADMIN_USER" == "acme" ]]; then
MAGE_ADMIN_USER="$(echo "$MAGE_ADMIN_FIRSTNAME" | tr '[:upper:]' '[:lower:]')"
fi
if [[ "$MAGE_ADMIN_EMAIL" == "info@example.com" ]] && email="$(git config --global --get user.email 2> /dev/null)"; then
MAGE_ADMIN_EMAIL="$email"
fi
}
# Add a setting to the config file, quoted so the file stays valid bash
function mage_config_save() {
mkdir -p "$MAGE_CONFIG_DIR"
if [[ ! -f "$MAGE_CONFIG_FILE" ]]; then
touch "$MAGE_CONFIG_FILE"
chmod 600 "$MAGE_CONFIG_FILE"
fi
printf '%s=%q\n' "$1" "$2" >> "$MAGE_CONFIG_FILE"
mage_notice "Saved ${1} in ${MAGE_CONFIG_FILE}"
}
# --- core/tools.sh
# Commands used by mage, an environment can override them in its apply hook
MAGENTO_CLI="bin/magento"
PHP_CLI="php"
COMPOSER_CLI="composer"
NODE_CLI="node"
NPM_CLI="npm"
MYSQL_CLI="mysql"
MYSQLDUMP_CLI="mysqldump"
REDIS_CLI="redis-cli"
VARNISH_CLI="varnishadm"
RSYNC_CLI="rsync"
# Always on your machine, where the ssh keys are, also with an environment
SSH_CLI="ssh"
SYNC_RSYNC_CLI="rsync"
SEARCH_CURL_CLI="curl"
PURGE_CLI="rm -rf"
OPEN_CLI="xdg-open"
if [[ "$OSTYPE" == "darwin"* ]]; then
OPEN_CLI="open"
fi
# Detected on first use, see set_magerun_cli
MAGERUN_CLI=""
MAGERUN_CHECKED=0
# Detect the magerun2 cli on first use, as the version check is slow
# in a Magento root and most commands never need it
function set_magerun_cli() {
if [[ -n "$MAGERUN_CLI" ]] || [[ $MAGERUN_CHECKED == 1 ]]; then
return
fi
MAGERUN_CHECKED=1
if command -v magerun2 &> /dev/null && magerun2 --version &> /dev/null; then
MAGERUN_CLI="magerun2"
elif command -v n98-magerun2 &> /dev/null && n98-magerun2 --version &> /dev/null; then
MAGERUN_CLI="n98-magerun2"
fi
}
function check_has_magerun() {
set_magerun_cli
if [[ -z "$MAGERUN_CLI" ]]; then
mage_error "Magerun2 is not installed or incompatible with current PHP version"
exit 1
fi
}
# --- core/env.sh
# Environments in order of priority, the first one detected wins.
# Each env/<name>.sh defines env_<name>_available, env_<name>_detect
# and env_<name>_apply, and may add any other hook, see env_call.
MAGE_ENVS="warden ddev valet local"
MAGE_ENV="local"
# Echo the environment used by the current folder
function mage_env_detect() {
local env
for env in $MAGE_ENVS; do
if "env_${env}_detect"; then
echo "$env"
return
fi
done
echo "local"
}
# Echo the environments that are installed on this machine
function mage_env_available() {
local env
local available=()
for env in $MAGE_ENVS; do
if "env_${env}_available"; then
available+=("$env")
fi
done
echo "${available[*]}"
}
# Check whether the name is a known environment
function mage_env_exists() {
[[ " $MAGE_ENVS " == *" $1 "* ]]
}
# Switch to the given environment
function mage_env_use() {
if ! mage_env_exists "$1"; then
mage_error "Unknown environment '$1', use one of: ${MAGE_ENVS}"
exit 1
fi
MAGE_ENV="$1"
env_call apply
}
function mage_env_init() {
mage_env_use "$(mage_env_detect)"
}
# Run a hook of the current environment, falling back to the local one.
# A hook that neither defines is a no-op.
function env_call() {
local hook="$1"
shift
if declare -F "env_${MAGE_ENV}_${hook}" > /dev/null; then
"env_${MAGE_ENV}_${hook}" "$@"
elif declare -F "env_local_${hook}" > /dev/null; then
"env_local_${hook}" "$@"
fi
}
# --- core/root.sh
MAGE_ROOT=""
MAGE_CALL_DIR="$PWD"
# Echo the Magento root at or above the given folder
function mage_find_root() {
local dir="${1:-$PWD}"
while true; do
if [[ -f "${dir}/bin/magento" ]] && [[ -f "${dir}/app/etc/di.xml" ]]; then
echo "$dir"
return 0
fi
if [[ "$dir" == "/" ]] || [[ -z "$dir" ]]; then
return 1
fi
dir="$(dirname "$dir")"
done
}
# Move to the Magento root, when called from a nested folder
function mage_root_enter() {
MAGE_ROOT="$(mage_find_root "$PWD")"
if [[ -z "$MAGE_ROOT" ]]; then
mage_error "This does not look like a Magento 2 project, aborting.."
mage_info "Run 'mage help' to see what mage can do"
return 1
fi
if [[ "$MAGE_ROOT" != "$PWD" ]]; then
mage_notice "Running from ${MAGE_ROOT}"
cd "$MAGE_ROOT" || return 1
fi
}
# Echo a path given from the calling folder, relative to the Magento root,
# for commands that take a path. Relative to the root, it works the same
# on the host and inside a container.
function mage_resolve_path() {
local path="$1"
if [[ "$path" == /* ]] || [[ "$MAGE_CALL_DIR" == "$MAGE_ROOT" ]]; then
echo "$path"
elif [[ "$MAGE_CALL_DIR" == "$MAGE_ROOT"/* ]]; then
echo "${MAGE_CALL_DIR#"$MAGE_ROOT"/}/${path}"
else
echo "${MAGE_CALL_DIR}/${path}"
fi
}
# --- core/helpers.sh
# Echo the mage config folder, and create it when missing
function mage_config_dir() {
mkdir -p "$MAGE_CONFIG_DIR"
echo "$MAGE_CONFIG_DIR"
}
# Ask a question, where an empty answer takes the default.
# The prompt goes to stderr, so this stays usable inside a command substitution.
function mage_ask() {
local question="$1"
local default="$2"
local answer=""
if [[ $MAGE_YES == 1 ]] && [[ -n "$default" ]]; then
echo "$default"
return
fi
if [[ -n "$default" ]]; then
read -r -e -p "${question} (${default}): " answer || mage_no_answer "$question"
else
read -r -e -p "${question}: " answer || mage_no_answer "$question"
fi
echo "${answer:-$default}"
}
# Ask a yes/no question, where an empty answer takes the default of 'n' or 'y'
function mage_confirm() {
local question="$1"
local default="${2:-n}"
local options="y/N"
if [[ $default == "y" ]]; then
options="Y/n"
fi
if [[ $MAGE_YES == 1 ]]; then
[[ $default == "y" ]]
return $?
fi
read -r -e -p "${question} [${options}] " || mage_no_answer "$question"
if [[ -z "$REPLY" ]]; then
[[ $default == "y" ]]
return $?
fi
[[ $REPLY =~ ^[yY] ]]
}
# Echo a value from app/etc/env.php by its path, such as 'db/connection/default/dbname'.
# Uses the host php, so it fails quietly when php is not installed.
function mage_env_php() {
if [[ ! -f app/etc/env.php ]] || ! command -v php &> /dev/null; then
return 1
fi
php -r '
$value = include "app/etc/env.php";
foreach (explode("/", $argv[1]) as $key) {
if (!is_array($value) || !isset($value[$key])) { exit(1); }
$value = $value[$key];
}
if (is_scalar($value)) { echo $value; }
' -- "$1" 2> /dev/null
}
# Set the MAGE_DB_* settings from app/etc/env.php, keeping the current ones for what it lacks.
# The database name falls back to MAGE_DB_NAME, then the project folder.
function mage_env_php_db() {
MAGE_DB_NAME="$(mage_env_php db/connection/default/dbname || echo "${MAGE_DB_NAME:-$(basename "$PWD")}")"
MAGE_DB_HOST="$(mage_env_php db/connection/default/host || echo "$MAGE_DB_HOST")"
MAGE_DB_USER="$(mage_env_php db/connection/default/username || echo "$MAGE_DB_USER")"
MAGE_DB_PASS="$(mage_env_php db/connection/default/password || echo "$MAGE_DB_PASS")"
}
# Set MAGE_DB_ARGS to the connection arguments of mysql and mysqldump. The host
# can hold a port or a socket, such as localhost:3307 or localhost:/tmp/mysql.sock
function mage_db_args() {
MAGE_DB_ARGS=(-h"${MAGE_DB_HOST%%:*}" -u"$MAGE_DB_USER")
if [[ "$MAGE_DB_HOST" == *:/* ]]; then
MAGE_DB_ARGS+=(--socket="${MAGE_DB_HOST#*:}")
elif [[ "$MAGE_DB_HOST" == *:* ]]; then
MAGE_DB_ARGS+=(-P"${MAGE_DB_HOST#*:}")
fi
}
# Ask to type the name to confirm something that can not be undone
function mage_confirm_name() {
local answer=""
read -r -p "Type '${1}' to confirm: " answer || mage_no_answer "Type '${1}' to confirm"
[[ "$answer" == "$1" ]]
}
# Stop when a question gets no answer, such as without a terminal for a script or
# agent, instead of quietly taking a default
function mage_no_answer() {
echo "" >&2
mage_error "No answer for: ${1}"
mage_error "Run it in a terminal, or pass the answer as an option or -y, see docs/automation.md"
exit 1
}
# Download a url to a given path, using curl or wget
function mage_download_file() {
local url="$1"
local target="$2"
local temp="${target}.part"
if command -v curl &> /dev/null; then
curl -fsL "$url" -o "$temp"
elif command -v wget &> /dev/null; then
wget -qO "$temp" "$url"
else
mage_error "Neither curl nor wget is available"
return 1
fi
if [[ ! -s "$temp" ]]; then
rm -f "$temp"
return 1
fi
mv "$temp" "$target"
}
# Echo the package name from a composer.json
function mage_composer_name() {
if [[ -f "$1" ]]; then
grep -E '"name"[[:space:]]*:' "$1" | head -n 1 | sed -E 's/.*"name"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/'
fi
}
# Convert a string to kebab-case, such as MyTheme to my-theme
function mage_kebab_case() {
echo "$*" | sed 's/\([A-Z]\)/-\1/g' | tr '[:upper:]' '[:lower:]' | sed -e 's/^-*//' -e 's/-*$//' | tr -s '[:blank:]' '-'
}
function mage_lower_case() {
echo "$*" | tr '[:upper:]' '[:lower:]'
}
# Ask for the vendor and name of a new theme or module, where 'Vendor/Name'
# works as one answer, and a name given as argument skips the question.
# A function can only echo one value, so the result is shared through
# MAGE_NEW_VENDOR, MAGE_NEW_NAME, MAGE_NEW_VENDOR_PKG and MAGE_NEW_NAME_PKG.
function mage_ask_vendor_name() {
local label="$1"
local name="$2"
local vendor=""
if [[ -z "$name" ]]; then
name="$(mage_ask "${label} name (Vendor/Name)")" || return 1
fi
if [[ "$name" == */* ]]; then
vendor="${name%%/*}"
name="${name#*/}"
fi
if [[ -z "$vendor" ]]; then
vendor="$(mage_ask "${label} vendor")" || return 1
fi
MAGE_NEW_VENDOR="$(echo "$vendor" | tr -d '[:blank:]')"
MAGE_NEW_NAME="$(echo "$name" | tr -d '[:blank:]')"
if [[ -z "$MAGE_NEW_VENDOR" ]] || [[ -z "$MAGE_NEW_NAME" ]]; then
mage_error "The ${label} vendor and name can not be empty"
return 1
fi
MAGE_NEW_VENDOR_PKG="$(mage_lower_case "$MAGE_NEW_VENDOR")"
MAGE_NEW_NAME_PKG="$(mage_kebab_case "$MAGE_NEW_NAME")"
}
function mage_is_hyva_installed() {
[[ -d vendor/hyva-themes/magento2-theme-module ]]
}
# Echo the packages in the composer.json key that contain any of the terms,
# case-insensitive and as plain text. Platform entries like php and ext-* have no slash.
function mage_composer_matches() {
local key="$1"
shift
local patterns=()
local term
for term in "$@"; do
patterns+=(-e "$term")
done
jq -r --arg key "$key" '.[$key] // {} | keys[] | select(contains("/"))' composer.json |
grep -i -F "${patterns[@]}"
}
# Exit when jq is missing, the argument describes what needs it
function mage_require_jq() {
if ! command -v jq &> /dev/null; then
mage_error "$1 requires jq, install it with 'brew install jq' or your package manager"
exit 1
fi
}
# Make the theme, such as Hyva/default, the active theme where possible,
# otherwise point to the admin. Returns 1 when the theme was not set.
function mage_set_theme() {
if [[ -d vendor/yireo/magento2-theme-commands ]]; then
$MAGENTO_CLI theme:change "$1" && $MAGENTO_CLI cache:clean
return
fi
mage_notice "Select the $1 theme in the admin, under Content, Design, Configuration"
return 1
}
# Check whether the arguments ask for json output
function mage_wants_json() {
[[ " $* " == *" --json "* ]]
}
# --- core/handlers.sh
# Commands like add, clean, set and show pass their first argument to a handler.
# A handler registers as 'name|description' in the registry of its command,
# and is implemented as mage_<command>_<name>, with dashes as underscores.
# Check whether the name is in the given handler entries
function mage_handler_exists() {
local name="$1"
local entry
shift
for entry in "$@"; do
if [[ "${entry%%|*}" == "$name" ]]; then
return 0
fi
done
return 1
}
# Run the handler of a command, such as mage_clean_sample_files for 'clean sample-files'
function mage_handler_run() {
local command="$1"
local name="$2"
shift 2
"mage_${command}_${name//-/_}" "$@"
}
# Print a help line for each of the given handler entries
function mage_handler_help() {
local command="$1"
local entry
shift
for entry in "$@"; do
mage_help_cmd "${command} ${entry%%|*}" "${entry#*|}"
done
}
# --- core/templates.sh
# The templates are synced to the mage config folder on first use and by
# self-update, so they are available offline and never fetched per command
# Replace the templates in the target folder with those from the latest release.
# The whole folder is replaced at once, so a failed sync keeps the previous templates.
function mage_sync_templates() {
local target="$1"
local temp_dir
temp_dir="$(mktemp -d)"
local archive="${temp_dir}/templates.tar.gz"
local status=1
if mage_download_file "$MAGE_TEMPLATES_ARCHIVE" "$archive" &&
tar -xzf "$archive" -C "$temp_dir" --strip-components=1 &> /dev/null &&
[[ -d "$temp_dir/templates" ]]; then
rm -rf "$target"
mv "$temp_dir/templates" "$target"
status=0
fi
rm -rf "$temp_dir"
return $status
}
# Echo the templates folder. Running unbuilt, that is the one in the repository.
function mage_templates_dir() {
if [[ "$MAGE_VERSION" == "dev" ]]; then
echo "$(dirname "$MAGE_SRC")/templates"
return
fi
local templates_dir
templates_dir="$(mage_config_dir)/templates"
if [[ ! -d "$templates_dir" ]]; then
mage_sync_templates "$templates_dir"
fi
if [[ ! -d "$templates_dir" ]]; then
return 1
fi
echo "$templates_dir"
}
# Echo the path to a single template file
function mage_template_file() {
local file
file="$(mage_templates_dir)/$1"
if [[ ! -f "$file" ]]; then
return 1
fi
echo "$file"
}
# Copy a template folder to a destination,
# where each NAME=value argument replaces {{NAME}} in the copied files
function mage_copy_template() {
local template="$1"
local dest="$2"
shift 2
local template_dir
template_dir="$(mage_templates_dir)/${template}"
if [[ ! -d "$template_dir" ]]; then
mage_error "Could not get the '${template}' template from ${MAGE_TEMPLATES_ARCHIVE}"
return 1
fi
mkdir -p "$dest"
cp -R "${template_dir}/." "$dest"
local file
local content
local pair
while IFS= read -r -d '' file; do
content="$(cat "$file")"
for pair in "$@"; do
content="${content//\{\{${pair%%=*}\}\}/${pair#*=}}"
done
printf '%s\n' "$content" > "$file"
done < <(find "$dest" -type f -print0)
}
# --- core/php.sh
# Magento has no command for some of what mage needs, so this boots Magento with php.
# The code gets $objectManager and the functions below, and its arguments as $argv from 1.
MAGE_PHP_BOOTSTRAP='
require "app/bootstrap.php";
$objectManager = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER)->getObjectManager();
function mageAdminUrl($objectManager) {
$config = $objectManager->get(\Magento\Framework\App\Config\ScopeConfigInterface::class);
$base = $config->isSetFlag("admin/url/use_custom")
? $config->getValue("admin/url/custom")
: $objectManager->get(\Magento\Store\Model\StoreManagerInterface::class)
->getStore(0)->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB, true);
$frontName = $objectManager->get(\Magento\Backend\App\Area\FrontNameResolver::class)->getFrontName();
return rtrim($base, "/") . "/" . $frontName . "/";
}
'
function mage_php() {
local code="$1"
shift
$PHP_CLI -r "${MAGE_PHP_BOOTSTRAP}${code}" -- "$@"
}
# --- env/local.sh
# The local environment is the fallback for every hook,
# the defaults it runs with are set in core/tools.sh and core/config.sh
function env_local_available() {
return 0
}
function env_local_detect() {
return 0
}
function env_local_apply() {
return 0
}
# Run mysql with the MAGE_DB_* credentials
function env_local_mysql() {
mage_db_args
MYSQL_PWD="$MAGE_DB_PASS" $MYSQL_CLI "${MAGE_DB_ARGS[@]}" "$@"
}
# Create the composer project in a new folder, and move into it
function env_local_create_project() {
local name="$1"
local package="$2"
local repository="$3"
$COMPOSER_CLI create-project --no-install --stability dev --prefer-source --repository="$repository" "$package" "$name" || return 1
cd "$name" || return 1
}
# Prepare the services before the Magento install, a new empty database
function env_local_setup_prepare() {
local db_name="$2"
if ! command -v $MYSQL_CLI &> /dev/null; then
mage_error "mysql not found! Create the database '${db_name}' before running 'mage setup' again"
return 1
fi
mage_info "Setting up database '${db_name}'..."
env_local_mysql -e "DROP DATABASE IF EXISTS \`${db_name}\`;" &&
env_local_mysql -e "CREATE DATABASE \`${db_name}\`;"
}
# The database comes from app/etc/env.php, falling back to the config and the project name
function env_local_nuke() {
mage_env_php_db
local db_name="$MAGE_DB_NAME"
mage_clean_opensearch "$db_name"
env_local_clean_redis
if env_local_mysql -e "DROP DATABASE IF EXISTS \`${db_name}\`;"; then
mage_check 0 "Database '${db_name}' dropped"
else
mage_check 1 "Could not drop database '${db_name}'"
fi
}
# Dump the database gzipped to the file, leaving out the magerun2 table groups
# of the second argument. Without magerun2 it falls back to mysqldump.
function env_local_backup_db() {
local file="$1"
local strip="$2"
set_magerun_cli
if [[ -z "$MAGERUN_CLI" ]]; then
mage_backup_mysqldump "$file"
return
fi
local args=(db:dump --stdout)
if [[ -n "$strip" ]]; then
args+=("--strip=${strip}")
fi
$MAGERUN_CLI "${args[@]}" | gzip > "$file"
}
# Replace the database with the gzipped dump, with magerun2 or mysql
function env_local_restore_db() {
local file="$1"
set_magerun_cli
if [[ -n "$MAGERUN_CLI" ]]; then
$MAGERUN_CLI db:import --no-interaction --drop --compression=gzip "$file"
return
fi
if ! command -v "${MYSQL_CLI%% *}" &> /dev/null; then
mage_error "Neither magerun2 nor mysql found, install one of them"
return 1
fi
env_local_mysql -e "DROP DATABASE IF EXISTS \`${MAGE_DB_NAME}\`; CREATE DATABASE \`${MAGE_DB_NAME}\`;" &&
gzip -dc "$file" | env_local_mysql "$MAGE_DB_NAME"
}
# Delete the cache keys of the project from Redis, by the id prefix of each
# cache in app/etc/env.php, so other projects on the same Redis keep theirs
function env_local_clean_redis() {
if ! command -v $REDIS_CLI &> /dev/null; then
mage_check 1 "redis-cli not found, the Redis caches are left as is"
return 1
fi
local cache
local options
local prefix
local host
local port
local db
for cache in default page_cache; do
options="cache/frontend/${cache}/backend_options"
prefix="$(mage_env_php "cache/frontend/${cache}/id_prefix")"
host="$(mage_env_php "${options}/server" || echo "$MAGE_REDIS_HOST")"
port="$(mage_env_php "${options}/port" || echo 6379)"
db="$(mage_env_php "${options}/database" || echo 0)"
if [[ -z "$prefix" ]]; then
mage_check 1 "Could not determine the Redis prefix of the ${cache} cache"
continue
fi
# Cache keys look like zc:k:<prefix><ID> and their tags like zc:ti:<prefix><TAG>
$REDIS_CLI -h "$host" -p "$port" -n "$db" --scan --pattern "zc:*:${prefix}*" |
xargs -n 100 $REDIS_CLI -h "$host" -p "$port" -n "$db" del &> /dev/null
mage_check 0 "Redis ${cache} cache with prefix '${prefix}'"
done
}
# The domain of a new store view is up to the web server on your machine
function env_local_add_store() {
mage_notice "Point ${1} to this project in your web server, and set MAGE_RUN_CODE=${2} with MAGE_RUN_TYPE=store for it"
}
function env_local_open_mail() {
mage_open_browser "$MAGE_MAIL_URL"
}
# Echo the command of a global cache-clean, from 'composer global require mage-os/magento-cache-clean'
function env_local_watch_cli() {
if command -v cache-clean.js &> /dev/null; then
echo "cache-clean.js"
fi
}
# --- env/valet.sh
# Laravel Valet, services run on the host like the local environment
function env_valet_available() {
command -v valet &> /dev/null
}
function env_valet_detect() {
env_valet_available
}
function env_valet_setup_prepare() {
env_local_setup_prepare "$@" || return 1
mage_info "Securing with Valet..."
valet secure "$1"
}
# Echo a store entry for the .valet-env.php, commented out when the third argument is 'true'
function env_valet_store_entry() {
local store_name="${1:-store}"
local store_code="${2:-default}"
local prefix=""
if [[ "$3" == true ]]; then
prefix="// "
fi
printf "\t%s'%s' => [\n" "$prefix" "$store_name"
printf "\t%s\t'MAGE_RUN_CODE' => '%s',\n" "$prefix" "$store_code"
printf "\t%s\t'MAGE_RUN_TYPE' => 'store',\n" "$prefix"
printf "\t%s],\n" "$prefix"
}
# Prepare the .valet-env.php for multi store setups, and the driver that keeps assets fresh
function env_valet_setup_finish() {
local name="$1"
{
printf '<?php declare(strict_types=1);\n\nreturn [\n'
env_valet_store_entry "$name" "default"
env_valet_store_entry "store-2" "default2" true
printf '];\n'
} > .valet-env.php
env_valet_add_driver
}
# Valet serves static files without Cache-Control, so browsers keep stale assets
# in developer mode, this driver makes them revalidate. An existing driver is kept.
function env_valet_add_driver() {
if [[ -e LocalValetDriver.php ]]; then
mage_notice "A LocalValetDriver.php is already present, skipping"
return
fi
local template
template="$(mage_template_file "LocalValetDriver.php")"
if [[ -z "$template" ]]; then
mage_warn "Could not get the LocalValetDriver.php from ${MAGE_TEMPLATES_ARCHIVE}"
return 1
fi
cp "$template" LocalValetDriver.php
mage_check 0 "Added LocalValetDriver.php, so the browser revalidates static files"
}
function env_valet_nuke() {
local name="$1"
env_local_nuke "$@"
valet unsecure "$name"
mage_check 0 "Valet site '${name}' unsecured"
if [[ -f .valet-env.php ]] && command -v php &> /dev/null; then
local store
local stores
stores="$(php -r '$stores = include ".valet-env.php"; if (is_array($stores)) { echo implode(PHP_EOL, array_keys($stores)); }' 2> /dev/null)"
for store in $stores; do
if [[ "$store" != "$name" ]]; then
valet unsecure "$store"
valet unlink "$store"
mage_check 0 "Valet store '${store}' unsecured and unlinked"
fi
done
fi
}
# Valet serves a site by its name without the tld, which is also the key in .valet-env.php
function env_valet_add_store() {
local domain="$1"
local code="$2"
local site="${domain%."${MAGE_DOMAIN}"}"