From 06a79a1a06f8ec8975aed1370fd3e6a2f99ace84 Mon Sep 17 00:00:00 2001
From: xSlendiX <slendi@socopon.com>
Date: Sun, 26 Feb 2023 01:17:36 +0200
Subject: [PATCH] Add pre-commit hook to remove cursors.

This patch adds a pre-commit hook specifically for *NIX systems to
remove the cursor byte from all files under `src/`.

The reason why I chose python is because it is assumed that most *NIX
systems already come with it pre-installed.

Signed-off-by: xSlendiX <slendi@socopon.com>
---
 meta/check_code.py    | 33 +++++++++++++++++++++++++++++++++
 meta/install_hooks.sh |  8 ++++++++
 meta/pre-commit       | 25 +++++++++++++++++++++++++
 3 files changed, 66 insertions(+)
 create mode 100755 meta/check_code.py
 create mode 100755 meta/install_hooks.sh
 create mode 100755 meta/pre-commit

diff --git a/meta/check_code.py b/meta/check_code.py
new file mode 100755
index 00000000..4bcfd424
--- /dev/null
+++ b/meta/check_code.py
@@ -0,0 +1,33 @@
+#!/usr/bin/env python3
+
+import os
+from pathlib import Path
+
+os.chdir(os.path.realpath(os.path.dirname(__file__))+'/../src')
+
+for f in Path(os.getcwd()).glob('**/*'):
+    if not f.is_file():
+        continue
+
+    if not os.path.basename(f).lower().endswith('.zc'):
+        continue
+
+    contents = b''
+    with open(f, 'r+b') as file:
+        contents = file.read()
+
+        n = contents.find(b'\x05')
+        byte = contents[n]
+
+        if n == -1: continue
+        if contents[n-1] == 0 or contents[n-1] > 127: continue
+        if n+1 < len(contents) and contents[n+1] == 5: continue
+        if contents[n-1] <= 0x1F and (not contents[n-1] in b'\n\r'): continue
+        if n+1 < len(contents) and contents[n+1] <= 0x1F and (not contents[n+1] in b'\n\r'): continue
+
+        contents = contents[0:n:]
+
+        file.seek(0)
+        file.truncate()
+        file.write(contents)
+
diff --git a/meta/install_hooks.sh b/meta/install_hooks.sh
new file mode 100755
index 00000000..7b6af2b5
--- /dev/null
+++ b/meta/install_hooks.sh
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+script_path=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
+cd "${script_path}/.." || exit 1
+
+mkdir -p .git/hooks
+cp meta/pre-commit .git/hooks/.
+
diff --git a/meta/pre-commit b/meta/pre-commit
new file mode 100755
index 00000000..2d971ac3
--- /dev/null
+++ b/meta/pre-commit
@@ -0,0 +1,25 @@
+#!/bin/sh
+
+set -e
+
+script_path=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
+cd "${script_path}/.." || exit 1
+pwd | grep -q '.git' && cd ..
+
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+NC='\033[0m' # No Color
+
+FAILURES=0
+
+set +e
+
+echo "Running meta/check_code.sh"
+if time meta/check_code.sh "$@" && git diff --exit-code; then
+    echo -e "[${GREEN}GOOD${NC}]: meta/check_code.sh"
+else
+    echo -e "[${RED}FAIL${NC}]: meta/check_code.sh"
+    ((FAILURES+=1))
+fi
+
+exit "${FAILURES}"