Skip to content
Merged
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
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,41 @@ sdk

SDK 也可在 WebUI 的设置页面中管理。已有工具链可在“本地工具链配置”中登记,实际编译器选择仍以项目配置为准。

## 提交前格式化代码

激活 Env 后,在目标 Git 仓库的任意目录运行:

```bash
format-changed
```

也可以使用 `rt-env format-changed`。命令会查找当前仓库中未暂存、已暂存以及尚未跟踪的 C/C++ 源文件和头文件,
使用项目内最近的 `.clang-format` 或 `_clang-format` 配置,对选中文件的完整内容进行格式化。
删除的文件、被 Git 忽略的未跟踪文件、符号链接及 Windows 目录联接下的文件和子模块内容会跳过;缺少配置或存在合并冲突时会提示并停止。

命令要求 clang-format的版本为 **22.1.8**。

如果改动已经提交到 PR 分支,指定目标分支可以同时处理当前分支自共同节点以来仍有差异的文件:

```bash
git fetch origin
format-changed --base origin/master
```

将 `origin/master` 替换为实际 PR 目标分支。多笔提交涉及同一文件时,只格式化该文件在工作区的当前内容一次;
未提交的改动也会纳入处理。历史差异仅纳入当前仍受 Git 跟踪的路径,避免改写已取消跟踪并忽略的本地文件。
命令使用本地 Git 引用,不会自动拉取远端。

只检查格式、不修改文件:

```bash
format-changed --check
format-changed --base origin/master --check
```

格式不符合要求或执行出错时返回非零退出码,没有符合条件的文件时正常结束。
格式化结果仅保留在工作区,不会修改暂存区、创建提交或推送;请检查 `git diff` 后手动 `git add` 和提交。

## WebUI

在项目目录运行以下命令,启动服务并打开浏览器:
Expand Down
2 changes: 1 addition & 1 deletion cmds/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@
# 2018-5-28 SummerGift Add copyright information
#

__all__ = ['cmd_package', 'cmd_system', 'cmd_menuconfig', 'cmd_sdk', 'cmd_plugin', 'cmd_webui']
__all__ = ['cmd_package', 'cmd_system', 'cmd_menuconfig', 'cmd_sdk', 'cmd_plugin', 'cmd_webui', 'cmd_format_changed']
197 changes: 197 additions & 0 deletions cmds/cmd_format_changed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
"""Format changed C/C++ files with clang-format 22.1.8."""

import os
from pathlib import Path
import re
import shutil
import stat
import subprocess
import sys

from env_paths import get_env_root


CLANG_FORMAT_VERSION = '22.1.8'
EXTENSIONS = {'.c', '.h', '.cc', '.hh', '.cpp', '.hpp', '.cxx', '.hxx', '.c++', '.h++', '.inl', '.ipp', '.tpp'}
DIFF_OPTIONS = ['-z', '--diff-filter=ACMRT', '--no-ext-diff', '--ignore-submodules=all']


class CommandError(Exception):
pass


def find_tool(name):
filenames = [name]
if os.name == 'nt':
extensions = (os.environ.get('PATHEXT') or '.COM;.EXE;.BAT;.CMD').split(os.pathsep)
filenames = [name + extension for extension in extensions if re.fullmatch(r'\.[a-zA-Z0-9]+', extension)]
directories = [Path(get_env_root()) / 'tools' / 'bin']
directories.extend(Path(entry.strip('"')) for entry in os.environ.get('PATH', '').split(os.pathsep) if entry)
for directory in directories:
if not directory.is_absolute():
continue
# An absolute candidate prevents Windows/Python 3.11 from searching cwd first.
for filename in filenames:
command = shutil.which(str(directory / filename))
if command:
return os.path.abspath(command)
return None


def git(*args, cwd=None):
command = find_tool('git')
if not command:
raise CommandError('Git was not found in Env tools or absolute PATH directories.')
result = subprocess.run([command, *args], cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode:
raise CommandError(result.stderr.decode('utf-8', errors='replace').strip())
return result.stdout


def filenames(data):
return {os.fsdecode(name) for name in data.split(b'\0') if name}


def changed_files(root, base):
tracked = set()
symlinks = set()
submodules = set()
for entry in git('ls-files', '--stage', '-z', cwd=root).split(b'\0'):
if not entry:
continue
metadata, _, name = entry.partition(b'\t')
mode, _, stage = metadata.split()
if stage != b'0':
raise CommandError('Resolve merge conflicts before running format-changed.')
name = os.fsdecode(name)
tracked.add(name)
if mode == b'120000':
symlinks.add(name)
elif mode == b'160000':
submodules.add(name)

names = set()
# Disable rename detection so each NUL-delimited status has exactly one path.
unstaged = git('diff', '--name-status', '--no-renames', *DIFF_OPTIONS, '--', cwd=root).split(b'\0')
for status, name in zip(unstaged[::2], unstaged[1::2]):
name = os.fsdecode(name)
names.add(name)
if status == b'T':
# Use the worktree type after replacement, retaining Windows placeholder filtering.
symlinks.discard(name)
names.update(filenames(git('diff', '--cached', '--name-only', *DIFF_OPTIONS, '--', cwd=root)))
names.update(filenames(git('ls-files', '--others', '--exclude-standard', '-z', cwd=root)))

if base:
revision = git('rev-parse', '--verify', '--end-of-options', base + '^{commit}', cwd=root).strip().decode('ascii')
ancestor = git('merge-base', 'HEAD', revision, cwd=root).strip().decode('ascii')
historical = filenames(git('diff', '--name-only', *DIFF_OPTIONS, ancestor, 'HEAD', '--', cwd=root))
names.update(historical & tracked)

selected = []
for name in sorted(names - symlinks):
# Historical diffs can name files now owned by a submodule in the index.
if any(name == submodule or name.startswith(submodule + '/') for submodule in submodules):
continue
path = root / name
if path.suffix.lower() not in EXTENSIONS or not path.is_file() or has_link_component(path, root):
continue
try:
path.resolve().relative_to(root)
except ValueError:
continue
selected.append(path)
return selected


def has_link_component(path, root):
current = root
for part in path.relative_to(root).parts:
current = current / part
metadata = current.lstat()
# Reparse points include Windows junctions; Path.is_junction needs Python 3.12.
if stat.S_ISLNK(metadata.st_mode) or getattr(metadata, 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT:
return True
return False


def has_project_style(path, root):
directory = path.parent
while True:
if any((directory / name).is_file() for name in ('.clang-format', '_clang-format')):
return True
if directory == root:
return False
directory = directory.parent


def find_clang_format():
command = find_tool('clang-format')
if not command:
raise CommandError('clang-format 22.1.8 was not found. Install it and add it to PATH, or use Env for Windows with it bundled.')
result = subprocess.run([command, '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
version = result.stdout.decode('utf-8', errors='replace').strip()
match = re.search(r'\bversion\s+(\d+\.\d+\.\d+)\b', version)
if result.returncode or not match or match.group(1) != CLANG_FORMAT_VERSION:
raise CommandError('clang-format 22.1.8 is required; %s reported: %s' % (command, version or 'unknown version'))
return command


def printable(text, stream):
encoding = getattr(stream, 'encoding', None) or 'utf-8'
return str(text).encode(encoding, errors='backslashreplace').decode(encoding)


def cmd(args):
try:
root = Path(os.fsdecode(git('rev-parse', '--show-toplevel').rstrip(b'\r\n'))).resolve()
files = changed_files(root, args.base)
if not files:
print('No changed C/C++ files to process.')
return 0

missing = [path.relative_to(root).as_posix() for path in files if not has_project_style(path, root)]
if missing:
raise CommandError(
'No .clang-format or _clang-format found inside the repository for:\n '
+ '\n '.join(missing)
+ "\nAdd the project's formatting configuration and run again. No files were formatted."
)

clang_format = find_clang_format()
options = ['--style=file', '--fallback-style=none', '--Werror']
options += ['--dry-run'] if args.check else ['-i']
action = 'Checking' if args.check else 'Formatting'
print('Selected %d changed C/C++ file(s).' % len(files), flush=True)
failed = False
for path in files:
print('%s: %s' % (action, printable(path.relative_to(root).as_posix(), sys.stdout)), flush=True)
result = subprocess.run([clang_format, *options, str(path)], cwd=root)
if result.returncode:
failed = True
if not args.check:
return result.returncode if result.returncode > 0 else 1
if failed:
return 1
if args.check:
print('Formatting check passed.')
else:
print('Done. Review git diff and git add the files you want to commit.')
return 0
except (CommandError, OSError) as error:
print(printable('Error: %s' % error, sys.stderr), file=sys.stderr)
return 1


def add_parser(sub):
parser = sub.add_parser(
'format-changed',
help=__doc__,
description=(
'Format whole changed C/C++ files with clang-format 22.1.8. '
'Includes unstaged, staged and untracked files; leaves the Git index unchanged.'
),
)
parser.add_argument('--base', metavar='REF', help='also include committed changes since the merge base of HEAD and REF')
parser.add_argument('--check', action='store_true', help='check formatting without modifying files (nonzero exit on violations)')
parser.set_defaults(func=cmd)
8 changes: 6 additions & 2 deletions env.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
mpath = os.path.dirname(script_path)
sys.path.insert(0, mpath)

from cmds import cmd_menuconfig, cmd_package, cmd_plugin, cmd_sdk, cmd_system, cmd_webui
from cmds import cmd_format_changed, cmd_menuconfig, cmd_package, cmd_plugin, cmd_sdk, cmd_system, cmd_webui
from env_paths import get_env_root, get_package_root, get_rtt_root as resolve_rtt_root
from vars import Export
from info import get_name, get_version
Expand Down Expand Up @@ -112,7 +112,7 @@ def init_argparse():
parser.add_argument('-v', '--version', action='version', version=env_ver_str)
parser.add_argument('--info', action='store_true', help='Show environment information')

for command in (cmd_system, cmd_menuconfig, cmd_package, cmd_sdk, cmd_plugin, cmd_webui):
for command in (cmd_system, cmd_menuconfig, cmd_package, cmd_sdk, cmd_plugin, cmd_webui, cmd_format_changed):
command.add_parser(subs)

return parser
Expand Down Expand Up @@ -226,6 +226,10 @@ def system():
return exec_arg('system')


def format_changed():
return exec_arg('format-changed')


def webui():
show_version_warning()
export_environment_variable()
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pkgs = "env.env:pkgs"
sdk = "env.env:sdk"
system = "env.env:system"
webui = "env.env:webui"
format-changed = "env.env:format_changed"

[tool.setuptools]
package-dir = { env = ".", "env.cmds" = "cmds", "env.cmds.cmd_package" = "cmds/cmd_package", "env.plugins" = "plugins", "env.plugins.sdk" = "plugins/sdk", "env.plugins.epack" = "plugins/epack", "env.plugins.spec" = "plugins/spec", "env.plugins.webui" = "plugins/webui" }
Expand Down
Loading