Skip to content

Commit

Permalink
feat(add): initial feature (#1)
Browse files Browse the repository at this point in the history
* use clang-tidy and clang-format; organize cmake scripts

* support unit tests in src

* add a dev container; support address sanitizers
  • Loading branch information
guuzaa authored Jul 28, 2024
1 parent 2c83a04 commit 00d0df1
Show file tree
Hide file tree
Showing 27 changed files with 1,090 additions and 80 deletions.
42 changes: 42 additions & 0 deletions .clang-tidy
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
Checks: '
bugprone-*,
clang-analyzer-*,
performance-*,
portability-*,
readability-*,
-bugprone-easily-swappable-parameters,
-bugprone-implicit-widening-of-multiplication-result,
-bugprone-narrowing-conversions,
-bugprone-reserved-identifier,
-bugprone-signed-char-misuse,
-bugprone-suspicious-include,
-bugprone-unhandled-self-assignment,
-clang-analyzer-cplusplus.NewDelete,
-clang-analyzer-cplusplus.NewDeleteLeaks,
-clang-analyzer-security.insecureAPI.rand,
-clang-diagnostic-implicit-int-float-conversion,
-google-readability-avoid-underscore-in-googletest-name,
-modernize-use-nodiscard,
-readability-convert-member-functions-to-static,
-readability-identifier-length,
-readability-function-cognitive-complexity,
-readability-magic-numbers,
-readability-make-member-function-const,
-readability-qualified-auto,
-readability-redundant-access-specifiers,
-bugprone-exception-escape,
'
CheckOptions:
- { key: readability-identifier-naming.ClassCase, value: CamelCase }
- { key: readability-identifier-naming.EnumCase, value: CamelCase }
- { key: readability-identifier-naming.FunctionCase, value: CamelCase }
- { key: readability-identifier-naming.GlobalConstantCase, value: UPPER_CASE }
- { key: readability-identifier-naming.MemberCase, value: lower_case }
- { key: readability-identifier-naming.MemberSuffix, value: _ }
- { key: readability-identifier-naming.NamespaceCase, value: lower_case }
- { key: readability-identifier-naming.StructCase, value: CamelCase }
- { key: readability-identifier-naming.UnionCase, value: CamelCase }
- { key: readability-identifier-naming.VariableCase, value: lower_case }
WarningsAsErrors: '*'
HeaderFilterRegex: '/(src|tests)/include'
AnalyzeTemporaryDtors: true
15 changes: 15 additions & 0 deletions .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM mcr.microsoft.com/devcontainers/cpp:1-ubuntu-22.04

# Optionally install the cmake for vcpkg
COPY ./package.sh /tmp/

RUN chmod +x /tmp/package.sh \
&& /tmp/package.sh \
&& rm -f /tmp/package.sh

# [Optional] Uncomment this section to install additional vcpkg ports.
# RUN su vscode -c "${VCPKG_ROOT}/vcpkg install <your-port-name-here>"

# [Optional] Uncomment this section to install additional packages.
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
# && apt-get -y install --no-install-recommends <your-package-list-here>
23 changes: 23 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/cpp
{
"name": "C++",
"build": {
"dockerfile": "Dockerfile"
}

// Features to add to the dev container. More info: https://containers.dev/features.
// "features": {},

// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],

// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "gcc -v",

// Configure tool-specific properties.
// "customizations": {},

// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
}
22 changes: 22 additions & 0 deletions .devcontainer/package.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
#-------------------------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.
#-------------------------------------------------------------------------------------------------------------
#
set -e

apt-get -y update

apt-get -y install \
build-essential \
clang-12 \
clang-format-12 \
clang-tidy-12 \
cmake \
doxygen \
git \
pkg-config \
zlib1g-dev \
libelf-dev \
libdwarf-dev
12 changes: 12 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for more information:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
# https://containers.dev/guide/dependabot

version: 2
updates:
- package-ecosystem: "devcontainers"
directory: "/"
schedule:
interval: weekly
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
build*/
build/
.idea/
.vscode/

__pycache__/
31 changes: 20 additions & 11 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
cmake_minimum_required(VERSION 3.10)

# Descriptions for the project
set(PROJ_NAME cmaker)
set(VER 0.0.1)
set(CPP_STD 17)
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH})

include(Config)

project(${PROJ_NAME} VERSION ${VER} LANGUAGES C CXX)

Expand All @@ -19,18 +18,17 @@ endif(PROJECT_IS_IN_ROOT)
option(HAS_TESTS "Build and perform tests" ${PROJECT_IS_IN_ROOT})
option(HAS_BENCHES "Build and perform benches" ${PROJECT_IS_IN_ROOT})
option(HAS_EXAMPLES "Build and perform examples" ${PROJECT_IS_IN_ROOT})
option(HAS_CLANG_TOOLS "Build and use Clang tools" ${PROJECT_IS_IN_ROOT})
option(HAS_MSAN "Build and use Memory Sanitizer" ${PROJECT_IS_IN_ROOT})

# Includes
set(SRC_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/src/include)
include_directories(${SRC_INCLUDE_DIR})

add_subdirectory(${PROJECT_SOURCE_DIR}/src)

if(PROJECT_IS_IN_ROOT)
include(${CMAKE_SOURCE_DIR}/cmake/3rd_party.cmake)
endif(PROJECT_IS_IN_ROOT)

if(HAS_BENCHES)
include(3rdParty)
include_googletest()
set(CMAKE_BUILD_TYPE Release)
include_benchmark()
Expand All @@ -40,11 +38,16 @@ endif(HAS_BENCHES)

# The below needs to be built in Debug mode
set(CMAKE_BUILD_TYPE Debug)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g")
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g")

if(HAS_MSAN)
include(Sanitizers)
message(STATUS "Building Sanitizers")
define_sanitizer()
endif(HAS_MSAN)

if(HAS_TESTS)
include_benchmark()
include(3rdParty)
include_googletest()
message(STATUS "Building tests")
add_subdirectory(tests)
endif(HAS_TESTS)
Expand All @@ -53,3 +56,9 @@ if(HAS_EXAMPLES)
message(STATUS "Building examples")
add_subdirectory(examples)
endif(HAS_EXAMPLES)

if(HAS_CLANG_TOOLS)
include(ClangTools)
define_clang_tidy_targets()
define_clang_format_targets()
endif(HAS_CLANG_TOOLS)
19 changes: 10 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
# CMaker
<h1 align="center"><code>CMaker</code></h1>

CMaker is a CMake template for C/C++ that adopts a Cargo-like package layout.

## What it does
- Make a Cargo for C/C++ from CMake.
- Support C and C++
- Use [`GoogleTest`](https://github.com/google/googletest) for test
- Use [`Google Benchmark`](https://github.com/google/benchmark) for benchmark
- Designed for C and C++
- Opt for Cargo-like [`package layout`](https://doc.rust-lang.org/cargo/guide/project-layout.html) in CMake.
- Apply [`GoogleTest`](https://github.com/google/googletest) for test and [`Google Benchmark`](https://github.com/google/benchmark) for benchmark
- Use [`Clang-format` and `Clang-tidy`](https://github.com/llvm/llvm-project) for static program analysis (not ready yet)
- Use `Memory Sanitizer` for memory safety check (not ready yet)
- Use `Memory Sanitizer` for memory safety check

## Why do that
As we all know, Cargo might be the best package manager in the computer world. It helps us to create a library or an execuable as ease. In addition, it allows us to run some examples or bins of your choice by the cargo run command. However, Cargo is designed only for Rust progarmming language. If we use C++ more often, how can we configure CMake to function similarly to Cargo? `CMaker` it is.
## Why do this
In my opinion, Cargo might be the best build system in the computer world. It helps us to create a library or an execuable as ease. In addition, it allows us to run some examples or tests of your choice by the cargo run command. However, Cargo is designed only for Rust programming language. If we use C/C++ more often, how can we configure CMake to function similarly to Cargo? `CMaker` is the answer.

## License
CMaker is under [CC0 1.0 Universial](./LICENSE) license, which means it's in the world-wide public domain.
CMaker is under the [CC0 1.0 Universial](./LICENSE) license, which means it's in the world-wide public domain.
15 changes: 12 additions & 3 deletions benches/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
set(bench_dir_list "${CMAKE_CURRENT_SOURCE_DIR}/lib")

enable_testing()

foreach(bench_dir ${bench_dir_list})
file(GLOB_RECURSE bench_files "${bench_dir}/*-bench.cpp" "${bench_dir}/*-bench.cc")
get_filename_component(dir_name ${bench_dir} NAME)
file(GLOB_RECURSE bench_files "${bench_dir}/*.cpp" "${bench_dir}/*.cc")
get_filename_component(dir_name ${bench_dir} NAME_WE)

set(bench_name ${dir_name}_bench)
add_executable(${bench_name} EXCLUDE_FROM_ALL ${bench_files})
Expand All @@ -13,7 +15,14 @@ foreach(bench_dir ${bench_dir_list})
COMMENT "Running bench ${bench_name}..."
COMMAND ${bench_name}
)
set_target_properties(${bench_name} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/benches")
set_target_properties(${bench_name} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${BenchesBinaryPath}")

list(APPEND BENCH_TARGETS ${bench_name})
add_test(NAME ${bench_name} COMMAND ${bench_name})
endforeach(bench_dir ${bench_dir_list})

add_custom_target(run-benches
COMMAND ${CMAKE_CTEST_COMMAND} -C Debug --verbose
DEPENDS ${BENCH_TARGETS}
COMMENT "Building and runnig all benches..."
)
Empty file.
131 changes: 131 additions & 0 deletions build_support/run_clang_format.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
# Modified from the Apache Arrow project for the Terrier project.

import argparse
import codecs
import difflib
import fnmatch
import os
import subprocess
import sys


def has_correct_extensions(filename, extensions=(".h", ".hh", ".cc", ".cpp", ".inc")):
return filename.endswith(extensions)


def check(arguments, source_dir):
formatted_filenames = []
error = False
for directory, subdirs, filenames in os.walk(source_dir):
fullpaths = (os.path.join(directory, filename)
for filename in filenames)
source_files = [x for x in fullpaths
if has_correct_extensions(x)]
formatted_filenames.extend(
# Filter out files that match the globs in the globs file
[filename for filename in source_files
if not any((fnmatch.fnmatch(filename, exclude_glob)
for exclude_glob in exclude_globs))])

if arguments.fix:
if not arguments.quiet:
# Print out each file on its own line, but run
# clang format once for all of the files
print("\n".join(map(lambda x: "Formatting {}".format(x),
formatted_filenames)))
subprocess.check_call([arguments.clang_format_binary,
"-i"] + formatted_filenames)
else:
for filename in formatted_filenames:
if not arguments.quiet:
print("Checking {}".format(filename))
#
# Due to some incompatibilities between Python 2 and
# Python 3, there are some specific actions we take here
# to make sure the difflib.unified_diff call works.
#
# In Python 2, the call to subprocess.check_output return
# a 'str' type. In Python 3, however, the call returns a
# 'bytes' type unless the 'encoding' argument is
# specified. Unfortunately, the 'encoding' argument is not
# in the Python 2 API. We could do an if/else here based
# on the version of Python we are running, but it's more
# straightforward to read the file in binary and do utf-8
# conversion. In Python 2, it's just converting string
# types to unicode types, whereas in Python 3 it's
# converting bytes types to utf-8 encoded str types. This
# approach ensures that the arguments to
# difflib.unified_diff are acceptable string types in both
# Python 2 and Python 3.
with open(filename, "rb") as reader:
# Run clang-format and capture its output
formatted = subprocess.check_output(
[arguments.clang_format_binary,
filename])
formatted = codecs.decode(formatted, "utf-8")
# Read the original file
original = codecs.decode(reader.read(), "utf-8")
# Run the equivalent of diff -u
diff = list(difflib.unified_diff(
original.splitlines(True),
formatted.splitlines(True),
fromfile=filename,
tofile="{} (after clang format)".format(
filename)))
if diff:
print("{} had clang-format style issues".format(filename))
# Print out the diff to stderr
error = True
sys.stderr.writelines(diff)
return error


if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Runs clang format on all of the source "
"files. If --fix is specified, and compares the output "
"with the existing file, outputting a unifiied diff if "
"there are any necessary changes")
parser.add_argument("clang_format_binary",
help="Path to the clang-format binary")
parser.add_argument("exclude_globs",
help="Filename containing globs for files "
"that should be excluded from the checks")
parser.add_argument("--source_dirs",
help="Comma-separated root directories of the code")
parser.add_argument("--fix", default=False,
action="store_true",
help="If specified, will re-format the source "
"code instead of comparing the re-formatted "
"output, defaults to %(default)s")
parser.add_argument("--quiet", default=False,
action="store_true",
help="If specified, only print errors")

args = parser.parse_args()

had_err = False
exclude_globs = [line.strip() for line in open(args.exclude_globs)]
for source_dir in args.source_dirs.split(','):
if len(source_dir) > 0:
had_err = had_err or check(args, source_dir)

sys.exit(1 if had_err else 0)
Loading

0 comments on commit 00d0df1

Please sign in to comment.