Skip to content

Commit

Permalink
Merge branch 'main' into 1314-expose-gitlab-add-remove-labels
Browse files Browse the repository at this point in the history
  • Loading branch information
orta authored Mar 2, 2023
2 parents 3526bf7 + 89fabea commit 1b5bd85
Show file tree
Hide file tree
Showing 80 changed files with 517 additions and 446 deletions.
7 changes: 5 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
<!-- Your comment below this -->

- Feature: Expose addLabels, removeLabels via gitlab.utils, @glensc #1353
- Fix remote dangerfiles always parsing as JavaScript. TypeScript files should now work properly. - [@snowe2010]
- Add support for BitBucket Cloud Repository Access Token - [@thawankeane]

<!-- Your comment above this -->

Expand Down Expand Up @@ -1976,10 +1978,9 @@ Not usable for others, only stubs of classes etc. - [@orta]
[@hmschreiner]: https://github.com/hmschreiner
[@hongrich]: https://github.com/hongrich
[@igorbek]: https://github.com/igorbek
[@ivankatliarchuk]: https://github.com/ivankatliarchuk
[@iljadaderko]: https://github.com/IljaDaderko
[@ivankatliarchuk]: https://github.com/ivankatliarchuk
[@imorente]: https://github.com/imorente
[@ivankatliarchuk]: https://github.com/ivankatliarchuk
[@jamiebuilds]: https://github.com/jamiebuilds
[@jamime]: https://github.com/jamime
[@joarwilk]: https://github.com/joarwilk
Expand Down Expand Up @@ -2031,6 +2032,7 @@ Not usable for others, only stubs of classes etc. - [@orta]
[@sgtcoolguy]: https://github.com/sgtcoolguy
[@sharkysharks]: https://github.com/sharkysharks
[@shyim]: https://github.com/shyim
[@snowe2010]: https://github.com/snowe2010
[@sogame]: https://github.com/sogame
[@soyn]: https://github.com/Soyn
[@stefanbuck]: https://github.com/stefanbuck
Expand All @@ -2041,6 +2043,7 @@ Not usable for others, only stubs of classes etc. - [@orta]
[@thii]: https://github.com/thii
[@tibdex]: https://github.com/tibdex
[@tim3trick]: https://github.com/tim3trick
[@thawankeane]: https://github.com/thawankeane
[@tychota]: https://github.com/tychota
[@urkle]: https://github.com/urkle
[@valscion]: https://github.com/valscion
Expand Down
26 changes: 18 additions & 8 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
FROM node:14-slim
FROM node:14-slim as build

LABEL maintainer="Orta Therox"
LABEL "com.github.actions.name"="Danger JS Action"
LABEL "com.github.actions.description"="Runs JavaScript/TypeScript Dangerfiles"
LABEL "com.github.actions.icon"="zap"
LABEL "com.github.actions.color"="blue"

RUN mkdir -p /usr/src/danger
COPY . /usr/src/danger
RUN cd /usr/src/danger && \
yarn && \
yarn run build:fast && \
chmod +x distribution/commands/danger.js && \
ln -s $(pwd)/distribution/commands/danger.js /usr/bin/danger
WORKDIR /usr/src/danger
COPY package.json yarn.lock ./
RUN yarn install
COPY . .
RUN yarn run build:fast
RUN yarn remove 'typescript' --dev && yarn add 'typescript'
RUN yarn install --production --frozen-lockfile
RUN chmod +x distribution/commands/danger.js


FROM node:14-slim
WORKDIR /usr/src/danger
ENV PATH="/usr/src/danger/node_modules/.bin:$PATH"
COPY package.json ./
COPY --from=build /usr/src/danger/distribution ./dist
COPY --from=build /usr/src/danger/node_modules ./node_modules
RUN ln -s /usr/src/danger/dist/commands/danger.js /usr/bin/danger

ENTRYPOINT ["danger", "ci"]
4 changes: 2 additions & 2 deletions dangerfile.lite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ const sentence = danger.utils.sentence

import { realProviders } from "./source/ci_source/providers"
const readme = fs.readFileSync("README.md").toString()
const names = realProviders.map(p => new p({}).name)
const missing = names.filter(n => !readme.includes(n))
const names = realProviders.map((p) => new p({}).name)
const missing = names.filter((n) => !readme.includes(n))
if (missing.length) {
warn(`These providers are missing from the README: ${sentence(missing)}`)
}
4 changes: 4 additions & 0 deletions docs/guides/the_dangerfile.html.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ export DANGER_BITBUCKETCLOUD_PASSWORD='yyyy'
# You can get OAuth key from Settings > OAuth > Add consumer, put `https://bitbucket.org/site/oauth2/authorize` for `Callback URL`, and enable Read Pull requests, and Read Account Permissions.
export DANGER_BITBUCKETCLOUD_OAUTH_KEY='xxxx'
export DANGER_BITBUCKETCLOUD_OAUTH_SECRET='yyyy'

# or for BitBucket Cloud by Repository Access Token
# You can get a Repository Access Token from Repo Settings > Security > Acesss Tokens and set Pull requests write scope.
export DANGER_BITBUCKETCLOUD_REPO_ACCESSTOKEN='xxxx'
```

Then the danger CLI will use authenticated API calls, which don't get this by API limits.
Expand Down
4 changes: 2 additions & 2 deletions docs/tutorials/dependencies.html.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,10 @@ So for example with a diff of `package.json` where spaced-between is added:

```js
{
dependencies {
dependencies: {
added: ["chalk"],
removed: [],
after: { commander: "^2.9.0", debug: "^2.6.0", spaced-between: "^1.1.1", typescript: "^2.2.1" },
after: { commander: "^2.9.0", debug: "^2.6.0", "spaced-between": "^1.1.1", typescript: "^2.2.1" },
before: { commander: "^2.9.0", debug: "^2.6.0", typescript: "^2.2.1" },
}
}
Expand Down
9 changes: 8 additions & 1 deletion docs/usage/bitbucket_cloud.html.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ blurb: An overview of using Danger with BitBucket Cloud, and some examples
To use Danger JS with BitBucket Cloud: you'll need to create a new account for Danger to use, then set the following
environment variables on your CI:

You could use either username with password or OAuth key with OAuth secret.
You could use either username with password, OAuth key with OAuth secret or repository access token.

For username and password, you need to set.

Expand All @@ -30,6 +30,13 @@ For OAuth key and OAuth secret, you can get them from.
- `DANGER_BITBUCKETCLOUD_OAUTH_SECRET` = The consumer secret for the account used to comment, as show as `Secret` on the
website.

For [repository access token](https://support.atlassian.com/bitbucket-cloud/docs/repository-access-tokens/), what you
need to create one is:

- Open your repository URL
- Navigate to Settings > Security > Access Tokens > Create Repository Access Token
- Give it a name and set Pull requests write scope

Then in your Dangerfiles you will have a fully fleshed out `danger.bitbucket_cloud` object to work with. For example:

```ts
Expand Down
8 changes: 6 additions & 2 deletions source/ci_source/ci_source_helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
BitBucketServerAPI,
bitbucketServerRepoCredentialsFromEnv,
} from "../platforms/bitbucket_server/BitBucketServerAPI"
import { RepoMetaData } from "../dsl/BitBucketServerDSL"
import { RepoMetaData } from "../dsl/RepoMetaData"
import { BitBucketCloudAPI, bitbucketCloudCredentialsFromEnv } from "../platforms/bitbucket_cloud/BitBucketCloudAPI"

/**
Expand Down Expand Up @@ -45,7 +45,11 @@ export async function getPullRequestIDForBranch(metadata: RepoMetaData, env: Env
}
return 0
}
if (process.env["DANGER_BITBUCKETCLOUD_OAUTH_KEY"] || process.env["DANGER_BITBUCKETCLOUD_USERNAME"]) {
if (
process.env["DANGER_BITBUCKETCLOUD_OAUTH_KEY"] ||
process.env["DANGER_BITBUCKETCLOUD_USERNAME"] ||
process.env["DANGER_BITBUCKETCLOUD_REPO_ACCESSTOKEN"]
) {
const api = new BitBucketCloudAPI(metadata, bitbucketCloudCredentialsFromEnv(env))
const prs = await api.getPullRequestsFromBranch(branch)
if (prs.length) {
Expand Down
4 changes: 2 additions & 2 deletions source/ci_source/get_ci_source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { Env, CISource } from "./ci_source"
* @returns {?CISource} a CI source if it's OK, otherwise Danger can't run.
*/
export function getCISourceForEnv(env: Env): CISource | undefined {
const availableProviders = [...(providers as any)].map(Provider => new Provider(env)).filter(x => x.isCI)
const availableProviders = [...(providers as any)].map((Provider) => new Provider(env)).filter((x) => x.isCI)
return availableProviders && availableProviders.length > 0 ? availableProviders[0] : undefined
}

Expand All @@ -24,7 +24,7 @@ export function getCISourceForEnv(env: Env): CISource | undefined {
*/
export async function getCISourceForExternal(env: Env, modulePath: string): Promise<CISource | undefined> {
const path = resolve(process.cwd(), modulePath)
return new Promise<CISource | undefined>(resolve => {
return new Promise<CISource | undefined>((resolve) => {
fs.stat(path, (error, stat) => {
if (error) {
console.error(`could not load CI provider at ${modulePath} due to ${error}`)
Expand Down
5 changes: 3 additions & 2 deletions source/ci_source/providers/BitbucketPipelines.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ import { ensureEnvKeysExist, ensureEnvKeysAreInt } from "../ci_source_helpers"
*
* ### Token Setup
*
* You can either add `DANGER_BITBUCKETCLOUD_USERNAME`, `DANGER_BITBUCKETCLOUD_PASSWORD`
* or add `DANGER_BITBUCKETCLOUD_OAUTH_KEY`, `DANGER_BITBUCKETCLOUD_OAUTH_SECRET`
* You can add `DANGER_BITBUCKETCLOUD_USERNAME` and `DANGER_BITBUCKETCLOUD_PASSWORD`
* or add `DANGER_BITBUCKETCLOUD_OAUTH_KEY` and `DANGER_BITBUCKETCLOUD_OAUTH_SECRET`
* or add `DANGER_BITBUCKETCLOUD_REPO_ACCESSTOKEN`
* -
*/

Expand Down
3 changes: 1 addition & 2 deletions source/ci_source/providers/Jenkins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ export class Jenkins implements CISource {
const isGitHubPR =
ensureEnvKeysExist(this.env, ["ghprbPullId", "ghprbGhRepository"]) &&
ensureEnvKeysAreInt(this.env, ["ghprbPullId"])
const isGitLabMR =
ensureEnvKeysExist(this.env, ["gitlabMergeRequestIid", "gitlabMergeRequestId"])
const isGitLabMR = ensureEnvKeysExist(this.env, ["gitlabMergeRequestIid", "gitlabMergeRequestId"])
const isMultiBranchPR =
ensureEnvKeysExist(this.env, ["CHANGE_ID", "CHANGE_URL"]) && ensureEnvKeysAreInt(this.env, ["CHANGE_ID"])

Expand Down
7 changes: 2 additions & 5 deletions source/ci_source/providers/XcodeCloud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,15 @@ import { ensureEnvKeysExist } from "../ci_source_helpers"
* See the Xcode Cloud documentation [here](https://developer.apple.com/documentation/xcode/xcode-cloud-workflow-reference#Custom-Environment-Variables)
*/
export class XcodeCloud implements CISource {
constructor(private readonly env: Env) { }
constructor(private readonly env: Env) {}

get name(): string {
return "Xcode Cloud"
}

get isCI(): boolean {
const mustHave = ["CI", "CI_XCODEBUILD_ACTION"]
return (
ensureEnvKeysExist(this.env, mustHave) &&
this.env.CI == "TRUE"
)
return ensureEnvKeysExist(this.env, mustHave) && this.env.CI == "TRUE"
}

get isPR(): boolean {
Expand Down
10 changes: 5 additions & 5 deletions source/ci_source/providers/_tests/_jenkins.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ const envs = {
const types = Object.keys(envs)

describe("being found when looking for CI", () => {
it.each(types)("%s - finds Jenkins with the right ENV", type => {
it.each(types)("%s - finds Jenkins with the right ENV", (type) => {
const env = envs[type]
const ci = getCISourceForEnv(env)
expect(ci).toBeInstanceOf(Jenkins)
})
})

describe(".isCI", () => {
it.each(types)("%s - validates when JENKINS_URL is present in environment", type => {
it.each(types)("%s - validates when JENKINS_URL is present in environment", (type) => {
const jenkins = new Jenkins(envs[type])
expect(jenkins.isCI).toBeTruthy()
})
Expand All @@ -42,7 +42,7 @@ describe(".isCI", () => {
})

describe(".isPR", () => {
it.each(types)("%s - validates when all Jenkins environment variables are set", type => {
it.each(types)("%s - validates when all Jenkins environment variables are set", (type) => {
const jenkins = new Jenkins(envs[type])
expect(jenkins.isPR).toBeTruthy()
})
Expand All @@ -52,7 +52,7 @@ describe(".isPR", () => {
expect(jenkins.isPR).toBeFalsy()
})

describe.each(types)("%s", type => {
describe.each(types)("%s", (type) => {
const envVars = Object.keys(envs[type])
envVars.forEach((key: string) => {
const env = {
Expand Down Expand Up @@ -87,7 +87,7 @@ describe(".isPR", () => {
})

describe(".pullRequestID", () => {
it.each(types)("%s - pulls it out of environment", type => {
it.each(types)("%s - pulls it out of environment", (type) => {
const jenkins = new Jenkins(envs[type])
expect(jenkins.pullRequestID).toEqual("50")
})
Expand Down
2 changes: 1 addition & 1 deletion source/commands/danger-ci.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ program

setSharedArgs(program).parse(process.argv)

const app = (program as any) as SharedCLI
const app = program as any as SharedCLI
runRunner(app)
4 changes: 2 additions & 2 deletions source/commands/danger-local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ program
.allowUnknownOption(true)
setSharedArgs(program).parse(process.argv)

const app = (program as any) as App
const app = program as any as App
const base = app.base

const localPlatform = new LocalGit({ base, staging: app.staging })
localPlatform.validateThereAreChanges().then(changes => {
localPlatform.validateThereAreChanges().then((changes) => {
if (changes) {
const fakeSource = new FakeCI(process.env)
// By setting the custom env var we can be sure that the runner doesn't
Expand Down
11 changes: 5 additions & 6 deletions source/commands/danger-pr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import prettyjson from "prettyjson"
import { FakeCI } from "../ci_source/providers/Fake"
import { pullRequestParser } from "../platforms/pullRequestParser"
import { dangerfilePath } from "./utils/fileUtils"
import validateDangerfileExists from "./utils/validateDangerfileExists"
import setSharedArgs, { SharedCLI } from "./utils/sharedDangerfileArgs"
import { jsonDSLGenerator } from "../runner/dslGenerator"
import { prepareDangerDSL } from "./utils/runDangerSubprocess"
Expand Down Expand Up @@ -43,12 +42,13 @@ program
!process.env["DANGER_BITBUCKETSERVER_HOST"] &&
!process.env["DANGER_BITBUCKETCLOUD_OAUTH_KEY"] &&
!process.env["DANGER_BITBUCKETCLOUD_USERNAME"] &&
!process.env["DANGER_BITBUCKETCLOUD_REPO_ACCESSTOKEN"] &&
!gitLabApiCredentials.token &&
!gitLabApiCredentials.oauthToken
) {
log("")
log(
" You don't have a DANGER_GITHUB_API_TOKEN/DANGER_GITLAB_API_TOKEN/DANGER_GITLAB_API_OAUTH_TOKEN/DANGER_BITBUCKETCLOUD_OAUTH_KEY/DANGER_BITBUCKETCLOUD_USERNAME set up, this is optional, but TBH, you want to do this."
" You don't have a DANGER_GITHUB_API_TOKEN/DANGER_GITLAB_API_TOKEN/DANGER_GITLAB_API_OAUTH_TOKEN/DANGER_BITBUCKETCLOUD_OAUTH_KEY/DANGER_BITBUCKETCLOUD_USERNAME/DANGER_BITBUCKETCLOUD_REPO_ACCESSTOKEN set up, this is optional, but TBH, you want to do this."
)
log(" Check out: http://danger.systems/js/guides/the_dangerfile.html#working-on-your-dangerfile")
log("")
Expand All @@ -66,7 +66,7 @@ program

setSharedArgs(program).parse(process.argv)

const app = (program as any) as App
const app = program as any as App
const customProcess = !!app.process

if (program.args.length === 0) {
Expand All @@ -77,7 +77,7 @@ if (program.args.length === 0) {
process.env["DANGER_GITHUB_HOST"] || process.env["DANGER_BITBUCKETSERVER_HOST"] || gitLabApiCredentials.host // this defaults to https://gitlab.com

// Allow an ambiguous amount of args to find the PR reference
const findPR = program.args.find(a => a.includes(customHost) || a.includes("github") || a.includes("bitbucket.org"))
const findPR = program.args.find((a) => a.includes(customHost) || a.includes("github") || a.includes("bitbucket.org"))

if (!findPR) {
console.error(`Could not find an arg which mentioned GitHub, BitBucket Server, BitBucket Cloud, or GitLab.`)
Expand All @@ -94,8 +94,7 @@ if (program.args.length === 0) {
const isJSON = app.js || app.json
const note = isJSON ? console.error : console.log
note(`Starting Danger PR on ${pr.repo}#${pr.pullRequestNumber}`)

if (customProcess || isJSON || validateDangerfileExists(dangerfilePath(program))) {
if (customProcess || isJSON || dangerfilePath(program)) {
if (!customProcess) {
d(`executing dangerfile at ${dangerfilePath(program)}`)
}
Expand Down
6 changes: 3 additions & 3 deletions source/commands/danger-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ program
.allowUnknownOption(true)

setSharedArgs(program)
program.action(process_name => (subprocessName = process_name)).parse(process.argv)
program.action((process_name) => (subprocessName = process_name)).parse(process.argv)

// The dynamic nature of the program means typecasting a lot
// use this to work with dynamic properties
Expand All @@ -55,7 +55,7 @@ if (process.env["DANGER_VERBOSE"] || app.verbose) {
global.verbose = true
}

getRuntimeCISource(app).then(source => {
getRuntimeCISource(app).then((source) => {
// This does not set a failing exit code
if (source && !source.isPR) {
console.log("Skipping Danger due to this run not executing on a PR.")
Expand All @@ -73,7 +73,7 @@ getRuntimeCISource(app).then(source => {
}

if (platform) {
jsonDSLGenerator(platform, source, app).then(dangerJSONDSL => {
jsonDSLGenerator(platform, source, app).then((dangerJSONDSL) => {
if (!subprocessName) {
// Just pipe it out to the CLI
const processInput = prepareDangerDSL(dangerJSONDSL)
Expand Down
2 changes: 1 addition & 1 deletion source/commands/danger-reset-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ import { runRunner } from "./ci/resetStatus"
program.usage("[options]").description("Reset the status of a GitHub PR to pending.")
setSharedArgs(program).parse(process.argv)

const app = (program as any) as SharedCLI
const app = program as any as SharedCLI
runRunner(app)
2 changes: 1 addition & 1 deletion source/commands/danger-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const run = (config: SharedCLI) => async (jsonString: string) => {
if (platform.executeRuntimeEnvironment) {
await platform.executeRuntimeEnvironment(inline.runDangerfileEnvironment, dangerFile, runtimeEnv)
} else {
await inline.runDangerfileEnvironment([dangerFile], [undefined], runtimeEnv)
await inline.runDangerfileEnvironment([[dangerFile, false]], [undefined], runtimeEnv)
}
}

Expand Down
2 changes: 1 addition & 1 deletion source/commands/danger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import program from "commander"
import chalk from "chalk"
import { version } from "../../package.json"

process.on("unhandledRejection", function(reason: string, _p: any) {
process.on("unhandledRejection", function (reason: string, _p: any) {
console.log(chalk.red("Error: "), reason)
process.exitCode = 1
})
Expand Down
2 changes: 1 addition & 1 deletion source/commands/init/default-dangerfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const generateDefaultDangerfile = (state: InitState) => {

if (dangerfileState.hasSeparateTestFolder || dangerfileState.hasJest) {
const tests = dangerfileState.hasJest ? "__tests__" : "tests"
const source = ["src", "source", "lib"].filter(path => fs.existsSync(path))
const source = ["src", "source", "lib"].filter((path) => fs.existsSync(path))
if (source[0]) {
rules.push(checkSeparateTestsFolder(source[0], tests))
}
Expand Down
Loading

0 comments on commit 1b5bd85

Please sign in to comment.