Skip to content

Commit 0ea525f

Browse files
committed
Move mx clangformat command to sdk suite.
1 parent a8d89df commit 0ea525f

File tree

4 files changed

+115
-74
lines changed

4 files changed

+115
-74
lines changed

sulong/.clang-format .clang-format

File renamed without changes.

sdk/mx.sdk/mx_sdk.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#
2-
# Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved.
2+
# Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved.
33
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44
#
55
# The Universal Permissive License (UPL), Version 1.0
@@ -47,6 +47,7 @@
4747
import mx_sdk_vm
4848
import mx_sdk_vm_impl
4949
import mx_sdk_benchmark # pylint: disable=unused-import
50+
import mx_sdk_clangformat # pylint: disable=unused-import
5051
import datetime
5152
from mx_bisect import define_bisect_default_build_steps
5253
from mx_bisect_strategy import BuildStepsGraalVMStrategy

sdk/mx.sdk/mx_sdk_clangformat.py

+112
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
#
2+
# Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
3+
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+
#
5+
# The Universal Permissive License (UPL), Version 1.0
6+
#
7+
# Subject to the condition set forth below, permission is hereby granted to any
8+
# person obtaining a copy of this software, associated documentation and/or
9+
# data (collectively the "Software"), free of charge and under any and all
10+
# copyright rights in the Software, and any and all patent rights owned or
11+
# freely licensable by each licensor hereunder covering either (i) the
12+
# unmodified Software as contributed to or provided by such licensor, or (ii)
13+
# the Larger Works (as defined below), to deal in both
14+
#
15+
# (a) the Software, and
16+
#
17+
# (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
18+
# one is included with the Software each a "Larger Work" to which the Software
19+
# is contributed by such licensors),
20+
#
21+
# without restriction, including without limitation the rights to copy, create
22+
# derivative works of, display, perform, and distribute the Software and make,
23+
# use, sell, offer for sale, import, export, have made, and have sold the
24+
# Software and the Larger Work(s), and to sublicense the foregoing rights on
25+
# either these or other terms.
26+
#
27+
# This license is subject to the following condition:
28+
#
29+
# The above copyright notice and either this complete permission notice or at a
30+
# minimum a reference to the UPL must be included in all copies or substantial
31+
# portions of the Software.
32+
#
33+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
39+
# SOFTWARE.
40+
#
41+
42+
import mx
43+
44+
import os.path
45+
import subprocess
46+
import sys
47+
48+
from argparse import ArgumentParser
49+
50+
_suite = mx.suite('sdk')
51+
52+
@mx.command(_suite.name, "clangformat")
53+
def clangformat(args=None):
54+
""" Runs clang-format on C/C++ files in native projects of the primary suite """
55+
parser = ArgumentParser(prog='mx clangformat')
56+
parser.add_argument('--with-projects', action='store_true', help='check native projects. Defaults to true unless a path is specified.')
57+
parser.add_argument('--primary', action='store_true', help='limit checks to primary suite')
58+
parser.add_argument('paths', metavar='path', nargs='*', help='check given paths')
59+
args = parser.parse_args(args)
60+
paths = [(p, "<cmd-line-argument>") for p in args.paths]
61+
62+
if not paths or args.with_projects:
63+
paths += [(p.dir, p.name) for p in mx.projects(limit_to_primary=args.primary) if p.isNativeProject() and getattr(p, "clangFormat", True)]
64+
65+
# ensure LLVM_TOOLCHAIN is built
66+
mx.command_function('build')(['--dependencies', 'LLVM_TOOLCHAIN'])
67+
clangFormat = os.path.join(mx.dependency('LLVM_TOOLCHAIN', fatalIfMissing=True).get_output(), 'bin', mx.exe_suffix('clang-format'))
68+
69+
error = False
70+
for f, reason in paths:
71+
if not checkCFiles(clangFormat, f, reason):
72+
error = True
73+
if error:
74+
mx.log_error("found formatting errors!")
75+
sys.exit(-1)
76+
77+
78+
def checkCFiles(clangFormat, target, reason):
79+
error = False
80+
files_to_check = []
81+
if os.path.isfile(target):
82+
files_to_check.append(target)
83+
else:
84+
for path, _, files in os.walk(target):
85+
for f in files:
86+
if f.endswith('.c') or f.endswith('.cpp') or f.endswith('.h') or f.endswith('.hpp'):
87+
files_to_check.append(os.path.join(path, f))
88+
if not files_to_check:
89+
mx.logv("clang-format: no files found {} ({})".format(target, reason))
90+
return True
91+
mx.logv("clang-format: checking {} ({}, {} files)".format(target, reason, len(files_to_check)))
92+
for f in files_to_check:
93+
if not checkCFile(clangFormat, f):
94+
error = True
95+
return not error
96+
97+
98+
def checkCFile(clangFormat, targetFile):
99+
mx.logvv(" checking file " + targetFile)
100+
""" Checks the formatting of a C file and returns True if the formatting is okay """
101+
formatCommand = [clangFormat, targetFile]
102+
formattedContent = subprocess.check_output(formatCommand).decode().splitlines()
103+
with open(targetFile) as f:
104+
originalContent = f.read().splitlines()
105+
if not formattedContent == originalContent:
106+
# modify the file to the right format
107+
subprocess.check_output(formatCommand + ['-i'])
108+
mx.log('\n'.join(formattedContent))
109+
mx.log('\nmodified formatting in {0} to the format above'.format(targetFile))
110+
mx.logv("command: " + " ".join(formatCommand))
111+
return False
112+
return True

sulong/mx.sulong/mx_sulong_gate.py

+1-73
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,10 @@
2929
#
3030
import argparse
3131
import os
32-
import sys
33-
import subprocess
3432
from argparse import ArgumentParser
3533

3634
import mx
3735
import mx_subst
38-
import mx_sulong
3936
import mx_unittest
4037

4138
from mx_gate import Task, add_gate_runner, add_gate_argument
@@ -185,11 +182,8 @@ def _unittest(title, test_suite, tags=None, testClasses=None, unittestArgs=None,
185182
if mx.checkcopyrights(['--primary']) != 0:
186183
t.abort('Copyright errors found. Please run "mx checkcopyrights --primary -- --fix" to fix them.')
187184

188-
with Task('BuildLLVMorg', tasks, tags=['style', 'clangformat']) as t:
189-
# needed for clang-format
190-
if t: build_llvm_org(args)
191185
with Task('ClangFormat', tasks, tags=['style', 'clangformat']) as t:
192-
if t: clangformat([])
186+
if t: mx.command_function('clangformat')([])
193187
# Folders not containing tests: options, services, util
194188
_unittest('Benchmarks', 'SULONG_SHOOTOUT_TEST_SUITE', description="Language Benchmark game tests", testClasses=['ShootoutsSuite'], tags=['benchmarks', 'sulongMisc'])
195189
_unittest('Types', 'SULONG_TEST', description="Test floating point arithmetic", testClasses=['com.oracle.truffle.llvm.tests.types.floating.'], tags=['type', 'sulongMisc', 'sulongCoverage'])
@@ -280,69 +274,3 @@ def runLLVMUnittests(unittest_runner):
280274
build_args = ['--language:llvm'] + java_run_props
281275
unittest_runner(['com.oracle.truffle.llvm.tests.interop', '--force-builder-on-cp', '--run-args'] + run_args +
282276
['--build-args', '--initialize-at-build-time'] + build_args)
283-
284-
285-
def build_llvm_org(args=None):
286-
defaultBuildArgs = ['-p']
287-
if not args.no_warning_as_error:
288-
defaultBuildArgs += ['--warning-as-error']
289-
mx.command_function('build')(defaultBuildArgs + ['--project', 'LLVM_TOOLCHAIN'] + args.extra_build_args)
290-
291-
292-
@mx.command(_suite.name, "clangformat")
293-
def clangformat(args=None):
294-
""" Runs clang-format on C/C++ files in native projects of the primary suite """
295-
parser = ArgumentParser(prog='mx clangformat')
296-
parser.add_argument('--with-projects', action='store_true', help='check native projects. Defaults to true unless a path is specified.')
297-
parser.add_argument('paths', metavar='path', nargs='*', help='check given paths')
298-
args = parser.parse_args(args)
299-
paths = [(p, "<cmd-line-argument>") for p in args.paths]
300-
301-
if not paths or args.with_projects:
302-
paths += [(p.dir, p.name) for p in mx.projects(limit_to_primary=True) if p.isNativeProject() and getattr(p, "clangFormat", True)]
303-
304-
error = False
305-
for f, reason in paths:
306-
if not checkCFiles(f, reason):
307-
error = True
308-
if error:
309-
mx.log_error("found formatting errors!")
310-
sys.exit(-1)
311-
312-
313-
def checkCFiles(target, reason):
314-
error = False
315-
files_to_check = []
316-
if os.path.isfile(target):
317-
files_to_check.append(target)
318-
else:
319-
for path, _, files in os.walk(target):
320-
for f in files:
321-
if f.endswith('.c') or f.endswith('.cpp') or f.endswith('.h') or f.endswith('.hpp'):
322-
files_to_check.append(os.path.join(path, f))
323-
if not files_to_check:
324-
mx.logv("clang-format: no files found {} ({})".format(target, reason))
325-
return True
326-
mx.logv("clang-format: checking {} ({}, {} files)".format(target, reason, len(files_to_check)))
327-
for f in files_to_check:
328-
if not checkCFile(f):
329-
error = True
330-
return not error
331-
332-
333-
def checkCFile(targetFile):
334-
mx.logvv(" checking file " + targetFile)
335-
""" Checks the formatting of a C file and returns True if the formatting is okay """
336-
clangFormat = mx_sulong.findBundledLLVMProgram('clang-format')
337-
formatCommand = [clangFormat, targetFile]
338-
formattedContent = mx_sulong._decode(subprocess.check_output(formatCommand)).splitlines()
339-
with open(targetFile) as f:
340-
originalContent = f.read().splitlines()
341-
if not formattedContent == originalContent:
342-
# modify the file to the right format
343-
subprocess.check_output(formatCommand + ['-i'])
344-
mx.log('\n'.join(formattedContent))
345-
mx.log('\nmodified formatting in {0} to the format above'.format(targetFile))
346-
mx.logv("command: " + " ".join(formatCommand))
347-
return False
348-
return True

0 commit comments

Comments
 (0)