Skip to content

Commit

Permalink
feat: added test coverage
Browse files Browse the repository at this point in the history
feat: rename to changescribe
removed: removed --includeCommit
  • Loading branch information
giovanni-bertoncelli committed Feb 22, 2024
1 parent b7f9676 commit fc0698f
Show file tree
Hide file tree
Showing 27 changed files with 6,464 additions and 1,615 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ jobs:
scope: "@ctinnovation"

- name: install dependencies
run: npm install -g @ctinnovation/changelogger
run: npm install -g changescribe
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_GET_TOKEN}}

Expand Down
38 changes: 38 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
name: Test

on:
push:
branches:
- "**"
- "!release**"
tags:
- "v**"

workflow_dispatch:
inputs:
logLevel:
description: "Log level"
required: true
default: "warning"

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v4

- uses: actions/setup-node@v4
with:
node-version: "20.x"

- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- run: npm ci
- run: npm run test
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,6 @@ PR-*
KALI-*
TEST-*
CHANGELOG

.tap
!test/unreleased
2 changes: 2 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{
}
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@ Feel free to customize your template by modifying the templates inside `template
| -p, --fromPackageJson | Retrieve target version from pkg.json *(overrides `--targetVersion`)* | [boolean] [default: false] |
| -o, --output | Ouput CHANGELOG file | [string] [default: process.pwd()/CHANGELOG.md] |
| -i, --input | Input folder for compiling the changelog | [string] [default: process.pwd()/unreleased] |
| --includeCommits | Include branch commits in new release | [boolean] [default: false] |
| -u, --taskUrlTemplate | Associated task URL template. *Mandatory if `--excludeTaskList` is false* | [string] [required] |
| --excludeTaskList | Exclude tasks list after release title | [boolean] [default: false] |
| --createOutputIfNotFound | Create a new output file if not found | [boolean] [default: true] |
Expand Down
File renamed without changes
10 changes: 4 additions & 6 deletions commands/explore/argv.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,15 @@ const argvBuilder = function argvBuilder (yargs) {
.default('input', defaults.input)
.describe('input', 'Input CHANGELOG for explore diffs')
.check((args) => {
const { range, output } = args
if (!range) {
throw new Error('Should provide a range!')
}
const { output } = args

if (output !== 'console' && !fs.lstatSync(output).isDirectory()) {
throw new Error('You must provide a folder as --output, not a file path!')
if (output !== 'console' && (!fs.existsSync(output) || !fs.lstatSync(output).isDirectory())) {
throw new Error('You must provide a valid and existing folder as --output!')
}

return true // tell Yargs that the arguments passed the check
})
.demandOption('range')
.help()
}

Expand Down
10 changes: 6 additions & 4 deletions commands/explore/handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,20 +66,21 @@ async function handler (argv) {
const pkgPath = path.join(targetRoot, 'package.json')
let name = 'Unknown'
if (!fs.existsSync(pkgPath)) {
console.warning('Unable to find a valid package.json to retrieve the name from!')
console.warn('Unable to find a valid package.json to retrieve the name from!')
} else {
name = require(pkgPath).name
}
const changelogInputPath = path.isAbsolute(argv.input)
? argv.input
: path.resolve(targetRoot, argv.input)

const lines = fs.readFileSync(changelogInputPath, 'utf-8')

if (!lines) {
const exists = fs.existsSync(changelogInputPath)
if (!exists) {
throw new Error(`File ${argv.input} not found`)
}

const lines = fs.readFileSync(changelogInputPath, 'utf-8')

let min
let max
// extract the bounds of the versions
Expand All @@ -102,6 +103,7 @@ async function handler (argv) {
max = splittedVersions[0]
}
// any other input
/* c8 ignore next 5 */
} else {
console.error('Error in the inserted range.')
console.log('Closing the tool.')
Expand Down
14 changes: 5 additions & 9 deletions commands/generate/argv.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ const COMMAND_DEFAULTS = {
fromPackageJson: false,
output: path.resolve(process.cwd(), './CHANGELOG.md'),
input: path.resolve(process.cwd(), './unreleased'),
includeCommits: false,
excludeTaskList: false,
createOutputIfNotFound: false
createOutputIfNotFound: true
}

const argvBuilder = function argvBuilder (yargs) {
Expand Down Expand Up @@ -37,9 +36,6 @@ const argvBuilder = function argvBuilder (yargs) {
.alias('input', 'i')
.default('input', defaults.input)
.describe('input', 'Input folder for compiling the changelog')
.boolean('includeCommits')
.default('includeCommits', defaults.includeCommits)
.describe('includeCommits', 'Include branch commits in new release')
.boolean('excludeTaskList')
.default('excludeTaskList', defaults.excludeTaskList)
.describe('excludeTaskList', 'Exclude tasks list after release title')
Expand All @@ -56,14 +52,14 @@ const argvBuilder = function argvBuilder (yargs) {
throw new Error('Should provide --targetVersion or use the --fromPackageJson flag!')
}

if (!taskUrlTemplate.includes('{taskCode}')) {
throw new Error('Should provide a URL that contains `{taskCode}`!')
}

if (!excludeTaskList && !taskUrlTemplate) {
throw new Error('Should provide --taskUrlTemplate when --excludeTaskList is false!')
}

if (!excludeTaskList && !taskUrlTemplate.includes('{taskCode}')) {
throw new Error('Should provide a URL that contains `{taskCode}`!')
}

return true // tell Yargs that the arguments passed the check
})
.help()
Expand Down
25 changes: 4 additions & 21 deletions commands/generate/handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ const {
Handlebars, versionTemplate, taskTemplate, headerTemplate
} = require('../../helpers/hbs')
const { verifyTargetVersion } = require('../../helpers/semver')
const { VERSION_LINE_REGEX, UNRELEASED_LINE_REGEX, URL_TASK_REGEX } = require('../../helpers/regexprs')
const { createVersionIndex, createCommitSummary, parseTaskFile } = require('../../helpers/md')
const { VERSION_LINE_REGEX, UNRELEASED_LINE_REGEX } = require('../../helpers/regexprs')
const { createVersionIndex, parseTaskFile } = require('../../helpers/md')

async function handler (argv) {
const targetRoot = path.resolve(process.cwd(), '.')
Expand Down Expand Up @@ -47,13 +47,6 @@ async function handler (argv) {
}
}

// check taskUrlTemplate
const urlRegexCheck = new RegExp(URL_TASK_REGEX)
if (!urlRegexCheck.test(argv.taskUrlTemplate)) {
console.error('The inserted URL is not supported: the tools accepts valid URL that contains the keyword {taskCode}.')
process.exit(1)
}

if (!changelogExists && !argv.createOutputIfNotFound) {
console.error(`Missing file ${changelogPath} and option createOutputIfNotFound set to false.`)
console.log('Unable to continue. The tool will be shut down.')
Expand Down Expand Up @@ -91,11 +84,6 @@ async function handler (argv) {
const tempChangelog = `${changelogPath}-temp-${new Date().getTime()}`
const writeStream = fs.createWriteStream(tempChangelog)

writeStream.on('error', (e) => {
console.error(e)
process.exit(1)
})

// write header template
const header = Handlebars.compile(headerTemplate)({
index: createVersionIndex(targetVersion, oldChangelogBody)
Expand All @@ -119,7 +107,7 @@ async function handler (argv) {
const taskBody = fs.readFileSync(fullPath, 'utf-8')

tasks.push(taskCode)
const urlTask = argv.taskUrlTemplate.replace('{taskCode}', taskCode)
const urlTask = (argv.taskUrlTemplate || '').replace('{taskCode}', taskCode)
finalSectionMap = parseTaskFile(taskCode, taskBody, urlTask, finalSectionMap)
})

Expand All @@ -144,15 +132,10 @@ async function handler (argv) {
writeStream.write('\n')
})

if (argv.includeCommits) {
writeStream.write('\n##### Commit history\n\n')
const commitSummary = await createCommitSummary()
writeStream.write(commitSummary)
}

writeStream.on('finish', () => {
// write on the final changelog file
fs.copyFile(tempChangelog, changelogPath, (err) => {
/* c8 ignore next 4 */
if (err) {
console.error(err)
process.exit(1)
Expand Down
6 changes: 0 additions & 6 deletions commands/init/handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,6 @@ async function handler (argv) {
}

const writeStream = fs.createWriteStream(changelogPath)

writeStream.on('error', (e) => {
console.error(e)
process.exit(1)
})

// write header template
const header = Handlebars.compile(headerTemplate)({})
writeStream.write(header)
Expand Down
16 changes: 0 additions & 16 deletions helpers/md.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
const git = require('simple-git')({
baseDir: process.cwd(),
binary: 'git'
})

const { Handlebars, versionTemplate, lineCodeTemplate } = require('./hbs')
const {
VERSION_LINE_REGEX,
TASK_SECTION_REGEX,
SUBSECTION_TITLE_REGEX,
upperFirst,
matchesToArray,
SUBSECTION_POINT_REGEX,
matchSectionTitle
Expand Down Expand Up @@ -104,17 +98,7 @@ function createVersionIndex (targetVersion, currentChangelog) {
return result
}

async function createCommitSummary () {
const commits = await git.log({
from: 'main'
})
return commits.all
.map((c) => ` * ${c.message}`)
.join('\n')
}

module.exports = {
createVersionIndex,
createCommitSummary,
parseTaskFile
}
8 changes: 1 addition & 7 deletions helpers/regexprs.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,10 @@ const ADDED_REGEX = /add(ed)?|created?/gi
const REMOVED_REGEX = /removed?|cancel(led)?/gi
const REFACTORED_REGEX = /refactor(ed)?/gi
const SUBSECTION_POINT_REGEX = /( )*- .+(?:\n|$)/gi
const URL_TASK_REGEX = /^(http(s):\/\/.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}([-a-zA-Z0-9@:%_\+.~#?&//=]*.{taskCode}[^\s]+)/
const EXTRACT_VERSION = /\n+## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\n+/g
const REMOVE_TASK_BADGES = /\[(.*?)\]\((.*?)\)\]/g
const REMOVE_TASK_LINK = /( ‧ \[.*?\]\(.*?\))/g

function upperFirst (string = '') {
return `${string.charAt(0).toUpperCase()}${string.substr(1).toLowerCase()}`
}

function matchSectionTitle (currentTitle) {
if (currentTitle.match(CHANGED_REGEX)) {
return 'Changed'
Expand All @@ -37,6 +32,7 @@ function matchSectionTitle (currentTitle) {
}

function matchesToArray (regex, string) {
/* c8 ignore next */
regex.lastIndex = 0
const result = []
let next = regex.exec(string)
Expand All @@ -54,15 +50,13 @@ module.exports = {
TASK_SECTION_REGEX,
SUBSECTION_TITLE_REGEX,
SUBSECTION_POINT_REGEX,
upperFirst,
matchesToArray,
CHANGED_REGEX,
FIXED_REGEX,
ADDED_REGEX,
REMOVED_REGEX,
REFACTORED_REGEX,
matchSectionTitle,
URL_TASK_REGEX,
EXTRACT_VERSION,
REMOVE_TASK_BADGES,
REMOVE_TASK_LINK
Expand Down
2 changes: 2 additions & 0 deletions helpers/semver.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ function verifyTargetVersion (targetVersion, currentChangelog) {
currentChangelog
)

/* c8 ignore next 2 */
if (!versionMatches || !versionMatches[1]) {
return
}

const lastVersion = versionMatches[1]

/* c8 ignore next 4 */
if (!semver.valid(lastVersion)) {
console.error('Last version is not a valid semver version!', `[${lastVersion}]`)
process.exit(1)
Expand Down
Loading

0 comments on commit fc0698f

Please sign in to comment.