Skip to content

Instantly share code, notes, and snippets.

@yarikoptic
Last active May 23, 2024 16:33
Show Gist options
  • Save yarikoptic/5da985d200fa1a2185a702ce9913d4d4 to your computer and use it in GitHub Desktop.
Save yarikoptic/5da985d200fa1a2185a702ce9913d4d4 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# A little script that given a path would produce a sequence
# of bash (didn't check with posix shell)
# 'echo' and 'mkdir' commands to replicate content of that path.
# Initial motivation -- provide commands to embed into Container file.
set -eu
# Check if the path is provided
if [ -z "$1" ]; then
echo "Usage: $0 <path> [<target_prefix>]"
exit 1
fi
# Get the absolute path
SOURCE_PATH=$(realpath "$1")
SOURCE_DIR=$(dirname "$SOURCE_PATH")
TARGET_PREFIX=""
if [ "$#" -ge 2 ]; then
TARGET_PREFIX="$2"
if [ -d "$SOURCE_PATH" ] ; then
# if we did point to folder and provided alternative prefix
# take of entire folder as SOURCE_DIR
SOURCE_DIR="$SOURCE_PATH"
fi
fi
# Function to process a single file
process_file() {
local file=$1
if file "$file" | grep -q "text"; then
relative_path=$(realpath --relative-to="${SOURCE_DIR}" "$file")
file_content=$(cat "$file" | sed -e 's,\([$!\\]\),\\\1,g')
# Print echo command to replicate the file content
echo "echo \"${file_content//\"/\\\"}\" > \"$TARGET_PREFIX$relative_path\""
#echo "cat << 'EOL' > \"$TARGET_PREFIX$relative_path\""
#cat "$file"
#echo "EOL"
else
echo "Error: $file is not a text file."
exit 1
fi
}
# Function to traverse directory and print commands
traverse_directory() {
local current_path=$1
# Iterate over the items in the current directory
for item in "$current_path"/*; do
if [ -d "$item" ]; then
# If item is a directory, print mkdir command
relative_path=$(realpath --relative-to="$SOURCE_DIR" "$item")
echo "mkdir -p \"$TARGET_PREFIX$relative_path\""
# Recursively traverse the directory
traverse_directory "$item"
elif [ -f "$item" ]; then
# Process the file
process_file "$item"
else
# If item is neither a directory nor a file, exit with error
echo "Error: $item is not a directory or a file."
exit 1
fi
done
}
# Check if the target path is a directory or a file
if [ -d "$SOURCE_PATH" ]; then
# If it's a directory, start traversing
traverse_directory "$SOURCE_PATH"
elif [ -f "$SOURCE_PATH" ]; then
# If it's a file, process the file
process_file "$SOURCE_PATH"
else
echo "Error: $SOURCE_PATH is not a directory or a file."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment