From b855ef39919a7b5f054b004e1ac59bdf5c05533c Mon Sep 17 00:00:00 2001 From: Mariana Dima Date: Tue, 23 Aug 2022 16:16:31 +0200 Subject: [PATCH] Expand mage and add build options (#73) * trial * change * add pkg * update * update * work on mage * work on mage * work on ci * work on ci * fix * remove * notice * forbidigo * forbidigo * sort imports * lint * lint * work on build * undo installer * work on version * unitTest * test binaries * remove local * rename * remore extra logging * review * add flags * version update * version update * version fix * lint * add binary check * add binary check * remove * rename env --- .ci/Jenkinsfile | 4 +- .gitignore | 4 +- .goreleaser.yaml | 66 +++ NOTICE.txt | 493 +++++++++++----------- dev-tools/common/common.go | 90 ++++ dev-tools/common/test.go | 139 ++++++ dev-tools/templates/notice/overrides.json | 1 - go.mod | 8 +- go.sum | 7 + magefile.go | 161 ++++++- main.go | 7 + tools/tools.go | 2 + tools/version.go | 7 + 13 files changed, 732 insertions(+), 257 deletions(-) create mode 100644 .goreleaser.yaml create mode 100644 dev-tools/common/common.go create mode 100644 dev-tools/common/test.go create mode 100644 tools/version.go diff --git a/.ci/Jenkinsfile b/.ci/Jenkinsfile index 1d18685..b50067d 100644 --- a/.ci/Jenkinsfile +++ b/.ci/Jenkinsfile @@ -78,8 +78,8 @@ pipeline { steps { withGithubNotify(context: "Test-${PLATFORM}") { dir("${BASE_DIR}"){ - withGoEnv(){ - goTestJUnit(options: '-v ./...', output: 'junit-report.xml') + withMageEnv(){ + cmd(label: 'Go unitTest', script: 'mage unitTest') } } } diff --git a/.gitignore b/.gitignore index dea8f93..7b94426 100644 --- a/.gitignore +++ b/.gitignore @@ -47,7 +47,5 @@ fleet.yml # agent build/ elastic-agent-shipper +dist/ - -# VSCode -/.vscode \ No newline at end of file diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..efdd47b --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,66 @@ +# Make sure to check the documentation at https://goreleaser.com +before: + hooks: + - go mod tidy + - go generate ./... +builds: + - id: darwin + binary: '{{ .ProjectName }}-{{ .Env.DEFAULT_VERSION }}-{{ .Os }}-{{ if eq .Arch "amd64" }}x86_64{{ end }}{{ if eq .Arch "arm64" }}aarch64{{ end }}/{{ .ProjectName }}' + goos: + - darwin + goarch: + - amd64 + - arm64 + flags: + - -buildmode=pie + ldflags: + - '{{ if eq .Env.DEV "false" }}-s -w{{ end }}' + - -X main.Version={{ .Env.DEFAULT_VERSION }} -X main.Commit={{.Commit}} -X main.BuildTime={{.Date}} + gcflags: + - '{{ if eq .Env.DEV "true" }}all=-N -l{{ end }}' + no_unique_dist_dir: true + - id: linux + binary: '{{ .ProjectName }}-{{ .Env.DEFAULT_VERSION }}-{{ .Os }}-{{ if eq .Arch "amd64" }}x86_64{{ end }}{{ if eq .Arch "386" }}x86{{ end }}{{ if eq .Arch "arm64" }}{{ .Arch }}{{ end }}/{{ .ProjectName }}' + goos: + - linux + goarch: + - amd64 + - arm64 + - 386 + no_unique_dist_dir: true + ldflags: + - '{{ if eq .Env.DEV "false" }}-s -w{{end}}' + - -X main.Version={{ .Env.DEFAULT_VERSION }} -X main.Commit={{.Commit}} -X main.BuildTime={{.Date}} + gcflags: + - '{{ if eq .Env.DEV "true" }}all=-N -l{{ end }}' + overrides: + - goos: linux + goarch: amd64 + goarm: '' + gomips: '' + flags: + - -buildmode=pie + - goos: linux + goarch: arm64 + goarm: '' + gomips: '' + flags: + - -buildmode=pie + - id: windows + binary: '{{ .ProjectName }}-{{ .Env.DEFAULT_VERSION }}-{{ .Os }}-{{ if eq .Arch "amd64" }}x86_64{{ end }}{{ if eq .Arch "386" }}x86{{ end }}/{{ .ProjectName }}' + goos: + - windows + goarch: + - amd64 + - 386 + no_unique_dist_dir: true + flags: + - -buildmode=pie + ldflags: + - '{{ if eq .Env.DEV "false" }}-s -w{{ end }}' + - -X main.Version={{ .Env.DEFAULT_VERSION }} -X main.Commit={{.Commit}} -X main.BuildTime={{.Date}} + gcflags: + - '{{ if eq .Env.DEV "true" }}all=-N -l{{ end }}' +changelog: + skip: true +dist: build/binaries \ No newline at end of file diff --git a/NOTICE.txt b/NOTICE.txt index b55e1d0..e611d40 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -1031,6 +1031,39 @@ Contents of probable licence file $GOMODCACHE/github.com/magefile/mage@v1.13.0/L limitations under the License. +-------------------------------------------------------------------------------- +Dependency : github.com/pkg/errors +Version: v0.9.1 +Licence type (autodetected): BSD-2-Clause +-------------------------------------------------------------------------------- + +Contents of probable licence file $GOMODCACHE/github.com/pkg/errors@v0.9.1/LICENSE: + +Copyright (c) 2015, Dave Cheney +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + -------------------------------------------------------------------------------- Dependency : github.com/spf13/cobra Version: v1.3.0 @@ -1744,6 +1777,218 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +-------------------------------------------------------------------------------- +Dependency : gotest.tools/gotestsum +Version: v1.7.0 +Licence type (autodetected): Apache-2.0 +-------------------------------------------------------------------------------- + +Contents of probable licence file $GOMODCACHE/gotest.tools/gotestsum@v1.7.0/LICENSE: + + + 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. + + ================================================================================ @@ -41495,39 +41740,6 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------------------------------------------------------------------------------- -Dependency : github.com/pkg/errors -Version: v0.9.1 -Licence type (autodetected): BSD-2-Clause --------------------------------------------------------------------------------- - -Contents of probable licence file $GOMODCACHE/github.com/pkg/errors@v0.9.1/LICENSE: - -Copyright (c) 2015, Dave Cheney -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -------------------------------------------------------------------------------- Dependency : github.com/pkg/sftp Version: v1.10.1 @@ -51374,215 +51586,26 @@ limitations under the License. -------------------------------------------------------------------------------- -Dependency : gotest.tools/gotestsum -Version: v1.7.0 +Dependency : gotest.tools/v3 +Version: v3.0.3 Licence type (autodetected): Apache-2.0 -------------------------------------------------------------------------------- -Contents of probable licence file $GOMODCACHE/gotest.tools/gotestsum@v1.7.0/LICENSE: - - - 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. +Contents of probable licence file $GOMODCACHE/gotest.tools/v3@v3.0.3/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] +Copyright 2018 gotest.tools 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 +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 + 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. +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/dev-tools/common/common.go b/dev-tools/common/common.go new file mode 100644 index 0000000..99b025b --- /dev/null +++ b/dev-tools/common/common.go @@ -0,0 +1,90 @@ +// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +// or more contributor license agreements. Licensed under the Elastic License; +// you may not use this file except in compliance with the Elastic License. + +package common + +import ( + "context" + "fmt" + "io/ioutil" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + + "github.com/magefile/mage/mg" + "github.com/pkg/errors" + + "github.com/elastic/elastic-agent-libs/dev-tools/mage/gotool" +) + +const ProjectName = "elastic-agent-shipper" + +var PlatformFiles = map[string][]string{ + "windows": {"windows-x86_64", "windows-x86"}, + "linux": {"linux-arm64", "linux-x86_64", "linux-x86"}, + "darwin": {"darwin-aarch64", "darwin-x86_64"}, + "darwin/amd64": {"darwin-x86_64"}, + "darwin/arm64": {"darwin-aarch64"}, + "linux/386": {"linux-x86"}, + "linux/amd64": {"linux-x86_64"}, + "linux/arm64": {"linux-arm64"}, + "windows/386": {"windows-x86"}, + "windows/amd64": {"windows-x86_64"}, + "all": {"darwin-aarch64", "darwin-x86_64", "linux-arm64", "linux-x86_64", "linux-x86", "windows-x86_64", "windows-x86"}, +} + +// CreateDir creates the parent directory for the given file. +func CreateDir(file string) string { + // Create the output directory. + if dir := filepath.Dir(file); dir != "." { + if err := os.MkdirAll(dir, 0755); err != nil { + panic(errors.Wrapf(err, "failed to create parent dir for %v", file)) + } + } + return file +} + +func InstallGoTestTools() { + gotool.Install(gotool.Install.Package("gotest.tools/gotestsum")) //nolint:errcheck //not required +} + +func MakeCommand(ctx context.Context, env map[string]string, cmd string, args ...string) *exec.Cmd { + c := exec.CommandContext(ctx, cmd, args...) + c.Env = os.Environ() + for k, v := range env { + c.Env = append(c.Env, k+"="+v) + } + c.Stdout = ioutil.Discard + if mg.Verbose() { + c.Stdout = os.Stdout + } + c.Stderr = os.Stderr + c.Stdin = os.Stdin + fmt.Println("exec:", cmd, strings.Join(args, " ")) //nolint:forbidigo // just for mage + return c +} + +func EnvOrDefault(buildEnv string, defaultValue string) string { + if val := os.Getenv(buildEnv); val != "" { + boolVal, err := strconv.ParseBool(val) + if err != nil { + return defaultValue + } + return strconv.FormatBool(boolVal) + } + return defaultValue +} + +func BoolEnvOrFalse(buildEnv string) bool { + if val := os.Getenv(buildEnv); val != "" { + boolVal, err := strconv.ParseBool(val) + if err != nil { + return false + } + return boolVal + } + return false +} diff --git a/dev-tools/common/test.go b/dev-tools/common/test.go new file mode 100644 index 0000000..233d766 --- /dev/null +++ b/dev-tools/common/test.go @@ -0,0 +1,139 @@ +// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +// or more contributor license agreements. Licensed under the Elastic License; +// you may not use this file except in compliance with the Elastic License. + +package common + +import ( + "bytes" + "context" + "fmt" + "io/ioutil" + "path/filepath" + "strings" + + "io" + "os" + "os/exec" + + "github.com/magefile/mage/mg" + "github.com/magefile/mage/sh" + "github.com/pkg/errors" +) + +func GoUnitTest(ctx context.Context, testCoverage bool) error { + mg.Deps(InstallGoTestTools) + + fmt.Println(">> go test:", "Unit Testing") //nolint:forbidigo // just for tests + var testArgs []string + + gotestsumArgs := []string{"--no-color"} + if mg.Verbose() { + gotestsumArgs = append(gotestsumArgs, "-f", "standard-verbose") + } else { + gotestsumArgs = append(gotestsumArgs, "-f", "standard-quiet") + } + //create report files + fileName := filepath.Join("build", "TEST-go-unit") + CreateDir(fileName + ".xml") + gotestsumArgs = append(gotestsumArgs, "--junitfile", fileName+".xml") + CreateDir(fileName + ".out") + gotestsumArgs = append(gotestsumArgs, "--jsonfile", fileName+".out"+".json") + + covFile := fileName + ".cov" + if testCoverage { + CreateDir(covFile) + covFile = CreateDir(filepath.Clean(covFile)) + testArgs = append(testArgs, + "-covermode=atomic", + "-coverprofile="+covFile, + ) + } + + testArgs = append(testArgs, []string{"./..."}...) + + args := append(gotestsumArgs, append([]string{"--"}, testArgs...)...) + + goTest := MakeCommand(ctx, map[string]string{}, "gotestsum", args...) + // Wire up the outputs. + var outputs []io.Writer + fileOutput, err := os.Create(CreateDir(fileName + ".out")) + if err != nil { + return errors.Wrap(err, "failed to create go test output file") + } + defer fileOutput.Close() + outputs = append(outputs, fileOutput) + + output := io.MultiWriter(outputs...) + goTest.Stdout = io.MultiWriter(output, os.Stdout) + goTest.Stderr = io.MultiWriter(output, os.Stderr) + err = goTest.Run() + + var goTestErr *exec.ExitError + if err != nil { + // Command ran. + var exitErr *exec.ExitError + if !errors.As(err, &exitErr) { + return errors.Wrap(err, "failed to execute go") + } + // Command ran but failed. Process the output. + goTestErr = exitErr + } + + // Generate a HTML code coverage report. + var htmlCoverReport string + if testCoverage { + htmlCoverReport = strings.TrimSuffix(covFile, + filepath.Ext(covFile)) + ".html" + coverToHTML := sh.RunCmd("go", "tool", "cover", + "-html="+covFile, + "-o", htmlCoverReport) + if err = coverToHTML(); err != nil { + return errors.Wrap(err, "failed to write HTML code coverage report") + } + } + + // Generate an XML code coverage report. + var codecovReport string + if testCoverage { + fmt.Println(">> go run gocover-cobertura:", covFile, "Started") //nolint:forbidigo // just for tests + + // execute gocover-cobertura in order to create cobertura report + // install pre-requisites + installCobertura := sh.RunCmd("go", "install", "github.com/boumenot/gocover-cobertura@latest") + if err = installCobertura(); err != nil { + return errors.Wrap(err, "failed to install gocover-cobertura") + } + + codecovReport = strings.TrimSuffix(covFile, + filepath.Ext(covFile)) + "-cov.xml" + + coverage, err := ioutil.ReadFile(covFile) + if err != nil { + return errors.Wrap(err, "failed to read code coverage report") + } + + coberturaFile, err := os.Create(codecovReport) + if err != nil { + return err + } + defer coberturaFile.Close() + + coverToXML := exec.Command("gocover-cobertura") + coverToXML.Stdout = coberturaFile + coverToXML.Stderr = os.Stderr + coverToXML.Stdin = bytes.NewReader(coverage) + if err = coverToXML.Run(); err != nil { + return errors.Wrap(err, "failed to write XML code coverage report") + } + fmt.Println(">> go run gocover-cobertura:", covFile, "Created") //nolint:forbidigo // just for tests + } + // Return an error indicating that testing failed. + if goTestErr != nil { + fmt.Println(">> go test:", "Unit Tests : Test Failed") //nolint:forbidigo // just for tests + return errors.Wrap(goTestErr, "go test returned a non-zero value") + } + + fmt.Println(">> go test:", "Unit Tests : Test Passed") //nolint:forbidigo // just for tests + return nil +} diff --git a/dev-tools/templates/notice/overrides.json b/dev-tools/templates/notice/overrides.json index 13bc589..eb1781d 100644 --- a/dev-tools/templates/notice/overrides.json +++ b/dev-tools/templates/notice/overrides.json @@ -22,4 +22,3 @@ {"name": "github.com/elastic/e2e-testing", "licenceType": "Elastic"} {"name": "github.com/elastic/elastic-agent-shipper-client", "licenceType": "Elastic"} {"name": "github.com/awslabs/kinesis-aggregation/go/v2", "licenceType": "Apache-2.0", "url": "https://github.com/awslabs/kinesis-aggregation/blob/master/LICENSE.txt"} - diff --git a/go.mod b/go.mod index 9b506f0..4958f0e 100644 --- a/go.mod +++ b/go.mod @@ -17,36 +17,41 @@ require ( github.com/elastic/go-ucfg v0.8.6 github.com/gofrs/uuid v4.2.0+incompatible github.com/magefile/mage v1.13.0 + github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.7.1 go.elastic.co/go-licence-detector v0.5.0 golang.org/x/net v0.0.0-20220809184613-07c6da5e1ced + gotest.tools/gotestsum v1.7.0 ) require ( github.com/armon/go-radix v1.0.0 // indirect github.com/cyphar/filepath-securejoin v0.2.3 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dnephin/pflag v1.0.7 // indirect github.com/dustin/go-humanize v1.0.0 // indirect github.com/elastic/go-licenser v0.4.1 // indirect github.com/elastic/go-structform v0.0.10 // indirect github.com/elastic/go-sysinfo v1.8.1 // indirect github.com/elastic/go-windows v1.0.1 // indirect github.com/fatih/color v1.13.0 // indirect + github.com/fsnotify/fsnotify v1.5.1 // indirect github.com/gobuffalo/here v0.6.0 // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/google/licenseclassifier v0.0.0-20200402202327-879cb1424de0 // indirect + github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/jcchavezs/porto v0.4.0 // indirect github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901 // indirect + github.com/jonboulle/clockwork v0.2.2 // indirect github.com/karrick/godirwalk v1.15.8 // indirect github.com/kr/text v0.2.0 // indirect github.com/markbates/pkger v0.17.0 // indirect github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-isatty v0.0.14 // indirect github.com/pierrec/lz4/v4 v4.1.15 // indirect - github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/procfs v0.8.0 // indirect github.com/santhosh-tekuri/jsonschema v1.2.4 // indirect @@ -62,6 +67,7 @@ require ( golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab // indirect + golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.12 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect diff --git a/go.sum b/go.sum index 86bb734..a220aa4 100644 --- a/go.sum +++ b/go.sum @@ -457,6 +457,7 @@ github.com/digitalocean/godo v1.62.0/go.mod h1:p7dOjjtSBqCTUksqtA5Fd3uaKs9kyTq2x github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/dnaeon/go-vcr v1.0.1/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= +github.com/dnephin/pflag v1.0.7 h1:oxONGlWxhmUct0YzKTgrpQv9AUA1wtPBn7zuSjJqptk= github.com/dnephin/pflag v1.0.7/go.mod h1:uxE91IoWURlOiTUIA8Mq5ZZkAv3dPUfZNaT80Zm7OQE= github.com/docker/distribution v0.0.0-20190905152932-14b96e55d84c/go.mod h1:0+TTO4EOBfRPhZXAeF1Vu+W3hHZ8eLp8PgKVZlcvtFY= github.com/docker/distribution v2.7.1-0.20190205005809-0d3efadf0154+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= @@ -570,6 +571,7 @@ github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM github.com/fsnotify/fsevents v0.1.1/go.mod h1:+d+hS27T6k5J8CRaPLKFgwKYcpS7GwW3Ule9+SC2ZRc= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/fullsailor/pkcs7 v0.0.0-20190404230743-d7302db945fa/go.mod h1:KnogPXtdwXqoenmZCw6S+25EAm2MkxbG0deNDu4cbSA= github.com/garyburd/redigo v0.0.0-20150301180006-535138d7bcd7/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= @@ -844,6 +846,7 @@ github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -1004,6 +1007,7 @@ github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901 h1:rp+c0RAYOWj8 github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901/go.mod h1:Z86h9688Y0wesXCyonoVr47MasHilkuLMqGhRZ4Hpak= github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ= github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= github.com/josephspurrier/goversioninfo v0.0.0-20190209210621-63e6d1acd3dd/go.mod h1:eJTEwMjXb7kZ633hO3Ln9mBUCOjX2+FlTljvpl9SYdE= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= @@ -1936,6 +1940,7 @@ golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXR golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -2286,8 +2291,10 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= +gotest.tools/gotestsum v1.7.0 h1:RwpqwwFKBAa2h+F6pMEGpE707Edld0etUD3GhqqhDNc= gotest.tools/gotestsum v1.7.0/go.mod h1:V1m4Jw3eBerhI/A6qCxUE07RnCg7ACkKj9BYcAm09V8= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= +gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0= gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/magefile.go b/magefile.go index 3b2ced9..34f8749 100644 --- a/magefile.go +++ b/magefile.go @@ -8,31 +8,147 @@ package main import ( + "context" + "fmt" + "os" "path/filepath" + "runtime" + "strconv" + "strings" - //mage:import "github.com/elastic/elastic-agent-libs/dev-tools/mage" + devtools "github.com/elastic/elastic-agent-shipper/dev-tools/common" + "github.com/elastic/elastic-agent-shipper/tools" + "github.com/pkg/errors" + + //mage:import + "github.com/elastic/elastic-agent-libs/dev-tools/mage/gotool" "github.com/magefile/mage/mg" "github.com/magefile/mage/sh" ) -var ( - goLicenserRepo = "github.com/elastic/go-licenser@v0.4.1" +const ( + GoreleaserRepo = "github.com/goreleaser/goreleaser@v1.6.3" ) // Aliases are shortcuts to long target names. // nolint: deadcode // it's used by `mage`. var Aliases = map[string]interface{}{ - "llc": mage.Linter.LastChange, - "lint": mage.Linter.All, + "build": Build.Binary, + "unitTest": Test.Unit, + "integrationTest": Test.Integration, +} + +// BUILD + +// Build contains targets related to linting the Go code +type Build mg.Namespace + +// All builds binaries for the all os/arch. +func (Build) All() { + os.Setenv("PLATFORMS", "all") + mg.Deps(Build.Binary) +} + +// Clean removes the build directory. +func (Build) Clean(test string) { + os.RemoveAll("build") // nolint:errcheck //not required } -func Build() { - sh.Run("go", "build") +// InstallGoReleaser target installs goreleaser +func InstallGoReleaser() error { + return gotool.Install( + gotool.Install.Package(GoreleaserRepo), + ) } -// Check runs all the checks +// Binary will create the project binaries found in /build/binaries (use `mage build`) +// ENV PLATFORMS = all, darwin, linux, windows, darwin/amd64, darwin/arm64, linux/386, linux/amd64, linux/arm64, windows/386, windows/amd64 +// ENV SNAPSHOT = true/false +// ENV DEV = true/false +func (Build) Binary() error { + InstallGoReleaser() + + args := []string{"build", "--rm-dist", "--skip-validate"} + // Environment variable + env := map[string]string{ + "CGO_ENABLED": devtools.EnvOrDefault("CGO_ENABLED", "0"), + "DEV": devtools.EnvOrDefault("DEV", "false"), + "DEFAULT_VERSION": tools.DefaultBeatVersion, + } + + versionQualifier, versionQualified := os.LookupEnv("VERSION_QUALIFIER") + if versionQualified { + env["VERSION_QUALIFIER"] = versionQualifier + env["DEFAULT_VERSION"] += fmt.Sprintf("-%s", versionQualifier) + } + + if snapshotEnv := os.Getenv("SNAPSHOT"); snapshotEnv != "" { + isSnapshot, err := strconv.ParseBool(snapshotEnv) + if err != nil { + return err + } + if isSnapshot { + args = append(args, "--snapshot") + env["DEFAULT_VERSION"] += fmt.Sprintf("-%s", "SNAPSHOT") + } + } + + platform := os.Getenv("PLATFORMS") + if platform != "" && devtools.PlatformFiles[platform] == nil { + return errors.Errorf("Platform %s not recognized, only supported options: all, darwin, linux, windows, darwin/amd64, darwin/arm64, linux/386, linux/amd64, linux/arm64, windows/386, windows/amd64", platform) + } + switch platform { + case "windows", "linux", "darwin": + args = append(args, "--id", platform) + case "darwin/amd64", "darwin/arm64", "linux/386", "linux/amd64", "linux/arm64", "windows/386", "windows/amd64": + goos := strings.Split(platform, "/")[0] + arch := strings.Split(platform, "/")[1] + env["GOOS"] = goos + env["GOARCH"] = arch + args = append(args, "--id", goos, "--single-target") + case "all": + default: + goos := runtime.GOOS + goarch := runtime.GOARCH + platform = goos + "/" + goarch + args = append(args, "--id", goos, "--single-target") + } + fmt.Println(">> build: Building binary for", platform) //nolint:forbidigo // it's ok to use fmt.println in mage + err := sh.RunWithV(env, "goreleaser", args...) + if err != nil { + return errors.Wrapf(err, "Build failed on %s", platform) + } + return CheckBinaries(platform, env["DEFAULT_VERSION"]) + +} + +// TEST + +// Test namespace contains all the task for testing the projects. +type Test mg.Namespace + +// All runs all the tests. +func (Test) All() { + mg.SerialDeps(Test.Unit, Test.Integration) +} + +// Integration runs all the integration tests (use alias `mage integrationTest`). +func (Test) Integration(ctx context.Context) error { + return nil +} + +// Unit runs all the unit tests (use alias `mage unitTest`). +func (Test) Unit(ctx context.Context) error { + testCoverage := devtools.BoolEnvOrFalse("TEST_COVERAGE") + //mg.Deps(Build.Binary, Build.TestBinaries) + return devtools.GoUnitTest(ctx, testCoverage) +} + +//CHECKS + +// Check runs all the checks including licence, notice, gomod, git changes func Check() { // these are not allowed in parallel mg.SerialDeps( @@ -45,7 +161,7 @@ func Check() { // CheckLicense checks the license headers func CheckLicense() error { - mg.Deps(InstallLicenser) + mg.Deps(mage.InstallGoLicenser) return gotool.Licenser( gotool.Licenser.License("Elastic"), @@ -53,15 +169,30 @@ func CheckLicense() error { ) } -// InstallLicenser installs the licenser in the current environment -func InstallLicenser() error { - return gotool.Install(gotool.Install.Package(goLicenserRepo)) +// CheckBinaries checks if the binaries are generated (for now). +func CheckBinaries(platform string, version string) error { + path := filepath.Join("build", "binaries") + selectedPlatformFiles := devtools.PlatformFiles[platform] + if selectedPlatformFiles == nil { + return errors.New("No selected platform files found") + } + for _, platform := range selectedPlatformFiles { + var execName = devtools.ProjectName + if strings.Contains(platform, "windows") { + execName += ".exe" + } + binary := filepath.Join(path, fmt.Sprintf("%s-%s-%s", devtools.ProjectName, version, platform), execName) + if _, err := os.Stat(binary); err != nil { + return errors.Wrap(err, "Build: binary check failed") + } + } + + return nil } -// CheckLicense checks the license headers +// License generates the license headers or returns an error func License() error { - mg.Deps(InstallLicenser) - + mg.Deps(mage.InstallGoLicenser) return gotool.Licenser( gotool.Licenser.License("Elastic"), ) diff --git a/main.go b/main.go index d15b4c4..52b75e8 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,13 @@ import ( "os" "github.com/elastic/elastic-agent-shipper/cmd" + "github.com/elastic/elastic-agent-shipper/tools" +) + +var ( + Version string = tools.DefaultBeatVersion + Commit string + BuildTime string ) func main() { diff --git a/tools/tools.go b/tools/tools.go index 4a2040b..cc1d331 100644 --- a/tools/tools.go +++ b/tools/tools.go @@ -12,4 +12,6 @@ import ( _ "go.elastic.co/go-licence-detector" _ "github.com/elastic/elastic-agent-libs/dev-tools/mage" + + _ "gotest.tools/gotestsum/cmd" ) diff --git a/tools/version.go b/tools/version.go new file mode 100644 index 0000000..39107be --- /dev/null +++ b/tools/version.go @@ -0,0 +1,7 @@ +// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +// or more contributor license agreements. Licensed under the Elastic License; +// you may not use this file except in compliance with the Elastic License. + +package tools + +const DefaultBeatVersion = "8.5.0"