Page Menu
Home
DevCentral
Search
Configure Global Search
Log In
Files
F42734236
D4140.id10862.diff
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
2 KB
Referenced Files
None
Subscribers
None
D4140.id10862.diff
View Options
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
Details
Attached
Mime Type
text/plain
Expires
Mon, Aug 10, 02:28 (18 h, 39 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3980058
Default Alt Text
D4140.id10862.diff (2 KB)
Attached To
Mode
D4140: Format .tf files automatically
Attached
Detach File
Event Timeline
Log In to Comment