Skip to content

Instantly share code, notes, and snippets.

@Jamesits
Last active March 11, 2023 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jamesits/46862ff152b2c0e1414af66226632347 to your computer and use it in GitHub Desktop.
Save Jamesits/46862ff152b2c0e1414af66226632347 to your computer and use it in GitHub Desktop.
Convert a text file to a patch file
#!/usr/bin/env bash
# convert a text file to a patch file
set -Eeuo pipefail
# usage: file2patch "source/file" "relative/destination/path" "patch/file"
file2patch() {
local SRCFILE="$1"
local PATCHPATH="$2"
local OUTFILE="$3"
local FILEMODE="$(stat -c '%a' "${SRCFILE}")"
local LINECOUNT="$(wc -l "${SRCFILE}" | cut -d' ' -f1)"
(
printf "diff --git a/%s b/%s\n" "${PATCHPATH}" "${PATCHPATH}"
printf "new file mode 100%s\n" "${FILEMODE}"
printf "index 00000000..11451419\n"
printf "%s\n" "--- /dev/null" # "printf --" will cause parsing problems
printf "+++ b/%s\n" "${PATCHPATH}"
printf "@@ -0,0 +1,%d @@\n" "${LINECOUNT}"
cat "${SRCFILE}" | sed -e 's/^/+/g'
) > "${OUTFILE}"
}
file2patch "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment