<commit_before>#!/usr/bin/env python3

# Copyright 2014-2015 Open Source Robotics Foundation, 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.

from __future__ import print_function

import argparse
import os
import sys
import time
from xml.sax.saxutils import escape
from xml.sax.saxutils import quoteattr

import ament_lint_cmake.cmakelint as cmakelint


def main(argv=sys.argv[1:]):
    parser = argparse.ArgumentParser(
        description='Check CMake code against the style conventions.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        'paths',
        nargs='*',
        default=[os.curdir],
        help="The files or directories to check. For directories files named "
             "'CMakeLists.txt' and ending in '.cmake' will be considered.")
    parser.add_argument(
        '--filters',
        default="",
        help="Filters for lint_cmake, for a list of filters see: "
             "https://github.com/richq/cmake-lint/blob/master/README.md#usage")
    # not using a file handle directly
    # in order to prevent leaving an empty file when something fails early
    parser.add_argument(
        '--xunit-file',
        help='Generate a xunit compliant XML file')
    args = parser.parse_args(argv)

    if args.xunit_file:
        start_time = time.time()

    files = get_files(args.paths)
    if not files:
        print('No files found', file=sys.stderr)
        return 1

    # hook into error reporting
    DefaultError = cmakelint.Error
    report = []

    # invoke cmake lint
    cmakelint._lint_state.config = cmakelint._DEFAULT_CMAKELINTRC
    cmakelint._lint_state.SetFilters(args.filters)
    for filename in files:
        # hook into error reporting
        errors = []

        def custom_error(filename, linenumber, category, message):
            if cmakelint.ShouldPrintError(category):
                errors.append({
                    'linenumber': linenumber,
                    'category': category,
                    'message': message,
                })
            DefaultError(filename, linenumber, category, message)
        cmakelint.Error = custom_error

        cmakelint.ProcessFile(filename)
        report.append((filename, errors))
        if errors:
            print('')

    # print summary
    print('')
    if not cmakelint._lint_state.errors:
        print('No errors')
        rc = 0
    else:
        print('%d errors' % cmakelint._lint_state.errors)
        rc = 1

    # generate xunit file
    if args.xunit_file:
        folder_name = os.path.basename(os.path.dirname(args.xunit_file))
        file_name = os.path.basename(args.xunit_file)
        suffix = '.xml'
        if file_name.endswith(suffix):
            file_name = file_name[0:-len(suffix)]
        testname = '%s.%s' % (folder_name, file_name)

        xml = get_xunit_content(report, testname, time.time() - start_time)
        path = os.path.dirname(os.path.abspath(args.xunit_file))
        if not os.path.exists(path):
            os.makedirs(path)
        with open(args.xunit_file, 'w') as f:
            f.write(xml)

    return rc


def get_files(paths):
    files = []
    for path in paths:
        if os.path.isdir(path):
            for dirpath, dirnames, filenames in os.walk(path):
                # ignore folder starting with . or _
                dirnames[:] = [d for d in dirnames if d[0] not in ['.', '_']]
                dirnames.sort()

                # select files by name  / extension
                for filename in sorted(filenames):
                    fname_low = filename.lower()
                    if fname_low == 'CMakeLists.txt'.lower() or fname_low.endswith('.cmake'):
                        files.append(os.path.join(dirpath, filename))
        if os.path.isfile(path):
            files.append(path)
    return files


def get_xunit_content(report, testname, elapsed):<commit_msg>also check style of .cmake.in files<commit_after>#!/usr/bin/env python3

# Copyright 2014-2015 Open Source Robotics Foundation, 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.

from __future__ import print_function

import argparse
import os
import sys
import time
from xml.sax.saxutils import escape
from xml.sax.saxutils import quoteattr

import ament_lint_cmake.cmakelint as cmakelint


# override filename check to allow any filename to be checked
def IsValidFile(filename):
    return True

cmakelint.IsValidFile = IsValidFile


def main(argv=sys.argv[1:]):
    parser = argparse.ArgumentParser(
        description='Check CMake code against the style conventions.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        'paths',
        nargs='*',
        default=[os.curdir],
        help="The files or directories to check. For directories files named "
             "'CMakeLists.txt' and ending in '.cmake' or '.cmake.in' will be "
             "considered.")
    parser.add_argument(
        '--filters',
        default="",
        help="Filters for lint_cmake, for a list of filters see: "
             "https://github.com/richq/cmake-lint/blob/master/README.md#usage")
    # not using a file handle directly
    # in order to prevent leaving an empty file when something fails early
    parser.add_argument(
        '--xunit-file',
        help='Generate a xunit compliant XML file')
    args = parser.parse_args(argv)

    if args.xunit_file:
        start_time = time.time()

    files = get_files(args.paths)
    if not files:
        print('No files found', file=sys.stderr)
        return 1

    # hook into error reporting
    DefaultError = cmakelint.Error
    report = []

    # invoke cmake lint
    cmakelint._lint_state.config = cmakelint._DEFAULT_CMAKELINTRC
    cmakelint._lint_state.SetFilters(args.filters)
    for filename in files:
        # hook into error reporting
        errors = []

        def custom_error(filename, linenumber, category, message):
            if cmakelint.ShouldPrintError(category):
                errors.append({
                    'linenumber': linenumber,
                    'category': category,
                    'message': message,
                })
            DefaultError(filename, linenumber, category, message)
        cmakelint.Error = custom_error

        cmakelint.ProcessFile(filename)
        report.append((filename, errors))
        if errors:
            print('')

    # print summary
    print('')
    if not cmakelint._lint_state.errors:
        print('No errors')
        rc = 0
    else:
        print('%d errors' % cmakelint._lint_state.errors)
        rc = 1

    # generate xunit file
    if args.xunit_file:
        folder_name = os.path.basename(os.path.dirname(args.xunit_file))
        file_name = os.path.basename(args.xunit_file)
        suffix = '.xml'
        if file_name.endswith(suffix):
            file_name = file_name[0:-len(suffix)]
        testname = '%s.%s' % (folder_name, file_name)

        xml = get_xunit_content(report, testname, time.time() - start_time)
        path = os.path.dirname(os.path.abspath(args.xunit_file))
        if not os.path.exists(path):
            os.makedirs(path)
        with open(args.xunit_file, 'w') as f:
            f.write(xml)

    return rc


def get_files(paths):
    files = []
    for path in paths:
        if os.path.isdir(path):
            for dirpath, dirnames, filenames in os.walk(path):
                # ignore folder starting with . or _
                dirnames[:] = [d for d in dirnames if d[0] not in ['.', '_']]
                dirnames.sort()

                # select files by name  / extension
                for filename in sorted(filenames):
                    fname_low = filename.lower()
                    if (
                        fname_low == 'CMakeLists.txt'.lower() or
                        fname_low.endswith('.cmake') or
                        fname_low.endswith('.cmake.in')
                    ):
                        files.append(os.path.join(dirpath, filename))
        if os.path.isfile(path):
            files.append(path)
    return files


def get_xunit_content(report, testname, elapsed):
{'fraction_non_alphanumeric': 0.09551422319474837, 'fraction_numerical': 0.004157549234135667, 'mean_word_length': 2.296429859358096, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 10}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4926541', 'n_tokens_mistral': 2714, 'n_tokens_neox': 2591, 'n_words': 746}