-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfdevc.sh
More file actions
executable file
·1779 lines (1613 loc) · 70.7 KB
/
fdevc.sh
File metadata and controls
executable file
·1779 lines (1613 loc) · 70.7 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
: "${FDEVC_PYTHON:=python3}"
: "${FDEVC_DOCKER:=docker}"
# shellcheck disable=SC2296
if [[ -n "${ZSH_VERSION}" ]]; then
SCRIPT_DIR="$(cd "$(dirname "${(%):-%x}")" && pwd)"
else
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
fi
: "${FDEVC_IMAGE:=philogicae/fdevc:latest}"
CONFIG_FILE="${SCRIPT_DIR}/.fdevc_config.json"
UTILS_PY="${SCRIPT_DIR}/utils.py"
HELP_FILE="${SCRIPT_DIR}/help.txt"
_check_dependencies() {
local missing=()
local docker_base_cmd
docker_base_cmd=$(echo "${FDEVC_DOCKER}" | awk '{print $1}')
if ! command -v "${docker_base_cmd}" &>/dev/null; then missing+=("${docker_base_cmd}"); fi
if ! command -v "${FDEVC_PYTHON}" &>/dev/null; then missing+=("${FDEVC_PYTHON}"); fi
if [[ ${#missing[@]} -gt 0 ]]; then
echo "✗ Missing required dependencies: ${missing[*]}" >&2
echo " Please install them before using dev container commands." >&2
return 1
fi
# Check if utils.py exists
if [[ ! -f "${UTILS_PY}" ]]; then
echo "✗ Missing utils.py at: ${UTILS_PY}" >&2
return 1
fi
# Check if help.txt exists
if [[ ! -f "${HELP_FILE}" ]]; then
echo "✗ Missing help.txt at: ${HELP_FILE}" >&2
return 1
fi
}
# shellcheck disable=SC2317
if ! _check_dependencies; then
if [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then
return 1
else
exit 1
fi
fi
# Color and styling helpers
_c_reset="\033[0m"
_c_bold="\033[1m"
_c_dim="\033[2m"
_c_blue="\033[94m"
_c_cyan="\033[96m"
_c_green="\033[92m"
_c_yellow="\033[93m"
_c_red="\033[91m"
_c_magenta="\033[95m"
_icon_arrow="→"
_icon_check="✓"
_icon_cross="✗"
_icon_info="ℹ"
_icon_running="●"
_icon_stopped="○"
_icon_saved="◌"
_msg_info() { echo -e "${_c_bold}${_c_cyan}${_icon_arrow}${_c_reset} ${_c_cyan}$*${_c_reset}"; }
_msg_success() { echo -e "${_c_bold}${_c_green}${_icon_check}${_c_reset} ${_c_green}$*${_c_reset}"; }
_msg_error() { echo -e "${_c_bold}${_c_red}${_icon_cross}${_c_reset} ${_c_red}$*${_c_reset}" >&2; }
_msg_warning() { echo -e "${_c_bold}${_c_yellow}⚠${_c_reset} ${_c_yellow}$*${_c_reset}"; }
_msg_detail() { echo -e " ${_c_dim}$*${_c_reset}"; }
_msg_highlight() { echo -e "${_c_bold}${_c_blue}$*${_c_reset}"; }
_msg_docker_cmd() { echo -e "${_c_magenta}$ $*${_c_reset}"; }
_format_container_title() {
local name="$1"
echo -e "${_c_bold}${_c_blue}${name}${_c_reset}"
}
_docker_exec() {
local docker_cmd="$1"
shift
local docker_parts
# Split docker command string into array so overrides like "docker -H host" work (support bash/zsh)
if [[ -n "${ZSH_VERSION-}" ]]; then
read -rA docker_parts <<< "${docker_cmd}"
else
read -r -a docker_parts <<< "${docker_cmd}"
fi
# Execute with proper error propagation
"${docker_parts[@]}" "$@"
}
_get_container_name() {
local basename_pwd
basename_pwd=$(basename "$PWD")
echo "fdevc.${basename_pwd:-root}"
}
_generate_project_label() {
${FDEVC_PYTHON} "${UTILS_PY}" random_label
}
_prepare_save_config_args() {
local no_socket="$1" socket_config="$2"
local socket_to_save="${socket_config}"
if [[ "${no_socket}" == true ]]; then
socket_to_save="false"
elif [[ -z "${socket_to_save}" ]]; then
socket_to_save="true"
fi
echo "${socket_to_save}"
}
_container_exists() {
_docker_exec "${2:-${FDEVC_DOCKER}}" ps -a --filter "name=^$1$" --format '{{.Names}}' 2>/dev/null | grep -q "^$1$"
}
_container_running() {
_docker_exec "${2:-${FDEVC_DOCKER}}" ps --filter "name=^$1$" --filter "status=running" --format '{{.Names}}' 2>/dev/null | grep -q "^$1$"
}
_container_status() {
local container_name="$1" docker_cmd="${2:-${FDEVC_DOCKER}}"
status_info=$(_docker_exec "${docker_cmd}" ps -a --filter "name=^${container_name}$" --format '{{.Status}}' 2>/dev/null)
if [[ -z "${status_info}" ]]; then
echo "missing"
elif [[ "${status_info}" == Up* ]]; then
echo "running"
else
echo "stopped"
fi
}
_container_image_name() {
_docker_exec "${2:-${FDEVC_DOCKER}}" inspect --format '{{.Config.Image}}' "$1" 2>/dev/null || true
}
_remove_image_if_exists() {
local image_ref="$1" docker_cmd="${2:-${FDEVC_DOCKER}}"
[[ -z "${image_ref}" ]] && return 0
[[ "${image_ref}" == "${FDEVC_IMAGE}" ]] && return 0
_docker_exec "${docker_cmd}" image rm "${image_ref}" >/dev/null 2>&1 || true
}
_get_container_by_index() {
local id="$1"
local docker_output
docker_output=$(_docker_exec "${FDEVC_DOCKER}" ps -a --filter "name=^fdevc\\." --format '{{.Names}}|||{{.Status}}|||{{.Image}}' 2>/dev/null)
printf '%s\n' "${docker_output}" | ${FDEVC_PYTHON} "${UTILS_PY}" resolve_index "${CONFIG_FILE}" "${id}"
}
_load_config() {
local container_name="$1"
[[ ! -f "${CONFIG_FILE}" ]] && echo "{}" && return
${FDEVC_PYTHON} "${UTILS_PY}" load_config "${CONFIG_FILE}" "${container_name}" 2>/dev/null
}
_get_config_value() {
local config="$1" key="$2" default="$3"
local value
value=$(echo "${config}" | ${FDEVC_PYTHON} "${UTILS_PY}" get_config_value "${key}" "${default}" 2>/dev/null)
echo "${value:-${default}}"
}
_get_config() {
local container_name="$1" key="$2" default="$3"
local config
config=$(_load_config "${container_name}")
_get_config_value "${config}" "${key}" "${default}"
}
_container_created_at() {
local container_name="$1" docker_cmd="${2:-${FDEVC_DOCKER}}"
_docker_exec "${docker_cmd}" inspect --format '{{.Created}}' "${container_name}" 2>/dev/null || true
}
_extract_port_from_error() {
local error_output="$1"
local patterns=("Bind for 0.0.0.0:\K[0-9]+" "0.0.0.0:\K[0-9]+" ":\K[0-9]+(?=: bind:)" "port \K[0-9]+")
for pattern in "${patterns[@]}"; do
local port
port=$(echo "${error_output}" | grep -oP "${pattern}" | head -1)
if [[ -n "${port}" ]]; then
echo "${port}"
return 0
fi
done
return 1
}
_handle_port_conflict() {
local error_output="$1" docker_cmd="${2:-${FDEVC_DOCKER}}"
# Check if it's a port conflict
if ! echo "${error_output}" | grep -qE "(Bind for 0.0.0.0|port is already allocated|address already in use)"; then
return 0
fi
local conflicting_port
if conflicting_port=$(_extract_port_from_error "${error_output}"); then
_msg_detail "Port ${conflicting_port} is already in use"
# Find which container is using this port
local blocking_container
blocking_container=$(_docker_exec "${docker_cmd}" ps -a --format '{{.Names}}|||{{.Ports}}' 2>/dev/null | grep ":${conflicting_port}->" | cut -d'|' -f1 | head -1)
if [[ -n "${blocking_container}" ]]; then
echo -e " ${_c_bold}${_c_yellow}⚠ Blocked by container: ${_c_blue}${blocking_container}${_c_reset}"
echo -e " ${_c_dim}Run: ${_c_reset}${_c_bold}fdevc stop ${blocking_container}${_c_reset}"
fi
else
_msg_detail "Port conflict detected"
fi
}
_is_workspace_mounted() {
local volumes_str="$1"
local project_path="$2"
[[ -z "${volumes_str}" ]] && return 1
local volume_list=()
if [[ -n "${ZSH_VERSION-}" ]]; then
IFS='|||' read -rA volume_list <<< "${volumes_str}"
else
IFS='|||' read -r -a volume_list <<< "${volumes_str}"
fi
for vol in "${volume_list[@]}"; do
[[ -z "${vol}" ]] && continue
local expanded_vol
expanded_vol=$(_expand_volume "${vol}" "${project_path}")
[[ "${expanded_vol}" == *:/workspace* ]] && return 0
done
return 1
}
_copy_local_script_to_container() {
local container_name="$1"
local docker_cmd="$2"
local startup_cmd="$3"
if [[ -z "${startup_cmd}" ]]; then
echo "${startup_cmd}"
return 0
fi
local script_path="${startup_cmd%% *}" # Extract first word (script path)
if [[ -f "${script_path}" || ( "${script_path}" == ./* && -f "${script_path#./}" ) ]]; then
local source_file="${script_path}"
[[ "${source_file}" == ./* ]] && source_file="${source_file#./}"
if [[ -f "${source_file}" ]]; then
{ _msg_info "Copying local script to container"; } >&2
{ _msg_detail "Source: ${source_file}"; } >&2
_docker_exec "${docker_cmd}" exec "${container_name}" mkdir -p /workspace >/dev/null 2>&1
local basename_script
basename_script="$(basename "${source_file}")"
if _docker_exec "${docker_cmd}" cp "${source_file}" "${container_name}:/workspace/${basename_script}" >/dev/null 2>&1 \
&& _docker_exec "${docker_cmd}" exec "${container_name}" chmod +x "/workspace/${basename_script}" >/dev/null 2>&1; then
{ _msg_success "Script copied to /workspace/${basename_script}"; } >&2
# Update startup command to use the copied script
echo "${startup_cmd/${script_path}/./${basename_script}}"
return 0
else
{ _msg_error "Failed to copy script to container"; } >&2
fi
fi
fi
echo "${startup_cmd}"
}
_build_attach_command() {
local startup_cmd="$1"
local persist="${2:-false}"
local run_on_reattach="${3:-false}" # true if -c was used (run every time)
if [[ "${persist}" == "true" ]]; then
# For persistent containers, use tmux for session persistence
local session_name="fdevc_persistent"
local cmd="if command -v tmux >/dev/null 2>&1; then "
cmd+=" if tmux has-session -t ${session_name} 2>/dev/null; then "
cmd+=" echo -e '\\033[1m\\033[94m→ Reattaching to persistent session\\033[0m'; "
# Run -c command even on reattach if specified
if [[ -n "${startup_cmd}" && "${run_on_reattach}" == "true" ]]; then
cmd+=" tmux send-keys -t ${session_name} 'cd /workspace; ${startup_cmd}' C-m; "
fi
cmd+=" exec tmux attach-session -t ${session_name}; "
cmd+=" else "
cmd+=" echo -e '\\033[1m\\033[94m→ Creating persistent session\\033[0m'; "
cmd+=" cd /workspace; "
if [[ -n "${startup_cmd}" ]]; then
cmd+=" ${startup_cmd}; "
fi
# Create session with a shell that has exit function to detach
cmd+=" exec tmux new-session -s ${session_name} \"bash --rcfile <(echo 'source ~/.bashrc 2>/dev/null || true; exit() { tmux detach-client; }') -i\"; "
cmd+=" fi; "
cmd+="else "
cmd+=" echo -e '\\033[1m\\033[93m⚠ Warning: tmux not found, session will not persist\\033[0m'; "
cmd+=" cd /workspace; "
if [[ -n "${startup_cmd}" ]]; then
cmd+=" ${startup_cmd}; "
fi
cmd+=" exec bash -l; "
cmd+="fi"
else
# For non-persistent containers, reattach to tmux if exists but override exit to actually exit
local session_name="fdevc_persistent"
local cmd="if command -v tmux >/dev/null 2>&1 && tmux has-session -t ${session_name} 2>/dev/null; then "
cmd+=" echo -e '\\033[1m\\033[94m→ Reattaching to session (stop on exit)\\033[0m'; "
# Override exit function to kill tmux session and then exit the shell
cmd+=" tmux send-keys -t ${session_name} 'exit() { tmux kill-session -t ${session_name}; builtin exit; }' C-m; "
cmd+=" exec tmux attach-session -t ${session_name}; "
cmd+="else "
cmd+=" cd /workspace"
if [[ -n "${startup_cmd}" ]]; then
cmd+="; ${startup_cmd}"
fi
cmd+="; exec bash -l; "
cmd+="fi"
fi
echo "${cmd}"
}
_attach_session() {
local container_name="$1"
local docker_cmd="$2"
local startup_cmd="$3"
local persist="$4"
local run_on_reattach="$5"
local detach="$6"
local has_tty="$7"
shift 7
local attach_msg_stop="$1"; shift
local attach_msg_persist="$1"; shift
local noninteractive_run_msg="$1"; shift
local noninteractive_skip_msg="$1"; shift
local noninteractive_run_level="${1:-warning}"
if [[ "${has_tty}" == true ]]; then
local attach_message="${attach_msg_stop}"
if [[ "${detach}" == true ]]; then
attach_message="${attach_msg_persist}"
fi
_msg_success "${attach_message}"
local attach_cmd
attach_cmd=$(_build_attach_command "${startup_cmd}" "${persist}" "${run_on_reattach}")
local docker_exec_args=(exec -i -t -w /workspace "${container_name}" bash -lc "${attach_cmd}")
_docker_exec "${docker_cmd}" "${docker_exec_args[@]}"
return $?
fi
if [[ -n "${startup_cmd}" ]]; then
if [[ "${noninteractive_run_level}" == "success" ]]; then
_msg_success "${noninteractive_run_msg}"
else
_msg_warning "${noninteractive_run_msg}"
fi
local noninteractive_cmd="cd /workspace; ${startup_cmd}"
_docker_exec "${docker_cmd}" exec -i -w /workspace "${container_name}" bash -lc "${noninteractive_cmd}"
return $?
fi
_msg_warning "${noninteractive_skip_msg}"
return 0
}
_normalize_volumes_for_comparison() {
local volumes="$1" container_name="$2" project_path="$3"
# Delegate to Python for consistent normalization
${FDEVC_PYTHON} "${UTILS_PY}" normalize_volumes "${volumes}" "${container_name}" "${project_path}" 2>/dev/null
}
_save_config() {
local container_name="$1"
local ports="$2"
local image="$3"
local docker_cmd="$4"
local project_path="$5"
local startup_cmd="$6"
local socket_state="$7"
local created_at="$8"
local persist="$9"
local volumes="${10}"
mkdir -p "$(dirname "${CONFIG_FILE}")"
local persist_str="false"
[[ "${persist}" == "true" || "${persist}" == "1" ]] && persist_str="true"
local collapsed_project=""
[[ -n "${project_path}" ]] && collapsed_project=$(_collapse_path "${project_path}" "")
local collapsed_startup="${startup_cmd}"
if [[ -n "${startup_cmd}" ]]; then
local first_word="${startup_cmd%% *}"
if [[ -f "${first_word}" || "${first_word}" == __*__* || "${first_word}" == ~* || "${first_word}" == /* ]]; then
collapsed_startup=$(_collapse_path "${startup_cmd}" "${project_path}")
fi
fi
local collapsed_volumes=""
if [[ -n "${volumes}" ]]; then
local volume_list=()
if [[ -n "${ZSH_VERSION-}" ]]; then
IFS='|||' read -rA volume_list <<< "${volumes}"
else
IFS='|||' read -r -a volume_list <<< "${volumes}"
fi
local collapsed_vol_list=()
for vol in "${volume_list[@]}"; do
[[ -z "${vol}" || "${vol}" == "/var/run/docker.sock:/var/run/docker.sock" ]] && continue
# shellcheck disable=SC2155
local normalized_vol=$(_normalize_volume_name "${vol}" "${container_name}" "${project_path}")
# shellcheck disable=SC2155
local collapsed_vol=$(_collapse_volume "${normalized_vol}" "${project_path}")
collapsed_vol_list+=("${collapsed_vol}")
done
# Sort volumes: mount volumes (with :) first, then excluded volumes (without :)
# Sort alphabetically within each group to match Python normalization
local mount_volumes=()
local excluded_volumes=()
for vol in "${collapsed_vol_list[@]}"; do
if [[ "${vol}" == *:* ]]; then
mount_volumes+=("${vol}")
else
excluded_volumes+=("${vol}")
fi
done
# Sort each group alphabetically (use LC_ALL=C for consistent ASCII sorting like Python)
local sorted_mount_volumes=()
local sorted_excluded_volumes=()
if [[ ${#mount_volumes[@]} -gt 0 ]]; then
if [[ -n "${ZSH_VERSION-}" ]]; then
# shellcheck disable=SC2296
sorted_mount_volumes=("${(@on)mount_volumes}")
else
# shellcheck disable=SC2207
IFS=$'\n' sorted_mount_volumes=($(LC_ALL=C sort <<<"${mount_volumes[*]}"))
IFS=' '
fi
fi
if [[ ${#excluded_volumes[@]} -gt 0 ]]; then
if [[ -n "${ZSH_VERSION-}" ]]; then
# shellcheck disable=SC2296
sorted_excluded_volumes=("${(@on)excluded_volumes}")
else
# shellcheck disable=SC2207
IFS=$'\n' sorted_excluded_volumes=($(LC_ALL=C sort <<<"${excluded_volumes[*]}"))
IFS=' '
fi
fi
local sorted_volumes=("${sorted_mount_volumes[@]}" "${sorted_excluded_volumes[@]}")
if [[ ${#sorted_volumes[@]} -gt 0 ]]; then
local first=true
for vol in "${sorted_volumes[@]}"; do
if [[ "${first}" == true ]]; then
collapsed_volumes="${vol}"
first=false
else
collapsed_volumes="${collapsed_volumes}|||${vol}"
fi
done
fi
fi
${FDEVC_PYTHON} "${UTILS_PY}" save_config "${CONFIG_FILE}" "${container_name}" "${ports}" "${image}" "${docker_cmd}" "${collapsed_project}" "${collapsed_startup}" "${socket_state}" "${created_at}" "${persist_str}" "${collapsed_volumes}" 2>/dev/null
}
_remove_config() {
local container_name="$1"
[[ ! -f "${CONFIG_FILE}" ]] && return 0
${FDEVC_PYTHON} "${UTILS_PY}" remove_config "${CONFIG_FILE}" "${container_name}" 2>/dev/null
}
_build_port_flags() {
[[ -z "$1" ]] && return 0
# Use tr to split by spaces, works in both bash and zsh
echo "$1" | tr ' ' '\n' | while read -r port; do
[[ -z "$port" ]] && continue
echo "-p"
if [[ "$port" == *:* ]]; then
echo "$port"
else
echo "${port}:${port}"
fi
done
}
_is_dockerfile() { [[ -f "$1" ]]; }
_absolute_path() {
local path="$1"
[[ "${path}" == /* ]] && { printf '%s\n' "${path}"; return; }
local dir="${path%/*}"
[[ "${dir}" == "${path}" ]] && dir=.
if cd "${dir}" 2>/dev/null; then
printf '%s/%s\n' "$(pwd)" "${path##*/}"
else
printf '%s\n' "${path}"
fi
}
_build_from_dockerfile() {
local dockerfile="$1" docker_cmd="${2:-${FDEVC_DOCKER}}" container_name="${3:-fdevc.custom}"
if [[ ! -f "${dockerfile}" ]]; then
_msg_error "Dockerfile not found: ${dockerfile}"
return 1
fi
# Cross-platform hash computation (Linux uses md5sum, macOS uses md5)
local dockerfile_hash
if command -v md5sum &>/dev/null; then
dockerfile_hash=$(md5sum "${dockerfile}" 2>/dev/null | cut -d' ' -f1 || echo "latest")
elif command -v md5 &>/dev/null; then
dockerfile_hash=$(md5 -q "${dockerfile}" 2>/dev/null || echo "latest")
else
dockerfile_hash="latest"
fi
local image_name="${container_name}:${dockerfile_hash:0:8}"
local dockerfile_dir
dockerfile_dir="$(dirname "${dockerfile}")"
if _docker_exec "${docker_cmd}" images -q "${image_name}" 2>/dev/null | grep -q .; then
_msg_info "Using cached image: ${image_name}" >&2
echo "${image_name}"
return 0
fi
_msg_info "Building image from Dockerfile: ${dockerfile}" >&2
_msg_detail "Image tag: ${image_name}" >&2
_msg_detail "Building" >&2
if _docker_exec "${docker_cmd}" build -t "${image_name}" -f "${dockerfile}" "${dockerfile_dir}"; then
_msg_success "Image built: ${image_name}" >&2
echo "${image_name}"
return 0
else
_msg_error "Failed to build image from Dockerfile"
return 1
fi
}
_resolve_image() {
local image_arg="$1"
local docker_cmd="$2" container_name="$3"
if _is_dockerfile "${image_arg}"; then
_build_from_dockerfile "${image_arg}" "${docker_cmd}" "${container_name}"
else
echo "${image_arg}"
fi
}
_resolve_container_name() {
local arg="$1"
case "${arg}" in
"") _get_container_name ;;
[0-9]*) _get_container_by_index "${arg}" ;;
*) echo "${arg}" ;;
esac
}
_get_default_image() {
[[ -f "$PWD/fdevc.Dockerfile" ]] && echo "$PWD/fdevc.Dockerfile" || echo "${FDEVC_IMAGE}"
}
_resolve_project_path() {
local project_override="$1" project_from_config="$2"
case "${project_override}" in
"__NO_PROJECT__") echo "" ;;
"") echo "${project_from_config}" ;;
*) echo "${project_override}" ;;
esac
}
_resolve_socket_value() {
local socket_override="$1" socket_from_config="$2"
if [[ -n "${socket_override}" ]]; then
echo "${socket_override}"
elif [[ "${socket_from_config}" == "__DEVCONF_NO_SOCKET__" ]]; then
echo ""
else
echo "${socket_from_config}"
fi
}
_normalize_persist_value() {
local persist_raw="$1"
local persist_lower
persist_lower=$(printf '%s' "${persist_raw}" | tr '[:upper:]' '[:lower:]')
case "${persist_lower}" in
true|"1"|yes) echo "true" ;;
*) echo "false" ;;
esac
}
_collapse_path() {
local path="$1" project_path="${2:-}"
[[ -z "${path}" ]] && return 0
local home_expanded="${HOME}"
if [[ -n "${project_path}" && "${path}" == "${project_path}"* ]]; then
echo "${path/${project_path}/__PROJECT_PATH__}"
elif [[ "${path}" == "${home_expanded}"* ]]; then
echo "${path/${home_expanded}/__HOME__}"
else
echo "${path}"
fi
}
_expand_path() {
local path="$1" project_path="${2:-}"
[[ -z "${path}" ]] && return 0
if [[ "${path}" == __PROJECT_PATH__* ]]; then
if [[ -z "${project_path}" ]]; then
echo "${path}"
else
echo "${path/__PROJECT_PATH__/${project_path}}"
fi
elif [[ "${path}" == __HOME__* ]]; then
echo "${path/__HOME__/${HOME}}"
else
echo "${path}"
fi
}
_collapse_volume() {
local volume="$1" project_path="${2:-}"
local vol_source="${volume%%:*}"
local vol_target="${volume#*:}"
if [[ "${vol_source}" == ./* ]]; then
if [[ -z "${project_path}" || "${project_path}" == "__NO_PROJECT__" ]]; then
local abs_path
abs_path=$(cd "$(dirname "${vol_source}")" 2>/dev/null && pwd)/$(basename "${vol_source}")
vol_source=$(_collapse_path "${abs_path}" "")
else
vol_source="__PROJECT_PATH__${vol_source#.}"
fi
else
vol_source=$(_collapse_path "${vol_source}" "${project_path}")
fi
if [[ "${volume}" == *:* ]]; then
if [[ "${vol_target}" == ./* ]]; then
vol_target="/workspace${vol_target#.}"
fi
echo "${vol_source}:${vol_target}"
else
echo "${vol_source}"
fi
}
_expand_volume() {
local volume="$1" project_path="${2:-}"
[[ -z "${volume}" ]] && return 0
local vol_source="${volume%%:*}"
local vol_target="${volume#*:}"
local expanded_source
expanded_source=$(_expand_path "${vol_source}" "${project_path}")
[[ "${expanded_source}" == ./* ]] && {
[[ -n "${project_path}" && "${project_path}" != "__NO_PROJECT__" ]] && expanded_source="${project_path}${expanded_source#.}" || expanded_source="${PWD}${expanded_source#.}"
}
if [[ "${volume}" == *:* ]]; then
[[ "${vol_target}" == ./* ]] && vol_target="/workspace${vol_target#.}"
echo "${expanded_source}:${vol_target}"
else
echo "${expanded_source}"
fi
}
_normalize_volume_name() {
local volume="$1" container_name="$2" project_path="${3:-}"
[[ -z "${volume}" ]] && return 0
local expanded_vol
expanded_vol=$(_expand_volume "${volume}" "${project_path}")
local vol_source="${expanded_vol%%:*}"
local vol_target="${expanded_vol#*:}"
# Only add container prefix if it's a named volume (not absolute/relative path and no placeholders)
if [[ "${vol_source}" != /* && "${vol_source}" != ./* && "${vol_source}" != *__*__* && "${expanded_vol}" == *:* && "${vol_source}" != "${container_name}."* ]]; then
vol_source="${container_name}.${vol_source}"
fi
[[ "${expanded_vol}" == *:* ]] && echo "${vol_source}:${vol_target}" || echo "${vol_source}"
}
_merge_config() {
local container_name="$1" ports_override="$2" image_override="$3" docker_cmd_override="$4" project_override="$5" socket_override="$6" volumes_override="$7"
local config
config=$(_load_config "${container_name}")
local config_present="false"
[[ -n "${config}" && "${config}" != "{}" ]] && config_present="true"
local default_image
default_image=$(_get_default_image)
local ports="${ports_override:-$(_get_config_value "${config}" "ports" "")}"
local image="${image_override:-$(_get_config_value "${config}" "image" "${default_image}")}"
local docker_cmd="${docker_cmd_override:-$(_get_config_value "${config}" "docker_cmd" "${FDEVC_DOCKER}")}"
local project_from_config
project_from_config=$(_get_config_value "${config}" "project_path" "")
local project_path
if [[ -n "${project_override}" ]]; then
project_path="${project_override}"
elif [[ -n "${project_from_config}" ]]; then
project_path=$(_expand_path "${project_from_config}" "")
elif [[ "${config_present}" == "false" ]]; then
project_path="$PWD"
else
project_path=""
fi
local socket_from_config
socket_from_config=$(_get_config_value "${config}" "socket" "__DEVCONF_NO_SOCKET__")
local socket_value
socket_value=$(_resolve_socket_value "${socket_override}" "${socket_from_config}")
local volumes_from_config
volumes_from_config=$(_get_config_value "${config}" "volumes" "")
local volumes="${volumes_override:-${volumes_from_config}}"
local startup_cmd
startup_cmd=$(_get_config_value "${config}" "startup_cmd" "")
local persist_mode_raw
persist_mode_raw=$(_get_config_value "${config}" "persist" "false")
local persist_mode_value
persist_mode_value=$(_normalize_persist_value "${persist_mode_raw}")
[[ -f "${image}" ]] && image="$(_absolute_path "${image}")"
echo "${ports}|${image}|${docker_cmd}|${project_path}|${startup_cmd}|${socket_value}|${config_present}|${persist_mode_value}|${volumes}"
}
_validate_container_name() {
local container_name="$1" context="${2:-operation}"
if [[ -z "${container_name}" ]]; then
_msg_error "No container found for ${context}. Run 'fdevc ls'."
return 1
fi
}
_stop_container() {
local container_name="$1" docker_cmd="$2"
_msg_info "Stopping $(_format_container_title "${container_name}")"
_msg_docker_cmd "${docker_cmd} stop ${container_name}"
if _docker_exec "${docker_cmd}" stop "${container_name}" >/dev/null 2>&1; then
_msg_success "Stopped"
return 0
else
_msg_error "Failed to stop $(_format_container_title "${container_name}")"
return 1
fi
}
_remove_container() {
local container_name="$1" docker_cmd="$2" force="${3:-false}"
local action="Removing"
local flags=(-v)
[[ "${force}" == "true" ]] && { action="Force removing"; flags=(-f -v); }
_msg_info "${action} $(_format_container_title "${container_name}")"
_msg_docker_cmd "${docker_cmd} rm ${flags[*]} ${container_name}"
if _docker_exec "${docker_cmd}" rm "${flags[@]}" "${container_name}" >/dev/null 2>&1; then
_msg_success "Removed"
return 0
else
_msg_error "Failed to remove $(_format_container_title "${container_name}")"
return 1
fi
}
_fdevc_start() {
local container_arg ports_override image_override docker_cmd_override detach remove_on_exit
container_arg=""
ports_override=""
image_override=""
docker_cmd_override=""
detach=false
remove_on_exit=false
local no_dir no_socket force_new force_recreate vm_mode no_v_dir
no_dir=false
no_socket=false
force_new=false
force_recreate=false
vm_mode=false
no_v_dir=false
local startup_cmd_once startup_cmd_save startup_cmd_save_flag ignore_startup_cmd
startup_cmd_once=""
startup_cmd_save=""
startup_cmd_save_flag=false
ignore_startup_cmd=false
local detach_user_set
detach_user_set=false
local copy_config_from custom_basename
copy_config_from=""
custom_basename=""
local volumes_override=()
local has_tty=true
# Check if we actually have a TTY available
[[ ! -t 0 || ! -t 1 ]] && has_tty=false
# Only force non-interactive mode if explicitly requested via environment variable
[[ "${FDEVC_FORCE_NONINTERACTIVE:-}" == "true" ]] && has_tty=false
while [[ $# -gt 0 ]]; do
case "$1" in
-p) ports_override="$2"; shift 2 ;;
-v) volumes_override+=("$2"); shift 2 ;;
-i) image_override="$2"; shift 2 ;;
--dkr) docker_cmd_override="$2"; shift 2 ;;
--tmp) remove_on_exit=true; shift ;;
-d) detach=true; detach_user_set=true; shift ;;
--no-d) detach=false; detach_user_set=true; shift ;;
--no-dir) no_dir=true; shift ;;
--no-v-dir) no_v_dir=true; shift ;;
--no-s) no_socket=true; shift ;;
-c) startup_cmd_once="$2"; shift 2 ;;
--c-s) startup_cmd_once="$2"; startup_cmd_save="$2"; startup_cmd_save_flag=true; shift 2 ;;
--no-c) ignore_startup_cmd=true; shift ;;
-f|--force) force_recreate=true; shift ;;
--new) force_new=true; shift ;;
--vm) vm_mode=true; no_dir=true; no_socket=true; shift ;;
--cp) copy_config_from="$2"; shift 2 ;;
-n) custom_basename="$2"; shift 2 ;;
--) shift; break ;;
*)
if [[ "$1" == -* ]]; then
_msg_error "Unknown option: $1"
return 1
fi
if [[ "${force_new}" == true ]] || [[ "${vm_mode}" == true ]]; then
_msg_error "Unknown argument: $1"
return 1
fi
container_arg="$1"
shift
;;
esac
done
if [[ "${remove_on_exit}" == true && "${detach}" == true ]]; then
_msg_info "--tmp overrides -d; container stops and is removed."
detach=false
fi
if [[ "${ignore_startup_cmd}" == true ]]; then
startup_cmd_once=""
startup_cmd_save=""
startup_cmd_save_flag=false
fi
# Resolve --cp (copy config from) if provided
local copy_config_source=""
if [[ -n "${copy_config_from}" ]]; then
copy_config_source="$(_resolve_container_name "${copy_config_from}")"
if [[ -z "${copy_config_source}" ]]; then
_msg_error "Config source not found: ${copy_config_from}. Run 'fdevc ls'."
return 1
fi
# Verify config exists
local source_config
source_config=$(_load_config "${copy_config_source}")
if [[ -z "${source_config}" || "${source_config}" == "{}" ]]; then
_msg_error "No config found for: ${copy_config_source}"
return 1
fi
_msg_info "Copying config from: ${copy_config_source}"
fi
local overrides_supplied=false
[[ -n "${ports_override}" || -n "${image_override}" || -n "${docker_cmd_override}" || ${#volumes_override[@]} -gt 0 ]] && overrides_supplied=true
local container_running=false
local container_was_running=false
local image_to_remove_after_create=""
# Determine container name based on mode
local container_name
local config_target_name
local is_vm_copy=false
# Check if copying from a VM container to preserve VM mode
if [[ -n "${copy_config_from}" ]]; then
local source_name
source_name="$(_resolve_container_name "${copy_config_from}")"
if [[ "${source_name}" == fdevc.vm.* ]]; then
is_vm_copy=true
fi
fi
if [[ -n "${custom_basename}" ]]; then
# Custom basename provided with -n
# Determine the final container name first
local proposed_name
if [[ "${vm_mode}" == true ]] || [[ "${is_vm_copy}" == true ]]; then
proposed_name="fdevc.vm.${custom_basename}"
else
proposed_name="fdevc.${custom_basename}"
fi
# Check for name collision (exact match or with .tmp suffix)
if [[ "${force_recreate}" != true ]]; then
local collision_check
collision_check=$(_docker_exec "${FDEVC_DOCKER}" ps -a --filter "name=^${proposed_name}$" --filter "name=^${proposed_name}.tmp$" --format '{{.Names}}' 2>/dev/null | head -1)
if [[ -z "${collision_check}" && -f "${CONFIG_FILE}" ]]; then
# Also check saved configs
collision_check=$(${FDEVC_PYTHON} -c "import json; data = json.load(open('${CONFIG_FILE}')); print('${proposed_name}' if '${proposed_name}' in data or '${proposed_name}.tmp' in data else '')" 2>/dev/null)
fi
if [[ -n "${collision_check}" ]]; then
_msg_error "Name collision: container '${collision_check}' already exists"
_msg_detail "Choose a different basename with -n, use --force to replace, or remove the existing container"
return 1
fi
else
# Force mode: remove any existing container with this name
local existing_container
existing_container=$(_docker_exec "${FDEVC_DOCKER}" ps -a --filter "name=^${proposed_name}$" --filter "name=^${proposed_name}.tmp$" --format '{{.Names}}' 2>/dev/null | head -1)
if [[ -n "${existing_container}" ]]; then
_msg_info "Force mode: removing existing container '${existing_container}'"
_docker_exec "${FDEVC_DOCKER}" rm -f "${existing_container}" >/dev/null 2>&1
_remove_config "${existing_container}"
fi
fi
container_name="${proposed_name}"
config_target_name="${container_name}"
elif [[ "${vm_mode}" == true ]]; then
# VM mode: generate special name fdevc.vm.<random-name>
container_name="fdevc.vm.$(_generate_project_label)"
config_target_name="${container_name}"
elif [[ "${force_new}" == true ]]; then
container_name="fdevc.$(basename "$PWD").$(date +%s)"
config_target_name="${container_name}"
elif [[ "${no_dir}" == true && -z "${container_arg}" ]]; then
container_name="fdevc.$(_generate_project_label)"
config_target_name="${container_name}"
else
container_name="$(_resolve_container_name "${container_arg}")"
_validate_container_name "${container_name}" "id ${container_arg}" || return 1
config_target_name="${container_name}"
fi
# Prefer base configuration when available (unless tmp requested or --cp used)
if [[ "${force_new}" != true && "${remove_on_exit}" != true && -z "${copy_config_source}" ]]; then
local base_config_name="${config_target_name}"
base_config_name="${base_config_name%.tmp}"
if [[ "${base_config_name}" != "${config_target_name}" ]]; then
local base_config_json
base_config_json="$(_load_config "${base_config_name}")"
if [[ -n "${base_config_json}" && "${base_config_json}" != "{}" ]]; then
config_target_name="${base_config_name}"
container_name="${base_config_name}"
fi
fi
fi
local base_container_name="${container_name}"
base_container_name="${base_container_name%.tmp}"
local socket_override_arg=""
[[ "${no_socket}" == true ]] && socket_override_arg="false"
local merge_project_path=""
if [[ "${no_dir}" == true ]]; then
merge_project_path="__NO_PROJECT__"
elif [[ "${vm_mode}" == true ]] || [[ "${is_vm_copy}" == true ]]; then
merge_project_path="__NO_PROJECT__"
if [[ "${is_vm_copy}" == true && "${no_socket}" != true && -z "${socket_override_arg}" ]]; then
no_socket=true
socket_override_arg="false"
fi
elif [[ "${force_new}" == true ]]; then
merge_project_path="$PWD"
elif [[ -n "${copy_config_source}" ]]; then
local source_project
source_project=$(_get_config "${copy_config_source}" "project_path")
if [[ -z "${source_project}" ]]; then
merge_project_path="__NO_PROJECT__"
fi
fi
local config_source="${copy_config_source:-${config_target_name}}"
local volumes_override_str=""
if [[ ${#volumes_override[@]} -gt 0 ]]; then
local first=true
for vol in "${volumes_override[@]}"; do
if [[ "${first}" == true ]]; then
volumes_override_str="${vol}"
first=false
else
volumes_override_str="${volumes_override_str}|||${vol}"
fi
done
fi
IFS='|' read -r ports image_config docker_cmd project_path startup_cmd_config socket_config config_present persist_mode_config volumes_config <<< "$(_merge_config "${config_source}" "${ports_override}" "${image_override}" "${docker_cmd_override}" "${merge_project_path}" "${socket_override_arg}" "${volumes_override_str}")"
local startup_cmd_expanded="${startup_cmd_config}"
if [[ -n "${startup_cmd_expanded}" ]]; then
startup_cmd_expanded=$(_expand_path "${startup_cmd_expanded}" "${project_path}")
fi
local startup_cmd_session="${startup_cmd_once:-${startup_cmd_expanded}}"
local run_on_reattach=false
[[ -n "${startup_cmd_once}" ]] && run_on_reattach=true
local startup_cmd_to_save="${startup_cmd_config}"
if [[ "${startup_cmd_save_flag}" == true ]]; then
if [[ -f "${startup_cmd_save%% *}" ]]; then
startup_cmd_to_save=$(_collapse_path "${startup_cmd_save}" "${project_path}")
else
startup_cmd_to_save="${startup_cmd_save}"
fi
fi
if [[ "${ignore_startup_cmd}" == true ]]; then
startup_cmd_session=""
fi
# If user explicitly set detach mode, mirror it into persist setting