如何指示clang格式在文件';结束?

如何指示clang格式在文件';结束?,clang,llvm,eof,clang-format,Clang,Llvm,Eof,Clang Format,也许我错过了什么,但还是没有找到这样的背景。从形式上讲,clangformat不能生成正确的UNIX文本文件,因为最后一行总是缺少EOL字符。选项1: 找到和外部参考。这可以帮助您,“您可以递归地添加一个下线字符/清理来自…的文件。” 如果文件已经存在,它不会删除文件末尾的EOL。但如果它不存在,那么如果它添加了EOL就好了。三年后,这个似乎仍然在clang-format中缺失。是的,这很令人伤心。至少,IDE允许在保存时强制执行,例如CLion/Android Studio:文件->设置->编

也许我错过了什么,但还是没有找到这样的背景。从形式上讲,
clangformat
不能生成正确的UNIX文本文件,因为最后一行总是缺少EOL字符。

选项1:

找到和外部参考。这可以帮助您,“您可以递归地添加一个下线字符/清理来自…的文件。”


如果文件已经存在,它不会删除文件末尾的EOL。但如果它不存在,那么如果它添加了EOL就好了。三年后,这个似乎仍然在clang-format中缺失。是的,这很令人伤心。至少,IDE允许在保存时强制执行,例如CLion/Android Studio:
文件->设置->编辑器->常规-/code>和切换
在保存时确保文件末尾有一个空行
不确定这是否相关:不完全是问题的答案,但将.editorconfig文件添加到存储库的根目录至少会使现代编辑器添加EOL和EOF。VisualStudio支持它。因此,虽然您无法用clang格式重新格式化所有文件,但至少新文件将以正确的格式保存。选项1非常好,谢谢!特别是与编辑器的正确设置相结合,这样以后就不会引入缺少EOF的EOL的新文件。我不知道选项2在实践中应该如何使用。
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.
#!/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