Page MenuHomeDevCentral

D4140.diff
No OneTemporary

D4140.diff

diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml
--- a/.pre-commit-hooks.yaml
+++ b/.pre-commit-hooks.yaml
@@ -4,3 +4,11 @@
entry: pre-commit-hooks/shellcheck.sh
language: script
exclude: \.jinja$
+
+- id: tf-format
+ name: TfFormat
+ description: Terraform / OpenTofu .tf format
+ entry: pre-commit-hooks/tf-format.sh
+ language: script
+ types_or: [terraform, hcl]
+ pass_filenames: true
diff --git a/pre-commit-hooks/README.md b/pre-commit-hooks/README.md
--- a/pre-commit-hooks/README.md
+++ b/pre-commit-hooks/README.md
@@ -17,3 +17,16 @@
- id: shellcheck
args: ["--enable require-variable-braces,deprecate-which"]
```
+
+### TfFormat
+
+Allow to format automatically .tf files detecting if OpenTofu or Terraform
+is installed and using the first one found.
+
+```yaml
+repos:
+ - repo: https://github.com/nasqueron/codestyle
+ rev: 0.2.0
+ hooks:
+ - id: tf-format
+```
diff --git a/pre-commit-hooks/tf-format.sh b/pre-commit-hooks/tf-format.sh
new file mode 100755
--- /dev/null
+++ b/pre-commit-hooks/tf-format.sh
@@ -0,0 +1,41 @@
+#!/bin/sh
+
+# -------------------------------------------------------------
+# pre-commit :: hooks :: tf-format
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+# Project: Nasqueron
+# Description: Call tofu fmt or terraform fmt as pre-commit hook
+# License: BSD-2-Clause
+# -------------------------------------------------------------
+
+# -------------------------------------------------------------
+# Determine which command to use
+#
+# Prefer OpenTofu, fallback to Terraform
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+TF_CMD="tofu"
+if ! command -v tofu >/dev/null 2>&1; then
+ if command -v terraform >/dev/null 2>&1; then
+ TF_CMD="terraform"
+ else
+ echo "Error: Neither 'tofu' nor 'terraform' found in PATH." >&2
+ exit 1
+ fi
+fi
+
+# -------------------------------------------------------------
+# Check
+#
+# :: 1. run in check mode to print a diff
+# :: 2. actual run in write mode, when needed
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+$TF_CMD fmt -check -diff "$@"
+EXIT_CODE=$?
+
+if [ $EXIT_CODE -ne 0 ]; then
+ $TF_CMD fmt -write=true "$@"
+fi
+
+exit $EXIT_CODE

File Metadata

Mime Type
text/plain
Expires
Sun, Aug 9, 09:48 (7 h, 21 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3980058
Default Alt Text
D4140.diff (2 KB)

Event Timeline