【问题标题】:How to instruct clang-format to add EOL-character at file's end?如何指示 clang-format 在文件末尾添加 EOL 字符?
【发布时间】:2017-10-24 12:23:19
【问题描述】:

也许我错过了一些东西,但仍然没有找到这样的设置。正式地说,clang-format 不会生成正确的 UNIX 文本文件,因为最后一行总是缺少 EOL 字符。

【问题讨论】:

  • 好吧,如果文件末尾的 EOL 已经存在,它不会删除它。但是,如果它不存在时添加 EOL,那就太好了。三年后,clang 格式似乎仍然缺少这一点。
  • 是的,这很可悲。至少,IDE 允许在保存时强制执行,例如 CLion/Android Studio:File->Settings->Editor->General 和切换 Ensure an empty line at the end of a file on Save
  • 不是这个问题的答案,但是将 .editorconfig 文件添加到存储库的根目录至少会使现代编辑器添加 EOL 和 EOF。 VisualStudio 支持它。因此,虽然您无法使用 clang-format 重新格式化所有文件,但至少新文件会以正确的格式保存。

标签: clang llvm eof clang-format


【解决方案1】:

选项 1:

发现和外部参考。这可以帮助您,“您可以递归地添加 EOL 字符/清理来自 here...的文件...

git ls-files -z "*.cpp" "*.hpp" | while IFS= read -rd '' f; do tail -c1 < "$f" | read -r _ || echo >> "$f"; done

解释:

git ls-files -z "*.cpp" "*.hpp" //lists files in the repository matching the listed patterns. You can add more patterns, but they need the quotes so that the * is not substituted by the shell but interpreted by git. As an alternative, you could use find -print0 ... or similar programs to list affected files - just make sure it emits NUL-delimited entries.

while IFS= read -rd '' f; do ... done //iterates through the entries, safely handling filenames that include whitespace and/or newlines.

tail -c1 < "$f" reads the last char from a file.

read -r _ exits with a nonzero exit status if a trailing newline is missing.

|| echo >> "$f" appends a newline to the file if the exit status of the previous command was nonzero.

来自 Clang format script 的选项 2:

#!/bin/bash

set -e

function append_newline {
    if [[ -z "$(tail -c 1 "$1")" ]]; then
        :
    else
        echo >> "$1"
    fi
}

if [ -z "$1" ]; then
    TARGET_DIR="."
else
    TARGET_DIR=$1
fi

pushd ${TARGET_DIR} >> /dev/null

# Find all source files using Git to automatically respect .gitignore
FILES=$(git ls-files "*.h" "*.cpp" "*.c")

# Run clang-format
clang-format-10 -i ${FILES}

# Check newlines
for f in ${FILES}; do
    append_newline $f
done

popd >> /dev/null

【讨论】:

  • 选项 1 很棒,谢谢!尤其是与您的编辑器的正确设置相结合,这样之后就不会引入在 EOF 处缺少 EOL 的新文件。我不知道在实践中应该如何使用选项 2。
  • 选项2可用于git pre-commit hooks等脚本,可读性更强。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 2014-07-10
  • 2022-06-20
  • 2014-05-28
相关资源
最近更新 更多