Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a file formatting script for pre-commit #3383

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
52 changes: 52 additions & 0 deletions .github/workflows/file_format.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

if len(sys.argv) < 2:
print("Invalid usage of file_format.py, it should be called with a path to one or multiple files.")
sys.exit(1)

BOM = b"\xef\xbb\xbf"

changed = []
invalid = []

for file in sys.argv[1:]:
try:
with open(file, "rt", encoding="utf-8") as f:
original = f.read()
except UnicodeDecodeError:
invalid.append(file)
continue

if original == "":
continue

EOL = "\n"
WANTS_BOM = False

revamp = EOL.join([line.rstrip("\n\r\t ") for line in original.splitlines(True)]).rstrip(EOL) + EOL

new_raw = revamp.encode(encoding="utf-8")
if not WANTS_BOM and new_raw.startswith(BOM):
new_raw = new_raw[len(BOM) :]
elif WANTS_BOM and not new_raw.startswith(BOM):
new_raw = BOM + new_raw

with open(file, "rb") as f:
old_raw = f.read()

if old_raw != new_raw:
changed.append(file)
with open(file, "wb") as f:
f.write(new_raw)

if changed:
for file in changed:
print(f"FIXED: {file}")

if invalid:
for file in invalid:
print(f"REQUIRES MANUAL CHANGES: {file}")
sys.exit(1)
20 changes: 20 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
default_language_version:
python: python3

exclude: |
(?x)^(
3rdparty/.*|
bindings/.*|
include/bgfx/c99/bgfx\.h|
.*\.bin\.h|
.*\.ttf\.h$
)

repos:
- repo: local
hooks:
- id: file-format
name: file-format
language: python
entry: python .github/workflows/file_format.py
types_or: [text]