From 6fe70c75e44b83efa231cba7c5bf614c62ce0541 Mon Sep 17 00:00:00 2001
From: Jerry Lee <oldratlee@gmail.com>
Date: Thu, 10 Feb 2022 16:27:07 +0800
Subject: [PATCH] feat: add `gen_source_guard`

---
 bin/.editorconfig    |  2 ++
 bin/gen_source_guard | 36 ++++++++++++++++++++++++++++++++++++
 2 files changed, 38 insertions(+)
 create mode 100644 bin/.editorconfig
 create mode 100755 bin/gen_source_guard

diff --git a/bin/.editorconfig b/bin/.editorconfig
new file mode 100644
index 0000000..930c491
--- /dev/null
+++ b/bin/.editorconfig
@@ -0,0 +1,2 @@
+[*]
+indent_size = 4
diff --git a/bin/gen_source_guard b/bin/gen_source_guard
new file mode 100755
index 0000000..6b7928c
--- /dev/null
+++ b/bin/gen_source_guard
@@ -0,0 +1,36 @@
+#!/bin/bash
+#
+# gen a source guard code snippet for a shell lib file.
+#
+set -eEuo pipefail
+
+p_uuid_gen() {
+    if command -v uuidgen &>/dev/null; then
+        uuidgen
+    else
+        python3 -c 'import uuid; print(str(uuid.uuid4()).upper())'
+    fi
+}
+
+new_source_guard_var_name() {
+    local uuid
+    uuid=$(p_uuid_gen)
+    uuid=${uuid//-/_}
+
+    echo "__source_guard_$uuid"
+}
+
+new_source_guard() {
+    local source_guard_var_name
+    source_guard_var_name="$(new_source_guard_var_name)"
+
+    cat <<EOF
+#_ source guard start _#
+[ -z "\${$source_guard_var_name:+dummy}" ] || return 0
+$source_guard_var_name="\$(dirname "\$(readlink -f "\${BASH_SOURCE[0]}")")"
+readonly $source_guard_var_name
+#_ source guard end _#
+EOF
+}
+
+new_source_guard