From e22fd25c2028e1a3c030829de02954717570a030 Mon Sep 17 00:00:00 2001 From: Patrick Spek Date: Sun, 26 Mar 2023 12:08:00 +0200 Subject: Redo dir_hash with new file_hash functionality --- CHANGELOG.md | 4 ++++ lib/util.bash | 35 ++++++++++++++++++++++++++++++++--- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0af0434..0e752aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 GNU+Linux distributions. - The `$BASHTARD_PLATFORM` variable now contains an additional entry, `init`, to allow for handling different init systems on GNU+Linux in a cleaner fashion. +- A `file_hash` utility function has been added. It currently uses `md5`, but is + written in such a fashion that this can easily be updated for the future. Its + intent is to encapsulate differences between naming and usage of hashing + utilities found on different systems. - A `dir_hash` utility function has been added, which will give you a hash based on the file contents of a directory. This function will find files recursively, calculate a hash for each of them, and then calculate a hash diff --git a/lib/util.bash b/lib/util.bash index c36b576..fac492c 100644 --- a/lib/util.bash +++ b/lib/util.bash @@ -63,9 +63,19 @@ die() { # in a directory. It can be used to check whether contents changed after # templating files in a given directory. dir_hash() { - find "$1" -type f -exec sha1sum {} \; \ - | sha1sum \ - | awk '{ print $1 }' + local path + + path="$1" ; shift + + for entry in "$path"/* + do + if [[ -d "$entry" ]] + then + dir_hash "$entry" + fi + + file_hash "$entry" + done | file_hash - } # Fetch a file from an URL. Using this function introduces a dependency on curl. @@ -108,6 +118,25 @@ fetch_http_wget() { wget --quiet --output-document "$2" "$1" } +# Hash a given file. This is a convenience function to work around different +# systems calling their file hashing programs differently, and generating +# different output. This function only expects 1 file as argument, and only +# outputs the hash of this particular file. +file_hash() { + file_hash_md5 "$@" +} + +file_hash_md5() { + local file + + file="$1" ; shift + + case "${BASHTARD_PLATFORM[key]}" in + freebsd) md5 "$file" | awk '{ print $NF }' ;; + linux-*) md5sum "$file" | awk '{ print $1 }' ;; + esac +} + # A very simple means of templating a file, using sed and awk. The template # file is assumed to exist within the share directory of the current playbook. # Variables are passed as key=value pairs to this function. Inside the -- cgit v1.1