build: Enforce gofmt on all Go sources

Gofmt returns with an exit code of 0 even when it's not happy with the
formatting of the source files. The recommendation is to check the
emptyness of the output [1].

[1] https://github.com/golang/go/issues/24230

https://github.com/containers/toolbox/pull/983
This commit is contained in:
Debarshi Ray 2022-01-11 02:15:41 +01:00
parent 3f9ee19a66
commit afbed7a057
2 changed files with 42 additions and 0 deletions

View file

@ -1,6 +1,8 @@
go_build_wrapper_file = files('go-build-wrapper')
go_build_wrapper_program = find_program('go-build-wrapper')
meson_go_fmt_program = find_program('meson_go_fmt.py')
sources = files(
'toolbox.go',
'cmd/create.go',
@ -66,4 +68,5 @@ if shellcheck.found()
test('shellcheck go-build-wrapper', shellcheck, args: [go_build_wrapper_file])
endif
test('go fmt', meson_go_fmt_program, args: [meson.current_source_dir()])
test('toolbox go unit tests', go, args: ['test', '-v', './...'], workdir: meson.current_source_dir())

39
src/meson_go_fmt.py Normal file
View file

@ -0,0 +1,39 @@
#!/usr/bin/env python3
#
# Copyright © 2022 Red Hat 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.
#
import subprocess
import sys
if len(sys.argv) != 2:
print('{}: wrong arguments'.format(sys.argv[0]), file=sys.stderr)
print('Usage: {} [SOURCE DIR]'.format(sys.argv[0]), file=sys.stderr)
sys.exit(1)
source_dir = sys.argv[1]
try:
gofmt = subprocess.run(['gofmt', '-d', source_dir], capture_output=True, check=True)
except subprocess.CalledProcessError as e:
print('{}: gofmt returned non-zero exit status {}'.format(sys.argv[0], e.returncode), file=sys.stderr)
sys.exit(e.returncode)
if gofmt.stdout:
diff = gofmt.stdout.decode()
print(diff)
sys.exit(1)
sys.exit(0)