dx/dxkit/modules/fs.module.sh

83 lines
1.6 KiB
Bash

#!/usr/bin/env bash
function fs::write_file() {
local src="$1"
local dest="$2"
if platform::is_windows; then
# Windows: no sudo, just overwrite (assumes elevated shell if needed)
mv "$src" "$dest"
return $?
fi
# macOS / Linux
sudo tee "$dest" >/dev/null < "$src"
}
function fs::sed_inplace() {
local use_sudo=false
local suffix=""
local expr
local file
# Detect sudo flag
if [[ "$1" == "--sudo" ]]; then
use_sudo=true
shift
fi
# Detect suffix
if [[ "$1" == .* ]]; then
suffix="$1"
shift
fi
expr="$1"
file="$2"
local SUDO=""
if $use_sudo && ! platform::is_windows; then
SUDO="sudo"
fi
if platform::is_macos; then
if [[ -z "$suffix" ]]; then
$SUDO sed -i '' "$expr" "$file"
else
$SUDO sed -i "$suffix" "$expr" "$file"
fi
else
if [[ -z "$suffix" ]]; then
$SUDO sed -i "$expr" "$file"
else
$SUDO sed -i"$suffix" "$expr" "$file"
fi
fi
}
function fs::replace_block() {
local file="$1"
local start_marker="$2"
local end_marker="$3"
local content="$4"
local tmp
tmp="$(mktemp)"
# Remove existing block safely (no regex, no sed)
awk -v start="$start_marker" -v end="$end_marker" '
$0 == start {skip=1; next}
$0 == end {skip=0; next}
!skip
' "$file" > "$tmp"
# Only add leading newline if file has content and doesn't already end with one
if [[ -s "$tmp" ]]; then
local last_char
last_char="$(tail -c1 "$tmp")"
[[ "$last_char" != "" ]] && printf "\n" >> "$tmp"
fi
printf "%s\n" "$content" >> "$tmp"
echo "$tmp"
}