- reformat source - lineLength 120

This commit is contained in:
Mike Penz
2022-07-29 13:48:53 +00:00
committed by GitHub
parent f0d418bd0c
commit b1ea770a88
12 changed files with 130 additions and 478 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
{
"printWidth": 80,
"printWidth": 120,
"tabWidth": 2,
"useTabs": false,
"semi": false,
Generated Vendored
+10 -34
View File
@@ -282,38 +282,20 @@ class GitCommandManager {
}
latestTag() {
return __awaiter(this, void 0, void 0, function* () {
const revListOutput = yield this.execGit([
'rev-list',
'--tags',
'--skip=0',
'--max-count=1'
]);
const output = yield this.execGit([
'describe',
'--abbrev=0',
'--tags',
revListOutput.stdout.trim()
]);
const revListOutput = yield this.execGit(['rev-list', '--tags', '--skip=0', '--max-count=1']);
const output = yield this.execGit(['describe', '--abbrev=0', '--tags', revListOutput.stdout.trim()]);
return output.stdout.trim();
});
}
initialCommit() {
return __awaiter(this, void 0, void 0, function* () {
const revListOutput = yield this.execGit([
'rev-list',
'--max-parents=0',
'HEAD'
]);
const revListOutput = yield this.execGit(['rev-list', '--max-parents=0', 'HEAD']);
return revListOutput.stdout.trim();
});
}
tagCreation(tagName) {
return __awaiter(this, void 0, void 0, function* () {
const creationDate = yield this.execGit([
'for-each-ref',
'--format="%(creatordate:rfc)"',
`refs/tags/${tagName}`
]);
const creationDate = yield this.execGit(['for-each-ref', '--format="%(creatordate:rfc)"', `refs/tags/${tagName}`]);
return creationDate.stdout.trim().replace(/"/g, '');
});
}
@@ -800,8 +782,7 @@ class ReleaseNotes {
core.setOutput('commits', diffInfo.commits);
if (mergedPullRequests.length === 0) {
core.warning(`⚠️ No pull requests found`);
return (0, transform_1.fillAdditionalPlaceholders)(this.options.configuration.empty_template ||
configuration_1.DefaultConfiguration.empty_template, this.options);
return (0, transform_1.fillAdditionalPlaceholders)(this.options.configuration.empty_template || configuration_1.DefaultConfiguration.empty_template, this.options);
}
core.startGroup('📦 Build changelog');
const resultChangelog = (0, transform_1.buildChangelog)(diffInfo, mergedPullRequests, this.options);
@@ -841,8 +822,7 @@ class ReleaseNotes {
const lastCommit = commits[commits.length - 1];
let fromDate = firstCommit.date;
const toDate = lastCommit.date;
const maxDays = configuration.max_back_track_time_days ||
configuration_1.DefaultConfiguration.max_back_track_time_days;
const maxDays = configuration.max_back_track_time_days || configuration_1.DefaultConfiguration.max_back_track_time_days;
const maxFromDate = toDate.clone().subtract(maxDays, 'days');
if (maxFromDate.isAfter(fromDate)) {
core.info(`⚠️ Adjusted 'fromDate' to go max ${maxDays} back`);
@@ -852,8 +832,7 @@ class ReleaseNotes {
const pullRequestsApi = new pullRequests_1.PullRequests(octokit);
const pullRequests = yield pullRequestsApi.getBetweenDates(owner, repo, fromDate, toDate, configuration.max_pull_requests || configuration_1.DefaultConfiguration.max_pull_requests);
core.info(`️ Retrieved ${pullRequests.length} merged PRs for ${owner}/${repo}`);
const prCommits = (0, commits_1.filterCommits)(commits, configuration.exclude_merge_branches ||
configuration_1.DefaultConfiguration.exclude_merge_branches);
const prCommits = (0, commits_1.filterCommits)(commits, configuration.exclude_merge_branches || configuration_1.DefaultConfiguration.exclude_merge_branches);
core.info(`️ Retrieved ${prCommits.length} release commits for ${owner}/${repo}`);
// create array of commits for this release
const releaseCommitHashes = prCommits.map(commmit => {
@@ -866,8 +845,7 @@ class ReleaseNotes {
let allPullRequests = mergedPullRequests;
if (includeOpen) {
// retrieve all open pull requests
const openPullRequests = yield pullRequestsApi.getOpen(owner, repo, configuration.max_pull_requests ||
configuration_1.DefaultConfiguration.max_pull_requests);
const openPullRequests = yield pullRequestsApi.getOpen(owner, repo, configuration.max_pull_requests || configuration_1.DefaultConfiguration.max_pull_requests);
core.info(`️ Retrieved ${openPullRequests.length} open PRs for ${owner}/${repo}`);
// all pull requests
allPullRequests = allPullRequests.concat(openPullRequests);
@@ -911,8 +889,7 @@ class ReleaseNotes {
if (commits.length === 0) {
return [diffInfo, []];
}
const prCommits = (0, commits_1.filterCommits)(commits, configuration.exclude_merge_branches ||
configuration_1.DefaultConfiguration.exclude_merge_branches);
const prCommits = (0, commits_1.filterCommits)(commits, configuration.exclude_merge_branches || configuration_1.DefaultConfiguration.exclude_merge_branches);
core.info(`️ Retrieved ${prCommits.length} commits for ${owner}/${repo}`);
const prs = prCommits.map(function (commit) {
return {
@@ -1032,8 +1009,7 @@ class ReleaseNotesBuilder {
// ensure proper from <-> to tag range
core.startGroup(`🔖 Resolve tags`);
const tagsApi = new tags_1.Tags(octokit);
const tagRange = yield tagsApi.retrieveRange(this.repositoryPath, this.owner, this.repo, this.fromTag, this.toTag, this.ignorePreReleases, this.configuration.max_tags_to_fetch ||
configuration_1.DefaultConfiguration.max_tags_to_fetch, this.configuration.tag_resolver || configuration_1.DefaultConfiguration.tag_resolver);
const tagRange = yield tagsApi.retrieveRange(this.repositoryPath, this.owner, this.repo, this.fromTag, this.toTag, this.ignorePreReleases, this.configuration.max_tags_to_fetch || configuration_1.DefaultConfiguration.max_tags_to_fetch, this.configuration.tag_resolver || configuration_1.DefaultConfiguration.tag_resolver);
let thisTag = tagRange.to;
if (!thisTag) {
(0, utils_1.failOrError)(`💥 Missing or couldn't resolve 'toTag'`, this.failOnError);
Generated Vendored
+1 -1
View File
File diff suppressed because one or more lines are too long
+5 -21
View File
@@ -31,23 +31,13 @@ export interface CommitInfo {
export class Commits {
constructor(private octokit: Octokit) {}
async getDiff(
owner: string,
repo: string,
base: string,
head: string
): Promise<DiffInfo> {
async getDiff(owner: string, repo: string, base: string, head: string): Promise<DiffInfo> {
const diff: DiffInfo = await this.getDiffRemote(owner, repo, base, head)
diff.commitInfo = this.sortCommits(diff.commitInfo)
return diff
}
private async getDiffRemote(
owner: string,
repo: string,
base: string,
head: string
): Promise<DiffInfo> {
private async getDiffRemote(owner: string, repo: string, base: string, head: string): Promise<DiffInfo> {
let changedFilesCount = 0
let additionCount = 0
let deletionCount = 0
@@ -56,8 +46,7 @@ export class Commits {
// Fetch comparisons recursively until we don't find any commits
// This is because the GitHub API limits the number of commits returned in a single response.
let commits: RestEndpointMethodTypes['repos']['compareCommits']['response']['data']['commits'] =
[]
let commits: RestEndpointMethodTypes['repos']['compareCommits']['response']['data']['commits'] = []
let compareHead = head
// eslint-disable-next-line no-constant-condition
while (true) {
@@ -84,9 +73,7 @@ export class Commits {
compareHead = `${commits[0].sha}^`
}
core.info(
`️ Found ${commits.length} commits from the GitHub API for ${owner}/${repo}`
)
core.info(`️ Found ${commits.length} commits from the GitHub API for ${owner}/${repo}`)
return {
changedFiles: changedFilesCount,
@@ -135,10 +122,7 @@ export class Commits {
/**
* Filters out all commits which match the exclude pattern
*/
export function filterCommits(
commits: CommitInfo[],
excludeMergeBranches: string[]
): CommitInfo[] {
export function filterCommits(commits: CommitInfo[], excludeMergeBranches: string[]): CommitInfo[] {
const filteredCommits = []
for (const commit of commits) {
+8 -36
View File
@@ -2,9 +2,7 @@ import * as exec from '@actions/exec'
import * as io from '@actions/io'
import {directoryExistsSync} from './utils'
export async function createCommandManager(
workingDirectory: string
): Promise<GitCommandManager> {
export async function createCommandManager(workingDirectory: string): Promise<GitCommandManager> {
return await GitCommandManager.createCommandManager(workingDirectory)
}
@@ -20,52 +18,28 @@ class GitCommandManager {
}
async latestTag(): Promise<string> {
const revListOutput = await this.execGit([
'rev-list',
'--tags',
'--skip=0',
'--max-count=1'
])
const output = await this.execGit([
'describe',
'--abbrev=0',
'--tags',
revListOutput.stdout.trim()
])
const revListOutput = await this.execGit(['rev-list', '--tags', '--skip=0', '--max-count=1'])
const output = await this.execGit(['describe', '--abbrev=0', '--tags', revListOutput.stdout.trim()])
return output.stdout.trim()
}
async initialCommit(): Promise<string> {
const revListOutput = await this.execGit([
'rev-list',
'--max-parents=0',
'HEAD'
])
const revListOutput = await this.execGit(['rev-list', '--max-parents=0', 'HEAD'])
return revListOutput.stdout.trim()
}
async tagCreation(tagName: string): Promise<string> {
const creationDate = await this.execGit([
'for-each-ref',
'--format="%(creatordate:rfc)"',
`refs/tags/${tagName}`
])
const creationDate = await this.execGit(['for-each-ref', '--format="%(creatordate:rfc)"', `refs/tags/${tagName}`])
return creationDate.stdout.trim().replace(/"/g, '')
}
static async createCommandManager(
workingDirectory: string
): Promise<GitCommandManager> {
static async createCommandManager(workingDirectory: string): Promise<GitCommandManager> {
const result = new GitCommandManager()
await result.initializeCommandManager(workingDirectory)
return result
}
private async execGit(
args: string[],
allowAllExitCodes = false,
silent = false
): Promise<GitOutput> {
private async execGit(args: string[], allowAllExitCodes = false, silent = false): Promise<GitOutput> {
directoryExistsSync(this.workingDirectory, true)
const result = new GitOutput()
@@ -88,9 +62,7 @@ class GitCommandManager {
return result
}
private async initializeCommandManager(
workingDirectory: string
): Promise<void> {
private async initializeCommandManager(workingDirectory: string): Promise<void> {
this.workingDirectory = workingDirectory
this.gitPath = await io.which('git', true)
}
+2 -8
View File
@@ -1,11 +1,6 @@
import * as core from '@actions/core'
import * as github from '@actions/github'
import {
parseConfiguration,
resolveConfiguration,
retrieveRepositoryPath,
writeOutput
} from './utils'
import {parseConfiguration, resolveConfiguration, retrieveRepositoryPath, writeOutput} from './utils'
import {ReleaseNotesBuilder} from './releaseNotesBuilder'
import {Configuration} from './configuration'
@@ -44,8 +39,7 @@ async function run(): Promise<void> {
const ignorePreReleases = core.getInput('ignorePreReleases') === 'true'
const failOnError = core.getInput('failOnError') === 'true'
const fetchReviewers = core.getInput('fetchReviewers') === 'true'
const fetchReleaseInformation =
core.getInput('fetchReleaseInformation') === 'true'
const fetchReleaseInformation = core.getInput('fetchReleaseInformation') === 'true'
const commitMode = core.getInput('commitMode') === 'true'
const result = await new ReleaseNotesBuilder(
+11 -43
View File
@@ -26,20 +26,14 @@ export interface PullRequestInfo {
type PullData = RestEndpointMethodTypes['pulls']['get']['response']['data']
type PullsListData =
RestEndpointMethodTypes['pulls']['list']['response']['data']
type PullsListData = RestEndpointMethodTypes['pulls']['list']['response']['data']
type PullReviewData =
RestEndpointMethodTypes['pulls']['listReviews']['response']['data']
type PullReviewData = RestEndpointMethodTypes['pulls']['listReviews']['response']['data']
export class PullRequests {
constructor(private octokit: Octokit) {}
async getSingle(
owner: string,
repo: string,
prNumber: number
): Promise<PullRequestInfo | null> {
async getSingle(owner: string, repo: string, prNumber: number): Promise<PullRequestInfo | null> {
try {
const {data} = await this.octokit.pulls.get({
owner,
@@ -49,9 +43,7 @@ export class PullRequests {
return mapPullRequest(data)
} catch (e: any /* eslint-disable-line @typescript-eslint/no-explicit-any */) {
core.warning(
`⚠️ Cannot find PR ${owner}/${repo}#${prNumber} - ${e.message}`
)
core.warning(`⚠️ Cannot find PR ${owner}/${repo}#${prNumber} - ${e.message}`)
return null
}
}
@@ -98,11 +90,7 @@ export class PullRequests {
return sortPrs(mergedPRs)
}
async getOpen(
owner: string,
repo: string,
maxPullRequests: number
): Promise<PullRequestInfo[]> {
async getOpen(owner: string, repo: string, maxPullRequests: number): Promise<PullRequestInfo[]> {
const openPrs: PullRequestInfo[] = []
const options = this.octokit.pulls.list.endpoint.merge({
owner,
@@ -134,11 +122,7 @@ export class PullRequests {
return sortPrs(openPrs)
}
async getReviewers(
owner: string,
repo: string,
pr: PullRequestInfo
): Promise<PullReviewData[]> {
async getReviewers(owner: string, repo: string, pr: PullRequestInfo): Promise<PullReviewData[]> {
const options = this.octokit.pulls.listReviews.endpoint.merge({
owner,
repo,
@@ -164,10 +148,7 @@ function sortPrs(pullRequests: PullRequestInfo[]): PullRequestInfo[] {
})
}
export function sortPullRequests(
pullRequests: PullRequestInfo[],
sort: Sort | string
): PullRequestInfo[] {
export function sortPullRequests(pullRequests: PullRequestInfo[], sort: Sort | string): PullRequestInfo[] {
let sortConfig: Sort
// legacy handling to support string sort config
@@ -191,11 +172,7 @@ export function sortPullRequests(
return pullRequests
}
export function compare(
a: PullRequestInfo,
b: PullRequestInfo,
sort: Sort
): number {
export function compare(a: PullRequestInfo, b: PullRequestInfo, sort: Sort): number {
if (sort.on_property === 'mergedAt') {
const aa = a.mergedAt || a.createdAt
const bb = b.mergedAt || b.createdAt
@@ -212,10 +189,7 @@ export function compare(
}
// helper function to add a special open label to prs not merged.
function attachSpeciaLabels(
status: 'open' | 'merged',
labels: Set<string>
): Set<string> {
function attachSpeciaLabels(status: 'open' | 'merged', labels: Set<string>): Set<string> {
labels.add(`--rcba-${status}`)
return labels
}
@@ -234,17 +208,11 @@ const mapPullRequest = (
mergeCommitSha: pr.merge_commit_sha || '',
author: pr.user?.login || '',
repoName: pr.base.repo.full_name,
labels: attachSpeciaLabels(
status,
new Set(
pr.labels?.map(lbl => lbl.name?.toLocaleLowerCase('en') || '') || []
)
),
labels: attachSpeciaLabels(status, new Set(pr.labels?.map(lbl => lbl.name?.toLocaleLowerCase('en') || '') || [])),
milestone: pr.milestone?.title || '',
body: pr.body || '',
assignees: pr.assignees?.map(asignee => asignee?.login || '') || [],
requestedReviewers:
pr.requested_reviewers?.map(reviewer => reviewer?.login || '') || [],
requestedReviewers: pr.requested_reviewers?.map(reviewer => reviewer?.login || '') || [],
approvedReviewers: [],
status
})
+19 -54
View File
@@ -62,54 +62,39 @@ export class ReleaseNotes {
if (mergedPullRequests.length === 0) {
core.warning(`⚠️ No pull requests found`)
return fillAdditionalPlaceholders(
this.options.configuration.empty_template ||
DefaultConfiguration.empty_template,
this.options.configuration.empty_template || DefaultConfiguration.empty_template,
this.options
)
}
core.startGroup('📦 Build changelog')
const resultChangelog = buildChangelog(
diffInfo,
mergedPullRequests,
this.options
)
const resultChangelog = buildChangelog(diffInfo, mergedPullRequests, this.options)
core.endGroup()
return resultChangelog
}
private async getCommitHistory(octokit: Octokit): Promise<DiffInfo> {
const {owner, repo, fromTag, toTag, failOnError} = this.options
core.info(
`️ Comparing ${owner}/${repo} - '${fromTag.name}...${toTag.name}'`
)
core.info(`️ Comparing ${owner}/${repo} - '${fromTag.name}...${toTag.name}'`)
const commitsApi = new Commits(octokit)
let diffInfo: DiffInfo
try {
diffInfo = await commitsApi.getDiff(owner, repo, fromTag.name, toTag.name)
} catch (error) {
failOrError(
`💥 Failed to retrieve - Invalid tag? - Because of: ${error}`,
failOnError
)
failOrError(`💥 Failed to retrieve - Invalid tag? - Because of: ${error}`, failOnError)
return DefaultDiffInfo
}
if (diffInfo.commitInfo.length === 0) {
core.warning(
`⚠️ No commits found between - ${fromTag.name}...${toTag.name}`
)
core.warning(`⚠️ No commits found between - ${fromTag.name}...${toTag.name}`)
return DefaultDiffInfo
}
return diffInfo
}
private async getMergedPullRequests(
octokit: Octokit
): Promise<[DiffInfo, PullRequestInfo[]]> {
const {owner, repo, includeOpen, fetchReviewers, configuration} =
this.options
private async getMergedPullRequests(octokit: Octokit): Promise<[DiffInfo, PullRequestInfo[]]> {
const {owner, repo, includeOpen, fetchReviewers, configuration} = this.options
const diffInfo = await this.getCommitHistory(octokit)
const commits = diffInfo.commitInfo
@@ -122,18 +107,14 @@ export class ReleaseNotes {
let fromDate = firstCommit.date
const toDate = lastCommit.date
const maxDays =
configuration.max_back_track_time_days ||
DefaultConfiguration.max_back_track_time_days
const maxDays = configuration.max_back_track_time_days || DefaultConfiguration.max_back_track_time_days
const maxFromDate = toDate.clone().subtract(maxDays, 'days')
if (maxFromDate.isAfter(fromDate)) {
core.info(`⚠️ Adjusted 'fromDate' to go max ${maxDays} back`)
fromDate = maxFromDate
}
core.info(
`️ Fetching PRs between dates ${fromDate.toISOString()} to ${toDate.toISOString()} for ${owner}/${repo}`
)
core.info(`️ Fetching PRs between dates ${fromDate.toISOString()} to ${toDate.toISOString()} for ${owner}/${repo}`)
const pullRequestsApi = new PullRequests(octokit)
const pullRequests = await pullRequestsApi.getBetweenDates(
@@ -144,19 +125,14 @@ export class ReleaseNotes {
configuration.max_pull_requests || DefaultConfiguration.max_pull_requests
)
core.info(
`️ Retrieved ${pullRequests.length} merged PRs for ${owner}/${repo}`
)
core.info(`️ Retrieved ${pullRequests.length} merged PRs for ${owner}/${repo}`)
const prCommits = filterCommits(
commits,
configuration.exclude_merge_branches ||
DefaultConfiguration.exclude_merge_branches
configuration.exclude_merge_branches || DefaultConfiguration.exclude_merge_branches
)
core.info(
`️ Retrieved ${prCommits.length} release commits for ${owner}/${repo}`
)
core.info(`️ Retrieved ${prCommits.length} release commits for ${owner}/${repo}`)
// create array of commits for this release
const releaseCommitHashes = prCommits.map(commmit => {
@@ -174,25 +150,19 @@ export class ReleaseNotes {
const openPullRequests = await pullRequestsApi.getOpen(
owner,
repo,
configuration.max_pull_requests ||
DefaultConfiguration.max_pull_requests
configuration.max_pull_requests || DefaultConfiguration.max_pull_requests
)
core.info(
`️ Retrieved ${openPullRequests.length} open PRs for ${owner}/${repo}`
)
core.info(`️ Retrieved ${openPullRequests.length} open PRs for ${owner}/${repo}`)
// all pull requests
allPullRequests = allPullRequests.concat(openPullRequests)
core.info(
`️ Retrieved ${allPullRequests.length} total PRs for ${owner}/${repo}`
)
core.info(`️ Retrieved ${allPullRequests.length} total PRs for ${owner}/${repo}`)
}
// retrieve base branches we allow
const baseBranches =
configuration.base_branches || DefaultConfiguration.base_branches
const baseBranches = configuration.base_branches || DefaultConfiguration.base_branches
const baseBranchPatterns = baseBranches.map(baseBranch => {
return new RegExp(baseBranch.replace('\\\\', '\\'), 'gu')
})
@@ -213,9 +183,7 @@ export class ReleaseNotes {
for (const pr of finalPrs) {
await pullRequestsApi.getReviewers(owner, repo, pr)
if (pr.approvedReviewers.length > 0) {
core.info(
`️ Retrieved ${pr.approvedReviewers.length} reviewer(s) for PR ${owner}/${repo}/#${pr.number}`
)
core.info(`️ Retrieved ${pr.approvedReviewers.length} reviewer(s) for PR ${owner}/${repo}/#${pr.number}`)
}
}
} else {
@@ -225,9 +193,7 @@ export class ReleaseNotes {
return [diffInfo, finalPrs]
}
private async generateCommitPRs(
octokit: Octokit
): Promise<[DiffInfo, PullRequestInfo[]]> {
private async generateCommitPRs(octokit: Octokit): Promise<[DiffInfo, PullRequestInfo[]]> {
const {owner, repo, configuration} = this.options
const diffInfo = await this.getCommitHistory(octokit)
@@ -238,8 +204,7 @@ export class ReleaseNotes {
const prCommits = filterCommits(
commits,
configuration.exclude_merge_branches ||
DefaultConfiguration.exclude_merge_branches
configuration.exclude_merge_branches || DefaultConfiguration.exclude_merge_branches
)
core.info(`️ Retrieved ${prCommits.length} commits for ${owner}/${repo}`)
+4 -18
View File
@@ -57,8 +57,7 @@ export class ReleaseNotesBuilder {
this.fromTag,
this.toTag,
this.ignorePreReleases,
this.configuration.max_tags_to_fetch ||
DefaultConfiguration.max_tags_to_fetch,
this.configuration.max_tags_to_fetch || DefaultConfiguration.max_tags_to_fetch,
this.configuration.tag_resolver || DefaultConfiguration.tag_resolver
)
@@ -73,10 +72,7 @@ export class ReleaseNotesBuilder {
let previousTag = tagRange.from
if (previousTag == null) {
failOrError(
`💥 Unable to retrieve previous tag given ${this.toTag}`,
this.failOnError
)
failOrError(`💥 Unable to retrieve previous tag given ${this.toTag}`, this.failOnError)
return null
}
core.setOutput('fromTag', previousTag.name)
@@ -85,18 +81,8 @@ export class ReleaseNotesBuilder {
if (this.fetchReleaseInformation) {
// load release information from the GitHub API
core.info(`️ Fetching release information was enabled`)
thisTag = await tagsApi.fillTagInformation(
this.repositoryPath,
this.owner,
this.repo,
thisTag
)
previousTag = await tagsApi.fillTagInformation(
this.repositoryPath,
this.owner,
this.repo,
previousTag
)
thisTag = await tagsApi.fillTagInformation(this.repositoryPath, this.owner, this.repo, thisTag)
previousTag = await tagsApi.fillTagInformation(this.repositoryPath, this.owner, this.repo, previousTag)
} else {
core.debug(`️ Fetching release information was disabled`)
}
+20 -70
View File
@@ -26,11 +26,7 @@ export interface SortableTagInfo extends TagInfo {
export class Tags {
constructor(private octokit: Octokit) {}
async getTags(
owner: string,
repo: string,
maxTagsToFetch: number
): Promise<TagInfo[]> {
async getTags(owner: string, repo: string, maxTagsToFetch: number): Promise<TagInfo[]> {
const tagsInfo: TagInfo[] = []
const options = this.octokit.repos.listTags.endpoint.merge({
owner,
@@ -40,8 +36,7 @@ export class Tags {
})
for await (const response of this.octokit.paginate.iterator(options)) {
type TagsListData =
RestEndpointMethodTypes['repos']['listTags']['response']['data']
type TagsListData = RestEndpointMethodTypes['repos']['listTags']['response']['data']
const tags: TagsListData = response.data as TagsListData
for (const tag of tags) {
@@ -63,12 +58,7 @@ export class Tags {
return tagsInfo
}
async fillTagInformation(
repositoryPath: string,
owner: string,
repo: string,
tagInfo: TagInfo
): Promise<TagInfo> {
async fillTagInformation(repositoryPath: string, owner: string, repo: string, tagInfo: TagInfo): Promise<TagInfo> {
const options = this.octokit.repos.getReleaseByTag.endpoint.merge({
owner,
repo,
@@ -77,14 +67,11 @@ export class Tags {
try {
const response = await this.octokit.request(options)
type ReleaseInformation =
RestEndpointMethodTypes['repos']['getReleaseByTag']['response']['data']
type ReleaseInformation = RestEndpointMethodTypes['repos']['getReleaseByTag']['response']['data']
const release: ReleaseInformation = response.data as ReleaseInformation
tagInfo.date = moment(release.created_at)
core.info(
`️ Retrieved information about the release associated with ${tagInfo.name} from the GitHub API`
)
core.info(`️ Retrieved information about the release associated with ${tagInfo.name} from the GitHub API`)
} catch (error) {
core.info(
`⚠️ No release information found for ${tagInfo.name}, trying to retrieve tag creation time as fallback.`
@@ -117,13 +104,9 @@ export class Tags {
const length = tags.length
if (tags.length > 1) {
for (let i = 0; i < length; i++) {
if (
tags[i].name.toLocaleLowerCase('en') === tag.toLocaleLowerCase('en')
) {
if (tags[i].name.toLocaleLowerCase('en') === tag.toLocaleLowerCase('en')) {
if (ignorePreReleases) {
core.info(
`️ Enabled 'ignorePreReleases', searching for the closest release`
)
core.info(`️ Enabled 'ignorePreReleases', searching for the closest release`)
for (let ii = i + 1; ii < length; ii++) {
if (!tags[ii].name.includes('-')) {
return tags[ii]
@@ -134,15 +117,11 @@ export class Tags {
}
}
} else {
core.info(
`️ Only one tag found for the given repository. Usually this is the case for the initial release.`
)
core.info(`️ Only one tag found for the given repository. Usually this is the case for the initial release.`)
// if not specified try to retrieve tag from git
const gitHelper = await createCommandManager(repositoryPath)
const initialCommit = await gitHelper.initialCommit()
core.info(
`🔖 Resolved initial commit (${initialCommit}) from 'git rev-list --max-parents=0 HEAD'`
)
core.info(`🔖 Resolved initial commit (${initialCommit}) from 'git rev-list --max-parents=0 HEAD'`)
return {name: initialCommit, commit: initialCommit}
}
return tags[0]
@@ -203,25 +182,19 @@ export class Tags {
// if not specified try to retrieve tag from github.context.ref
if (github.context.ref?.startsWith('refs/tags/') === true) {
toTag = github.context.ref.replace('refs/tags/', '')
core.info(
`🔖 Resolved current tag (${toTag}) from the 'github.context.ref'`
)
core.info(`🔖 Resolved current tag (${toTag}) from the 'github.context.ref'`)
resultToTag = {
name: toTag,
commit: toTag
}
} else if (tags.length > 1) {
resultToTag = tags[0]
core.info(
`🔖 Resolved current tag (${resultToTag.name}) from the tags git API`
)
core.info(`🔖 Resolved current tag (${resultToTag.name}) from the tags git API`)
} else {
// if not specified try to retrieve tag from git
const gitHelper = await createCommandManager(repositoryPath)
const latestTag = await gitHelper.latestTag()
core.info(
`🔖 Resolved current tag (${latestTag}) from 'git rev-list --tags --skip=0 --max-count=1'`
)
core.info(`🔖 Resolved current tag (${latestTag}) from 'git rev-list --tags --skip=0 --max-count=1'`)
resultToTag = {
name: latestTag,
commit: latestTag
@@ -241,17 +214,10 @@ export class Tags {
if (!fromTag) {
core.debug(`fromTag undefined, trying to resolve via API`)
resultFromTag = await this.findPredecessorTag(
tags,
repositoryPath,
toTag,
ignorePreReleases
)
resultFromTag = await this.findPredecessorTag(tags, repositoryPath, toTag, ignorePreReleases)
if (resultFromTag != null) {
core.info(
`🔖 Resolved previous tag (${resultFromTag.name}) from the tags git API`
)
core.info(`🔖 Resolved previous tag (${resultFromTag.name}) from the tags git API`)
}
} else {
resultFromTag = {
@@ -271,20 +237,12 @@ export class Tags {
* Uses the provided filter (if available) to filter out any tags not currently relevant.
* https://github.com/mikepenz/release-changelog-builder-action/issues/566
*/
export function filterTags(
tags: TagInfo[],
tagResolver: TagResolver
): TagInfo[] {
export function filterTags(tags: TagInfo[], tagResolver: TagResolver): TagInfo[] {
const filter = tagResolver.filter
if (filter !== undefined) {
const regex = new RegExp(
filter.pattern.replace('\\\\', '\\'),
filter.flags ?? 'gu'
)
const regex = new RegExp(filter.pattern.replace('\\\\', '\\'), filter.flags ?? 'gu')
const filteredTags = tags.filter(tag => tag.name.match(regex) !== null)
core.debug(
`️ Filtered tags count: ${filteredTags.length}, original count: ${tags.length}`
)
core.debug(`️ Filtered tags count: ${filteredTags.length}, original count: ${tags.length}`)
return filteredTags
} else {
return tags
@@ -294,16 +252,10 @@ export function filterTags(
/**
* Helper function to transform the tag name given the transformer
*/
function transformTags(
tags: TagInfo[],
transformer: RegexTransformer
): TagInfo[] {
function transformTags(tags: TagInfo[], transformer: RegexTransformer): TagInfo[] {
return tags.map(function (tag) {
if (transformer.pattern) {
const transformedName = tag.name.replace(
transformer.pattern,
transformer.target
)
const transformedName = tag.name.replace(transformer.pattern, transformer.target)
core.debug(`️ Transformed ${tag.name} to ${transformedName}`)
return {
tmp: tag.name, // remember the original name
@@ -347,9 +299,7 @@ function semVerSorting(tags: TagInfo[]): TagInfo[] {
loose: true
}) !== null
if (!isValid) {
core.debug(
`⚠️ dropped tag ${tag.name} because it is not a valid semver tag`
)
core.debug(`⚠️ dropped tag ${tag.name} because it is not a valid semver tag`)
}
return isValid
})
+40 -159
View File
@@ -1,19 +1,10 @@
import * as core from '@actions/core'
import {
Category,
DefaultConfiguration,
Extractor,
Transformer
} from './configuration'
import {Category, DefaultConfiguration, Extractor, Transformer} from './configuration'
import {PullRequestInfo, sortPullRequests} from './pullRequests'
import {ReleaseNotesOptions} from './releaseNotes'
import {DiffInfo} from './commits'
export function buildChangelog(
diffInfo: DiffInfo,
prs: PullRequestInfo[],
options: ReleaseNotesOptions
): string {
export function buildChangelog(diffInfo: DiffInfo, prs: PullRequestInfo[], options: ReleaseNotesOptions): string {
// sort to target order
const config = options.configuration
const sort = config.sort || DefaultConfiguration.sort
@@ -33,18 +24,14 @@ export function buildChangelog(
if (extracted !== null && extracted.length > 0) {
deduplicatedMap.set(extracted[0], pr)
} else {
core.info(
` PR (${pr.number}) did not resolve an ID using the \`duplicate_filter\``
)
core.info(` PR (${pr.number}) did not resolve an ID using the \`duplicate_filter\``)
unmatched.push(pr)
}
}
const deduplicatedPRs = Array.from(deduplicatedMap.values())
deduplicatedPRs.push(...unmatched) // add all unmatched PRs to map
const removedElements = prs.length - deduplicatedPRs.length
core.info(
`️ Removed ${removedElements} pull requests during deduplication`
)
core.info(`️ Removed ${removedElements} pull requests during deduplication`)
prs = sortPullRequests(deduplicatedPRs, sort) // resort deduplicatedPRs
} else {
core.warning(`⚠️ Configured \`duplicate_filter\` invalid.`)
@@ -70,25 +57,16 @@ export function buildChangelog(
for (const pr of prs) {
transformedMap.set(
pr,
transform(
fillTemplate(
pr,
config.pr_template || DefaultConfiguration.pr_template
),
validatedTransformers
)
transform(fillTemplate(pr, config.pr_template || DefaultConfiguration.pr_template), validatedTransformers)
)
}
core.info(
`️ Used ${validatedTransformers.length} transformers to adjust message`
)
core.info(`️ Used ${validatedTransformers.length} transformers to adjust message`)
core.info(`✒️ Wrote messages for ${prs.length} pull requests`)
// bring PRs into the order of categories
const categorized = new Map<Category, string[]>()
const categories = config.categories || DefaultConfiguration.categories
const ignoredLabels =
config.ignore_labels || DefaultConfiguration.ignore_labels
const ignoredLabels = config.ignore_labels || DefaultConfiguration.ignore_labels
for (const category of categories) {
categorized.set(category, [])
@@ -203,9 +181,7 @@ export function buildChangelog(
for (const pr of uncategorizedPrs) {
changelogUncategorized = `${changelogUncategorized + pr}\n`
}
core.info(
`✒️ Wrote ${uncategorizedPrs.length} non categorized pull requests down`
)
core.info(`✒️ Wrote ${uncategorizedPrs.length} non categorized pull requests down`)
if (core.isDebug()) {
for (const pr of uncategorizedPrs) {
core.debug(` ${pr}`)
@@ -240,95 +216,41 @@ export function buildChangelog(
// fill template
let transformedChangelog = config.template || DefaultConfiguration.template
transformedChangelog = transformedChangelog.replace(
/\${{CHANGELOG}}/g,
changelog
)
transformedChangelog = transformedChangelog.replace(
/\${{UNCATEGORIZED}}/g,
changelogUncategorized
)
transformedChangelog = transformedChangelog.replace(
/\${{OPEN}}/g,
changelogOpen
)
transformedChangelog = transformedChangelog.replace(
/\${{IGNORED}}/g,
changelogIgnored
)
transformedChangelog = transformedChangelog.replace(/\${{CHANGELOG}}/g, changelog)
transformedChangelog = transformedChangelog.replace(/\${{UNCATEGORIZED}}/g, changelogUncategorized)
transformedChangelog = transformedChangelog.replace(/\${{OPEN}}/g, changelogOpen)
transformedChangelog = transformedChangelog.replace(/\${{IGNORED}}/g, changelogIgnored)
// fill other placeholders
transformedChangelog = transformedChangelog.replace(
/\${{CATEGORIZED_COUNT}}/g,
categorizedPrs.length.toString()
)
transformedChangelog = transformedChangelog.replace(
/\${{UNCATEGORIZED_COUNT}}/g,
uncategorizedPrs.length.toString()
)
transformedChangelog = transformedChangelog.replace(
/\${{OPEN_COUNT}}/g,
openPrs.length.toString()
)
transformedChangelog = transformedChangelog.replace(
/\${{IGNORED_COUNT}}/g,
ignoredPrs.length.toString()
)
transformedChangelog = transformedChangelog.replace(/\${{CATEGORIZED_COUNT}}/g, categorizedPrs.length.toString())
transformedChangelog = transformedChangelog.replace(/\${{UNCATEGORIZED_COUNT}}/g, uncategorizedPrs.length.toString())
transformedChangelog = transformedChangelog.replace(/\${{OPEN_COUNT}}/g, openPrs.length.toString())
transformedChangelog = transformedChangelog.replace(/\${{IGNORED_COUNT}}/g, ignoredPrs.length.toString())
// code change placeholders
transformedChangelog = transformedChangelog.replace(
/\${{CHANGED_FILES}}/g,
diffInfo.changedFiles.toString()
)
transformedChangelog = transformedChangelog.replace(
/\${{ADDITIONS}}/g,
diffInfo.additions.toString()
)
transformedChangelog = transformedChangelog.replace(
/\${{DELETIONS}}/g,
diffInfo.deletions.toString()
)
transformedChangelog = transformedChangelog.replace(
/\${{CHANGES}}/g,
diffInfo.changes.toString()
)
transformedChangelog = transformedChangelog.replace(
/\${{COMMITS}}/g,
diffInfo.commits.toString()
)
transformedChangelog = fillAdditionalPlaceholders(
transformedChangelog,
options
)
transformedChangelog = transformedChangelog.replace(/\${{CHANGED_FILES}}/g, diffInfo.changedFiles.toString())
transformedChangelog = transformedChangelog.replace(/\${{ADDITIONS}}/g, diffInfo.additions.toString())
transformedChangelog = transformedChangelog.replace(/\${{DELETIONS}}/g, diffInfo.deletions.toString())
transformedChangelog = transformedChangelog.replace(/\${{CHANGES}}/g, diffInfo.changes.toString())
transformedChangelog = transformedChangelog.replace(/\${{COMMITS}}/g, diffInfo.commits.toString())
transformedChangelog = fillAdditionalPlaceholders(transformedChangelog, options)
core.info(`️ Filled template`)
return transformedChangelog
}
export function fillAdditionalPlaceholders(
text: string,
options: ReleaseNotesOptions
): string {
export function fillAdditionalPlaceholders(text: string, options: ReleaseNotesOptions): string {
let transformed = text
// repository placeholders
transformed = transformed.replace(/\${{OWNER}}/g, options.owner)
transformed = transformed.replace(/\${{REPO}}/g, options.repo)
transformed = transformed.replace(/\${{FROM_TAG}}/g, options.fromTag.name)
transformed = transformed.replace(
/\${{FROM_TAG_DATE}}/g,
options.fromTag.date?.toISOString() || ''
)
transformed = transformed.replace(/\${{FROM_TAG_DATE}}/g, options.fromTag.date?.toISOString() || '')
transformed = transformed.replace(/\${{TO_TAG}}/g, options.toTag.name)
transformed = transformed.replace(
/\${{TO_TAG_DATE}}/g,
options.toTag.date?.toISOString() || ''
)
transformed = transformed.replace(/\${{TO_TAG_DATE}}/g, options.toTag.date?.toISOString() || '')
const fromDate = options.fromTag.date
const toDate = options.toTag.date
if (fromDate !== undefined && toDate !== undefined) {
transformed = transformed.replace(
/\${{DAYS_SINCE}}/g,
toDate.diff(fromDate, 'days').toString() || ''
)
transformed = transformed.replace(/\${{DAYS_SINCE}}/g, toDate.diff(fromDate, 'days').toString() || '')
} else {
transformed = transformed.replace(/\${{DAYS_SINCE}}/g, '')
}
@@ -353,14 +275,8 @@ function fillTemplate(pr: PullRequestInfo, template: string): string {
transformed = transformed.replace(/\${{TITLE}}/g, pr.title)
transformed = transformed.replace(/\${{URL}}/g, pr.htmlURL)
transformed = transformed.replace(/\${{STATUS}}/g, pr.status)
transformed = transformed.replace(
/\${{CREATED_AT}}/g,
pr.createdAt.toISOString()
)
transformed = transformed.replace(
/\${{MERGED_AT}}/g,
pr.mergedAt?.toISOString() || ''
)
transformed = transformed.replace(/\${{CREATED_AT}}/g, pr.createdAt.toISOString())
transformed = transformed.replace(/\${{MERGED_AT}}/g, pr.mergedAt?.toISOString() || '')
transformed = transformed.replace(/\${{MERGE_SHA}}/g, pr.mergeCommitSha)
transformed = transformed.replace(/\${{AUTHOR}}/g, pr.author)
transformed = transformed.replace(
@@ -369,18 +285,9 @@ function fillTemplate(pr: PullRequestInfo, template: string): string {
)
transformed = transformed.replace(/\${{MILESTONE}}/g, pr.milestone || '')
transformed = transformed.replace(/\${{BODY}}/g, pr.body)
transformed = transformed.replace(
/\${{ASSIGNEES}}/g,
pr.assignees?.join(', ') || ''
)
transformed = transformed.replace(
/\${{REVIEWERS}}/g,
pr.requestedReviewers?.join(', ') || ''
)
transformed = transformed.replace(
/\${{APPROVERS}}/g,
pr.approvedReviewers?.join(', ') || ''
)
transformed = transformed.replace(/\${{ASSIGNEES}}/g, pr.assignees?.join(', ') || '')
transformed = transformed.replace(/\${{REVIEWERS}}/g, pr.requestedReviewers?.join(', ') || '')
transformed = transformed.replace(/\${{APPROVERS}}/g, pr.approvedReviewers?.join(', ') || '')
return transformed
}
@@ -397,11 +304,8 @@ function transform(filled: string, transformers: RegexTransformer[]): string {
return transformed
}
function validateTransformers(
specifiedTransformers: Transformer[]
): RegexTransformer[] {
const transformers =
specifiedTransformers || DefaultConfiguration.transformers
function validateTransformers(specifiedTransformers: Transformer[]): RegexTransformer[] {
const transformers = specifiedTransformers || DefaultConfiguration.transformers
return transformers
.map(transformer => {
return validateTransformer(transformer)
@@ -412,9 +316,7 @@ function validateTransformers(
})
}
export function validateTransformer(
transformer?: Transformer
): RegexTransformer | null {
export function validateTransformer(transformer?: Transformer): RegexTransformer | null {
if (transformer === undefined) {
return null
}
@@ -436,10 +338,7 @@ export function validateTransformer(
}
return {
pattern: new RegExp(
transformer.pattern.replace('\\\\', '\\'),
transformer.flags ?? 'gu'
),
pattern: new RegExp(transformer.pattern.replace('\\\\', '\\'), transformer.flags ?? 'gu'),
target: transformer.target || '',
onProperty,
method,
@@ -451,33 +350,20 @@ export function validateTransformer(
}
}
function extractValues(
pr: PullRequestInfo,
extractor: RegexTransformer,
extractor_usecase: string
): string[] | null {
function extractValues(pr: PullRequestInfo, extractor: RegexTransformer, extractor_usecase: string): string[] | null {
if (extractor.pattern == null) {
return null
}
if (extractor.onProperty !== undefined) {
let results: string[] = []
const list: (
| 'title'
| 'author'
| 'milestone'
| 'body'
| 'status'
| 'branch'
)[] = extractor.onProperty
const list: ('title' | 'author' | 'milestone' | 'body' | 'status' | 'branch')[] = extractor.onProperty
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < list.length; i++) {
const prop = list[i]
let value: string | undefined = pr[prop]
if (value === undefined) {
core.warning(
`⚠️ the provided property '${extractor.onProperty}' for \`${extractor_usecase}\` is not valid`
)
core.warning(`⚠️ the provided property '${extractor.onProperty}' for \`${extractor_usecase}\` is not valid`)
value = pr['body']
}
@@ -492,10 +378,7 @@ function extractValues(
}
}
function extractValuesFromString(
value: string,
extractor: RegexTransformer
): string[] | null {
function extractValuesFromString(value: string, extractor: RegexTransformer): string[] | null {
if (extractor.pattern == null) {
return null
}
@@ -520,9 +403,7 @@ function extractValuesFromString(
export interface RegexTransformer {
pattern: RegExp | null
target: string
onProperty?:
| ('title' | 'author' | 'milestone' | 'body' | 'status' | 'branch')[]
| undefined
onProperty?: ('title' | 'author' | 'milestone' | 'body' | 'status' | 'branch')[] | undefined
method?: 'replace' | 'match' | undefined
onEmpty?: string | undefined
}
+9 -33
View File
@@ -23,10 +23,7 @@ export function retrieveRepositoryPath(providedPath: string): string {
/**
* Will automatically either report the message to the log, or mark the action as failed. Additionally defining the output failed, allowing it to be read in by other actions
*/
export function failOrError(
message: string | Error,
failOnError: boolean
): void {
export function failOrError(message: string | Error, failOnError: boolean): void {
// if we report any failure, consider the action to have failed, may not make the build fail
core.setOutput('failed', true)
if (failOnError) {
@@ -39,16 +36,10 @@ export function failOrError(
/**
* Retrieves the configuration given the file path, if not found it will fallback to the `DefaultConfiguration`
*/
export function resolveConfiguration(
githubWorkspacePath: string,
configurationFile: string
): Configuration {
export function resolveConfiguration(githubWorkspacePath: string, configurationFile: string): Configuration {
let configuration = DefaultConfiguration
if (configurationFile) {
const configurationPath = path.resolve(
githubWorkspacePath,
configurationFile
)
const configurationPath = path.resolve(githubWorkspacePath, configurationFile)
core.debug(`configurationPath = '${configurationPath}'`)
const providedConfiguration = readConfiguration(configurationPath)
if (providedConfiguration) {
@@ -76,9 +67,7 @@ function readConfiguration(filename: string): Configuration | undefined {
} catch (error) {
core.debug(`Failed to load configuration due to: ${error}`)
}
core.info(
`⚠️ Configuration provided, but it couldn't be found. Fallback to Defaults.`
)
core.info(`⚠️ Configuration provided, but it couldn't be found. Fallback to Defaults.`)
return undefined
}
/**
@@ -87,14 +76,10 @@ function readConfiguration(filename: string): Configuration | undefined {
export function parseConfiguration(config: string): Configuration | undefined {
try {
// for compatiblity with the `yml` file we require to use `#{{}}` instead of `${{}}` - replace it here.
const configurationJSON: Configuration = JSON.parse(
config.replace(/#{{/g, '${{')
)
const configurationJSON: Configuration = JSON.parse(config.replace(/#{{/g, '${{'))
return configurationJSON
} catch (error) {
core.info(
`⚠️ Configuration provided, but it couldn't be parsed. Fallback to Defaults.`
)
core.info(`⚠️ Configuration provided, but it couldn't be parsed. Fallback to Defaults.`)
return undefined
}
}
@@ -102,10 +87,7 @@ export function parseConfiguration(config: string): Configuration | undefined {
/**
* Checks if a given directory exists
*/
export function directoryExistsSync(
inputPath: string,
required?: boolean
): boolean {
export function directoryExistsSync(inputPath: string, required?: boolean): boolean {
if (!inputPath) {
throw new Error("Arg 'path' must not be empty")
}
@@ -122,9 +104,7 @@ export function directoryExistsSync(
throw new Error(`Directory '${inputPath}' does not exist`)
}
throw new Error(
`Encountered an error when checking whether path '${inputPath}' exists: ${error.message}`
)
throw new Error(`Encountered an error when checking whether path '${inputPath}' exists: ${error.message}`)
}
if (stats.isDirectory()) {
@@ -139,11 +119,7 @@ export function directoryExistsSync(
/**
* Writes the changelog to the given the file
*/
export function writeOutput(
githubWorkspacePath: string,
outputFile: string,
changelog: string | null
): void {
export function writeOutput(githubWorkspacePath: string, outputFile: string, changelog: string | null): void {
if (outputFile && changelog) {
const outputPath = path.resolve(githubWorkspacePath, outputFile)
core.debug(`outputPath = '${outputPath}'`)