Compare commits

..

No commits in common. "master" and "file-rename" have entirely different histories.

119 changed files with 404 additions and 3324 deletions

View file

@ -12,8 +12,6 @@ steps:
image: golang:1.14.15
commands:
- go test ./...
- go build -o /dev/null github.com/drone/drone/cmd/drone-server
- go build -o /dev/null -tags "oss nolimit" github.com/drone/drone/cmd/drone-server
- name: build
image: golang:1.14.15

View file

@ -4,9 +4,9 @@ Bugs or Issues? Please create a new topic in our Discourse forum.
We are migrating all Drone repositories to Discourse for bug tracking.
New GitHub issues may be automatically deleted.
https://community.harness.io/
https://community.harness.io/c/bugs/17
https://community.harness.io/c/ideas/11
https://discourse.drone.io/
https://discourse.drone.io/c/bugs
https://discourse.drone.io/c/ideas
Failing Builds? Please do not use GitHub issues for generic support
questions. Instead please use Stack Overflow:

65
.github/readme.md vendored
View file

@ -1,56 +1,12 @@
# [Drone](https://www.drone.io/) <img src="https://github.com/drone/brand/blob/master/screenshots/screenshot_build_success.png" style="max-width:100px;" />
**Welcome to the Drone codebase, we are thrilled to have you here!**
Drone is a Continuous Delivery system built on container technology. Drone uses a simple YAML configuration file, a superset of docker-compose, to define and execute Pipelines inside Docker containers.
## What is Drone?
Drone is a continuous delivery system built on container technology. Drone uses a simple YAML build file, to define and execute build pipelines inside Docker containers.
## Table of Contents
<br/>
- [What is Drone?](#what-is-drone)
- [Table of Contents](#table-of-contents)
- [Community and Support](#community-and-support)
- [Contributing](#contributing)
- [Code of Conduct](#code-of-conduct)
- [Setup Documentation](#setup-documentation)
- [Usage Documentation](#usage-documentation)
- [Example `.drone.yml` build file](#example-droneyml-build-file)
- [Plugin Index](#plugin-index)
- [Documentation and Other Links](#documentation-and-Other-Links)
<img src="https://github.com/drone/brand/blob/master/screenshots/screenshot_build_success.png" style="max-width:100px;" />
## Community and Support
[Harness Community Slack](https://join.slack.com/t/harnesscommunity/shared_invite/zt-y4hdqh7p-RVuEQyIl5Hcx4Ck8VCvzBw) - Join the #drone slack channel to connect with our engineers and other users running Drone CI.
</br>
[Harness Community Forum](https://community.harness.io/) - Ask questions, find answers, and help other users.
</br>
[Report A Bug](https://community.harness.io/c/bugs/17) - Find a bug? Please report in our forum under Drone Bugs. Please provide screenshots and steps to reproduce.
</br>
[Events](https://www.meetup.com/harness/) - Keep up to date with Drone events and check out previous events [here](https://www.youtube.com/watch?v=Oq34ImUGcHA&list=PLXsYHFsLmqf3zwelQDAKoVNmLeqcVsD9o).
Sample Pipeline Configuration:
## Contributing
We encourage you to contribute to Drone! Whether that's joining in on the community slack or discourse, or contributing pull requests / documentation changes or raising issues.
## Code of Conduct
Drone follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md).
### Setup Documentation
This section of the [documentation](http://docs.drone.io/installation/) will help you install and configure the Drone Server and one or many Runners. A runner is a standalone daemon that polls the server for pending pipelines to execute.
### Usage Documentation
Our [documentation](http://docs.drone.io/getting-started/) can help you get started with the different types of pipelines/builds. There are different runners / plugins / extensions designed for different use cases to help make an efficient and simple build pipeline
### Plugin Index
Plugins are used in build steps to perform actions, eg send a message to slack or push a container to a registry. We have an extensive list of community plugins to customize your build pipeline, you can find those [here](http://plugins.drone.io/).
### Example `.drone.yml` build file.
This build file contains a single pipeline (you can have multiple pipelines too) that builds a go application. The front end with npm. Publishes the docker container to a registry and announces the results to a slack room.
```YAML
```yaml
name: default
kind: pipeline
@ -84,7 +40,7 @@ steps:
username: drone
```
## Documentation and Other Links
Documentation and Other Links:
* Setup Documentation [docs.drone.io/installation](http://docs.drone.io/installation/)
* Usage Documentation [docs.drone.io/getting-started](http://docs.drone.io/getting-started/)
@ -93,9 +49,8 @@ steps:
* Build the Enterprise Edition [BUILDING](https://github.com/drone/drone/blob/master/BUILDING)
* Build the Community Edition [BUILDING_OSS](https://github.com/drone/drone/blob/master/BUILDING_OSS)
## Building from source
_Please note the official Docker images run the Drone Enterprise distribution. If you would like to run the Community Edition you can build from source by following the instructions in [BUILDING_OSS](https://github.com/drone/drone/blob/master/BUILDING_OSS)._
We have two versions available: the [Enterprise Edition](https://github.com/drone/drone/blob/master/BUILDING) and the [Community Edition](https://github.com/drone/drone/blob/master/BUILDING_OSS)
## Release procedure
@ -107,16 +62,14 @@ docker run -it --rm -v "$(pwd)":/usr/local/src/your-app githubchangeloggenerator
You can generate a token by logging into your GitHub account and going to Settings -> Personal access tokens.
Next we tag the PR's with the fixes or enhancements labels. If the PR does not fulfill the requirements, do not add a label.
Next we tag the PR's with the fixes or enhancements labels. If the PR does not fufil the requirements, do not add a label.
**Before moving on make sure to update the version file `version/version.go && version/version_test.go`.**
Run the changelog generator again with the future version according to semver.
```BASH
docker run -it --rm -v "$(pwd)":/usr/local/src/your-app githubchangeloggenerator/github-changelog-generator -u harness -p drone -t <secret token> --future-release v1.0.0
docker run -it --rm -v "$(pwd)":/usr/local/src/your-app githubchangeloggenerator/github-changelog-generator -u drone -p drone -t <secret token> --future-release v1.0.0
```
Create your pull request for the release. Get it merged then tag the release.
[⬆ Back to Top](#table-of-contents)

View file

@ -1,3 +1,2 @@
since-tag=v2.0.4
issues=false

1
.gitignore vendored
View file

@ -10,4 +10,3 @@ release/
scripts/*.go
docker/**/data
TODO*
.idea

View file

@ -1,326 +1,47 @@
# Changelog
## [v2.12.1](https://github.com/harness/drone/tree/v2.12.1) (2022-06-15)
## [v2.1.0](https://github.com/drone/drone/tree/v2.1.0) (2021-08-24)
[Full Changelog](https://github.com/harness/drone/compare/v2.12.0...v2.12.1)
**Fixed bugs:**
- \(bug\) - fix original template scripts & remove amend scripts [\#3229](https://github.com/harness/drone/pull/3229) ([eoinmcafee00](https://github.com/eoinmcafee00))
- \(bug\) - remove unique index on template name [\#3226](https://github.com/harness/drone/pull/3226) ([eoinmcafee00](https://github.com/eoinmcafee00))
- Added OAuth2 token refresher for Gitlab [\#3215](https://github.com/harness/drone/pull/3215) ([EndymionWight](https://github.com/EndymionWight))
**Merged pull requests:**
- \(maint\) fix starlark test on windows [\#3230](https://github.com/harness/drone/pull/3230) ([tphoney](https://github.com/tphoney))
- \(maint\) fix unit tests so they pass on windows [\#3228](https://github.com/harness/drone/pull/3228) ([tphoney](https://github.com/tphoney))
- Update Readme to Fix Typo [\#3223](https://github.com/harness/drone/pull/3223) ([hrittikhere](https://github.com/hrittikhere))
- \(bug\) add unit test for comments in template file [\#3221](https://github.com/harness/drone/pull/3221) ([eoinmcafee00](https://github.com/eoinmcafee00))
- Bump scm version to v1.24.0 [\#3219](https://github.com/harness/drone/pull/3219) ([kit101](https://github.com/kit101))
## [v2.12.0](https://github.com/harness/drone/tree/v2.12.0) (2022-05-16)
[Full Changelog](https://github.com/harness/drone/compare/v2.11.1...v2.12.0)
[Full Changelog](https://github.com/drone/drone/compare/v2.0.6...v2.1.0)
**Implemented enhancements:**
- bump SCM version to v1.21.1 [\#3204](https://github.com/harness/drone/pull/3204) ([d1wilko](https://github.com/d1wilko))
- bump ui version [\#3202](https://github.com/harness/drone/pull/3202) ([d1wilko](https://github.com/d1wilko))
- \(maint\) ui version v2.0.1. - https://github.com/drone/drone-ui/blob/main/CHANGELOG.md [\#3123](https://github.com/drone/drone/pull/3123) ([d1wilko](https://github.com/d1wilko))
- add support for yaml templates [\#3120](https://github.com/drone/drone/pull/3120) ([eoinmcafee00](https://github.com/eoinmcafee00))
**Fixed bugs:**
- \(fix\) update drone ui to 2.8.2 [\#3211](https://github.com/harness/drone/pull/3211) ([tphoney](https://github.com/tphoney))
- \(dron-267\) correctly set parent for promotion retry [\#3210](https://github.com/harness/drone/pull/3210) ([tphoney](https://github.com/tphoney))
- Update error message to forbidden if user membership doesn't exist on repo [\#3122](https://github.com/drone/drone/pull/3122) ([eoinmcafee00](https://github.com/eoinmcafee00))
- update create template path to have namespace, instead of inside the payload [\#3121](https://github.com/drone/drone/pull/3121) ([eoinmcafee00](https://github.com/eoinmcafee00))
- update dependency drone/go-scm to 1.15.2 to fix gitea build problem [\#3118](https://github.com/drone/drone/pull/3118) ([sesky4](https://github.com/sesky4))
## [v2.0.6](https://github.com/drone/drone/tree/v2.0.6) (2021-08-17)
[Full Changelog](https://github.com/drone/drone/compare/v2.0.5...v2.0.6)
**Merged pull requests:**
- release prep v2.12.0 [\#3214](https://github.com/harness/drone/pull/3214) ([tphoney](https://github.com/tphoney))
- fixing URL [\#3208](https://github.com/harness/drone/pull/3208) ([dnielsen](https://github.com/dnielsen))
- update community information with updated links [\#3199](https://github.com/harness/drone/pull/3199) ([mrsantons](https://github.com/mrsantons))
- \(maint\) v2.0.6 release prep [\#3119](https://github.com/drone/drone/pull/3119) ([tphoney](https://github.com/tphoney))
## [v2.11.1](https://github.com/harness/drone/tree/v2.11.1) (2022-03-15)
## [v2.0.5](https://github.com/drone/drone/tree/v2.0.5) (2021-08-17)
[Full Changelog](https://github.com/harness/drone/compare/v2.11.0...v2.11.1)
[Full Changelog](https://github.com/drone/drone/compare/v2.0.4...v2.0.5)
**Implemented enhancements:**
- bump ui version [\#3115](https://github.com/drone/drone/pull/3115) ([d1wilko](https://github.com/d1wilko))
- bump ui version [\#3114](https://github.com/drone/drone/pull/3114) ([d1wilko](https://github.com/d1wilko))
- Add support for nested data objects within templates [\#3110](https://github.com/drone/drone/pull/3110) ([eoinmcafee00](https://github.com/eoinmcafee00))
- \(feat\) redis implementation for pub-sub, log streaming and canceller [\#3108](https://github.com/drone/drone/pull/3108) ([marko-gacesa](https://github.com/marko-gacesa))
**Fixed bugs:**
- ignore nil repos in list and add better debugging [\#3196](https://github.com/harness/drone/pull/3196) ([d1wilko](https://github.com/d1wilko))
- fix issue where map changes order therefore test randomly fails [\#3112](https://github.com/drone/drone/pull/3112) ([eoinmcafee00](https://github.com/eoinmcafee00))
**Merged pull requests:**
- \(maint\) release prep for 2.11.1 [\#3197](https://github.com/harness/drone/pull/3197) ([d1wilko](https://github.com/d1wilko))
## [v2.11.0](https://github.com/harness/drone/tree/v2.11.0) (2022-03-08)
[Full Changelog](https://github.com/harness/drone/compare/v2.10.0...v2.11.0)
**Implemented enhancements:**
- bump UI and SCM versions [\#3193](https://github.com/harness/drone/pull/3193) ([d1wilko](https://github.com/d1wilko))
**Merged pull requests:**
- \(maint\) release prep for 2.11.0 [\#3194](https://github.com/harness/drone/pull/3194) ([d1wilko](https://github.com/d1wilko))
## [v2.10.0](https://github.com/harness/drone/tree/v2.10.0) (2022-03-03)
[Full Changelog](https://github.com/harness/drone/compare/v2.9.1...v2.10.0)
**Implemented enhancements:**
- bump UI version to v2.7.0 [\#3190](https://github.com/harness/drone/pull/3190) ([d1wilko](https://github.com/d1wilko))
- bump UI version to v2.6.2 [\#3188](https://github.com/harness/drone/pull/3188) ([d1wilko](https://github.com/d1wilko))
**Merged pull requests:**
- \(maint\) release prep for 2.10.0 [\#3191](https://github.com/harness/drone/pull/3191) ([d1wilko](https://github.com/d1wilko))
## [v2.9.1](https://github.com/harness/drone/tree/v2.9.1) (2022-01-27)
[Full Changelog](https://github.com/harness/drone/compare/v2.9.0...v2.9.1)
**Fixed bugs:**
- bump ui version 2.6.1 [\#3185](https://github.com/harness/drone/pull/3185) ([d1wilko](https://github.com/d1wilko))
**Merged pull requests:**
- \(maint\) release prep for 2.9.1 [\#3186](https://github.com/harness/drone/pull/3186) ([tphoney](https://github.com/tphoney))
## [v2.9.0](https://github.com/harness/drone/tree/v2.9.0) (2022-01-26)
[Full Changelog](https://github.com/harness/drone/compare/v2.8.0...v2.9.0)
**Implemented enhancements:**
- bump ui to v2.6.0 [\#3183](https://github.com/harness/drone/pull/3183) ([eoinmcafee00](https://github.com/eoinmcafee00))
**Merged pull requests:**
- release prep for v2.9.0 [\#3184](https://github.com/harness/drone/pull/3184) ([eoinmcafee00](https://github.com/eoinmcafee00))
## [v2.8.0](https://github.com/harness/drone/tree/v2.8.0) (2022-01-11)
[Full Changelog](https://github.com/harness/drone/compare/v2.7.3...v2.8.0)
**Implemented enhancements:**
- bump UI to v2.5.0 [\#3180](https://github.com/harness/drone/pull/3180) ([eoinmcafee00](https://github.com/eoinmcafee00))
- \(feat\) ignore archive repos on sync [\#3178](https://github.com/harness/drone/pull/3178) ([eoinmcafee00](https://github.com/eoinmcafee00))
- Datadog add the tag of 'remote:gitee' [\#3174](https://github.com/harness/drone/pull/3174) ([kit101](https://github.com/kit101))
- Add tag filter when call build list endpoint [\#3173](https://github.com/harness/drone/pull/3173) ([michelangelomo](https://github.com/michelangelomo))
**Fixed bugs:**
- \(maint\) add warning around typo for stage\_id in step struct [\#3179](https://github.com/harness/drone/pull/3179) ([tphoney](https://github.com/tphoney))
**Merged pull requests:**
- release prep v2.8.0 [\#3181](https://github.com/harness/drone/pull/3181) ([eoinmcafee00](https://github.com/eoinmcafee00))
## [v2.7.3](https://github.com/harness/drone/tree/v2.7.3) (2021-12-30)
[Full Changelog](https://github.com/harness/drone/compare/v2.7.2...v2.7.3)
**Fixed bugs:**
- bump go-scm to v1.16.3 [\#3175](https://github.com/harness/drone/pull/3175) ([eoinmcafee00](https://github.com/eoinmcafee00))
**Merged pull requests:**
- release prep v2.7.3 [\#3176](https://github.com/harness/drone/pull/3176) ([eoinmcafee00](https://github.com/eoinmcafee00))
## [v2.7.2](https://github.com/harness/drone/tree/v2.7.2) (2021-12-19)
[Full Changelog](https://github.com/harness/drone/compare/v2.7.1...v2.7.2)
**Implemented enhancements:**
- bump go-scm to v1.16.2 [\#3169](https://github.com/harness/drone/pull/3169) ([kit101](https://github.com/kit101))
**Fixed bugs:**
- fixbug gitee provide refresher [\#3168](https://github.com/harness/drone/pull/3168) ([kit101](https://github.com/kit101))
**Merged pull requests:**
- release prep 2.7.2 [\#3172](https://github.com/harness/drone/pull/3172) ([eoinmcafee00](https://github.com/eoinmcafee00))
## [v2.7.1](https://github.com/harness/drone/tree/v2.7.1) (2021-12-17)
[Full Changelog](https://github.com/harness/drone/compare/v2.7.0...v2.7.1)
**Fixed bugs:**
- fixes issue with redirects on double slashes in url [\#3170](https://github.com/harness/drone/pull/3170) ([eoinmcafee00](https://github.com/eoinmcafee00))
**Merged pull requests:**
- release prep v2.7.1 [\#3171](https://github.com/harness/drone/pull/3171) ([eoinmcafee00](https://github.com/eoinmcafee00))
## [v2.7.0](https://github.com/harness/drone/tree/v2.7.0) (2021-12-15)
[Full Changelog](https://github.com/harness/drone/compare/v2.6.0...v2.7.0)
**Implemented enhancements:**
- bump UI to v2.4.1 [\#3167](https://github.com/harness/drone/pull/3167) ([d1wilko](https://github.com/d1wilko))
**Fixed bugs:**
- \(DRON-157\) use deploy string in deployment [\#3165](https://github.com/harness/drone/pull/3165) ([tphoney](https://github.com/tphoney))
**Merged pull requests:**
- release v2.7.0 [\#3166](https://github.com/harness/drone/pull/3166) ([d1wilko](https://github.com/d1wilko))
## [v2.6.0](https://github.com/harness/drone/tree/v2.6.0) (2021-11-30)
[Full Changelog](https://github.com/harness/drone/compare/v2.5.0...v2.6.0)
**Implemented enhancements:**
- Feat: implemented gitee client [\#3156](https://github.com/harness/drone/pull/3156) ([kit101](https://github.com/kit101))
**Merged pull requests:**
- release prep for v2.6.0 [\#3163](https://github.com/harness/drone/pull/3163) ([tphoney](https://github.com/tphoney))
## [v2.5.0](https://github.com/harness/drone/tree/v2.5.0) (2021-11-17)
[Full Changelog](https://github.com/harness/drone/compare/v2.4.0...v2.5.0)
**Implemented enhancements:**
- bump ui to v2.4.0 [\#3160](https://github.com/harness/drone/pull/3160) ([eoinmcafee00](https://github.com/eoinmcafee00))
- add new endpoint for uploading cards [\#3159](https://github.com/harness/drone/pull/3159) ([eoinmcafee00](https://github.com/eoinmcafee00))
- refactor create / find / delete end points for cards [\#3158](https://github.com/harness/drone/pull/3158) ([eoinmcafee00](https://github.com/eoinmcafee00))
- bump ui to v2.3.1 [\#3155](https://github.com/harness/drone/pull/3155) ([d1wilko](https://github.com/d1wilko))
- provide ability to create/read/store card data in drone server [\#3149](https://github.com/harness/drone/pull/3149) ([eoinmcafee00](https://github.com/eoinmcafee00))
- \(DRON-124\) adding new status endpoint [\#3143](https://github.com/harness/drone/pull/3143) ([tphoney](https://github.com/tphoney))
**Fixed bugs:**
- fix a typo in readme [\#3150](https://github.com/harness/drone/pull/3150) ([nothatDinger](https://github.com/nothatDinger))
**Merged pull requests:**
- release prep for v2.5.0 [\#3161](https://github.com/harness/drone/pull/3161) ([eoinmcafee00](https://github.com/eoinmcafee00))
## [v2.4.0](https://github.com/harness/drone/tree/v2.4.0) (2021-09-23)
[Full Changelog](https://github.com/harness/drone/compare/v2.3.1...v2.4.0)
**Implemented enhancements:**
- bump ui version to v2.3.0 [\#3146](https://github.com/harness/drone/pull/3146) ([d1wilko](https://github.com/d1wilko))
- verify if the application is buildable [\#3144](https://github.com/harness/drone/pull/3144) ([marko-gacesa](https://github.com/marko-gacesa))
**Fixed bugs:**
- fixes build issue with bitbucket cloud [\#3147](https://github.com/harness/drone/pull/3147) ([eoinmcafee00](https://github.com/eoinmcafee00))
- Fix stepLimit param in Starlark and Template OSS code [\#3141](https://github.com/harness/drone/pull/3141) ([phil-davis](https://github.com/phil-davis))
- fix a broken link in readme [\#3140](https://github.com/harness/drone/pull/3140) ([empire](https://github.com/empire))
**Merged pull requests:**
- \(maint\)-release 2.4.0 [\#3148](https://github.com/harness/drone/pull/3148) ([d1wilko](https://github.com/d1wilko))
- Allow jsonnet imports in pipeline configuration [\#3105](https://github.com/harness/drone/pull/3105) ([hhamalai](https://github.com/hhamalai))
## [v2.3.1](https://github.com/harness/drone/tree/v2.3.1) (2021-09-09)
[Full Changelog](https://github.com/harness/drone/compare/v2.3.0...v2.3.1)
**Implemented enhancements:**
- bump ui to v2.2.1 - https://github.com/drone/drone-ui/blob/main/CHANGELOG.md [\#3138](https://github.com/harness/drone/pull/3138) ([d1wilko](https://github.com/d1wilko))
**Merged pull requests:**
- \(maint\)-release 2.3.1 [\#3139](https://github.com/harness/drone/pull/3139) ([d1wilko](https://github.com/d1wilko))
## [v2.3.0](https://github.com/harness/drone/tree/v2.3.0) (2021-09-09)
[Full Changelog](https://github.com/harness/drone/compare/v2.2.0...v2.3.0)
**Implemented enhancements:**
- bump ui to v2.2.0 - https://github.com/drone/drone-ui/blob/main/CHANGELOG.md [\#3137](https://github.com/harness/drone/pull/3137) ([d1wilko](https://github.com/d1wilko))
- Make starlark step limit configurable [\#3134](https://github.com/harness/drone/pull/3134) ([phil-davis](https://github.com/phil-davis))
- \(feat\) drone h/a: wrapped scheduler's signal func with redis mutex [\#3130](https://github.com/harness/drone/pull/3130) ([marko-gacesa](https://github.com/marko-gacesa))
**Fixed bugs:**
- \(fix\) trim http/s prefixes from config hostnames [\#3136](https://github.com/harness/drone/pull/3136) ([tphoney](https://github.com/tphoney))
- \(fix\) remove unused jwt-go library [\#3129](https://github.com/harness/drone/pull/3129) ([tphoney](https://github.com/tphoney))
## [v2.2.0](https://github.com/harness/drone/tree/v2.2.0) (2021-09-01)
[Full Changelog](https://github.com/harness/drone/compare/v2.1.0...v2.2.0)
**Implemented enhancements:**
- \(maint\) ui version v2.1.0 - https://github.com/drone/drone-ui/blob/main/CHANGELOG.md [\#3132](https://github.com/harness/drone/pull/3132) ([d1wilko](https://github.com/d1wilko))
- Ability to cancel running builds, if a new commit is pushed [\#3126](https://github.com/harness/drone/pull/3126) ([eoinmcafee00](https://github.com/eoinmcafee00))
**Fixed bugs:**
- fix templating reg expression to match if .drone.yml contains --- characters [\#3131](https://github.com/harness/drone/pull/3131) ([eoinmcafee00](https://github.com/eoinmcafee00))
- add check on template extension type - throw error if invalid [\#3128](https://github.com/harness/drone/pull/3128) ([eoinmcafee00](https://github.com/eoinmcafee00))
**Merged pull requests:**
- \(maint\)-release 2.2.0 [\#3133](https://github.com/harness/drone/pull/3133) ([eoinmcafee00](https://github.com/eoinmcafee00))
- Rename files with camelCase name to use snake\_case convention [\#3127](https://github.com/harness/drone/pull/3127) ([marko-gacesa](https://github.com/marko-gacesa))
- event-stream supports timeout [\#3125](https://github.com/harness/drone/pull/3125) ([zc2638](https://github.com/zc2638))
- \(maint\) Readme update Add Contributor Section [\#3111](https://github.com/harness/drone/pull/3111) ([mrsantons](https://github.com/mrsantons))
## [v2.1.0](https://github.com/harness/drone/tree/v2.1.0) (2021-08-24)
[Full Changelog](https://github.com/harness/drone/compare/v2.0.6...v2.1.0)
**Implemented enhancements:**
- \(maint\) ui version v2.0.1. - https://github.com/drone/drone-ui/blob/main/CHANGELOG.md [\#3123](https://github.com/harness/drone/pull/3123) ([d1wilko](https://github.com/d1wilko))
- add support for yaml templates [\#3120](https://github.com/harness/drone/pull/3120) ([eoinmcafee00](https://github.com/eoinmcafee00))
**Fixed bugs:**
- Update error message to forbidden if user membership doesn't exist on repo [\#3122](https://github.com/harness/drone/pull/3122) ([eoinmcafee00](https://github.com/eoinmcafee00))
- update create template path to have namespace, instead of inside the payload [\#3121](https://github.com/harness/drone/pull/3121) ([eoinmcafee00](https://github.com/eoinmcafee00))
- update dependency drone/go-scm to 1.15.2 to fix gitea build problem [\#3118](https://github.com/harness/drone/pull/3118) ([sesky4](https://github.com/sesky4))
**Merged pull requests:**
- \(maint\) v2.1.0 release prep [\#3124](https://github.com/harness/drone/pull/3124) ([d1wilko](https://github.com/d1wilko))
## [v2.0.6](https://github.com/harness/drone/tree/v2.0.6) (2021-08-17)
[Full Changelog](https://github.com/harness/drone/compare/v2.0.5...v2.0.6)
**Merged pull requests:**
- \(maint\) v2.0.6 release prep [\#3119](https://github.com/harness/drone/pull/3119) ([tphoney](https://github.com/tphoney))
## [v2.0.5](https://github.com/harness/drone/tree/v2.0.5) (2021-08-17)
[Full Changelog](https://github.com/harness/drone/compare/v2.0.4...v2.0.5)
**Implemented enhancements:**
- bump ui version [\#3115](https://github.com/harness/drone/pull/3115) ([d1wilko](https://github.com/d1wilko))
- bump ui version [\#3114](https://github.com/harness/drone/pull/3114) ([d1wilko](https://github.com/d1wilko))
- Add support for nested data objects within templates [\#3110](https://github.com/harness/drone/pull/3110) ([eoinmcafee00](https://github.com/eoinmcafee00))
- \(feat\) redis implementation for pub-sub, log streaming and canceller [\#3108](https://github.com/harness/drone/pull/3108) ([marko-gacesa](https://github.com/marko-gacesa))
**Fixed bugs:**
- fix issue where map changes order therefore test randomly fails [\#3112](https://github.com/harness/drone/pull/3112) ([eoinmcafee00](https://github.com/eoinmcafee00))
**Merged pull requests:**
- release 2.0.5 [\#3117](https://github.com/harness/drone/pull/3117) ([eoinmcafee00](https://github.com/eoinmcafee00))
- Update pull\_request\_template.md [\#3107](https://github.com/harness/drone/pull/3107) ([tphoney](https://github.com/tphoney))
- release 2.0.5 [\#3117](https://github.com/drone/drone/pull/3117) ([eoinmcafee00](https://github.com/eoinmcafee00))
- Update pull\_request\_template.md [\#3107](https://github.com/drone/drone/pull/3107) ([tphoney](https://github.com/tphoney))
All notable changes to this project will be documented in this file.

View file

@ -21,7 +21,7 @@ Drone Non-Commercial License
Contributor: Drone.IO, Inc.
Source Code: https://github.com/harness/drone
Source Code: https://github.com/drone/drone
This license lets you use and share this software for free,
with a trial-length time limit on commercial use. Specifically:

View file

@ -79,7 +79,6 @@ tasks:
- cmd: go test -count=1 github.com/drone/drone/store/batch
- cmd: go test -count=1 github.com/drone/drone/store/batch2
- cmd: go test -count=1 github.com/drone/drone/store/build
- cmd: go test -count=1 github.com/drone/drone/store/card
- cmd: go test -count=1 github.com/drone/drone/store/cron
- cmd: go test -count=1 github.com/drone/drone/store/logs
- cmd: go test -count=1 github.com/drone/drone/store/perm
@ -114,7 +113,6 @@ tasks:
- cmd: go test -count=1 github.com/drone/drone/store/batch
- cmd: go test -count=1 github.com/drone/drone/store/batch2
- cmd: go test -count=1 github.com/drone/drone/store/build
- cmd: go test -count=1 github.com/drone/drone/store/card
- cmd: go test -count=1 github.com/drone/drone/store/cron
- cmd: go test -count=1 github.com/drone/drone/store/logs
- cmd: go test -count=1 github.com/drone/drone/store/perm

View file

@ -86,7 +86,6 @@ type (
GitLab GitLab
Gogs Gogs
Stash Stash
Gitee Gitee
}
// Cloning provides the cloning configuration.
@ -140,14 +139,12 @@ type (
// Jsonnet configures the jsonnet plugin
Jsonnet struct {
Enabled bool `envconfig:"DRONE_JSONNET_ENABLED"`
ImportLimit int `envconfig:"DRONE_JSONNET_IMPORT_LIMIT" default:"0"`
Enabled bool `envconfig:"DRONE_JSONNET_ENABLED"`
}
// Starlark configures the starlark plugin
Starlark struct {
Enabled bool `envconfig:"DRONE_STARLARK_ENABLED"`
StepLimit uint64 `envconfig:"DRONE_STARLARK_STEP_LIMIT"`
Enabled bool `envconfig:"DRONE_STARLARK_ENABLED"`
}
// License provides license configuration
@ -278,9 +275,10 @@ type (
// Session provides the session configuration.
Session struct {
Timeout time.Duration `envconfig:"DRONE_COOKIE_TIMEOUT" default:"720h"`
Secret string `envconfig:"DRONE_COOKIE_SECRET"`
Secure bool `envconfig:"DRONE_COOKIE_SECURE"`
Timeout time.Duration `envconfig:"DRONE_COOKIE_TIMEOUT" default:"720h"`
Secret string `envconfig:"DRONE_COOKIE_SECRET"`
Secure bool `envconfig:"DRONE_COOKIE_SECURE"`
MappingFile string `envconfig:"DRONE_LEGACY_TOKEN_MAPPING_FILE"`
}
// Status provides status configurations.
@ -320,10 +318,6 @@ type (
SkipVerify bool `envconfig:"DRONE_CONVERT_PLUGIN_SKIP_VERIFY"`
CacheSize int `envconfig:"DRONE_CONVERT_PLUGIN_CACHE_SIZE" default:"10"`
Timeout time.Duration `envconfig:"DRONE_CONVERT_TIMEOUT" default:"1m"`
// this flag can be removed once we solve for
// https://github.com/harness/drone/pull/2994#issuecomment-795955312
Multi bool `envconfig:"DRONE_CONVERT_MULTI"`
}
// Validate provides the validation webhook configuration.
@ -368,18 +362,6 @@ type (
Debug bool `envconfig:"DRONE_GITHUB_DEBUG"`
}
// Gitee providers the gitee client configuration.
Gitee struct {
Server string `envconfig:"DRONE_GITEE_SERVER" default:"https://gitee.com"`
APIServer string `envconfig:"DRONE_GITEE_API_SERVER" default:"https://gitee.com/api/v5"`
ClientID string `envconfig:"DRONE_GITEE_CLIENT_ID"`
ClientSecret string `envconfig:"DRONE_GITEE_CLIENT_SECRET"`
RedirectURL string `envconfig:"DRONE_GITEE_REDIRECT_URL"`
SkipVerify bool `envconfig:"DRONE_GITEE_SKIP_VERIFY"`
Scope []string `envconfig:"DRONE_GITEE_SCOPE" default:"user_info,projects,pull_requests,hook"`
Debug bool `envconfig:"DRONE_GITEE_DEBUG"`
}
// GitLab provides the gitlab client configuration.
GitLab struct {
Server string `envconfig:"DRONE_GITLAB_SERVER" default:"https://gitlab.com"`
@ -493,12 +475,6 @@ func (c *Config) IsGitea() bool {
return c.Gitea.Server != ""
}
// IsGitee returns true if the Gitee integration
// is activated.
func (c *Config) IsGitee() bool {
return c.Gitee.ClientID != ""
}
// IsBitbucket returns true if the Bitbucket Cloud
// integration is activated.
func (c *Config) IsBitbucket() bool {
@ -511,28 +487,17 @@ func (c *Config) IsStash() bool {
return c.Stash.Server != ""
}
func cleanHostname(hostname string) string {
hostname = strings.ToLower(hostname)
hostname = strings.TrimPrefix(hostname, "http://")
hostname = strings.TrimPrefix(hostname, "https://")
return hostname
}
func defaultAddress(c *Config) {
if c.Server.Key != "" || c.Server.Cert != "" || c.Server.Acme {
c.Server.Port = ":443"
c.Server.Proto = "https"
}
c.Server.Host = cleanHostname(c.Server.Host)
c.Server.Addr = c.Server.Proto + "://" + c.Server.Host
}
func defaultProxy(c *Config) {
if c.Proxy.Host == "" {
c.Proxy.Host = c.Server.Host
} else {
c.Proxy.Host = cleanHostname(c.Proxy.Host)
}
if c.Proxy.Proto == "" {
c.Proxy.Proto = c.Server.Proto

View file

@ -1,48 +0,0 @@
// Copyright 2019 Drone IO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import "testing"
func Test_cleanHostname(t *testing.T) {
tests := []struct {
name string
hostname string
want string
}{
{
name: "no prefix",
hostname: "drone.io",
want: "drone.io",
},
{
name: "http prefix",
hostname: "http://drone.io",
want: "drone.io",
},
{
name: "https prefix",
hostname: "https://drone.io",
want: "drone.io",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := cleanHostname(tt.hostname); got != tt.want {
t.Errorf("cleanHostname() = %v, want %v", got, tt.want)
}
})
}
}

View file

@ -28,7 +28,6 @@ import (
"github.com/drone/go-scm/scm"
"github.com/drone/go-scm/scm/driver/bitbucket"
"github.com/drone/go-scm/scm/driver/gitea"
"github.com/drone/go-scm/scm/driver/gitee"
"github.com/drone/go-scm/scm/driver/github"
"github.com/drone/go-scm/scm/driver/gitlab"
"github.com/drone/go-scm/scm/driver/gogs"
@ -54,8 +53,6 @@ func provideClient(config config.Config) *scm.Client {
return provideBitbucketClient(config)
case config.Github.ClientID != "":
return provideGithubClient(config)
case config.Gitee.ClientID != "":
return provideGiteeClient(config)
case config.Gitea.Server != "":
return provideGiteaClient(config)
case config.GitLab.ClientID != "":
@ -110,32 +107,6 @@ func provideGithubClient(config config.Config) *scm.Client {
return client
}
// provideGiteeClient is a Wire provider function that returns
// a Gitee client based on the environment configuration.
func provideGiteeClient(config config.Config) *scm.Client {
client, err := gitee.New(config.Gitee.APIServer)
if err != nil {
logrus.WithError(err).
Fatalln("main: cannot create the Gitee client")
}
if config.Gitee.Debug {
client.DumpResponse = httputil.DumpResponse
}
client.Client = &http.Client{
Transport: &oauth2.Transport{
Scheme: oauth2.SchemeBearer,
Source: &oauth2.Refresher{
ClientID: config.Gitee.ClientID,
ClientSecret: config.Gitee.ClientSecret,
Endpoint: strings.TrimSuffix(config.Gitee.Server, "/") + "/oauth/token",
Source: oauth2.ContextTokenSource(),
},
Base: defaultTransport(config.Gitee.SkipVerify),
},
}
return client
}
// provideGiteaClient is a Wire provider function that returns
// a Gitea client based on the environment configuration.
func provideGiteaClient(config config.Config) *scm.Client {
@ -180,13 +151,7 @@ func provideGitlabClient(config config.Config) *scm.Client {
}
client.Client = &http.Client{
Transport: &oauth2.Transport{
Scheme: oauth2.SchemeBearer,
Source: &oauth2.Refresher{
ClientID: config.GitLab.ClientID,
ClientSecret: config.GitLab.ClientSecret,
Endpoint: strings.TrimSuffix(config.GitLab.Server, "/") + "/oauth/token",
Source: oauth2.ContextTokenSource(),
},
Source: oauth2.ContextTokenSource(),
Base: defaultTransport(config.GitLab.SkipVerify),
},
}

View file

@ -19,7 +19,6 @@ import (
"github.com/drone/go-login/login"
"github.com/drone/go-login/login/bitbucket"
"github.com/drone/go-login/login/gitea"
"github.com/drone/go-login/login/gitee"
"github.com/drone/go-login/login/github"
"github.com/drone/go-login/login/gitlab"
"github.com/drone/go-login/login/gogs"
@ -45,8 +44,6 @@ func provideLogin(config config.Config) login.Middleware {
return provideBitbucketLogin(config)
case config.Github.ClientID != "":
return provideGithubLogin(config)
case config.Gitee.ClientID != "":
return provideGiteeLogin(config)
case config.Gitea.Server != "":
return provideGiteaLogin(config)
case config.GitLab.ClientID != "":
@ -90,33 +87,13 @@ func provideGithubLogin(config config.Config) login.Middleware {
}
}
// provideGiteeLogin is a Wire provider function that returns
// a Gitee authenticator based on the environment configuration.
func provideGiteeLogin(config config.Config) login.Middleware {
if config.Gitee.ClientID == "" {
return nil
}
redirectURL := config.Gitee.RedirectURL
if redirectURL == "" {
redirectURL = config.Server.Addr + "/login"
}
return &gitee.Config{
ClientID: config.Gitee.ClientID,
ClientSecret: config.Gitee.ClientSecret,
RedirectURL: redirectURL,
Server: config.Gitee.Server,
Scope: config.Gitee.Scope,
Client: defaultClient(config.Gitee.SkipVerify),
}
}
// provideGiteaLogin is a Wire provider function that returns
// a Gitea authenticator based on the environment configuration.
func provideGiteaLogin(config config.Config) login.Middleware {
if config.Gitea.Server == "" {
return nil
}
return &gitea.Config{
return &gitea.Config {
ClientID: config.Gitea.ClientID,
ClientSecret: config.Gitea.ClientSecret,
Server: config.Gitea.Server,
@ -197,23 +174,6 @@ func provideRefresher(config config.Config) *oauth2.Refresher {
Source: oauth2.ContextTokenSource(),
Client: defaultClient(config.Gitea.SkipVerify),
}
case config.GitLab.ClientID != "":
return &oauth2.Refresher{
ClientID: config.GitLab.ClientID,
ClientSecret: config.GitLab.ClientSecret,
Endpoint: strings.TrimSuffix(config.GitLab.Server, "/") + "/oauth/token",
Source: oauth2.ContextTokenSource(),
Client: defaultClient(config.GitLab.SkipVerify),
}
case config.Gitee.ClientID != "":
return &oauth2.Refresher{
ClientID: config.Gitee.ClientID,
ClientSecret: config.Gitee.ClientSecret,
Endpoint: strings.TrimSuffix(config.Gitee.Server, "/") + "/oauth/token",
Source: oauth2.ContextTokenSource(),
Client: defaultClient(config.Gitee.SkipVerify),
}
}
return nil
}

View file

@ -76,22 +76,17 @@ func provideConfigPlugin(client *scm.Client, contents core.FileService, conf spe
// provideConvertPlugin is a Wire provider function that returns
// a yaml conversion plugin based on the environment
// configuration.
func provideConvertPlugin(client *scm.Client, fileService core.FileService, conf spec.Config, templateStore core.TemplateStore) core.ConvertService {
func provideConvertPlugin(client *scm.Client, conf spec.Config, templateStore core.TemplateStore) core.ConvertService {
return converter.Combine(
conf.Convert.Multi,
converter.Legacy(false),
converter.Starlark(
conf.Starlark.Enabled,
conf.Starlark.StepLimit,
),
converter.Jsonnet(
conf.Jsonnet.Enabled,
conf.Jsonnet.ImportLimit,
fileService,
),
converter.Template(
templateStore,
conf.Starlark.StepLimit,
),
converter.Memoize(
converter.Remote(

View file

@ -120,6 +120,15 @@ func provideRepositoryService(client *scm.Client, renewer core.Renewer, config c
// provideSession is a Wire provider function that returns a
// user session based on the environment configuration.
func provideSession(store core.UserStore, config config.Config) (core.Session, error) {
if config.Session.MappingFile != "" {
return session.Legacy(store, session.Config{
Secure: config.Session.Secure,
Secret: config.Session.Secret,
Timeout: config.Session.Timeout,
MappingFile: config.Session.MappingFile,
})
}
return session.New(store, session.NewConfig(
config.Session.Secret,
config.Session.Timeout,
@ -212,7 +221,6 @@ func provideDatadog(
EnableStash: config.IsStash(),
EnableGogs: config.IsGogs(),
EnableGitea: config.IsGitea(),
EnableGitee: config.IsGitee(),
EnableAgents: !config.Agent.Disabled,
},
)

View file

@ -21,7 +21,6 @@ import (
"github.com/drone/drone/store/batch"
"github.com/drone/drone/store/batch2"
"github.com/drone/drone/store/build"
"github.com/drone/drone/store/card"
"github.com/drone/drone/store/cron"
"github.com/drone/drone/store/logs"
"github.com/drone/drone/store/perm"
@ -51,7 +50,6 @@ var storeSet = wire.NewSet(
provideBatchStore,
// batch.New,
cron.New,
card.New,
perm.New,
secret.New,
global.New,

View file

@ -1,6 +1,6 @@
// Code generated by Wire. DO NOT EDIT.
//go:generate wire
//go:generate go run github.com/google/wire/cmd/wire
//+build !wireinject
package main
@ -20,7 +20,6 @@ import (
"github.com/drone/drone/service/token"
"github.com/drone/drone/service/transfer"
"github.com/drone/drone/service/user"
"github.com/drone/drone/store/card"
"github.com/drone/drone/store/cron"
"github.com/drone/drone/store/perm"
"github.com/drone/drone/store/secret"
@ -71,20 +70,19 @@ func InitializeApplication(config2 config.Config) (application, error) {
fileService := provideContentService(client, renewer)
configService := provideConfigPlugin(client, fileService, config2)
templateStore := template.New(db)
convertService := provideConvertPlugin(client, fileService, config2, templateStore)
convertService := provideConvertPlugin(client, config2, templateStore)
validateService := provideValidatePlugin(config2)
triggerer := trigger.New(coreCanceler, configService, convertService, commitService, statusService, buildStore, scheduler, repositoryStore, userStore, validateService, webhookSender)
cronScheduler := cron2.New(commitService, cronStore, repositoryStore, userStore, triggerer)
reaper := provideReaper(repositoryStore, buildStore, stageStore, coreCanceler, config2)
coreLicense := provideLicense(client, config2)
datadog := provideDatadog(userStore, repositoryStore, buildStore, system, coreLicense, config2)
cardStore := card.New(db)
logStore := provideLogStore(db, config2)
logStream := livelog.New(redisDB)
netrcService := provideNetrcService(client, renewer, config2)
secretStore := secret.New(db, encrypter)
globalSecretStore := global.New(db, encrypter)
buildManager := manager.New(buildStore, cardStore, configService, convertService, corePubsub, logStore, logStream, netrcService, repositoryStore, scheduler, secretStore, globalSecretStore, statusService, stageStore, stepStore, system, userStore, webhookSender)
buildManager := manager.New(buildStore, configService, convertService, corePubsub, logStore, logStream, netrcService, repositoryStore, scheduler, secretStore, globalSecretStore, statusService, stageStore, stepStore, system, userStore, webhookSender)
secretService := provideSecretPlugin(config2)
registryService := provideRegistryPlugin(config2)
runner := provideRunner(buildManager, secretService, registryService, config2)
@ -101,7 +99,7 @@ func InitializeApplication(config2 config.Config) (application, error) {
syncer := provideSyncer(repositoryService, repositoryStore, userStore, batcher, config2)
transferer := transfer.New(repositoryStore, permStore)
userService := user.New(client, renewer)
server := api.New(buildStore, commitService, cardStore, cronStore, corePubsub, globalSecretStore, hookService, logStore, coreLicense, licenseService, organizationService, permStore, repositoryStore, repositoryService, scheduler, secretStore, stageStore, stepStore, statusService, session, logStream, syncer, system, templateStore, transferer, triggerer, userStore, userService, webhookSender)
server := api.New(buildStore, commitService, cronStore, corePubsub, globalSecretStore, hookService, logStore, coreLicense, licenseService, organizationService, permStore, repositoryStore, repositoryService, scheduler, secretStore, stageStore, stepStore, statusService, session, logStream, syncer, system, templateStore, transferer, triggerer, userStore, userService, webhookSender)
admissionService := provideAdmissionPlugin(client, organizationService, userService, config2)
hookParser := parser.New(client)
coreLinker := linker.New(client)

View file

@ -1,41 +0,0 @@
// Copyright 2019 Drone IO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package core
import (
"context"
"encoding/json"
"io"
)
type CardInput struct {
Schema string `json:"schema"`
Data json.RawMessage `json:"data"`
}
// CardStore manages repository cards.
type CardStore interface {
// Find returns a card data stream from the datastore.
Find(ctx context.Context, step int64) (io.ReadCloser, error)
// Create copies the card stream from Reader r to the datastore.
Create(ctx context.Context, step int64, r io.Reader) error
// Update copies the card stream from Reader r to the datastore.
Update(ctx context.Context, step int64, r io.Reader) error
// Delete purges the card data from the datastore.
Delete(ctx context.Context, step int64) error
}

View file

@ -65,36 +65,6 @@ type (
Secret string `json:"-"`
Build *Build `json:"build,omitempty"`
Perms *Perm `json:"permissions,omitempty"`
Archived bool `json:"archived"`
}
RepoBuildStage struct {
RepoNamespace string `json:"repo_namespace"`
RepoName string `json:"repo_name"`
RepoSlug string `json:"repo_slug"`
BuildNumber int64 `json:"build_number"`
BuildAuthor string `json:"build_author"`
BuildAuthorName string `json:"build_author_name"`
BuildAuthorEmail string `json:"build_author_email"`
BuildAuthorAvatar string `json:"build_author_avatar"`
BuildSender string `json:"build_sender"`
BuildStarted int64 `json:"build_started"`
BuildFinished int64 `json:"build_finished"`
BuildCreated int64 `json:"build_created"`
BuildUpdated int64 `json:"build_updated"`
StageName string `json:"stage_name"`
StageKind string `json:"stage_kind"`
StageType string `json:"stage_type"`
StageStatus string `json:"stage_status"`
StageMachine string `json:"stage_machine"`
StageOS string `json:"stage_os"`
StageArch string `json:"stage_arch"`
StageVariant string `json:"stage_variant"`
StageKernel string `json:"stage_kernel"`
StageLimit string `json:"stage_limit"`
StageLimitRepo string `json:"stage_limit_repo"`
StageStarted int64 `json:"stage_started"`
StageStopped int64 `json:"stage_stopped"`
}
// RepositoryStore defines operations for working with repositories.
@ -114,9 +84,6 @@ type (
// the datastore with incomplete builds.
ListIncomplete(context.Context) ([]*Repository, error)
// ListRunningStatus returns a list of build / repository /stage information for builds that are incomplete.
ListRunningStatus(context.Context) ([]*RepoBuildStage, error)
// ListAll returns a paginated list of all repositories
// stored in the database, including disabled repositories.
ListAll(ctx context.Context, limit, offset int) ([]*Repository, error)

View file

@ -20,7 +20,7 @@ type (
// Step represents an individual step in the stage.
Step struct {
ID int64 `json:"id"`
StageID int64 `json:"step_id"` // this is a typo, fixing it has far reaching ramifications. It should only be attempted in a major version change
StageID int64 `json:"step_id"`
Number int `json:"number"`
Name string `json:"name"`
Status string `json:"status"`
@ -33,7 +33,6 @@ type (
DependsOn []string `json:"depends_on,omitempty"`
Image string `json:"image,omitempty"`
Detached bool `json:"detached,omitempty"`
Schema string `json:"schema,omitempty"`
}
// StepStore persists build step information to storage.

14
go.mod
View file

@ -12,21 +12,21 @@ require (
github.com/coreos/go-semver v0.2.0
github.com/dchest/authcookie v0.0.0-20120917135355-fbdef6e99866
github.com/dchest/uniuri v0.0.0-20160212164326-8902c56451e9
github.com/drone/drone-go v1.7.2-0.20220308165842-f9e4fe31c2af
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/drone/drone-go v1.4.1-0.20201109202657-b9e58bbbcf27
github.com/drone/drone-runtime v1.1.1-0.20200623162453-61e33e2cab5d
github.com/drone/drone-ui v2.8.2+incompatible
github.com/drone/drone-ui v2.0.1+incompatible
github.com/drone/drone-yaml v1.2.4-0.20200326192514-6f4d6dfb39e4
github.com/drone/envsubst v1.0.3-0.20200709231038-aa43e1c1a629
github.com/drone/funcmap v0.0.0-20210823160631-9e9dec149056
github.com/drone/funcmap v0.0.0-20210823160631-9e9dec149056 // indirect
github.com/drone/go-license v1.0.2
github.com/drone/go-login v1.1.0
github.com/drone/go-scm v1.24.0
github.com/drone/go-login v1.0.4-0.20190311170324-2a4df4f242a2
github.com/drone/go-scm v1.15.2
github.com/drone/signal v1.0.0
github.com/dustin/go-humanize v1.0.0
github.com/go-chi/chi v3.3.3+incompatible
github.com/go-chi/cors v1.0.0
github.com/go-redis/redis/v8 v8.11.0
github.com/go-redsync/redsync/v4 v4.3.0
github.com/go-sql-driver/mysql v1.4.0
github.com/golang/mock v1.3.1
github.com/google/go-cmp v0.5.6
@ -35,7 +35,7 @@ require (
github.com/gosimple/slug v1.3.0
github.com/h2non/gock v1.0.15
github.com/hashicorp/go-cleanhttp v0.5.1 // indirect
github.com/hashicorp/go-multierror v1.1.0
github.com/hashicorp/go-multierror v1.0.0
github.com/hashicorp/go-retryablehttp v0.5.4
github.com/hashicorp/golang-lru v0.5.1
github.com/jmoiron/sqlx v0.0.0-20180614180643-0dae4fefe7c0

52
go.sum
View file

@ -73,25 +73,29 @@ github.com/docker/go-connections v0.3.0 h1:3lOnM9cSzgGwx8VfK/NGOW5fLQ0GjIlCkaktF
github.com/docker/go-connections v0.3.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
github.com/docker/go-units v0.3.3 h1:Xk8S3Xj5sLGlG5g67hJmYMmUgXv5N4PhkjJHHqrwnTk=
github.com/docker/go-units v0.3.3/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/drone/drone-go v1.7.2-0.20220308165842-f9e4fe31c2af h1:I+xfWPZLMaskFvfFO5fEJ6tVI1Q9bWR9tuORZeaCTPo=
github.com/drone/drone-go v1.7.2-0.20220308165842-f9e4fe31c2af/go.mod h1:fxCf9jAnXDZV1yDr0ckTuWd1intvcQwfJmTRpTZ1mXg=
github.com/drone/drone-go v1.4.1-0.20201109202657-b9e58bbbcf27 h1:58xKlW/Kwp/Apz+R5qNGzBUIzfq1Z57L7Udz1B6bgWE=
github.com/drone/drone-go v1.4.1-0.20201109202657-b9e58bbbcf27/go.mod h1:fxCf9jAnXDZV1yDr0ckTuWd1intvcQwfJmTRpTZ1mXg=
github.com/drone/drone-runtime v1.0.7-0.20190729202838-87c84080f4a1/go.mod h1:+osgwGADc/nyl40J0fdsf8Z09bgcBZXvXXnLOY48zYs=
github.com/drone/drone-runtime v1.1.1-0.20200623162453-61e33e2cab5d h1:P5HI/Y9hARTZ3F3EKs0kYijhjXZWQRQHYn1neTi0pWM=
github.com/drone/drone-runtime v1.1.1-0.20200623162453-61e33e2cab5d/go.mod h1:4/2QToW5+HGD0y1sTw7X35W1f7YINS14UfDY4isggT8=
github.com/drone/drone-ui v2.8.2+incompatible h1:7F/MlcSEIZVi5VND/qmOnDDwQOkgqwsCVOQOsGJ2HJc=
github.com/drone/drone-ui v2.8.2+incompatible/go.mod h1:NBtVWW7NNJpD9+huMD/5TAE1db2nrEh0i35/9Rf1MPI=
github.com/drone/drone-ui v0.0.0-20210812155550-12795bc368b3 h1:03iiv5fPLbTpz5Xh0w/Agc4p9UBub+bNFgIhIV6rwVU=
github.com/drone/drone-ui v0.0.0-20210812155550-12795bc368b3/go.mod h1:NBtVWW7NNJpD9+huMD/5TAE1db2nrEh0i35/9Rf1MPI=
github.com/drone/drone-ui v2.0.1+incompatible h1:p+cFE2xB5zlQKaEDWXNe2SGzbzyy0oAcmQE2oe8h/xw=
github.com/drone/drone-ui v2.0.1+incompatible/go.mod h1:NBtVWW7NNJpD9+huMD/5TAE1db2nrEh0i35/9Rf1MPI=
github.com/drone/drone-yaml v1.2.4-0.20200326192514-6f4d6dfb39e4 h1:XsstoCeXC2t8lA9OLTdoFwckaptqahxwjCWsenySfX8=
github.com/drone/drone-yaml v1.2.4-0.20200326192514-6f4d6dfb39e4/go.mod h1:QsqliFK8nG04AHFN9tTn9XJomRBQHD4wcejWW1uz/10=
github.com/drone/envsubst v1.0.3-0.20200709231038-aa43e1c1a629 h1:rIaZZalMGGPb2cU/+ypuggZ8aMlpa17RUlJUtsMv8pw=
github.com/drone/envsubst v1.0.3-0.20200709231038-aa43e1c1a629/go.mod h1:N2jZmlMufstn1KEqvbHjw40h1KyTmnVzHcSc9bFiJ2g=
github.com/drone/funcmap v0.0.0-20190918184546-d4ef6e88376d h1:/IO7UVVu191Jc0DajV4cDVoO+91cuppvgxg2MZl+AXI=
github.com/drone/funcmap v0.0.0-20190918184546-d4ef6e88376d/go.mod h1:Hph0/pT6ZxbujnE1Z6/08p5I0XXuOsppqF6NQlGOK0E=
github.com/drone/funcmap v0.0.0-20210823160631-9e9dec149056 h1:SCJwMR0FMA0aKwAntCBh02YmtHEnU40zaDzeeCvIRug=
github.com/drone/funcmap v0.0.0-20210823160631-9e9dec149056/go.mod h1:Hph0/pT6ZxbujnE1Z6/08p5I0XXuOsppqF6NQlGOK0E=
github.com/drone/go-license v1.0.2 h1:7OwndfYk+Lp/cGHkxe4HUn/Ysrrw3WYH2pnd99yrkok=
github.com/drone/go-license v1.0.2/go.mod h1:fGRHf+F1cEaw3YVYiJ6js3G3dVhcxyS617RnNRUMsms=
github.com/drone/go-login v1.1.0 h1:anQFRh2Z5ketEJ/LvL6SJ6rIwDdfysGXK5bSXkFLInI=
github.com/drone/go-login v1.1.0/go.mod h1:FLxy9vRzLbyBxoCJYxGbG9R0WGn6OyuvBmAtYNt43uw=
github.com/drone/go-scm v1.24.0 h1:wE6bP9gnuyyKJStnl6wl0npt/SBQumjE9jilQAcFy6Q=
github.com/drone/go-scm v1.24.0/go.mod h1:DFIJJjhMj0TSXPz+0ni4nyZ9gtTtC40Vh/TGRugtyWw=
github.com/drone/go-login v1.0.4-0.20190311170324-2a4df4f242a2 h1:RGpgNkowJc5LAVn/ZONx70qmnaTA0z/3hHPzTBdAEO8=
github.com/drone/go-login v1.0.4-0.20190311170324-2a4df4f242a2/go.mod h1:FLxy9vRzLbyBxoCJYxGbG9R0WGn6OyuvBmAtYNt43uw=
github.com/drone/go-scm v1.15.2 h1:H5iDEGTYZwb/n3sx+ekbXHOwqi/3sYTJJunJUiXLAVA=
github.com/drone/go-scm v1.15.2/go.mod h1:lXwfbyrIJwFFME5TpzavkwO2T5X8yBK6t6cve7g91x0=
github.com/drone/signal v1.0.0 h1:NrnM2M/4yAuU/tXs6RP1a1ZfxnaHwYkd0kJurA1p6uI=
github.com/drone/signal v1.0.0/go.mod h1:S8t92eFT0g4WUgEc/LxG+LCuiskpMNsG0ajAMGnyZpc=
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
@ -109,15 +113,8 @@ github.com/go-chi/chi v3.3.3+incompatible h1:KHkmBEMNkwKuK4FdQL7N2wOeB9jnIx7jR5w
github.com/go-chi/chi v3.3.3+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ=
github.com/go-chi/cors v1.0.0 h1:e6x8k7uWbUwYs+aXDoiUzeQFT6l0cygBYyNhD7/1Tg0=
github.com/go-chi/cors v1.0.0/go.mod h1:K2Yje0VW/SJzxiyMYu6iPQYa7hMjQX2i/F491VChg1I=
github.com/go-redis/redis v6.15.9+incompatible h1:K0pv1D7EQUjfyoMql+r/jZqCLizCGKFlFgcHWWmHQjg=
github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/go-redis/redis/v7 v7.4.0 h1:7obg6wUoj05T0EpY0o8B59S9w5yeMWql7sw2kwNW1x4=
github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg=
github.com/go-redis/redis/v8 v8.1.1/go.mod h1:ysgGY09J/QeDYbu3HikWEIPCwaeOkuNoTgKayTEaEOw=
github.com/go-redis/redis/v8 v8.11.0 h1:O1Td0mQ8UFChQ3N9zFQqo6kTU2cJ+/it88gDB+zg0wo=
github.com/go-redis/redis/v8 v8.11.0/go.mod h1:DLomh7y2e3ggQXQLd1YgmvIfecPJoFl7WU5SOQ/r06M=
github.com/go-redsync/redsync/v4 v4.3.0 h1:5cNxbHJc/tr1KX04piPv8nylURyuT3nqjmodkW8JCjM=
github.com/go-redsync/redsync/v4 v4.3.0/go.mod h1:QBOJAs1k8O6Eyrre4a++pxQgHe5eQ+HF56KuTVv+8Bs=
github.com/go-sql-driver/mysql v1.4.0 h1:7LxgVwFb2hIQtMm87NdgAVfXjnt4OePseqT1tKx+opk=
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/gogo/protobuf v0.0.0-20170307180453-100ba4e88506 h1:zDlw+wgyXdfkRuvFCdEDUiPLmZp2cvf/dWHazY0a5VM=
@ -138,14 +135,11 @@ github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:W
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/gomodule/redigo v1.8.2 h1:H5XSIre1MB5NbPYFp+i1NBbb5qN1W8Y8YAQoAYbkm8k=
github.com/gomodule/redigo v1.8.2/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-jsonnet v0.17.0 h1:/9NIEfhK1NQRKl3sP2536b2+x5HnZMdql7x3yK/l8JY=
@ -166,8 +160,8 @@ github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brv
github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM=
github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-multierror v1.1.0 h1:B9UzwGQJehnUY1yNrnwREHc3fGbC2xefo8g4TbElacI=
github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA=
github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-retryablehttp v0.5.4 h1:1BZvpawXoJCWX6pNtow9+rpEj+3itIlutiqnntI6jOE=
github.com/hashicorp/go-retryablehttp v0.5.4/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
@ -217,15 +211,11 @@ github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uY
github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.14.1/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY=
github.com/onsi/ginkgo v1.15.0 h1:1V1NfVQR87RtWAgp1lv9JZJ5Jap+XFGKPi00andXGi4=
github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg=
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.10.2/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.10.5 h1:7n6FEkpFmfCoo2t+YYqXH0evK+a9ICQz0xcAy9dYcaQ=
github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48=
github.com/opencontainers/go-digest v1.0.0-rc1 h1:WzifXhOVOEOuFYOJAW6aQqW0TooG2iki3E3Ii+WN7gQ=
@ -265,18 +255,13 @@ github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203 h1:QVqDTf3h2WHt08YuiTGPZLls0Wq99X9bWd0Q5ZSBesM=
github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203/go.mod h1:oqN97ltKNihBbwlX8dLpwxCl3+HnXKV/R0e+sRLd9C8=
github.com/unrolled/secure v0.0.0-20181022170031-4b6b7cf51606 h1:dU9yXzNi9rl6Mou7+3npdfPyeFPb2+7BHs3zL47bhPY=
github.com/unrolled/secure v0.0.0-20181022170031-4b6b7cf51606/go.mod h1:mnPT77IAdsi/kV7+Es7y+pXALeV3h7G6dQF6mNYjcLA=
github.com/vinzenz/yaml v0.0.0-20170920082545-91409cdd725d h1:3wDi6J5APMqaHBVPuVd7RmHD2gRTfqbdcVSpCNoUWtk=
github.com/vinzenz/yaml v0.0.0-20170920082545-91409cdd725d/go.mod h1:mb5taDqMnJiZNRQ3+02W2IFG+oEz1+dTuCXkp4jpkfo=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.opentelemetry.io/otel v0.11.0/go.mod h1:G8UCk+KooF2HLkgo8RHX9epABH/aRGYET7gQOqBVdB0=
go.starlark.net v0.0.0-20201118183435-e55f603d8c79 h1:JPjLPz44y2N9mkzh2N344kTk1Y4/V4yJAjTrXGmzv8I=
go.starlark.net v0.0.0-20201118183435-e55f603d8c79/go.mod h1:5YFcFnRptTN+41758c2bMPiqpGg4zBfYji1IQz8wNFk=
golang.org/x/crypto v0.0.0-20180820150726-614d502a4dac/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
@ -301,7 +286,6 @@ golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
@ -323,12 +307,9 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210112080510-489259a85091 h1:DMyOG0U+gKfu8JZzg2UQe9MeaC1X+xQWlAKcRnjxjCw=
@ -385,14 +366,11 @@ gopkg.in/h2non/gock.v1 v1.0.14/go.mod h1:sX4zAkdYX1TRGJ2JY156cFspQn4yRWn6p9EMdOD
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/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=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

View file

@ -23,7 +23,6 @@ import (
"github.com/drone/drone/handler/api/auth"
"github.com/drone/drone/handler/api/badge"
globalbuilds "github.com/drone/drone/handler/api/builds"
"github.com/drone/drone/handler/api/card"
"github.com/drone/drone/handler/api/ccmenu"
"github.com/drone/drone/handler/api/events"
"github.com/drone/drone/handler/api/queue"
@ -64,7 +63,6 @@ var corsOpts = cors.Options{
func New(
builds core.BuildStore,
commits core.CommitService,
card core.CardStore,
cron core.CronStore,
events core.Pubsub,
globals core.GlobalSecretStore,
@ -94,7 +92,6 @@ func New(
) Server {
return Server{
Builds: builds,
Card: card,
Cron: cron,
Commits: commits,
Events: events,
@ -128,7 +125,6 @@ func New(
// Server is a http.Handler which exposes drone functionality over HTTP.
type Server struct {
Builds core.BuildStore
Card core.CardStore
Cron core.CronStore
Commits core.CommitService
Events core.Pubsub
@ -289,16 +285,6 @@ func (s Server) Handler() http.Handler {
acl.CheckAdminAccess(),
).Delete("/{member}", collabs.HandleDelete(s.Users, s.Repos, s.Perms))
})
r.Route("/cards", func(r chi.Router) {
r.Get("/{build}/{stage}/{step}", card.HandleFind(s.Builds, s.Card, s.Stages, s.Steps, s.Repos))
r.With(
acl.CheckAdminAccess(),
).Post("/{build}/{stage}/{step}", card.HandleCreate(s.Builds, s.Card, s.Stages, s.Steps, s.Repos))
r.With(
acl.CheckAdminAccess(),
).Delete("/{build}/{stage}/{step}", card.HandleDelete(s.Builds, s.Card, s.Stages, s.Steps, s.Repos))
})
})
})
@ -359,7 +345,6 @@ func (s Server) Handler() http.Handler {
r.Route("/builds", func(r chi.Router) {
r.Use(acl.AuthorizeAdmin)
r.Get("/incomplete", globalbuilds.HandleIncomplete(s.Repos))
r.Get("/incomplete/v2", globalbuilds.HandleRunningStatus(s.Repos))
})
r.Route("/secrets", func(r chi.Router) {

View file

@ -28,16 +28,3 @@ func HandleIncomplete(repos core.RepositoryStore) http.HandlerFunc {
}
}
}
func HandleRunningStatus(repos core.RepositoryStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
list, err := repos.ListRunningStatus(r.Context())
if err != nil {
render.InternalError(w, err)
logger.FromRequest(r).WithError(err).
Debugln("api: cannot list incomplete builds")
} else {
render.JSON(w, list, 200)
}
}
}

View file

@ -31,7 +31,3 @@ var notImplemented = func(w http.ResponseWriter, r *http.Request) {
func HandleIncomplete(repos core.RepositoryStore) http.HandlerFunc {
return notImplemented
}
func HandleRunningStatus(repos core.RepositoryStore) http.HandlerFunc {
return notImplemented
}

View file

@ -1,103 +0,0 @@
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
// +build !oss
package card
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"strconv"
"github.com/drone/drone/core"
"github.com/drone/drone/handler/api/render"
"github.com/go-chi/chi"
)
// HandleCreate returns an http.HandlerFunc that processes http
// requests to create a new card.
func HandleCreate(
buildStore core.BuildStore,
cardStore core.CardStore,
stageStore core.StageStore,
stepStore core.StepStore,
repoStore core.RepositoryStore,
) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
namespace = chi.URLParam(r, "owner")
name = chi.URLParam(r, "name")
)
buildNumber, err := strconv.ParseInt(chi.URLParam(r, "build"), 10, 64)
if err != nil {
render.BadRequest(w, err)
return
}
stageNumber, err := strconv.Atoi(chi.URLParam(r, "stage"))
if err != nil {
render.BadRequest(w, err)
return
}
stepNumber, err := strconv.Atoi(chi.URLParam(r, "step"))
if err != nil {
render.BadRequest(w, err)
return
}
in := new(core.CardInput)
err = json.NewDecoder(r.Body).Decode(in)
if err != nil {
render.BadRequest(w, err)
return
}
repo, err := repoStore.FindName(r.Context(), namespace, name)
if err != nil {
render.NotFound(w, err)
return
}
build, err := buildStore.FindNumber(r.Context(), repo.ID, buildNumber)
if err != nil {
render.NotFound(w, err)
return
}
stage, err := stageStore.FindNumber(r.Context(), build.ID, stageNumber)
if err != nil {
render.NotFound(w, err)
return
}
step, err := stepStore.FindNumber(r.Context(), stage.ID, stepNumber)
if err != nil {
render.NotFound(w, err)
return
}
data := ioutil.NopCloser(
bytes.NewBuffer(in.Data),
)
/// create card
err = cardStore.Create(r.Context(), step.ID, data)
if err != nil {
render.InternalError(w, err)
return
}
// add schema
step.Schema = in.Schema
err = stepStore.Update(r.Context(), step)
if err != nil {
render.InternalError(w, err)
return
}
render.JSON(w, step.ID, 200)
}
}

View file

@ -1,168 +0,0 @@
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
// +build !oss
package card
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/drone/drone/core"
"github.com/drone/drone/handler/api/errors"
"github.com/drone/drone/mock"
"github.com/go-chi/chi"
"github.com/golang/mock/gomock"
"github.com/google/go-cmp/cmp"
)
type card struct {
Id int64 `json:"id,omitempty"`
Data []byte `json:"card_data"`
}
var (
dummyRepo = &core.Repository{
ID: 1,
UserID: 1,
Slug: "octocat/hello-world",
}
dummyBuild = &core.Build{
ID: 1,
RepoID: 1,
Number: 1,
}
dummyStage = &core.Stage{
ID: 1,
BuildID: 1,
}
dummyStep = &core.Step{
ID: 1,
StageID: 1,
Schema: "https://myschema.com",
}
dummyCard = &card{
Id: dummyStep.ID,
Data: []byte("{\"type\": \"AdaptiveCard\"}"),
}
)
func TestHandleCreate(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
repos := mock.NewMockRepositoryStore(controller)
repos.EXPECT().FindName(gomock.Any(), "octocat", "hello-world").Return(dummyRepo, nil)
build := mock.NewMockBuildStore(controller)
build.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyBuild, nil)
stage := mock.NewMockStageStore(controller)
stage.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyStage, nil)
step := mock.NewMockStepStore(controller)
step.EXPECT().FindNumber(gomock.Any(), dummyStage.ID, gomock.Any()).Return(dummyStep, nil)
step.EXPECT().Update(gomock.Any(), gomock.Any()).Return(nil)
card := mock.NewMockCardStore(controller)
card.EXPECT().Create(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
c := new(chi.Context)
c.URLParams.Add("owner", "octocat")
c.URLParams.Add("name", "hello-world")
c.URLParams.Add("build", "1")
c.URLParams.Add("stage", "1")
c.URLParams.Add("step", "1")
in := new(bytes.Buffer)
json.NewEncoder(in).Encode(dummyCard)
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/", in)
r = r.WithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, c),
)
HandleCreate(build, card, stage, step, repos).ServeHTTP(w, r)
if got, want := w.Code, http.StatusOK; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
}
func TestHandleCreate_BadRequest(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
c := new(chi.Context)
c.URLParams.Add("owner", "octocat")
c.URLParams.Add("name", "hello-world")
c.URLParams.Add("build", "1")
c.URLParams.Add("stage", "1")
c.URLParams.Add("step", "1")
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/", nil)
r = r.WithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, c),
)
HandleCreate(nil, nil, nil, nil, nil).ServeHTTP(w, r)
got, want := &errors.Error{}, &errors.Error{Message: "EOF"}
json.NewDecoder(w.Body).Decode(got)
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
}
func TestHandleCreate_CreateError(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
repos := mock.NewMockRepositoryStore(controller)
repos.EXPECT().FindName(gomock.Any(), "octocat", "hello-world").Return(dummyRepo, nil)
build := mock.NewMockBuildStore(controller)
build.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyBuild, nil)
stage := mock.NewMockStageStore(controller)
stage.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyStage, nil)
card := mock.NewMockCardStore(controller)
card.EXPECT().Create(gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.ErrNotFound)
step := mock.NewMockStepStore(controller)
step.EXPECT().FindNumber(gomock.Any(), dummyStage.ID, gomock.Any()).Return(dummyStep, nil)
c := new(chi.Context)
c.URLParams.Add("owner", "octocat")
c.URLParams.Add("name", "hello-world")
c.URLParams.Add("build", "1")
c.URLParams.Add("stage", "1")
c.URLParams.Add("step", "1")
in := new(bytes.Buffer)
json.NewEncoder(in).Encode(dummyCard)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", in)
r = r.WithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, c),
)
HandleCreate(build, card, stage, step, repos).ServeHTTP(w, r)
if got, want := w.Code, http.StatusInternalServerError; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
got, want := new(errors.Error), errors.ErrNotFound
json.NewDecoder(w.Body).Decode(got)
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
}

View file

@ -1,86 +0,0 @@
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
// +build !oss
package card
import (
"strconv"
"github.com/drone/drone/core"
"github.com/drone/drone/handler/api/render"
"net/http"
"github.com/go-chi/chi"
)
// HandleDelete returns an http.HandlerFunc that processes http
// requests to delete a card.
func HandleDelete(
buildStore core.BuildStore,
cardStore core.CardStore,
stageStore core.StageStore,
stepStore core.StepStore,
repoStore core.RepositoryStore,
) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
namespace = chi.URLParam(r, "owner")
name = chi.URLParam(r, "name")
)
buildNumber, err := strconv.ParseInt(chi.URLParam(r, "build"), 10, 64)
if err != nil {
render.BadRequest(w, err)
return
}
stageNumber, err := strconv.Atoi(chi.URLParam(r, "stage"))
if err != nil {
render.BadRequest(w, err)
return
}
stepNumber, err := strconv.Atoi(chi.URLParam(r, "step"))
if err != nil {
render.BadRequest(w, err)
return
}
repo, err := repoStore.FindName(r.Context(), namespace, name)
if err != nil {
render.NotFound(w, err)
return
}
build, err := buildStore.FindNumber(r.Context(), repo.ID, buildNumber)
if err != nil {
render.NotFound(w, err)
return
}
stage, err := stageStore.FindNumber(r.Context(), build.ID, stageNumber)
if err != nil {
render.NotFound(w, err)
return
}
step, err := stepStore.FindNumber(r.Context(), stage.ID, stepNumber)
if err != nil {
render.NotFound(w, err)
return
}
_, err = cardStore.Find(r.Context(), step.ID)
if err != nil {
render.NotFound(w, err)
return
}
err = cardStore.Delete(r.Context(), step.ID)
if err != nil {
render.InternalError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
}

View file

@ -1,156 +0,0 @@
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
// +build !oss
package card
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/drone/drone/handler/api/errors"
"github.com/drone/drone/mock"
"github.com/go-chi/chi"
"github.com/golang/mock/gomock"
"github.com/google/go-cmp/cmp"
)
func TestHandleDelete(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
repos := mock.NewMockRepositoryStore(controller)
repos.EXPECT().FindName(gomock.Any(), "octocat", "hello-world").Return(dummyRepo, nil)
build := mock.NewMockBuildStore(controller)
build.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyBuild, nil)
stage := mock.NewMockStageStore(controller)
stage.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyStage, nil)
step := mock.NewMockStepStore(controller)
step.EXPECT().FindNumber(gomock.Any(), dummyStage.ID, gomock.Any()).Return(dummyStep, nil)
card := mock.NewMockCardStore(controller)
card.EXPECT().Find(gomock.Any(), dummyStep.ID).Return(ioutil.NopCloser(
bytes.NewBuffer(dummyCard.Data),
), nil)
card.EXPECT().Delete(gomock.Any(), dummyCard.Id).Return(nil)
c := new(chi.Context)
c.URLParams.Add("owner", "octocat")
c.URLParams.Add("name", "hello-world")
c.URLParams.Add("build", "1")
c.URLParams.Add("stage", "1")
c.URLParams.Add("step", "1")
w := httptest.NewRecorder()
r := httptest.NewRequest("DELETE", "/", nil)
r = r.WithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, c),
)
HandleDelete(build, card, stage, step, repos).ServeHTTP(w, r)
if got, want := w.Code, http.StatusNoContent; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
}
func TestHandleDelete_CardNotFound(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
repos := mock.NewMockRepositoryStore(controller)
repos.EXPECT().FindName(gomock.Any(), "octocat", "hello-world").Return(dummyRepo, nil)
build := mock.NewMockBuildStore(controller)
build.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyBuild, nil)
stage := mock.NewMockStageStore(controller)
stage.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyStage, nil)
step := mock.NewMockStepStore(controller)
step.EXPECT().FindNumber(gomock.Any(), dummyStage.ID, gomock.Any()).Return(dummyStep, nil)
card := mock.NewMockCardStore(controller)
card.EXPECT().Find(gomock.Any(), dummyStep.ID).Return(nil, errors.ErrNotFound)
c := new(chi.Context)
c.URLParams.Add("owner", "octocat")
c.URLParams.Add("name", "hello-world")
c.URLParams.Add("build", "1")
c.URLParams.Add("stage", "1")
c.URLParams.Add("step", "1")
w := httptest.NewRecorder()
r := httptest.NewRequest("DELETE", "/", nil)
r = r.WithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, c),
)
HandleDelete(build, card, stage, step, repos).ServeHTTP(w, r)
if got, want := w.Code, http.StatusNotFound; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
got, want := new(errors.Error), errors.ErrNotFound
json.NewDecoder(w.Body).Decode(got)
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
}
func TestHandleDelete_DeleteError(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
repos := mock.NewMockRepositoryStore(controller)
repos.EXPECT().FindName(gomock.Any(), "octocat", "hello-world").Return(dummyRepo, nil)
build := mock.NewMockBuildStore(controller)
build.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyBuild, nil)
stage := mock.NewMockStageStore(controller)
stage.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyStage, nil)
step := mock.NewMockStepStore(controller)
step.EXPECT().FindNumber(gomock.Any(), dummyStage.ID, gomock.Any()).Return(dummyStep, nil)
card := mock.NewMockCardStore(controller)
card.EXPECT().Find(gomock.Any(), dummyStep.ID).Return(ioutil.NopCloser(
bytes.NewBuffer(dummyCard.Data),
), nil)
card.EXPECT().Delete(gomock.Any(), dummyCard.Id).Return(errors.ErrNotFound)
c := new(chi.Context)
c.URLParams.Add("owner", "octocat")
c.URLParams.Add("name", "hello-world")
c.URLParams.Add("build", "1")
c.URLParams.Add("stage", "1")
c.URLParams.Add("step", "1")
w := httptest.NewRecorder()
r := httptest.NewRequest("DELETE", "/", nil)
r = r.WithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, c),
)
HandleDelete(build, card, stage, step, repos).ServeHTTP(w, r)
if got, want := w.Code, http.StatusInternalServerError; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
got, want := new(errors.Error), errors.ErrNotFound
json.NewDecoder(w.Body).Decode(got)
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
}

View file

@ -1,82 +0,0 @@
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
// +build !oss
package card
import (
"io"
"net/http"
"strconv"
"github.com/drone/drone/core"
"github.com/drone/drone/handler/api/render"
"github.com/go-chi/chi"
)
// HandleFind returns an http.HandlerFunc that writes a json-encoded
func HandleFind(
buildStore core.BuildStore,
cardStore core.CardStore,
stageStore core.StageStore,
stepStore core.StepStore,
repoStore core.RepositoryStore,
) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
namespace = chi.URLParam(r, "owner")
name = chi.URLParam(r, "name")
)
buildNumber, err := strconv.ParseInt(chi.URLParam(r, "build"), 10, 64)
if err != nil {
render.BadRequest(w, err)
return
}
stageNumber, err := strconv.Atoi(chi.URLParam(r, "stage"))
if err != nil {
render.BadRequest(w, err)
return
}
stepNumber, err := strconv.Atoi(chi.URLParam(r, "step"))
if err != nil {
render.BadRequest(w, err)
return
}
repo, err := repoStore.FindName(r.Context(), namespace, name)
if err != nil {
render.NotFound(w, err)
return
}
build, err := buildStore.FindNumber(r.Context(), repo.ID, buildNumber)
if err != nil {
render.NotFound(w, err)
return
}
stage, err := stageStore.FindNumber(r.Context(), build.ID, stageNumber)
if err != nil {
render.NotFound(w, err)
return
}
step, err := stepStore.FindNumber(r.Context(), stage.ID, stepNumber)
if err != nil {
render.NotFound(w, err)
return
}
cardData, err := cardStore.Find(r.Context(), step.ID)
if err != nil {
render.NotFound(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
io.Copy(w, cardData)
cardData.Close()
}
}

View file

@ -1,114 +0,0 @@
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
// +build !oss
package card
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/drone/drone/handler/api/errors"
"github.com/drone/drone/mock"
"github.com/go-chi/chi"
"github.com/golang/mock/gomock"
"github.com/google/go-cmp/cmp"
)
func TestHandleFind(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
repos := mock.NewMockRepositoryStore(controller)
repos.EXPECT().FindName(gomock.Any(), "octocat", "hello-world").Return(dummyRepo, nil)
build := mock.NewMockBuildStore(controller)
build.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyBuild, nil)
stage := mock.NewMockStageStore(controller)
stage.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyStage, nil)
step := mock.NewMockStepStore(controller)
step.EXPECT().FindNumber(gomock.Any(), dummyStage.ID, gomock.Any()).Return(dummyStep, nil)
card := mock.NewMockCardStore(controller)
card.EXPECT().Find(gomock.Any(), dummyStep.ID).Return(ioutil.NopCloser(
bytes.NewBuffer(dummyCard.Data),
), nil)
c := new(chi.Context)
c.URLParams.Add("owner", "octocat")
c.URLParams.Add("name", "hello-world")
c.URLParams.Add("build", "1")
c.URLParams.Add("stage", "1")
c.URLParams.Add("step", "1")
in := new(bytes.Buffer)
json.NewEncoder(in).Encode(dummyCard)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", in)
r = r.WithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, c),
)
HandleFind(build, card, stage, step, repos).ServeHTTP(w, r)
if got, want := w.Code, http.StatusOK; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
}
func TestHandleFind_CardNotFound(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
repos := mock.NewMockRepositoryStore(controller)
repos.EXPECT().FindName(gomock.Any(), "octocat", "hello-world").Return(dummyRepo, nil)
build := mock.NewMockBuildStore(controller)
build.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyBuild, nil)
stage := mock.NewMockStageStore(controller)
stage.EXPECT().FindNumber(gomock.Any(), dummyBuild.ID, gomock.Any()).Return(dummyStage, nil)
step := mock.NewMockStepStore(controller)
step.EXPECT().FindNumber(gomock.Any(), dummyStage.ID, gomock.Any()).Return(dummyStep, nil)
card := mock.NewMockCardStore(controller)
card.EXPECT().Find(gomock.Any(), dummyStep.ID).Return(nil, errors.ErrNotFound)
c := new(chi.Context)
c.URLParams.Add("owner", "octocat")
c.URLParams.Add("name", "hello-world")
c.URLParams.Add("build", "1")
c.URLParams.Add("stage", "1")
c.URLParams.Add("step", "1")
in := new(bytes.Buffer)
json.NewEncoder(in).Encode(dummyCard)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", in)
r = r.WithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, c),
)
HandleFind(build, card, stage, step, repos).ServeHTTP(w, r)
if got, want := w.Code, http.StatusNotFound; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
got, want := new(errors.Error), errors.ErrNotFound
json.NewDecoder(w.Body).Decode(got)
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
}

View file

@ -1,76 +0,0 @@
// Copyright 2019 Drone IO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build oss
package card
import (
"net/http"
"github.com/drone/drone/core"
"github.com/drone/drone/handler/api/render"
)
var notImplemented = func(w http.ResponseWriter, r *http.Request) {
render.NotImplemented(w, render.ErrNotImplemented)
}
func HandleCreate(
buildStore core.BuildStore,
cardStore core.CardStore,
stageStore core.StageStore,
stepStore core.StepStore,
repoStore core.RepositoryStore,
) http.HandlerFunc {
return notImplemented
}
func HandleDelete(
buildStore core.BuildStore,
cardStore core.CardStore,
stageStore core.StageStore,
stepStore core.StepStore,
repoStore core.RepositoryStore,
) http.HandlerFunc {
return notImplemented
}
func HandleFind(
buildStore core.BuildStore,
cardStore core.CardStore,
stageStore core.StageStore,
stepStore core.StepStore,
repoStore core.RepositoryStore,
) http.HandlerFunc {
return notImplemented
}
func HandleFindAll(
buildStore core.BuildStore,
cardStore core.CardStore,
repoStore core.RepositoryStore,
) http.HandlerFunc {
return notImplemented
}
func HandleFindData(
buildStore core.BuildStore,
cardStore core.CardStore,
stageStore core.StageStore,
stepStore core.StepStore,
repoStore core.RepositoryStore,
) http.HandlerFunc {
return notImplemented
}

View file

@ -82,7 +82,6 @@ func HandleEvents(
events, errc := events.Subscribe(ctx)
logger.Debugln("events: stream opened")
timeoutChan := time.After(24 * time.Hour)
L:
for {
select {
@ -92,7 +91,7 @@ func HandleEvents(
case <-errc:
logger.Debugln("events: stream error")
break L
case <-timeoutChan:
case <-time.After(time.Hour):
logger.Debugln("events: stream timeout")
break L
case <-time.After(pingInterval):

View file

@ -63,7 +63,6 @@ func HandleGlobal(
events, errc := events.Subscribe(ctx)
logger.Debugln("events: stream opened")
timeoutChan := time.After(24 * time.Hour)
L:
for {
select {
@ -73,7 +72,7 @@ func HandleGlobal(
case <-errc:
logger.Debugln("events: stream error")
break L
case <-timeoutChan:
case <-time.After(time.Hour):
logger.Debugln("events: stream timeout")
break L
case <-time.After(pingInterval):

View file

@ -102,7 +102,6 @@ func HandleLogStream(
return
}
timeoutChan := time.After(24 * time.Hour)
L:
for {
select {
@ -110,7 +109,7 @@ func HandleLogStream(
break L
case <-errc:
break L
case <-timeoutChan:
case <-time.After(time.Hour):
break L
case <-time.After(pingInterval):
io.WriteString(w, ": ping\n\n")

View file

@ -37,7 +37,6 @@ func HandleList(
namespace = chi.URLParam(r, "owner")
name = chi.URLParam(r, "name")
branch = r.FormValue("branch")
tag = r.FormValue("tag")
page = r.FormValue("page")
perPage = r.FormValue("per_page")
)
@ -67,9 +66,6 @@ func HandleList(
if branch != "" {
ref := fmt.Sprintf("refs/heads/%s", branch)
results, err = builds.ListRef(r.Context(), repo.ID, ref, limit, offset)
} else if tag != "" {
ref := fmt.Sprintf("refs/tags/%s", tag)
results, err = builds.ListRef(r.Context(), repo.ID, ref, limit, offset)
} else {
results, err = builds.List(r.Context(), repo.ID, limit, offset)
}

View file

@ -139,38 +139,6 @@ func TestListBranch(t *testing.T) {
}
}
func TestListTag(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
repos := mock.NewMockRepositoryStore(controller)
repos.EXPECT().FindName(gomock.Any(), gomock.Any(), mockRepo.Name).Return(mockRepo, nil)
builds := mock.NewMockBuildStore(controller)
builds.EXPECT().ListRef(gomock.Any(), mockRepo.ID, "refs/tags/1.33.7", 25, 0).Return(mockBuilds, nil)
c := new(chi.Context)
c.URLParams.Add("owner", "octocat")
c.URLParams.Add("name", "hello-world")
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/?tag=1.33.7", nil)
r = r.WithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, c),
)
HandleList(repos, builds)(w, r)
if got, want := w.Code, 200; want != got {
t.Errorf("Want response code %d, got %d", want, got)
}
got, want := []*core.Build{}, mockBuilds
json.NewDecoder(w.Body).Decode(&got)
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
}
func TestList_RepositoryNotFound(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()

View file

@ -64,7 +64,6 @@ func HandleRetry(
}
hook := &core.Hook{
Parent: prev.Number,
Trigger: user.Login,
Event: prev.Event,
Action: prev.Action,

View file

@ -24,7 +24,7 @@ import (
var (
dummyTemplate = &core.Template{
Name: "my_template.yml",
Name: "my_template",
Data: "my_data",
Created: 1,
Updated: 2,

View file

@ -8,23 +8,16 @@ package template
import (
"encoding/json"
"github.com/go-chi/chi"
"net/http"
"path/filepath"
"github.com/drone/drone/core"
"github.com/drone/drone/handler/api/errors"
"github.com/drone/drone/handler/api/render"
"github.com/go-chi/chi"
)
var (
errTemplateExtensionInvalid = errors.New("Template extension invalid. Must be yaml, starlark or jsonnet")
)
type templateInput struct {
Name string `json:"name"`
Data string `json:"data"`
Name string `json:"name"`
Data string `json:"data"`
}
// HandleCreate returns an http.HandlerFunc that processes http
@ -39,16 +32,6 @@ func HandleCreate(templateStore core.TemplateStore) http.HandlerFunc {
return
}
// check valid template extension type
switch filepath.Ext(in.Name) {
case ".yml", ".yaml":
case ".star", ".starlark", ".script":
case ".jsonnet":
default:
render.BadRequest(w, errTemplateExtensionInvalid)
return
}
t := &core.Template{
Name: in.Name,
Data: in.Data,

View file

@ -48,13 +48,13 @@ func TestHandleCreate(t *testing.T) {
}
}
func TestHandleCreate_NotValidTemplateExtensionName(t *testing.T) {
func TestHandleCreate_ValidationErrorName(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
c := new(chi.Context)
in := new(bytes.Buffer)
json.NewEncoder(in).Encode(&core.Template{Name: "my_template", Data: "my_data"})
json.NewEncoder(in).Encode(&core.Template{Name: "", Data: "my_data"})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", in)
@ -67,7 +67,7 @@ func TestHandleCreate_NotValidTemplateExtensionName(t *testing.T) {
t.Errorf("Want response code %d, got %d", want, got)
}
got, want := &errors.Error{}, &errors.Error{Message: "Template extension invalid. Must be yaml, starlark or jsonnet"}
got, want := &errors.Error{}, &errors.Error{Message: "No Template Name Provided"}
json.NewDecoder(w.Body).Decode(got)
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
@ -80,7 +80,7 @@ func TestHandleCreate_ValidationErrorData(t *testing.T) {
c := new(chi.Context)
in := new(bytes.Buffer)
json.NewEncoder(in).Encode(&core.Template{Name: "my_template.yml", Data: ""})
json.NewEncoder(in).Encode(&core.Template{Name: "my_template", Data: ""})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", in)

View file

@ -30,7 +30,7 @@ func TestHandleDelete(t *testing.T) {
template.EXPECT().Delete(gomock.Any(), dummyTemplate).Return(nil)
c := new(chi.Context)
c.URLParams.Add("name", "my_template.yml")
c.URLParams.Add("name", "my_template")
c.URLParams.Add("namespace", "my_org")
w := httptest.NewRecorder()
@ -53,7 +53,7 @@ func TestHandleDelete_TemplateNotFound(t *testing.T) {
template.EXPECT().FindName(gomock.Any(), dummyTemplate.Name, dummyTemplate.Namespace).Return(nil, errors.ErrNotFound)
c := new(chi.Context)
c.URLParams.Add("name", "my_template.yml")
c.URLParams.Add("name", "my_template")
c.URLParams.Add("namespace", "my_org")
w := httptest.NewRecorder()
@ -83,7 +83,7 @@ func TestHandleDelete_DeleteError(t *testing.T) {
template.EXPECT().Delete(gomock.Any(), dummyTemplate).Return(errors.ErrNotFound)
c := new(chi.Context)
c.URLParams.Add("name", "my_template.yml")
c.URLParams.Add("name", "my_template")
c.URLParams.Add("namespace", "my_org")
w := httptest.NewRecorder()

View file

@ -29,7 +29,7 @@ func TestHandleFind(t *testing.T) {
template.EXPECT().FindName(gomock.Any(), dummyTemplate.Name, dummyTemplate.Namespace).Return(dummyTemplate, nil)
c := new(chi.Context)
c.URLParams.Add("name", "my_template.yml")
c.URLParams.Add("name", "my_template")
c.URLParams.Add("namespace", "my_org")
w := httptest.NewRecorder()
@ -52,7 +52,7 @@ func TestHandleFind_TemplateNotFound(t *testing.T) {
template.EXPECT().FindName(gomock.Any(), dummyTemplate.Name, dummyTemplate.Namespace).Return(nil, errors.ErrNotFound)
c := new(chi.Context)
c.URLParams.Add("name", "my_template.yml")
c.URLParams.Add("name", "my_template")
c.URLParams.Add("namespace", "my_org")
w := httptest.NewRecorder()

View file

@ -32,7 +32,7 @@ func TestHandleUpdate(t *testing.T) {
template.EXPECT().Update(gomock.Any(), gomock.Any()).Return(nil)
c := new(chi.Context)
c.URLParams.Add("name", "my_template.yml")
c.URLParams.Add("name", "my_template")
c.URLParams.Add("namespace", "my_org")
in := new(bytes.Buffer)
@ -55,10 +55,10 @@ func TestHandleUpdate_ValidationErrorData(t *testing.T) {
defer controller.Finish()
template := mock.NewMockTemplateStore(controller)
template.EXPECT().FindName(gomock.Any(), dummyTemplate.Name, dummyTemplate.Namespace).Return(&core.Template{Name: "my_template.yml"}, nil)
template.EXPECT().FindName(gomock.Any(), dummyTemplate.Name, dummyTemplate.Namespace).Return(&core.Template{Name: "my_template"}, nil)
c := new(chi.Context)
c.URLParams.Add("name", "my_template.yml")
c.URLParams.Add("name", "my_template")
c.URLParams.Add("namespace", "my_org")
in := new(bytes.Buffer)
@ -90,7 +90,7 @@ func TestHandleUpdate_TemplateNotFound(t *testing.T) {
template.EXPECT().FindName(gomock.Any(), dummyTemplate.Name, dummyTemplate.Namespace).Return(nil, errors.ErrNotFound)
c := new(chi.Context)
c.URLParams.Add("name", "my_template.yml")
c.URLParams.Add("name", "my_template")
c.URLParams.Add("namespace", "my_org")
in := new(bytes.Buffer)
@ -119,11 +119,11 @@ func TestHandleUpdate_UpdateError(t *testing.T) {
defer controller.Finish()
template := mock.NewMockTemplateStore(controller)
template.EXPECT().FindName(gomock.Any(), dummyTemplate.Name, dummyTemplate.Namespace).Return(&core.Template{Name: "my_template.yml"}, nil)
template.EXPECT().FindName(gomock.Any(), dummyTemplate.Name, dummyTemplate.Namespace).Return(&core.Template{Name: "my_template"}, nil)
template.EXPECT().Update(gomock.Any(), gomock.Any()).Return(errors.ErrNotFound)
c := new(chi.Context)
c.URLParams.Add("name", "my_template.yml")
c.URLParams.Add("name", "my_template")
c.URLParams.Add("namespace", "my_org")
in := new(bytes.Buffer)

View file

@ -97,7 +97,7 @@ func (s Server) Handler() http.Handler {
r.Use(middleware.Recoverer)
r.Use(middleware.NoCache)
r.Use(logger.Middleware)
r.Use(middleware.StripSlashes)
r.Use(middleware.RedirectSlashes)
sec := secure.New(s.Options)
r.Use(sec.Handler)

View file

@ -29,6 +29,5 @@ type Config struct {
EnableStash bool
EnableGogs bool
EnableGitea bool
EnableGitee bool
EnableAgents bool
}

View file

@ -92,7 +92,7 @@ func (d *Datadog) do(ctx context.Context, unix int64) error {
}
userList, _ := d.users.ListRange(ctx, core.UserParams{
Sort: false,
Page: 0,
Page: 1,
Size: 5,
})
tags := createTags(d.config)

View file

@ -39,7 +39,7 @@ func TestDo(t *testing.T) {
users := mock.NewMockUserStore(controller)
users.EXPECT().Count(gomock.Any()).Return(int64(10), nil)
users.EXPECT().ListRange(gomock.Any(), gomock.Any()).Return([]*core.User{{Email: "jane@acme.com", Created: 1257894000}}, nil)
users.EXPECT().ListRange(gomock.Any(), gomock.Any()).Return([]*core.User{{Email: "jane@acme.com"}}, nil)
repos := mock.NewMockRepositoryStore(controller)
repos.EXPECT().Count(gomock.Any()).Return(int64(20), nil)
@ -75,7 +75,7 @@ var sample = `{
"points": [[915148800, 10]],
"type": "gauge",
"host": "test.example.com",
"tags": ["version:` + version.Version.String() + `","remote:github:cloud","scheduler:internal:agents","license:trial","installer:jane@acme.com","installed:2009-11-10T23:00:00Z"]
"tags": ["version:` + version.Version.String() + `","remote:github:cloud","scheduler:internal:agents","license:trial","installer:jane@acme.com"]
},
{
"metric": "drone.repos",

View file

@ -16,7 +16,6 @@ package sink
import (
"fmt"
"time"
"github.com/drone/drone/core"
"github.com/drone/drone/version"
@ -42,8 +41,6 @@ func createTags(config Config) []string {
tags = append(tags, "remote:gogs")
case config.EnableGitea:
tags = append(tags, "remote:gitea")
case config.EnableGitee:
tags = append(tags, "remote:gitee")
default:
tags = append(tags, "remote:undefined")
}
@ -84,9 +81,8 @@ func createInstallerTags(users []*core.User) []string {
if len(user.Email) == 0 {
continue
}
tag1 := fmt.Sprintf("installer:%s", user.Email)
tag2 := fmt.Sprintf("installed:%s", time.Unix(user.Created, 0).UTC().Format(time.RFC3339Nano))
tags = append(tags, tag1, tag2)
tag := fmt.Sprintf("installer:%s", user.Email)
tags = append(tags, tag)
break
}
return tags

View file

@ -6,4 +6,4 @@
package mock
//go:generate mockgen -package=mock -destination=mock_gen.go github.com/drone/drone/core Pubsub,Canceler,ConvertService,ValidateService,NetrcService,Renewer,HookParser,UserService,RepositoryService,CommitService,StatusService,HookService,FileService,Batcher,BuildStore,CronStore,LogStore,PermStore,SecretStore,GlobalSecretStore,StageStore,StepStore,RepositoryStore,UserStore,Scheduler,Session,OrganizationService,SecretService,RegistryService,ConfigService,Transferer,Triggerer,Syncer,LogStream,WebhookSender,LicenseService,TemplateStore,CardStore
//go:generate mockgen -package=mock -destination=mock_gen.go github.com/drone/drone/core Pubsub,Canceler,ConvertService,ValidateService,NetrcService,Renewer,HookParser,UserService,RepositoryService,CommitService,StatusService,HookService,FileService,Batcher,BuildStore,CronStore,LogStore,PermStore,SecretStore,GlobalSecretStore,StageStore,StepStore,RepositoryStore,UserStore,Scheduler,Session,OrganizationService,SecretService,RegistryService,ConfigService,Transferer,Triggerer,Syncer,LogStream,WebhookSender,LicenseService,TemplateStore

View file

@ -1,5 +1,5 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/drone/drone/core (interfaces: Pubsub,Canceler,ConvertService,ValidateService,NetrcService,Renewer,HookParser,UserService,RepositoryService,CommitService,StatusService,HookService,FileService,Batcher,BuildStore,CronStore,LogStore,PermStore,SecretStore,GlobalSecretStore,StageStore,StepStore,RepositoryStore,UserStore,Scheduler,Session,OrganizationService,SecretService,RegistryService,ConfigService,Transferer,Triggerer,Syncer,LogStream,WebhookSender,LicenseService,TemplateStore,CardStore)
// Source: github.com/drone/drone/core (interfaces: Pubsub,Canceler,ConvertService,ValidateService,NetrcService,Renewer,HookParser,UserService,RepositoryService,CommitService,StatusService,HookService,FileService,Batcher,BuildStore,CronStore,LogStore,PermStore,SecretStore,GlobalSecretStore,StageStore,StepStore,RepositoryStore,UserStore,Scheduler,Session,OrganizationService,SecretService,RegistryService,ConfigService,Transferer,Triggerer,Syncer,LogStream,WebhookSender,LicenseService,TemplateStore)
// Package mock is a generated GoMock package.
package mock
@ -1917,21 +1917,6 @@ func (mr *MockRepositoryStoreMockRecorder) ListRecent(arg0, arg1 interface{}) *g
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListRecent", reflect.TypeOf((*MockRepositoryStore)(nil).ListRecent), arg0, arg1)
}
// ListRunningStatus mocks base method.
func (m *MockRepositoryStore) ListRunningStatus(arg0 context.Context) ([]*core.RepoBuildStage, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListRunningStatus", arg0)
ret0, _ := ret[0].([]*core.RepoBuildStage)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// ListRunningStatus indicates an expected call of ListRunningStatus.
func (mr *MockRepositoryStoreMockRecorder) ListRunningStatus(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListRunningStatus", reflect.TypeOf((*MockRepositoryStore)(nil).ListRunningStatus), arg0)
}
// Update mocks base method.
func (m *MockRepositoryStore) Update(arg0 context.Context, arg1 *core.Repository) error {
m.ctrl.T.Helper()
@ -2894,83 +2879,3 @@ func (mr *MockTemplateStoreMockRecorder) Update(arg0, arg1 interface{}) *gomock.
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockTemplateStore)(nil).Update), arg0, arg1)
}
// MockCardStore is a mock of CardStore interface.
type MockCardStore struct {
ctrl *gomock.Controller
recorder *MockCardStoreMockRecorder
}
// MockCardStoreMockRecorder is the mock recorder for MockCardStore.
type MockCardStoreMockRecorder struct {
mock *MockCardStore
}
// NewMockCardStore creates a new mock instance.
func NewMockCardStore(ctrl *gomock.Controller) *MockCardStore {
mock := &MockCardStore{ctrl: ctrl}
mock.recorder = &MockCardStoreMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockCardStore) EXPECT() *MockCardStoreMockRecorder {
return m.recorder
}
// Create mocks base method.
func (m *MockCardStore) Create(arg0 context.Context, arg1 int64, arg2 io.Reader) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Create", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
}
// Create indicates an expected call of Create.
func (mr *MockCardStoreMockRecorder) Create(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockCardStore)(nil).Create), arg0, arg1, arg2)
}
// Delete mocks base method.
func (m *MockCardStore) Delete(arg0 context.Context, arg1 int64) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Delete", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// Delete indicates an expected call of Delete.
func (mr *MockCardStoreMockRecorder) Delete(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockCardStore)(nil).Delete), arg0, arg1)
}
// Find mocks base method.
func (m *MockCardStore) Find(arg0 context.Context, arg1 int64) (io.ReadCloser, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Find", arg0, arg1)
ret0, _ := ret[0].(io.ReadCloser)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Find indicates an expected call of Find.
func (mr *MockCardStoreMockRecorder) Find(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Find", reflect.TypeOf((*MockCardStore)(nil).Find), arg0, arg1)
}
// Update mocks base method.
func (m *MockCardStore) Update(arg0 context.Context, arg1 int64, arg2 io.Reader) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Update", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockCardStoreMockRecorder) Update(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockCardStore)(nil).Update), arg0, arg1, arg2)
}

View file

@ -797,19 +797,3 @@ func (mr *MockUserServiceMockRecorder) FindLogin(arg0, arg1 interface{}) *gomock
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindLogin", reflect.TypeOf((*MockUserService)(nil).FindLogin), arg0, arg1)
}
// ListEmail mocks base method
func (m *MockUserService) ListEmail(arg0 context.Context, arg1 scm.ListOptions) ([]*scm.Email, *scm.Response, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ListEmail", arg0, arg1)
ret0, _ := ret[0].([]*scm.Email)
ret1, _ := ret[1].(*scm.Response)
ret2, _ := ret[2].(error)
return ret0, ret1, ret2
}
// ListEmail indicates an expected call of ListEmail.
func (mr *MockUserServiceMockRecorder) ListEmail(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListEmail", reflect.TypeOf((*MockUserService)(nil).ListEmail), arg0, arg1)
}

View file

@ -18,7 +18,6 @@ import (
"bytes"
"context"
"io"
"io/ioutil"
"time"
"github.com/drone/drone-yaml/yaml/converter"
@ -66,10 +65,10 @@ type (
// After signals the build step is complete.
After(ctx context.Context, step *core.Step) error
// BeforeAll signals the build stage is about to start.
// Before signals the build stage is about to start.
BeforeAll(ctx context.Context, stage *core.Stage) error
// AfterAll signals the build stage is complete.
// After signals the build stage is complete.
AfterAll(ctx context.Context, stage *core.Stage) error
// Watch watches for build cancellation requests.
@ -83,9 +82,6 @@ type (
// UploadBytes uploads the full logs
UploadBytes(ctx context.Context, step int64, b []byte) error
// UploadCard creates a new card
UploadCard(ctx context.Context, step int64, input *core.CardInput) error
}
// Request provides filters when requesting a pending
@ -105,7 +101,6 @@ type (
// New returns a new Manager.
func New(
builds core.BuildStore,
cards core.CardStore,
config core.ConfigService,
converter core.ConvertService,
events core.Pubsub,
@ -125,7 +120,6 @@ func New(
) BuildManager {
return &Manager{
Builds: builds,
Cards: cards,
Config: config,
Converter: converter,
Events: events,
@ -149,7 +143,6 @@ func New(
// can more easily interact with the server.
type Manager struct {
Builds core.BuildStore
Cards core.CardStore
Config core.ConfigService
Converter core.ConvertService
Events core.Pubsub
@ -542,16 +535,3 @@ func (m *Manager) UploadBytes(ctx context.Context, step int64, data []byte) erro
}
return err
}
// UploadCard creates card for step.
func (m *Manager) UploadCard(ctx context.Context, stepId int64, input *core.CardInput) error {
data := ioutil.NopCloser(
bytes.NewBuffer(input.Data),
)
err := m.Cards.Create(ctx, stepId, data)
if err != nil {
logger := logrus.WithError(err)
logger.Warnln("manager: cannot create card")
}
return nil
}

View file

@ -9,7 +9,6 @@ package rpc
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -209,10 +208,6 @@ func (s *Client) UploadBytes(ctx context.Context, step int64, data []byte) error
return s.upload(noContext, endpoint, data)
}
func (s *Client) UploadCard(ctx context.Context, step int64, input *core.CardInput) error {
return errors.New("rpc upload card not supported")
}
func (s *Client) send(ctx context.Context, path string, in, out interface{}) error {
// Source a buffer from a pool. The agent may generate a
// large number of small requests for log entries. This will

View file

@ -29,7 +29,6 @@ import (
"github.com/go-chi/chi"
"github.com/drone/drone/core"
"github.com/drone/drone/handler/api/render"
"github.com/drone/drone/operator/manager"
"github.com/drone/drone/store/shared/db"
)
@ -271,31 +270,6 @@ func HandleLogUpload(m manager.BuildManager) http.HandlerFunc {
}
}
// HandleCardUpload returns an http.HandlerFunc that accepts an
// http.Request to upload and persist a card for a pipeline step.
//
// POST /rpc/v2/step/{step}/card
func HandleCardUpload(m manager.BuildManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
step, _ := strconv.ParseInt(
chi.URLParam(r, "step"), 10, 64)
in := new(core.CardInput)
err := json.NewDecoder(r.Body).Decode(in)
if err != nil {
render.BadRequest(w, err)
return
}
err = m.UploadCard(noContext, step, in)
if err != nil {
writeError(w, err)
} else {
writeOK(w)
}
}
}
// write a 200 Status OK to the response body.
func writeJSON(w http.ResponseWriter, v interface{}) {
json.NewEncoder(w).Encode(v)

View file

@ -37,7 +37,6 @@ func NewServer(manager manager.BuildManager, secret string) Server {
r.Post("/build/{build}/watch", HandleWatch(manager))
r.Post("/step/{step}/logs/batch", HandleLogBatch(manager))
r.Post("/step/{step}/logs/upload", HandleLogUpload(manager))
r.Post("/step/{step}/card", HandleCardUpload(manager))
return Server(r)
}
@ -56,3 +55,4 @@ func authorization(token string) func(http.Handler) http.Handler {
})
}
}

View file

@ -54,20 +54,15 @@ func (s *membership) Admit(ctx context.Context, user *core.User) error {
if ok {
return nil
}
// make an API call to retrive the list of organizations
// to which the user belongs.
orgs, err := s.service.List(ctx, user)
if err != nil {
return err
}
// if the user is a member of an organization in the
// account whitelist we can admit the user.
for _, org := range orgs {
_, ok := s.account[strings.ToLower(org.Name)]
if ok {
return nil
}
}
// else deny access
return ErrMembership
}

View file

@ -2,7 +2,6 @@
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
//go:build !oss
// +build !oss
package config
@ -34,7 +33,7 @@ func Global(endpoint, signer string, skipVerify bool, timeout time.Duration) cor
}
type global struct {
client config.Plugin
client config.Plugin
timeout time.Duration
}
@ -52,10 +51,6 @@ func (g *global) Find(ctx context.Context, in *core.ConfigArgs) (*core.Config, e
req := &config.Request{
Repo: toRepo(in.Repo),
Build: toBuild(in.Build),
Token: drone.Token{
Access: in.User.Token,
Refresh: in.User.Refresh,
},
}
res, err := g.client.Find(ctx, req)

View file

@ -22,16 +22,12 @@ import (
// Combine combines the conversion services, provision support
// for multiple conversion utilities.
func Combine(multi bool, services ...core.ConvertService) core.ConvertService {
return &combined{multi: multi, sources: services}
func Combine(services ...core.ConvertService) core.ConvertService {
return &combined{services}
}
type combined struct {
sources []core.ConvertService
// this feature flag can be removed once we solve for
// https://github.com/harness/drone/pull/2994#issuecomment-795955312
multi bool
}
func (c *combined) Convert(ctx context.Context, req *core.ConvertArgs) (*core.Config, error) {
@ -46,11 +42,7 @@ func (c *combined) Convert(ctx context.Context, req *core.ConvertArgs) (*core.Co
if config.Data == "" {
continue
}
if c.multi {
req.Config = config
} else {
return config, nil
}
return config, nil
}
return req.Config, nil
}

View file

@ -39,7 +39,7 @@ func TestCombine(t *testing.T) {
service := mock.NewMockConvertService(controller)
service.EXPECT().Convert(noContext, args).Return(resp, nil)
result, err := Combine(false, service).Convert(noContext, args)
result, err := Combine(service).Convert(noContext, args)
if err != nil {
t.Error(err)
return
@ -58,7 +58,7 @@ func TestCombineErr(t *testing.T) {
service := mock.NewMockConvertService(controller)
service.EXPECT().Convert(noContext, nil).Return(nil, resp)
_, err := Combine(false, service).Convert(noContext, nil)
_, err := Combine(service).Convert(noContext, nil)
if err != resp {
t.Errorf("expected convert service error")
}
@ -85,7 +85,7 @@ func TestCombineNoConfig(t *testing.T) {
service3 := mock.NewMockConvertService(controller)
service3.EXPECT().Convert(noContext, args).Return(resp, nil)
result, err := Combine(false, service1, service2, service3).Convert(noContext, args)
result, err := Combine(service1, service2, service3).Convert(noContext, args)
if err != nil {
t.Error(err)
return
@ -110,7 +110,7 @@ func TestCombineEmptyConfig(t *testing.T) {
service1 := mock.NewMockConvertService(controller)
service1.EXPECT().Convert(noContext, args).Return(nil, nil)
result, err := Combine(false, service1).Convert(noContext, args)
result, err := Combine(service1).Convert(noContext, args)
if err != nil {
t.Error(err)
return

View file

@ -19,18 +19,14 @@ import (
// Jsonnet returns a conversion service that converts the
// jsonnet file to a yaml file.
func Jsonnet(enabled bool, limit int, fileService core.FileService) core.ConvertService {
func Jsonnet(enabled bool) core.ConvertService {
return &jsonnetPlugin{
enabled: enabled,
limit: limit,
fileService: fileService,
enabled: enabled,
}
}
type jsonnetPlugin struct {
enabled bool
limit int
fileService core.FileService
enabled bool
}
func (p *jsonnetPlugin) Convert(ctx context.Context, req *core.ConvertArgs) (*core.Config, error) {
@ -44,7 +40,7 @@ func (p *jsonnetPlugin) Convert(ctx context.Context, req *core.ConvertArgs) (*co
return nil, nil
}
file, err := jsonnet.Parse(req, p.fileService, p.limit, nil, nil)
file, err := jsonnet.Parse(req, nil, nil)
if err != nil {
return nil, err

View file

@ -2,14 +2,10 @@ package jsonnet
import (
"bytes"
"context"
"fmt"
"path"
"strconv"
"strings"
"github.com/drone/drone/core"
"github.com/drone/drone/handler/api/errors"
"github.com/google/go-jsonnet"
)
@ -18,91 +14,11 @@ const repo = "repo."
const build = "build."
const param = "param."
var noContext = context.Background()
type importer struct {
repo *core.Repository
build *core.Build
// jsonnet does not cache file imports and may request
// the same file multiple times. We cache the files to
// duplicate API calls.
cache map[string]jsonnet.Contents
// limit the number of outbound requests. github limits
// the number of api requests per hour, so we should
// make sure that a single build does not abuse the api
// by importing dozens of files.
limit int
// counts the number of outbound requests. if the count
// exceeds the limit, the importer will return errors.
count int
fileService core.FileService
user *core.User
}
func (i *importer) Import(importedFrom, importedPath string) (contents jsonnet.Contents, foundAt string, err error) {
if i.cache == nil {
i.cache = map[string]jsonnet.Contents{}
}
// the import is relative to the imported from path. the
// imported path must resolve to a filepath relative to
// the root of the repository.
importedPath = path.Join(
path.Dir(importedFrom),
importedPath,
)
if strings.HasPrefix(importedFrom, "../") {
err = fmt.Errorf("jsonnet: cannot resolve import: %s", importedPath)
return contents, foundAt, err
}
// if the contents exist in the cache, return the
// cached item.
if contents, ok := i.cache[importedPath]; ok {
return contents, importedPath, nil
}
defer func() {
i.count++
}()
// if the import limit is exceeded log an error message.
if i.limit > 0 && i.count >= i.limit {
return contents, foundAt, errors.New("jsonnet: import limit exceeded")
}
find, err := i.fileService.Find(noContext, i.user, i.repo.Slug, i.build.After, i.build.Ref, importedPath)
if err != nil {
return contents, foundAt, err
}
i.cache[importedPath] = jsonnet.MakeContents(string(find.Data))
return i.cache[importedPath], importedPath, err
}
func Parse(req *core.ConvertArgs, fileService core.FileService, limit int, template *core.Template, templateData map[string]interface{}) (string, error) {
func Parse(req *core.ConvertArgs, template *core.Template, templateData map[string]interface{}) (string, error) {
vm := jsonnet.MakeVM()
vm.MaxStack = 500
vm.StringOutput = false
vm.ErrorFormatter.SetMaxStackTraceSize(20)
if fileService != nil && limit > 0 {
vm.Importer(
&importer{
repo: req.Repo,
build: req.Build,
limit: limit,
user: req.User,
fileService: fileService,
},
)
}
//map build/repo parameters
if req.Build != nil {
@ -132,9 +48,9 @@ func Parse(req *core.ConvertArgs, fileService core.FileService, limit int, templ
// convert the jsonnet file to yaml
buf := new(bytes.Buffer)
docs, err := vm.EvaluateAnonymousSnippetStream(jsonnetFileName, jsonnetFile)
docs, err := vm.EvaluateSnippetStream(jsonnetFileName, jsonnetFile)
if err != nil {
doc, err2 := vm.EvaluateAnonymousSnippet(jsonnetFileName, jsonnetFile)
doc, err2 := vm.EvaluateSnippet(jsonnetFileName, jsonnetFile)
if err2 != nil {
return "", err
}

View file

@ -2,8 +2,6 @@ package jsonnet
import (
"io/ioutil"
"runtime"
"strings"
"testing"
"github.com/drone/drone/core"
@ -46,19 +44,13 @@ func TestParse(t *testing.T) {
req.Config.Data = string(before)
got, err := Parse(req, nil, 0, template, templateData)
parsedFile, err := Parse(req, template, templateData)
if err != nil {
t.Error(err)
return
}
want := string(after)
// on windows line endings are \r\n, lets change them to linux for comparison
if runtime.GOOS == "windows" {
want = strings.Replace(want, "\r\n", "\n", -1)
}
if want != got {
if want, got := parsedFile, string(after); want != got {
t.Errorf("Want %q got %q", want, got)
}
}
@ -90,19 +82,13 @@ func TestParseJsonnetNotTemplateFile(t *testing.T) {
req.Repo.Config = "plugin.jsonnet"
req.Config.Data = string(before)
got, err := Parse(req, nil, 0, nil, nil)
parsedFile, err := Parse(req, nil, nil)
if err != nil {
t.Error(err)
return
}
want := string(after)
// on windows line endings are \r\n, lets change them to linux for comparison
if runtime.GOOS == "windows" {
want = strings.Replace(want, "\r\n", "\n", -1)
}
if want != got {
if want, got := parsedFile, string(after); want != got {
t.Errorf("Want %q got %q", want, got)
}
}

View file

@ -22,6 +22,6 @@ import (
// Jsonnet returns a conversion service that converts the
// jsonnet file to a yaml file.
func Jsonnet(enabled bool, limit int, fileService core.FileService) core.ConvertService {
func Jsonnet(enabled bool) core.ConvertService {
return new(noop)
}

View file

@ -10,9 +10,6 @@ import (
"testing"
"github.com/drone/drone/core"
"github.com/drone/drone/mock"
"github.com/golang/mock/gomock"
)
const jsonnetFile = `{"foo": "bar"}`
@ -29,32 +26,12 @@ const jsonnetStreamAfter = `---
}
`
const jsonnetFileImport = `local step = import '.step.libsonnet';
{"foo": ["bar"], "steps": [step]}`
const jsonnetFileImportLib = `{"image": "app"}`
const jsonnetFileImportAfter = `---
{
"foo": [
"bar"
],
"steps": [
{
"image": "app"
}
]
}
`
const jsonnetFileMultipleImports = `local step = import '.step.libsonnet';
local step2 = import '.step2.jsonnet';
{"foo": ["bar"], "steps": [step, step2]}`
func TestJsonnet_Stream(t *testing.T) {
args := &core.ConvertArgs{
Repo: &core.Repository{Config: ".drone.jsonnet"},
Config: &core.Config{Data: jsonnetStream},
}
service := Jsonnet(true, 0, nil)
service := Jsonnet(true)
res, err := service.Convert(noContext, args)
if err != nil {
t.Error(err)
@ -74,7 +51,7 @@ func TestJsonnet_Snippet(t *testing.T) {
Repo: &core.Repository{Config: ".drone.jsonnet"},
Config: &core.Config{Data: jsonnetFile},
}
service := Jsonnet(true, 0, nil)
service := Jsonnet(true)
res, err := service.Convert(noContext, args)
if err != nil {
t.Error(err)
@ -94,7 +71,7 @@ func TestJsonnet_Error(t *testing.T) {
Repo: &core.Repository{Config: ".drone.jsonnet"},
Config: &core.Config{Data: "\\"}, // invalid jsonnet
}
service := Jsonnet(true, 0, nil)
service := Jsonnet(true)
_, err := service.Convert(noContext, args)
if err == nil {
t.Errorf("Expect jsonnet parsing error, got nil")
@ -102,7 +79,7 @@ func TestJsonnet_Error(t *testing.T) {
}
func TestJsonnet_Disabled(t *testing.T) {
service := Jsonnet(false, 0, nil)
service := Jsonnet(false)
res, err := service.Convert(noContext, nil)
if err != nil {
t.Error(err)
@ -116,7 +93,7 @@ func TestJsonnet_NotJsonnet(t *testing.T) {
args := &core.ConvertArgs{
Repo: &core.Repository{Config: ".drone.yml"},
}
service := Jsonnet(true, 0, nil)
service := Jsonnet(true)
res, err := service.Convert(noContext, args)
if err != nil {
t.Error(err)
@ -125,169 +102,3 @@ func TestJsonnet_NotJsonnet(t *testing.T) {
t.Errorf("Expect nil response when not jsonnet")
}
}
func TestJsonnet_Import(t *testing.T) {
args := &core.ConvertArgs{
Build: &core.Build{
Ref: "a6586b3db244fb6b1198f2b25c213ded5b44f9fa",
After: "542ed565d03dab86f079798f937663ec1f05360b",
},
Repo: &core.Repository{
Slug: "octocat/hello-world",
Config: ".drone.jsonnet"},
Config: &core.Config{Data: jsonnetFileImport},
User: &core.User{
Token: "foobar",
},
}
importedContent := &core.File{
Data: []byte(jsonnetFileImportLib),
}
controller := gomock.NewController(t)
mockFileService := mock.NewMockFileService(controller)
mockFileService.EXPECT().Find(gomock.Any(), &core.User{Token: "foobar"}, "octocat/hello-world", "542ed565d03dab86f079798f937663ec1f05360b", "a6586b3db244fb6b1198f2b25c213ded5b44f9fa", ".step.libsonnet").Return(importedContent, nil).Times(2)
service := Jsonnet(true, 1, mockFileService)
res, err := service.Convert(noContext, args)
if err != nil {
t.Error(err)
}
if got, want := res.Data, jsonnetFileImportAfter; got != want {
t.Errorf("Want converted file:\n%q\ngot\n%q", want, got)
}
}
func TestJsonnet_ImportLimit(t *testing.T) {
args := &core.ConvertArgs{
Build: &core.Build{
Ref: "a6586b3db244fb6b1198f2b25c213ded5b44f9fa",
After: "542ed565d03dab86f079798f937663ec1f05360b",
},
Repo: &core.Repository{
Slug: "octocat/hello-world",
Config: ".drone.jsonnet"},
Config: &core.Config{Data: jsonnetFileMultipleImports},
User: &core.User{
Token: "foobar",
},
}
importedContent := &core.File{
Data: []byte(jsonnetFileImportLib),
}
controller := gomock.NewController(t)
mockFileService := mock.NewMockFileService(controller)
mockFileService.EXPECT().Find(gomock.Any(), &core.User{Token: "foobar"}, "octocat/hello-world", "542ed565d03dab86f079798f937663ec1f05360b", "a6586b3db244fb6b1198f2b25c213ded5b44f9fa", ".step.libsonnet").Return(importedContent, nil).Times(2)
service := Jsonnet(true, 1, mockFileService)
_, err := service.Convert(noContext, args)
if err == nil {
t.Errorf("Expect nil response when jsonnet import limit is exceeded")
}
}
func TestJsonnet_LimitZero(t *testing.T) {
args := &core.ConvertArgs{
Build: &core.Build{
Ref: "a6586b3db244fb6b1198f2b25c213ded5b44f9fa",
After: "542ed565d03dab86f079798f937663ec1f05360b",
},
Repo: &core.Repository{
Slug: "octocat/hello-world",
Config: ".drone.jsonnet"},
Config: &core.Config{Data: jsonnetFile},
User: &core.User{
Token: "foobar",
},
}
controller := gomock.NewController(t)
mockFileService := mock.NewMockFileService(controller)
mockFileService.EXPECT().Find(gomock.Any(), &core.User{Token: "foobar"}, "octocat/hello-world", "542ed565d03dab86f079798f937663ec1f05360b", "a6586b3db244fb6b1198f2b25c213ded5b44f9fa", ".step.libsonnet").Times(0)
service := Jsonnet(true, 0, mockFileService)
res, err := service.Convert(noContext, args)
if err != nil {
t.Error(err)
return
}
if got, want := res.Data, jsonnetFileAfter; got != want {
t.Errorf("Want converted file %q, got %q", want, got)
}
}
func TestJsonnet_ImportLimitZero(t *testing.T) {
args := &core.ConvertArgs{
Build: &core.Build{
Ref: "a6586b3db244fb6b1198f2b25c213ded5b44f9fa",
After: "542ed565d03dab86f079798f937663ec1f05360b",
},
Repo: &core.Repository{
Slug: "octocat/hello-world",
Config: ".drone.jsonnet"},
Config: &core.Config{Data: jsonnetFileImport},
User: &core.User{
Token: "foobar",
},
}
importedContent := &core.File{
Data: []byte(jsonnetFileImportLib),
}
controller := gomock.NewController(t)
mockFileService := mock.NewMockFileService(controller)
mockFileService.EXPECT().Find(gomock.Any(), &core.User{Token: "foobar"}, "octocat/hello-world", "542ed565d03dab86f079798f937663ec1f05360b", "a6586b3db244fb6b1198f2b25c213ded5b44f9fa", ".step.libsonnet").Return(importedContent, nil).Times(2)
service := Jsonnet(true, 0, mockFileService)
_, err := service.Convert(noContext, args)
if err == nil {
t.Errorf("Expect nil response when jsonnet import limit is exceeded")
}
}
func TestJsonnet_ImportFileServiceNil(t *testing.T) {
args := &core.ConvertArgs{
Build: &core.Build{
Ref: "a6586b3db244fb6b1198f2b25c213ded5b44f9fa",
After: "542ed565d03dab86f079798f937663ec1f05360b",
},
Repo: &core.Repository{
Slug: "octocat/hello-world",
Config: ".drone.jsonnet"},
Config: &core.Config{Data: jsonnetFileMultipleImports},
User: &core.User{
Token: "foobar",
},
}
service := Jsonnet(true, 1, nil)
_, err := service.Convert(noContext, args)
if err == nil {
t.Errorf("Expect nil response when jsonnet import limit is exceeded")
}
}
func TestJsonnet_FileServiceNil(t *testing.T) {
args := &core.ConvertArgs{
Build: &core.Build{
Ref: "a6586b3db244fb6b1198f2b25c213ded5b44f9fa",
After: "542ed565d03dab86f079798f937663ec1f05360b",
},
Repo: &core.Repository{
Slug: "octocat/hello-world",
Config: ".drone.jsonnet"},
Config: &core.Config{Data: jsonnetFile},
User: &core.User{
Token: "foobar",
},
}
service := Jsonnet(true, 1, nil)
res, err := service.Convert(noContext, args)
if err != nil {
t.Error(err)
return
}
if got, want := res.Data, jsonnetFileAfter; got != want {
t.Errorf("Want converted file %q, got %q", want, got)
}
}

View file

@ -2,7 +2,6 @@
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
//go:build !oss
// +build !oss
package converter
@ -37,7 +36,7 @@ func Remote(endpoint, signer, extension string, skipVerify bool, timeout time.Du
type remote struct {
client converter.Plugin
extension string
timeout time.Duration
timeout time.Duration
}
func (g *remote) Convert(ctx context.Context, in *core.ConvertArgs) (*core.Config, error) {
@ -62,10 +61,6 @@ func (g *remote) Convert(ctx context.Context, in *core.ConvertArgs) (*core.Confi
Config: drone.Config{
Data: in.Config.Data,
},
Token: drone.Token{
Access: in.User.Token,
Refresh: in.User.Refresh,
},
}
res, err := g.client.Convert(ctx, req)

View file

@ -26,16 +26,14 @@ import (
// Starlark returns a conversion service that converts the
// starlark file to a yaml file.
func Starlark(enabled bool, stepLimit uint64) core.ConvertService {
func Starlark(enabled bool) core.ConvertService {
return &starlarkPlugin{
enabled: enabled,
stepLimit: stepLimit,
}
}
type starlarkPlugin struct {
enabled bool
stepLimit uint64
}
func (p *starlarkPlugin) Convert(ctx context.Context, req *core.ConvertArgs) (*core.Config, error) {
@ -53,7 +51,7 @@ func (p *starlarkPlugin) Convert(ctx context.Context, req *core.ConvertArgs) (*c
return nil, nil
}
file, err := starlark.Parse(req, nil, nil, p.stepLimit)
file, err := starlark.Parse(req, nil, nil)
if err != nil {
return nil, err
}

View file

@ -54,7 +54,7 @@ var (
ErrCannotLoad = errors.New("starlark: cannot load external scripts")
)
func Parse(req *core.ConvertArgs, template *core.Template, templateData map[string]interface{}, stepLimit uint64) (string, error) {
func Parse(req *core.ConvertArgs, template *core.Template, templateData map[string]interface{}) (string, error) {
thread := &starlark.Thread{
Name: "drone",
Load: noLoad,
@ -101,10 +101,7 @@ func Parse(req *core.ConvertArgs, template *core.Template, templateData map[stri
// set the maximum number of operations in the script. this
// mitigates long running scripts.
if stepLimit == 0 {
stepLimit = 50000
}
thread.SetMaxExecutionSteps(stepLimit)
thread.SetMaxExecutionSteps(50000)
// execute the main method in the script.
mainVal, err = starlark.Call(thread, main, args, nil)

View file

@ -57,7 +57,7 @@ func TestParseStarlark(t *testing.T) {
req.Config.Data = string(before)
parsedFile, err := Parse(req, template, templateData, 0)
parsedFile, err := Parse(req, template, templateData)
if err != nil {
t.Error(err)
return
@ -95,7 +95,7 @@ func TestParseStarlarkNotTemplateFile(t *testing.T) {
req.Repo.Config = "plugin.starlark.star"
req.Config.Data = string(before)
parsedFile, err := Parse(req, nil, nil, 0)
parsedFile, err := Parse(req, nil, nil)
if err != nil {
t.Error(err)
return

View file

@ -18,6 +18,6 @@ package converter
import "github.com/drone/drone/core"
func Starlark(enabled bool, stepLimit uint64) core.ConvertService {
func Starlark(enabled bool) core.ConvertService {
return new(noop)
}

View file

@ -16,15 +16,13 @@ package converter
import (
"io/ioutil"
"runtime"
"strings"
"testing"
"github.com/drone/drone/core"
)
func TestStarlarkConvert(t *testing.T) {
plugin := Starlark(true, 0)
plugin := Starlark(true)
req := &core.ConvertArgs{
Build: &core.Build{
@ -102,7 +100,7 @@ func TestConvert_Multi(t *testing.T) {
},
}
plugin := Starlark(true, 0)
plugin := Starlark(true)
config, err := plugin.Convert(noContext, req)
if err != nil {
t.Error(err)
@ -119,14 +117,7 @@ func TestConvert_Multi(t *testing.T) {
return
}
want := string(after)
// on windows line endings are \r\n, lets change them to linux for comparison
if runtime.GOOS == "windows" {
want = strings.Replace(want, "\r\n", "\n", -1)
}
got := config.Data
if want != got {
if want, got := config.Data, string(after); want != got {
t.Errorf("Want %q got %q", want, got)
}
}
@ -134,7 +125,7 @@ func TestConvert_Multi(t *testing.T) {
// this test verifies the plugin is skipped when it has
// not been explicitly enabled.
func TestConvert_Skip(t *testing.T) {
plugin := Starlark(false, 0)
plugin := Starlark(false)
config, err := plugin.Convert(noContext, nil)
if err != nil {
t.Error(err)
@ -154,7 +145,7 @@ func TestConvert_SkipYaml(t *testing.T) {
},
}
plugin := Starlark(true, 0)
plugin := Starlark(true)
config, err := plugin.Convert(noContext, req)
if err != nil {
t.Error(err)

View file

@ -35,23 +35,20 @@ import (
)
var (
// templateFileRE regex to verifying kind is template.
templateFileRE = regexp.MustCompilePOSIX("^kind:[[:space:]]+template[[:space:]]?+$")
errTemplateNotFound = errors.New("template converter: template name given not found")
errTemplateSyntaxErrors = errors.New("template converter: there is a problem with the yaml file provided")
errTemplateExtensionInvalid = errors.New("template extension invalid. must be yaml, starlark or jsonnet")
// TemplateFileRE regex to verifying kind is template.
TemplateFileRE = regexp.MustCompile("^kind:\\s+template+\\n")
ErrTemplateNotFound = errors.New("template converter: template name given not found")
ErrTemplateSyntaxErrors = errors.New("template converter: there is a problem with the yaml file provided")
)
func Template(templateStore core.TemplateStore, stepLimit uint64) core.ConvertService {
func Template(templateStore core.TemplateStore) core.ConvertService {
return &templatePlugin{
templateStore: templateStore,
stepLimit: stepLimit,
}
}
type templatePlugin struct {
templateStore core.TemplateStore
stepLimit uint64
}
func (p *templatePlugin) Convert(ctx context.Context, req *core.ConvertArgs) (*core.Config, error) {
@ -61,19 +58,19 @@ func (p *templatePlugin) Convert(ctx context.Context, req *core.ConvertArgs) (*c
}
// check kind is template
if templateFileRE.MatchString(req.Config.Data) == false {
if TemplateFileRE.MatchString(req.Config.Data) == false {
return nil, nil
}
// map to templateArgs
var templateArgs core.TemplateArgs
err := yaml.Unmarshal([]byte(req.Config.Data), &templateArgs)
if err != nil {
return nil, errTemplateSyntaxErrors
return nil, ErrTemplateSyntaxErrors
}
// get template from db
template, err := p.templateStore.FindName(ctx, templateArgs.Load, req.Repo.Namespace)
if err == sql.ErrNoRows {
return nil, errTemplateNotFound
return nil, ErrTemplateNotFound
}
if err != nil {
return nil, err
@ -83,12 +80,13 @@ func (p *templatePlugin) Convert(ctx context.Context, req *core.ConvertArgs) (*c
case ".yml", ".yaml":
return parseYaml(req, template, templateArgs)
case ".star", ".starlark", ".script":
return parseStarlark(req, template, templateArgs, p.stepLimit)
return parseStarlark(req, template, templateArgs)
case ".jsonnet":
return parseJsonnet(req, template, templateArgs)
default:
return nil, errTemplateExtensionInvalid
}
return nil, nil
}
func parseYaml(req *core.ConvertArgs, template *core.Template, templateArgs core.TemplateArgs) (*core.Config, error) {
@ -112,7 +110,7 @@ func parseYaml(req *core.ConvertArgs, template *core.Template, templateArgs core
}
func parseJsonnet(req *core.ConvertArgs, template *core.Template, templateArgs core.TemplateArgs) (*core.Config, error) {
file, err := jsonnet.Parse(req, nil, 0, template, templateArgs.Data)
file, err := jsonnet.Parse(req, template, templateArgs.Data)
if err != nil {
return nil, err
}
@ -121,8 +119,8 @@ func parseJsonnet(req *core.ConvertArgs, template *core.Template, templateArgs c
}, nil
}
func parseStarlark(req *core.ConvertArgs, template *core.Template, templateArgs core.TemplateArgs, stepLimit uint64) (*core.Config, error) {
file, err := starlark.Parse(req, template, templateArgs.Data, stepLimit)
func parseStarlark(req *core.ConvertArgs, template *core.Template, templateArgs core.TemplateArgs) (*core.Config, error) {
file, err := starlark.Parse(req, template, templateArgs.Data)
if err != nil {
return nil, err
}

View file

@ -22,7 +22,7 @@ import (
"github.com/drone/drone/core"
)
func Template(templateStore core.TemplateStore, stepLimit uint64) core.ConvertService {
func Template(templateStore core.TemplateStore) core.ConvertService {
return &templatePlugin{
templateStore: templateStore,
}

View file

@ -17,8 +17,6 @@ package converter
import (
"encoding/json"
"io/ioutil"
"runtime"
"strings"
"testing"
"github.com/drone/drone/core"
@ -72,7 +70,7 @@ func TestTemplatePluginConvertStarlark(t *testing.T) {
templates := mock.NewMockTemplateStore(controller)
templates.EXPECT().FindName(gomock.Any(), template.Name, req.Repo.Namespace).Return(template, nil)
plugin := Template(templates, 0)
plugin := Template(templates)
config, err := plugin.Convert(noContext, req)
if err != nil {
t.Error(err)
@ -91,7 +89,7 @@ func TestTemplatePluginConvertStarlark(t *testing.T) {
func TestTemplatePluginConvertNotYamlFile(t *testing.T) {
plugin := Template(nil, 0)
plugin := Template(nil)
req := &core.ConvertArgs{
Build: &core.Build{
After: "3d21ec53a331a6f037a91c368710b99387d012c1",
@ -119,7 +117,7 @@ func TestTemplatePluginConvertDroneFileTypePipeline(t *testing.T) {
t.Error(err)
return
}
plugin := Template(nil, 0)
plugin := Template(nil)
req := &core.ConvertArgs{
Build: &core.Build{
After: "3d21ec53a331a6f037a91c368710b99387d012c1",
@ -171,7 +169,7 @@ func TestTemplatePluginConvertTemplateNotFound(t *testing.T) {
templates := mock.NewMockTemplateStore(controller)
templates.EXPECT().FindName(gomock.Any(), template.Name, req.Repo.Namespace).Return(nil, nil)
plugin := Template(templates, 0)
plugin := Template(templates)
config, err := plugin.Convert(noContext, req)
if config != nil {
@ -224,7 +222,7 @@ func TestTemplatePluginConvertJsonnet(t *testing.T) {
templates := mock.NewMockTemplateStore(controller)
templates.EXPECT().FindName(gomock.Any(), template.Name, req.Repo.Namespace).Return(template, nil)
plugin := Template(templates, 0)
plugin := Template(templates)
config, err := plugin.Convert(noContext, req)
if err != nil {
t.Error(err)
@ -236,14 +234,7 @@ func TestTemplatePluginConvertJsonnet(t *testing.T) {
return
}
want := string(after)
// on windows line endings are \r\n, lets change them to linux for comparison
if runtime.GOOS == "windows" {
want = strings.Replace(want, "\r\n", "\n", -1)
}
got := config.Data
if want != got {
if want, got := config.Data, string(after); want != got {
t.Errorf("Want %q got %q", want, got)
}
}
@ -303,7 +294,7 @@ func TestTemplateNestedValuesPluginConvertStarlark(t *testing.T) {
templates := mock.NewMockTemplateStore(controller)
templates.EXPECT().FindName(gomock.Any(), template.Name, req.Repo.Namespace).Return(template, nil)
plugin := Template(templates, 0)
plugin := Template(templates)
config, err := plugin.Convert(noContext, req)
if err != nil {
t.Error(err)
@ -381,118 +372,7 @@ func TestTemplatePluginConvertYaml(t *testing.T) {
templates := mock.NewMockTemplateStore(controller)
templates.EXPECT().FindName(gomock.Any(), template.Name, req.Repo.Namespace).Return(template, nil)
plugin := Template(templates, 0)
config, err := plugin.Convert(noContext, req)
if err != nil {
t.Error(err)
return
}
if config == nil {
t.Error("Want non-nil configuration")
return
}
if want, got := config.Data, string(after); want != got {
t.Errorf("Want %q got %q", want, got)
}
}
// tests to check error is thrown if user has already loaded a template file of invalid extension
// and refers to it in the drone.yml file
func TestTemplatePluginConvertInvalidTemplateExtension(t *testing.T) {
// reads yml input file which refers to a template file of invalid extensions
templateArgs, err := ioutil.ReadFile("testdata/yaml.template.invalid.yml")
if err != nil {
t.Error(err)
return
}
req := &core.ConvertArgs{
Build: &core.Build{
After: "3d21ec53a331a6f037a91c368710b99387d012c1",
},
Repo: &core.Repository{
Slug: "octocat/hello-world",
Config: ".drone.yml",
Namespace: "octocat",
},
Config: &core.Config{
Data: string(templateArgs),
},
}
// reads the template drone.yml
beforeInput, err := ioutil.ReadFile("testdata/yaml.input.yml")
if err != nil {
t.Error(err)
return
}
template := &core.Template{
Name: "plugin.txt",
Data: string(beforeInput),
Namespace: "octocat",
}
controller := gomock.NewController(t)
defer controller.Finish()
templates := mock.NewMockTemplateStore(controller)
templates.EXPECT().FindName(gomock.Any(), template.Name, req.Repo.Namespace).Return(template, nil)
plugin := Template(templates, 0)
config, err := plugin.Convert(noContext, req)
if config != nil {
t.Errorf("template extension invalid. must be yaml, starlark or jsonnet")
}
}
func TestTemplatePluginConvertYamlWithComment(t *testing.T) {
templateArgs, err := ioutil.ReadFile("testdata/yaml.template.comment.yml")
if err != nil {
t.Error(err)
return
}
req := &core.ConvertArgs{
Build: &core.Build{
After: "3d21ec53a331a6f037a91c368710b99387d012c1",
},
Repo: &core.Repository{
Slug: "octocat/hello-world",
Config: ".drone.yml",
Namespace: "octocat",
},
Config: &core.Config{
Data: string(templateArgs),
},
}
beforeInput, err := ioutil.ReadFile("testdata/yaml.input.yml")
if err != nil {
t.Error(err)
return
}
after, err := ioutil.ReadFile("testdata/yaml.input.golden")
if err != nil {
t.Error(err)
return
}
template := &core.Template{
Name: "plugin.yaml",
Data: string(beforeInput),
Namespace: "octocat",
}
controller := gomock.NewController(t)
defer controller.Finish()
templates := mock.NewMockTemplateStore(controller)
templates.EXPECT().FindName(gomock.Any(), template.Name, req.Repo.Namespace).Return(template, nil)
plugin := Template(templates, 0)
plugin := Template(templates)
config, err := plugin.Convert(noContext, req)
if err != nil {
t.Error(err)

View file

@ -1,4 +1,3 @@
---
kind: template
load: plugin.starlark
data:

View file

@ -1,8 +0,0 @@
---
# this is a comment
kind: template
load: plugin.yaml
data:
stepName: my_step
image: my_image
commands: my_command

View file

@ -1,6 +0,0 @@
kind: template
load: plugin.txt
data:
stepName: my_step
image: my_image
commands: my_command

View file

@ -19,15 +19,13 @@ import (
"sync"
"time"
"github.com/drone/drone/core"
"github.com/drone/drone/service/redisdb"
"github.com/drone/drone-go/drone"
"github.com/drone/drone/core"
)
type queue struct {
sync.Mutex
globMx redisdb.LockErr
ready chan struct{}
paused bool
@ -42,7 +40,6 @@ type queue struct {
func newQueue(store core.StageStore) *queue {
q := &queue{
store: store,
globMx: redisdb.LockErrNoOp{},
ready: make(chan struct{}, 1),
workers: map[*worker]struct{}{},
interval: time.Minute,
@ -118,11 +115,6 @@ func (q *queue) Request(ctx context.Context, params core.Filter) (*core.Stage, e
}
func (q *queue) signal(ctx context.Context) error {
if err := q.globMx.LockContext(ctx); err != nil {
return err
}
defer q.globMx.UnlockContext(ctx)
q.Lock()
count := len(q.workers)
pause := q.paused

View file

@ -17,8 +17,6 @@
package queue
import (
"time"
"github.com/drone/drone/core"
"github.com/drone/drone/service/redisdb"
)
@ -32,13 +30,8 @@ func New(store core.StageStore, r redisdb.RedisDB) core.Scheduler {
}
}
sched := schedulerRedis{
return schedulerRedis{
queue: newQueue(store),
cancellerRedis: newCancellerRedis(r),
}
const globalMutexExpiryTime = 10 * time.Second
sched.globMx = r.NewMutex("drone-scheduler-mx", globalMutexExpiryTime)
return sched
}

View file

@ -16,7 +16,6 @@ package commit
import (
"context"
"github.com/drone/drone/core"
"github.com/drone/go-scm/scm"
)
@ -79,8 +78,8 @@ func (s *service) FindRef(ctx context.Context, user *core.User, repo, ref string
})
switch s.client.Driver {
case scm.DriverBitbucket,
scm.DriverStash:
case scm.DriverBitbucket:
case scm.DriverStash:
ref = scm.TrimRef(ref)
branch, _, err := s.client.Git.FindBranch(ctx, repo, ref) // wont work for a Tag
if err != nil {

View file

@ -77,7 +77,7 @@ func (s *Service) Create(ctx context.Context, user *core.User, repo *core.Reposi
}
switch s.client.Driver {
case scm.DriverGitlab, scm.DriverGitee:
case scm.DriverGitlab:
netrc.Login = "oauth2"
netrc.Password = user.Token
case scm.DriverBitbucket:

View file

@ -141,37 +141,6 @@ func TestNetrc_Bitbucket(t *testing.T) {
}
}
func TestNetrc_Gitee(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
mockRepo := &core.Repository{Private: true, HTTPURL: "https://gitee.com/kit101/drone-yml-test"}
mockUser := &core.User{
Token: "755bb80e5b",
Refresh: "e08f3fa43e",
}
mockRenewer := mock.NewMockRenewer(controller)
mockRenewer.EXPECT().Renew(gomock.Any(), mockUser, true)
s := Service{
renewer: mockRenewer,
client: &scm.Client{Driver: scm.DriverGitee},
}
got, err := s.Create(noContext, mockUser, mockRepo)
if err != nil {
t.Error(err)
}
want := &core.Netrc{
Machine: "gitee.com",
Login: "oauth2",
Password: "755bb80e5b",
}
if diff := cmp.Diff(got, want); diff != "" {
t.Errorf(diff)
}
}
func TestNetrc_Nil(t *testing.T) {
s := Service{
private: false,

View file

@ -1,32 +0,0 @@
// Copyright 2021 Drone IO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package redisdb
import (
"context"
)
// LockErr is an interface with lock and unlock functions that return an error.
// Method names are chosen so that redsync.Mutex implements the interface.
type LockErr interface {
LockContext(context.Context) error
UnlockContext(context.Context) (bool, error)
}
// LockErrNoOp is a dummy no-op locker
type LockErrNoOp struct{}
func (l LockErrNoOp) LockContext(context.Context) error { return nil }
func (l LockErrNoOp) UnlockContext(context.Context) (bool, error) { return false, nil }

View file

@ -19,9 +19,6 @@ import (
"fmt"
"time"
"github.com/go-redsync/redsync/v4"
"github.com/go-redsync/redsync/v4/redis/goredis/v8"
"github.com/drone/drone/cmd/drone-server/config"
"github.com/go-redis/redis/v8"
@ -54,11 +51,8 @@ func New(config config.Config) (srv RedisDB, err error) {
return
}
rs := redsync.New(goredis.NewPool(rdb))
srv = redisService{
rdb: rdb,
mutexGen: rs,
rdb: rdb,
}
return
@ -67,12 +61,10 @@ func New(config config.Config) (srv RedisDB, err error) {
type RedisDB interface {
Client() redis.Cmdable
Subscribe(ctx context.Context, channelName string, channelSize int, proc PubSubProcessor)
NewMutex(name string, expiry time.Duration) LockErr
}
type redisService struct {
rdb *redis.Client
mutexGen *redsync.Redsync
rdb *redis.Client
}
// Client exposes redis.Cmdable interface
@ -175,12 +167,3 @@ func (r redisService) Subscribe(ctx context.Context, channelName string, channel
}
}
}
func (r redisService) NewMutex(name string, expiry time.Duration) LockErr {
var options []redsync.Option
if expiry > 0 {
options = append(options, redsync.WithExpiry(expiry))
}
return r.mutexGen.NewMutex(name, options...)
}

View file

@ -57,9 +57,7 @@ func (s *service) List(ctx context.Context, user *core.User) ([]*core.Repository
return nil, err
}
for _, src := range result {
if src != nil {
repos = append(repos, convertRepository(src, s.visibility, s.trusted))
}
repos = append(repos, convertRepository(src, s.visibility, s.trusted))
}
opts.Page = meta.Page.Next
opts.URL = meta.Page.NextURL

View file

@ -246,44 +246,3 @@ func TestList_RefreshErr(t *testing.T) {
t.Errorf("Expect error refreshing token")
}
}
func TestListWithNilRepo(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
mockUser := &core.User{}
mockRepos := []*scm.Repository{
{
Namespace: "octocat",
Name: "hello-world",
},
nil,
}
mockRepoService := mockscm.NewMockRepositoryService(controller)
mockRepoService.EXPECT().List(gomock.Any(), gomock.Any()).Return(mockRepos, &scm.Response{}, nil)
mockRenewer := mock.NewMockRenewer(controller)
mockRenewer.EXPECT().Renew(gomock.Any(), mockUser, false)
client := new(scm.Client)
client.Repositories = mockRepoService
want := []*core.Repository{
{
Namespace: "octocat",
Name: "hello-world",
Slug: "octocat/hello-world",
Visibility: "public",
},
}
service := New(client, mockRenewer, "", false)
got, err := service.List(noContext, mockUser)
if err != nil {
t.Error(err)
}
if diff := cmp.Diff(got, want); diff != "" {
t.Errorf(diff)
}
}

View file

@ -35,7 +35,6 @@ func convertRepository(src *scm.Repository, visibility string, trusted bool) *co
Visibility: convertVisibility(src, visibility),
Branch: src.Branch,
Trusted: trusted,
Archived: src.Archived,
}
}

View file

@ -76,7 +76,7 @@ func (s *service) Send(ctx context.Context, user *core.User, req *core.StatusInp
Desc: createDesc(req.Build.Status),
State: convertStatus(req.Build.Status),
Target: fmt.Sprintf("%s/%s/%d", s.base, req.Repo.Slug, req.Build.Number),
Environment: req.Build.Deploy,
Environment: req.Build.Target,
})
return err
}

View file

@ -105,6 +105,7 @@ func TestCreateDesc(t *testing.T) {
}
func TestConvertStatus(t *testing.T) {
tests := []struct {
from string
to scm.State

View file

@ -16,7 +16,6 @@ package syncer
import (
"context"
"runtime/debug"
"strings"
"time"
@ -67,7 +66,7 @@ func (s *Synchronizer) Sync(ctx context.Context, user *core.User) (*core.Batch,
// a panic that should absolutely never happen.
if err := recover(); err != nil {
logger = logger.WithField("error", err)
logger.Errorf("syncer: unexpected panic\n%s\n", debug.Stack())
logger.Errorln("syncer: unexpected panic")
}
// when the synchronization process is complete
@ -111,13 +110,6 @@ func (s *Synchronizer) Sync(ctx context.Context, user *core.User) (*core.Batch,
WithField("uid", repo.UID).
Traceln("syncer: skipping subrepositories")
}
} else if repo.Archived {
if logrus.GetLevel() == logrus.TraceLevel {
logger.WithField("namespace", repo.Namespace).
WithField("name", repo.Name).
WithField("uid", repo.UID).
Traceln("syncer: skipping archived repositories")
}
} else if s.match(repo) {
remote[repo.UID] = repo
if logrus.GetLevel() == logrus.TraceLevel {

View file

@ -434,52 +434,3 @@ func TestSync_SkipSubrepo(t *testing.T) {
t.Errorf(diff)
}
}
func TestSyncArchive(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
user := &core.User{ID: 1}
userStore := mock.NewMockUserStore(controller)
userStore.EXPECT().Update(gomock.Any(), user).Return(nil)
userStore.EXPECT().Update(gomock.Any(), user).Return(nil)
batcher := mock.NewMockBatcher(controller)
batcher.EXPECT().Batch(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
repoStore := mock.NewMockRepositoryStore(controller)
repoStore.EXPECT().List(gomock.Any(), gomock.Any()).Return([]*core.Repository{}, nil)
repoService := mock.NewMockRepositoryService(controller)
repoService.EXPECT().List(gomock.Any(), user).Return([]*core.Repository{
{
UID: "1",
Slug: "octocat/hello-world",
Namespace: "octocat",
Name: "hello-world",
Private: false,
Visibility: core.VisibilityPublic,
Archived: true,
},
}, nil)
s := New(
repoService,
repoStore,
userStore,
batcher,
)
got, err := s.Sync(context.Background(), user)
if err != nil {
t.Error(err)
}
want := &core.Batch{}
ignore := cmpopts.IgnoreFields(core.Repository{},
"Synced", "Created", "Updated")
if diff := cmp.Diff(got, want, ignore); len(diff) != 0 {
t.Errorf(diff)
}
}

View file

@ -18,9 +18,10 @@ import "time"
// Config provides the session configuration.
type Config struct {
Secure bool
Secret string
Timeout time.Duration
Secure bool
Secret string
Timeout time.Duration
MappingFile string
}
// NewConfig returns a new session configuration.

108
session/legacy.go Normal file
View file

@ -0,0 +1,108 @@
// Copyright 2019 Drone IO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package session
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"github.com/drone/drone/core"
"github.com/dgrijalva/jwt-go"
)
type legacy struct {
*session
mapping map[string]string
}
// Legacy returns a session manager that is capable of mapping
// legacy tokens to 1.0 users using a mapping file.
func Legacy(users core.UserStore, config Config) (core.Session, error) {
base := &session{
secret: []byte(config.Secret),
secure: config.Secure,
timeout: config.Timeout,
users: users,
}
out, err := ioutil.ReadFile(config.MappingFile)
if err != nil {
return nil, err
}
mapping := map[string]string{}
err = json.Unmarshal(out, &mapping)
if err != nil {
return nil, err
}
return &legacy{base, mapping}, nil
}
func (s *legacy) Get(r *http.Request) (*core.User, error) {
switch {
case isAuthorizationToken(r):
return s.fromToken(r)
case isAuthorizationParameter(r):
return s.fromToken(r)
default:
return s.fromSession(r)
}
}
func (s *legacy) fromToken(r *http.Request) (*core.User, error) {
extracted := extractToken(r)
// determine if the token is a legacy token based on length.
// legacy tokens are > 64 characters.
if len(extracted) < 64 {
return s.users.FindToken(r.Context(), extracted)
}
token, err := jwt.Parse(extracted, func(token *jwt.Token) (interface{}, error) {
// validate the signing method
_, ok := token.Method.(*jwt.SigningMethodHMAC)
if !ok {
return nil, errors.New("Legacy token: invalid signature")
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, errors.New("Legacy token: invalid claim format")
}
// extract the username claim
claim, ok := claims["text"]
if !ok {
return nil, errors.New("Legacy token: invalid format")
}
// lookup the username to get the secret
secret, ok := s.mapping[claim.(string)]
if !ok {
return nil, errors.New("Legacy token: cannot lookup user")
}
return []byte(secret), nil
})
if err != nil {
return nil, err
}
return s.users.FindLogin(
r.Context(),
token.Claims.(jwt.MapClaims)["text"].(string),
)
}

93
session/legacy_test.go Normal file
View file

@ -0,0 +1,93 @@
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
// +build !oss
package session
import (
"net/http/httptest"
"testing"
"time"
"github.com/drone/drone/core"
"github.com/drone/drone/mock"
"github.com/golang/mock/gomock"
)
func TestLegacyGet_NotLegacy(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
mockUser := &core.User{
Login: "octocat",
Hash: "ulSxuA0FKjNiOFIchk18NNvC6ygSxdtKjiOAS",
}
users := mock.NewMockUserStore(controller)
users.EXPECT().FindToken(gomock.Any(), mockUser.Hash).Return(mockUser, nil)
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set("Authorization", "Bearer ulSxuA0FKjNiOFIchk18NNvC6ygSxdtKjiOAS")
session, _ := Legacy(users, Config{Secure: false, Timeout: time.Hour, MappingFile: "testdata/mapping.json"})
user, _ := session.Get(r)
if user != mockUser {
t.Errorf("Want authenticated user")
}
}
func TestLegacyGet(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
mockUser := &core.User{
Login: "octocat",
Hash: "ulSxuA0FKjNiOFIchk18NNvC6ygSxdtKjiOAS",
}
users := mock.NewMockUserStore(controller)
users.EXPECT().FindLogin(gomock.Any(), gomock.Any()).Return(mockUser, nil)
r := httptest.NewRequest("GET", "/?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwidGV4dCI6Im9jdG9jYXQiLCJpYXQiOjE1MTYyMzkwMjJ9.jf17GpOuKu-KAhuvxtjVvmZfwyeC7mEpKNiM6_cGOvo", nil)
session, _ := Legacy(users, Config{Secure: false, Timeout: time.Hour, MappingFile: "testdata/mapping.json"})
user, err := session.Get(r)
if err != nil {
t.Error(err)
return
}
if user != mockUser {
t.Errorf("Want authenticated user")
}
}
func TestLegacyGet_UserNotFound(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
users := mock.NewMockUserStore(controller)
r := httptest.NewRequest("GET", "/?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwidGV4dCI6ImJpbGx5aWRvbCIsImlhdCI6MTUxNjIzOTAyMn0.yxTCucstDM7BaixXBMAJCXup9zBaFr02Kalv_PqCDM4", nil)
session, _ := Legacy(users, Config{Secure: false, Timeout: time.Hour, MappingFile: "testdata/mapping.json"})
_, err := session.Get(r)
if err == nil || err.Error() != "Legacy token: cannot lookup user" {
t.Errorf("Expect user lookup error, got %v", err)
return
}
}
func TestLegacyGet_InvalidSignature(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
users := mock.NewMockUserStore(controller)
r := httptest.NewRequest("GET", "/?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwidGV4dCI6InNwYWNlZ2hvc3QiLCJpYXQiOjE1MTYyMzkwMjJ9.jlGcn2WI_oEZyLqYrvNvDXNbG3H3rqMyqQI2Gc6CHIY", nil)
session, _ := Legacy(users, Config{Secure: false, Timeout: time.Hour, MappingFile: "testdata/mapping.json"})
_, err := session.Get(r)
if err == nil || err.Error() != "signature is invalid" {
t.Errorf("Expect user lookup error, got %v", err)
return
}
}

View file

@ -1,146 +0,0 @@
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
// +build !oss
package card
import (
"bytes"
"context"
"io"
"io/ioutil"
"github.com/drone/drone/core"
"github.com/drone/drone/store/shared/db"
)
// New returns a new card database store.
func New(db *db.DB) core.CardStore {
return &cardStore{
db: db,
}
}
type cardStore struct {
db *db.DB
}
type card struct {
Id int64 `json:"id,omitempty"`
Data []byte `json:"card_data"`
}
func (c cardStore) Find(ctx context.Context, step int64) (io.ReadCloser, error) {
out := &card{Id: step}
err := c.db.View(func(queryer db.Queryer, binder db.Binder) error {
params, err := toParams(out)
if err != nil {
return err
}
query, args, err := binder.BindNamed(queryKey, params)
if err != nil {
return err
}
row := queryer.QueryRow(query, args...)
return scanRow(row, out)
})
return ioutil.NopCloser(
bytes.NewBuffer(out.Data),
), err
}
func (c cardStore) Create(ctx context.Context, step int64, r io.Reader) error {
data, err := ioutil.ReadAll(r)
if err != nil {
return err
}
return c.db.Lock(func(execer db.Execer, binder db.Binder) error {
in := &card{
Id: step,
Data: data,
}
params, err := toParams(in)
stmt, args, err := binder.BindNamed(stmtInsert, params)
if err != nil {
return err
}
_, err = execer.Exec(stmt, args...)
return err
})
}
func (c *cardStore) Update(ctx context.Context, step int64, r io.Reader) error {
data, err := ioutil.ReadAll(r)
if err != nil {
return err
}
return c.db.Lock(func(execer db.Execer, binder db.Binder) error {
card := &card{
Id: step,
Data: data,
}
params, err := toParams(card)
if err != nil {
return err
}
stmt, args, err := binder.BindNamed(stmtUpdate, params)
if err != nil {
return err
}
_, err = execer.Exec(stmt, args...)
return err
})
}
func (c cardStore) Delete(ctx context.Context, step int64) error {
return c.db.Lock(func(execer db.Execer, binder db.Binder) error {
params := &card{
Id: step,
}
stmt, args, err := binder.BindNamed(stmtDelete, params)
if err != nil {
return err
}
_, err = execer.Exec(stmt, args...)
return err
})
}
const queryBase = `
SELECT
card_id
,card_data
`
const queryKey = queryBase + `
FROM cards
WHERE card_id = :card_id
LIMIT 1
`
const stmtInsert = `
INSERT INTO cards (
card_id
,card_data
) VALUES (
:card_id
,:card_data
)
`
const stmtUpdate = `
UPDATE cards
SET card_data = :card_data
WHERE card_id = :card_id
`
const stmtDelete = `
DELETE FROM cards
WHERE card_id = :card_id
`
const stmtInsertPostgres = stmtInsert + `
RETURNING card_id
`

View file

@ -1,47 +0,0 @@
// Copyright 2019 Drone IO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build oss
package card
import (
"context"
"io"
"github.com/drone/drone/core"
"github.com/drone/drone/store/shared/db"
)
func New(db *db.DB) core.CardStore {
return new(noop)
}
type noop struct{}
func (noop) Find(ctx context.Context, step int64) (io.ReadCloser, error) {
return nil, nil
}
func (noop) Create(ctx context.Context, step int64, r io.Reader) error {
return nil
}
func (noop) Update(ctx context.Context, step int64, r io.Reader) error {
return nil
}
func (noop) Delete(ctx context.Context, step int64) error {
return nil
}

View file

@ -1,122 +0,0 @@
package card
import (
"bytes"
"context"
"database/sql"
"io/ioutil"
"testing"
"github.com/drone/drone/core"
"github.com/drone/drone/store/build"
"github.com/drone/drone/store/repos"
"github.com/drone/drone/store/shared/db/dbtest"
"github.com/drone/drone/store/step"
)
var noContext = context.TODO()
func TestCard(t *testing.T) {
conn, err := dbtest.Connect()
if err != nil {
t.Error(err)
return
}
defer func() {
dbtest.Reset(conn)
dbtest.Disconnect(conn)
}()
// seed with a dummy repository
dummyRepo := &core.Repository{UID: "1", Slug: "octocat/hello-world"}
repos := repos.New(conn)
repos.Create(noContext, dummyRepo)
// seed with a dummy stage
stage := &core.Stage{Number: 1}
stages := []*core.Stage{stage}
// seed with a dummy build
dummyBuild := &core.Build{Number: 1, RepoID: dummyRepo.ID}
builds := build.New(conn)
builds.Create(noContext, dummyBuild, stages)
// seed with a dummy step
dummyStep := &core.Step{Number: 1, StageID: stage.ID}
steps := step.New(conn)
steps.Create(noContext, dummyStep)
store := New(conn).(*cardStore)
t.Run("Create", testCardCreate(store, dummyStep))
t.Run("Find", testFindCard(store, dummyStep))
t.Run("Update", testLogsUpdate(store, dummyStep))
}
func testCardCreate(store *cardStore, step *core.Step) func(t *testing.T) {
return func(t *testing.T) {
buf := ioutil.NopCloser(
bytes.NewBuffer([]byte("{\"type\": \"AdaptiveCard\"}")),
)
err := store.Create(noContext, step.ID, buf)
if err != nil {
t.Error(err)
}
}
}
func testFindCard(card *cardStore, step *core.Step) func(t *testing.T) {
return func(t *testing.T) {
r, err := card.Find(noContext, step.ID)
if err != nil {
t.Error(err)
} else {
data, err := ioutil.ReadAll(r)
if err != nil {
t.Error(err)
return
}
if got, want := string(data), "{\"type\": \"AdaptiveCard\"}"; got != want {
t.Errorf("Want card data output stream %q, got %q", want, got)
}
}
}
}
func testLogsUpdate(store *cardStore, step *core.Step) func(t *testing.T) {
return func(t *testing.T) {
buf := bytes.NewBufferString("hola mundo")
err := store.Update(noContext, step.ID, buf)
if err != nil {
t.Error(err)
return
}
r, err := store.Find(noContext, step.ID)
if err != nil {
t.Error(err)
return
}
data, err := ioutil.ReadAll(r)
if err != nil {
t.Error(err)
return
}
if got, want := string(data), "hola mundo"; got != want {
t.Errorf("Want updated log output stream %q, got %q", want, got)
}
}
}
func testLogsDelete(store *cardStore, step *core.Step) func(t *testing.T) {
return func(t *testing.T) {
err := store.Delete(noContext, step.ID)
if err != nil {
t.Error(err)
return
}
_, err = store.Find(noContext, step.ID)
if got, want := sql.ErrNoRows, err; got != want {
t.Errorf("Want sql.ErrNoRows, got %v", got)
return
}
}
}

View file

@ -1,33 +0,0 @@
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
// +build !oss
package card
import (
"github.com/drone/drone/store/shared/db"
)
// helper function converts the card structure to a set
// of named query parameters.
func toParams(card *card) (map[string]interface{}, error) {
return map[string]interface{}{
"card_id": card.Id,
"card_data": card.Data,
}, nil
}
// helper function scans the sql.Row and copies the column
// values to the destination object.
func scanRow(scanner db.Scanner, dst *card) error {
err := scanner.Scan(
&dst.Id,
&dst.Data,
)
if err != nil {
return err
}
return nil
}

View file

@ -104,19 +104,6 @@ func (s *repoStore) ListIncomplete(ctx context.Context) ([]*core.Repository, err
return out, err
}
func (s *repoStore) ListRunningStatus(ctx context.Context) ([]*core.RepoBuildStage, error) {
var out []*core.RepoBuildStage
err := s.db.View(func(queryer db.Queryer, binder db.Binder) error {
rows, err := queryer.Query(queryReposRunningStatus)
if err != nil {
return err
}
out, err = repoBuildStageRowsBuild(rows)
return err
})
return out, err
}
func (s *repoStore) ListAll(ctx context.Context, limit, offset int) ([]*core.Repository, error) {
var out []*core.Repository
err := s.db.View(func(queryer db.Queryer, binder db.Binder) error {
@ -549,37 +536,3 @@ WHERE EXISTS (
ORDER BY build_id DESC
LIMIT 50;
`
const queryReposRunningStatus = `
SELECT
repo_namespace
,repo_name
,repo_slug
,build_number
,build_author
,build_author_name
,build_author_email
,build_author_avatar
,build_sender
,build_started
,build_finished
,build_created
,build_updated
,stage_name
,stage_kind
,stage_type
,stage_status
,stage_machine
,stage_os
,stage_arch
,stage_variant
,stage_kernel
,stage_limit
,stage_limit_repo
,stage_started
,stage_stopped
FROM repos
INNER JOIN builds ON builds.build_repo_id = repos.repo_id
inner join stages on stages.stage_build_id = builds.build_id
where stages.stage_status IN ('pending', 'running')
ORDER BY build_id DESC;
`

View file

@ -208,52 +208,3 @@ func scanRowsBuild(rows *sql.Rows) ([]*core.Repository, error) {
}
return repos, nil
}
// helper function scans the sql.Row and copies the column values to the destination object.
func repoBuildStageRowBuild(scanner db.Scanner, dest *core.RepoBuildStage) error {
err := scanner.Scan(
&dest.RepoNamespace,
&dest.RepoName,
&dest.RepoSlug,
&dest.BuildNumber,
&dest.BuildAuthor,
&dest.BuildAuthorName,
&dest.BuildAuthorEmail,
&dest.BuildAuthorAvatar,
&dest.BuildSender,
&dest.BuildStarted,
&dest.BuildFinished,
&dest.BuildCreated,
&dest.BuildUpdated,
&dest.StageName,
&dest.StageKind,
&dest.StageType,
&dest.StageStatus,
&dest.StageMachine,
&dest.StageOS,
&dest.StageArch,
&dest.StageVariant,
&dest.StageKernel,
&dest.StageLimit,
&dest.StageLimitRepo,
&dest.StageStarted,
&dest.StageStopped,
)
return err
}
// helper function scans the sql.Row and copies the column values to the destination object.
func repoBuildStageRowsBuild(rows *sql.Rows) ([]*core.RepoBuildStage, error) {
defer rows.Close()
slices := []*core.RepoBuildStage{}
for rows.Next() {
row := new(core.RepoBuildStage)
err := repoBuildStageRowBuild(rows, row)
if err != nil {
return nil, err
}
slices = append(slices, row)
}
return slices, nil
}

View file

@ -48,7 +48,6 @@ func Connect() (*db.DB, error) {
func Reset(d *db.DB) {
d.Lock(func(tx db.Execer, _ db.Binder) error {
tx.Exec("DELETE FROM cron")
tx.Exec("DELETE FROM cards")
tx.Exec("DELETE FROM logs")
tx.Exec("DELETE FROM steps")
tx.Exec("DELETE FROM stages")
@ -57,7 +56,6 @@ func Reset(d *db.DB) {
tx.Exec("DELETE FROM perms")
tx.Exec("DELETE FROM repos")
tx.Exec("DELETE FROM users")
tx.Exec("DELETE FROM templates")
tx.Exec("DELETE FROM orgsecrets")
return nil
})

Some files were not shown because too many files have changed in this diff Show more