import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import * as yaml from 'js-yaml'
import {fileURLToPath} from 'url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
function updateUsage(
actionReference: string,
actionYamlPath = 'action.yml',
readmePath = 'README.md',
startToken = '<!-- start usage -->',
endToken = '<!-- end usage -->'
): void {
if (!actionReference) {
throw new Error('Parameter actionReference must not be empty')
}
const actionYaml = yaml.load(fs.readFileSync(actionYamlPath).toString())
const originalReadme = fs.readFileSync(readmePath).toString()
const startTokenIndex = originalReadme.indexOf(startToken)
if (startTokenIndex < 0) {
throw new Error(`Start token '${startToken}' not found`)
}
const endTokenIndex = originalReadme.indexOf(endToken)
if (endTokenIndex < 0) {
throw new Error(`End token '${endToken}' not found`)
} else if (endTokenIndex < startTokenIndex) {
throw new Error('Start token must appear before end token')
}
const newReadme: string[] = []
newReadme.push(originalReadme.substr(0, startTokenIndex + startToken.length))
newReadme.push('```yaml', `- uses: ${actionReference}`, ' with:')
const inputs = actionYaml.inputs
let firstInput = true
for (const key of Object.keys(inputs)) {
const input = inputs[key]
if (!firstInput) {
newReadme.push('')
}
const width = 80
let description = (input.description as string)
.trimRight()
.replace(/\r\n/g, '\n')
.replace(/ +/g, ' ')
.replace(/ \n/g, '\n')
while (description) {
let segment: string = description
if (description.length > width) {
segment = description.substr(0, width + 1)
while (!segment.endsWith(' ') && !segment.endsWith('\n') && segment) {
segment = segment.substr(0, segment.length - 1)
}
if (segment.length < width * 0.67) {
segment = description
}
} else {
segment = description
}
const newlineIndex = segment.indexOf('\n')
if (newlineIndex >= 0) {
segment = segment.substr(0, newlineIndex + 1)
}
newReadme.push(` # ${segment}`.trimRight())
description = description.substr(segment.length)
}
if (input.default !== undefined) {
if ((input.description as string).trimRight().match(/\n[ ]*\r?\n/)) {
newReadme.push(` #`)
}
newReadme.push(` # Default: ${input.default}`)
}
newReadme.push(` ${key}: ''`)
firstInput = false
}
newReadme.push('```')
newReadme.push(originalReadme.substr(endTokenIndex))
fs.writeFileSync(readmePath, newReadme.join(os.EOL))
}
updateUsage(
'actions/checkout@v7',
path.join(__dirname, '..', '..', 'action.yml'),
path.join(__dirname, '..', '..', 'README.md')
)