Skip to content
Open
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
189 changes: 189 additions & 0 deletions .clang-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
# The style used for all options not specifically set in the configuration.
BasedOnStyle: LLVM

# The extra indent or outdent of access modifiers, e.g. public:.
AccessModifierOffset: -4

# Aligns escaped newlines as far left as possible
AlignEscapedNewlines: Left

# This will align the assignment operators of consecutive lines.
AlignConsecutiveAssignments: Consecutive

# Do not align the declaration names.
AlignConsecutiveDeclarations: None

# Align the bitfield in declarations
AlignConsecutiveBitFields: Consecutive

# If true, aligns trailing comments.
AlignTrailingComments: true

# Align operands when the expression is broken in multiple lines.
AlignOperands: Align

# Allow putting all parameters of a function declaration onto the next line even if BinPackParameters is false.
AllowAllParametersOfDeclarationOnNextLine: false

# Allows contracting simple braced statements to a single line.
AllowShortBlocksOnASingleLine: false

# If true, short case labels will be contracted to a single line.
AllowShortCaseLabelsOnASingleLine: false

# Dependent on the value, int f() { return 0; } can be put on a single line. Possible values: None, Inline, All.
AllowShortFunctionsOnASingleLine: None

# If true, if (a) return; can be put on a single line.
AllowShortIfStatementsOnASingleLine: false

# If true, while (true) continue; can be put on a single line.
AllowShortLoopsOnASingleLine: false

# If true, always break after function definition return types.
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None

# If true, always break before multiline string literals.
AlwaysBreakBeforeMultilineStrings: false

# If true, always break after the template<...> of a template declaration.
AlwaysBreakTemplateDeclarations: Yes

# If false, a function call's arguments will either be all on the same line or will have one line each.
BinPackArguments: true

# If false, a function declaration's or function definition's parameters will either all be on the same line
# or will have one line each.
BinPackParameters: true

# The way to wrap binary operators. Possible values: None, NonAssignment, All.
BreakBeforeBinaryOperators: None

# The brace breaking style to use. Possible values: Attach, Linux, Stroustrup, Allman, GNU.
BreakBeforeBraces: Allman

# If true, ternary operators will be placed after line breaks.
BreakBeforeTernaryOperators: false

# Always break constructor initializers before commas and align the commas with the colon.
BreakConstructorInitializers: BeforeComma

# The column limit. A column limit of 0 means that there is no column limit.
ColumnLimit: 120

# A regular expression that describes comments with special meaning, which should not be split into lines or otherwise changed.
CommentPragmas: "^ *"

# If the constructor initializers don't fit on a line, put each initializer on its own line.
PackConstructorInitializers: CurrentLine

# The number of characters to use for indentation of constructor initializer lists.
ConstructorInitializerIndentWidth: 4

# Indent width for line continuations.
ContinuationIndentWidth: 4

# If true, format braced lists as best suited for C++11 braced lists.
Cpp11BracedListStyle: true

# Disables formatting at all.
DisableFormat: false

# Indent case labels one level from the switch statement.
# When false, use the same indentation level as for the switch statement.
# Switch statement body is always indented one level more than case labels.
IndentCaseLabels: false

# The number of columns to use for indentation.
IndentWidth: 4

# Indent if a function definition or declaration is wrapped after the type.
IndentWrappedFunctionNames: false

# If true, empty lines at the start of blocks are kept.
KeepEmptyLinesAtTheStartOfBlocks: true

# Language, this format style is targeted at. Possible values: None, Cpp, Java, JavaScript, Proto.
Language: Cpp

# The maximum number of consecutive empty lines to keep.
MaxEmptyLinesToKeep: 1

# The indentation used for namespaces. Possible values: None, Inner, All.
NamespaceIndentation: None

# The penalty for breaking a function call after "call(".
PenaltyBreakBeforeFirstCallParameter: 19

# The penalty for each line break introduced inside a comment.
PenaltyBreakComment: 300

# The penalty for breaking before the first <<.
PenaltyBreakFirstLessLess: 400

# The penalty for each line break introduced inside a string literal.
PenaltyBreakString: 1000

# The penalty for each character outside of the column limit.
PenaltyExcessCharacter: 1000000

# Penalty for putting the return type of a function onto its own line.
PenaltyReturnTypeOnItsOwnLine: 1000000000

# Pointer and reference alignment style. Possible values: Left, Right, Middle.
PointerAlignment: Right

# Do not sort includes, many generated headers don't appropriately include what they rely on.
SortIncludes: Never

# If true, a space may be inserted after C style casts.
SpaceAfterCStyleCast: false

# If false, spaces will be removed before assignment operators.
SpaceBeforeAssignmentOperators: true

# Defines in which cases to put a space before opening parentheses. Possible values: Never, ControlStatements, Always.
SpaceBeforeParens: ControlStatements

# If true, spaces may be inserted into '()'.
SpaceInEmptyParentheses: false

# The number of spaces before trailing line comments (// - comments).
SpacesBeforeTrailingComments: 1

# If true, spaces will be inserted after '<' and before '>' in template argument lists.
SpacesInAngles: false

# If true, spaces may be inserted into C style casts.
SpacesInCStyleCastParentheses: false

# If true, spaces are inserted inside container literals (e.g. ObjC and Javascript array and dict literals).
SpacesInContainerLiterals: false

# If true, spaces will be inserted after '(' and before ')'.
SpacesInParentheses: false

# If true, spaces will be inserted after '[' and before ']'.
SpacesInSquareBrackets: false

# Format compatible with this standard, e.g. use A<A<int> > instead of A<A<int>> for LS_Cpp03. Possible values: Cpp03, Cpp11, Auto.
Standard: Cpp11

# The number of columns used for tab stops.
TabWidth: 4

# The way to use tab characters in the resulting file. Possible values: Never, ForIndentation, Always.
UseTab: Never

# Support formatting other languages too, mostly using default configs
---
Language: Java
IndentWidth: 4
---
Language: Json
IndentWidth: 4
---
Language: ObjC
IndentWidth: 4
BreakBeforeBraces: Allman
63 changes: 63 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,69 @@ env:
BUILD_JOBS: 16

jobs:
check-coding-style:
runs-on: ubuntu-22.04

steps:
- name: Checkout code
uses: actions/checkout@v3
with:
fetch-depth: 0

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.x'

- name: Install pre-commit
run: pip install pre-commit

- name: Install clang-format
run: |
sudo apt update
sudo apt install --assume-yes clang-format

- name: Run pre-commit
run: |
# Determine the base reference for comparison
if [ "${{ github.event_name }}" == "pull_request" ]; then
BASE_REF="origin/${{ github.event.pull_request.base.ref }}"
else
BASE_REF="origin/main"
fi

echo "Running pre-commit from $BASE_REF to HEAD"
pre-commit run --from-ref $BASE_REF --to-ref HEAD

check-commit-messages:
runs-on: ubuntu-22.04

steps:
- name: Checkout code
uses: actions/checkout@v3
with:
fetch-depth: 0

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.x'

- name: Install gitlint
run: pip install gitlint

- name: Run gitlint
run: |
# Determine the base reference for comparison
if [ "${{ github.event_name }}" == "pull_request" ]; then
BASE_REF="origin/${{ github.event.pull_request.base.ref }}"
else
BASE_REF="origin/main"
fi

echo "Running gitlint from $BASE_REF to HEAD"
gitlint --commits $BASE_REF..HEAD

Vulkan-Video-Samples-linux:
strategy:
matrix:
Expand Down
11 changes: 11 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
repos:
- repo: local
hooks:
- id: check-code-format
name: Check C/C++ code formatting
entry: python scripts/check_code_format.py
language: system
files: \.(c|cc|cxx|cpp|h|hpp)$
exclude: ^include/vulkan/
pass_filenames: false
always_run: false
105 changes: 105 additions & 0 deletions scripts/check_code_format.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
#!/usr/bin/env python3

# Copyright (c) 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Script to determine if source code in Pull Request is properly formatted.
# Exits with non 0 exit code if formatting is needed.
#
# This script assumes to be invoked at the project root directory.

import subprocess
import sys
import os
import re

# Color codes for terminal output
class Colors:
RED = '\033[0;31m'
GREEN = '\033[0;32m'
NC = '\033[0m' # No Color

def run_command(cmd, capture_output=True):
"""Run a shell command and return the result."""
try:
result = subprocess.run(cmd, shell=True, capture_output=capture_output,
text=True, check=False)
return result.returncode, result.stdout, result.stderr
except Exception as e:
print(f"Error running command '{cmd}': {e}")
return 1, "", str(e)

def get_files_to_check():
"""Get list of C/C++ files to check formatting for."""
# Get files changed compared to master
returncode, stdout, stderr = run_command("git diff --name-only master")
if returncode != 0:
print(f"Error getting git diff: {stderr}")
return []

files = stdout.strip().split('\n') if stdout.strip() else []

# Filter for C/C++ files, excluding vulkan headers
cpp_extensions = re.compile(r'.*\.(cpp|cc|c\+\+|cxx|c|h|hpp)$')
vulkan_include = re.compile(r'^include/vulkan')

filtered_files = []
for file in files:
if file and cpp_extensions.match(file) and not vulkan_include.match(file):
filtered_files.append(file)

return filtered_files

def check_formatting(files):
"""Check formatting of specified files using clang-format-diff.py."""
if not files:
return True, ""

files_str = ' '.join(files)
cmd = f"git diff -U0 master -- {files_str} | python ./scripts/clang-format-diff.py -p1 -style=file"

returncode, stdout, stderr = run_command(cmd)
if returncode != 0:
print(f"Error running clang-format-diff: {stderr}")
return False, stderr

return stdout.strip() == "", stdout

def main():
"""Main function to check code formatting."""
# Change to script directory's parent (project root)
script_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(script_dir)
os.chdir(project_root)

files_to_check = get_files_to_check()

if not files_to_check:
print(f"{Colors.GREEN}No source code to check for formatting.{Colors.NC}")
return 0

print(f"Checking formatting for files: {', '.join(files_to_check)}")

is_formatted, format_output = check_formatting(files_to_check)

if is_formatted:
print(f"{Colors.GREEN}All source code in PR properly formatted.{Colors.NC}")
return 0
else:
print(f"{Colors.RED}Found formatting errors!{Colors.NC}")
print(format_output)
return 1

if __name__ == "__main__":
sys.exit(main())
Loading