aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/format.sh
blob: b6a875e8902476bb7c12d7aedb89b031a354f911 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env bash
set -eou pipefail

source "$(dirname "${BASH_SOURCE[0]}")/lib/log.sh"

usage() {
  echo "Usage: $0 [FORMATTER]"
  echo ""
  echo "Run code formatters"
  echo ""
  echo "Arguments:"
  echo "  FORMATTER    Formatter to run (gofmt, shfmt)"
  echo "               If not specified, runs all formatters"
  echo ""
  echo "Examples:"
  echo "  $0 gofmt      # Run only gofmt"
  echo "  $0            # Run all formatters"
}

main() {
  local formatter="${1:-}"
  if [[ $formatter == "-h" || $formatter == "--help" ]]; then
    usage
    exit 0
  fi

  if [[ -n "$formatter" ]]; then
    case "$formatter" in
      gofmt)
        format_gofmt
        ;;
      shfmt)
        format_shfmt
        ;;
      *)
        log_error "Invalid formatter: $formatter"
        log_newline
        usage
        exit 1
        ;;
    esac
  else
    log_header "Running all formatters"
    local failed_formatters=()

    if ! format_gofmt; then
      failed_formatters+=("gofmt")
    fi

    if ! format_shfmt; then
      failed_formatters+=("shfmt")
    fi

    if [[ ${#failed_formatters[@]} -eq 0 ]]; then
      log_success "All formatters completed!"
    else
      log_error "Failed formatters: ${failed_formatters[*]}"
      exit 1
    fi
  fi
}

format_gofmt() {
  log_info "Running gofmt..."
  local unformatted
  unformatted=$(gofmt -l .)
  if [[ -n "$unformatted" ]]; then
    log_step "Formatting files with gofmt..."
    gofmt -w .
    log_success "gofmt completed"
    return 0
  fi
  log_success "All Go files already formatted"
  return 0
}

format_shfmt() {
  log_info "Running shfmt..."
  if ! command -v shfmt &>/dev/null; then
    log_error "shfmt is not installed"
    return 1
  fi

  local unformatted
  unformatted=$(shfmt -l scripts/)
  if [[ -n "$unformatted" ]]; then
    log_step "Formatting files with shfmt..."
    shfmt -w scripts/
    log_success "shfmt completed"
    return 0
  fi
  log_success "All shell scripts already formatted"
  return 0
}

main "$@"