├── .github └── workflows │ └── pr.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── README.md ├── docker-compose.yml ├── git.go ├── go.mod ├── go.sum ├── hooks └── command ├── images └── example.png ├── main.go ├── main_test.go ├── pipeline.go ├── plugin.yml ├── project.go ├── project_test.go └── tests ├── .dockerignore ├── Dockerfile ├── dynamic_pipeline.yml └── post-command.bats /.github/workflows/pr.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | pull_request: 5 | types: [opened, synchronize, reopened] 6 | push: 7 | branches: 8 | - master 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | 16 | - name: Run tests 17 | run: make test 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | buildpipe-* 2 | buildpipe 3 | coverage 4 | 5 | # Binaries for programs and plugins 6 | *.exe 7 | *.exe~ 8 | *.dll 9 | *.so 10 | *.dylib 11 | 12 | # Test binary, built with `go test -c` 13 | *.test 14 | 15 | # Output of the go coverage tool, specifically when used with LiteIDE 16 | *.out 17 | 18 | # Dependency directories (remove the comment below to include it) 19 | # vendor/ 20 | 21 | # Jetbrains 22 | .idea/ 23 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | 0.10.3 (oallenj) 4 | ------------------ 5 | 6 | 1. Allow buildpipe to use buildkite's notification. 7 | 8 | 0.10.2 (oallenj) 9 | ------------------ 10 | 11 | 1. Fix buildpipe not working if any attributes are used on the wait step 12 | 13 | 0.10.1 (TBoshoven) 14 | ------------------ 15 | 16 | 1. Re-tag to properly pick the proper version when using the hook. 17 | 18 | 0.10.0 (boyntoni) 19 | ----------------- 20 | 21 | 1. Add support for manually specifying build projects. 22 | 23 | 0.9.4 (TBoshoven) 24 | ----------------- 25 | 26 | 1. Fix space-separation in step keys. 27 | 2. Fix parsing when `depends_on` is a string instead of an array. 28 | 29 | 0.9.3 (boyntoni) 30 | ---------------- 31 | 32 | 1. Generate unique keys for project steps, and add support for `depends_on`. 33 | 34 | 35 | 0.9.2 (mowies) 36 | -------------- 37 | 1. Add option to set pipeline and project scoped environment variables. 38 | 39 | 40 | 0.9.1 (ksindi) 41 | -------------- 42 | 43 | 1. Capture and log stderr on Buildkite pipeline upload failure. 44 | 45 | 0.9.0 (ksindi) 46 | -------------- 47 | 48 | 1. Rewrite plugin in Go 49 | 2. Change license to Apache 2 50 | 51 | 0.8.0 (ksindi) 52 | -------------- 53 | 54 | 1. Projects are now defined in the dynamic_pipeline.yml file and not the initial pipeline. This allow define most configuration changes in one file. 55 | 2. The diff command has been split into two commands to give more flexibility on whether you are specifying the default branch or a non-default branch. 56 | 57 | 0.7.0 (ksindi) 58 | -------------- 59 | 60 | This is a complete rewrite to a Buildkite plugin. Other changes: 61 | 62 | The schema of the pipeline has changed. 63 | The tag rules removed to just skipping based on labels. 64 | Please read the README.md carefully before migrating. Also please use 0.7.4+ as the prior release has some issues with the command hook. 65 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, political orientation, ideology, or sexual identity and orientation. 6 | 7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to a positive environment for our community include: 12 | 13 | * Demonstrating empathy and kindness toward other people 14 | * Being respectful of differing opinions, viewpoints, and experiences 15 | * Giving and gracefully accepting constructive feedback 16 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 17 | * Focusing on what is best not just for us as individuals, but for the overall community 18 | * Communicate generously. Assume that contributors lack context rather than experience. 19 | 20 | Examples of unacceptable behavior include: 21 | * The use of sexualized language or imagery, and sexual attention or advances of any kind 22 | * Trolling, insulting or derogatory comments, and personal or political attacks 23 | * Public or private harassment 24 | * Publishing others’ private information, such as a physical or email address, without their explicit permission 25 | * Other conduct which could reasonably be considered inappropriate in a professional setting 26 | 27 | ## Enforcement Responsibilities 28 | 29 | Project maintainers are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 32 | 33 | ## Scope 34 | 35 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 36 | 37 | ## Enforcement 38 | 39 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project maintainers responsible for enforcement at conduct@jwplayer.com. All complaints will be reviewed and investigated promptly and fairly. 40 | 41 | All project maintainers are obligated to respect the privacy and security of the reporter of any incident. 42 | 43 | ## Attribution 44 | 45 | This Code of Conduct is adapted from the Contributor Covenant, version 2.0, 46 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 47 | 48 | Community Impact Guidelines were inspired by Mozilla’s code of conduct enforcement ladder. 49 | 50 | For answers to common questions about this code of conduct, see the FAQ at 51 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 52 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # CONTRIBUTING 2 | 3 | When contributing to this repository, please first discuss the change you wish to 4 | make via [issue](https://github.com/jwplayer/buildpipe-buildkite-plugin/issues). 5 | 6 | Please note we have a [code of conduct](https://github.com/jwplayer/buildpipe-buildkite-plugin/blob/master/CODE_OF_CONDUCT.md), 7 | please follow it in all your interactions with the project. 8 | 9 | ## Releasing 10 | 11 | 1. Update documentation and `hook/command` to new version number. 12 | 1. Run `make build` to generate `buildpipe-linux` binary. 13 | 1. Add notes to `CHANGELOG.md`. 14 | 1. Create a new release in GitHub. Attach `buildpipe-linux` binary. 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 JW Player 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | NAME=buildpipe 2 | VERSION := $(shell head CHANGELOG.md | grep -e '^[0-9]' | head -n 1 | cut -f 1 -d ' ') 3 | GOPATH ?= $(curdir)/.gopath 4 | COMMIT=$(shell git rev-parse --short=7 HEAD) 5 | TIMESTAMP:=$(shell date -u '+%Y-%m-%dT%I:%M:%SZ') 6 | 7 | LDFLAGS += -X main.BuildTime=${TIMESTAMP} 8 | LDFLAGS += -X main.BuildSHA=${COMMIT} 9 | LDFLAGS += -X main.Version=${VERSION} 10 | 11 | PREFIX?=${PWD}/ 12 | DOCKER=$(shell command -v docker;) 13 | TEST_FLAGS?=-race 14 | 15 | .PHONY: all 16 | all: quality test 17 | 18 | .PHONY: quality 19 | quality: 20 | go vet 21 | go fmt 22 | go mod tidy 23 | ifneq (${DOCKER},) 24 | docker run -v ${PWD}:/src -w /src -it golangci/golangci-lint golangci-lint run --true gocritic --true gosec --true golint --true stylecheck --exclude-use-default=false 25 | endif 26 | 27 | .PHONY: test 28 | test: clean test-plugin 29 | 30 | test-unit: 31 | go test ${TEST_FLAGS} -coverprofile=coverage 32 | 33 | test-plugin: 34 | docker-compose up --build buildkite_plugin_tester 35 | 36 | .PHONY: clean 37 | clean: 38 | rm -f coverage 39 | rm -f ${NAME}* 40 | 41 | distclean: clean 42 | @rm -rf Gopkg.lock 43 | 44 | .PHONY: build 45 | build: clean distclean build-linux 46 | 47 | build-%: 48 | GOOS=$* GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -o ${PREFIX}${NAME}-$* 49 | 50 | .PHONY: docker 51 | docker: 52 | ifeq (${DOCKER},) 53 | @echo Skipping Docker build because Docker is not installed 54 | else 55 | docker run --rm -i hadolint/hadolint < Dockerfile 56 | docker build \ 57 | --build-arg NAME="${NAME}" \ 58 | --build-arg VERSION="${VERSION}" \ 59 | --build-arg COMMIT="${COMMIT}" \ 60 | --build-arg BUILD_DATE="${TIMESTAMP}" \ 61 | --build-arg LDFLAGS='${LDFLAGS}' \ 62 | --tag ${NAME} . 63 | docker tag ${NAME} ${NAME}:${VERSION} 64 | docker run -it ${NAME}:${VERSION} -- -help 2>&1 | grep -F '${NAME} v${VERSION} ${TIMESTAMP} ${COMMIT}' 65 | endif 66 | 67 | release: test 68 | go mod tidy 69 | @echo "Releasing $(APPNAME) v$(VERSION)" 70 | git tag v$(VERSION) 71 | git push --tags 72 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Buildpipe 2 | ========= 3 | 4 | A Buildkite plugin to dynamically generate pipelines. Especially useful 5 | for monorepos where you want to create dependencies between projects. 6 | 7 | Example 8 | ------- 9 | 10 | ![Buildpipe example](images/example.png) 11 | 12 | ### initial\_pipeline.yml 13 | 14 | ```yaml 15 | steps: 16 | - label: ":buildkite:" 17 | plugins: 18 | - jwplayer/buildpipe#v0.10.3: 19 | dynamic_pipeline: dynamic_pipeline.yml 20 | ``` 21 | 22 | ### dynamic\_pipeline.yml 23 | 24 | ```yaml 25 | env: 26 | GLOBAL_ENV_VAR: test 27 | projects: 28 | - label: project1 29 | path: project1/ # changes in this directory will trigger steps for project1 30 | skip: 31 | - deploy* # skip steps with label matching deploy* (e.g. deploy-prd) 32 | - test 33 | env: 34 | PROJECT_ENV_VAR: project1variable 35 | - label: project2 36 | skip: test 37 | path: 38 | - project2/ 39 | - project1 # you can trigger a project using multiple paths 40 | - label: project3 41 | skip: 42 | - deploy-stg 43 | path: project3/somedir/ # subpaths can also be triggered 44 | steps: # the same schema as regular buildkite pipeline steps 45 | - label: test 46 | env: 47 | BUILDPIPE_SCOPE: project # this variable ensures a test step is generated for each project 48 | command: 49 | - cd $$BUILDPIPE_PROJECT_PATH # BUILDPIPE_PROJECT_PATH is set by buildpipe 50 | - make test 51 | - wait 52 | - label: build 53 | branches: "master" 54 | env: 55 | BUILDPIPE_SCOPE: project 56 | command: 57 | - cd $$BUILDPIPE_PROJECT_PATH 58 | - make build 59 | - make publish-image 60 | agents: 61 | - queue=build 62 | - wait 63 | - label: tag 64 | branches: "master" 65 | command: 66 | - make tag-release 67 | - wait 68 | - label: deploy-stg 69 | branches: "master" 70 | concurrency: 1 71 | concurrency_group: deploy-stg 72 | env: 73 | BUILDPIPE_SCOPE: project 74 | command: 75 | - cd $$BUILDPIPE_PROJECT_PATH 76 | - make deploy-staging 77 | - wait 78 | - block: ":rocket: Release!" 79 | branches: "master" 80 | - wait 81 | - label: deploy-prd 82 | branches: "master" 83 | concurrency: 1 84 | concurrency_group: deploy-prd 85 | env: 86 | BUILDPIPE_SCOPE: project 87 | command: 88 | - cd $$BUILDPIPE_PROJECT_PATH 89 | - make deploy-prod 90 | ``` 91 | 92 | The above pipelines specify the following: 93 | 94 | - There are three projects to track in the repository. 95 | - The env variable `BUILDPIPE_SCOPE: project` tells buildpipe to 96 | generate a step for each project if that project changed. 97 | - The `skip` option will skip any step label matching `deploy*`. 98 | - The env variable `BUILDPIPE_PROJECT_PATH` is created by buildpipe as 99 | the project\'s path. If multiple paths are specified for a project, 100 | it\'s the first path. 101 | - There is a global environment variable defined (`GLOBAL_ENV_VAR`). 102 | This variable will be added to every step in the pipeline. 103 | - There is also a project scoped environment variable defined (`PROJECT_ENV_VAR`). 104 | That variable will be added to all steps of the project where it was defined (`project1`). 105 | 106 | ### Full working example 107 | 108 | For a full working example, check out [Buildkite Monorepo Example](https://github.com/ksindi/buildkite-monorepo-example). 109 | 110 | Configuration 111 | ------------- 112 | 113 | ### Plugin 114 | 115 | | Option | Required | Type | Default | Description 116 | | ---------------- | -------- | ------ | ------- | -------------------------------------------------- | 117 | | default_branch | No | string | master | Default branch of repository | 118 | | diff_pr | No | string | | Override command for non-default branch (see below for a better explanation of the defaults) | 119 | | diff_default | No | string | | Override command for default branch (see below for a better explanation of the defaults) | 120 | | dynamic_pipeline | Yes | string | | The name including the path to the pipeline that contains all the actual steps | 121 | | log_level | No | string | INFO | The Level of logging to be used by the python script underneath; pass DEBUG for verbose logging if errors occur | 122 | 123 | ### Project schema 124 | 125 | | Option | Required | Type | Default | Description | Environment variable | 126 | | ------ | -------- | ----------- | ------- | ------------------------------------- | -------------------- | 127 | | label | Yes | string | | Project label | `BUILDPIPE_PROJECT_LABEL` | 128 | | path | Yes | array | | The path(s) that specify changes to a project | `BUILDPIPE_PROJECT_PATH` | 129 | | skip | No | array | | Exclude steps that have labels that match the rule | | 130 | | env | No | dictionary | | Define environment variable on a project scope | | 131 | 132 | Other useful things to note: 133 | 134 | - Option `skip` makes use of Unix shell-style wildcards (Look at 135 | .gitignore files for inspiration) 136 | - If multiple paths are specified, the environment variable 137 | `BUILDPIPE_PROJECT_PATH` will be the first path. 138 | - Environment variables are available in the pipeline step. 139 | 140 | ### Environment Variables 141 | 142 | Since version 0.9.2, there is the option to define environment variables on different scope levels in the pipeline. 143 | Buildkite already supports environment variables defined on a step scope, but buildpipe adds the ability to define global 144 | and also project specific environment variables. 145 | 146 | #### Project env vars 147 | ```yaml 148 | env: 149 | THIS_IS_A_GLOBAL_ENV_VAR: global 150 | GLOBAL_ENV_VAR_2: another_global_value 151 | projects: 152 | - label: project1 153 | path: project1/ 154 | env: 155 | THIS_IS_A_PROJECT_ENV_VAR: project_scoped 156 | PROJECT_ENV_VAR_2: second_env_var_value 157 | - label: project2 158 | ... 159 | steps: 160 | - label: step1 161 | ... 162 | ``` 163 | 164 | ### Specifying build projects 165 | 166 | Since version 0.10.0, you can manually specify which projects you wish to build using the `BUILDKITE_PLUGIN_BUILDPIPE_BUILD_PROJECTS` environment variable. 167 | If this environemnt variable is provided, it will take precedence over any existing `git` diff. You can specify the build projects in one of two ways: 168 | 169 | 1. Provide a comma-separated list of build projects (identified by the project label attribute). For example: 170 | 171 | ```bash 172 | BUILDKITE_PLUGIN_BUILDPIPE_BUILD_PROJECTS="project1,project2" 173 | ``` 174 | 175 | 2. Build all projects in a Buildpipe configuration: 176 | 177 | ```bash 178 | BUILDKITE_PLUGIN_BUILDPIPE_BUILD_PROJECTS="*" 179 | ``` 180 | 181 | `diff_` commands 182 | ---------------- 183 | 184 | Depending on your [merge 185 | strategy](https://help.github.com/en/github/administering-a-repository/about-merge-methods-on-github), 186 | you might need to use different diff command. 187 | 188 | Buildpipe assumes you are using a merge strategy on the default branch, which is assumed to be `master`. 189 | 190 | The command for the non-default branch (e.g. when you have a PR up) is: 191 | ```bash 192 | git log --name-only --no-merges --pretty=format: origin..HEAD 193 | ``` 194 | 195 | The command for the default branch you merge to is currently: 196 | ```bash 197 | git log -m -1 --name-only --pretty=format: $BUILDKITE_COMMIT 198 | ``` 199 | 200 | Requirements 201 | ------------ 202 | 203 | Only `curl` is required to download the binary. 204 | 205 | Installing buildpipe 206 | -------------------- 207 | 208 | You can also install buildpipe in the agent bootstrap script: 209 | 210 | ```bash 211 | curl -Lf -o /usr/local/bin/buildpipe https://github.com/jwplayer/buildpipe-buildkite-plugin/releases/download/v${BUILDPIPE_VERSION}/buildpipe-linux \ 212 | && chmod +x /usr/local/bin/buildpipe 213 | ``` 214 | 215 | Your initial pipeline would need to pass the options as environment variables with prefix `BUILDKITE_PLUGIN_BUILDPIPE_`. For example: 216 | 217 | ```yml 218 | steps: 219 | - label: "buildpipe" 220 | command: buildpipe 221 | env: 222 | BUILDKITE_PLUGIN_BUILDPIPE_DYNAMIC_PIPELINE: path/to/dynamic_pipeline.yml 223 | BUILDKITE_PLUGIN_BUILDPIPE_LOG_LEVEL: debug 224 | ``` 225 | 226 | Troubleshooting 227 | --------------- 228 | 229 | ### Buildpipe is incorrectly showing project as changed 230 | 231 | Buildkite doesn\'t by default do clean checkouts. To enable clean 232 | checkouts set the `BUILDKITE_CLEAN_CHECKOUT` [environment variable](https://buildkite.com/docs/pipelines/environment-variables). An 233 | example is to modify the pre-checkout hook, 234 | `.buildkite/hooks/pre-checkout`: 235 | 236 | ```bash 237 | #!/bin/bash 238 | set -euo pipefail 239 | 240 | echo '--- :house_with_garden: Setting up pre-checkout' 241 | 242 | export BUILDKITE_CLEAN_CHECKOUT="true" 243 | ``` 244 | 245 | Testing 246 | ------- 247 | 248 | ```bash 249 | make test 250 | ``` 251 | 252 | License 253 | ------- 254 | 255 | Apache v2 256 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | buildkite_plugin_tester: 4 | build: 5 | context: . 6 | dockerfile: tests/Dockerfile 7 | buildkite_plugin_linter: 8 | image: buildkite/plugin-linter 9 | command: ['--id', 'jwplayer/buildpipe'] 10 | volumes: 11 | - ".:/plugin:ro" 12 | -------------------------------------------------------------------------------- /git.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "os" 7 | "os/exec" 8 | "strings" 9 | 10 | log "github.com/sirupsen/logrus" 11 | ) 12 | 13 | func getEnv(key, fallback string) string { 14 | if value, ok := os.LookupEnv(key); ok { 15 | return value 16 | } 17 | return fallback 18 | } 19 | 20 | func dedupe(list []string) []string { 21 | unique := make([]string, 0) 22 | set := make(map[string]bool) 23 | 24 | for _, item := range list { 25 | _, ok := set[item] 26 | if ok == false { 27 | set[item] = true 28 | unique = append(unique, item) 29 | } 30 | } 31 | return unique 32 | } 33 | 34 | func execCommand(program string, args []string) string { 35 | cmd := exec.Command(program, args...) 36 | var out bytes.Buffer 37 | var stderr bytes.Buffer 38 | cmd.Stdout = &out 39 | cmd.Stderr = &stderr 40 | if err := cmd.Run(); err != nil { 41 | log.Fatalf(fmt.Sprint(err) + ": " + stderr.String()) 42 | } 43 | return out.String() 44 | } 45 | 46 | func getGitBranch() string { 47 | branch := os.Getenv("BUILDKITE_BRANCH") 48 | if branch == "" { 49 | branch = execCommand("git", []string{"rev-parse", "--abbrev-ref", "HEAD"}) 50 | } 51 | return strings.TrimSpace(branch) 52 | } 53 | 54 | func determineGitArgs(branch string, defaultBranch string) []string { 55 | var command string 56 | if branch == defaultBranch { 57 | commit := getEnv("BUILDKITE_COMMIT", branch) 58 | command = getEnv(pluginPrefix+"DIFF_DEFAULT", "log -m -1 --name-only --pretty=format: "+commit) 59 | } else { 60 | command = getEnv(pluginPrefix+"DIFF_PR", "log --name-only --no-merges --pretty=format: origin..HEAD") 61 | } 62 | log.Debugf("Running command args: %s", command) 63 | return strings.Split(command, " ") 64 | } 65 | 66 | func index(slice []string, item string) int { 67 | for i, _ := range slice { 68 | if slice[i] == item { 69 | return i 70 | } 71 | } 72 | return -1 73 | } 74 | 75 | func getChangedFiles() []string { 76 | branch := getGitBranch() 77 | log.Debugf("Current branch: %s", branch) 78 | defaultBranch := getEnv(pluginPrefix+"DEFAULT_BRANCH", "master") 79 | 80 | cmdArgs := determineGitArgs(branch, defaultBranch) 81 | changedFiles := strings.Split(execCommand("git", cmdArgs), "\n") 82 | 83 | if branch == defaultBranch { 84 | firstMergeBreak := index(changedFiles, "") 85 | changedFiles = changedFiles[:firstMergeBreak] 86 | } 87 | 88 | log.Debugf("changedFiles: %s", changedFiles) 89 | uniqueFiles := dedupe(changedFiles) 90 | return uniqueFiles 91 | } 92 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jwplayer/buildpipe-buildkite-plugin 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 7 | github.com/sirupsen/logrus v1.5.0 8 | github.com/stretchr/testify v1.4.0 9 | gopkg.in/yaml.v2 v2.2.2 10 | ) 11 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= 5 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 6 | github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= 7 | github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= 8 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 9 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 10 | github.com/sirupsen/logrus v1.5.0 h1:1N5EYkVAPEywqZRJd7cwnRtCb6xJx7NH3T3WUTF980Q= 11 | github.com/sirupsen/logrus v1.5.0/go.mod h1:+F7Ogzej0PZc/94MaYx/nvG9jOFMD2osvC3s+Squfpo= 12 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 13 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 14 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= 15 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 16 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= 17 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 18 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 19 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 20 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 21 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 22 | -------------------------------------------------------------------------------- /hooks/command: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | 4 | buildpipe_version="${BUILDKITE_PLUGIN_BUILDPIPE_VERSION:-0.10.3}" 5 | is_test="${BUILDKITE_PLUGIN_BUILDPIPE_TEST_MODE:-false}" 6 | 7 | if [[ "$is_test" == "false" ]]; then 8 | curl -Lf -o buildpipe https://github.com/jwplayer/buildpipe-buildkite-plugin/releases/download/v${buildpipe_version}/buildpipe-linux \ 9 | && chmod +x buildpipe 10 | fi 11 | 12 | ./buildpipe 13 | -------------------------------------------------------------------------------- /images/example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jwplayer/buildpipe-buildkite-plugin/d7e375c88587ea511faa34838d355499e55798fd/images/example.png -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "strings" 7 | 8 | log "github.com/sirupsen/logrus" 9 | "gopkg.in/yaml.v2" 10 | ) 11 | 12 | const pluginPrefix = "BUILDKITE_PLUGIN_BUILDPIPE_" 13 | 14 | type Config struct { 15 | Projects []Project `yaml:"projects"` 16 | Steps []interface{} `yaml:"steps"` 17 | Env map[string]string `yaml:"env"` 18 | Notify []interface{} `yaml:"notify"` 19 | } 20 | 21 | func NewConfig(filename string) *Config { 22 | config := Config{} 23 | 24 | yamlFile, err := ioutil.ReadFile(filename) 25 | if err != nil { 26 | log.Fatalf("Error reading file %s: %s\n", filename, err) 27 | } 28 | 29 | if err = yaml.Unmarshal(yamlFile, &config); err != nil { 30 | log.Fatalf("Error unmarshalling: %s\n", err) 31 | } 32 | 33 | return &config 34 | } 35 | 36 | func getAffectedProjects(projects []Project, changedFiles []string) []Project { 37 | affectedProjects := make([]Project, 0) 38 | for _, project := range projects { 39 | if project.checkAffected(changedFiles) { 40 | affectedProjects = append(affectedProjects, project) 41 | } 42 | } 43 | 44 | return affectedProjects 45 | } 46 | 47 | func projectsFromBuildProjects(buildProjects string, projects []Project) []Project { 48 | if buildProjects == "*" { 49 | return projects 50 | } 51 | 52 | projectNames := strings.Split(buildProjects, ",") 53 | 54 | affectedProjects := make([]Project, 0) 55 | for _, projectName := range projectNames { 56 | for _, configProject := range projects { 57 | if projectName == configProject.Label { 58 | affectedProjects = append(affectedProjects, configProject) 59 | } 60 | } 61 | } 62 | return affectedProjects 63 | } 64 | 65 | func main() { 66 | logLevel := getEnv(pluginPrefix+"LOG_LEVEL", "info") 67 | ll, err := log.ParseLevel(logLevel) 68 | if err != nil { 69 | ll = log.InfoLevel 70 | } 71 | 72 | log.SetLevel(ll) 73 | 74 | config := NewConfig(os.Getenv(pluginPrefix + "DYNAMIC_PIPELINE")) 75 | buildProjects := os.Getenv(pluginPrefix + "BUILD_PROJECTS") 76 | 77 | var affectedProjects []Project 78 | if len(buildProjects) > 0 { 79 | affectedProjects = projectsFromBuildProjects(buildProjects, config.Projects) 80 | } else { 81 | changedFiles := getChangedFiles() 82 | if len(changedFiles) == 0 { 83 | log.Info("No files were changed") 84 | os.Exit(0) 85 | } 86 | 87 | affectedProjects = getAffectedProjects(config.Projects, changedFiles) 88 | if len(affectedProjects) == 0 { 89 | log.Info("No project was affected from git changes") 90 | os.Exit(0) 91 | } 92 | } 93 | 94 | pipeline := generatePipeline(config.Steps, config.Notify, config.Env, affectedProjects) 95 | 96 | uploadPipeline(*pipeline) 97 | } 98 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestProjectsFromBuildProjects(t *testing.T) { 10 | assert := assert.New(t) 11 | p1 := Project{Label: "project1", Path: []string{"project1/"}, Skip: []string{}} 12 | p2 := Project{Label: "project2", Path: []string{"project2/"}, Skip: []string{}} 13 | p3 := Project{Label: "project3", Path: []string{"project3/"}, Skip: []string{}} 14 | 15 | projects := []Project{p1, p2, p3} 16 | projectNames := "project1,project3" 17 | 18 | filteredList := projectsFromBuildProjects(projectNames, projects) 19 | 20 | assert.Equal(filteredList, []Project{p1, p3}) 21 | } 22 | 23 | func TestAllProjectsFromBuildProjects(t *testing.T) { 24 | assert := assert.New(t) 25 | p1 := Project{Label: "project1", Path: []string{"project1/"}, Skip: []string{}} 26 | p2 := Project{Label: "project2", Path: []string{"project2/"}, Skip: []string{}} 27 | p3 := Project{Label: "project3", Path: []string{"project3/"}, Skip: []string{}} 28 | 29 | projects := []Project{p1, p2, p3} 30 | projectNames := "*" 31 | filteredList := projectsFromBuildProjects(projectNames, projects) 32 | 33 | assert.Equal(filteredList, []Project{p1, p2, p3}) 34 | } 35 | -------------------------------------------------------------------------------- /pipeline.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "os" 7 | 8 | "github.com/mohae/deepcopy" 9 | log "github.com/sirupsen/logrus" 10 | "gopkg.in/yaml.v2" 11 | ) 12 | 13 | type Pipeline struct { 14 | Steps []interface{} `yaml:"steps"` 15 | Notify []interface{} `yaml:"notify,omitempty"` 16 | } 17 | 18 | func generateProjectSteps(steps []interface{}, step interface{}, projects []Project) []interface{} { 19 | projectSteps := make([]interface{}, 0) 20 | 21 | for _, project := range projects { 22 | stepCopy := deepcopy.Copy(step) 23 | stepCopyMap := stepCopy.(map[interface{}]interface{}) 24 | 25 | if project.checkProjectRules(stepCopyMap) { 26 | // Unique project level label 27 | stepCopyMap["label"] = fmt.Sprintf("%s %s", stepCopyMap["label"], project.Label) 28 | 29 | // Set default buildpipe environment variables and 30 | // set project env vars as step env vars 31 | env := stepCopyMap["env"].(map[interface{}]interface{}) 32 | env["BUILDPIPE_PROJECT_LABEL"] = project.Label 33 | env["BUILDPIPE_PROJECT_PATH"] = project.getMainPath() 34 | for envVarName, envVarValue := range project.Env { 35 | env[envVarName] = envVarValue 36 | } 37 | 38 | // Unique project level key, if present 39 | if val, ok := stepCopyMap["key"]; ok { 40 | stepCopyMap["key"] = fmt.Sprintf("%s:%s", val, project.Label) 41 | } 42 | 43 | // If the step includes a depends_on clause, we need to validate whether each dependency 44 | // is a project-scoped step. If so, the dependency has the current project name added 45 | // to it to match the unique key given above. 46 | if val, ok := stepCopyMap["depends_on"]; ok { 47 | // depends_on can be an array or a string 48 | dependencyList, ok := val.([]interface{}) 49 | if !ok { 50 | dependencyList = []interface{}{val} 51 | stepCopyMap["depends_on"] = dependencyList 52 | } 53 | 54 | for i, dependency := range dependencyList { 55 | depStr := dependency.(string) 56 | 57 | if step := findStepByKey(steps, depStr); step != nil { 58 | if isProjectScopeStep(step) { 59 | dependencyList[i] = fmt.Sprintf("%s:%s", depStr, project.Label) 60 | } 61 | } 62 | } 63 | } 64 | projectSteps = append(projectSteps, stepCopy) 65 | } 66 | } 67 | 68 | return projectSteps 69 | } 70 | 71 | func isProjectScopeStep(step map[interface{}]interface{}) bool { 72 | if env, ok := step["env"].(map[interface{}]interface{}); ok { 73 | if value, ok := env["BUILDPIPE_SCOPE"]; ok { 74 | return value == "project" 75 | } 76 | } 77 | return false 78 | } 79 | 80 | func findStepByKey(steps []interface{}, stepKey string) map[interface{}]interface{} { 81 | for _, step := range steps { 82 | // skip wait commands 83 | stepMap, ok := step.(map[interface{}]interface{}) 84 | if !ok { 85 | continue 86 | } 87 | // grab key if it has one and check whether it is project scoped 88 | foundStepKey, ok := stepMap["key"] 89 | if ok && stepKey == foundStepKey { 90 | return stepMap 91 | } 92 | } 93 | return nil 94 | } 95 | 96 | func generatePipeline(steps []interface{}, notify []interface{}, pipelineEnv map[string]string, projects []Project) *Pipeline { 97 | generatedSteps := make([]interface{}, 0) 98 | 99 | for _, step := range steps { 100 | stepMap, ok := step.(map[interface{}]interface{}) 101 | if !ok { 102 | generatedSteps = append(generatedSteps, step) 103 | continue 104 | } 105 | 106 | env, foundEnv := stepMap["env"].(map[interface{}]interface{}) 107 | _, foundBlockStep := stepMap["block"].(string) 108 | _, foundWaitStep := stepMap["wait"] 109 | 110 | if !foundBlockStep && !foundWaitStep { 111 | if !foundEnv { 112 | env = make(map[interface{}]interface{}) 113 | stepMap["env"] = env 114 | } 115 | 116 | for envVarName, envVarValue := range pipelineEnv { 117 | env[envVarName] = envVarValue 118 | } 119 | } 120 | 121 | value, ok := env["BUILDPIPE_SCOPE"] 122 | if ok && value == "project" { 123 | projectSteps := generateProjectSteps(steps, step, projects) 124 | generatedSteps = append(generatedSteps, projectSteps...) 125 | } else { 126 | generatedSteps = append(generatedSteps, step) 127 | } 128 | } 129 | 130 | return &Pipeline{ 131 | Steps: generatedSteps, 132 | Notify: notify, 133 | } 134 | } 135 | 136 | func uploadPipeline(pipeline Pipeline) { 137 | tmpFile, err := ioutil.TempFile(os.TempDir(), "buildpipe-") 138 | if err != nil { 139 | log.Fatalf("Cannot create temporary file: %s\n", err) 140 | } 141 | defer os.Remove(tmpFile.Name()) 142 | 143 | data, err := yaml.Marshal(&pipeline) 144 | 145 | fmt.Printf("Pipeline:\n%s", string(data)) 146 | 147 | err = ioutil.WriteFile(tmpFile.Name(), data, 0644) 148 | if err != nil { 149 | log.Fatalf("Error writing outfile: %s\n", err) 150 | } 151 | 152 | execCommand("buildkite-agent", []string{"pipeline", "upload", tmpFile.Name()}) 153 | } 154 | -------------------------------------------------------------------------------- /plugin.yml: -------------------------------------------------------------------------------- 1 | name: Buildpipe 2 | description: Dynamically generate Buildkite pipelines based on project changes 3 | author: https://github.com/ksindi 4 | requirements: 5 | - curl 6 | configuration: 7 | properties: 8 | default_branch: 9 | type: string 10 | diff_default: 11 | type: string 12 | diff_pr: 13 | type: string 14 | dynamic_pipeline: 15 | type: string 16 | log_level: 17 | type: string 18 | required: 19 | - dynamic_pipeline 20 | -------------------------------------------------------------------------------- /project.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "path" 5 | "path/filepath" 6 | "reflect" 7 | "strings" 8 | ) 9 | 10 | func Min(x, y int) int { 11 | if x < y { 12 | return x 13 | } 14 | return y 15 | } 16 | 17 | // https://github.com/go-yaml/yaml/issues/100 18 | type StringArray []string 19 | 20 | func (a *StringArray) UnmarshalYAML(unmarshal func(interface{}) error) error { 21 | var multi []string 22 | err := unmarshal(&multi) 23 | if err != nil { 24 | var single string 25 | err := unmarshal(&single) 26 | if err != nil { 27 | return err 28 | } 29 | *a = []string{single} 30 | } else { 31 | *a = multi 32 | } 33 | return nil 34 | } 35 | 36 | type Project struct { 37 | Label string 38 | Path StringArray 39 | Skip StringArray 40 | Env map[string]string 41 | } 42 | 43 | func (p *Project) getMainPath() string { 44 | return p.Path[0] 45 | } 46 | 47 | func (p *Project) checkProjectRules(step map[interface{}]interface{}) bool { 48 | for _, pattern := range p.Skip { 49 | label := step["label"].(string) 50 | if matched, _ := filepath.Match(pattern, label); matched { 51 | return false 52 | } 53 | } 54 | return true 55 | } 56 | 57 | func (p *Project) checkAffected(changedFiles []string) bool { 58 | for _, filePath := range p.Path { 59 | if filePath == "." { 60 | return true 61 | } 62 | normalizedPath := path.Clean(filePath) 63 | projectDirs := strings.Split(normalizedPath, "/") 64 | for _, changedFile := range changedFiles { 65 | changedDirs := strings.Split(changedFile, "/") 66 | if reflect.DeepEqual(changedDirs[:Min(len(projectDirs), len(changedDirs))], projectDirs) { 67 | return true 68 | } 69 | } 70 | } 71 | return false 72 | } 73 | -------------------------------------------------------------------------------- /project_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestCheckAffected(t *testing.T) { 10 | assert := assert.New(t) 11 | 12 | changedFiles := []string{"project1/app.py", "project2/README.md", "", "README.md"} 13 | 14 | p1 := Project{Label: "project1", Path: []string{"project1/"}, Skip: []string{}} 15 | assert.Equal(true, p1.checkAffected(changedFiles)) 16 | 17 | p2 := Project{Label: "project2", Path: []string{"project2"}, Skip: []string{"somelabel"}} 18 | assert.Equal(true, p2.checkAffected(changedFiles)) 19 | 20 | p3 := Project{Label: "project3", Path: []string{"project3/", "project2/foo/"}, Skip: []string{"project1"}} 21 | assert.Equal(false, p3.checkAffected(changedFiles)) 22 | 23 | // test no changes 24 | assert.Equal(false, p3.checkAffected([]string{})) 25 | 26 | } 27 | -------------------------------------------------------------------------------- /tests/.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | *_test.go 3 | coverage 4 | buildpipe* 5 | LICENSE 6 | Makefile 7 | *.md 8 | -------------------------------------------------------------------------------- /tests/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.14 as builder 2 | 3 | WORKDIR /go/src/github.com/jwplayer/buildpipe-buildkite-plugin/ 4 | 5 | COPY . . 6 | 7 | RUN make clean 8 | RUN make build-linux 9 | 10 | FROM buildkite/plugin-tester:v1.1.0 11 | 12 | COPY . . 13 | 14 | COPY --from=builder /go/src/github.com/jwplayer/buildpipe-buildkite-plugin/buildpipe-linux buildpipe 15 | 16 | CMD ["bats", "tests/"] 17 | -------------------------------------------------------------------------------- /tests/dynamic_pipeline.yml: -------------------------------------------------------------------------------- 1 | env: 2 | TEST_ENV_PIPELINE: test-pipeline 3 | projects: 4 | - label: project1 5 | path: project1/ # changes in this dir will trigger steps for project1 6 | skip: deploy* # skip steps with label matching deploy* (e.g. deploy-prd) 7 | env: 8 | TEST_ENV_PROJECT: test-project 9 | - label: project2 10 | skip: test 11 | path: 12 | - project2/ 13 | - project1 # you can trigger a project using multiple paths 14 | - label: project3 15 | skip: # you can skip a list of steps for a project 16 | - test 17 | - deploy-stg 18 | path: project3/somedir/ # subpaths can also be triggered 19 | steps: # the same schema as regular buildkite pipeline steps 20 | - label: bootstrap # a non project scoped step (to test depends_on handling) 21 | key: bootstrap 22 | command: 23 | - make bootstrap 24 | - label: test 25 | key: test 26 | env: 27 | BUILDPIPE_SCOPE: project # this variable ensures a test step is generated for each project 28 | command: 29 | - cd $$BUILDPIPE_PROJECT_PATH # BUILDPIPE_PROJECT_PATH will be set by buildpipe 30 | - make test 31 | - wait: ~ 32 | - label: build 33 | branches: "master" 34 | env: 35 | BUILDPIPE_SCOPE: project 36 | TEST_ENV_STEP: test-step 37 | command: 38 | - cd $$BUILDPIPE_PROJECT_PATH 39 | - make build 40 | - make publish-image 41 | agents: 42 | - queue=build 43 | depends_on: 44 | - bootstrap # the rendered template should not include the project name for a non-project step 45 | - test # the rendered template should include the project name for a project-scoped step 46 | - wait 47 | - label: tag 48 | branches: "master" 49 | command: 50 | - make tag-release 51 | - wait 52 | - label: deploy-stg 53 | key: deploy-stg 54 | branches: "master" 55 | concurrency: 1 56 | concurrency_group: deploy-stg 57 | env: 58 | BUILDPIPE_SCOPE: project 59 | command: 60 | - cd $$BUILDPIPE_PROJECT_PATH 61 | - make deploy-staging 62 | - wait 63 | - block: ":rocket: Release!" 64 | branches: "master" 65 | - wait 66 | - label: deploy-prd 67 | branches: "master" 68 | concurrency: 1 69 | concurrency_group: deploy-prd 70 | depends_on: deploy-stg 71 | env: 72 | BUILDPIPE_SCOPE: project 73 | command: 74 | - cd $$BUILDPIPE_PROJECT_PATH 75 | - make deploy-prod 76 | notify: 77 | - email: "example@example.com" 78 | -------------------------------------------------------------------------------- /tests/post-command.bats: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bats 2 | 3 | load "$BATS_PATH/load.bash" 4 | 5 | setup() { 6 | _GET_CHANGED_FILE='log --name-only --no-merges --pretty=format: origin..HEAD' 7 | stub git "${_GET_CHANGED_FILE} : echo 'project1/app.py'" 8 | stub buildkite-agent pipeline upload 9 | } 10 | 11 | teardown() { 12 | unstub git 13 | # TODO: fix not being able to unstub 14 | # unstub buildkite-agent 15 | } 16 | 17 | 18 | @test "Checks projects affected" { 19 | export BUILDKITE_PLUGIN_BUILDPIPE_DYNAMIC_PIPELINE="tests/dynamic_pipeline.yml" 20 | export BUILDKITE_PLUGIN_BUILDPIPE_LOG_LEVEL="DEBUG" 21 | export BUILDKITE_PLUGIN_BUILDPIPE_TEST_MODE="true" 22 | export BUILDKITE_BRANCH="not_master" 23 | 24 | run hooks/command 25 | 26 | assert_success 27 | refute_output --partial "label: deploy-stg project1" 28 | refute_output --partial "label: deploy-prd project1" 29 | refute_output --partial "label: deploy-stg project3" 30 | refute_output --partial "label: deploy-prd project3" 31 | refute_output --partial "label: test project2" 32 | refute_output --partial "label: test project3" 33 | IFS='' 34 | 35 | assert_output --partial << EOM 36 | steps: 37 | - command: 38 | - make bootstrap 39 | env: 40 | TEST_ENV_PIPELINE: test-pipeline 41 | key: bootstrap 42 | label: bootstrap 43 | - command: 44 | - cd \$\$BUILDPIPE_PROJECT_PATH 45 | - make test 46 | env: 47 | BUILDPIPE_PROJECT_LABEL: project1 48 | BUILDPIPE_PROJECT_PATH: project1/ 49 | BUILDPIPE_SCOPE: project 50 | TEST_ENV_PIPELINE: test-pipeline 51 | TEST_ENV_PROJECT: test-project 52 | key: test:project1 53 | label: test project1 54 | - wait: null 55 | - agents: 56 | - queue=build 57 | branches: master 58 | command: 59 | - cd \$\$BUILDPIPE_PROJECT_PATH 60 | - make build 61 | - make publish-image 62 | depends_on: 63 | - bootstrap 64 | - test:project1 65 | env: 66 | BUILDPIPE_PROJECT_LABEL: project1 67 | BUILDPIPE_PROJECT_PATH: project1/ 68 | BUILDPIPE_SCOPE: project 69 | TEST_ENV_PIPELINE: test-pipeline 70 | TEST_ENV_PROJECT: test-project 71 | TEST_ENV_STEP: test-step 72 | label: build project1 73 | - agents: 74 | - queue=build 75 | branches: master 76 | command: 77 | - cd \$\$BUILDPIPE_PROJECT_PATH 78 | - make build 79 | - make publish-image 80 | depends_on: 81 | - bootstrap 82 | - test:project2 83 | env: 84 | BUILDPIPE_PROJECT_LABEL: project2 85 | BUILDPIPE_PROJECT_PATH: project2/ 86 | BUILDPIPE_SCOPE: project 87 | TEST_ENV_PIPELINE: test-pipeline 88 | TEST_ENV_STEP: test-step 89 | label: build project2 90 | - wait 91 | - branches: master 92 | command: 93 | - make tag-release 94 | env: 95 | TEST_ENV_PIPELINE: test-pipeline 96 | label: tag 97 | - wait 98 | - branches: master 99 | command: 100 | - cd \$\$BUILDPIPE_PROJECT_PATH 101 | - make deploy-staging 102 | concurrency: 1 103 | concurrency_group: deploy-stg 104 | env: 105 | BUILDPIPE_PROJECT_LABEL: project2 106 | BUILDPIPE_PROJECT_PATH: project2/ 107 | BUILDPIPE_SCOPE: project 108 | TEST_ENV_PIPELINE: test-pipeline 109 | key: deploy-stg:project2 110 | label: deploy-stg project2 111 | - wait 112 | - block: ':rocket: Release!' 113 | branches: master 114 | - wait 115 | - branches: master 116 | command: 117 | - cd \$\$BUILDPIPE_PROJECT_PATH 118 | - make deploy-prod 119 | concurrency: 1 120 | concurrency_group: deploy-prd 121 | depends_on: 122 | - deploy-stg:project2 123 | env: 124 | BUILDPIPE_PROJECT_LABEL: project2 125 | BUILDPIPE_PROJECT_PATH: project2/ 126 | BUILDPIPE_SCOPE: project 127 | TEST_ENV_PIPELINE: test-pipeline 128 | label: deploy-prd project2 129 | notify: 130 | - email: example@example.com 131 | EOM 132 | } 133 | --------------------------------------------------------------------------------