forked from tuya/TuyaOpen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport.sh
More file actions
executable file
·1646 lines (1528 loc) · 57.1 KB
/
Copy pathexport.sh
File metadata and controls
executable file
·1646 lines (1528 loc) · 57.1 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
#
# Usage: . ./export.sh
#
# Set TUYAOPEN_EXPORT_VERBOSE=1 before sourcing for full diagnostic output.
# Set TUYAOPEN_EXPORT_IDE=1 when invoked by TuyaOpen IDE (stage markers for progress UI).
# Set TUYAOPEN_EXPORT_SKIP_MAIN=1 to load functions only (tests).
# Set TUYAOPEN_CN_DOWNLOAD=1 or 0 to force CN / overseas uv download mirrors (default: auto via timezone).
#
# This script must be *sourced* (not executed). It:
# * locates the TuyaOpen project root,
# * ensures `uv` from <root>/.tools/uv/<version>/ (uv-manifest.env),
# * installs Python 3.12.13 via uv into <root>/.tools/python/3.12.13/,
# * creates <root>/.venv and runs `uv sync --frozen` (pyproject.toml + uv.lock),
# * exports OPEN_SDK_ROOT / OPEN_SDK_UV / OPEN_SDK_PYTHON / OPEN_SDK_PIP,
# * adds the project root to PATH so `tos.py` is runnable,
# * runs tos.py prepare (host tools on Windows via export.ps1),
# * registers deactivate / exit helpers and shell completion.
# ---------------------------------------------------------------------------
# Constants (aligned with export.ps1)
# ---------------------------------------------------------------------------
TUYA_UV_VERSION='0.11.18'
TUYA_UV_BASE_URL='https://github.com/astral-sh/uv/releases/download'
TUYA_UV_ASTRAL_BASE_URL='https://releases.astral.sh/github/uv/releases/download'
TUYA_PYTHON_VERSION='3.12.13'
TUYA_VENV_MARKER='.tuyaopen-uv'
TUYA_UV_DOWNLOAD_ATTEMPTS=2
TUYA_ALIYUN_PYPI_INDEX='https://mirrors.aliyun.com/pypi/simple/'
# CN mirror for uv-managed Python (python-build-standalone). Replaces the
# default GitHub base for `uv python install` via UV_PYTHON_INSTALL_MIRROR.
TUYA_PYTHON_INSTALL_MIRROR_CN='https://registry.npmmirror.com/-/binary/python-build-standalone'
TUYA_PROMPT_PREFIX='(TuyaOpen) '
TUYA_CN_TZ_OFFSET_TARGET=480
TUYA_CN_TZ_OFFSET_TOLERANCE=30
if [ "${TUYAOPEN_EXPORT_IDE:-}" = '1' ]; then
export NO_COLOR=1 FORCE_COLOR=0 CLICOLOR=0
fi
# ---------------------------------------------------------------------------
# Locate this script (bash, zsh, POSIX sh)
# ---------------------------------------------------------------------------
if [ -n "${BASH_VERSION:-}" ]; then
_tuya_script_dir=$(realpath "$(dirname "${BASH_SOURCE[0]}")")
elif [ -n "${ZSH_VERSION:-}" ]; then
_tuya_script_dir=$(realpath "$(dirname "${(%):-%x}")")
else
_tuya_script_dir=$(realpath "$(dirname "$0")")
fi
_tuya_pwd_dir="$(pwd)"
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
tuya_info() { echo "$@" >&2; }
tuya_debug() { [ -n "${TUYAOPEN_EXPORT_VERBOSE:-}" ] && echo "$@" >&2; return 0; }
tuya_stage() {
tuya_is_ide_host || return 0
tuya_info "[TuyaOpen] Stage: $1"
}
tuya_is_ide_host() {
[ "${TUYAOPEN_EXPORT_IDE:-}" = '1' ]
}
# ---------------------------------------------------------------------------
# Region detection (CN download mirror; UTC+8 ± tolerance)
# ---------------------------------------------------------------------------
tuya_parse_tz_offset_z() {
local z="$1" sign=1 hours=0 mins=0
[ -n "$z" ] || return 1
case "$z" in
-*)
sign=-1
z="${z#-}"
;;
+*)
z="${z#+}"
;;
*)
return 1
;;
esac
z="${z//:/}"
if [ "${#z}" -lt 4 ]; then
return 1
fi
hours=$((10#${z:0:2}))
mins=$((10#${z:2:2}))
echo $(( sign * (hours * 60 + mins) ))
}
tuya_get_utc_offset_minutes() {
local z=''
z=$(date +%z 2>/dev/null) || return 1
tuya_parse_tz_offset_z "$z"
}
tuya_is_in_cn_tz_range() {
local offset="${1:-}"
local min max
if [ -z "$offset" ]; then
return 1
fi
min=$((TUYA_CN_TZ_OFFSET_TARGET - TUYA_CN_TZ_OFFSET_TOLERANCE))
max=$((TUYA_CN_TZ_OFFSET_TARGET + TUYA_CN_TZ_OFFSET_TOLERANCE))
[ "$offset" -ge "$min" ] && [ "$offset" -le "$max" ]
}
tuya_is_mainland_china() {
case "${TUYAOPEN_CN_DOWNLOAD:-}" in
1) return 0 ;;
0) return 1 ;;
esac
local offset=''
offset=$(tuya_get_utc_offset_minutes) || return 1
tuya_is_in_cn_tz_range "$offset"
}
tuya_detect_region() {
local offset='' override='' msg=''
tuya_stage region
case "${TUYAOPEN_CN_DOWNLOAD:-}" in
1)
_tuya_use_cn_download=1
override=' (override)'
;;
0)
_tuya_use_cn_download=0
override=' (override)'
;;
*)
offset=$(tuya_get_utc_offset_minutes) || offset='unknown'
if [ "$offset" != 'unknown' ] && tuya_is_in_cn_tz_range "$offset"; then
_tuya_use_cn_download=1
else
_tuya_use_cn_download=0
fi
;;
esac
if [ "$_tuya_use_cn_download" -eq 1 ]; then
msg="[TuyaOpen] Region: mainland China (UTC+8±${TUYA_CN_TZ_OFFSET_TOLERANCE}min"
if [ -n "$offset" ] && [ "$offset" != 'unknown' ]; then
msg="${msg}, offset=${offset}"
fi
msg="${msg}, CN download mirror)${override}"
else
msg='[TuyaOpen] Region: overseas'
if [ -n "$offset" ] && [ "$offset" != 'unknown' ]; then
msg="${msg} (offset=${offset})"
fi
msg="${msg} (GitHub/Astral download source)${override}"
fi
# Remember the decision (reason + which source) but don't print it here:
# it's surfaced at uv download time so a warm start (nothing downloaded)
# stays quiet. tuya_debug still shows it under TUYAOPEN_EXPORT_VERBOSE.
_tuya_region_msg="$msg"
tuya_debug "$msg"
}
tuya_size_to_mib() {
local value="$1" unit
unit=$(echo "$2" | tr '[:lower:]' '[:upper:]')
case "$unit" in
KIB) awk "BEGIN {printf \"%.4f\", $value / 1024}" ;;
MIB) echo "$value" ;;
GIB) awk "BEGIN {printf \"%.4f\", $value * 1024}" ;;
*) echo "$value" ;;
esac
}
_tuya_prog_last_text=''
_tuya_prog_last_at=0
_tuya_prog_last_pct=-1
tuya_emit_if_changed() {
local text="$1" pct="${2:--1}" min_ms="${3:-2000}" min_pct="${4:-2}"
local now pct_delta=100 elapsed=999999
now=$(date +%s 2>/dev/null || echo 0)
elapsed=$((now - _tuya_prog_last_at))
if [ "$pct" -ge 0 ] && [ "$_tuya_prog_last_pct" -ge 0 ]; then
pct_delta=$((pct - _tuya_prog_last_pct))
[ "$pct_delta" -lt 0 ] && pct_delta=$((-pct_delta))
fi
if [ "$text" = "$_tuya_prog_last_text" ] && [ "$elapsed" -lt 5 ]; then
return 0
fi
if [ "$elapsed" -lt 2 ] && [ "$pct_delta" -lt "$min_pct" ]; then
return 0
fi
_tuya_prog_last_text="$text"
_tuya_prog_last_at="$now"
_tuya_prog_last_pct="$pct"
tuya_info "$text"
}
# uv diagnostics: keep error/cause lines from a streamed uv run so a failure
# can explain the real reason (network vs. other) instead of a bare exit code.
_tuya_uv_diag=''
tuya_uv_reset_diag() { _tuya_uv_diag=''; }
tuya_uv_capture_diag() {
case "$1" in
error:*|warning:*|*[Ee]rror:*|*Caused\ by:*|*[Ff]ailed\ to\ *|*[Tt]imed\ out*)
_tuya_uv_diag="${_tuya_uv_diag}${1}
"
;;
esac
}
# Best-effort: does the captured uv output look like a network/connectivity issue?
tuya_uv_diag_is_network() {
case "$_tuya_uv_diag" in
*[Dd]ns*|*lookup*|*"name resolution"*|*"Connection refused"*|\
*"Connection reset"*|*"connect error"*|*"tcp connect"*|*"could not connect"*|\
*[Tt]imed\ out*|*[Tt]imeout*|*"Failed to fetch"*|*"Failed to download"*|\
*"error sending request"*|*"Request failed"*|*retries*|*unreachable*|\
*certificate*|*[Ss][Ss][Ll]*|*[Tt][Ll][Ss]*|*proxy*|*network*)
return 0
;;
esac
return 1
}
tuya_uv_print_diag() {
[ -n "$_tuya_uv_diag" ] || return 0
tuya_info 'uv output:'
printf '%s' "$_tuya_uv_diag" | while IFS= read -r _line; do
[ -n "$_line" ] && tuya_info " $_line"
done
}
tuya_uv_run_stream() {
# Run OPEN_SDK_UV with streaming line-by-line callback and correct exit code.
# Uses a FIFO so the while loop runs in the current shell (variable mutations
# persist) and wait() gives the real uv exit code. Falls back to a temp
# file when mkfifo is unavailable (no real-time streaming, but correct rc).
# UV_NO_PROGRESS and UV_LINK_MODE are set/exported here and restored on exit.
local on_line="$1"
shift
local rc=0 line="" fifo="" tmp="" uv_pid=0
local _saved_no_prog="${UV_NO_PROGRESS:-}"
local _saved_link="${UV_LINK_MODE:-}"
UV_NO_PROGRESS=1
UV_LINK_MODE="${UV_LINK_MODE:-copy}"
export UV_NO_PROGRESS UV_LINK_MODE
tuya_uv_reset_diag
fifo=$(mktemp -u 2>/dev/null || printf '%s' "/tmp/tuya_uv_fifo_$$")
if mkfifo "$fifo" 2>/dev/null; then
"$OPEN_SDK_UV" "$@" >"$fifo" 2>&1 &
uv_pid=$!
while IFS= read -r line; do
tuya_uv_capture_diag "$line"
[ -n "$line" ] && "$on_line" "$line"
done <"$fifo"
wait "$uv_pid" || rc=$?
rm -f "$fifo" 2>/dev/null || true
else
tmp=$(mktemp 2>/dev/null || printf '%s' "/tmp/tuya_uv_stream_$$")
"$OPEN_SDK_UV" "$@" >"$tmp" 2>&1 || rc=$?
while IFS= read -r line; do
tuya_uv_capture_diag "$line"
[ -n "$line" ] && "$on_line" "$line"
done <"$tmp"
rm -f "$tmp" 2>/dev/null || true
fi
if [ -z "$_saved_no_prog" ]; then unset UV_NO_PROGRESS; else UV_NO_PROGRESS="$_saved_no_prog"; export UV_NO_PROGRESS; fi
if [ -z "$_saved_link" ]; then unset UV_LINK_MODE; else UV_LINK_MODE="$_saved_link"; export UV_LINK_MODE; fi
return "$rc"
}
_tuya_sync_current=0
_tuya_sync_last_name=''
_tuya_sync_pkg_total=1
tuya_on_uv_sync_line() {
tuya_parse_uv_sync_line "$1" "$_tuya_sync_pkg_total"
}
tuya_parse_uv_sync_line() {
local line="$1" total="$2"
local changed=0 pkg="" n=0
case "$line" in
+*)
pkg=${line#+ }
pkg=${pkg%% *}
_tuya_sync_current=$((_tuya_sync_current + 1))
[ "$_tuya_sync_current" -gt "$total" ] && _tuya_sync_current=$total
_tuya_sync_last_name="$pkg"
changed=1
;;
esac
case "$line" in
[Dd]ownloading\ *)
pkg=${line#Downloading }
pkg=${pkg%% *}
n=$((_tuya_sync_current + 1))
[ "$n" -gt "$total" ] && n=$total
if [ "$n" -gt "$_tuya_sync_current" ]; then
_tuya_sync_current=$n
_tuya_sync_last_name="$pkg"
changed=1
fi
;;
esac
case "$line" in
*Installed\ [0-9]*\ packages*)
n=$(echo "$line" | sed -n 's/.*Installed \([0-9][0-9]*\) packages.*/\1/p')
if [ -n "$n" ] && [ "$n" -gt "$_tuya_sync_current" ]; then
[ "$n" -gt "$total" ] && n=$total
_tuya_sync_current=$n
changed=1
fi
;;
*Audited\ [0-9]*\ packages*)
n=$(echo "$line" | sed -n 's/.*Audited \([0-9][0-9]*\) packages.*/\1/p')
if [ -n "$n" ] && [ "$n" -gt "$_tuya_sync_current" ]; then
[ "$n" -gt "$total" ] && n=$total
_tuya_sync_current=$n
changed=1
fi
;;
esac
if [ "$changed" -eq 1 ]; then
local pct=0 filled=0 empty=28 bar='' text='' i=0
[ "$total" -lt 1 ] && total=1
pct=$((100 * _tuya_sync_current / total))
[ "$pct" -gt 100 ] && pct=100
filled=$((28 * _tuya_sync_current / total))
[ "$filled" -gt 28 ] && filled=28
empty=$((28 - filled))
bar=$(printf '%*s' "$filled" '' | tr ' ' '#')
bar="${bar}$(printf '%*s' "$empty" '' | tr ' ' '-')"
text="[TuyaOpen] Syncing dependencies [$bar] ${_tuya_sync_current}/${total} (${pct}%)"
[ -n "$_tuya_sync_last_name" ] && text="$text - $_tuya_sync_last_name"
tuya_emit_if_changed "$text" "$pct"
fi
}
_tuya_py_artifact='cpython'
_tuya_py_total_mib=0
_tuya_py_recv_mib=-1
tuya_parse_python_install_line() {
local line="$1" recv_u='' total_u='' pct=0 text='' changed=0
case "$line" in
*[Dd]ownloading\ cpython*)
_tuya_py_artifact=$(echo "$line" | sed -n 's/.*[Dd]ownloading \([^ (]*\).*/\1/p')
changed=1
;;
esac
recv_u=$(echo "$line" | sed -n 's/.*\([0-9][0-9.]*\) MiB *\/ *\([0-9][0-9.]*\) MiB.*/\1/p')
total_u=$(echo "$line" | sed -n 's/.*\([0-9][0-9.]*\) MiB *\/ *\([0-9][0-9.]*\) MiB.*/\2/p')
if [ -n "$recv_u" ] && [ -n "$total_u" ]; then
_tuya_py_recv_mib="$recv_u"
_tuya_py_total_mib="$total_u"
changed=1
fi
if [ "$changed" -eq 1 ]; then
text="[TuyaOpen] Installing Python ${TUYA_PYTHON_VERSION}: ${_tuya_py_artifact}"
if [ -n "$total_u" ] && [ -n "$recv_u" ]; then
pct=$(awk "BEGIN {v=int(100*$recv_u/$total_u); if (v>99) v=99; print v}")
text="$text: $recv_u / $total_u MB (${pct}%)"
tuya_emit_if_changed "$text" "$pct"
else
tuya_emit_if_changed "$text" -1
fi
fi
}
tuya_export_cold_start_kind() {
local venv_path="$OPEN_SDK_ROOT/.venv" install_dir python_exe=''
if ! tuya_load_uv_manifest "$OPEN_SDK_ROOT"; then
echo 'full'
return 0
fi
if ! tuya_new_uv_context "$OPEN_SDK_ROOT"; then
echo 'full'
return 0
fi
if ! tuya_test_uv_exe "$_tuya_uv_exe"; then
echo 'full'
return 0
fi
install_dir=$(tuya_python_install_dir)
python_exe=$(tuya_find_managed_python "$install_dir")
if ! tuya_test_python_exe "$python_exe"; then
echo 'full'
return 0
fi
if ! tuya_is_uv_venv "$venv_path"; then
echo 'venv_only'
return 0
fi
echo 'warm'
}
tuya_write_cold_start_hint() {
case "$1" in
full)
tuya_info '[TuyaOpen] First-time setup: downloading uv, Python, and dependencies (may take 3-10 minutes). Please wait...'
;;
venv_only)
tuya_info '[TuyaOpen] Rebuilding virtual environment (Python already installed)...'
;;
esac
}
tuya_export_cold_start() {
[ "$(tuya_export_cold_start_kind)" != 'warm' ]
}
tuya_error() {
local stage="$1" summary="$2" cause="$3"
shift 3
tuya_info "[TuyaOpen] Error: $stage - $summary"
[ -n "$cause" ] && tuya_info "Cause: $cause"
if [ "$#" -gt 0 ]; then
tuya_info 'Next:'
while [ "$#" -gt 0 ]; do
tuya_info " $1"
shift
done
fi
}
tuya_cleanup() {
unset _tuya_script_dir _tuya_pwd_dir tuya_is_env_active
unset _tuya_uv_ver _tuya_uv_triple _tuya_uv_artifact _tuya_uv_url_astral _tuya_uv_url_github _tuya_use_cn_download _tuya_region_msg
unset _tuya_uv_dl_size _tuya_uv_dl_sha256 _tuya_uv_tools_dir
unset _tuya_uv_archive _tuya_uv_exe
unset _tuya_managed_python _tuya_venv_py
unset _tuya_sync_current _tuya_sync_last_name _tuya_sync_pkg_total
unset _tuya_py_artifact _tuya_py_total_mib _tuya_py_recv_mib
unset _tuya_prog_last_text _tuya_prog_last_at _tuya_prog_last_pct
unset _tuya_uv_diag
unset -f tuya_debug tuya_error \
tuya_is_sdk_root tuya_print_version tuya_has_cmd \
tuya_ensure_dir tuya_path_add \
tuya_triple_manifest_key tuya_trim_manifest_value tuya_load_uv_manifest \
tuya_get_uv_artifact_check tuya_get_release_urls tuya_get_uv_download_urls \
tuya_get_uv_cn_url tuya_has_uv_download_override tuya_uv_source_label \
tuya_parse_tz_offset_z tuya_get_utc_offset_minutes tuya_is_in_cn_tz_range tuya_is_mainland_china tuya_detect_region \
tuya_get_arch tuya_select_uv_artifact \
tuya_check_glibc tuya_download_file tuya_verify_sha256 \
tuya_download_file_ide \
tuya_test_uv_exe tuya_new_uv_context \
tuya_resolve_uv tuya_download_uv \
tuya_extract_uv tuya_install_uv tuya_setup_uv \
tuya_python_install_dir tuya_find_managed_python \
tuya_test_python_exe tuya_install_python tuya_install_python_ide \
tuya_run_python_install tuya_python_install_error \
tuya_uv_reset_diag tuya_uv_capture_diag tuya_uv_diag_is_network tuya_uv_print_diag \
tuya_setup_python tuya_uv_sync_plan tuya_uv \
tuya_lock_pkg_count tuya_sync_deps tuya_sync_deps_ide tuya_sync_deps_error \
tuya_is_uv_venv tuya_migrate_legacy_venv \
tuya_setup_venv tuya_is_env_active \
tuya_set_env tuya_reset_cache \
tuya_install_prompt tuya_install_completion \
tuya_register_helpers tuya_invoke_hello \
tuya_platform_banner tuya_guard_active tuya_finalize \
tuya_is_ide_host tuya_size_to_mib tuya_emit_if_changed \
tuya_uv_run_stream tuya_on_uv_sync_line \
tuya_parse_uv_sync_line tuya_parse_python_install_line \
tuya_export_cold_start_kind tuya_write_cold_start_hint \
tuya_export_cold_start tuya_check_git \
tuya_human_size tuya_cleanup 2>/dev/null || true
}
tuya_has_cmd() {
command -v "$1" >/dev/null 2>&1
}
tuya_human_size() {
local bytes="$1" mb kb
mb=$((bytes / 1048576))
[ "$mb" -ge 1 ] && { echo "${mb} MB"; return 0; }
kb=$((bytes / 1024))
[ "$kb" -ge 1 ] && { echo "${kb} KB"; return 0; }
echo "${bytes} B"
}
tuya_ensure_dir() {
local dir="$1"
if [ -d "$dir" ]; then
return 0
fi
if mkdir -p "$dir" 2>/dev/null; then
return 0
fi
tuya_error Io 'Cannot create directory.' "$dir" \
"Ensure the path is writable: $dir" 'Re-run with sufficient permissions.'
return 1
}
tuya_path_add() {
local dir="$1"
case ":${PATH}:" in
*":$dir:"*) ;;
*) PATH="$dir:$PATH" ;;
esac
export PATH
}
tuya_path_remove() {
local dir="$1" new_path="" part rest
rest="${PATH}:"
while [ -n "$rest" ]; do
part="${rest%%:*}"
rest="${rest#*:}"
[ -z "$part" ] && continue
[ "$part" = "$dir" ] && continue
new_path="${new_path:+${new_path}:}${part}"
done
PATH="$new_path"
export PATH
}
# ---------------------------------------------------------------------------
# Project root
# ---------------------------------------------------------------------------
tuya_is_sdk_root() {
[ -f "$1/export.sh" ] && [ -f "$1/pyproject.toml" ] && [ -f "$1/uv.lock" ] && [ -f "$1/tos.py" ]
}
if tuya_is_sdk_root "$_tuya_pwd_dir"; then
OPEN_SDK_ROOT="$_tuya_pwd_dir"
elif tuya_is_sdk_root "$_tuya_script_dir"; then
OPEN_SDK_ROOT="$_tuya_script_dir"
else
tuya_error Entry 'Unable to locate TuyaOpen project root.' \
'export.sh + pyproject.toml + uv.lock + tos.py not found.' \
'Run from the project root or use the absolute path.'
tuya_cleanup
return 1
fi
export OPEN_SDK_ROOT
_tuya_missing=""
for _f in export.sh pyproject.toml uv.lock tos.py; do
if [ ! -f "$OPEN_SDK_ROOT/$_f" ]; then
_tuya_missing="$_tuya_missing $_f"
fi
done
unset _f
if [ -n "$_tuya_missing" ]; then
tuya_error Entry 'Required project files are missing.' "${_tuya_missing# }" \
'Use a complete TuyaOpen clone.' "Missing under: $OPEN_SDK_ROOT"
unset _tuya_missing
tuya_cleanup
return 1
fi
unset _tuya_missing
# ---------------------------------------------------------------------------
# Git availability (hard dependency: platform update / submodules / version)
# ---------------------------------------------------------------------------
tuya_check_git() {
if tuya_has_cmd git; then
return 0
fi
tuya_error Git 'git not found. It may not be installed.' \
'Open a terminal and install, e.g.: sudo apt install git (or: brew install git)' \
'Then restart your terminal and re-run: . ./export.sh'
return 1
}
# ---------------------------------------------------------------------------
# Git version banner
# ---------------------------------------------------------------------------
tuya_print_version() {
local root="$1" ver="" tag="" short="" dirty="" status_out=""
if ! tuya_has_cmd git; then
echo "TuyaOpen version: (git not found)"
return 0
fi
if [ ! -e "$root/.git" ]; then
echo "TuyaOpen version: (not a git checkout)"
return 0
fi
status_out=$(git -C "$root" status --porcelain 2>/dev/null) || status_out=""
if [ -n "$status_out" ]; then
dirty="-dirty"
fi
ver=$(git -C "$root" describe --tags --exact-match HEAD 2>/dev/null) || ver=""
if [ -z "$ver" ]; then
tag=$(git -C "$root" describe --tags --abbrev=0 HEAD 2>/dev/null) || tag=""
short=$(git -C "$root" rev-parse --short=8 HEAD 2>/dev/null) || short=""
if [ -n "$tag" ] && [ -n "$short" ]; then
ver="${tag}-${short}"
elif [ -n "$short" ]; then
ver="$short"
else
ver="unknown"
fi
fi
echo "TuyaOpen version: ${ver}${dirty}"
}
# ---------------------------------------------------------------------------
# uv manifest (uv-manifest.env + env overrides; see export.ps1)
# ---------------------------------------------------------------------------
tuya_triple_manifest_key() {
echo "$1" | tr '[:lower:]' '[:upper:]' | tr '-' '_'
}
tuya_trim_manifest_value() {
local v="$1"
v="${v%$'\r'}"
v="${v#"${v%%[![:space:]]*}"}"
v="${v%"${v##*[![:space:]]}"}"
printf '%s' "$v"
}
tuya_load_uv_manifest() {
local root="$1"
local env_file="$root/uv-manifest.env"
_tuya_uv_ver="$TUYA_UV_VERSION"
_tuya_uv_url_github="$TUYA_UV_BASE_URL"
_tuya_uv_url_astral="$TUYA_UV_ASTRAL_BASE_URL"
if [ -f "$env_file" ]; then
local key val
while IFS= read -r line || [ -n "$line" ]; do
line="${line%$'\r'}"
case "$line" in
''|\#*) continue ;;
UV_VERSION=*) _tuya_uv_ver="$(tuya_trim_manifest_value "${line#UV_VERSION=}")" ;;
UV_DOWNLOAD_SOURCE_ASTRAL=*) _tuya_uv_url_astral="$(tuya_trim_manifest_value "${line#UV_DOWNLOAD_SOURCE_ASTRAL=}")" ;;
UV_DOWNLOAD_SOURCE_GITHUB=*) _tuya_uv_url_github="$(tuya_trim_manifest_value "${line#UV_DOWNLOAD_SOURCE_GITHUB=}")" ;;
UV_*_DOWNLOAD_CN=*)
key="${line%%_DOWNLOAD_CN=*}"
key="${key#UV_}"
val="$(tuya_trim_manifest_value "${line#*=}")"
eval "_tuya_uv_cn_url_${key}=\$val"
;;
UV_*_SHA256=*)
key="${line%%_SHA256=*}"
key="${key#UV_}"
val="$(tuya_trim_manifest_value "${line#*=}")"
eval "_tuya_uv_sha256_${key}=\$val"
;;
UV_*_SIZE=*)
key="${line%%_SIZE=*}"
key="${key#UV_}"
val="$(tuya_trim_manifest_value "${line#*=}")"
eval "_tuya_uv_size_${key}=\$val"
;;
esac
done < "$env_file"
fi
}
tuya_get_uv_artifact_check() {
local triple="$1" key size_var sha_var
key=$(tuya_triple_manifest_key "$triple")
size_var="_tuya_uv_size_${key}"
sha_var="_tuya_uv_sha256_${key}"
eval "local size=\${${size_var}:-}"
eval "local sha=\${${sha_var}:-}"
if [ -z "$size" ] || [ -z "$sha" ]; then
return 1
fi
echo "$size $sha"
}
tuya_get_release_urls() {
local version="$1"
if [ -n "${UV_DOWNLOAD_URL:-}" ]; then
echo "$UV_DOWNLOAD_URL"
return 0
fi
if [ -n "${UV_INSTALLER_GHE_BASE_URL:-}" ]; then
echo "${UV_INSTALLER_GHE_BASE_URL}/astral-sh/uv/releases/download/$version"
return 0
fi
if [ -n "${UV_INSTALLER_GITHUB_BASE_URL:-}" ]; then
echo "${UV_INSTALLER_GITHUB_BASE_URL}/astral-sh/uv/releases/download/$version"
return 0
fi
echo "${_tuya_uv_url_github}/$version"
echo "${_tuya_uv_url_astral}/$version"
}
tuya_has_uv_download_override() {
[ -n "${UV_DOWNLOAD_URL:-}" ] \
|| [ -n "${UV_INSTALLER_GHE_BASE_URL:-}" ] \
|| [ -n "${UV_INSTALLER_GITHUB_BASE_URL:-}" ]
}
tuya_get_uv_cn_url() {
local triple="$1" key url_var url=''
key=$(tuya_triple_manifest_key "$triple")
url_var="_tuya_uv_cn_url_${key}"
eval "url=\${${url_var}:-}"
if [ -n "$url" ]; then
echo "$url"
fi
}
tuya_get_uv_download_urls() {
local base cn_url=''
if tuya_has_uv_download_override; then
for base in $(tuya_get_release_urls "$_tuya_uv_ver"); do
echo "${base%/}/$_tuya_uv_artifact"
done
return 0
fi
if [ "${_tuya_use_cn_download:-0}" -eq 1 ]; then
cn_url=$(tuya_get_uv_cn_url "$_tuya_uv_triple")
if [ -n "$cn_url" ]; then
echo "$cn_url"
fi
fi
for base in $(tuya_get_release_urls "$_tuya_uv_ver"); do
echo "${base%/}/$_tuya_uv_artifact"
done
}
# ---------------------------------------------------------------------------
# Platform / artifact selection (from uv-installer.sh)
# ---------------------------------------------------------------------------
tuya_check_glibc() {
local min_major="$1" min_minor="$2" local_glibc major minor
if ! tuya_has_cmd ldd; then
return 1
fi
local_glibc=$(ldd --version 2>/dev/null | awk 'FNR<=1 {print $NF}')
major=$(echo "$local_glibc" | awk -F. '{print $1}')
minor=$(echo "$local_glibc" | awk -F. '{print $2}')
if [ "$major" = "$min_major" ] && [ "${minor:-0}" -ge "$min_minor" ] 2>/dev/null; then
return 0
fi
tuya_debug "System glibc ($local_glibc) is below ${min_major}.${min_minor}; trying musl fallback."
return 1
}
tuya_get_arch() {
local ostype cputype clibtype bitness current_exe _arch
ostype=$(uname -s)
cputype=$(uname -m)
clibtype='gnu'
case "$ostype" in
Linux)
if ldd --version 2>&1 | grep -q musl; then
clibtype='musl-dynamic'
fi
if [ -r /proc/self/exe ]; then
current_exe=/proc/self/exe
elif [ -n "${SHELL:-}" ]; then
current_exe=$SHELL
else
current_exe=/bin/sh
fi
if tuya_has_cmd head; then
case "$(head -c 5 "$current_exe" 2>/dev/null)" in
$'\177ELF\001') bitness=32 ;;
$'\177ELF\002') bitness=64 ;;
*) bitness=64 ;;
esac
else
bitness=64
fi
ostype="unknown-linux-$clibtype"
;;
Darwin)
ostype='apple-darwin'
if [ "$cputype" = i386 ] && sysctl hw.optional.x86_64 2>/dev/null | grep -q ': 1'; then
cputype=x86_64
elif [ "$cputype" = x86_64 ] && sysctl hw.optional.arm64 2>/dev/null | grep -q ': 1'; then
cputype=arm64
fi
;;
MINGW*|MSYS*|CYGWIN*)
tuya_error Entry 'Use export.ps1 on Windows.' "$(uname -s)" \
'Run: . .\export.ps1'
return 1
;;
*)
tuya_error Entry 'Unsupported host OS.' "$ostype" \
'Use Linux or macOS with export.sh.'
return 1
;;
esac
case "$cputype" in
x86_64|x64|amd64) cputype=x86_64 ;;
aarch64|arm64) cputype=aarch64 ;;
armv7l|armv8l) cputype=armv7; ostype="${ostype}eabihf" ;;
i386|i686|x86) cputype=i686 ;;
riscv64) cputype=riscv64gc ;;
*)
tuya_error Uv 'Unknown CPU type.' "$cputype" \
'Open an issue with uname -m output.'
return 1
;;
esac
if [ "$ostype" = 'unknown-linux-gnu' ] && [ "${bitness:-64}" -eq 32 ] && [ "$cputype" = x86_64 ]; then
cputype=i686
fi
_arch="${cputype}-${ostype}"
echo "$_arch"
}
tuya_select_uv_artifact() {
local true_arch="$1" archive=""
case "$true_arch" in
x86_64-unknown-linux-gnu)
archive='uv-x86_64-unknown-linux-gnu.tar.gz'
tuya_check_glibc 2 17 || archive='uv-x86_64-unknown-linux-musl.tar.gz'
;;
x86_64-unknown-linux-musl-dynamic|x86_64-unknown-linux-musl-static)
archive='uv-x86_64-unknown-linux-musl.tar.gz'
;;
aarch64-unknown-linux-gnu)
archive='uv-aarch64-unknown-linux-gnu.tar.gz'
tuya_check_glibc 2 28 || archive='uv-aarch64-unknown-linux-musl.tar.gz'
;;
aarch64-unknown-linux-musl-dynamic|aarch64-unknown-linux-musl-static)
archive='uv-aarch64-unknown-linux-musl.tar.gz'
;;
x86_64-apple-darwin)
archive='uv-x86_64-apple-darwin.tar.gz'
;;
aarch64-apple-darwin)
archive='uv-aarch64-apple-darwin.tar.gz'
;;
*)
tuya_error Uv 'No uv build for this platform.' "$true_arch" \
'See https://github.com/astral-sh/uv/releases'
return 1
;;
esac
echo "$archive"
}
# ---------------------------------------------------------------------------
# Download / verify / extract uv
# ---------------------------------------------------------------------------
tuya_download_file_ide() {
local url="$1" dest="$2" expected="$3" label="$4" token="${UV_GITHUB_TOKEN:-}"
local tmp="${dest}.part" pid=0 rc=0 received=0 total_mib=0 recv_mib=0
local last_text='' line=''
total_mib=$(awk "BEGIN {printf \"%.1f\", $expected / 1048576}")
rm -f "$tmp" 2>/dev/null || true
if tuya_has_cmd curl; then
if [ -n "$token" ]; then
curl -fL -sS --header "Authorization: Bearer $token" "$url" -o "$tmp" &
else
curl -fL -sS "$url" -o "$tmp" &
fi
pid=$!
while kill -0 "$pid" 2>/dev/null; do
if [ -f "$tmp" ]; then
received=$(wc -c <"$tmp" 2>/dev/null || echo 0)
recv_mib=$(awk "BEGIN {printf \"%.1f\", $received / 1048576}")
line="${label}: ${recv_mib} / ${total_mib} MB"
if [ "$line" != "$last_text" ]; then
tuya_info "$line"
last_text="$line"
fi
fi
sleep 1
done
wait "$pid" || rc=$?
if [ "$rc" -eq 0 ]; then
mv -f "$tmp" "$dest"
line="${label}: ${total_mib} / ${total_mib} MB"
[ "$line" != "$last_text" ] && tuya_info "$line"
else
rm -f "$tmp" 2>/dev/null || true
fi
return "$rc"
fi
tuya_download_file "$url" "$dest"
}
tuya_download_file() {
local url="$1" dest="$2" expected="${3:-0}" label="${4:-[TuyaOpen] Downloading}"
local token="${UV_GITHUB_TOKEN:-}"
if tuya_is_ide_host && [ "$expected" -gt 0 ] 2>/dev/null; then
tuya_download_file_ide "$url" "$dest" "$expected" "$label"
return $?
fi
if tuya_has_cmd curl; then
if [ -n "$token" ]; then
curl -fL --progress-bar --header "Authorization: Bearer $token" "$url" -o "$dest"
else
curl -fL --progress-bar "$url" -o "$dest"
fi
return $?
fi
if tuya_has_cmd wget; then
if [ -n "$token" ]; then
wget --header "Authorization: Bearer $token" "$url" -O "$dest"
else
wget "$url" -O "$dest"
fi
return $?
fi
tuya_error Uv 'curl or wget is required.' 'Neither found on PATH.' \
'Install curl or wget and re-run: . ./export.sh'
return 1
}
tuya_verify_sha256() {
local file="$1" expected="$2" actual=""
if ! tuya_has_cmd sha256sum; then
tuya_debug 'Skipping SHA256 verification (sha256sum not found).'
return 0
fi
actual=$(sha256sum -b "$file" | awk '{print $1}')
if [ "$actual" != "$expected" ]; then
tuya_debug "SHA256 mismatch: got $actual want $expected"
return 1
fi
return 0
}
tuya_test_uv_exe() {
local exe="$1"
[ -x "$exe" ] && "$exe" --version >/dev/null 2>&1
}
tuya_new_uv_context() {
local root="$1" true_arch triple artifact check size sha
true_arch=$(tuya_get_arch) || return 1
artifact=$(tuya_select_uv_artifact "$true_arch") || return 1
triple="${artifact#uv-}"
triple="${triple%.tar.gz}"
check=$(tuya_get_uv_artifact_check "$triple") || {
local manifest_key
manifest_key=$(tuya_triple_manifest_key "$triple")
tuya_error Uv 'Missing uv artifact metadata.' \
"UV_${manifest_key}_SIZE / UV_${manifest_key}_SHA256 in uv-manifest.env" \
'Add checksums for this platform to uv-manifest.env.' \
'Re-run: . ./export.sh'
return 1
}
size="${check%% *}"
sha="${check#* }"
_tuya_uv_triple="$triple"
_tuya_uv_artifact="$artifact"
_tuya_uv_dl_size="$size"
_tuya_uv_dl_sha256="$sha"
_tuya_uv_tools_dir="$root/.tools/uv/$_tuya_uv_ver"
_tuya_uv_archive="$root/.tools/archives/uv/$_tuya_uv_ver/$artifact"
_tuya_uv_exe="$_tuya_uv_tools_dir/uv"
}
# Map a download URL to a short, friendly source name (github/astral/tuyacn).
tuya_uv_source_label() {
case "$1" in
*github.com*) echo github ;;
*astral.sh*) echo astral ;;
*tuyacn.com*) echo tuyacn ;;
*)
local host="${1#*://}"
host="${host%%/*}"
echo "${host:-unknown}"
;;
esac
}
tuya_download_uv() {
local url attempt mirror=0 total=0 rc=1 src=''
total=$(tuya_get_uv_download_urls | wc -l | awk '{print $1}')
for url in $(tuya_get_uv_download_urls); do
mirror=$((mirror + 1))
src=$(tuya_uv_source_label "$url")
if [ "$total" -gt 1 ]; then
tuya_info "[TuyaOpen] Downloading ${_tuya_uv_artifact} from ${src} (source ${mirror}/${total})"
else
tuya_info "[TuyaOpen] Downloading ${_tuya_uv_artifact} from ${src}"
fi
tuya_debug "[TuyaOpen] URL: $url"
attempt=1
while [ "$attempt" -le "$TUYA_UV_DOWNLOAD_ATTEMPTS" ]; do
[ "$attempt" -gt 1 ] && tuya_info "[TuyaOpen] Retry $attempt/$TUYA_UV_DOWNLOAD_ATTEMPTS from ${src}..."
rm -f "$_tuya_uv_archive" 2>/dev/null || true
if tuya_download_file "$url" "$_tuya_uv_archive" "$_tuya_uv_dl_size" "[TuyaOpen] Downloading $_tuya_uv_artifact"; then
rc=0
break 2
else
rc=$?
fi
attempt=$((attempt + 1))
done
if [ "$mirror" -lt "$total" ]; then