Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instruct clang-format to add EOL-character at file's end?

Maybe I miss something, but still didn't find such a setting. Formally speaking clang-format doesn't produce proper UNIX text files, since last lines always lack EOL-character.

like image 841
ababo Avatar asked Oct 24 '17 12:10

ababo


People also ask

How do you add a format to clang?

You can install clang-format and git-clang-format via npm install -g clang-format . To automatically format a file according to Electron C++ code style, run clang-format -i path/to/electron/file.cc . It should work on macOS/Linux/Windows.

Where does clang format look for clang format?

clang-format is located in clang/tools/clang-format and can be used to format C/C++/Java/JavaScript/Objective-C/Protobuf code.

How do I use clang format in Visual Studio?

To format all or part of a file, use the default Visual Studio format CTRL+K, CTRL+D. Visual Studio will usually tell you it's found a Clang Format file when you do this.

How do I get rid of clang format?

There is no functionality in clang-format for undoing a format operation.


1 Answers

Option 1:

Found and outside ref. which could help you, "You can recursively add an EOL-character / sanitize the files from here..."

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

Explanation:

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.

Option 2 from Clang format script:

#!/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
like image 188
Transformer Avatar answered Sep 23 '22 14:09

Transformer