Skip to content

Commit c30d90f

Browse files
committedMay 27, 2019
Add automated code formatting infrastructure
1 parent 96ba9d4 commit c30d90f

File tree

7 files changed

+305
-3
lines changed

7 files changed

+305
-3
lines changed
 

‎.clang-format

+106
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
Language: Cpp
2+
BasedOnStyle: Chromium
3+
AccessModifierOffset: -2
4+
AlignAfterOpenBracket: Align
5+
AlignConsecutiveAssignments: false
6+
AlignConsecutiveDeclarations: false
7+
AlignEscapedNewlines: Left
8+
AlignOperands: true
9+
AlignTrailingComments: true
10+
AllowAllParametersOfDeclarationOnNextLine: false
11+
AllowShortBlocksOnASingleLine: true
12+
AllowShortCaseLabelsOnASingleLine: false
13+
AllowShortFunctionsOnASingleLine: true
14+
AllowShortIfStatementsOnASingleLine: true
15+
AllowShortLoopsOnASingleLine: false
16+
AlwaysBreakAfterDefinitionReturnType: None
17+
AlwaysBreakAfterReturnType: None
18+
AlwaysBreakBeforeMultilineStrings: true
19+
AlwaysBreakTemplateDeclarations: true
20+
BinPackArguments: true
21+
BinPackParameters: false
22+
BraceWrapping:
23+
AfterClass: false
24+
AfterControlStatement: false
25+
AfterEnum: false
26+
AfterFunction: false
27+
AfterNamespace: false
28+
AfterObjCDeclaration: false
29+
AfterStruct: false
30+
AfterUnion: false
31+
BeforeCatch: false
32+
BeforeElse: false
33+
IndentBraces: false
34+
SplitEmptyFunction: false
35+
SplitEmptyRecord: true
36+
SplitEmptyNamespace: true
37+
BreakBeforeBinaryOperators: All
38+
BreakBeforeBraces: Custom
39+
BreakBeforeInheritanceComma: false
40+
BreakBeforeTernaryOperators: true
41+
BreakConstructorInitializersBeforeComma: false
42+
BreakConstructorInitializers: BeforeComma
43+
BreakAfterJavaFieldAnnotations: false
44+
BreakStringLiterals: true
45+
ColumnLimit: 0
46+
CommentPragmas: '^ IWYU pragma:'
47+
CompactNamespaces: false
48+
ConstructorInitializerAllOnOneLineOrOnePerLine: false
49+
ConstructorInitializerIndentWidth: 4
50+
ContinuationIndentWidth: 4
51+
Cpp11BracedListStyle: true
52+
DerivePointerAlignment: false
53+
DisableFormat: false
54+
ExperimentalAutoDetectBinPacking: false
55+
FixNamespaceComments: true
56+
ForEachMacros:
57+
- foreach
58+
- Q_FOREACH
59+
- BOOST_FOREACH
60+
IncludeCategories:
61+
- Regex: '^<.*\.h>'
62+
Priority: 1
63+
- Regex: '^<.*'
64+
Priority: 2
65+
- Regex: '.*'
66+
Priority: 3
67+
IncludeIsMainRegex: '([-_](test|unittest))?$'
68+
IndentCaseLabels: true
69+
IndentWidth: 4
70+
IndentWrappedFunctionNames: false
71+
IndentPPDirectives: AfterHash
72+
JavaScriptQuotes: Leave
73+
JavaScriptWrapImports: true
74+
KeepEmptyLinesAtTheStartOfBlocks: false
75+
MacroBlockBegin: ''
76+
MacroBlockEnd: ''
77+
MaxEmptyLinesToKeep: 1
78+
NamespaceIndentation: None
79+
ObjCBlockIndentWidth: 2
80+
ObjCSpaceAfterProperty: false
81+
ObjCSpaceBeforeProtocolList: false
82+
PenaltyBreakAssignment: 2
83+
PenaltyBreakBeforeFirstCallParameter: 1
84+
PenaltyBreakComment: 300
85+
PenaltyBreakFirstLessLess: 120
86+
PenaltyBreakString: 1000
87+
PenaltyExcessCharacter: 1000000
88+
PenaltyReturnTypeOnItsOwnLine: 200
89+
PointerAlignment: Left
90+
ReflowComments: false
91+
SortIncludes: false
92+
SortUsingDeclarations: true
93+
SpaceAfterCStyleCast: false
94+
SpaceAfterTemplateKeyword: false
95+
SpaceBeforeAssignmentOperators: true
96+
SpaceBeforeParens: ControlStatements
97+
SpaceInEmptyParentheses: false
98+
SpacesBeforeTrailingComments: 1
99+
SpacesInAngles: false
100+
SpacesInContainerLiterals: true
101+
SpacesInCStyleCastParentheses: false
102+
SpacesInParentheses: false
103+
SpacesInSquareBrackets: false
104+
Standard: Auto
105+
TabWidth: 4
106+
UseTab: Never

‎.travis.yml

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
language: cpp
22

3-
#dist: trusty
4-
sudo: false
3+
dist: trusty
54
addons:
65
apt:
76
sources:
87
- ubuntu-toolchain-r-test # For newer GCC
98
- george-edison55-precise-backports # For cmake
9+
- llvm-toolchain-trusty-7
1010
packages:
1111
- autoconf
1212
- automake
@@ -40,6 +40,7 @@ addons:
4040
- valgrind
4141
- zip
4242
- qt5-default
43+
- clang-format-7
4344

4445
before_install:
4546
- source .travis/common.sh

‎.travis/script.sh

+7-1
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,10 @@ start_section "vtr.test.5" "${GREEN}Testing..${NC} ${CYAN}odin_reg_operators${NC
5555
./run_reg_test.pl odin_reg_operators
5656
end_section "vtr.test.5"
5757

58-
$SPACER
58+
$SPACER
59+
60+
start_section "vtr.test.6" "${GREEN}Checking..${NC} ${CYAN}code formatting${NC}"
61+
./dev/check-format.sh
62+
end_section "vtr.test.6"
63+
64+
$SPACER

‎CMakeLists.txt

+12
Original file line numberDiff line numberDiff line change
@@ -364,3 +364,15 @@ if(WITH_BLIFEXPLORER)
364364
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/blifexplorer"
365365
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/blifexplorer")
366366
endif()
367+
368+
#
369+
#
370+
# Code Autoformatting
371+
#
372+
#
373+
list(APPEND DIRS_TO_FORMAT_CPP "${CMAKE_CURRENT_SOURCE_DIR}/vpr")
374+
list(APPEND DIRS_TO_FORMAT_CPP "${CMAKE_CURRENT_SOURCE_DIR}/libs/libarchfpga")
375+
list(APPEND DIRS_TO_FORMAT_CPP "${CMAKE_CURRENT_SOURCE_DIR}/libs/libvtrutil")
376+
list(APPEND DIRS_TO_FORMAT_CPP "${CMAKE_CURRENT_SOURCE_DIR}/libs/libpugiutil")
377+
list(APPEND DIRS_TO_FORMAT_CPP "${CMAKE_CURRENT_SOURCE_DIR}/libs/liblog")
378+
include(AutoClangFormat)

‎cmake/modules/AutoClangFormat.cmake

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
include(ProcessorCount)
2+
ProcessorCount(CPU_COUNT)
3+
if(CPU_COUNT EQUAL 0)
4+
message(FATAL_ERROR "Unknown number of CPUs!?")
5+
endif()
6+
7+
#
8+
# ----------------------- Code format --------------------------
9+
#
10+
11+
set(FIND_TO_FORMAT_CPP
12+
-name '*.cpp' -print -o -name '*.h' -print
13+
-o -name '*.tpp' -print -o -name '*.hpp' -print)
14+
15+
list(APPEND DIRS_TO_FORMAT_CPP "")
16+
17+
#
18+
# List the files which will be auto-formatted.
19+
#
20+
add_custom_target(format-cpp-files
21+
COMMAND find ${DIRS_TO_FORMAT_CPP} ${FIND_TO_FORMAT_CPP})
22+
23+
#
24+
# Use clang-format-7 for code format
25+
#
26+
add_custom_target(format-cpp
27+
COMMAND find ${DIRS_TO_FORMAT_CPP} ${FIND_TO_FORMAT_CPP} |
28+
xargs -P ${CPU_COUNT} clang-format-7 -style=file -i)
29+
30+
#
31+
# Use simple python script for fixing C like boxed comments
32+
#
33+
add_custom_target(format-cpp-fix-comments DEPENDS format-cpp
34+
COMMAND find ${DIRS_TO_FORMAT_CPP} ${FIND_TO_FORMAT_CPP} |
35+
xargs -L 1 -P ${CPU_COUNT}
36+
python3 ${PROJECT_SOURCE_DIR}/dev/code_format_fixup.py --inplace --fix-comments --input)
37+
38+
#
39+
# Use simple python script for fixing template brackets e.g. <<>
40+
#
41+
add_custom_target(format-cpp-fix-template-operators DEPENDS format-cpp
42+
COMMAND find ${DIRS_TO_FORMAT_CPP} ${FIND_TO_FORMAT_CPP} |
43+
xargs -L 1 -P ${CPU_COUNT}
44+
python3 ${PROJECT_SOURCE_DIR}/dev/code_format_fixup.py --inplace --fix-template-operators --input)
45+
46+
add_custom_target(format DEPENDS format-cpp-fix-comments format-cpp-fix-template-operators)

‎dev/check-format.sh

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#!/bin/bash
2+
3+
clean=$(git status -s -uno | wc -l) #Short ignore untracked
4+
5+
if [ $clean -ne 0 ]; then
6+
echo "Current working tree was not clean! This tool only works on clean checkouts"
7+
exit 2
8+
else
9+
echo "Code Formatting Check"
10+
echo "====================="
11+
make format > /dev/null
12+
13+
valid_format=$(git diff | wc -l)
14+
15+
if [ $valid_format -ne 0 ]; then
16+
echo "FAILED"
17+
echo ""
18+
echo "You *must* make the following changes to match the formatting style"
19+
echo "-------------------------------------------------------------------"
20+
echo ""
21+
22+
git diff
23+
24+
echo ""
25+
echo "Run 'make format' to apply these changes"
26+
27+
git reset --hard > /dev/null
28+
exit 1
29+
else
30+
echo "OK"
31+
fi
32+
fi
33+
exit 0

‎dev/code_format_fixup.py

+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
#!/usr/bin/env python3
2+
3+
import sys, os
4+
import argparse
5+
6+
def fix_comments(f, o):
7+
space_string = ''
8+
9+
for line in f:
10+
# Skip lines with // comments
11+
if space_string == '' and line.find('//') != -1:
12+
o.write(line)
13+
continue
14+
15+
sc = line.find("/*")
16+
ec = line.find("*/")
17+
18+
# Skip /* foo bar */ comments
19+
if sc != -1 and ec != -1:
20+
o.write(line)
21+
else:
22+
# Start of /* comment */
23+
if sc != -1:
24+
space_string = (''.join(' ' for i in range(sc+1)))
25+
o.write(line)
26+
elif space_string != '':
27+
# Already in /* comment */
28+
ls = line.lstrip()
29+
30+
# Empty line, write aligned comment prefix
31+
if len(ls) == 0:
32+
o.write(space_string + "*" + "\n")
33+
elif ls[0] != '*':
34+
#
35+
# Fix comments like '********* sth **********'
36+
# to look like ' * ********** sth **********'
37+
#
38+
o.write(space_string + "* " + ls)
39+
else:
40+
# Rest of the /* comment */
41+
o.write(space_string + ls)
42+
else:
43+
# Outside /* comment */
44+
o.write(line)
45+
46+
# Moving outside /* comment */
47+
if ec != -1:
48+
space_string = ''
49+
50+
def fix_template_operators(f, o):
51+
for line in f:
52+
line = line.replace('<<>', '< <>');
53+
line = line.replace('><>', '> <>');
54+
line = line.replace('==<>', '== <>');
55+
line = line.replace('!=<>', '!= <>');
56+
57+
o.write(line);
58+
59+
def main(argv):
60+
parser = argparse.ArgumentParser(description='Tool for fixing clang code formatting')
61+
parser.add_argument('--inplace', dest='inplace',
62+
action='store_true',
63+
help='Inplace edit specified file')
64+
parser.add_argument('--fix-comments', dest='fix_comments',
65+
action='store_const',
66+
const='fix_comments',
67+
help='Fix C like box comments')
68+
parser.add_argument('--fix-template-operators', dest='fix_template_operators',
69+
action='store_const',
70+
const='fix_template_operators',
71+
help='Fix C++ template operators e.g. operator<<> => operator< <>')
72+
parser.add_argument('--input', dest='inputfile', action='store',
73+
help='Input file')
74+
parser.add_argument('--output', dest='outputfile', action='store',
75+
help='Output file')
76+
args = parser.parse_args(argv[1:]);
77+
78+
for p in args.fix_comments, args.fix_template_operators:
79+
if not p:
80+
continue
81+
82+
fin = open(args.inputfile, 'r')
83+
84+
if args.inplace:
85+
fout = open(args.inputfile + '.bak', 'w')
86+
else:
87+
fout = open(args.outputfile, 'w');
88+
89+
eval('' + p + '(fin, fout)')
90+
91+
fin.close();
92+
fout.close();
93+
94+
if args.inplace:
95+
os.rename(args.inputfile + '.bak', args.inputfile)
96+
97+
if __name__ == "__main__":
98+
main(sys.argv)

0 commit comments

Comments
 (0)
Please sign in to comment.