From 031b284c8a15ad4b28f81b113a9f2018af5b1da6 Mon Sep 17 00:00:00 2001 From: Mike Brown Date: Fri, 21 Apr 2017 11:39:29 -0500 Subject: [PATCH 1/3] Squashed 'hack/repro-infra/' content from commit 684e550 git-subtree-dir: hack/repro-infra git-subtree-split: 684e550a2f006dbe3cf3b3d481d3f19217b228f7 --- .gitignore | 6 + .travis.yml | 17 ++ LICENSE | 201 +++++++++++++++++ README.md | 61 ++++++ WORKSPACE | 1 + defs/BUILD | 8 + defs/build.bzl | 119 +++++++++++ defs/deb.bzl | 34 +++ defs/gcs_uploader.py | 71 ++++++ defs/go.bzl | 100 +++++++++ verify/README.md | 52 +++++ verify/boilerplate/BUILD | 3 + verify/boilerplate/boilerplate.Dockerfile.txt | 14 ++ verify/boilerplate/boilerplate.Makefile.txt | 14 ++ verify/boilerplate/boilerplate.go.txt | 16 ++ verify/boilerplate/boilerplate.py | 202 ++++++++++++++++++ verify/boilerplate/boilerplate.py.txt | 14 ++ verify/boilerplate/boilerplate.sh.txt | 14 ++ verify/boilerplate/boilerplate_test.py | 52 +++++ verify/boilerplate/test/fail.go | 19 ++ verify/boilerplate/test/fail.py | 17 ++ verify/boilerplate/test/pass.go | 17 ++ verify/boilerplate/test/pass.py | 17 ++ verify/go-tools/verify-gofmt.sh | 34 +++ verify/go-tools/verify-gometalinter.sh | 31 +++ verify/go-tools/verify-govet.sh | 20 ++ verify/verify-boilerplate.sh | 56 +++++ verify/verify-go-src.sh | 111 ++++++++++ 28 files changed, 1321 insertions(+) create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 WORKSPACE create mode 100644 defs/BUILD create mode 100644 defs/build.bzl create mode 100644 defs/deb.bzl create mode 100644 defs/gcs_uploader.py create mode 100644 defs/go.bzl create mode 100644 verify/README.md create mode 100644 verify/boilerplate/BUILD create mode 100644 verify/boilerplate/boilerplate.Dockerfile.txt create mode 100644 verify/boilerplate/boilerplate.Makefile.txt create mode 100644 verify/boilerplate/boilerplate.go.txt create mode 100755 verify/boilerplate/boilerplate.py create mode 100644 verify/boilerplate/boilerplate.py.txt create mode 100644 verify/boilerplate/boilerplate.sh.txt create mode 100644 verify/boilerplate/boilerplate_test.py create mode 100644 verify/boilerplate/test/fail.go create mode 100644 verify/boilerplate/test/fail.py create mode 100644 verify/boilerplate/test/pass.go create mode 100644 verify/boilerplate/test/pass.py create mode 100755 verify/go-tools/verify-gofmt.sh create mode 100755 verify/go-tools/verify-gometalinter.sh create mode 100755 verify/go-tools/verify-govet.sh create mode 100755 verify/verify-boilerplate.sh create mode 100755 verify/verify-go-src.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..bf5a9a8c7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +/bazel-* diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..4d6e1c91a --- /dev/null +++ b/.travis.yml @@ -0,0 +1,17 @@ +language: go + +go: + - master + +before_install: + - go get -u github.com/alecthomas/gometalinter + +install: + - gometalinter --install + +build: + - true + +script: + - verify/verify-boilerplate.sh --rootdir="${TRAVIS_BUILD_DIR}" -v + - verify/verify-go-src.sh --rootdir "${TRAVIS_BUILD_DIR}" -v diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..8dada3eda --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/README.md b/README.md new file mode 100644 index 000000000..7139318d8 --- /dev/null +++ b/README.md @@ -0,0 +1,61 @@ +# Kubernetes repository infrastructure + +This repository contains repository infrastructure tools for use in +`kubernetes` and `kubernetes-incubator` repositories. Examples: + +- Boilerplate verification +- Go source code quality verification +- Golang build infrastructure + +--- + +## Using this repository + +This repository can be used via some golang "vendoring" mechanism +(such as glide), or it can be used via +[git subtree](http://git.kernel.org/cgit/git/git.git/plain/contrib/subtree/git-subtree.txt). + +### Using "vendoring" + +The exact mechanism to pull in this repository will vary depending on +the tool you use. However, unless you end up having this repository +at the root of your project's repository you wll probably need to +make sure you use the `--rootdir` command line parameter to let the +`verify-boilerplate.sh` know its location, eg: + + verify-boilerplate.sh --rootdir=/home/myrepo + +### Using `git subtree` + +When using the git subtree mechanism, this repository should be placed in the +top level of your project. + +To add `repo-infra` to your repository, use the following commands from the +root directory of **your** repository. + +First, add a git remote for the `repo-infra` repository: + +``` +$ git remote add repo-infra git://github.com/kubernetes/repo-infra +``` + +This is not strictly necessary, but reduces the typing required for subsequent +commands. + +Next, use `git subtree add` to create a new subtree in the `repo-infra` +directory within your project: + +``` +$ git subtree add -P repo-infra repo-infra master --squash +``` + +After this command, you will have: + +1. A `repo-infra` directory in your project containing the content of **this** + project +2. 2 new commits in the active branch: + 1. A commit that squashes the git history of the `repo-infra` project + 2. A merge commit whose ancestors are: + 1. The `HEAD` of the branch prior to when you ran `git subtree add` + 2. The commit containing the squashed `repo-infra` commits + diff --git a/WORKSPACE b/WORKSPACE new file mode 100644 index 000000000..f0a53cae4 --- /dev/null +++ b/WORKSPACE @@ -0,0 +1 @@ +workspace(name = "io_kubernetes_build") diff --git a/defs/BUILD b/defs/BUILD new file mode 100644 index 000000000..70e0e955b --- /dev/null +++ b/defs/BUILD @@ -0,0 +1,8 @@ +package(default_visibility = ["//visibility:public"]) + +py_binary( + name = "gcs_uploader", + srcs = [ + "gcs_uploader.py", + ], +) diff --git a/defs/build.bzl b/defs/build.bzl new file mode 100644 index 000000000..254707415 --- /dev/null +++ b/defs/build.bzl @@ -0,0 +1,119 @@ +def _gcs_upload_impl(ctx): + output_lines = [] + for t in ctx.attr.data: + label = str(t.label) + upload_path=ctx.attr.upload_paths.get(label, "") + for f in t.files: + output_lines.append("%s\t%s" % (f.short_path, upload_path)) + + ctx.file_action( + output = ctx.outputs.targets, + content = "\n".join(output_lines), + ) + + ctx.file_action( + content = "%s --manifest %s --root $PWD -- $@" % ( + ctx.attr.uploader.files_to_run.executable.short_path, + ctx.outputs.targets.short_path, + ), + output = ctx.outputs.executable, + executable = True, + ) + + return struct( + runfiles = ctx.runfiles( + files = ctx.files.data + ctx.files.uploader + + [ctx.info_file, ctx.version_file, ctx.outputs.targets] + ) + ) + +# Adds an executable rule to upload the specified artifacts to GCS. +# +# The keys in upload_paths must match the elaborated targets exactly; i.e., +# one must specify "//foo/bar:bar" and not just "//foo/bar". +# +# Both the upload_paths and the path supplied on the commandline can include +# Python format strings which will be replaced by values from the workspace status, +# e.g. gs://my-bucket-{BUILD_USER}/stash/{STABLE_BUILD_SCM_REVISION} +gcs_upload = rule( + attrs = { + "data": attr.label_list( + mandatory = True, + allow_files = True, + ), + "uploader": attr.label( + default = Label("//defs:gcs_uploader"), + allow_files = True, + ), + # TODO: combine with 'data' when label_keyed_string_dict is supported in Bazel + "upload_paths": attr.string_dict( + allow_empty = True, + ), + }, + executable = True, + outputs = { + "targets": "%{name}-targets.txt", + }, + implementation = _gcs_upload_impl, +) + +# Computes the md5sum of the provided src file, saving it in a file named 'name'. +def md5sum(name, src, visibility=None): + native.genrule( + name = name + "_genmd5sum", + srcs = [src], + outs = [name], + # Currently each go_binary target has two outputs (the binary and the library), + # so we hash both but only save the hash for the binary. + cmd = "for f in $(SRCS); do if command -v md5 >/dev/null; then md5 -q $$f>$@; else md5sum $$f | awk '{print $$1}' > $@; fi; done", + message = "Computing md5sum", + visibility = visibility, +) + +# Computes the sha1sum of the provided src file, saving it in a file named 'name'. +def sha1sum(name, src, visibility=None): + native.genrule( + name = name + "_gensha1sum", + srcs = [src], + outs = [name], + # Currently each go_binary target has two outputs (the binary and the library), + # so we hash both but only save the hash for the binary. + cmd = "command -v sha1sum >/dev/null && cmd=sha1sum || cmd='shasum -a1'; for f in $(SRCS); do $$cmd $$f | awk '{print $$1}' > $@; done", + message = "Computing sha1sum", + visibility = visibility, +) + +# Creates 3+N rules based on the provided targets: +# * A filegroup with just the provided targets (named 'name') +# * A filegroup containing all of the md5 and sha1 hash files ('name-hashes') +# * A filegroup containing both of the above ('name-and-hashes') +# * All of the necessary md5sum and sha1sum rules +def release_filegroup(name, srcs, visibility=None): + hashes = [] + for src in srcs: + parts = src.split(":") + if len(parts) > 1: + basename = parts[1] + else: + basename = src.split("/")[-1] + + md5sum(name=basename + ".md5", src=src, visibility=visibility) + hashes.append(basename + ".md5") + sha1sum(name=basename + ".sha1", src=src, visibility=visibility) + hashes.append(basename + ".sha1") + + native.filegroup( + name = name, + srcs = srcs, + visibility = visibility, + ) + native.filegroup( + name = name + "-hashes", + srcs = hashes, + visibility = visibility, + ) + native.filegroup( + name = name + "-and-hashes", + srcs = [name, name + "-hashes"], + visibility = visibility, + ) diff --git a/defs/deb.bzl b/defs/deb.bzl new file mode 100644 index 000000000..f67aa1471 --- /dev/null +++ b/defs/deb.bzl @@ -0,0 +1,34 @@ +load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar", "pkg_deb") + +KUBERNETES_AUTHORS = "Kubernetes Authors " + +KUBERNETES_HOMEPAGE = "http://kubernetes.io" + +def k8s_deb(name, depends = [], description = ""): + pkg_deb( + name = name, + architecture = "amd64", + data = name + "-data", + depends = depends, + description = description, + homepage = KUBERNETES_HOMEPAGE, + maintainer = KUBERNETES_AUTHORS, + package = name, + version = "1.6.0-alpha", + ) + +def deb_data(name, data = []): + deps = [] + for i, info in enumerate(data): + dname = "%s-deb-data-%s" % (name, i) + deps += [dname] + pkg_tar( + name = dname, + files = info["files"], + mode = info["mode"], + package_dir = info["dir"], + ) + pkg_tar( + name = name + "-data", + deps = deps, + ) diff --git a/defs/gcs_uploader.py b/defs/gcs_uploader.py new file mode 100644 index 000000000..e68bb7cd7 --- /dev/null +++ b/defs/gcs_uploader.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python + +# Copyright 2016 The Kubernetes Authors. +# +# 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 argparse +import atexit +import os +import os.path +import shutil +import subprocess +import sys +import tempfile + +def _workspace_status_dict(root): + d = {} + for f in ("stable-status.txt", "volatile-status.txt"): + with open(os.path.join(root, f)) as info_file: + for info_line in info_file: + info_line = info_line.strip("\n") + key, value = info_line.split(" ") + d[key] = value + return d + +def main(argv): + scratch = tempfile.mkdtemp(prefix="bazel-gcs.") + atexit.register(lambda: shutil.rmtree(scratch)) + + workspace_status = _workspace_status_dict(argv.root) + gcs_path = argv.gcs_path.format(**workspace_status) + + with open(argv.manifest) as manifest: + for artifact in manifest: + artifact = artifact.strip("\n") + src_file, dest_dir = artifact.split("\t") + dest_dir = dest_dir.format(**workspace_status) + scratch_dest_dir = os.path.join(scratch, dest_dir) + try: + os.makedirs(scratch_dest_dir) + except (OSError): + # skip directory already exists errors + pass + + src = os.path.join(argv.root, src_file) + dest = os.path.join(scratch_dest_dir, os.path.basename(src_file)) + os.symlink(src, dest) + + ret = subprocess.call(["gsutil", "-m", "rsync", "-C", "-r", scratch, gcs_path]) + print "Uploaded to %s" % gcs_path + sys.exit(ret) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Upload build targets to GCS.') + + parser.add_argument("--manifest", required=True, help="path to manifest of targets") + parser.add_argument("--root", required=True, help="path to root of workspace") + parser.add_argument("gcs_path", help="path in gcs to push targets") + + main(parser.parse_args()) diff --git a/defs/go.bzl b/defs/go.bzl new file mode 100644 index 000000000..dd13e1043 --- /dev/null +++ b/defs/go.bzl @@ -0,0 +1,100 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_env_attrs") + +go_filetype = ["*.go"] + +def _compute_genrule_variables(resolved_srcs, resolved_outs): + variables = {"SRCS": cmd_helper.join_paths(" ", resolved_srcs), + "OUTS": cmd_helper.join_paths(" ", resolved_outs)} + if len(resolved_srcs) == 1: + variables["<"] = list(resolved_srcs)[0].path + if len(resolved_outs) == 1: + variables["@"] = list(resolved_outs)[0].path + return variables + +def _go_sources_aspect_impl(target, ctx): + transitive_sources = set(target.go_sources) + for dep in ctx.rule.attr.deps: + transitive_sources = transitive_sources | dep.transitive_sources + return struct(transitive_sources = transitive_sources) + +go_sources_aspect = aspect( + attr_aspects = ["deps"], + implementation = _go_sources_aspect_impl, +) + +def _compute_genrule_command(ctx): + cmd = [ + 'set -e', + # setup GOROOT + 'export GOROOT=$$(pwd)/' + ctx.file.go_tool.dirname + '/..', + # setup main GOPATH + 'export GOPATH=/tmp/gopath', + 'export GO_WORKSPACE=$${GOPATH}/src/' + ctx.attr.go_prefix.go_prefix, + 'mkdir -p $${GO_WORKSPACE%/*}', + 'ln -s $$(pwd) $${GO_WORKSPACE}', + # setup genfile GOPATH + 'export GENGOPATH=/tmp/gengopath', + 'export GENGO_WORKSPACE=$${GENGOPATH}/src/' + ctx.attr.go_prefix.go_prefix, + 'mkdir -p $${GENGO_WORKSPACE%/*}', + 'ln -s $$(pwd)/$(GENDIR) $${GENGO_WORKSPACE}', + # drop into WORKSPACE + 'export GOPATH=$${GOPATH}:$${GENGOPATH}', + 'cd $${GO_WORKSPACE}', + # execute user command + ctx.attr.cmd.strip(' \t\n\r'), + ] + return '\n'.join(cmd) + +def _go_genrule_impl(ctx): + all_srcs = set(ctx.files.go_src) + label_dict = {} + + for dep in ctx.attr.go_deps: + all_srcs = all_srcs | dep.transitive_sources + + for dep in ctx.attr.srcs: + all_srcs = all_srcs | dep.files + label_dict[dep.label] = dep.files + + cmd = _compute_genrule_command(ctx) + + resolved_inputs, argv, runfiles_manifests = ctx.resolve_command( + command=cmd, + attribute="cmd", + expand_locations=True, + make_variables=_compute_genrule_variables(all_srcs, set(ctx.outputs.outs)), + tools=ctx.attr.tools, + label_dict=label_dict + ) + + ctx.action( + inputs = list(all_srcs) + resolved_inputs, + outputs = ctx.outputs.outs, + env = ctx.configuration.default_shell_env, + command = argv, + progress_message = "%s %s" % (ctx.attr.message, ctx), + mnemonic = "GoGenrule", + ) + +# We have codegen procedures that depend on the "go/*" stdlib packages +# and thus depend on executing with a valid GOROOT and GOPATH containing +# some amount transitive go src of dependencies. This go_genrule enables +# the creation of these sandboxes. +go_genrule = rule( + attrs = go_env_attrs + { + "srcs": attr.label_list(allow_files = True), + "tools": attr.label_list( + cfg = "host", + allow_files = True, + ), + "outs": attr.output_list(mandatory = True), + "cmd": attr.string(mandatory = True), + "go_deps": attr.label_list( + aspects = [go_sources_aspect], + ), + "message": attr.string(), + "executable": attr.bool(default = False), + }, + output_to_genfiles = True, + implementation = _go_genrule_impl, +) diff --git a/verify/README.md b/verify/README.md new file mode 100644 index 000000000..6eca4ece1 --- /dev/null +++ b/verify/README.md @@ -0,0 +1,52 @@ +# Verification scripts + +Collection of scripts that verifies that a project meets requirements set for kubernetes related projects. The scripts are to be invoked depending on the needs via CI tooling, such as Travis CI. See main Readme file on how to integrate the repo-infra in your project. + +The scripts are currently being migrated from the main kubernetes repository. If your project requires additional set of verifications, consider creating an issue/PR on repo-infra to avoid code duplication across multiple projects. + +If repo-infra is integrated at the root of your project as git submodule at path: `/repo-infra`, +then scripts can be invoked as `repo-infra/verify/verify-*.sh` + +travis.yaml example: + +``` +dist: trusty + +os: +- linux + +language: go + +go: +- 1.8 + +before_install: +- go get -u github.com/alecthomas/gometalinter + +install: +- gometalinter --install + +script: +- repo-infra/verify/verify-go-src.sh -v +- repo-infra/verify/verify-boilerplate.sh +# OR with vendoring +# - vendor/github.com/kubernetes/repo-infra/verify-go-src.sh --rootdir=$(pwd) -v +``` + +## Verify boilerplate + +Verifies that the boilerplate for various formats (go files, Makefile, etc.) is included in each file: `verify-boilerplate.sh`. + +## Verify go source code + +Runs a set of scripts on the go source code excluding vendored files: `verify-go-src.sh`. Expects `gometalinter` tooling installed (see travis file above) + +With git submodule from your repo root: `repo-infra/verify/verify-go-src.sh -v` + +With vendoring: `vendor/repo-infra/verify/verify-go-src.sh -v --rootdir $(pwd)` + +Checks include: + +1. gofmt +2. gometalinter +3. govet diff --git a/verify/boilerplate/BUILD b/verify/boilerplate/BUILD new file mode 100644 index 000000000..c405bde04 --- /dev/null +++ b/verify/boilerplate/BUILD @@ -0,0 +1,3 @@ +package(default_visibility = ["//visibility:public"]) + +exports_files(glob(["*.txt"])) diff --git a/verify/boilerplate/boilerplate.Dockerfile.txt b/verify/boilerplate/boilerplate.Dockerfile.txt new file mode 100644 index 000000000..384f325ab --- /dev/null +++ b/verify/boilerplate/boilerplate.Dockerfile.txt @@ -0,0 +1,14 @@ +# Copyright YEAR The Kubernetes Authors. +# +# 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. + diff --git a/verify/boilerplate/boilerplate.Makefile.txt b/verify/boilerplate/boilerplate.Makefile.txt new file mode 100644 index 000000000..384f325ab --- /dev/null +++ b/verify/boilerplate/boilerplate.Makefile.txt @@ -0,0 +1,14 @@ +# Copyright YEAR The Kubernetes Authors. +# +# 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. + diff --git a/verify/boilerplate/boilerplate.go.txt b/verify/boilerplate/boilerplate.go.txt new file mode 100644 index 000000000..59e740c1e --- /dev/null +++ b/verify/boilerplate/boilerplate.go.txt @@ -0,0 +1,16 @@ +/* +Copyright YEAR The Kubernetes Authors. + +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. +*/ + diff --git a/verify/boilerplate/boilerplate.py b/verify/boilerplate/boilerplate.py new file mode 100755 index 000000000..3507c214c --- /dev/null +++ b/verify/boilerplate/boilerplate.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python + +# Copyright 2015 The Kubernetes Authors. +# +# 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 difflib +import glob +import json +import mmap +import os +import re +import sys +from datetime import date + +parser = argparse.ArgumentParser() +parser.add_argument( + "filenames", + help="list of files to check, all files if unspecified", + nargs='*') + +# Rootdir defaults to the directory **above** the repo-infra dir. +rootdir = os.path.dirname(__file__) + "/../../../" +rootdir = os.path.abspath(rootdir) +parser.add_argument( + "--rootdir", default=rootdir, help="root directory to examine") + +default_boilerplate_dir = os.path.join(rootdir, "repo-infra/verify/boilerplate") +parser.add_argument( + "--boilerplate-dir", default=default_boilerplate_dir) + +parser.add_argument( + "-v", "--verbose", + help="give verbose output regarding why a file does not pass", + action="store_true") + +args = parser.parse_args() + +verbose_out = sys.stderr if args.verbose else open("/dev/null", "w") + +def get_refs(): + refs = {} + + for path in glob.glob(os.path.join(args.boilerplate_dir, "boilerplate.*.txt")): + extension = os.path.basename(path).split(".")[1] + + ref_file = open(path, 'r') + ref = ref_file.read().splitlines() + ref_file.close() + refs[extension] = ref + + return refs + +def file_passes(filename, refs, regexs): + try: + f = open(filename, 'r') + except Exception as exc: + print("Unable to open %s: %s" % (filename, exc), file=verbose_out) + return False + + data = f.read() + f.close() + + basename = os.path.basename(filename) + extension = file_extension(filename) + if extension != "": + ref = refs[extension] + else: + ref = refs[basename] + + # remove build tags from the top of Go files + if extension == "go": + p = regexs["go_build_constraints"] + (data, found) = p.subn("", data, 1) + + # remove shebang from the top of shell files + if extension == "sh" or extension == "py": + p = regexs["shebang"] + (data, found) = p.subn("", data, 1) + + data = data.splitlines() + + # if our test file is smaller than the reference it surely fails! + if len(ref) > len(data): + print('File %s smaller than reference (%d < %d)' % + (filename, len(data), len(ref)), + file=verbose_out) + return False + + # trim our file to the same number of lines as the reference file + data = data[:len(ref)] + + p = regexs["year"] + for d in data: + if p.search(d): + print('File %s is missing the year' % filename, file=verbose_out) + return False + + # Replace all occurrences of the regex "CURRENT_YEAR|...|2016|2015|2014" with "YEAR" + p = regexs["date"] + for i, d in enumerate(data): + (data[i], found) = p.subn('YEAR', d) + if found != 0: + break + + # if we don't match the reference at this point, fail + if ref != data: + print("Header in %s does not match reference, diff:" % filename, file=verbose_out) + if args.verbose: + print(file=verbose_out) + for line in difflib.unified_diff(ref, data, 'reference', filename, lineterm=''): + print(line, file=verbose_out) + print(file=verbose_out) + return False + + return True + +def file_extension(filename): + return os.path.splitext(filename)[1].split(".")[-1].lower() + +skipped_dirs = ['Godeps', 'third_party', '_gopath', '_output', '.git', + 'cluster/env.sh', 'vendor', 'test/e2e/generated/bindata.go', + 'repo-infra/verify/boilerplate/test', '.glide'] + +def normalize_files(files): + newfiles = [] + for pathname in files: + if any(x in pathname for x in skipped_dirs): + continue + newfiles.append(pathname) + for i, pathname in enumerate(newfiles): + if not os.path.isabs(pathname): + newfiles[i] = os.path.join(args.rootdir, pathname) + return newfiles + +def get_files(extensions): + files = [] + if len(args.filenames) > 0: + files = args.filenames + else: + for root, dirs, walkfiles in os.walk(args.rootdir): + # don't visit certain dirs. This is just a performance improvement + # as we would prune these later in normalize_files(). But doing it + # cuts down the amount of filesystem walking we do and cuts down + # the size of the file list + for d in skipped_dirs: + if d in dirs: + dirs.remove(d) + + for name in walkfiles: + pathname = os.path.join(root, name) + files.append(pathname) + + files = normalize_files(files) + + outfiles = [] + for pathname in files: + basename = os.path.basename(pathname) + extension = file_extension(pathname) + if extension in extensions or basename in extensions: + outfiles.append(pathname) + return outfiles + +def get_regexs(): + regexs = {} + # Search for "YEAR" which exists in the boilerplate, but shouldn't in the real thing + regexs["year"] = re.compile( 'YEAR' ) + # dates can be 2014, 2015, 2016, ..., CURRENT_YEAR, company holder names can be anything + years = range(2014, date.today().year + 1) + regexs["date"] = re.compile( '(%s)' % "|".join(map(lambda l: str(l), years)) ) + # strip // +build \n\n build constraints + regexs["go_build_constraints"] = re.compile(r"^(// \+build.*\n)+\n", re.MULTILINE) + # strip #!.* from shell scripts + regexs["shebang"] = re.compile(r"^(#!.*\n)\n*", re.MULTILINE) + return regexs + +def main(): + regexs = get_regexs() + refs = get_refs() + filenames = get_files(refs.keys()) + + for filename in filenames: + if not file_passes(filename, refs, regexs): + print(filename, file=sys.stdout) + + return 0 + +if __name__ == "__main__": + sys.exit(main()) diff --git a/verify/boilerplate/boilerplate.py.txt b/verify/boilerplate/boilerplate.py.txt new file mode 100644 index 000000000..384f325ab --- /dev/null +++ b/verify/boilerplate/boilerplate.py.txt @@ -0,0 +1,14 @@ +# Copyright YEAR The Kubernetes Authors. +# +# 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. + diff --git a/verify/boilerplate/boilerplate.sh.txt b/verify/boilerplate/boilerplate.sh.txt new file mode 100644 index 000000000..384f325ab --- /dev/null +++ b/verify/boilerplate/boilerplate.sh.txt @@ -0,0 +1,14 @@ +# Copyright YEAR The Kubernetes Authors. +# +# 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. + diff --git a/verify/boilerplate/boilerplate_test.py b/verify/boilerplate/boilerplate_test.py new file mode 100644 index 000000000..b8d5b8e9e --- /dev/null +++ b/verify/boilerplate/boilerplate_test.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +# Copyright 2016 The Kubernetes Authors. +# +# 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 boilerplate +import unittest +import StringIO +import os +import sys + +class TestBoilerplate(unittest.TestCase): + """ + Note: run this test from the hack/boilerplate directory. + + $ python -m unittest boilerplate_test + """ + + def test_boilerplate(self): + os.chdir("test/") + + class Args(object): + def __init__(self): + self.filenames = [] + self.rootdir = "." + self.boilerplate_dir = "../" + self.verbose = True + + # capture stdout + old_stdout = sys.stdout + sys.stdout = StringIO.StringIO() + + boilerplate.args = Args() + ret = boilerplate.main() + + output = sorted(sys.stdout.getvalue().split()) + + sys.stdout = old_stdout + + self.assertEquals( + output, ['././fail.go', '././fail.py']) diff --git a/verify/boilerplate/test/fail.go b/verify/boilerplate/test/fail.go new file mode 100644 index 000000000..59e79d659 --- /dev/null +++ b/verify/boilerplate/test/fail.go @@ -0,0 +1,19 @@ +/* +Copyright 2014 The Kubernetes Authors. + +fail + +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. +*/ + +package main diff --git a/verify/boilerplate/test/fail.py b/verify/boilerplate/test/fail.py new file mode 100644 index 000000000..cbdd06ff8 --- /dev/null +++ b/verify/boilerplate/test/fail.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python + +# Copyright 2015 The Kubernetes Authors. +# +# failed +# +# 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. diff --git a/verify/boilerplate/test/pass.go b/verify/boilerplate/test/pass.go new file mode 100644 index 000000000..6aa631178 --- /dev/null +++ b/verify/boilerplate/test/pass.go @@ -0,0 +1,17 @@ +/* +Copyright 2014 The Kubernetes Authors. + +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. +*/ + +package main diff --git a/verify/boilerplate/test/pass.py b/verify/boilerplate/test/pass.py new file mode 100644 index 000000000..5b7ce29a2 --- /dev/null +++ b/verify/boilerplate/test/pass.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python + +# Copyright 2015 The Kubernetes Authors. +# +# 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. + +True diff --git a/verify/go-tools/verify-gofmt.sh b/verify/go-tools/verify-gofmt.sh new file mode 100755 index 000000000..1f09fd2b1 --- /dev/null +++ b/verify/go-tools/verify-gofmt.sh @@ -0,0 +1,34 @@ +#!/bin/bash +# Copyright 2017 The Kubernetes Authors. +# +# 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. + +set -o errexit +set -o nounset +set -o pipefail + +find_files() { + find . -not \( \ + \( \ + -wholename '*/vendor/*' \ + \) -prune \ + \) -name '*.go' +} + +GOFMT="gofmt -s" +bad_files=$(find_files | xargs $GOFMT -l) +if [[ -n "${bad_files}" ]]; then + echo "!!! '$GOFMT' needs to be run on the following files: " + echo "${bad_files}" + exit 1 +fi diff --git a/verify/go-tools/verify-gometalinter.sh b/verify/go-tools/verify-gometalinter.sh new file mode 100755 index 000000000..b47d596c6 --- /dev/null +++ b/verify/go-tools/verify-gometalinter.sh @@ -0,0 +1,31 @@ +#!/bin/bash +# Copyright 2017 The Kubernetes Authors. +# +# 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. + +set -o errexit +set -o nounset +set -o pipefail + +for d in $(find . -type d -not -iwholename '*.git*' -a -not -iname '.tool' -a -not -iwholename '*vendor*'); do + gometalinter --deadline=50s --vendor \ + --cyclo-over=50 --dupl-threshold=100 \ + --exclude=".*should not use dot imports \(golint\)$" \ + --disable-all \ + --enable=vet \ + --enable=deadcode \ + --enable=golint \ + --enable=vetshadow \ + --enable=gocyclo \ + --tests "${d}" +done diff --git a/verify/go-tools/verify-govet.sh b/verify/go-tools/verify-govet.sh new file mode 100755 index 000000000..5f690bd31 --- /dev/null +++ b/verify/go-tools/verify-govet.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# Copyright 2017 The Kubernetes Authors. +# +# 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. + +set -o errexit +set -o nounset +set -o pipefail + +go vet -v $(go list ./... | grep -v /vendor/) diff --git a/verify/verify-boilerplate.sh b/verify/verify-boilerplate.sh new file mode 100755 index 000000000..0168d336e --- /dev/null +++ b/verify/verify-boilerplate.sh @@ -0,0 +1,56 @@ +#!/bin/bash + +# Copyright 2014 The Kubernetes Authors. +# +# 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. + +set -o errexit +set -o nounset +set -o pipefail + +# This script is intended to be used via subtree in a top-level directory: +# / +# repo-infra/ +# verify/ + +REPO_ROOT=$(dirname "${BASH_SOURCE}")/../.. + +boilerDir="${REPO_ROOT}/repo-infra/verify/boilerplate" +boiler="${boilerDir}/boilerplate.py" + +files_need_boilerplate=($(${boiler} "$@")) + +# Run boilerplate.py unit tests +unitTestOut="$(mktemp)" +trap cleanup EXIT +cleanup() { + rm "${unitTestOut}" +} + +pushd "${boilerDir}" >/dev/null +if ! python -m unittest boilerplate_test 2>"${unitTestOut}"; then + echo "boilerplate_test.py failed" + echo + cat "${unitTestOut}" + exit 1 +fi +popd >/dev/null + +# Run boilerplate check +if [[ ${#files_need_boilerplate[@]} -gt 0 ]]; then + for file in "${files_need_boilerplate[@]}"; do + echo "Boilerplate header is wrong for: ${file}" + done + + exit 1 +fi diff --git a/verify/verify-go-src.sh b/verify/verify-go-src.sh new file mode 100755 index 000000000..edf73dd7b --- /dev/null +++ b/verify/verify-go-src.sh @@ -0,0 +1,111 @@ +#!/bin/bash + +# Copyright 2017 The Kubernetes Authors. +# +# 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. + +set -o errexit +set -o nounset +set -o pipefail + +# This script is intended to be used via subtree in a top-level directory: +# / +# repo-infra/ +# verify/ +# Or via vendoring and passing root directory as vendor/repo-infra/verify-*.sh --rootdir **full path to your repo dir** +# / +# vendor/ +# repo-infra/ +# ... +# + + +SILENT=true +REPO_ROOT=$(dirname "${BASH_SOURCE}")/../.. + +# Convert long opts to short ones to read through getopts +for arg in "$@"; do + shift + case "$arg" in + "--rootdir") set -- "$@" "-r";; + *) + set -- "$@" "$arg" + ;; + esac +done + +OPTIND=1 +while getopts "vr:" opt; do + case ${opt} in + v) + SILENT=false + ;; + r) + REPO_ROOT=${OPTARG} + ;; + \?) + echo "Invalid flag: -${OPTARG}" >&2 + exit 1 + ;; + esac +done + +shift "$(($OPTIND-1))" + +echo "Working directory: ${REPO_ROOT}" + +GO_TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/go-tools" + +function run-cmd { + if ${SILENT}; then + "$@" &> /dev/null + else + "$@" + fi +} + +# Some useful colors. +if [[ -z "${color_start-}" ]]; then + declare -r color_start="\033[" + declare -r color_red="${color_start}0;31m" + declare -r color_yellow="${color_start}0;33m" + declare -r color_green="${color_start}0;32m" + declare -r color_norm="${color_start}0m" +fi + +function run-checks { + local -r pattern=$1 + local -r runner=$2 + + for t in $(ls ${pattern}) + do + echo -e "Verifying ${t}" + local start=$(date +%s) + cd $REPO_ROOT && run-cmd "${runner}" "${t}" && tr=$? || tr=$? + local elapsed=$(($(date +%s) - ${start})) + if [[ ${tr} -eq 0 ]]; then + echo -e "${color_green}SUCCESS${color_norm} ${t}\t${elapsed}s" + else + echo -e "${color_red}FAILED${color_norm} ${t}\t${elapsed}s" + ret=1 + fi + done +} + +if ${SILENT} ; then + echo "Running in the silent mode, run with -v if you want to see script logs." +fi + +ret=0 +run-checks "${GO_TOOLS_DIR}/*.sh" bash +exit ${ret} From f9e02affccd51702191e5312665a16045ffef8ab Mon Sep 17 00:00:00 2001 From: Mike Brown Date: Fri, 21 Apr 2017 12:44:25 -0500 Subject: [PATCH 2/3] adds boilerplate test to verify; cleanup boilerplate on a few files Signed-off-by: Mike Brown --- Makefile | 21 ++++++++++++++++++- cmd/cri-containerd/cri_containerd.go | 2 +- cmd/cri-containerd/options/options.go | 2 +- hack/lint.sh | 2 +- .../verify/boilerplate/boilerplate.py | 10 ++++----- 5 files changed, 28 insertions(+), 9 deletions(-) diff --git a/Makefile b/Makefile index 60bff994a..8a9446fb5 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,17 @@ +# Copyright 2017 The Kubernetes Authors. +# +# 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. + GO ?= go EPOCH_TEST_COMMIT ?= f2925f58acc259c4b894353f5fc404bdeb40028e PROJECT := github.com/kubernetes-incubator/cri-containerd @@ -25,7 +39,7 @@ ifndef GOPATH $(error GOPATH is not set) endif -verify: lint gofmt +verify: lint gofmt boiler lint: check-gopath @echo "checking lint" @@ -35,6 +49,10 @@ gofmt: @echo "checking gofmt" @./hack/verify-gofmt.sh +boiler: + @echo "checking boilerplate" + @./hack/repo-infra/verify/verify-boilerplate.sh + cri-containerd: check-gopath $(GO) build -o $(BUILD_DIR)/$@ \ $(PROJECT)/cmd/cri-containerd @@ -72,6 +90,7 @@ install.tools: .install.gitvalidation .install.gometalinter .PHONY: \ binaries \ + boiler \ clean \ default \ gofmt \ diff --git a/cmd/cri-containerd/cri_containerd.go b/cmd/cri-containerd/cri_containerd.go index 8917af8aa..175341506 100644 --- a/cmd/cri-containerd/cri_containerd.go +++ b/cmd/cri-containerd/cri_containerd.go @@ -1,5 +1,5 @@ /* -Copyright 2017 The Kubernetes Authors All rights reserved. +Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/cmd/cri-containerd/options/options.go b/cmd/cri-containerd/options/options.go index 7838f118e..6fa0c5b94 100644 --- a/cmd/cri-containerd/options/options.go +++ b/cmd/cri-containerd/options/options.go @@ -1,5 +1,5 @@ /* -Copyright 2017 The Kubernetes Authors All rights reserved. +Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/hack/lint.sh b/hack/lint.sh index 9b10f6883..4f3326ac1 100755 --- a/hack/lint.sh +++ b/hack/lint.sh @@ -11,7 +11,7 @@ # 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.#!/usr/bin/env bash +# limitations under the License. set -o errexit set -o nounset diff --git a/hack/repo-infra/verify/boilerplate/boilerplate.py b/hack/repo-infra/verify/boilerplate/boilerplate.py index 3507c214c..8f60c8ae5 100755 --- a/hack/repo-infra/verify/boilerplate/boilerplate.py +++ b/hack/repo-infra/verify/boilerplate/boilerplate.py @@ -32,13 +32,13 @@ parser.add_argument( help="list of files to check, all files if unspecified", nargs='*') -# Rootdir defaults to the directory **above** the repo-infra dir. -rootdir = os.path.dirname(__file__) + "/../../../" +# Rootdir defaults to the directory **above** the hack/repo-infra dir. +rootdir = os.path.dirname(__file__) + "/../../../../" rootdir = os.path.abspath(rootdir) parser.add_argument( "--rootdir", default=rootdir, help="root directory to examine") -default_boilerplate_dir = os.path.join(rootdir, "repo-infra/verify/boilerplate") +default_boilerplate_dir = os.path.join(rootdir, "hack/repo-infra/verify/boilerplate") parser.add_argument( "--boilerplate-dir", default=default_boilerplate_dir) @@ -131,9 +131,9 @@ def file_passes(filename, refs, regexs): def file_extension(filename): return os.path.splitext(filename)[1].split(".")[-1].lower() -skipped_dirs = ['Godeps', 'third_party', '_gopath', '_output', '.git', +skipped_dirs = ['Godeps', 'third_party', '_gopath', '_output', '.git', 'cluster/env.sh', 'vendor', 'test/e2e/generated/bindata.go', - 'repo-infra/verify/boilerplate/test', '.glide'] + 'hack/repo-infra/verify/boilerplate/test', '.glide'] def normalize_files(files): newfiles = [] From 8243c1feb7955032595f06794bac9f2e89e42188 Mon Sep 17 00:00:00 2001 From: Mike Brown Date: Fri, 21 Apr 2017 14:11:01 -0500 Subject: [PATCH 3/3] removing unused repo-infra files; updating README.md Signed-off-by: Mike Brown --- hack/repo-infra/.travis.yml | 17 --- hack/repo-infra/README.md | 60 +-------- hack/repo-infra/WORKSPACE | 1 - hack/repo-infra/defs/BUILD | 8 -- hack/repo-infra/defs/build.bzl | 119 ------------------ hack/repo-infra/defs/deb.bzl | 34 ----- hack/repo-infra/defs/gcs_uploader.py | 71 ----------- hack/repo-infra/defs/go.bzl | 100 --------------- hack/repo-infra/verify/README.md | 37 ++---- .../verify/go-tools/verify-gofmt.sh | 34 ----- .../verify/go-tools/verify-gometalinter.sh | 31 ----- .../verify/go-tools/verify-govet.sh | 20 --- hack/repo-infra/verify/verify-go-src.sh | 111 ---------------- 13 files changed, 8 insertions(+), 635 deletions(-) delete mode 100644 hack/repo-infra/.travis.yml delete mode 100644 hack/repo-infra/WORKSPACE delete mode 100644 hack/repo-infra/defs/BUILD delete mode 100644 hack/repo-infra/defs/build.bzl delete mode 100644 hack/repo-infra/defs/deb.bzl delete mode 100644 hack/repo-infra/defs/gcs_uploader.py delete mode 100644 hack/repo-infra/defs/go.bzl delete mode 100755 hack/repo-infra/verify/go-tools/verify-gofmt.sh delete mode 100755 hack/repo-infra/verify/go-tools/verify-gometalinter.sh delete mode 100755 hack/repo-infra/verify/go-tools/verify-govet.sh delete mode 100755 hack/repo-infra/verify/verify-go-src.sh diff --git a/hack/repo-infra/.travis.yml b/hack/repo-infra/.travis.yml deleted file mode 100644 index 4d6e1c91a..000000000 --- a/hack/repo-infra/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -language: go - -go: - - master - -before_install: - - go get -u github.com/alecthomas/gometalinter - -install: - - gometalinter --install - -build: - - true - -script: - - verify/verify-boilerplate.sh --rootdir="${TRAVIS_BUILD_DIR}" -v - - verify/verify-go-src.sh --rootdir "${TRAVIS_BUILD_DIR}" -v diff --git a/hack/repo-infra/README.md b/hack/repo-infra/README.md index 7139318d8..2163521ad 100644 --- a/hack/repo-infra/README.md +++ b/hack/repo-infra/README.md @@ -1,61 +1,3 @@ # Kubernetes repository infrastructure -This repository contains repository infrastructure tools for use in -`kubernetes` and `kubernetes-incubator` repositories. Examples: - -- Boilerplate verification -- Go source code quality verification -- Golang build infrastructure - ---- - -## Using this repository - -This repository can be used via some golang "vendoring" mechanism -(such as glide), or it can be used via -[git subtree](http://git.kernel.org/cgit/git/git.git/plain/contrib/subtree/git-subtree.txt). - -### Using "vendoring" - -The exact mechanism to pull in this repository will vary depending on -the tool you use. However, unless you end up having this repository -at the root of your project's repository you wll probably need to -make sure you use the `--rootdir` command line parameter to let the -`verify-boilerplate.sh` know its location, eg: - - verify-boilerplate.sh --rootdir=/home/myrepo - -### Using `git subtree` - -When using the git subtree mechanism, this repository should be placed in the -top level of your project. - -To add `repo-infra` to your repository, use the following commands from the -root directory of **your** repository. - -First, add a git remote for the `repo-infra` repository: - -``` -$ git remote add repo-infra git://github.com/kubernetes/repo-infra -``` - -This is not strictly necessary, but reduces the typing required for subsequent -commands. - -Next, use `git subtree add` to create a new subtree in the `repo-infra` -directory within your project: - -``` -$ git subtree add -P repo-infra repo-infra master --squash -``` - -After this command, you will have: - -1. A `repo-infra` directory in your project containing the content of **this** - project -2. 2 new commits in the active branch: - 1. A commit that squashes the git history of the `repo-infra` project - 2. A merge commit whose ancestors are: - 1. The `HEAD` of the branch prior to when you ran `git subtree add` - 2. The commit containing the squashed `repo-infra` commits - +This is a subtree pulled from githu.com/kubernetes/repo-infra diff --git a/hack/repo-infra/WORKSPACE b/hack/repo-infra/WORKSPACE deleted file mode 100644 index f0a53cae4..000000000 --- a/hack/repo-infra/WORKSPACE +++ /dev/null @@ -1 +0,0 @@ -workspace(name = "io_kubernetes_build") diff --git a/hack/repo-infra/defs/BUILD b/hack/repo-infra/defs/BUILD deleted file mode 100644 index 70e0e955b..000000000 --- a/hack/repo-infra/defs/BUILD +++ /dev/null @@ -1,8 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -py_binary( - name = "gcs_uploader", - srcs = [ - "gcs_uploader.py", - ], -) diff --git a/hack/repo-infra/defs/build.bzl b/hack/repo-infra/defs/build.bzl deleted file mode 100644 index 254707415..000000000 --- a/hack/repo-infra/defs/build.bzl +++ /dev/null @@ -1,119 +0,0 @@ -def _gcs_upload_impl(ctx): - output_lines = [] - for t in ctx.attr.data: - label = str(t.label) - upload_path=ctx.attr.upload_paths.get(label, "") - for f in t.files: - output_lines.append("%s\t%s" % (f.short_path, upload_path)) - - ctx.file_action( - output = ctx.outputs.targets, - content = "\n".join(output_lines), - ) - - ctx.file_action( - content = "%s --manifest %s --root $PWD -- $@" % ( - ctx.attr.uploader.files_to_run.executable.short_path, - ctx.outputs.targets.short_path, - ), - output = ctx.outputs.executable, - executable = True, - ) - - return struct( - runfiles = ctx.runfiles( - files = ctx.files.data + ctx.files.uploader + - [ctx.info_file, ctx.version_file, ctx.outputs.targets] - ) - ) - -# Adds an executable rule to upload the specified artifacts to GCS. -# -# The keys in upload_paths must match the elaborated targets exactly; i.e., -# one must specify "//foo/bar:bar" and not just "//foo/bar". -# -# Both the upload_paths and the path supplied on the commandline can include -# Python format strings which will be replaced by values from the workspace status, -# e.g. gs://my-bucket-{BUILD_USER}/stash/{STABLE_BUILD_SCM_REVISION} -gcs_upload = rule( - attrs = { - "data": attr.label_list( - mandatory = True, - allow_files = True, - ), - "uploader": attr.label( - default = Label("//defs:gcs_uploader"), - allow_files = True, - ), - # TODO: combine with 'data' when label_keyed_string_dict is supported in Bazel - "upload_paths": attr.string_dict( - allow_empty = True, - ), - }, - executable = True, - outputs = { - "targets": "%{name}-targets.txt", - }, - implementation = _gcs_upload_impl, -) - -# Computes the md5sum of the provided src file, saving it in a file named 'name'. -def md5sum(name, src, visibility=None): - native.genrule( - name = name + "_genmd5sum", - srcs = [src], - outs = [name], - # Currently each go_binary target has two outputs (the binary and the library), - # so we hash both but only save the hash for the binary. - cmd = "for f in $(SRCS); do if command -v md5 >/dev/null; then md5 -q $$f>$@; else md5sum $$f | awk '{print $$1}' > $@; fi; done", - message = "Computing md5sum", - visibility = visibility, -) - -# Computes the sha1sum of the provided src file, saving it in a file named 'name'. -def sha1sum(name, src, visibility=None): - native.genrule( - name = name + "_gensha1sum", - srcs = [src], - outs = [name], - # Currently each go_binary target has two outputs (the binary and the library), - # so we hash both but only save the hash for the binary. - cmd = "command -v sha1sum >/dev/null && cmd=sha1sum || cmd='shasum -a1'; for f in $(SRCS); do $$cmd $$f | awk '{print $$1}' > $@; done", - message = "Computing sha1sum", - visibility = visibility, -) - -# Creates 3+N rules based on the provided targets: -# * A filegroup with just the provided targets (named 'name') -# * A filegroup containing all of the md5 and sha1 hash files ('name-hashes') -# * A filegroup containing both of the above ('name-and-hashes') -# * All of the necessary md5sum and sha1sum rules -def release_filegroup(name, srcs, visibility=None): - hashes = [] - for src in srcs: - parts = src.split(":") - if len(parts) > 1: - basename = parts[1] - else: - basename = src.split("/")[-1] - - md5sum(name=basename + ".md5", src=src, visibility=visibility) - hashes.append(basename + ".md5") - sha1sum(name=basename + ".sha1", src=src, visibility=visibility) - hashes.append(basename + ".sha1") - - native.filegroup( - name = name, - srcs = srcs, - visibility = visibility, - ) - native.filegroup( - name = name + "-hashes", - srcs = hashes, - visibility = visibility, - ) - native.filegroup( - name = name + "-and-hashes", - srcs = [name, name + "-hashes"], - visibility = visibility, - ) diff --git a/hack/repo-infra/defs/deb.bzl b/hack/repo-infra/defs/deb.bzl deleted file mode 100644 index f67aa1471..000000000 --- a/hack/repo-infra/defs/deb.bzl +++ /dev/null @@ -1,34 +0,0 @@ -load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar", "pkg_deb") - -KUBERNETES_AUTHORS = "Kubernetes Authors " - -KUBERNETES_HOMEPAGE = "http://kubernetes.io" - -def k8s_deb(name, depends = [], description = ""): - pkg_deb( - name = name, - architecture = "amd64", - data = name + "-data", - depends = depends, - description = description, - homepage = KUBERNETES_HOMEPAGE, - maintainer = KUBERNETES_AUTHORS, - package = name, - version = "1.6.0-alpha", - ) - -def deb_data(name, data = []): - deps = [] - for i, info in enumerate(data): - dname = "%s-deb-data-%s" % (name, i) - deps += [dname] - pkg_tar( - name = dname, - files = info["files"], - mode = info["mode"], - package_dir = info["dir"], - ) - pkg_tar( - name = name + "-data", - deps = deps, - ) diff --git a/hack/repo-infra/defs/gcs_uploader.py b/hack/repo-infra/defs/gcs_uploader.py deleted file mode 100644 index e68bb7cd7..000000000 --- a/hack/repo-infra/defs/gcs_uploader.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2016 The Kubernetes Authors. -# -# 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 argparse -import atexit -import os -import os.path -import shutil -import subprocess -import sys -import tempfile - -def _workspace_status_dict(root): - d = {} - for f in ("stable-status.txt", "volatile-status.txt"): - with open(os.path.join(root, f)) as info_file: - for info_line in info_file: - info_line = info_line.strip("\n") - key, value = info_line.split(" ") - d[key] = value - return d - -def main(argv): - scratch = tempfile.mkdtemp(prefix="bazel-gcs.") - atexit.register(lambda: shutil.rmtree(scratch)) - - workspace_status = _workspace_status_dict(argv.root) - gcs_path = argv.gcs_path.format(**workspace_status) - - with open(argv.manifest) as manifest: - for artifact in manifest: - artifact = artifact.strip("\n") - src_file, dest_dir = artifact.split("\t") - dest_dir = dest_dir.format(**workspace_status) - scratch_dest_dir = os.path.join(scratch, dest_dir) - try: - os.makedirs(scratch_dest_dir) - except (OSError): - # skip directory already exists errors - pass - - src = os.path.join(argv.root, src_file) - dest = os.path.join(scratch_dest_dir, os.path.basename(src_file)) - os.symlink(src, dest) - - ret = subprocess.call(["gsutil", "-m", "rsync", "-C", "-r", scratch, gcs_path]) - print "Uploaded to %s" % gcs_path - sys.exit(ret) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='Upload build targets to GCS.') - - parser.add_argument("--manifest", required=True, help="path to manifest of targets") - parser.add_argument("--root", required=True, help="path to root of workspace") - parser.add_argument("gcs_path", help="path in gcs to push targets") - - main(parser.parse_args()) diff --git a/hack/repo-infra/defs/go.bzl b/hack/repo-infra/defs/go.bzl deleted file mode 100644 index dd13e1043..000000000 --- a/hack/repo-infra/defs/go.bzl +++ /dev/null @@ -1,100 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_env_attrs") - -go_filetype = ["*.go"] - -def _compute_genrule_variables(resolved_srcs, resolved_outs): - variables = {"SRCS": cmd_helper.join_paths(" ", resolved_srcs), - "OUTS": cmd_helper.join_paths(" ", resolved_outs)} - if len(resolved_srcs) == 1: - variables["<"] = list(resolved_srcs)[0].path - if len(resolved_outs) == 1: - variables["@"] = list(resolved_outs)[0].path - return variables - -def _go_sources_aspect_impl(target, ctx): - transitive_sources = set(target.go_sources) - for dep in ctx.rule.attr.deps: - transitive_sources = transitive_sources | dep.transitive_sources - return struct(transitive_sources = transitive_sources) - -go_sources_aspect = aspect( - attr_aspects = ["deps"], - implementation = _go_sources_aspect_impl, -) - -def _compute_genrule_command(ctx): - cmd = [ - 'set -e', - # setup GOROOT - 'export GOROOT=$$(pwd)/' + ctx.file.go_tool.dirname + '/..', - # setup main GOPATH - 'export GOPATH=/tmp/gopath', - 'export GO_WORKSPACE=$${GOPATH}/src/' + ctx.attr.go_prefix.go_prefix, - 'mkdir -p $${GO_WORKSPACE%/*}', - 'ln -s $$(pwd) $${GO_WORKSPACE}', - # setup genfile GOPATH - 'export GENGOPATH=/tmp/gengopath', - 'export GENGO_WORKSPACE=$${GENGOPATH}/src/' + ctx.attr.go_prefix.go_prefix, - 'mkdir -p $${GENGO_WORKSPACE%/*}', - 'ln -s $$(pwd)/$(GENDIR) $${GENGO_WORKSPACE}', - # drop into WORKSPACE - 'export GOPATH=$${GOPATH}:$${GENGOPATH}', - 'cd $${GO_WORKSPACE}', - # execute user command - ctx.attr.cmd.strip(' \t\n\r'), - ] - return '\n'.join(cmd) - -def _go_genrule_impl(ctx): - all_srcs = set(ctx.files.go_src) - label_dict = {} - - for dep in ctx.attr.go_deps: - all_srcs = all_srcs | dep.transitive_sources - - for dep in ctx.attr.srcs: - all_srcs = all_srcs | dep.files - label_dict[dep.label] = dep.files - - cmd = _compute_genrule_command(ctx) - - resolved_inputs, argv, runfiles_manifests = ctx.resolve_command( - command=cmd, - attribute="cmd", - expand_locations=True, - make_variables=_compute_genrule_variables(all_srcs, set(ctx.outputs.outs)), - tools=ctx.attr.tools, - label_dict=label_dict - ) - - ctx.action( - inputs = list(all_srcs) + resolved_inputs, - outputs = ctx.outputs.outs, - env = ctx.configuration.default_shell_env, - command = argv, - progress_message = "%s %s" % (ctx.attr.message, ctx), - mnemonic = "GoGenrule", - ) - -# We have codegen procedures that depend on the "go/*" stdlib packages -# and thus depend on executing with a valid GOROOT and GOPATH containing -# some amount transitive go src of dependencies. This go_genrule enables -# the creation of these sandboxes. -go_genrule = rule( - attrs = go_env_attrs + { - "srcs": attr.label_list(allow_files = True), - "tools": attr.label_list( - cfg = "host", - allow_files = True, - ), - "outs": attr.output_list(mandatory = True), - "cmd": attr.string(mandatory = True), - "go_deps": attr.label_list( - aspects = [go_sources_aspect], - ), - "message": attr.string(), - "executable": attr.bool(default = False), - }, - output_to_genfiles = True, - implementation = _go_genrule_impl, -) diff --git a/hack/repo-infra/verify/README.md b/hack/repo-infra/verify/README.md index 6eca4ece1..aa418d1e4 100644 --- a/hack/repo-infra/verify/README.md +++ b/hack/repo-infra/verify/README.md @@ -1,13 +1,13 @@ # Verification scripts -Collection of scripts that verifies that a project meets requirements set for kubernetes related projects. The scripts are to be invoked depending on the needs via CI tooling, such as Travis CI. See main Readme file on how to integrate the repo-infra in your project. +Collection of scripts that verifies that a project meets requirements set for kubernetes related projects. The scripts are to be invoked depending on the needs via CI tooling, such as Travis CI. See main Readme file on how to integrate the repo-infra in your project. -The scripts are currently being migrated from the main kubernetes repository. If your project requires additional set of verifications, consider creating an issue/PR on repo-infra to avoid code duplication across multiple projects. +The scripts are currently being migrated from the main kubernetes repository. If your project requires additional set of verifications, consider creating an issue/PR on repo-infra to avoid code duplication across multiple projects. -If repo-infra is integrated at the root of your project as git submodule at path: `/repo-infra`, -then scripts can be invoked as `repo-infra/verify/verify-*.sh` +If repo-infra is integrated at the root of your project as git submodule at path: `hack/repo-infra`, +then scripts can be invoked as `hack/repo-infra/verify/verify-*.sh` -travis.yaml example: +travis.yaml example: ``` dist: trusty @@ -20,33 +20,10 @@ language: go go: - 1.8 -before_install: -- go get -u github.com/alecthomas/gometalinter - -install: -- gometalinter --install - script: -- repo-infra/verify/verify-go-src.sh -v -- repo-infra/verify/verify-boilerplate.sh -# OR with vendoring -# - vendor/github.com/kubernetes/repo-infra/verify-go-src.sh --rootdir=$(pwd) -v +- hack/repo-infra/verify/verify-boilerplate.sh ``` ## Verify boilerplate -Verifies that the boilerplate for various formats (go files, Makefile, etc.) is included in each file: `verify-boilerplate.sh`. - -## Verify go source code - -Runs a set of scripts on the go source code excluding vendored files: `verify-go-src.sh`. Expects `gometalinter` tooling installed (see travis file above) - -With git submodule from your repo root: `repo-infra/verify/verify-go-src.sh -v` - -With vendoring: `vendor/repo-infra/verify/verify-go-src.sh -v --rootdir $(pwd)` - -Checks include: - -1. gofmt -2. gometalinter -3. govet +Verifies that the boilerplate for various formats (go files, Makefile, etc.) is included in each file: `verify-boilerplate.sh`. diff --git a/hack/repo-infra/verify/go-tools/verify-gofmt.sh b/hack/repo-infra/verify/go-tools/verify-gofmt.sh deleted file mode 100755 index 1f09fd2b1..000000000 --- a/hack/repo-infra/verify/go-tools/verify-gofmt.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/bash -# Copyright 2017 The Kubernetes Authors. -# -# 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. - -set -o errexit -set -o nounset -set -o pipefail - -find_files() { - find . -not \( \ - \( \ - -wholename '*/vendor/*' \ - \) -prune \ - \) -name '*.go' -} - -GOFMT="gofmt -s" -bad_files=$(find_files | xargs $GOFMT -l) -if [[ -n "${bad_files}" ]]; then - echo "!!! '$GOFMT' needs to be run on the following files: " - echo "${bad_files}" - exit 1 -fi diff --git a/hack/repo-infra/verify/go-tools/verify-gometalinter.sh b/hack/repo-infra/verify/go-tools/verify-gometalinter.sh deleted file mode 100755 index b47d596c6..000000000 --- a/hack/repo-infra/verify/go-tools/verify-gometalinter.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash -# Copyright 2017 The Kubernetes Authors. -# -# 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. - -set -o errexit -set -o nounset -set -o pipefail - -for d in $(find . -type d -not -iwholename '*.git*' -a -not -iname '.tool' -a -not -iwholename '*vendor*'); do - gometalinter --deadline=50s --vendor \ - --cyclo-over=50 --dupl-threshold=100 \ - --exclude=".*should not use dot imports \(golint\)$" \ - --disable-all \ - --enable=vet \ - --enable=deadcode \ - --enable=golint \ - --enable=vetshadow \ - --enable=gocyclo \ - --tests "${d}" -done diff --git a/hack/repo-infra/verify/go-tools/verify-govet.sh b/hack/repo-infra/verify/go-tools/verify-govet.sh deleted file mode 100755 index 5f690bd31..000000000 --- a/hack/repo-infra/verify/go-tools/verify-govet.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash -# Copyright 2017 The Kubernetes Authors. -# -# 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. - -set -o errexit -set -o nounset -set -o pipefail - -go vet -v $(go list ./... | grep -v /vendor/) diff --git a/hack/repo-infra/verify/verify-go-src.sh b/hack/repo-infra/verify/verify-go-src.sh deleted file mode 100755 index edf73dd7b..000000000 --- a/hack/repo-infra/verify/verify-go-src.sh +++ /dev/null @@ -1,111 +0,0 @@ -#!/bin/bash - -# Copyright 2017 The Kubernetes Authors. -# -# 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. - -set -o errexit -set -o nounset -set -o pipefail - -# This script is intended to be used via subtree in a top-level directory: -# / -# repo-infra/ -# verify/ -# Or via vendoring and passing root directory as vendor/repo-infra/verify-*.sh --rootdir **full path to your repo dir** -# / -# vendor/ -# repo-infra/ -# ... -# - - -SILENT=true -REPO_ROOT=$(dirname "${BASH_SOURCE}")/../.. - -# Convert long opts to short ones to read through getopts -for arg in "$@"; do - shift - case "$arg" in - "--rootdir") set -- "$@" "-r";; - *) - set -- "$@" "$arg" - ;; - esac -done - -OPTIND=1 -while getopts "vr:" opt; do - case ${opt} in - v) - SILENT=false - ;; - r) - REPO_ROOT=${OPTARG} - ;; - \?) - echo "Invalid flag: -${OPTARG}" >&2 - exit 1 - ;; - esac -done - -shift "$(($OPTIND-1))" - -echo "Working directory: ${REPO_ROOT}" - -GO_TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/go-tools" - -function run-cmd { - if ${SILENT}; then - "$@" &> /dev/null - else - "$@" - fi -} - -# Some useful colors. -if [[ -z "${color_start-}" ]]; then - declare -r color_start="\033[" - declare -r color_red="${color_start}0;31m" - declare -r color_yellow="${color_start}0;33m" - declare -r color_green="${color_start}0;32m" - declare -r color_norm="${color_start}0m" -fi - -function run-checks { - local -r pattern=$1 - local -r runner=$2 - - for t in $(ls ${pattern}) - do - echo -e "Verifying ${t}" - local start=$(date +%s) - cd $REPO_ROOT && run-cmd "${runner}" "${t}" && tr=$? || tr=$? - local elapsed=$(($(date +%s) - ${start})) - if [[ ${tr} -eq 0 ]]; then - echo -e "${color_green}SUCCESS${color_norm} ${t}\t${elapsed}s" - else - echo -e "${color_red}FAILED${color_norm} ${t}\t${elapsed}s" - ret=1 - fi - done -} - -if ${SILENT} ; then - echo "Running in the silent mode, run with -v if you want to see script logs." -fi - -ret=0 -run-checks "${GO_TOOLS_DIR}/*.sh" bash -exit ${ret}