1 Commits

Author SHA1 Message Date
Simon Schneegans
ba92b7eb01 🔧 Try downgrading the node version 2023-11-14 05:28:19 +01:00
4 changed files with 127 additions and 58 deletions

View File

@@ -13,16 +13,32 @@ jobs:
- name: Get the Numbers
run: echo "ANSWER=42" >> $GITHUB_ENV
- name: Create the Badge
uses: https://hub.cybercinch.nz/cybercinch/dynamic-badges-action@master
uses: schneegans/dynamic-badges-action@master
with:
auth: ${{ secrets.BADGE_API_TOKEN }}
host: https://badges.cybercinch.nz/cybercinch/dynamic-badges-action/answer
auth: ${{ secrets.GIST_SECRET }}
gistID: 2ab8f1d386f13aaebccbd87dac94068d
filename: answer.json
label: The Answer
message: is ${{ env.ANSWER }}
valColorRange: ${{ env.ANSWER }}
maxColorRange: 100
minColorRange: 0
svg-badge:
name: Create SVG Badge
runs-on: ubuntu-latest
steps:
- name: Create the Badge
uses: schneegans/dynamic-badges-action@master
with:
auth: ${{ secrets.GIST_SECRET }}
gistID: 2ab8f1d386f13aaebccbd87dac94068d
filename: badge.svg
label: This is
message: an SVG badge
color: red
labelColor: blue
color-range-badges:
name: "Create Color Range Badges"
runs-on: ubuntu-latest
@@ -41,11 +57,18 @@ jobs:
- 90
- 100
steps:
- name: "Stagger"
run: |
# Gist returns 500 if we try to update many files in the same gist all at once.
# Thanks to Ned Batchelder for this idea!
# https://nedbatchelder.com/blog/202209/making_a_coverage_badge.html
sleep $( expr ${{ matrix.total }} / 10 )
- name: "Make badge"
uses: https://hub.cybercinch.nz/cybercinch/dynamic-badges-action@master
uses: schneegans/dynamic-badges-action@master
with:
auth: ${{ secrets.BADGE_API_TOKEN }}
host: https://badges.cybercinch.nz/cybercinch/dynamic-badges-action/color_badge_${{ matrix.total }}
auth: ${{ secrets.GIST_SECRET }}
gistID: 2ab8f1d386f13aaebccbd87dac94068d
filename: color_badge_${{ matrix.total }}.json
label: Coverage
message: ${{ matrix.total }}%
minColorRange: 50

View File

@@ -101,7 +101,7 @@ Embed the badge with:
| Parameter | Description | Supported in SVG Mode |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
| `host` | Default is `https://api.github.com/gists/`. You can change this if you're using GitHub enterprise. The URL will be something like `https://github-enterprise-hostname/api/v3/gists/`. | ✅ |
| `host` | Default is `https://api.github.com/gists/`. You can change this if you're using GitHub enterprise. The URL will be something like `github-enterprise-hostname/api/v3/gists`. | ✅ |
| `forceUpdate` | Default is `false`. If set to `true`, the gist will be updated even if the content did not change. | ✅ |
### Shields.io Parameters (optional)
@@ -175,10 +175,6 @@ For all values in between, the color will be interpolated.
minColorRange: 0
```
### Self-hosted runner compatibility
The current action is compatible with `node20` only. In order to use it with a self-hosted runner, you must use runner with `node20` installed. Your runner version must be equal or higher than [v2.308.0](https://github.com/actions/runner/releases/tag/v2.308.0).
## Contributing to Dynamic Badges Action
Whenever you encounter a :beetle: **bug** or have :tada: **feature request**,

View File

@@ -8,7 +8,13 @@ branding:
color: "green"
inputs:
auth:
description: "Your secret token"
description: "Your secret with the gist scope"
required: true
gistID:
description: "The ID of the gist to use"
required: true
filename:
description: "The *.json or *.svg filename of the badge data"
required: true
label:
description: "The left text of the badge"
@@ -17,9 +23,13 @@ inputs:
description: "The right text of the badge"
required: true
host:
description: "The base URL of the badgestor API"
default: "https://badges.mydomain.com/"
required: true
description: "The base URL of the gist API"
default: "https://api.github.com/gists/"
required: false
forceUpdate:
description: "If set to true, the gist will be updated even if the content did not change"
default: "false"
required: false
labelColor:
description: "The left color of the badge"
required: false
@@ -69,5 +79,5 @@ inputs:
description: "Lightness used by the color range feature. Defaults to 40."
required: false
runs:
using: "node20"
using: "node16"
main: "index.js"

124
index.js
View File

@@ -8,56 +8,36 @@
import core from "@actions/core";
import { makeBadge } from "badge-maker";
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const util = require('util');
const hostUrl = new URL(core.getInput("host"));
const gistUrl = new URL(core.getInput("gistID"), core.getInput("host"));
// This uses the method above to update a gist with the given data. The user agent is
// required as defined in https://developer.github.com/v3/#user-agent-required
async function updateBadge(body) {
async function updateGist(body) {
const headers = new Headers([
["Content-Type", "application/json"],
["Content-Length", new TextEncoder().encode(body).length],
["User-Agent", "gitea-dynamic-badges"],
["x-api-key", `${core.getInput("auth")}`],
["User-Agent", "Schneegans"],
["Authorization", `token ${core.getInput("auth")}`],
]);
console.log("Making post request to: %s", hostUrl);
const response = await fetch(hostUrl, {
const response = await fetch(gistUrl, {
method: "POST",
headers,
body,
});
if (!response.ok) {
console.log("Returned: %j", response.body);
if (response.status === 409) {
// This means likely the badge already exists. Try to patch
console.log("Running patch on %s", hostUrl);
const response2 = await fetch(hostUrl, {
method: 'PATCH',
headers,
body,
});
if (!response2.ok) {
core.setFailed(
`Failed to create gist, response status code: ${response.status} ${response.statusText}`
);
return;
}
}
core.setFailed(
`Failed to create gist, response status code: ${response.status} ${response.statusText}`
);
return;
}
console.log("Success!");
}
// We wrap the entire action in a try / catch block so we can set it to "failed" if
// something goes wrong.
try {
@@ -65,11 +45,16 @@ try {
// and message attributes are always required. All others are optional and added to the
// content object only if they are given to the action.
let data = {
schemaVersion: 1,
label: core.getInput("label"),
message: core.getInput("message"),
};
const filename = core.getInput("filename");
const isSvgFile = filename.endsWith(".svg");
if (!isSvgFile) {
data.schemaVersion = 1;
}
// Compute the message color based on the given inputs.
const color = core.getInput("color");
@@ -125,27 +110,27 @@ try {
data.labelColor = labelColor;
}
if (isError != "") {
if (!isSvgFile && isError != "") {
data.isError = isError;
}
if (namedLogo != "") {
if (!isSvgFile && namedLogo != "") {
data.namedLogo = namedLogo;
}
if (logoSvg != "") {
if (!isSvgFile && logoSvg != "") {
data.logoSvg = logoSvg;
}
if (logoColor != "") {
if (!isSvgFile && logoColor != "") {
data.logoColor = logoColor;
}
if (logoWidth != "") {
if (!isSvgFile && logoWidth != "") {
data.logoWidth = parseInt(logoWidth);
}
if (logoPosition != "") {
if (!isSvgFile && logoPosition != "") {
data.logoPosition = logoPosition;
}
@@ -153,18 +138,73 @@ try {
data.style = style;
}
if (cacheSeconds != "") {
if (!isSvgFile && cacheSeconds != "") {
data.cacheSeconds = parseInt(cacheSeconds);
}
let content = "";
content = JSON.stringify({ payload: data });
if (isSvgFile) {
content = makeBadge(data);
} else {
content = JSON.stringify(data);
}
console.log("Body of request: %s", content);
// For the POST request, the above content is set as file contents for the
// given filename.
const body = JSON.stringify({ files: { [filename]: { content } } });
updateBadge(content);
// If "forceUpdate" is set to true, we can simply update the gist. If not, we have to
// get the gist data and compare it to the new value before.
if (core.getBooleanInput("forceUpdate")) {
updateGist(body);
} else {
// Get the old gist.
fetch(gistUrl, {
method: "GET",
headers: new Headers([
["Content-Type", "application/json"],
["User-Agent", "Schneegans"],
["Authorization", `token ${core.getInput("auth")}`],
]),
})
.then((response) => {
if (!response.ok) {
return Promise.reject(
`Failed to get gist: ${response.status} ${response.statusText}`
);
}
return response.json();
})
.then((oldGist) => {
let shouldUpdate = true;
if (oldGist?.files?.[filename]) {
const oldContent = oldGist.files[filename].content;
if (oldContent === content) {
console.log(
`Content did not change, not updating gist at ${filename}.`
);
shouldUpdate = false;
}
}
if (shouldUpdate) {
if (oldGist?.files?.[filename]) {
console.log(`Content changed, updating gist at ${filename}.`);
} else {
console.log(`Content didn't exist, creating gist at ${filename}.`);
}
updateGist(body);
}
})
.catch((error) => {
core.setFailed(error);
});
}
} catch (error) {
core.setFailed(error);
}