Skip to content

Commit eaacc60

Browse files
authored
feat: add GitHub branch count badge (fixes #11283) (#11781)
1 parent 86ad28b commit eaacc60

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import gql from 'graphql-tag'
2+
import Joi from 'joi'
3+
import { pathParam } from '../index.js'
4+
import { metric } from '../text-formatters.js'
5+
import { nonNegativeInteger } from '../validators.js'
6+
import { GithubAuthV4Service } from './github-auth-service.js'
7+
import { transformErrors, documentation } from './github-helpers.js'
8+
9+
const schema = Joi.object({
10+
data: Joi.object({
11+
repository: Joi.object({
12+
refs: Joi.object({
13+
totalCount: nonNegativeInteger,
14+
}).required(),
15+
}).required(),
16+
}).required(),
17+
}).required()
18+
19+
export default class GithubBranchCount extends GithubAuthV4Service {
20+
static category = 'analysis'
21+
22+
static route = {
23+
base: 'github/branches',
24+
pattern: ':user/:repo',
25+
}
26+
27+
static openApi = {
28+
'/github/branches/{user}/{repo}': {
29+
get: {
30+
summary: 'GitHub branch count',
31+
description: documentation,
32+
parameters: [
33+
pathParam({ name: 'user', example: 'badges' }),
34+
pathParam({ name: 'repo', example: 'shields' }),
35+
],
36+
},
37+
},
38+
}
39+
40+
static defaultBadgeData = { label: 'branches', color: 'blue' }
41+
42+
static render({ count }) {
43+
return {
44+
label: 'branches',
45+
message: metric(count),
46+
color: 'blue',
47+
}
48+
}
49+
50+
async fetch({ user, repo }) {
51+
return this._requestGraphql({
52+
query: gql`
53+
query ($user: String!, $repo: String!) {
54+
repository(owner: $user, name: $repo) {
55+
refs(refPrefix: "refs/heads/", first: 1) {
56+
totalCount
57+
}
58+
}
59+
}
60+
`,
61+
variables: { user, repo },
62+
schema,
63+
transformErrors,
64+
})
65+
}
66+
67+
async handle({ user, repo }) {
68+
const json = await this.fetch({ user, repo })
69+
const count = json.data.repository.refs.totalCount
70+
return this.constructor.render({ count })
71+
}
72+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { isMetric } from '../test-validators.js'
2+
import { createServiceTester } from '../tester.js'
3+
4+
export const t = await createServiceTester()
5+
6+
t.create('branch count').get('/badges/shields.json').expectBadge({
7+
label: 'branches',
8+
message: isMetric,
9+
color: 'blue',
10+
})
11+
12+
t.create('repo not found')
13+
.get('/badges/shields-nonexistent-repo-xyz.json')
14+
.expectBadge({
15+
label: 'branches',
16+
message: 'repo not found',
17+
})

0 commit comments

Comments
 (0)