From ec1ee32945f91e0392841556f89dbc5ef04fb3d8 Mon Sep 17 00:00:00 2001 From: Serge Khorun <104387024+sergekh2@users.noreply.github.com> Date: Mon, 1 Jul 2024 09:23:55 -0700 Subject: [PATCH] Run core/fmt.sh from VSCode on save (#323) --- .vscode/settings.json | 7 +++++-- core/fmt.sh | 23 +++++++++++++++++++---- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 6e81c0c6f..aba3c6c91 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -25,7 +25,7 @@ "[makefile]": { "editor.renderWhitespace": "all" }, - "go.formatTool": "gofumpt", + "go.formatTool": "custom", "go.testFlags": [ "-v", "-tags", @@ -36,5 +36,8 @@ "tailwindCSS.experimental.classRegex": [ ["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"], ["cn\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"] - ] + ], + "go.alternateTools": { + "customFormatter": "${workspaceFolder}/core/fmt.sh", + } } diff --git a/core/fmt.sh b/core/fmt.sh index 212fd9c27..e63a152a5 100755 --- a/core/fmt.sh +++ b/core/fmt.sh @@ -2,14 +2,29 @@ set -euo pipefail cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" -# In addition to running gofumpt this script also limits line length to 120 characters -# There is no good way to run golines for single file from .vscode -# due to this bug: https://github.com/golang/vscode-go/issues/2582 +if ! command -v "gofumpt" >/dev/null 2>&1; then + go install mvdan.cc/gofumpt@latest >/dev/null 2>&1 +fi +if ! command -v "golines" >/dev/null 2>&1; then + go install github.com/segmentio/golines@latest >/dev/null 2>&1 +fi + +# Read all lines from stdin into the variable 'input' +INPUT=$(cat) + +FMT_CMD="golines --base-formatter=gofumpt --max-len=120" + +# If arguments are empty and stdin is not empty, run formatter on stdin to stdout +if [[ -z "$*" && -n "${INPUT}" ]] +then + echo "${INPUT}" | ${FMT_CMD} + exit 0 +fi # Set ARGS to -w if not set, otherwie to cmd line args ARGS=${@:-"-w"} -OUTPUT=$(go list -f '{{.Dir}}' ./... | grep -v /contracts | grep -v /protocol | grep -v /mocks | xargs golines --base-formatter=gofumpt --max-len=120 $ARGS) +OUTPUT=$(go list -f '{{.Dir}}' ./... | grep -v /contracts | grep -v /protocol | grep -v /mocks | xargs ${FMT_CMD} $ARGS) if [ -n "$OUTPUT" ] then echo "$OUTPUT"