Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions .clang-format
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,24 @@ UseTab: Never
ColumnLimit: 105
BreakBeforeBraces: Attach
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
PointerAlignment: Left
DerivePointerAlignment: false
AlignAfterOpenBracket: AlwaysBreak
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignOperands: true
AlignConsecutiveAssignments: None
AlignConsecutiveDeclarations: None
AlignOperands: Align
AlignTrailingComments: true
SortIncludes: true
ReflowComments: true
SortIncludes:
Enabled: true
ReflowComments: Always
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInAngles: Never
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: true
SpacesInParentheses: false
Expand Down
141 changes: 141 additions & 0 deletions .githooks/pre-push
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
#!/usr/bin/env bash
set -e

BOLD="\033[1m"
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
RED="\033[0;31m"
CYAN="\033[0;36m"
DIM="\033[2m"
RESET="\033[0m"

PROJECT_DIR=$(git rev-parse --show-toplevel)

# Locate clang-format (needed to decide whether format:fix can run).
CLANG_FORMAT=""
for candidate in clang-format clang-format-18 clang-format-17 clang-format-16 \
clang-format-15 clang-format-14; do
if command -v "$candidate" >/dev/null 2>&1; then
CLANG_FORMAT="$candidate"
break
fi
done

if [[ -z "$CLANG_FORMAT" ]]; then
printf "${YELLOW}⚡ pre-push:${RESET} clang-format not found; running tests only.\n" >&2
SKIP_FORMAT=1
else
SKIP_FORMAT=0
fi

FORMAT_SCRIPT="$PROJECT_DIR/scripts/check_format.sh"

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT

names=()
logs=()
pids=()

# run_check <name> [command...]: runs the given command in the background,
# capturing its exit status and output for the spinner/report phase.
run_check() {
local name="$1"
shift
local log="$tmpdir/$name.log"
names+=("$name")
logs+=("$log")
printf " ${CYAN}·${RESET} ${name}\n"
(set +e; "$@" >"$log" 2>&1; echo $? >"$tmpdir/$name.status") &
pids+=($!)
}

printf "${CYAN}${BOLD}🚀 pre-push: running checks in parallel...${RESET}\n"

# Format + auto-fix: delegate to scripts/check_format.sh --fix.
# It exits 0 even when it reformats files, so we must check the working tree
# afterwards. If it changed any .cpp/.h files, abort the push so the user can
# review and commit the formatting before pushing again.
if [ "$SKIP_FORMAT" -eq 0 ]; then
run_check "format:fix" bash "$FORMAT_SCRIPT" --fix
fi

# Test check: the host-side test suite (C++ + Node.js).
run_check "test" bash "$PROJECT_DIR/test/run_tests.sh"

n=${#names[@]}
spinners=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
tick=0

# Rewrite bullet lines in-place: spinner while running, ✔/✘ on completion.
while true; do
spinner="${spinners[$((tick % ${#spinners[@]}))]}"
all_done=1
for i in "${!names[@]}"; do
name="${names[$i]}"
lines_up=$((n - i))
[ -f "$tmpdir/$name.reported" ] && continue
printf "\033[${lines_up}A\r\033[2K"
if [ -f "$tmpdir/$name.status" ]; then
status=$(cat "$tmpdir/$name.status")
touch "$tmpdir/$name.reported"
if [ "$status" -eq 0 ]; then
printf " ${GREEN}${BOLD}✔${RESET} ${name}"
else
printf " ${RED}${BOLD}✘${RESET} ${name}"
fi
else
all_done=0
printf " ${CYAN}${spinner}${RESET} ${name}"
fi
printf "\033[${lines_up}B\r"
done
[ "$all_done" -eq 1 ] && break
sleep 0.1
tick=$((tick + 1))
done

# After all checks finish, determine whether format:fix modified any files.
# clang-format -i modifies files on disk; git diff HEAD shows what changed.
reformatted=""
if [ "$SKIP_FORMAT" -eq 0 ]; then
reformatted=$(git -C "$PROJECT_DIR" diff --name-only HEAD -- src/ | grep -E '\.(cpp|h)$' || true)
fi

# Print output for failed checks below the bullet list.
failed=0
for i in "${!names[@]}"; do
name="${names[$i]}"
status=$(cat "$tmpdir/$name.status")
if [ "$status" -ne 0 ]; then
failed=1
printf "\n${RED}${BOLD}✘ ${name}${RESET}\n"
printf "${DIM}"
sed 's/^/ /' "$tmpdir/$name.log"
printf "${RESET}"
fi
done

# If format:fix reformatted files, treat that as a failure (abort push).
if [ -n "$reformatted" ]; then
failed=1
printf "\n${RED}${BOLD}✘ format:fix${RESET}\n"
printf "${DIM} clang-format reformatted the following files:${RESET}\n"
for f in $reformatted; do
printf " ${CYAN}·${RESET} $f\n"
done
printf "${DIM} Commit the formatting changes, then push again.${RESET}\n"
fi

for pid in "${pids[@]}"; do
wait "$pid" 2>/dev/null || true
done

printf "\n"
if [ $failed -eq 0 ]; then
printf "${GREEN}${BOLD}✅ pre-push: all checks passed.${RESET}\n"
else
printf "${RED}${BOLD}❌ pre-push: push aborted.${RESET}\n"
fi

exit $failed
39 changes: 39 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,45 @@ My computer is running linux, but you can use Windows or MacOS as well, there ar
- You should be able to see the debug output in the VS Code terminal
- If something goes wrong and you are stuck, feel free to start a [discussion](https://github.com/ktomy/nightscout-clock/discussions)

### Code formatting

C++ source files under `src/` are formatted with `clang-format` using the project's
`.clang-format` config (Google style, 4-space indent, attached braces, left-aligned
pointers, sorted includes, 105-column limit).

#### Check formatting

```sh
./scripts/check_format.sh
```

Exits non-zero if any file needs formatting. Pass file or directory arguments to check
a subset, for example `./scripts/check_format.sh src/main.cpp`.

#### Apply formatting

```sh
./scripts/check_format.sh --fix
```

Reformats all `src/*.{cpp,h}` files in place. You can also target specific paths.

#### Pre-push hook

The repository includes a `pre-push` git hook under `.githooks/` that runs
`check_format.sh --fix` and the host-side test suite (`test/run_tests.sh`) before every
push. If the hook reformats any files, or if any test fails, the push is aborted so you
can review and commit the changes first.

To enable it:

```sh
git config core.hooksPath .githooks
```

The hook is tracked in git under `.githooks/`, so it is shared with everyone who clones
the repository. You only need to run `core.hooksPath` once per clone.

### Adding a clock face

Register the face instance, label, and a unique, stable snake_case ID (for example,
Expand Down
108 changes: 108 additions & 0 deletions scripts/check_format.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
PROJECT_DIR=$(dirname -- "$SCRIPT_DIR")
CLANG_FORMAT_FILE="$PROJECT_DIR/.clang-format"

APPLY=false
TARGETS=()

usage() {
echo "Usage: $0 [--fix] [--help] [path ...]"
echo " default Check C++ source formatting against .clang-format"
echo " --fix Apply formatting in place (requires clang-format)"
echo " path Files or directories to check (default: src/)"
}

while (($#)); do
case $1 in
--fix | -f)
APPLY=true
;;
-h | --help)
usage
exit
;;
*)
TARGETS+=("$1")
;;
esac
shift
done

# Locate a clang-format binary.
CLANG_FORMAT=""
for candidate in clang-format clang-format-18 clang-format-17 clang-format-16 \
clang-format-15 clang-format-14; do
if command -v "$candidate" >/dev/null 2>&1; then
CLANG_FORMAT="$candidate"
break
fi
done

if [[ -z "$CLANG_FORMAT" ]]; then
echo "ERROR: clang-format not found." >&2
echo "Install it, for example:" >&2
echo " macOS: brew install clang-format" >&2
echo " Linux: apt install clang-format" >&2
echo "Then re-run $0." >&2
exit 1
fi

if [[ ! -f "$CLANG_FORMAT_FILE" ]]; then
echo "ERROR: .clang-format not found at $CLANG_FORMAT_FILE" >&2
exit 1
fi

# Collect the C++ source files to check or format.
if (( ${#TARGETS[@]} == 0 )); then
TARGETS=("$PROJECT_DIR/src")
fi

FILES=()
for target in "${TARGETS[@]}"; do
if [[ -f "$target" ]]; then
FILES+=("$target")
elif [[ -d "$target" ]]; then
while IFS= read -r -d '' file; do
FILES+=("$file")
done < <(find "$target" -type f \( -name '*.cpp' -o -name '*.h' \) -print0 | sort -z)
else
echo "ERROR: not a file or directory: $target" >&2
exit 1
fi
done

if (( ${#FILES[@]} == 0 )); then
echo "No C++ source files found."
exit 0
fi

run_clang_format() {
"$CLANG_FORMAT" --style=file "$@"
}

if [[ "$APPLY" == true ]]; then
echo "Applying clang-format to ${#FILES[@]} file(s)..."
run_clang_format -i "${FILES[@]+"${FILES[@]}"}"
echo "Done."
else
echo "Checking formatting of ${#FILES[@]} file(s) with $CLANG_FORMAT..."
NEEDS_FORMAT=()
for file in "${FILES[@]+"${FILES[@]}"}"; do
if ! run_clang_format --dry-run --Werror "$file" >/dev/null 2>&1; then
NEEDS_FORMAT+=("$file")
fi
done
if (( ${#NEEDS_FORMAT[@]} > 0 )); then
echo "Formatting issues found in ${#NEEDS_FORMAT[@]} file(s):" >&2
for file in "${NEEDS_FORMAT[@]+"${NEEDS_FORMAT[@]}"}"; do
echo " $file" >&2
done
echo "Run '$0 --fix' to apply formatting." >&2
exit 1
fi
echo "All files are correctly formatted."
fi
Loading
Loading