diff --git a/Makefile b/Makefile index c258ac2d..59842e9e 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY : build clean install-python test-cpp test-onnx +.PHONY : build clean format install-python test-cpp test-onnx TYPE ?= release CUDA ?= OFF @@ -6,6 +6,7 @@ BANG ?= OFF INTELCPU ?= off BACKTRACE ?= ON TEST ?= ON +FORMAT_ORIGIN ?= CMAKE_OPT = -DCMAKE_BUILD_TYPE=$(TYPE) CMAKE_OPT += -DUSE_CUDA=$(CUDA) @@ -24,6 +25,9 @@ build: clean: rm -rf build +format: + @python3 scripts/format.py $(FORMAT_ORIGIN) + install-python: build cp build/$(TYPE)/backend*.so pyinfinitensor/src/pyinfinitensor pip install pyinfinitensor/ diff --git a/scripts/format.py b/scripts/format.py new file mode 100644 index 00000000..7d74d54b --- /dev/null +++ b/scripts/format.py @@ -0,0 +1,50 @@ +import sys +from pathlib import Path +from subprocess import run + +c_style_file = [".h", ".hh", ".hpp", ".c", ".cc", ".cpp", ".cxx", ".cu", ".mlu"] +py_file = ".py" +proj_path = Path(sys.path[0]).parent + + +# Formats one file under project path. +def format_file(file): + file = Path(proj_path.joinpath(file)) + if file.suffix in c_style_file: + run(f"clang-format-14 -i {file}", cwd=proj_path, shell=True) + run(f"git add {file}", cwd=proj_path, shell=True) + elif file.suffix == py_file: + run(f"black {file}", cwd=proj_path, shell=True) + run(f"git add {file}", cwd=proj_path, shell=True) + + +if len(sys.argv) == 1: + # Last commit. + print("Formats git added files.") + for line in ( + run("git status", cwd=proj_path, capture_output=True, shell=True) + .stdout.decode() + .splitlines() + ): + line = line.strip() + # Only formats git added files. + for pre in ["new file:", "modified:"]: + if line.startswith(pre): + format_file(line[len(pre) :].strip()) + break +else: + # Origin commit. + origin = sys.argv[1] + print(f'Formats changed files from "{origin}".') + for line in ( + run(f"git diff {origin}", cwd=proj_path, capture_output=True, shell=True) + .stdout.decode() + .splitlines() + ): + diff = "diff --git " + if line.startswith(diff): + files = line[len(diff) :].split(" ") + assert len(files) == 2 + assert files[0][:2] == "a/" + assert files[1][:2] == "b/" + format_file(files[1][2:]) diff --git a/test/script/clang_format_inplace.sh b/test/script/clang_format_inplace.sh deleted file mode 100755 index 49b2e3d0..00000000 --- a/test/script/clang_format_inplace.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env bash -script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]:-$0}")" &>/dev/null && pwd 2>/dev/null)" -PET_HOME="$(readlink -f ${script_dir}/../..)" -find ${PET_HOME}/src ${PET_HOME}/include ${PET_HOME}/test -iname *.h -o -iname *.cc | xargs clang-format -i