├── .dockerignore ├── .drone.yml ├── .github ├── issue_template.md ├── pull_request_template.md └── settings.yml ├── .gitignore ├── .golangci.yml ├── LICENSE ├── README.md ├── docker ├── Dockerfile.linux.amd64 ├── Dockerfile.linux.arm64 └── manifest.tmpl ├── go.mod ├── go.sum ├── main.go └── plugin ├── __test__ └── package.json ├── __testwithport__ └── package.json ├── impl.go ├── impl_test.go ├── plugin.go └── plugin_test.go /.dockerignore: -------------------------------------------------------------------------------- 1 | * 2 | !release/ 3 | -------------------------------------------------------------------------------- /.drone.yml: -------------------------------------------------------------------------------- 1 | kind: pipeline 2 | type: vm 3 | name: testing 4 | platform: 5 | os: linux 6 | arch: amd64 7 | pool: 8 | use: ubuntu 9 | 10 | steps: 11 | - name: lint 12 | image: golang:1.19 13 | pull: always 14 | commands: 15 | - go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.50.1 16 | - golangci-lint version 17 | - golangci-lint run 18 | volumes: 19 | - name: gopath 20 | path: "/go" 21 | - name: test 22 | image: golang:1.19 23 | commands: 24 | - go test -cover ./... 25 | volumes: 26 | - name: gopath 27 | path: "/go" 28 | volumes: 29 | - name: gopath 30 | temp: {} 31 | trigger: 32 | ref: 33 | - refs/heads/master 34 | - refs/tags/** 35 | - refs/pull/** 36 | 37 | --- 38 | kind: pipeline 39 | type: vm 40 | name: linux-amd64 41 | platform: 42 | os: linux 43 | arch: amd64 44 | pool: 45 | use: ubuntu 46 | 47 | steps: 48 | - name: environment 49 | image: golang:1.19 50 | pull: always 51 | environment: 52 | CGO_ENABLED: "0" 53 | commands: 54 | - go version 55 | - go env 56 | - name: build 57 | image: golang:1.19 58 | environment: 59 | CGO_ENABLED: "0" 60 | commands: 61 | - go build -v -ldflags "-X main.version=" -a -tags netgo -o release/linux/amd64/drone-npm . 62 | - name: docker 63 | image: plugins/docker 64 | settings: 65 | dockerfile: docker/Dockerfile.linux.amd64 66 | repo: plugins/npm 67 | username: 68 | from_secret: docker_username 69 | password: 70 | from_secret: docker_password 71 | auto_tag: true 72 | auto_tag_suffix: linux-amd64 73 | depends_on: 74 | - testing 75 | trigger: 76 | ref: 77 | - refs/heads/master 78 | - refs/tags/** 79 | - refs/pull/** 80 | 81 | --- 82 | kind: pipeline 83 | type: vm 84 | name: linux-arm64 85 | platform: 86 | os: linux 87 | arch: arm64 88 | pool: 89 | use: ubuntu_arm64 90 | 91 | steps: 92 | - name: environment 93 | image: golang:1.19 94 | pull: always 95 | environment: 96 | CGO_ENABLED: "0" 97 | commands: 98 | - go version 99 | - go env 100 | - name: build 101 | image: golang:1.19 102 | environment: 103 | CGO_ENABLED: "0" 104 | commands: 105 | - go build -v -ldflags "-X main.version=" -a -tags netgo -o release/linux/arm64/drone-npm . 106 | - name: docker 107 | image: plugins/docker 108 | settings: 109 | dockerfile: docker/Dockerfile.linux.arm64 110 | repo: plugins/npm 111 | username: 112 | from_secret: docker_username 113 | password: 114 | from_secret: docker_password 115 | auto_tag: true 116 | auto_tag_suffix: linux-arm64 117 | depends_on: 118 | - testing 119 | trigger: 120 | ref: 121 | - refs/heads/master 122 | - refs/tags/** 123 | - refs/pull/** 124 | 125 | --- 126 | kind: pipeline 127 | type: vm 128 | name: manifest 129 | platform: 130 | os: linux 131 | arch: amd64 132 | pool: 133 | use: ubuntu 134 | 135 | steps: 136 | - name: manifest 137 | image: plugins/manifest 138 | settings: 139 | auto_tag: "true" 140 | username: 141 | from_secret: docker_username 142 | password: 143 | from_secret: docker_password 144 | spec: docker/manifest.tmpl 145 | ignore_missing: true 146 | depends_on: 147 | - linux-amd64 148 | - linux-arm64 149 | 150 | trigger: 151 | ref: 152 | - refs/heads/master 153 | - refs/tags/** 154 | -------------------------------------------------------------------------------- /.github/issue_template.md: -------------------------------------------------------------------------------- 1 | 10 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drone-plugins/drone-npm/df2ebf6cd93adf7d0751d1b56f7e92f439134e82/.github/pull_request_template.md -------------------------------------------------------------------------------- /.github/settings.yml: -------------------------------------------------------------------------------- 1 | repository: 2 | name: drone-npm 3 | description: Drone plugin for publishing packages to NPM 4 | homepage: http://plugins.drone.io/drone-plugins/drone-npm 5 | topics: drone, drone-plugin 6 | 7 | private: false 8 | has_issues: true 9 | has_wiki: false 10 | has_downloads: false 11 | 12 | default_branch: master 13 | 14 | allow_squash_merge: true 15 | allow_merge_commit: true 16 | allow_rebase_merge: true 17 | 18 | labels: 19 | - name: bug 20 | color: d73a4a 21 | description: Something isn't working 22 | - name: duplicate 23 | color: cfd3d7 24 | description: This issue or pull request already exists 25 | - name: enhancement 26 | color: a2eeef 27 | description: New feature or request 28 | - name: good first issue 29 | color: 7057ff 30 | description: Good for newcomers 31 | - name: help wanted 32 | color: 008672 33 | description: Extra attention is needed 34 | - name: invalid 35 | color: e4e669 36 | description: This doesn't seem right 37 | - name: question 38 | color: d876e3 39 | description: Further information is requested 40 | - name: renovate 41 | color: e99695 42 | description: Automated action from Renovate 43 | - name: wontfix 44 | color: ffffff 45 | description: This will not be worked on 46 | 47 | teams: 48 | - name: Admins 49 | permission: admin 50 | - name: Captain 51 | permission: admin 52 | - name: Maintainers 53 | permission: push 54 | 55 | branches: 56 | - name: master 57 | protection: 58 | required_pull_request_reviews: 59 | required_approving_review_count: 1 60 | dismiss_stale_reviews: false 61 | require_code_owner_reviews: false 62 | dismissal_restrictions: 63 | teams: 64 | - Admins 65 | - Captain 66 | required_status_checks: 67 | strict: true 68 | contexts: 69 | - continuous-integration/drone/pr 70 | enforce_admins: false 71 | restrictions: 72 | apps: 73 | - renovate 74 | users: [] 75 | teams: 76 | - Admins 77 | - Maintainers 78 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /release/ 2 | /drone-npm* 3 | 4 | coverage.out 5 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | linters-settings: 2 | dupl: 3 | threshold: 100 4 | funlen: 5 | lines: 400 6 | statements: 100 7 | gci: 8 | local-prefixes: github.com/golangci/golangci-lint 9 | goconst: 10 | min-len: 3 11 | min-occurrences: 3 12 | gocritic: 13 | enabled-tags: 14 | - diagnostic 15 | - experimental 16 | - opinionated 17 | - performance 18 | - style 19 | disabled-checks: 20 | - dupImport # https://github.com/go-critic/go-critic/issues/845 21 | - ifElseChain 22 | - octalLiteral 23 | - whyNoLint 24 | - wrapperFunc 25 | gocyclo: 26 | min-complexity: 25 27 | goimports: 28 | local-prefixes: github.com/golangci/golangci-lint 29 | gomnd: 30 | settings: 31 | mnd: 32 | # don't include the "operation" and "assign" 33 | checks: argument,case,condition,return 34 | govet: 35 | check-shadowing: true 36 | settings: 37 | printf: 38 | funcs: 39 | - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof 40 | - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf 41 | - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf 42 | - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf 43 | lll: 44 | line-length: 200 45 | maligned: 46 | suggest-new: true 47 | misspell: 48 | locale: US 49 | nolintlint: 50 | allow-leading-space: true # don't require machine-readable nolint directives (i.e. with no leading space) 51 | allow-unused: false # report any unused nolint directives 52 | require-explanation: false # don't require an explanation for nolint directives 53 | require-specific: false # don't require nolint directives to be specific about which linter is being skipped 54 | nakedret: 55 | max-func-lines: 100 56 | 57 | linters: 58 | # please, do not use `enable-all`: it's deprecated and will be removed soon. 59 | # inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint 60 | disable-all: true 61 | enable: 62 | - bodyclose 63 | - deadcode 64 | - depguard 65 | - dogsled 66 | - errcheck 67 | - exportloopref 68 | - exhaustive 69 | - funlen 70 | - gochecknoinits 71 | - goconst 72 | - gocritic 73 | - gocyclo 74 | - gofmt 75 | - goimports 76 | - gomnd 77 | - goprintffuncname 78 | #- gosec 79 | - gosimple 80 | - govet 81 | - ineffassign 82 | - lll 83 | - misspell 84 | - nakedret 85 | - noctx 86 | - nolintlint 87 | - revive 88 | - rowserrcheck 89 | - staticcheck 90 | - structcheck 91 | - stylecheck 92 | - typecheck 93 | - unconvert 94 | - unparam 95 | - unused 96 | - varcheck 97 | - whitespace 98 | 99 | # don't enable: 100 | # - asciicheck 101 | # - dupl 102 | # - scopelint 103 | # - gochecknoglobals 104 | # - gocognit 105 | # - godot 106 | # - godox 107 | # - goerr113 108 | # - interfacer 109 | # - maligned 110 | # - nestif 111 | # - prealloc 112 | # - testpackage 113 | # - revive 114 | # - wsl 115 | 116 | issues: 117 | # Excluding configuration per-path, per-linter, per-text and per-source 118 | exclude-rules: 119 | - path: _test\.go 120 | linters: 121 | - gomnd 122 | 123 | # https://github.com/go-critic/go-critic/issues/926 124 | - linters: 125 | - gocritic 126 | text: "unnecessaryDefer:" 127 | 128 | run: 129 | skip-files: 130 | - _gen\.go 131 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # drone-npm 2 | 3 | [![Build Status](http://cloud.drone.io/api/badges/drone-plugins/drone-npm/status.svg)](http://cloud.drone.io/drone-plugins/drone-npm) 4 | [![Gitter chat](https://badges.gitter.im/drone/drone.png)](https://gitter.im/drone/drone) 5 | [![Join the discussion at https://discourse.drone.io](https://img.shields.io/badge/discourse-forum-orange.svg)](https://discourse.drone.io) 6 | [![Drone questions at https://stackoverflow.com](https://img.shields.io/badge/drone-stackoverflow-orange.svg)](https://stackoverflow.com/questions/tagged/drone.io) 7 | [![](https://images.microbadger.com/badges/image/plugins/npm.svg)](https://microbadger.com/images/plugins/npm "Get your own image badge on microbadger.com") 8 | [![Go Doc](https://godoc.org/github.com/drone-plugins/drone-npm?status.svg)](http://godoc.org/github.com/drone-plugins/drone-npm) 9 | [![Go Report](https://goreportcard.com/badge/github.com/drone-plugins/drone-npm)](https://goreportcard.com/report/github.com/drone-plugins/drone-npm) 10 | 11 | Drone plugin to publish files and artifacts to a private or public NPM registry. For the usage information and a listing of the available options please take a look at [the docs](http://plugins.drone.io/drone-plugins/drone-npm/). 12 | 13 | ## Build 14 | 15 | Build the binary with the following command: 16 | 17 | ```console 18 | export GOOS=linux 19 | export GOARCH=amd64 20 | export CGO_ENABLED=0 21 | export GO111MODULE=on 22 | 23 | go build -v -a -tags netgo -o release/linux/amd64/drone-npm 24 | ``` 25 | 26 | ## Docker 27 | 28 | Build the Docker image with the following command: 29 | 30 | ```console 31 | docker build \ 32 | --label org.label-schema.build-date=$(date -u +"%Y-%m-%dT%H:%M:%SZ") \ 33 | --label org.label-schema.vcs-ref=$(git rev-parse --short HEAD) \ 34 | --file docker/Dockerfile.linux.amd64 --tag plugins/npm . 35 | ``` 36 | 37 | ## Usage 38 | ### Standard Local Usage 39 | ```console 40 | docker run --rm \ 41 | -e NPM_USERNAME=drone \ 42 | -e NPM_PASSWORD=password \ 43 | -e NPM_EMAIL=drone@drone.io \ 44 | -v $(pwd):$(pwd) \ 45 | -w $(pwd) \ 46 | plugins/npm 47 | ``` 48 | #### With a specified registry for validation 49 | This will allow the setting of the defautl publishing registry. This will also raise a validation error if the publish configuration of the npm package is not pointing to the specified registry. 50 | ```console 51 | docker run --rm \ 52 | -e NPM_USERNAME=drone \ 53 | -e NPM_PASSWORD=password \ 54 | -e NPM_EMAIL=drone@drone.io \ 55 | -e NPM_REGISTRY="https://fakenpm.reg.org/good/path" \ 56 | -v $(pwd):$(pwd) \ 57 | -w $(pwd) \ 58 | plugins/npm 59 | ``` 60 | 61 | #### Ignore registry validation 62 | This will all the setting of a default publishing registry but will skip the verification of it being the same as the one in the npmrc. In this instance no validation error is raised and the registry in the npm rc is used 63 | ```console 64 | docker run --rm \ 65 | -e NPM_USERNAME=drone \ 66 | -e NPM_PASSWORD=password \ 67 | -e NPM_EMAIL=drone@drone.io \ 68 | -e NPM_REGISTRY="https://fakenpm.reg.org/good/path" \ 69 | -e PLUGIN_SKIP_REGISTRY_VALIDATION=true \ 70 | -v $(pwd):$(pwd) \ 71 | -w $(pwd) \ 72 | plugins/npm 73 | ``` -------------------------------------------------------------------------------- /docker/Dockerfile.linux.amd64: -------------------------------------------------------------------------------- 1 | FROM plugins/base:linux-amd64 2 | 3 | LABEL maintainer="Drone.IO Community " \ 4 | org.label-schema.name="Drone NPM" \ 5 | org.label-schema.vendor="Drone.IO Community" \ 6 | org.label-schema.schema-version="1.0" 7 | 8 | RUN apk add --no-cache git nodejs npm 9 | 10 | ADD release/linux/amd64/drone-npm /bin/ 11 | ENTRYPOINT [ "/bin/drone-npm" ] 12 | -------------------------------------------------------------------------------- /docker/Dockerfile.linux.arm64: -------------------------------------------------------------------------------- 1 | FROM plugins/base:linux-arm64 2 | 3 | LABEL maintainer="Drone.IO Community " \ 4 | org.label-schema.name="Drone NPM" \ 5 | org.label-schema.vendor="Drone.IO Community" \ 6 | org.label-schema.schema-version="1.0" 7 | 8 | RUN apk add --no-cache git nodejs npm 9 | 10 | ADD release/linux/arm64/drone-npm /bin/ 11 | ENTRYPOINT [ "/bin/drone-npm" ] 12 | -------------------------------------------------------------------------------- /docker/manifest.tmpl: -------------------------------------------------------------------------------- 1 | image: plugins/npm:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}latest{{/if}} 2 | 3 | {{#if build.tags}} 4 | tags: 5 | {{#each build.tags}} 6 | - {{this}} 7 | {{/each}} 8 | {{/if}} 9 | 10 | manifests: 11 | - image: plugins/npm:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}linux-amd64 12 | platform: 13 | architecture: amd64 14 | os: linux 15 | - image: plugins/npm:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}linux-arm64 16 | platform: 17 | architecture: arm64 18 | os: linux 19 | variant: v8 20 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/drone-plugins/drone-npm 2 | 3 | go 1.19 4 | 5 | require ( 6 | github.com/drone-plugins/drone-plugin-lib v0.4.0 7 | github.com/joho/godotenv v1.4.0 8 | github.com/sirupsen/logrus v1.9.0 9 | github.com/urfave/cli/v2 v2.23.7 10 | ) 11 | 12 | require ( 13 | github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect 14 | github.com/davecgh/go-spew v1.1.1 // indirect 15 | github.com/pmezard/go-difflib v1.0.0 // indirect 16 | github.com/russross/blackfriday/v2 v2.1.0 // indirect 17 | github.com/stretchr/testify v1.10.0 // indirect 18 | github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect 19 | golang.org/x/sys v0.3.0 // indirect 20 | gopkg.in/yaml.v3 v3.0.1 // indirect 21 | ) 22 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 2 | github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= 3 | github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU= 4 | github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 5 | github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= 6 | github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 7 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 8 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 9 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 10 | github.com/drone-plugins/drone-plugin-lib v0.4.0 h1:qywEYGhquUuid6zNLmKia8CWY1TUa8jPQQ/G9ozfAmc= 11 | github.com/drone-plugins/drone-plugin-lib v0.4.0/go.mod h1:EgqogX38GoJFtckeSQyhBJYX8P+KWBPhdprAVvyRxF8= 12 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 13 | github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= 14 | github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= 15 | github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 16 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 17 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 18 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 19 | github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 20 | github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= 21 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 22 | github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= 23 | github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= 24 | github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= 25 | github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= 26 | github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= 27 | github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= 28 | github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= 29 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 30 | github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= 31 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 32 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 33 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 34 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 35 | github.com/urfave/cli/v2 v2.2.0/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ= 36 | github.com/urfave/cli/v2 v2.8.1 h1:CGuYNZF9IKZY/rfBe3lJpccSoIY1ytfvmgQT90cNOl4= 37 | github.com/urfave/cli/v2 v2.8.1/go.mod h1:Z41J9TPoffeoqP0Iza0YbAhGvymRdZAd2uPmZ5JxRdY= 38 | github.com/urfave/cli/v2 v2.23.7 h1:YHDQ46s3VghFHFf1DdF+Sh7H4RqhcM+t0TmZRJx4oJY= 39 | github.com/urfave/cli/v2 v2.23.7/go.mod h1:GHupkWPMM0M/sj1a2b4wUrWBPzazNrIjouW6fmdJLxc= 40 | github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= 41 | github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= 42 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 43 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 44 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 45 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 46 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 47 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= 48 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 49 | golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 50 | golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ= 51 | golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 52 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 53 | golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= 54 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 55 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 56 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 57 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 58 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 59 | gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= 60 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020, the Drone Plugins project authors. 2 | // Please see the AUTHORS file for details. All rights reserved. 3 | // Use of this source code is governed by an Apache 2.0 license that can be 4 | // found in the LICENSE file. 5 | 6 | // DO NOT MODIFY THIS FILE DIRECTLY 7 | 8 | package main 9 | 10 | import ( 11 | "os" 12 | 13 | "github.com/drone-plugins/drone-npm/plugin" 14 | "github.com/drone-plugins/drone-plugin-lib/errors" 15 | "github.com/drone-plugins/drone-plugin-lib/urfave" 16 | "github.com/joho/godotenv" 17 | "github.com/urfave/cli/v2" 18 | ) 19 | 20 | var version = "unknown" 21 | 22 | func main() { 23 | settings := &plugin.Settings{} 24 | 25 | if _, err := os.Stat("/run/drone/env"); err == nil { 26 | godotenv.Overload("/run/drone/env") //nolint:errcheck 27 | } 28 | 29 | app := &cli.App{ 30 | Name: "drone-npm", 31 | Usage: "push a package to a npm repository", 32 | Version: version, 33 | Flags: append(settingsFlags(settings), urfave.Flags()...), 34 | Action: run(settings), 35 | } 36 | 37 | if err := app.Run(os.Args); err != nil { 38 | errors.HandleExit(err) 39 | } 40 | } 41 | 42 | func run(settings *plugin.Settings) cli.ActionFunc { 43 | return func(ctx *cli.Context) error { 44 | urfave.LoggingFromContext(ctx) 45 | 46 | p := plugin.New( 47 | *settings, 48 | urfave.PipelineFromContext(ctx), 49 | urfave.NetworkFromContext(ctx), 50 | ) 51 | 52 | if err := p.Validate(); err != nil { 53 | if e, ok := err.(errors.ExitCoder); ok { 54 | return e 55 | } 56 | 57 | return errors.ExitMessagef("validation failed: %w", err) 58 | } 59 | 60 | if err := p.Execute(); err != nil { 61 | if e, ok := err.(errors.ExitCoder); ok { 62 | return e 63 | } 64 | 65 | return errors.ExitMessagef("execution failed: %w", err) 66 | } 67 | 68 | return nil 69 | } 70 | } 71 | 72 | // settingsFlags has the cli.Flags for the plugin.Settings. 73 | func settingsFlags(settings *plugin.Settings) []cli.Flag { 74 | return []cli.Flag{ 75 | &cli.StringFlag{ 76 | Name: "username", 77 | Usage: "NPM username", 78 | EnvVars: []string{"PLUGIN_USERNAME", "NPM_USERNAME"}, 79 | Destination: &settings.Username, 80 | }, 81 | &cli.StringFlag{ 82 | Name: "password", 83 | Usage: "NPM password", 84 | EnvVars: []string{"PLUGIN_PASSWORD", "NPM_PASSWORD"}, 85 | Destination: &settings.Password, 86 | }, 87 | &cli.StringFlag{ 88 | Name: "email", 89 | Usage: "NPM email", 90 | EnvVars: []string{"PLUGIN_EMAIL", "NPM_EMAIL"}, 91 | Destination: &settings.Email, 92 | }, 93 | &cli.StringFlag{ 94 | Name: "token", 95 | Usage: "NPM deploy token", 96 | EnvVars: []string{"PLUGIN_TOKEN", "NPM_TOKEN"}, 97 | Destination: &settings.Token, 98 | }, 99 | &cli.BoolFlag{ 100 | Name: "skip-whoami", 101 | Usage: "Skip credentials verification by running npm whoami command", 102 | EnvVars: []string{"PLUGIN_SKIP_WHOAMI", "NPM_SKIP_WHOAMI"}, 103 | Destination: &settings.SkipWhoami, 104 | }, 105 | &cli.StringFlag{ 106 | Name: "registry", 107 | Usage: "NPM registry", 108 | EnvVars: []string{"PLUGIN_REGISTRY", "NPM_REGISTRY"}, 109 | Destination: &settings.Registry, 110 | }, 111 | &cli.StringFlag{ 112 | Name: "folder", 113 | Usage: "folder containing package.json", 114 | EnvVars: []string{"PLUGIN_FOLDER"}, 115 | Destination: &settings.Folder, 116 | }, 117 | &cli.BoolFlag{ 118 | Name: "fail-on-version-conflict", 119 | Usage: "fail NPM publish if version already exists in NPM registry", 120 | EnvVars: []string{"PLUGIN_FAIL_ON_VERSION_CONFLICT"}, 121 | Destination: &settings.FailOnVersionConflict, 122 | }, 123 | &cli.StringFlag{ 124 | Name: "tag", 125 | Usage: "NPM publish tag", 126 | EnvVars: []string{"PLUGIN_TAG"}, 127 | Destination: &settings.Tag, 128 | }, 129 | &cli.StringFlag{ 130 | Name: "access", 131 | Usage: "NPM scoped package access", 132 | EnvVars: []string{"PLUGIN_ACCESS"}, 133 | Destination: &settings.Access, 134 | }, 135 | &cli.BoolFlag{ 136 | Name: "skip-registry-validation", 137 | Usage: "skips validation for uri in package.json and the currently configured registry", 138 | EnvVars: []string{"PLUGIN_SKIP_REGISTRY_VALIDATION"}, 139 | Destination: &settings.SkipRegistryValidation, 140 | }, 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /plugin/__test__/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "my-awesome-package", 3 | "version": "1.0.0", 4 | "author": "Your Name (https://example.com)", 5 | "publishConfig": { 6 | "registry": "https://fakenpm.reg.org/good/path" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /plugin/__testwithport__/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "my-awesome-package", 3 | "version": "1.0.0", 4 | "author": "Your Name (https://example.com)", 5 | "publishConfig": { 6 | "registry": "https://fakenpm.reg.org:443/good/path" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /plugin/impl.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020, the Drone Plugins project authors. 2 | // Please see the AUTHORS file for details. All rights reserved. 3 | // Use of this source code is governed by an Apache 2.0 license that can be 4 | // found in the LICENSE file. 5 | 6 | package plugin 7 | 8 | import ( 9 | "encoding/base64" 10 | "encoding/json" 11 | "fmt" 12 | "net" 13 | "net/url" 14 | "os" 15 | "os/exec" 16 | "os/user" 17 | "path" 18 | "strings" 19 | 20 | "github.com/sirupsen/logrus" 21 | ) 22 | 23 | type ( 24 | // Settings for the Plugin. 25 | Settings struct { 26 | Username string 27 | Password string 28 | Token string 29 | SkipWhoami bool 30 | Email string 31 | Registry string 32 | Folder string 33 | FailOnVersionConflict bool 34 | Tag string 35 | Access string 36 | SkipRegistryValidation bool 37 | 38 | npm *npmPackage 39 | } 40 | 41 | npmPackage struct { 42 | Name string `json:"name"` 43 | Version string `json:"version"` 44 | Config npmConfig `json:"publishConfig"` 45 | } 46 | 47 | npmConfig struct { 48 | Registry string `json:"registry"` 49 | } 50 | ) 51 | 52 | // globalRegistry defines the default NPM registry. 53 | const globalRegistry = "https://registry.npmjs.org/" 54 | 55 | // May be better as an enum in order to make it a const 56 | var defaultPortMap = map[string]string{ 57 | "http": "80", 58 | "https": "443", 59 | } 60 | 61 | func isNilPortOrStandardSchemePort(u *url.URL) bool { 62 | if u.Scheme != "http" && u.Scheme != "https" { 63 | // invalid schemes aren't worth checking and we want http or https 64 | return false 65 | } 66 | // since we verify above that the scheme above is valid and this map 67 | // is initialized in this file. It's safe to assume the key is in the map 68 | return u.Port() == "" || u.Port() == defaultPortMap[u.Scheme] 69 | } 70 | 71 | func (p *Plugin) CompareRegistries(nc npmConfig) (bool, error) { 72 | parsedConfigReg, err := url.Parse(nc.Registry) 73 | if err != nil { 74 | return false, fmt.Errorf("package.json registry: %s failed to parse", nc.Registry) 75 | } 76 | parsedSettingsReg, err := url.Parse(p.settings.Registry) 77 | if err != nil { 78 | return false, fmt.Errorf("drone yaml npm Registry: %s failed to parse", p.settings.Registry) 79 | } 80 | 81 | ncDefaultOrNilPort := isNilPortOrStandardSchemePort(parsedConfigReg) 82 | dyDefaultOrNilPort := isNilPortOrStandardSchemePort(parsedSettingsReg) 83 | 84 | matchingStatus := parsedSettingsReg.Scheme == parsedConfigReg.Scheme && 85 | parsedSettingsReg.Path == parsedConfigReg.Path && 86 | parsedSettingsReg.Hostname() == parsedConfigReg.Hostname() && 87 | dyDefaultOrNilPort == ncDefaultOrNilPort 88 | return matchingStatus, nil 89 | } 90 | 91 | // Validate handles the settings validation of the plugin. 92 | func (p *Plugin) Validate() error { 93 | // Check authentication options 94 | if p.settings.Token == "" { 95 | if p.settings.Username == "" { 96 | return fmt.Errorf("no username provided") 97 | } 98 | if p.settings.Email == "" { 99 | return fmt.Errorf("no email address provided") 100 | } 101 | if p.settings.Password == "" { 102 | return fmt.Errorf("no password provided") 103 | } 104 | 105 | logrus.WithFields(logrus.Fields{ 106 | "username": p.settings.Username, 107 | "email": p.settings.Email, 108 | }).Info("Specified credentials") 109 | } else { 110 | logrus.Info("Token credentials being used") 111 | } 112 | 113 | // Verify package.json file 114 | npm, err := readPackageFile(p.settings.Folder) 115 | if err != nil { 116 | return fmt.Errorf("invalid package.json: %w", err) 117 | } 118 | 119 | // Verify the same registry is being used 120 | if p.settings.Registry == "" { 121 | p.settings.Registry = globalRegistry 122 | } 123 | 124 | registriesMatch, err := p.CompareRegistries(npm.Config) 125 | if err != nil { 126 | return fmt.Errorf( 127 | "issue comparing the registries specified in drone yaml (%s) and package.json: (%s)", 128 | p.settings.Registry, 129 | npm.Config.Registry, 130 | ) // if there's an error using this default to standard validation by string compare 131 | } 132 | if !registriesMatch && !p.settings.SkipRegistryValidation { 133 | return fmt.Errorf("registry values do not match .drone.yml: %s package.json: %s", p.settings.Registry, npm.Config.Registry) 134 | } 135 | 136 | p.settings.npm = npm 137 | return nil 138 | } 139 | 140 | // Execute provides the implementation of the plugin. 141 | func (p *Plugin) Execute() error { 142 | // Write the npmrc file 143 | if err := p.writeNpmrc(); err != nil { 144 | return fmt.Errorf("could not create npmrc: %w", err) 145 | } 146 | 147 | // Attempt authentication 148 | if err := p.authenticate(); err != nil { 149 | return fmt.Errorf("could not authenticate: %w", err) 150 | } 151 | 152 | // Determine whether to publish 153 | publish, err := p.shouldPublishPackage() 154 | 155 | if err != nil { 156 | return fmt.Errorf("could not determine if package should be published: %w", err) 157 | } 158 | 159 | if publish { 160 | logrus.Info("Publishing package") 161 | if err = runCommand(publishCommand(&p.settings), p.settings.Folder); err != nil { 162 | return fmt.Errorf("could not publish package: %w", err) 163 | } 164 | } else { 165 | logrus.Info("Not publishing package") 166 | } 167 | 168 | return nil 169 | } 170 | 171 | // / writeNpmrc creates a .npmrc in the folder for authentication 172 | func (p *Plugin) writeNpmrc() error { 173 | var f func(settings *Settings) string 174 | if p.settings.Token == "" { 175 | logrus.WithFields(logrus.Fields{ 176 | "username": p.settings.Username, 177 | "email": p.settings.Email, 178 | }).Info("Specified credentials") 179 | f = npmrcContentsUsernamePassword 180 | } else { 181 | logrus.Info("Token credentials being used") 182 | f = npmrcContentsToken 183 | } 184 | 185 | // write npmrc file 186 | home := "/root" 187 | currentUser, err := user.Current() 188 | if err == nil { 189 | home = currentUser.HomeDir 190 | } 191 | npmrcPath := path.Join(home, ".npmrc") 192 | 193 | logrus.WithField("path", npmrcPath).Info("Writing npmrc") 194 | 195 | return os.WriteFile(npmrcPath, []byte(f(&p.settings)), 0644) //nolint:gomnd 196 | } 197 | 198 | // / shouldPublishPackage determines if the package should be published 199 | func (p *Plugin) shouldPublishPackage() (bool, error) { 200 | cmd := packageVersionsCommand(p.settings.npm.Name) 201 | cmd.Dir = p.settings.Folder 202 | 203 | trace(cmd) 204 | out, err := cmd.CombinedOutput() 205 | 206 | // see if there was an error 207 | // if there is an error its likely due to the package never being published 208 | if err == nil { 209 | // parse the json output 210 | var versions []string 211 | err = json.Unmarshal(out, &versions) 212 | 213 | if err != nil { 214 | logrus.Debug("Could not parse into array of string. Likely single value") 215 | 216 | var version string 217 | err := json.Unmarshal(out, &version) 218 | 219 | if err != nil { 220 | return false, err 221 | } 222 | 223 | versions = append(versions, version) 224 | } 225 | 226 | for _, value := range versions { 227 | logrus.WithField("version", value).Debug("Found version of package") 228 | 229 | if p.settings.npm.Version == value { 230 | logrus.Info("Version found in the registry") 231 | if p.settings.FailOnVersionConflict { 232 | return false, fmt.Errorf("cannot publish package due to version conflict") 233 | } 234 | return false, nil 235 | } 236 | } 237 | 238 | logrus.Info("Version not found in the registry") 239 | } else { 240 | logrus.Info("Name was not found in the registry") 241 | } 242 | 243 | return true, nil 244 | } 245 | 246 | // / authenticate atempts to authenticate with the NPM registry. 247 | func (p *Plugin) authenticate() error { 248 | var cmds []*exec.Cmd 249 | 250 | // Write the version command 251 | cmds = append(cmds, versionCommand()) 252 | 253 | // write registry command 254 | if p.settings.Registry != globalRegistry { 255 | cmds = append(cmds, registryCommand(p.settings.Registry)) 256 | } 257 | 258 | // Write skip verify command 259 | if p.network.SkipVerify { 260 | cmds = append(cmds, skipVerifyCommand()) 261 | } 262 | 263 | // Write whoami command to verify credentials 264 | if !p.settings.SkipWhoami { 265 | cmds = append(cmds, whoamiCommand()) 266 | } 267 | 268 | // Run commands 269 | err := runCommands(cmds, p.settings.Folder) 270 | 271 | if err != nil { 272 | return err 273 | } 274 | 275 | return nil 276 | } 277 | 278 | // / readPackageFile reads the package file at the given path. 279 | func readPackageFile(folder string) (*npmPackage, error) { 280 | // Verify package.json file exists 281 | packagePath := path.Join(folder, "package.json") 282 | info, err := os.Stat(packagePath) 283 | 284 | if os.IsNotExist(err) { 285 | return nil, fmt.Errorf("no package.json at %s: %w", packagePath, err) 286 | } 287 | if info.IsDir() { 288 | return nil, fmt.Errorf("the package.json at %s is a directory", packagePath) 289 | } 290 | 291 | // Read the file 292 | file, err := os.ReadFile(packagePath) 293 | if err != nil { 294 | return nil, fmt.Errorf("could not read package.json at %s: %w", packagePath, err) 295 | } 296 | 297 | // Unmarshal the json data 298 | npm := npmPackage{} 299 | err = json.Unmarshal(file, &npm) 300 | if err != nil { 301 | return nil, err 302 | } 303 | 304 | // Make sure values are present 305 | if npm.Name == "" { 306 | return nil, fmt.Errorf("no package name present") 307 | } 308 | if npm.Version == "" { 309 | return nil, fmt.Errorf("no package version present") 310 | } 311 | 312 | // Set the default registry 313 | if npm.Config.Registry == "" { 314 | npm.Config.Registry = globalRegistry 315 | } 316 | 317 | logrus.WithFields(logrus.Fields{ 318 | "name": npm.Name, 319 | "version": npm.Version, 320 | "path": packagePath, 321 | }).Info("Found package.json") 322 | 323 | return &npm, nil 324 | } 325 | 326 | // npmrcContentsUsernamePassword creates the contents from a username and 327 | // password 328 | func npmrcContentsUsernamePassword(config *Settings) string { 329 | // get the base64 encoded string 330 | authString := fmt.Sprintf("%s:%s", config.Username, config.Password) 331 | encoded := base64.StdEncoding.EncodeToString([]byte(authString)) 332 | 333 | // create the file contents 334 | return fmt.Sprintf("_auth = %s\nemail = %s", encoded, config.Email) 335 | } 336 | 337 | // / Writes npmrc contents when using a token 338 | func npmrcContentsToken(config *Settings) string { 339 | registry, _ := url.Parse(config.Registry) 340 | registry.Scheme = "" // Reset the scheme to empty. This makes it so we will get a protocol relative URL. 341 | host, port, _ := net.SplitHostPort(registry.Host) 342 | if port == "80" || port == "443" { 343 | registry.Host = host // Remove standard ports as they're not supported in authToken since NPM 7. 344 | } 345 | registryString := registry.String() 346 | 347 | if !strings.HasSuffix(registryString, "/") { 348 | registryString += "/" 349 | } 350 | return fmt.Sprintf("%s:_authToken=%s", registryString, config.Token) 351 | } 352 | 353 | // versionCommand gets the npm version 354 | func versionCommand() *exec.Cmd { 355 | return exec.Command("npm", "--version") 356 | } 357 | 358 | // registryCommand sets the NPM registry. 359 | func registryCommand(registry string) *exec.Cmd { 360 | return exec.Command("npm", "config", "set", "registry", registry) 361 | } 362 | 363 | // skipVerifyCommand disables ssl verification. 364 | func skipVerifyCommand() *exec.Cmd { 365 | return exec.Command("npm", "config", "set", "strict-ssl", "false") 366 | } 367 | 368 | // whoamiCommand creates a command that gets the currently logged in user. 369 | func whoamiCommand() *exec.Cmd { 370 | return exec.Command("npm", "whoami") 371 | } 372 | 373 | // packageVersionsCommand gets the versions of the npm package. 374 | func packageVersionsCommand(name string) *exec.Cmd { 375 | return exec.Command("npm", "view", name, "versions", "--json") 376 | } 377 | 378 | // publishCommand runs the publish command 379 | func publishCommand(settings *Settings) *exec.Cmd { 380 | commandArgs := []string{"publish"} 381 | 382 | if settings.Tag != "" { 383 | commandArgs = append(commandArgs, "--tag", settings.Tag) 384 | } 385 | 386 | if settings.Access != "" { 387 | commandArgs = append(commandArgs, "--access", settings.Access) 388 | } 389 | 390 | return exec.Command("npm", commandArgs...) 391 | } 392 | 393 | // trace writes each command to standard error (preceded by a ‘$ ’) before it 394 | // is executed. Used for debugging your build. 395 | func trace(cmd *exec.Cmd) { 396 | fmt.Fprintf(os.Stdout, "+ %s\n", strings.Join(cmd.Args, " ")) 397 | } 398 | 399 | // runCommands executes the list of cmds in the given directory. 400 | func runCommands(cmds []*exec.Cmd, dir string) error { 401 | for _, cmd := range cmds { 402 | err := runCommand(cmd, dir) 403 | 404 | if err != nil { 405 | return err 406 | } 407 | } 408 | 409 | return nil 410 | } 411 | 412 | func runCommand(cmd *exec.Cmd, dir string) error { 413 | cmd.Stdout = os.Stdout 414 | cmd.Stderr = os.Stderr 415 | cmd.Dir = dir 416 | trace(cmd) 417 | 418 | return cmd.Run() 419 | } 420 | -------------------------------------------------------------------------------- /plugin/impl_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020, the Drone Plugins project authors. 2 | // Please see the AUTHORS file for details. All rights reserved. 3 | // Use of this source code is governed by an Apache 2.0 license that can be 4 | // found in the LICENSE file. 5 | 6 | package plugin 7 | 8 | import ( 9 | "context" 10 | "net/url" 11 | "testing" 12 | 13 | "github.com/drone-plugins/drone-plugin-lib/drone" 14 | "github.com/stretchr/testify/assert" 15 | ) 16 | 17 | const testWithPort = "__testwithport__" 18 | 19 | func initFakeSettings() Settings { 20 | nc := npmConfig{ 21 | // Note: this registry is the one that would come from publishConfig in package.json 22 | Registry: "SetByFn_readPackageFile", 23 | } 24 | np := npmPackage{ 25 | Name: "Test Package", 26 | Version: "1.33.7", 27 | Config: nc, 28 | } 29 | return Settings{ 30 | Username: "fakeUser", 31 | Password: "fakePass", 32 | Token: "", 33 | SkipWhoami: false, 34 | Email: "fake@user.tst", 35 | // Note: this registry is the one that would come from drone yaml 36 | Registry: "https://fakenpm.reg.org/good/path", 37 | Folder: "__test__", 38 | FailOnVersionConflict: true, 39 | Tag: "", 40 | Access: "", 41 | SkipRegistryValidation: false, 42 | npm: &np, 43 | } 44 | } 45 | 46 | func initFakeNetwork() drone.Network { 47 | return drone.Network{ 48 | SkipVerify: true, 49 | Client: nil, 50 | Context: context.TODO(), 51 | } 52 | } 53 | 54 | func initFakePipeline() drone.Pipeline { 55 | return drone.Pipeline{ 56 | Build: drone.Build{}, 57 | Repo: drone.Repo{}, 58 | Commit: drone.Commit{}, 59 | Stage: drone.Stage{}, 60 | Step: drone.Step{}, 61 | SemVer: drone.SemVer{}, 62 | CalVer: drone.CalVer{}, 63 | System: drone.System{}, 64 | } 65 | } 66 | 67 | func initPlugin() *Plugin { 68 | return &Plugin{ 69 | settings: initFakeSettings(), 70 | pipeline: initFakePipeline(), 71 | network: initFakeNetwork(), 72 | } 73 | } 74 | 75 | func getParsedURI(s string) *url.URL { 76 | rslt, _ := url.Parse(s) 77 | return rslt 78 | } 79 | 80 | func TestIsDefaultOrNilPort(t *testing.T) { 81 | p := initPlugin() 82 | 83 | resultWithoutPort := isNilPortOrStandardSchemePort(getParsedURI(p.settings.Registry)) 84 | assert.Equal(t, true, resultWithoutPort) 85 | 86 | p.settings.Registry = "https://fakenpm.reg.org:443" 87 | resultWithPort := isNilPortOrStandardSchemePort(getParsedURI(p.settings.Registry)) 88 | assert.Equal(t, true, resultWithPort) 89 | 90 | p.settings.Registry = "http://fakenpm.reg.org:80" 91 | resultWithPortHTTP := isNilPortOrStandardSchemePort(getParsedURI(p.settings.Registry)) 92 | assert.Equal(t, true, resultWithPortHTTP) 93 | 94 | p.settings.Registry = "fakenpm.reg.org" 95 | resultWithoutSchemeOrPort := isNilPortOrStandardSchemePort(getParsedURI(p.settings.Registry)) 96 | // npm requires scheme to be part of the url; so this function will return false for any missing a scheme 97 | assert.Equal(t, false, resultWithoutSchemeOrPort) 98 | 99 | p.settings.Registry = "fakenpm.reg.org:80" 100 | resultWithoutScheme := isNilPortOrStandardSchemePort(getParsedURI(p.settings.Registry)) 101 | assert.Equal(t, false, resultWithoutScheme) 102 | 103 | p.settings.Registry = "https://fakenpm.reg.org:8443" 104 | resultWithNonStandardPort := isNilPortOrStandardSchemePort(getParsedURI(p.settings.Registry)) 105 | assert.Equal(t, false, resultWithNonStandardPort) 106 | 107 | p.settings.Registry = "https://fakenpm.reg.org:8080" 108 | resultWithNonStandardPortHTTP := isNilPortOrStandardSchemePort(getParsedURI(p.settings.Registry)) 109 | assert.Equal(t, false, resultWithNonStandardPortHTTP) 110 | } 111 | 112 | func TestCompareRegistries(t *testing.T) { 113 | p := initPlugin() 114 | goodReg := "https://fakenpm.reg.org/good/path" 115 | goodRegWithPort := "https://fakenpm.reg.org:443/good/path" 116 | goodRegWithNonStandardPort := "https://fakenpm.reg.org:8443/good/path" 117 | 118 | p.settings.Registry = goodReg 119 | p.settings.npm.Config.Registry = goodReg 120 | validNoPorts, _ := p.CompareRegistries(p.settings.npm.Config) 121 | assert.Equal(t, true, validNoPorts) 122 | 123 | p.settings.Registry = goodRegWithPort 124 | sameURLOneWithPort, _ := p.CompareRegistries(p.settings.npm.Config) 125 | assert.Equal(t, true, sameURLOneWithPort) 126 | 127 | p.settings.Registry = goodRegWithPort 128 | p.settings.npm.Config.Registry = goodRegWithPort 129 | sameURLBothWithPort, _ := p.CompareRegistries(p.settings.npm.Config) 130 | assert.Equal(t, true, sameURLBothWithPort) 131 | 132 | p.settings.Registry = "invalidUri" 133 | invalidURITest, _ := p.CompareRegistries(p.settings.npm.Config) 134 | assert.Equal(t, false, invalidURITest) 135 | 136 | p.settings.Registry = goodRegWithNonStandardPort 137 | nonStandardPortTest, _ := p.CompareRegistries(p.settings.npm.Config) 138 | assert.Equal(t, false, nonStandardPortTest) 139 | } 140 | 141 | func TestValidateWithInvalidFields(t *testing.T) { 142 | p := initPlugin() 143 | // Validation tests with fields missing 144 | p.settings.Email = "" 145 | noEmailErr := p.Validate() 146 | if assert.NotNil(t, noEmailErr) { 147 | assert.Contains(t, noEmailErr.Error(), "email") 148 | } 149 | 150 | p.settings.Email = "fakeemail" 151 | p.settings.Username = "" 152 | noUserErr := p.Validate() 153 | if assert.NotNil(t, noUserErr) { 154 | assert.Contains(t, noUserErr.Error(), "username") 155 | } 156 | 157 | p.settings.Username = "fakeuser" 158 | p.settings.Password = "" 159 | noPassErr := p.Validate() 160 | if assert.NotNil(t, noPassErr) { 161 | assert.Contains(t, noPassErr.Error(), "password") 162 | } 163 | 164 | p.settings.Token = "fakeToken" 165 | p.settings.Password = "" 166 | p.settings.Username = "" 167 | p.settings.Email = "" 168 | tokenErr := p.Validate() 169 | assert.Nil(t, tokenErr) 170 | } 171 | 172 | func TestValidateWithRegistryVariations(t *testing.T) { 173 | p := initPlugin() 174 | 175 | // Validation tests with an invalid registry 176 | p.settings.Registry = "fakenpm.reg.org/good/path" 177 | missingSchemeErr := p.Validate() 178 | if assert.NotNil(t, missingSchemeErr) { 179 | assert.Contains(t, missingSchemeErr.Error(), "fakenpm.reg.org") 180 | } 181 | 182 | p.settings.Registry = "https://fakenpm.reg.org:7894/good/path" 183 | weirdPortErr := p.Validate() 184 | if assert.NotNil(t, weirdPortErr) { 185 | assert.Contains(t, weirdPortErr.Error(), "7894") 186 | } 187 | 188 | // Validation tests with default/no ports defined 189 | p.settings.Registry = "https://fakenpm.reg.org:443/good/path" 190 | defaultPortErr := p.Validate() 191 | assert.Nil(t, defaultPortErr) 192 | 193 | // Validation tests with failure conditions on registry 194 | p.settings.Registry = "https://registry.npmjs.org/good/path" 195 | diffRegistry := p.Validate() 196 | if assert.NotNil(t, diffRegistry) { 197 | assert.Contains(t, diffRegistry.Error(), "npmjs.org") 198 | } 199 | 200 | p.settings.Registry = "https://registry.npmjs.org:443/good/path" 201 | diffRegistryWithPort := p.Validate() 202 | if assert.NotNil(t, diffRegistryWithPort) { 203 | assert.Contains(t, diffRegistryWithPort.Error(), "npmjs.org:443") 204 | } 205 | 206 | // Validation failures with standard ports but different paths 207 | p.settings.Registry = "https://registry.npmjs.org:443/bad/path" 208 | p.settings.Folder = testWithPort 209 | diffRegistryWithPort = p.Validate() 210 | if assert.NotNil(t, diffRegistryWithPort) { 211 | assert.Contains(t, diffRegistryWithPort.Error(), "npmjs.org:443/bad") 212 | } 213 | 214 | // Same path different ports 215 | p.settings.Registry = "https://registry.npmjs.org:8443/good/path" 216 | p.settings.Folder = testWithPort 217 | diffRegistryWithPort = p.Validate() 218 | if assert.NotNil(t, diffRegistryWithPort) { 219 | assert.Contains(t, diffRegistryWithPort.Error(), "npmjs.org:8443/good") 220 | } 221 | 222 | // Same path different ports and schemes 223 | p.settings.Registry = "http://registry.npmjs.org:80/good/path" 224 | p.settings.Folder = testWithPort 225 | diffRegistryWithPort = p.Validate() 226 | if assert.NotNil(t, diffRegistryWithPort) { 227 | assert.Contains(t, diffRegistryWithPort.Error(), "npmjs.org:80/good") 228 | } 229 | 230 | // Validation tests with SkipRegistryValidation 231 | p.settings.SkipRegistryValidation = true 232 | p.settings.Registry = "fakenpm.reg.org/good/path" 233 | skipMissingSchemeErr := p.Validate() 234 | assert.Nil(t, skipMissingSchemeErr) 235 | 236 | p.settings.SkipRegistryValidation = true 237 | p.settings.Registry = "https://fakenpm.reg.org:7894/good/path" 238 | skipWeirdPortErr := p.Validate() 239 | assert.Nil(t, skipWeirdPortErr) 240 | } 241 | 242 | func TestExecute(t *testing.T) { 243 | t.Skip() 244 | } 245 | -------------------------------------------------------------------------------- /plugin/plugin.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020, the Drone Plugins project authors. 2 | // Please see the AUTHORS file for details. All rights reserved. 3 | // Use of this source code is governed by an Apache 2.0 license that can be 4 | // found in the LICENSE file. 5 | 6 | package plugin 7 | 8 | import ( 9 | "github.com/drone-plugins/drone-plugin-lib/drone" 10 | ) 11 | 12 | // Plugin implements drone.Plugin to provide the plugin implementation. 13 | type Plugin struct { 14 | settings Settings 15 | pipeline drone.Pipeline 16 | network drone.Network 17 | } 18 | 19 | // New initializes a plugin from the given Settings, Pipeline, and Network. 20 | // 21 | //nolint:gocritic 22 | func New(settings Settings, pipeline drone.Pipeline, network drone.Network) drone.Plugin { 23 | return &Plugin{ 24 | settings: settings, 25 | pipeline: pipeline, 26 | network: network, 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /plugin/plugin_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020, the Drone Plugins project authors. 2 | // Please see the AUTHORS file for details. All rights reserved. 3 | // Use of this source code is governed by an Apache 2.0 license that can be 4 | // found in the LICENSE file. 5 | 6 | package plugin 7 | 8 | import ( 9 | "testing" 10 | ) 11 | 12 | func TestTokenRCContents(t *testing.T) { 13 | settings := Settings{ 14 | Registry: "https://npm.someorg.com/", 15 | Token: "token", 16 | } 17 | actual := npmrcContentsToken(&settings) 18 | expected := "//npm.someorg.com/:_authToken=token" 19 | if actual != expected { 20 | t.Errorf("Unexpected token settings (Got: %s, Expected: %s)", actual, expected) 21 | } 22 | 23 | settings.Registry = "https://npm.someorg.com/with/path/" 24 | actual = npmrcContentsToken(&settings) 25 | expected = "//npm.someorg.com/with/path/:_authToken=token" 26 | if actual != expected { 27 | t.Errorf("Unexpected token settings (Got: %s, Expected: %s)", actual, expected) 28 | } 29 | 30 | settings.Registry = globalRegistry 31 | actual = npmrcContentsToken(&settings) 32 | expected = "//registry.npmjs.org/:_authToken=token" 33 | if actual != expected { 34 | t.Errorf("Unexpected token settings (Got: %s, Expected: %s)", actual, expected) 35 | } 36 | 37 | settings.Registry = "https://npm.someorg.com" 38 | actual = npmrcContentsToken(&settings) 39 | expected = "//npm.someorg.com/:_authToken=token" 40 | if actual != expected { 41 | t.Errorf("Unexpected token settings (Got: %s, Expected: %s)", actual, expected) 42 | } 43 | 44 | settings.Registry = "https://npm.someorg.com/with/path" 45 | actual = npmrcContentsToken(&settings) 46 | expected = "//npm.someorg.com/with/path/:_authToken=token" 47 | if actual != expected { 48 | t.Errorf("Unexpected token settings (Got: %s, Expected: %s)", actual, expected) 49 | } 50 | } 51 | --------------------------------------------------------------------------------