refactor: improve changelog logic (#197)

* refactor: improve changelog logic

Signed-off-by: Ardalan Amini <[email protected]>

* chore: update license comment formatting across all files

Replaced `/*` with `/**` for correct JSDoc-style license comments in all files.
This ensures consistency and compatibility with documentation tools that rely on JSDoc conventions.

Signed-off-by: Ardalan Amini <[email protected]>

* test: add unit tests for inputs

Signed-off-by: Ardalan Amini <[email protected]>

* test: add unit tests for utils

Signed-off-by: Ardalan Amini <[email protected]>

* test: add unit tests for outputs

Signed-off-by: Ardalan Amini <[email protected]>

* test: add unit tests for nodes

Signed-off-by: Ardalan Amini <[email protected]>

* test: add missing unit tests

Signed-off-by: Ardalan Amini <[email protected]>

* chore: address PR comments

Signed-off-by: Ardalan Amini <[email protected]>

* chore: address PR comments

Signed-off-by: Ardalan Amini <[email protected]>

---------

Signed-off-by: Ardalan Amini <[email protected]>
This commit is contained in:
Ardalan Amini authored and GitHub committed 2025-06-07 15:37:31 +03:30
1 parent 3c1177539c
commit 9bd6b8698c
95 files changed
+4377 -298

No files matched your search

+3
View File
@@ -83,6 +83,9 @@ jobs:
- name: Install dependencies
run : pnpm i
- name: Type check unit tests
run : pnpm test:types
- name: Run unit tests
run : pnpm test:coverage
+2
View File
@@ -25,6 +25,8 @@
pnpm lint:fix
pnpm test:types
pnpm build
pnpm package
+28
View File
@@ -0,0 +1,28 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const mocked = jest.createMockFromModule<typeof import("@actions/core")>("@actions/core");
export = mocked;
+38
View File
@@ -0,0 +1,38 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const mocked = jest.createMockFromModule<typeof import("@actions/github")>("@actions/github");
if (!Reflect.getOwnPropertyDescriptor(mocked.context, "repo")) {
Reflect.defineProperty(mocked.context, "repo", {
configurable: true,
get : jest.fn(() => ({
owner: "ardalanamini",
repo : "auto-changelog",
})),
});
}
export = mocked;
+3 -3
View File
@@ -1,4 +1,4 @@
require('./sourcemap-register.js');(()=>{var e={252:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.generateChangelog=generateChangelog;const s=A(4708);const r=A(3820);function trim(e){if(e==null)return e;return e.trim().replace(/ {2,}/g," ")}function unique(e){return[...new Set(e)]}function sortBy(e,t){return e.sort(((e,A)=>e[t].localeCompare(A[t])))}async function generateChangelog(e){const{paginate:t,rest:A}=(0,r.octokit)();const{owner:o,repo:n,url:i}=(0,r.repository)();const a=(0,r.defaultCommitType)();const c=(0,r.commitTypes)();const l=(0,r.includePRLinks)();const g=(0,r.includeCommitLinks)();const u=(0,r.mentionAuthors)();const E=(0,r.useGithubAutolink)();const h=t.iterator(A.repos.listCommits,{per_page:100,sha:(0,r.sha)(),owner:o,repo:n});const d=[];e:for await(const{data:t}of h){for(const A of t){if(A.sha===e)break e;const t=A.commit.message.split("\n")[0];(0,s.debug)(`commit message -> ${t}`);let{type:o,scope:n,description:h,pr:p,flag:C,breaking:Q}=(0,r.parseCommitMessage)(t);if(!h)continue;h=trim(h);C=trim(C);if(C==="ignore")continue;o=c[trim(o??"")]??a;let I=d.find((e=>e.type===o));if(I==null){I={type:o,scopes:[]};d.push(I)}n=trim(n??"");let B=I.scopes.find((e=>e.scope===n));if(B==null){B={scope:n,logs:[]};I.scopes.push(B)}let m=B.logs.find((e=>e.description===h));if(m==null){m={breaking:Q,description:h,references:[]};B.logs.push(m)}const y=[];if(p&&l)y.push(E?`#${p}`:`[#${p}](${i}/issues/${p})`);else if(g)y.push(E?A.sha:`\`[${A.sha}](${i}/commit/${A.sha})\``);const w=A.author?.login;if(w&&u){const e=`by @${w}`;y.push(e);const t=m.references[m.references.length-1];if(t?.endsWith(e)){m.references.push(m.references.pop().replace(e,`& ${y.join(" ")}`));continue}}if(y.length>0)m.references.push(y.join(" "))}}const p=unique(Object.values(c).concat(a));const C=[];for(const e of p){const t=d.find((t=>t.type===e));if(t==null)continue;C.push(`## ${e}`);sortBy(t.scopes,"scope");for(const{scope:e,logs:A}of t.scopes){let t="";if(e.length>0){C.push(`* **${e}:**`);t=" "}for(const{breaking:e,description:s,references:r}of A){let A=`${t}* ${e?"***breaking:*** ":""}${s}`;if(r.length>0)A+=` (${r.join(", ")})`;C.push(A)}}C.push("")}return C.join("\n")}},6351:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.generateFooter=generateFooter;const s=A(6087);const r=A(3820);async function generateFooter(e){const{owner:t,repo:A,url:o}=(0,r.repository)();const n=(0,r.releaseName)();const i=[];if((0,r.mentionNewContributors)()){const{rest:o}=(0,r.octokit)();const{data:a}=await o.repos.generateReleaseNotes({owner:t,repo:A,tag_name:n,previous_tag_name:e});const c=s.marked.lexer(a.body);const l=c.findIndex((e=>e.type==="heading"&&e.text==="New Contributors"));const g=c[l+1];if(g.type==="list")i.push(`## New Contributors\n${g.raw}\n`)}if((0,r.includeCompareLink)()&&e){let t=`${o}/compare/${e}...${n}`;if(!(0,r.useGithubAutolink)()||(0,r.releaseNamePrefix)())t=`\`[${e}...${n}](${o}/compare/${e}...${n})\``;i.push(`**Full Changelog**: ${t}`)}if(i.length>0)i.unshift("");return i.join("\n\n")}},146:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.getTagInfo=getTagInfo;const s=A(3820);async function getTagInfo(){const{paginate:e,rest:t}=(0,s.octokit)();const{owner:A,repo:r}=(0,s.repository)();const o={releaseId:"latest",prerelease:false};let n=null;if((0,s.semver)()){n=(0,s.parseSemVer)();if(n==null)throw new Error(`Expected a semver compatible releaseName, got "${(0,s.releaseName)()}" instead.`);o.prerelease=n.prerelease.length>0;if(o.prerelease)o.releaseId=`${n.prerelease[0]}`}const i=e.iterator(t.repos.listTags,{per_page:100,owner:A,repo:r});e:for await(const{data:e}of i){for(const{name:t,commit:A}of e){if((0,s.sha)()===A.sha)continue;if(n==null){o.previous={name:t,sha:A.sha};break e}const e=(0,s.parseSemVer)(t);if(e==null||n.compare(e)<=0)continue;if(e.prerelease.length>0&&!o.prerelease)continue;o.previous={name:t,sha:A.sha};break e}}return o}},3545:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.booleanInput=booleanInput;const s=A(4708);const r=A(1506);function booleanInput(e,t=true){return(0,r.cache)(e,(()=>(0,s.getBooleanInput)(e,{required:t})))}},1506:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.cache=cache;const A=new Map;function cache(e,t,s=false){if(!A.has(e)||s)A.set(e,t());return A.get(e)}},3820:function(e,t,A){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,A,s){if(s===undefined)s=A;var r=Object.getOwnPropertyDescriptor(t,A);if(!r||("get"in r?!t.__esModule:r.writable||r.configurable)){r={enumerable:true,get:function(){return t[A]}}}Object.defineProperty(e,s,r)}:function(e,t,A,s){if(s===undefined)s=A;e[s]=t[A]});var r=this&&this.__exportStar||function(e,t){for(var A in e)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(t,A))s(t,e,A)};Object.defineProperty(t,"__esModule",{value:true});r(A(6956),t);r(A(273),t);r(A(3545),t);r(A(1506),t);r(A(5020),t);r(ALine truncated
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */;const escape=e=>e.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22");const normalizeLinefeeds=e=>e.replace(/\r?\n|\r/g,"\r\n");const s=[];const r=new Uint8Array([13,10]);g=0;let o=false;for(const[t,n]of e){if(typeof n==="string"){const e=S.encode(A+`; name="${escape(normalizeLinefeeds(t))}"`+`\r\n\r\n${normalizeLinefeeds(n)}\r\n`);s.push(e);g+=e.byteLength}else{const e=S.encode(`${A}; name="${escape(normalizeLinefeeds(t))}"`+(n.name?`; filename="${escape(n.name)}"`:"")+"\r\n"+`Content-Type: ${n.type||"application/octet-stream"}\r\n\r\n`);s.push(e,n,r);if(typeof n.size==="number"){g+=e.byteLength+n.size+r.byteLength}else{o=true}}}const n=S.encode(`--${t}--`);s.push(n);g+=n.byteLength;if(o){g=null}l=e;c=async function*(){for(const e of s){if(e.stream){yield*e.stream()}else{yield e}}};u="multipart/form-data; boundary="+t}else if(n(e)){l=e;g=e.size;if(e.type){u=e.type}}else if(typeof e[Symbol.asyncIterator]==="function"){if(t){throw new TypeError("keepalive")}if(r.isDisturbed(e)||e.locked){throw new TypeError("Response body object should not be disturbed or locked")}s=e instanceof R?e:o(e)}if(typeof l==="string"||r.isBuffer(l)){g=Buffer.byteLength(l)}if(c!=null){let t;s=new R({async start(){t=c(e)[Symbol.asyncIterator]()},async pull(e){const{value:A,done:r}=await t.next();if(r){queueMicrotask((()=>{e.close()}))}else{if(!B(s)){e.enqueue(new Uint8Array(A))}}return e.desiredSize>0},async cancel(e){await t.return()},type:undefined})}const E={stream:s,source:l,length:g};return[E,u]}function safelyExtractBody(e,t=false){if(!R){R=A(3774).ReadableStream}if(e instanceof R){I(!r.isDisturbed(e),"The body has already been consumed.");I(!e.locked,"The stream is locked.")}return extractBody(e,t)}function cloneBody(e){const[t,A]=e.stream.tee();const s=d(A,{transfer:[A]});const[,r]=s.tee();e.stream=t;return{stream:r,length:e.length,source:e.source}}async function*consumeBody(e){if(e){if(m(e)){yield e}else{const t=e.stream;if(r.isDisturbed(t)){throw new TypeError("The body has already been consumed.")}if(t.locked){throw new TypeError("The stream is locked.")}t[Q]=true;yield*t}}}function throwIfAborted(e){if(e.aborted){throw new h("The operation was aborted.","AbortError")}}function bodyMixinMethods(e){const t={blob(){return specConsumeBody(this,(e=>{let t=bodyMimeType(this);if(t==="failure"){t=""}else if(t){t=k(t)}return new p([e],{type:t})}),e)},arrayBuffer(){return specConsumeBody(this,(e=>new Uint8Array(e).buffer),e)},text(){return specConsumeBody(this,utf8DecodeBytes,e)},json(){return specConsumeBody(this,parseJSONFromBytes,e)},async formData(){E.brandCheck(this,e);throwIfAborted(this[u]);const t=this.headers.get("Content-Type");if(/multipart\/form-data/.test(t)){const e={};for(const[t,A]of this.headers)e[t.toLowerCase()]=A;const t=new g;let A;try{A=new s({headers:e,preservePath:true})}catch(e){throw new h(`${e}`,"AbortError")}A.on("field",((e,A)=>{t.append(e,A)}));A.on("file",((e,A,s,r,o)=>{const n=[];if(r==="base64"||r.toLowerCase()==="base64"){let r="";A.on("data",(e=>{r+=e.toString().replace(/[\r\n]/gm,"");const t=r.length-r.length%4;n.push(Buffer.from(r.slice(0,t),"base64"));r=r.slice(t)}));A.on("end",(()=>{n.push(Buffer.from(r,"base64"));t.append(e,new D(n,s,{type:o}))}))}else{A.on("data",(e=>{n.push(e)}));A.on("end",(()=>{t.append(e,new D(n,s,{type:o}))}))}}));const r=new Promise(((e,t)=>{A.on("finish",e);A.on("error",(e=>t(new TypeError(e))))}));if(this.body!==null)for await(const e of consumeBody(this[u].body))A.write(e);A.end();await r;return t}else if(/application\/x-www-form-urlencoded/.test(t)){let e;try{let t="";const A=new TextDecoder("utf-8",{ignoreBOM:true});for await(const e of consumeBody(this[u].body)){if(!m(e)){throw new TypeError("Expected Uint8Array chunk")}t+=A.decode(e,{stream:true})}t+=A.decode();e=new URLSearchParams(t)}catch(e){throw Object.assign(new TypeError,{cause:e})}const t=new g;for(const[A,s]of e){t.append(A,s)}return t}else{await Promise.resolve();throwIfAborted(this[u]);throw E.errors.exception({header:`${e.name}.formData`,message:"Could not parse content as FormData."})}}};return t}function mixinBody(e){Object.assign(e.prototype,bodyMixinMethods(e))}async function specConsumeBody(e,t,A){E.brandCheck(e,A);throwIfAborted(e[u]);if(bodyUnusable(e[u].body)){throw new TypeError("Body is unusable")}const s=c();const errorSteps=e=>s.reject(e);const successSteps=e=>{try{s.resolve(t(e))}catch(e){errorSteps(e)}};if(e[u].body==null){successSteps(new Uint8Array);return s.promise}await l(e[u].body,successSteps,errorSteps);return s.promise}function bodyUnusable(e){return e!=null&&(e.stream.locked||r.isDisturbed(e.stream))}function utf8DecodeBytes(e){if(e.length===0){return""}if(e[0]===239&&e[1]===187&&e[2]===191){e=e.subarray(3)}const t=T.decode(e);return t}function parseJSONFromBytes(e){return JSON.parse(utf8DecodeBytes(e))}function bodyMimeType(e){const{headersList:t}=e[u];const A=t.get("content-Line truncated
/*! ws. MIT License. Einar Otto Stangvik <[email protected]> */o[r-4]=this.maskKey[0];o[r-3]=this.maskKey[1];o[r-2]=this.maskKey[2];o[r-1]=this.maskKey[3];o[1]=A;if(A===126){o.writeUInt16BE(t,2)}else if(A===127){o[2]=o[3]=0;o.writeUIntBE(t,4,6)}o[1]|=128;for(let e=0;e<t;e++){o[r+e]=this.frameData[e]^this.maskKey[e%4]}return o}}e.exports={WebsocketFrameSend:WebsocketFrameSend}},2287:(e,t,A)=>{"use strict";const{Writable:s}=A(2203);const r=A(1637);const{parserStates:o,opcodes:n,states:i,emptyBuffer:a}=A(9189);const{kReadyState:c,kSentClose:l,kResponse:g,kReceivedClose:u}=A(7265);const{isValidStatusCode:E,failWebsocketConnection:h,websocketMessageReceived:d}=A(7386);const{WebsocketFrameSend:p}=A(3841);const C={};C.ping=r.channel("undici:websocket:ping");C.pong=r.channel("undici:websocket:pong");class ByteParser extends s{#n=[];#i=0;#a=o.INFO;#c={};#l=[];constructor(e){super();this.ws=e}_write(e,t,A){this.#n.push(e);this.#i+=e.length;this.run(A)}run(e){while(true){if(this.#a===o.INFO){if(this.#i<2){return e()}const t=this.consume(2);this.#c.fin=(t[0]&128)!==0;this.#c.opcode=t[0]&15;this.#c.originalOpcode??=this.#c.opcode;this.#c.fragmented=!this.#c.fin&&this.#c.opcode!==n.CONTINUATION;if(this.#c.fragmented&&this.#c.opcode!==n.BINARY&&this.#c.opcode!==n.TEXT){h(this.ws,"Invalid frame type was fragmented.");return}const A=t[1]&127;if(A<=125){this.#c.payloadLength=A;this.#a=o.READ_DATA}else if(A===126){this.#a=o.PAYLOADLENGTH_16}else if(A===127){this.#a=o.PAYLOADLENGTH_64}if(this.#c.fragmented&&A>125){h(this.ws,"Fragmented frame exceeded 125 bytes.");return}else if((this.#c.opcode===n.PING||this.#c.opcode===n.PONG||this.#c.opcode===n.CLOSE)&&A>125){h(this.ws,"Payload length for control frame exceeded 125 bytes.");return}else if(this.#c.opcode===n.CLOSE){if(A===1){h(this.ws,"Received close frame with a 1-byte body.");return}const e=this.consume(A);this.#c.closeInfo=this.parseCloseBody(false,e);if(!this.ws[l]){const e=Buffer.allocUnsafe(2);e.writeUInt16BE(this.#c.closeInfo.code,0);const t=new p(e);this.ws[g].socket.write(t.createFrame(n.CLOSE),(e=>{if(!e){this.ws[l]=true}}))}this.ws[c]=i.CLOSING;this.ws[u]=true;this.end();return}else if(this.#c.opcode===n.PING){const t=this.consume(A);if(!this.ws[u]){const e=new p(t);this.ws[g].socket.write(e.createFrame(n.PONG));if(C.ping.hasSubscribers){C.ping.publish({payload:t})}}this.#a=o.INFO;if(this.#i>0){continue}else{e();return}}else if(this.#c.opcode===n.PONG){const t=this.consume(A);if(C.pong.hasSubscribers){C.pong.publish({payload:t})}if(this.#i>0){continue}else{e();return}}}else if(this.#a===o.PAYLOADLENGTH_16){if(this.#i<2){return e()}const t=this.consume(2);this.#c.payloadLength=t.readUInt16BE(0);this.#a=o.READ_DATA}else if(this.#a===o.PAYLOADLENGTH_64){if(this.#i<8){return e()}const t=this.consume(8);const A=t.readUInt32BE(0);if(A>2**31-1){h(this.ws,"Received payload length > 2^31 bytes.");return}const s=t.readUInt32BE(4);this.#c.payloadLength=(A<<8)+s;this.#a=o.READ_DATA}else if(this.#a===o.READ_DATA){if(this.#i<this.#c.payloadLength){return e()}else if(this.#i>=this.#c.payloadLength){const e=this.consume(this.#c.payloadLength);this.#l.push(e);if(!this.#c.fragmented||this.#c.fin&&this.#c.opcode===n.CONTINUATION){const e=Buffer.concat(this.#l);d(this.ws,this.#c.originalOpcode,e);this.#c={};this.#l.length=0}this.#a=o.INFO}}if(this.#i>0){continue}else{e();break}}}consume(e){if(e>this.#i){return null}else if(e===0){return a}if(this.#n[0].length===e){this.#i-=this.#n[0].length;return this.#n.shift()}const t=Buffer.allocUnsafe(e);let A=0;while(A!==e){const s=this.#n[0];const{length:r}=s;if(r+A===e){t.set(this.#n.shift(),A);break}else if(r+A>e){t.set(s.subarray(0,e-A),A);this.#n[0]=s.subarray(e-A);break}else{t.set(this.#n.shift(),A);A+=s.length}}this.#i-=e;return t}parseCloseBody(e,t){let A;if(t.length>=2){A=t.readUInt16BE(0)}if(e){if(!E(A)){return null}return{code:A}}let s=t.subarray(2);if(s[0]===239&&s[1]===187&&s[2]===191){s=s.subarray(3)}if(A!==undefined&&!E(A)){return null}try{s=new TextDecoder("utf-8",{fatal:true}).decode(s)}catch{return null}return{code:A,reason:s}}get closingInfo(){return this.#c.closeInfo}}e.exports={ByteParser:ByteParser}},7265:e=>{"use strict";e.exports={kWebSocketURL:Symbol("url"),kReadyState:Symbol("ready state"),kController:Symbol("controller"),kResponse:Symbol("response"),kBinaryType:Symbol("binary type"),kSentClose:Symbol("sent close"),kReceivedClose:Symbol("received close"),kByteParser:Symbol("byte parser")}},7386:(e,t,A)=>{"use strict";const{kReadyState:s,kController:r,kResponse:o,kBinaryType:n,kWebSocketURL:i}=A(7265);const{states:a,opcodes:c}=A(9189);const{MessageEvent:l,ErrorEvent:g}=A(9779);function isEstablished(e){return e[s]===a.OPEN}function isClosing(e){return e[s]===a.CLOSING}function isClosed(e){return e[s]===a.CLOSED}function fireEvent(e,t,A=Event,s){const r=new A(e,s);t.dispatchEvent(r)}function websocketMessageReceived(e,t,A){if(e[s]!==a.OPEN){return}let r;if(t===c.TEXT){try{r=new TextDecoder("utf-8",{fatal:true}).decode(A)Line truncated
require('./sourcemap-register.js');(()=>{var e={252:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.generateChangelog=generateChangelog;const s=A(4708);const r=A(9456);const o=A(3820);async function generateChangelog(e){const{owner:t,repo:A}=(0,o.repository)();const n=new r.ChangelogNode;for await(const r of(0,o.iterateCommits)(t,A,e)){const e=r.commit.message.split("\n")[0];(0,s.debug)(`commit message -> ${e}`);let{type:t,scope:A,description:i,pr:a,flag:c,breaking:l}=(0,o.parseCommitMessage)(e);i=(0,o.trim)(i);if(!i)continue;c=(0,o.trim)(c);if(c==="ignore")continue;const g=n.addType(t);const u=g.addScope(A);const E=u.addCommit(i,l);const h=E.addAuthor(r.author?.login);h.addReference(r.sha,a)}const i=n.print();if(i)return`${i}\n`;return""}},6351:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.generateFooter=generateFooter;const s=A(6087);const r=A(8642);const o=A(3820);async function generateFooter(e){const{owner:t,repo:A,url:n}=(0,o.repository)();const i=(0,r.releaseName)();const a=[];if((0,r.mentionNewContributors)()){const{rest:r}=(0,o.octokit)();const{data:n}=await r.repos.generateReleaseNotes({owner:t,repo:A,tag_name:i,previous_tag_name:e});const c=s.marked.lexer(n.body);const l=c.findIndex((e=>e.type==="heading"&&e.text==="New Contributors"));const g=c[l+1];if(g.type==="list")a.push(`## New Contributors\n${g.raw}\n`)}if((0,r.includeCompareLink)()&&e){let t=`${n}/compare/${e}...${i}`;if(!(0,r.useGitHubAutolink)()||(0,r.releaseNamePrefix)())t=`\`[${e}...${i}](${n}/compare/${e}...${i})\``;a.push(`**Full Changelog**: ${t}`)}if(a.length>0)a.unshift("");return a.join("\n\n")}},3139:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.generate=generate;const s=A(252);const r=A(6351);const o=A(6027);const n=A(146);async function generate(){const{prerelease:e,releaseId:t,previous:A}=await(0,n.getTagInfo)();(0,o.setPrerelease)(e);(0,o.setReleaseId)(t);let i=await(0,s.generateChangelog)(A?.sha);i+=await(0,r.generateFooter)(A?.name);(0,o.setChangelog)(i)}},8453:function(e,t,A){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.commitTypes=commitTypes;const r=s(A(5625));const o=A(5020);function commitTypes(){return(0,o.input)("commit-types",(e=>r.default.parse(e)))}},2878:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.defaultCommitType=defaultCommitType;const s=A(5020);function defaultCommitType(){return(0,s.input)("default-commit-type")}},5595:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.gitHubToken=gitHubToken;const s=A(5020);function gitHubToken(){return(0,s.input)("github-token")}},1822:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.includeCommitLinks=includeCommitLinks;const s=A(3545);function includeCommitLinks(){return(0,s.booleanInput)("include-commit-links")}},1589:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.includeCompareLink=includeCompareLink;const s=A(3545);function includeCompareLink(){return(0,s.booleanInput)("include-compare-link")}},2065:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.includePRLinks=includePRLinks;const s=A(3545);function includePRLinks(){return(0,s.booleanInput)("include-pr-links")}},8642:function(e,t,A){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,A,s){if(s===undefined)s=A;var r=Object.getOwnPropertyDescriptor(t,A);if(!r||("get"in r?!t.__esModule:r.writable||r.configurable)){r={enumerable:true,get:function(){return t[A]}}}Object.defineProperty(e,s,r)}:function(e,t,A,s){if(s===undefined)s=A;e[s]=t[A]});var r=this&&this.__exportStar||function(e,t){for(var A in e)if(A!=="default"&&!Object.prototype.hasOwnProperty.call(t,A))s(t,e,A)};Object.defineProperty(t,"__esModule",{value:true});r(A(8453),t);r(A(2878),t);r(A(5595),t);r(A(1589),t);r(A(1822),t);r(A(2065),t);r(A(3317),t);r(A(9530),t);r(A(7211),t);r(A(4876),t);r(A(6340),t);r(A(4593),t)},3317:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.mentionAuthors=mentionAuthors;const s=A(3545);function mentionAuthors(){return(0,s.booleanInput)("mention-authors")}},9530:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.mentionNewContributors=mentionNewContributors;const s=A(3545);function mentionNewContributors(){return(0,s.booleanInput)("mention-new-contributors")}},4876:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.releaseNamePrefix=releaseNamePrefix;const s=A(5020);function releaseNamePrefix(){return(0,s.input)("release-name-prefix",false)}},7211:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.releaseName=releaseName;const s=A(5020);function releaseName(){return(0,s.input)("release-name")}},6340:(e,t,A)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.semver=sLine truncated
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */;const escape=e=>e.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22");const normalizeLinefeeds=e=>e.replace(/\r?\n|\r/g,"\r\n");const s=[];const r=new Uint8Array([13,10]);g=0;let o=false;for(const[t,n]of e){if(typeof n==="string"){const e=S.encode(A+`; name="${escape(normalizeLinefeeds(t))}"`+`\r\n\r\n${normalizeLinefeeds(n)}\r\n`);s.push(e);g+=e.byteLength}else{const e=S.encode(`${A}; name="${escape(normalizeLinefeeds(t))}"`+(n.name?`; filename="${escape(n.name)}"`:"")+"\r\n"+`Content-Type: ${n.type||"application/octet-stream"}\r\n\r\n`);s.push(e,n,r);if(typeof n.size==="number"){g+=e.byteLength+n.size+r.byteLength}else{o=true}}}const n=S.encode(`--${t}--`);s.push(n);g+=n.byteLength;if(o){g=null}l=e;c=async function*(){for(const e of s){if(e.stream){yield*e.stream()}else{yield e}}};u="multipart/form-data; boundary="+t}else if(n(e)){l=e;g=e.size;if(e.type){u=e.type}}else if(typeof e[Symbol.asyncIterator]==="function"){if(t){throw new TypeError("keepalive")}if(r.isDisturbed(e)||e.locked){throw new TypeError("Response body object should not be disturbed or locked")}s=e instanceof R?e:o(e)}if(typeof l==="string"||r.isBuffer(l)){g=Buffer.byteLength(l)}if(c!=null){let t;s=new R({async start(){t=c(e)[Symbol.asyncIterator]()},async pull(e){const{value:A,done:r}=await t.next();if(r){queueMicrotask((()=>{e.close()}))}else{if(!B(s)){e.enqueue(new Uint8Array(A))}}return e.desiredSize>0},async cancel(e){await t.return()},type:undefined})}const E={stream:s,source:l,length:g};return[E,u]}function safelyExtractBody(e,t=false){if(!R){R=A(3774).ReadableStream}if(e instanceof R){I(!r.isDisturbed(e),"The body has already been consumed.");I(!e.locked,"The stream is locked.")}return extractBody(e,t)}function cloneBody(e){const[t,A]=e.stream.tee();const s=d(A,{transfer:[A]});const[,r]=s.tee();e.stream=t;return{stream:r,length:e.length,source:e.source}}async function*consumeBody(e){if(e){if(m(e)){yield e}else{const t=e.stream;if(r.isDisturbed(t)){throw new TypeError("The body has already been consumed.")}if(t.locked){throw new TypeError("The stream is locked.")}t[Q]=true;yield*t}}}function throwIfAborted(e){if(e.aborted){throw new h("The operation was aborted.","AbortError")}}function bodyMixinMethods(e){const t={blob(){return specConsumeBody(this,(e=>{let t=bodyMimeType(this);if(t==="failure"){t=""}else if(t){t=k(t)}return new p([e],{type:t})}),e)},arrayBuffer(){return specConsumeBody(this,(e=>new Uint8Array(e).buffer),e)},text(){return specConsumeBody(this,utf8DecodeBytes,e)},json(){return specConsumeBody(this,parseJSONFromBytes,e)},async formData(){E.brandCheck(this,e);throwIfAborted(this[u]);const t=this.headers.get("Content-Type");if(/multipart\/form-data/.test(t)){const e={};for(const[t,A]of this.headers)e[t.toLowerCase()]=A;const t=new g;let A;try{A=new s({headers:e,preservePath:true})}catch(e){throw new h(`${e}`,"AbortError")}A.on("field",((e,A)=>{t.append(e,A)}));A.on("file",((e,A,s,r,o)=>{const n=[];if(r==="base64"||r.toLowerCase()==="base64"){let r="";A.on("data",(e=>{r+=e.toString().replace(/[\r\n]/gm,"");const t=r.length-r.length%4;n.push(Buffer.from(r.slice(0,t),"base64"));r=r.slice(t)}));A.on("end",(()=>{n.push(Buffer.from(r,"base64"));t.append(e,new D(n,s,{type:o}))}))}else{A.on("data",(e=>{n.push(e)}));A.on("end",(()=>{t.append(e,new D(n,s,{type:o}))}))}}));const r=new Promise(((e,t)=>{A.on("finish",e);A.on("error",(e=>t(new TypeError(e))))}));if(this.body!==null)for await(const e of consumeBody(this[u].body))A.write(e);A.end();await r;return t}else if(/application\/x-www-form-urlencoded/.test(t)){let e;try{let t="";const A=new TextDecoder("utf-8",{ignoreBOM:true});for await(const e of consumeBody(this[u].body)){if(!m(e)){throw new TypeError("Expected Uint8Array chunk")}t+=A.decode(e,{stream:true})}t+=A.decode();e=new URLSearchParams(t)}catch(e){throw Object.assign(new TypeError,{cause:e})}const t=new g;for(const[A,s]of e){t.append(A,s)}return t}else{await Promise.resolve();throwIfAborted(this[u]);throw E.errors.exception({header:`${e.name}.formData`,message:"Could not parse content as FormData."})}}};return t}function mixinBody(e){Object.assign(e.prototype,bodyMixinMethods(e))}async function specConsumeBody(e,t,A){E.brandCheck(e,A);throwIfAborted(e[u]);if(bodyUnusable(e[u].body)){throw new TypeError("Body is unusable")}const s=c();const errorSteps=e=>s.reject(e);const successSteps=e=>{try{s.resolve(t(e))}catch(e){errorSteps(e)}};if(e[u].body==null){successSteps(new Uint8Array);return s.promise}await l(e[u].body,successSteps,errorSteps);return s.promise}function bodyUnusable(e){return e!=null&&(e.stream.locked||r.isDisturbed(e.stream))}function utf8DecodeBytes(e){if(e.length===0){return""}if(e[0]===239&&e[1]===187&&e[2]===191){e=e.subarray(3)}const t=T.decode(e);return t}function parseJSONFromBytes(e){return JSON.parse(utf8DecodeBytes(e))}function bodyMimeType(e){const{headersList:t}=e[u];const A=t.get("content-Line truncated
/*! ws. MIT License. Einar Otto Stangvik <[email protected]> */o[r-4]=this.maskKey[0];o[r-3]=this.maskKey[1];o[r-2]=this.maskKey[2];o[r-1]=this.maskKey[3];o[1]=A;if(A===126){o.writeUInt16BE(t,2)}else if(A===127){o[2]=o[3]=0;o.writeUIntBE(t,4,6)}o[1]|=128;for(let e=0;e<t;e++){o[r+e]=this.frameData[e]^this.maskKey[e%4]}return o}}e.exports={WebsocketFrameSend:WebsocketFrameSend}},2287:(e,t,A)=>{"use strict";const{Writable:s}=A(2203);const r=A(1637);const{parserStates:o,opcodes:n,states:i,emptyBuffer:a}=A(9189);const{kReadyState:c,kSentClose:l,kResponse:g,kReceivedClose:u}=A(7265);const{isValidStatusCode:E,failWebsocketConnection:h,websocketMessageReceived:d}=A(7386);const{WebsocketFrameSend:p}=A(3841);const C={};C.ping=r.channel("undici:websocket:ping");C.pong=r.channel("undici:websocket:pong");class ByteParser extends s{#n=[];#i=0;#a=o.INFO;#c={};#l=[];constructor(e){super();this.ws=e}_write(e,t,A){this.#n.push(e);this.#i+=e.length;this.run(A)}run(e){while(true){if(this.#a===o.INFO){if(this.#i<2){return e()}const t=this.consume(2);this.#c.fin=(t[0]&128)!==0;this.#c.opcode=t[0]&15;this.#c.originalOpcode??=this.#c.opcode;this.#c.fragmented=!this.#c.fin&&this.#c.opcode!==n.CONTINUATION;if(this.#c.fragmented&&this.#c.opcode!==n.BINARY&&this.#c.opcode!==n.TEXT){h(this.ws,"Invalid frame type was fragmented.");return}const A=t[1]&127;if(A<=125){this.#c.payloadLength=A;this.#a=o.READ_DATA}else if(A===126){this.#a=o.PAYLOADLENGTH_16}else if(A===127){this.#a=o.PAYLOADLENGTH_64}if(this.#c.fragmented&&A>125){h(this.ws,"Fragmented frame exceeded 125 bytes.");return}else if((this.#c.opcode===n.PING||this.#c.opcode===n.PONG||this.#c.opcode===n.CLOSE)&&A>125){h(this.ws,"Payload length for control frame exceeded 125 bytes.");return}else if(this.#c.opcode===n.CLOSE){if(A===1){h(this.ws,"Received close frame with a 1-byte body.");return}const e=this.consume(A);this.#c.closeInfo=this.parseCloseBody(false,e);if(!this.ws[l]){const e=Buffer.allocUnsafe(2);e.writeUInt16BE(this.#c.closeInfo.code,0);const t=new p(e);this.ws[g].socket.write(t.createFrame(n.CLOSE),(e=>{if(!e){this.ws[l]=true}}))}this.ws[c]=i.CLOSING;this.ws[u]=true;this.end();return}else if(this.#c.opcode===n.PING){const t=this.consume(A);if(!this.ws[u]){const e=new p(t);this.ws[g].socket.write(e.createFrame(n.PONG));if(C.ping.hasSubscribers){C.ping.publish({payload:t})}}this.#a=o.INFO;if(this.#i>0){continue}else{e();return}}else if(this.#c.opcode===n.PONG){const t=this.consume(A);if(C.pong.hasSubscribers){C.pong.publish({payload:t})}if(this.#i>0){continue}else{e();return}}}else if(this.#a===o.PAYLOADLENGTH_16){if(this.#i<2){return e()}const t=this.consume(2);this.#c.payloadLength=t.readUInt16BE(0);this.#a=o.READ_DATA}else if(this.#a===o.PAYLOADLENGTH_64){if(this.#i<8){return e()}const t=this.consume(8);const A=t.readUInt32BE(0);if(A>2**31-1){h(this.ws,"Received payload length > 2^31 bytes.");return}const s=t.readUInt32BE(4);this.#c.payloadLength=(A<<8)+s;this.#a=o.READ_DATA}else if(this.#a===o.READ_DATA){if(this.#i<this.#c.payloadLength){return e()}else if(this.#i>=this.#c.payloadLength){const e=this.consume(this.#c.payloadLength);this.#l.push(e);if(!this.#c.fragmented||this.#c.fin&&this.#c.opcode===n.CONTINUATION){const e=Buffer.concat(this.#l);d(this.ws,this.#c.originalOpcode,e);this.#c={};this.#l.length=0}this.#a=o.INFO}}if(this.#i>0){continue}else{e();break}}}consume(e){if(e>this.#i){return null}else if(e===0){return a}if(this.#n[0].length===e){this.#i-=this.#n[0].length;return this.#n.shift()}const t=Buffer.allocUnsafe(e);let A=0;while(A!==e){const s=this.#n[0];const{length:r}=s;if(r+A===e){t.set(this.#n.shift(),A);break}else if(r+A>e){t.set(s.subarray(0,e-A),A);this.#n[0]=s.subarray(e-A);break}else{t.set(this.#n.shift(),A);A+=s.length}}this.#i-=e;return t}parseCloseBody(e,t){let A;if(t.length>=2){A=t.readUInt16BE(0)}if(e){if(!E(A)){return null}return{code:A}}let s=t.subarray(2);if(s[0]===239&&s[1]===187&&s[2]===191){s=s.subarray(3)}if(A!==undefined&&!E(A)){return null}try{s=new TextDecoder("utf-8",{fatal:true}).decode(s)}catch{return null}return{code:A,reason:s}}get closingInfo(){return this.#c.closeInfo}}e.exports={ByteParser:ByteParser}},7265:e=>{"use strict";e.exports={kWebSocketURL:Symbol("url"),kReadyState:Symbol("ready state"),kController:Symbol("controller"),kResponse:Symbol("response"),kBinaryType:Symbol("binary type"),kSentClose:Symbol("sent close"),kReceivedClose:Symbol("received close"),kByteParser:Symbol("byte parser")}},7386:(e,t,A)=>{"use strict";const{kReadyState:s,kController:r,kResponse:o,kBinaryType:n,kWebSocketURL:i}=A(7265);const{states:a,opcodes:c}=A(9189);const{MessageEvent:l,ErrorEvent:g}=A(9779);function isEstablished(e){return e[s]===a.OPEN}function isClosing(e){return e[s]===a.CLOSING}function isClosed(e){return e[s]===a.CLOSED}function fireEvent(e,t,A=Event,s){const r=new A(e,s);t.dispatchEvent(r)}function websocketMessageReceived(e,t,A){if(e[s]!==a.OPEN){return}let r;if(t===c.TEXT){try{r=new TextDecoder("utf-8",{fatal:true}).decode(A)Line truncated
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"index.js","names":["Object","defineProperty","exports","value","generateChangelog","core_1","__webpack_require__","index_js_1","trim","replace","unique","Set","sortBy","array","property","sort","a","b","localeCompare","async","lastSha","paginate","rest","octokit","owner","repo","url","repository","defaultType","defaultCommitType","typeMap","commitTypes","shouldIncludePRLinks","includePRLinks","shouldIncludeCommitLinks","includeCommitLinks","shouldMentionAuthors","mentionAuthors","shouldUseGithubAutolink","useGithubAutolink","iterator","repos","listCommits","per_page","sha","typeGroups","paginator","data","commit","message","split","debug","type","scope","description","pr","flag","breaking","parseCommitMessage","typeGroup","find","record","scopes","push","scopeGroup","logs","log","references","reference","username","author","login","mention","lastReference","length","endsWith","pop","join","types","values","concat","changelog","prefix","line","generateFooter","marked_1","previousTagName","tagName","releaseName","footer","mentionNewContributors","generateReleaseNotes","tag_name","previous_tag_name","tokens","marked","lexer","body","index","findIndex","markdownToken","text","raw","includeCompareLink","link","releaseNamePrefix","unshift","getTagInfo","info","releaseId","prerelease","semVer","semver","parseSemVer","Error","listTags","loop","name","previous","version","compare","booleanInput","cache_js_1","required","cache","getBooleanInput","CACHE","Map","key","overwrite","has","set","get","__createBinding","this","create","o","m","k","k2","undefined","desc","getOwnPropertyDescriptor","__esModule","writable","configurable","enumerable","__exportStar","p","prototype","hasOwnProperty","call","input","parser","getInput","__importDefault","mod","default","yaml_1","input_js_1","parse","boolean_input_js_1","token","github_1","getOctokit","output","setOutput","setChangelog","output_js_1","setPrerelease","setReleaseId","REGEX","exec","groups","semver_1","RegExp","includePrerelease","serverUrl","context","__setModuleDefault","v","__importStar","result","issue","issueCommand","os","utils_1","command","properties","cmd","Command","process","stdout","write","toString","EOL","CMD_STRING","constructor","cmdStr","keys","first","val","escapeProperty","escapeData","s","toCommandValue","__awaiter","thisArg","_arguments","P","generator","adopt","resolve","Promise","reject","fulfilled","step","next","e","rejected","done","then","apply","platform","toPlatformPath","toWin32Path","toPosixPath","markdownSummary","summary","getIDToken","getState","saveState","group","endGroup","startGroup","notice","warning","error","isDebug","setFailed","setCommandEcho","getMultilineInput","addPath","setSecret","exportVariable","ExitCode","command_1","file_command_1","path","oidc_utils_1","convertedVal","env","filePath","issueFileCommand","prepareKeyValueMessage","secret","inputPath","delimiter","options","toUpperCase","trimWhitespace","inputs","filter","x","map","trueValue","falseValue","includes","TypeError","enabled","exitCode","Failure","toCommandProperties","fn","aud","OidcClient","summary_1","summary_2","path_utils_1","crypto","fs","existsSync","appendFileSync","encoding","randomUUID","convertedValue","http_client_1","auth_1","createHttpClient","allowRetry","maxRetry","requestOptions","allowRetries","maxRetries","HttpClient","BearerCredentialHandler","getRequestToken","getIDTokenUrl","runtimeUrl","getCall","id_token_url","_a","httpclient","res","getJson","catch","statusCode","id_token","audience","encodedAudience","encodeURIComponent","pth","sep","getDetails","isLinux","isMacOS","isWindows","arch","os_1","getWindowsInfo","getExecOutput","silent","getMacOsInfo","_b","_c","_d","match","getLinuxInfo","assign","SUMMARY_DOCS_URL","SUMMARY_ENV_VAR","fs_1","access","appendFile","writeFile","promises","Summary","_buffer","_filePath","pathFromEnv","constants","R_OK","W_OK","wrap","tag","content","attrs","htmlAttrs","entries","writeFunc","emptyBuffer","clear","stringify","isEmptyBuffer","addRaw","addEOL","addCodeBlock","code","lang","element","addList","items","ordered","listItems","item","addTable","rows","tableBody","row","cells","cell","header","colspan","rowspan","addDetails","label","addImage","src","alt","width","height","addHeading","level","allowedTag","addSeparator","addBreak","addQuote","cite","addLink","href","_summary","String","JSON","annotationProperties","title","file","startLine","endLine","col","startColumn","endColumn","string_decoder_1","tr","commandLine","args","commandArgs","argStringToArray","toolPath","slice","runner","ToolRunner","stderr","stdoutDecoder","StringDecoder","stderrDecoder","originalStdoutListener","listeners","originalStdErrListener","stdErrListener","stdOutListener","end","events","child","io","ioUtil","timers_1","IS_WINDOWS","EventEmitter","super","_debug","_getCommandString","noPrefix","_getSpawnFileName","_getSpawnArgs","_isCmdFile","windowsVerbatimArguments","_windowsQuoteCmdArg","_processLineLine truncated
{"version":3,"file":"index.js","names":["Object","defineProperty","exports","value","generateChangelog","core_1","__webpack_require__","index_js_1","index_js_2","async","lastSha","owner","repo","repository","changelogNode","ChangelogNode","commit","iterateCommits","message","split","debug","type","scope","description","pr","flag","breaking","parseCommitMessage","trim","typeNode","addType","scopeNode","addScope","commitNote","addCommit","authorNode","addAuthor","author","login","addReference","sha","changelog","print","generateFooter","marked_1","previousTagName","url","tagName","releaseName","footer","mentionNewContributors","rest","octokit","data","repos","generateReleaseNotes","tag_name","previous_tag_name","tokens","marked","lexer","body","index","findIndex","markdownToken","text","push","raw","includeCompareLink","link","useGitHubAutolink","releaseNamePrefix","length","unshift","join","generate","changelog_js_1","footer_js_1","tag_js_1","prerelease","releaseId","previous","getTagInfo","setPrerelease","setReleaseId","name","setChangelog","__importDefault","this","mod","__esModule","default","commitTypes","yaml_1","input_js_1","input","parse","defaultCommitType","gitHubToken","includeCommitLinks","boolean_input_js_1","booleanInput","includePRLinks","__createBinding","create","o","m","k","k2","undefined","desc","getOwnPropertyDescriptor","writable","configurable","enumerable","get","__exportStar","p","prototype","hasOwnProperty","call","mentionAuthors","semver","node_js_1","type_js_1","Node","defaultType","typeMap","types","Map","has","TypeNode","set","prefix","size","acceptedTypes","Set","values","concat","parts","key","printedType","CommitAuthorNode","commit_hash_js_1","pull_request_js_1","username","shouldMentionAuthor","references","constructor","super","reference","PullRequestNode","CommitHashNode","existingRef","serverUrl","shouldUseGithubAutolink","printedReferences","printedReference","shouldNotPrint","slice","CommitNode","commit_author_js_1","authors","previousAuthor","printedAuthor","github_1","context","ScopeNode","commit_js_1","commits","commitNode","scope_js_1","scopes","scopeKeys","keys","sort","a","b","localeCompare","printedScope","output","paginate","info","semVer","parseSemVer","Error","iterator","listTags","per_page","loop","version","compare","cache_js_1","required","cache","getBooleanInput","clearCache","CACHE","overwrite","clear","octokit_js_1","sha_js_1","from","listCommits","parser","getInput","getOctokit","setOutput","REGEX","exec","groups","semver_1","replace","RegExp","includePrerelease","__setModuleDefault","v","__importStar","result","issue","issueCommand","os","utils_1","command","properties","cmd","Command","process","stdout","write","toString","EOL","CMD_STRING","cmdStr","first","val","escapeProperty","escapeData","s","toCommandValue","__awaiter","thisArg","_arguments","P","generator","adopt","resolve","Promise","reject","fulfilled","step","next","e","rejected","done","then","apply","platform","toPlatformPath","toWin32Path","toPosixPath","markdownSummary","summary","getIDToken","getState","saveState","group","endGroup","startGroup","notice","warning","error","isDebug","setFailed","setCommandEcho","getMultilineInput","addPath","setSecret","exportVariable","ExitCode","command_1","file_command_1","path","oidc_utils_1","convertedVal","env","filePath","issueFileCommand","prepareKeyValueMessage","secret","inputPath","delimiter","options","toUpperCase","trimWhitespace","inputs","filter","x","map","trueValue","falseValue","includes","TypeError","enabled","exitCode","Failure","toCommandProperties","fn","aud","OidcClient","summary_1","summary_2","path_utils_1","crypto","fs","existsSync","appendFileSync","encoding","randomUUID","convertedValue","http_client_1","auth_1","createHttpClient","allowRetry","maxRetry","requestOptions","allowRetries","maxRetries","HttpClient","BearerCredentialHandler","getRequestToken","token","getIDTokenUrl","runtimeUrl","getCall","id_token_url","_a","httpclient","res","getJson","catch","statusCode","id_token","audience","encodedAudience","encodeURIComponent","pth","sep","getDetails","isLinux","isMacOS","isWindows","arch","os_1","getWindowsInfo","getExecOutput","silent","getMacOsInfo","_b","_c","_d","match","getLinuxInfo","assign","SUMMARY_DOCS_URL","SUMMARY_ENV_VAR","fs_1","access","appendFile","writeFile","promises","Summary","_buffer","_filePath","pathFromEnv","constants","R_OK","W_OK","wrap","tag","content","attrs","htmlAttrs","entries","writeFunc","emptyBuffer","stringify","isEmptyBuffer","addRaw","addEOL","addCodeBlock","code","lang","element","addList","items","ordered","listItems","item","addTable","rows","tableBody","row","cells","cell","header","colspan","rowspan","addDetails","label","addImage","src","alt","width","height","addHeading","level","allowedTag","addSeparator","addBreak","addQuote","cite","addLink","href","_summary","String","JSON","annotationProperties","title","file","line","startLine","endLine","col","startColumn","endColumn","stringLine truncated
+1 -2
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,7 +20,6 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { type UserConfig } from "@commitlint/types";
+3 -4
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2024-2025 Ardalan Amini
@@ -20,7 +20,6 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
/**
@@ -161,10 +160,10 @@ export default {
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
setupFiles: ["<rootDir>/tests/jest/mocks.ts"],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
setupFilesAfterEnv: ["<rootDir>/tests/jest/lifecycles.ts"],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
+3 -1
View File
@@ -32,7 +32,8 @@
"package": "ncc build --out action --minify --source-map --license licenses.txt",
"all": "pnpm lint:fix && pnpm build && pnpm package",
"test": "node --expose-gc node_modules/jest/bin/jest -c jest.config.ts",
"test:coverage": "pnpm test --coverage"
"test:coverage": "pnpm test --coverage",
"test:types": "tsc -p ./tsconfig.json --noEmit"
},
"dependencies": {
"@actions/core": "^1.11.1",
@@ -56,6 +57,7 @@
"eslint-config-noir": "^1.5.2",
"eslint-import-resolver-typescript": "^3.6.3",
"eslint-plugin-import": "^2.31.0",
"fetch-mock": "^12.5.2",
"husky": "^9.1.6",
"is-ci": "^3.0.1",
"jest": "^29.7.0",
+41 -5
View File
@@ -59,13 +59,16 @@ importers:
version: 8.57.1
eslint-config-noir:
specifier: ^1.5.2
version: 1.5.2(@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])
version: 1.5.2(@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])
eslint-import-resolver-typescript:
specifier: ^3.6.3
version: 3.6.3(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
eslint-plugin-import:
specifier: ^2.31.0
version: 2.31.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
fetch-mock:
specifier: ^12.5.2
version: 12.5.2
husky:
specifier: ^9.1.6
version: 9.1.6
@@ -668,6 +671,9 @@ packages:
'@types/[email protected]':
resolution: {integrity: sha512-loB369iXNmAZglwWATL+WRe+CRMmmBPtpolYzIebFaX4YA3x+BEfLqhUAV9WanycKI3TG1IMr5bMJDajDKLlUQ==}
'@types/[email protected]':
resolution: {integrity: sha512-nDKoaKJYbnn1MZxUY0cA1bPmmgZbg0cTq7Rh13d0KWYNOiKbqoR+2d89SnRPszGh7ROzSwZ/GOjZ4jPbmmZ6Eg==}
'@types/[email protected]':
resolution: {integrity: sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==}
@@ -1110,6 +1116,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==}
[email protected]:
resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}
engines: {node: '>=6'}
[email protected]:
resolution: {integrity: sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==}
engines: {node: '>=8'}
@@ -1346,6 +1356,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==}
[email protected]:
resolution: {integrity: sha512-b5KGDFmdmado2MPQjZl6ix3dAG3iwCitb0XQwN72y2s9VnWZ3ObaGNy+bkpm1390foiLDybdJ7yjRGKD36kATw==}
engines: {node: '>=18.11.0'}
[email protected]:
resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==}
engines: {node: ^10.12.0 || >=12.0.0}
@@ -1438,6 +1452,9 @@ packages:
resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==}
engines: {node: '>=10.13.0'}
[email protected]:
resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==}
[email protected]:
resolution: {integrity: sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==}
deprecated: Glob versions prior to v9 are no longer supported
@@ -2163,6 +2180,10 @@ packages:
resolution: {integrity: sha512-vqlC04+RQoFalODCbCumG2xIOvapzVMHwsyIGM/SIE8fRhFFsXeH8/QQ+s0T0kDAhKc4k30s73/0ydkHQz6HlQ==}
engines: {node: '>= 0.4'}
[email protected]:
resolution: {integrity: sha512-RSYAtP31mvYLkAHrOlh25pCNQ5hWnT106VukGaaFfuJrZFkGRX5GhUAdPqpSDXxOhA2c4akmRuplv1mRqnBn6Q==}
engines: {node: '>=8'}
[email protected]:
resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}
engines: {node: '>=0.10.0'}
@@ -3292,6 +3313,8 @@ snapshots:
dependencies:
'@types/node': 18.16.3
'@types/[email protected]': {}
'@types/[email protected]':
dependencies:
'@types/node': 18.16.3
@@ -3804,6 +3827,8 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
@@ -3976,7 +4001,7 @@ snapshots:
[email protected]: {}
[email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]):
[email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected]):
dependencies:
eslint: 8.57.1
optionalDependencies:
@@ -3998,7 +4023,7 @@ snapshots:
debug: 4.3.7
enhanced-resolve: 5.17.1
eslint: 8.57.1
eslint-module-utils: 2.12.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])
eslint-module-utils: 2.12.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])
fast-glob: 3.3.2
get-tsconfig: 4.8.1
is-bun-module: 1.2.1
@@ -4011,7 +4036,7 @@ snapshots:
- eslint-import-resolver-webpack
- supports-color
[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]):
[email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]):
dependencies:
debug: 3.2.7
optionalDependencies:
@@ -4033,7 +4058,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
eslint-module-utils: 2.12.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])
eslint-module-utils: 2.12.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])
hasown: 2.0.2
is-core-module: 2.15.1
is-glob: 4.0.3
@@ -4165,6 +4190,13 @@ snapshots:
dependencies:
bser: 2.1.1
[email protected]:
dependencies:
'@types/glob-to-regexp': 0.4.4
dequal: 2.0.3
glob-to-regexp: 0.4.1
regexparam: 3.0.0
[email protected]:
dependencies:
flat-cache: 3.0.4
@@ -4261,6 +4293,8 @@ snapshots:
dependencies:
is-glob: 4.0.3
[email protected]: {}
[email protected]:
dependencies:
fs.realpath: 1.0.0
@@ -5109,6 +5143,8 @@ snapshots:
es-errors: 1.3.0
set-function-name: 2.0.2
[email protected]: {}
[email protected]: {}
[email protected]: {}
+17 -164
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2020-2025 Ardalan Amini
@@ -20,193 +20,46 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { debug } from "@actions/core";
import {
commitTypes,
defaultCommitType,
includeCommitLinks,
includePRLinks,
mentionAuthors,
octokit,
parseCommitMessage,
repository,
sha,
useGithubAutolink,
} from "./utils/index.js";
interface TypeGroupI {
scopes: ScopeGroupI[];
type: string;
}
interface ScopeGroupI {
logs: LogI[];
scope: string;
}
interface LogI {
breaking: boolean;
description: string;
references: string[];
}
function trim<T extends string | undefined>(value: T): T {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (value == null) return value;
return value.trim().replace(/ {2,}/g, " ") as never;
}
function unique(value: string[]): string[] {
return [...new Set(value)];
}
function sortBy<T>(array: T[], property: keyof T): T[] {
return array.sort((a, b) => (a[property] as string).localeCompare(b[property] as string));
}
import { ChangelogNode } from "./nodes/index.js";
import { iterateCommits, parseCommitMessage, repository, trim } from "./utils/index.js";
export async function generateChangelog(lastSha?: string): Promise<string> {
const { paginate, rest } = octokit();
const { owner, repo, url } = repository();
const defaultType = defaultCommitType();
const typeMap = commitTypes();
const shouldIncludePRLinks = includePRLinks();
const shouldIncludeCommitLinks = includeCommitLinks();
const shouldMentionAuthors = mentionAuthors();
const shouldUseGithubAutolink = useGithubAutolink();
const { owner, repo } = repository();
const iterator = paginate.iterator(
rest.repos.listCommits,
{
per_page: 100,
sha : sha(),
owner,
repo,
},
);
const typeGroups: TypeGroupI[] = [];
paginator: for await (const { data } of iterator) {
for (const commit of data) {
if (commit.sha === lastSha) break paginator;
const changelogNode = (new ChangelogNode);
for await (const commit of iterateCommits(owner, repo, lastSha)) {
const message = commit.commit.message.split("\n")[0];
debug(`commit message -> ${ message }`);
let { type, scope, description, pr, flag, breaking } = parseCommitMessage(message);
if (!description) continue;
description = trim(description);
if (!description) continue;
flag = trim(flag);
if (flag === "ignore") continue;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
type = typeMap[trim(type ?? "")] ?? defaultType;
const typeNode = changelogNode.addType(type);
let typeGroup = typeGroups.find(record => record.type === type);
const scopeNode = typeNode.addScope(scope);
if (typeGroup == null) {
typeGroup = {
type,
scopes: [],
};
const commitNote = scopeNode.addCommit(description, breaking);
typeGroups.push(typeGroup);
const authorNode = commitNote.addAuthor(commit.author?.login);
authorNode.addReference(commit.sha, pr);
}
scope = trim(scope ?? "");
const changelog = changelogNode.print();
let scopeGroup = typeGroup.scopes.find(record => record.scope === scope);
if (changelog) return `${ changelog }\n`;
if (scopeGroup == null) {
scopeGroup = {
scope,
logs: [],
};
typeGroup.scopes.push(scopeGroup);
}
let log = scopeGroup.logs.find(record => record.description === description);
if (log == null) {
log = {
breaking,
description,
references: [],
};
scopeGroup.logs.push(log);
}
const reference: string[] = [];
if (pr && shouldIncludePRLinks) reference.push(shouldUseGithubAutolink ? `#${ pr }` : `[#${ pr }](${ url }/issues/${ pr })`);
else if (shouldIncludeCommitLinks) reference.push(shouldUseGithubAutolink ? commit.sha : `\`[${ commit.sha }](${ url }/commit/${ commit.sha })\``);
const username = commit.author?.login;
if (username && shouldMentionAuthors) {
const mention = `by @${ username }`;
reference.push(mention);
const lastReference = log.references[log.references.length - 1];
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (lastReference?.endsWith(mention)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
log.references.push(log.references.pop()!.replace(mention, `& ${ reference.join(" ") }`));
continue;
}
}
if (reference.length > 0) log.references.push(reference.join(" "));
}
}
const types = unique(Object.values(typeMap).concat(defaultType));
const changelog: string[] = [];
for (const type of types) {
const typeGroup = typeGroups.find(log => log.type === type);
if (typeGroup == null) continue;
changelog.push(`## ${ type }`);
sortBy(typeGroup.scopes, "scope");
for (const { scope, logs } of typeGroup.scopes) {
let prefix = "";
if (scope.length > 0) {
changelog.push(`* **${ scope }:**`);
prefix = " ";
}
for (const { breaking, description, references } of logs) {
let line = `${ prefix }* ${ breaking ? "***breaking:*** " : "" }${ description }`;
if (references.length > 0) line += ` (${ references.join(", ") })`;
changelog.push(line);
}
}
changelog.push("");
}
return changelog.join("\n");
return "";
}
+5 -8
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2020-2025 Ardalan Amini
@@ -20,19 +20,17 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { marked } from "marked";
import {
includeCompareLink,
mentionNewContributors,
octokit,
releaseName,
releaseNamePrefix,
repository,
useGithubAutolink,
} from "./utils/index.js";
useGitHubAutolink,
} from "./inputs/index.js";
import { octokit, repository } from "./utils/index.js";
export async function generateFooter(previousTagName?: string): Promise<string> {
const { owner, repo, url } = repository();
@@ -40,7 +38,6 @@ export async function generateFooter(previousTagName?: string): Promise<string>
const footer: string[] = [];
if (mentionNewContributors()) {
const { rest } = octokit();
@@ -64,7 +61,7 @@ export async function generateFooter(previousTagName?: string): Promise<string>
if (includeCompareLink() && previousTagName) {
let link = `${ url }/compare/${ previousTagName }...${ tagName }`;
if (!useGithubAutolink() || releaseNamePrefix()) link = `\`[${ previousTagName }...${ tagName }](${ url }/compare/${ previousTagName }...${ tagName })\``;
if (!useGitHubAutolink() || releaseNamePrefix()) link = `\`[${ previousTagName }...${ tagName }](${ url }/compare/${ previousTagName }...${ tagName })\``;
footer.push(`**Full Changelog**: ${ link }`);
}
+42
View File
@@ -0,0 +1,42 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { generateChangelog } from "./changelog.js";
import { generateFooter } from "./footer.js";
import { setChangelog, setPrerelease, setReleaseId } from "./outputs/index.js";
import { getTagInfo } from "./tag.js";
export async function generate(): Promise<void> {
const { prerelease, releaseId, previous } = await getTagInfo();
setPrerelease(prerelease);
setReleaseId(releaseId);
let changelog = await generateChangelog(previous?.sha);
changelog += await generateFooter(previous?.name);
setChangelog(changelog);
}
+5 -21
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2020-2025 Ardalan Amini
@@ -20,27 +20,11 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
/* istanbul ignore file */
import { setFailed } from "@actions/core";
import { generateChangelog } from "./changelog.js";
import { generateFooter } from "./footer.js";
import { getTagInfo } from "./tag.js";
import { setChangelog, setPrerelease, setReleaseId } from "./utils/index.js";
import { generate } from "./generate.js";
async function run(): Promise<void> {
const { prerelease, releaseId, previous } = await getTagInfo();
setPrerelease(prerelease);
setReleaseId(releaseId);
let changelog = await generateChangelog(previous?.sha);
changelog += await generateFooter(previous?.name);
setChangelog(changelog);
}
run().catch(setFailed);
generate().catch(setFailed);
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,11 +20,10 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import YAML from "yaml";
import { input } from "../input.js";
import { input } from "../utils/input.js";
export function commitTypes(): Record<string, string> {
return input("commit-types", value => YAML.parse(value));
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,10 +20,9 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { input } from "../input.js";
import { input } from "../utils/input.js";
export function defaultCommitType(): string {
return input("default-commit-type");
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,11 +20,10 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { input } from "../input.js";
import { input } from "../utils/input.js";
export function token(): string {
export function gitHubToken(): string {
return input("github-token");
}
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,10 +20,9 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { booleanInput } from "../boolean-input.js";
import { booleanInput } from "../utils/boolean-input.js";
export function includeCommitLinks(): boolean {
return booleanInput("include-commit-links");
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,10 +20,9 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { booleanInput } from "../boolean-input.js";
import { booleanInput } from "../utils/boolean-input.js";
export function includeCompareLink(): boolean {
return booleanInput("include-compare-link");
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,10 +20,9 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { booleanInput } from "../boolean-input.js";
import { booleanInput } from "../utils/boolean-input.js";
export function includePRLinks(): boolean {
return booleanInput("include-pr-links");
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,11 +20,11 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
export * from "./commit-types.js";
export * from "./default-commit-type.js";
export * from "./github-token.js";
export * from "./include-compare-link.js";
export * from "./include-commit-links.js";
export * from "./include-pr-links.js";
@@ -33,5 +33,4 @@ export * from "./mention-new-contributors.js";
export * from "./release-name.js";
export * from "./release-name-prefix.js";
export * from "./semver.js";
export * from "./token.js";
export * from "./use-github-autolink.js";
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,10 +20,9 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { booleanInput } from "../boolean-input.js";
import { booleanInput } from "../utils/boolean-input.js";
export function mentionAuthors(): boolean {
return booleanInput("mention-authors");
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,10 +20,9 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { booleanInput } from "../boolean-input.js";
import { booleanInput } from "../utils/boolean-input.js";
export function mentionNewContributors(): boolean {
return booleanInput("mention-new-contributors");
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,11 +20,10 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { input } from "../input.js";
import { input } from "../utils/input.js";
export function releaseNamePrefix(): string {
return input("release-name-prefix", value => value || "", false);
return input("release-name-prefix", false);
}
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,10 +20,9 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { input } from "../input.js";
import { input } from "../utils/input.js";
export function releaseName(): string {
return input("release-name");
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,10 +20,9 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { booleanInput } from "../boolean-input.js";
import { booleanInput } from "../utils/boolean-input.js";
export function semver(): boolean {
return booleanInput("semver");
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,11 +20,10 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { booleanInput } from "../boolean-input.js";
import { booleanInput } from "../utils/boolean-input.js";
export function useGithubAutolink(): boolean {
export function useGitHubAutolink(): boolean {
return booleanInput("use-github-autolink");
}
+100
View File
@@ -0,0 +1,100 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { commitTypes, defaultCommitType } from "../inputs/index.js";
import { trim } from "../utils/index.js";
import { Node } from "./node.js";
import { TypeNode } from "./type.js";
/**
* Represents a changelog node which organizes and processes commit types into structured changelog entries.
* This class manages the mapping of commit types to their human-readable counterparts, aggregates commit
* types into groups, and generates a formatted output.
*/
export class ChangelogNode extends Node {
public readonly defaultType = defaultCommitType();
public readonly typeMap = commitTypes();
protected readonly types = (new Map<string, TypeNode>);
/**
* Adds a new type or retrieves an existing one from the already added types.
* If the input `type` is not found in the type map, the default type is assigned.
*
* @param [type=""] - The commit type to be mapped and added.
* @returns The corresponding type node that represents the added or existing type.
*/
public addType(type = ""): TypeNode {
const { types, typeMap, defaultType } = this;
// Map the commit type to the human-readable changelog type.
type = typeMap[trim(type)] ?? defaultType;
// Reusing the already added type to group the commits.
if (types.has(type)) return types.get(type)!;
const typeNode = new TypeNode(type);
types.set(type, typeNode);
return typeNode;
}
/**
* Compiles and concatenates the output of all accepted types into a single string, prefixed by the provided prefix.
*
* @param [prefix=""] - A string that is prefixed to each type's printed output.
* @returns A concatenated string of all printed types with the applied prefix, or null if no types are available.
*/
public print(prefix = ""): string | null {
const { types } = this;
if (types.size === 0) return null;
/**
* Using this instead of iterating over the `types` values allows the action users to apply their own custom order.
*/
const acceptedTypes = [...new Set(Object.values(this.typeMap).concat(this.defaultType))];
const parts: string[] = [];
for (const key of acceptedTypes) {
const type = types.get(key);
if (!type) continue;
const printedType = type.print(prefix);
if (printedType) parts.push(printedType);
}
if (parts.length === 0) return null;
// Joined by 2 new lines to have one empty line between each type group.
return parts.join("\n\n");
}
}
+110
View File
@@ -0,0 +1,110 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { mentionAuthors } from "../inputs/index.js";
import { CommitHashNode } from "./commit-hash.js";
import { Node } from "./node.js";
import { PullRequestNode } from "./pull-request.js";
/**
* Represents a node for a commit author, containing information about the author
* and associated references to commits or pull requests.
*/
export class CommitAuthorNode extends Node {
public readonly shouldMentionAuthor = mentionAuthors();
protected readonly references: Array<CommitHashNode | PullRequestNode> = [];
/**
* Initializes a new instance of the commit author node with an optional username.
*
* @param [username] - The commit author username.
*/
public constructor(public readonly username?: string) {
super();
}
/**
* Adds a reference to either a pull request or a commit hash.
* If a pull request is provided, it takes priority over the commit hash.
*
* @param sha - The SHA hash of the commit reference.
* @param [pr] - The optional pull request identifier.
* @returns The created reference node, either a CommitHashNode or a PullRequestNode.
*/
public addReference(sha: string, pr?: string): CommitHashNode | PullRequestNode {
let reference: CommitHashNode | PullRequestNode;
// PR references take priority over commit hash references
if (pr) reference = new PullRequestNode(pr);
else reference = new CommitHashNode(sha);
// Check if a reference already exists to avoid duplicates
for (const existingRef of this.references) {
if (
(!pr && existingRef instanceof CommitHashNode && existingRef.sha === sha)
|| (existingRef instanceof PullRequestNode && existingRef.pr === pr)
) return existingRef;
}
this.references.push(reference);
return reference;
}
/**
* Constructs and returns a formatted string representation based on references and author information.
* It combines references and adds author mention if applicable.
*
* @returns The formatted string representation or null if no parts are available.
*/
public print(): string | null {
const { username, references, serverUrl, shouldMentionAuthor, shouldUseGithubAutolink } = this;
const printedReferences: string[] = [];
for (const reference of references) {
const printedReference = reference.print();
if (printedReference) printedReferences.push(printedReference);
}
const parts: string[] = [];
if (printedReferences.length > 0) parts.push(printedReferences.join(" & "));
if (shouldMentionAuthor && username) {
if (parts.length > 0) parts.push("by");
if (shouldUseGithubAutolink) parts.push(`@${ username }`);
else parts.push(`[@${ username }](${ serverUrl }/${ username })`);
}
if (parts.length === 0) return null;
return parts.join(" ");
}
}
+65
View File
@@ -0,0 +1,65 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { includeCommitLinks } from "../inputs/index.js";
import { Node } from "./node.js";
/**
* Represents a node that holds a commit hash (SHA) and provides functionality
* for generating formatted strings or links based on its state and the repository context.
*/
export class CommitHashNode extends Node {
public readonly shouldNotPrint = !includeCommitLinks();
/**
* Constructs an instance of the commit hash node with a specified SHA string.
*
* @param sha - The SHA string associated with this instance.
*/
public constructor(public readonly sha: string) {
super();
}
/**
* Generates and returns a formatted string based on the current object state.
* If `shouldNotPrint` is true, the method returns null.
* If `shouldUseGithubAutolink` is true, the method directly returns the `sha` value.
* Otherwise,
* it returns a markdown-formatted string linking to the GitHub commit URL constructed using `sha` and `repo.url`.
*
* @returns A formatted string, the `sha` string, or null depending on conditions.
*/
public print(): string | null {
const { sha, shouldUseGithubAutolink, repo, shouldNotPrint } = this;
if (shouldNotPrint) return null;
if (shouldUseGithubAutolink) return sha;
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
return `\`[${ sha.slice(0, 7) }](${ repo.url }/commit/${ sha })\``;
}
}
+102
View File
@@ -0,0 +1,102 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { CommitAuthorNode } from "./commit-author.js";
import { Node } from "./node.js";
/**
* Represents a commit node in a data structure that tracks commit information.
* Extends the `Node` class and contains additional metadata such as description,
* authors, and a flag indicating whether the commit introduces breaking changes.
*/
export class CommitNode extends Node {
protected readonly authors: CommitAuthorNode[] = [];
/**
* Constructs an instance of the class.
*
* @param description - A description of the instance.
* @param [breaking=false] - Indicates whether the instance represents a breaking change.
*/
public constructor(public readonly description: string, public readonly breaking = false) {
super();
}
/**
* Adds a new author or retrieves the previous author if the username matches the last one.
* This optimization helps group consecutive commits by the same author efficiently.
*
* @param [username] - The username of the author to add.
* @returns The added or retrieved author node instance.
*/
public addAuthor(username?: string): CommitAuthorNode {
const { authors } = this;
// Only reuse authors with known usernames.
if (username && authors.length > 0) {
// Only if the last reference is to the same author, reuse the node.
const previousAuthor = authors[authors.length - 1];
if (previousAuthor.username === username) return previousAuthor;
}
const author = new CommitAuthorNode(username);
authors.push(author);
return author;
}
/**
* Constructs and returns a formatted string representation of the commit.
*
* @param [prefix=""] - A string to prefix the formatted output with.
* @returns A formatted string containing the description, authors, and a breaking indicator if applicable.
*/
public print(prefix = ""): string {
const { breaking, description, authors } = this;
const parts: string[] = [];
if (breaking) parts.push("***BREAKING:***");
parts.push(description);
if (authors.length > 0) {
const references: string[] = [];
for (const author of authors) {
const printedAuthor = author.print();
if (printedAuthor) references.push(printedAuthor);
}
if (references.length > 0) parts.push(`(${ references.join(", ") })`);
}
return `${ prefix }* ${ parts.join(" ") }`;
}
}
+32
View File
@@ -0,0 +1,32 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export * from "./changelog.js";
export * from "./commit.js";
export * from "./commit-author.js";
export * from "./commit-hash.js";
export * from "./node.js";
export * from "./pull-request.js";
export * from "./scope.js";
export * from "./type.js";
+48
View File
@@ -0,0 +1,48 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { context } from "@actions/github";
import { useGitHubAutolink } from "../inputs/index.js";
import { repository } from "../utils/index.js";
/**
* Represents the base class for all nodes in the changelog,
* providing shared functionality and requiring implementation of a print method.
*/
export abstract class Node {
public readonly repo = repository();
public readonly serverUrl = context.serverUrl;
public readonly shouldUseGithubAutolink = useGitHubAutolink();
/**
* Outputs a string representation of the changelog node.
*
* @returns The string representation if available, otherwise `null` if no representation exists or is provided.
*/
public abstract print(): string | null;
}
+62
View File
@@ -0,0 +1,62 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { includePRLinks } from "../inputs/index.js";
import { Node } from "./node.js";
/**
* Represents a node associated with a pull request or issue link.
* This class provides functionality to generate formatted links
* for pull requests or issues based on certain conditions.
*/
export class PullRequestNode extends Node {
public readonly shouldNotPrint = !includePRLinks();
/**
* Constructs an instance of the class with the specified `pr` parameter.
*
* @param pr - A string representing the parameter to be assigned to the instance.
*/
public constructor(public readonly pr: string) {
super();
}
/**
* Generates a formatted string representing a pull request or issue link
* based on the method's logic and class properties.
*
* @returns A string with the formatted pull request link or null if printing is disabled.
*/
public print(): string | null {
const { pr, shouldUseGithubAutolink, repo, shouldNotPrint } = this;
if (shouldNotPrint) return null;
if (shouldUseGithubAutolink) return `#${ pr }`;
return `[#${ pr }](${ repo.url }/issues/${ pr })`;
}
}
+91
View File
@@ -0,0 +1,91 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { CommitNode } from "./commit.js";
import { Node } from "./node.js";
/**
* Represents a scope node within a changelog hierarchy, containing a collection of commit nodes.
* A scope node can have an associated scope name and provides functionality to add commits
* and generate formatted output with scope and commit details.
*/
export class ScopeNode extends Node {
protected readonly commits = (new Map<string, CommitNode>);
/**
* Constructs an instance of the scope node.
*
* @param scope An optional string value representing the scope.
*/
public constructor(public readonly scope = "") {
super();
}
/**
* Adds a new commit to the internal collection or retrieves an existing one if it already exists.
*
* @param message The message associated with the commit.
* @param [breaking=false] Indicates whether the commit introduces breaking changes.
* @returns The newly added or existing commit node.
*/
public addCommit(message: string, breaking = false): CommitNode {
const { commits } = this;
const key = `${ breaking }::${ message }`;
if (commits.has(key)) return commits.get(key)!;
const commitNode = new CommitNode(message, breaking);
commits.set(key, commitNode);
return commitNode;
}
/**
* Generates a formatted string representation of the changelog's scope and commits.
*
* @param [prefix=""] Optional string to prepend to each line of the output.
* @returns A formatted string with scope and commit details, or null if there are no commits.
*/
public print(prefix = ""): string | null {
const { scope, commits } = this;
if (commits.size === 0) return null;
const parts: string[] = [];
if (scope) {
parts.push(`${ prefix }* **${ scope }:**`);
prefix += " ";
}
for (const commit of commits.values()) parts.push(commit.print(prefix));
return parts.join("\n");
}
}
+102
View File
@@ -0,0 +1,102 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { trim } from "../utils/index.js";
import { Node } from "./node.js";
import { ScopeNode } from "./scope.js";
/**
* Represents a node for a specific type that manages associated scopes.
* Provides methods to add scopes and retrieve a formatted string representation
* of its contents, including associated scopes and their respective commits.
*/
export class TypeNode extends Node {
protected readonly scopes = (new Map<string, ScopeNode>);
/**
* Constructs an instance of type node class with a specified type.
*
* @param type - The commit type associated with the instance.
*/
public constructor(public readonly type: string) {
super();
}
/**
* Adds a new scope to the scope collection.
* If the scope already exists,
* the existing scope node is returned instead of creating a new one.
*
* @param [scope=""] - The name of the scope to be added.
* @returns The scope node associated with the added or existing scope.
*/
public addScope(scope = ""): ScopeNode {
const { scopes } = this;
scope = trim(scope);
// Reusing the already added scope to group the commits.
if (scopes.has(scope)) return scopes.get(scope)!;
const scopeNode = new ScopeNode(scope);
scopes.set(scope, scopeNode);
return scopeNode;
}
/**
* Prints the commits and their scopes grouped in this type.
*
* @param [prefix=""] - A prefix string to prepend to the output.
* @returns The formatted string representation, or null if no scopes are available.
*/
public print(prefix = ""): string | null {
const { type, scopes } = this;
if (scopes.size === 0) return null;
const parts: string[] = [`${ prefix }## ${ type }`];
/**
* Sorting the scopes to have a consistent output order in all changelogs.
*/
const scopeKeys = [...scopes.keys()].sort((a, b) => a.localeCompare(b));
for (const key of scopeKeys) {
const scope = scopes.get(key)!;
const printedScope = scope.print(prefix);
if (printedScope) parts.push(printedScope);
}
// If only the header exists with no scope content, return null
if (parts.length === 1) return null;
return parts.join("\n");
}
}
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,7 +20,6 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
export * from "./set-changelog.js";
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,10 +20,9 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { output } from "../output.js";
import { output } from "../utils/index.js";
export function setChangelog(changelog: string): void {
output("changelog", changelog);
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,10 +20,9 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { output } from "../output.js";
import { output } from "../utils/index.js";
export function setPrerelease(prerelease: boolean): void {
output("prerelease", prerelease);
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,10 +20,9 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { output } from "../output.js";
import { output } from "../utils/index.js";
export function setReleaseId(releaseId: string): void {
output("release-id", releaseId);
+3 -3
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2020-2025 Ardalan Amini
@@ -20,11 +20,11 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { type SemVer } from "semver";
import { octokit, parseSemVer, releaseName, repository, semver, sha } from "./utils/index.js";
import { releaseName, semver } from "./inputs/index.js";
import { octokit, parseSemVer, repository, sha } from "./utils/index.js";
export interface TagInfoI {
prerelease: boolean;
+1 -2
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,7 +20,6 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { getBooleanInput } from "@actions/core";
+6 -3
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,13 +20,16 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
const CACHE = (new Map);
export function cache<T>(key: string, value: () => T, overwrite = false): T {
if (!CACHE.has(key) || overwrite) CACHE.set(key, value());
if (overwrite || !CACHE.has(key)) CACHE.set(key, value());
return CACHE.get(key);
}
export function clearCache(): void {
CACHE.clear();
}
+60
View File
@@ -0,0 +1,60 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { octokit } from "./octokit.js";
import { sha } from "./sha.js";
export async function *iterateCommits(owner: string, repo: string, from?: string): AsyncGenerator<TCommit> {
const { paginate, rest } = octokit();
const iterator = paginate.iterator(
rest.repos.listCommits,
{
per_page: 100,
sha : sha(),
owner,
repo,
},
);
loop: for await (const { data } of iterator) {
for (const commit of data) {
if (commit.sha === from) break loop;
yield commit;
}
}
}
export interface TCommit {
author?: {
login: string;
} | null;
commit: {
message: string;
};
sha: string;
}
+3 -4
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,13 +20,11 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
export * from "./inputs/index.js";
export * from "./outputs/index.js";
export * from "./boolean-input.js";
export * from "./cache.js";
export * from "./github.js";
export * from "./input.js";
export * from "./octokit.js";
export * from "./output.js";
@@ -34,3 +32,4 @@ export * from "./parse-commit-message.js";
export * from "./parse-semver.js";
export * from "./repository.js";
export * from "./sha.js";
export * from "./trim.js";
+17 -3
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,7 +20,6 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { getInput } from "@actions/core";
@@ -28,8 +27,23 @@ import { cache } from "./cache.js";
export function input<T = string>(
name: string,
parser: (value: string) => T = (value): T => value as T,
required?: boolean,
): T;
export function input<T = string>(
name: string,
parser: (value: string) => T,
required?: boolean,
): T;
export function input<T = string>(
name: string,
parser: boolean | ((value: string) => T) = (value): T => value as T,
required = true,
): T {
if (typeof parser === "boolean") {
required = parser;
parser = (value): T => value as T;
}
return cache(name, () => parser(getInput(name, { required })));
}
+3 -4
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,14 +20,13 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { getOctokit } from "@actions/github";
import { type GitHub } from "@actions/github/lib/utils.js";
import { gitHubToken } from "../inputs/index.js";
import { cache } from "./cache.js";
import { token } from "./inputs/index.js";
export function octokit(): InstanceType<typeof GitHub> {
return cache("octokit", () => getOctokit(token()));
return cache("octokit", () => getOctokit(gitHubToken()));
}
+1 -2
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,7 +20,6 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { info, setOutput } from "@actions/core";
+1 -2
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,7 +20,6 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
const REGEX = /^(?<type>[^!:() ]*)(?:\((?<scope>[^!()]*?)\)|)(?<breaking>!?): *(?<description>.+?) *(?:\(#(?<pr>[1-9]\d*?)\)|) *(?:\[(?<flag>[^[\]]*?)]|)\s*$/;
+3 -4
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,15 +20,14 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { parse, type SemVer } from "semver";
import { releaseName, releaseNamePrefix } from "../inputs/index.js";
import { cache } from "./cache.js";
import { releaseName, releaseNamePrefix } from "./inputs/index.js";
export function parseSemVer(version = releaseName()): SemVer | null {
return cache(`semver-${ version }`, () => parse(version.replace(new RegExp(`^${ releaseNamePrefix() }`), ""), { includePrerelease: true } as never));
}
export { SemVer };
export type { SemVer };
+1 -2
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,7 +20,6 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { context } from "@actions/github";
+1 -2
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2023-2025 Ardalan Amini
@@ -20,7 +20,6 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import { context } from "@actions/github";
+29
View File
@@ -0,0 +1,29 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export function trim<T extends string | null | undefined>(value: T): T {
if (!value) return value;
return value.trim().replace(/ {2,}/g, " ") as T;
}
+280
View File
@@ -0,0 +1,280 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* eslint-disable @typescript-eslint/no-magic-numbers */
import { getBooleanInput, getInput } from "@actions/core";
import { getOctokit } from "@actions/github";
import { GitHub } from "@actions/github/lib/utils";
import fetchMock from "fetch-mock";
import { generateChangelog } from "../src/changelog.js";
it("should return nothing", async () => {
const info = {
releaseId : "latest",
prerelease: false,
previous : {
name: "1.0.0",
sha : "3c1177539c1a216084f922ea52e56dd719a25945",
},
};
const gitHubTokenInputName = "github-token";
const gitHubTokenInputValue = "github-token-value";
const shouldUseGithubAutolink = true;
const defaultCommitType = "Other Changes";
const commitTypes = "chore: Chores\nci: CI";
jest.mocked(getBooleanInput).mockReturnValueOnce(shouldUseGithubAutolink);
jest.mocked(getInput).mockImplementation((input) => {
switch (input) {
case gitHubTokenInputName:
return gitHubTokenInputValue;
case "default-commit-type":
return defaultCommitType;
case "commit-types":
return commitTypes;
default:
return "";
}
});
const commit = {
author: {
login: "ardalanamini",
},
commit: {
message: "ci: update test workflow\n\nSigned-off-by: Ardalan Amini <[email protected]>",
},
sha: info.previous.sha,
};
const fetch = fetchMock.getOnce(
"begin:https://api.github.com/repos/ardalanamini/auto-changelog/commits",
[commit],
);
const gitHub = new GitHub({ request: { fetch: fetch.fetchHandler } });
jest.mocked(getOctokit).mockImplementationOnce(() => gitHub);
const result = await generateChangelog(info.previous.sha);
expect(result).toBe("");
});
it("should return nothing (no description)", async () => {
const info = {
releaseId : "latest",
prerelease: false,
previous : {
name: "1.0.0",
sha : "7a94b0db6150850cb1ae7243b13a4c972e9db261",
},
};
const gitHubTokenInputName = "github-token";
const gitHubTokenInputValue = "github-token-value";
const shouldUseGithubAutolink = true;
const defaultCommitType = "Other Changes";
const commitTypes = "chore: Chores\nci: CI";
jest.mocked(getBooleanInput).mockReturnValueOnce(shouldUseGithubAutolink);
jest.mocked(getInput).mockImplementation((input) => {
switch (input) {
case gitHubTokenInputName:
return gitHubTokenInputValue;
case "default-commit-type":
return defaultCommitType;
case "commit-types":
return commitTypes;
default:
return "";
}
});
const commit = {
author: {
login: "ardalanamini",
},
commit: {
message: "ci: \n\nSigned-off-by: Ardalan Amini <[email protected]>",
},
sha: "3c1177539c1a216084f922ea52e56dd719a25945",
};
const fetch = fetchMock.getOnce(
"begin:https://api.github.com/repos/ardalanamini/auto-changelog/commits",
[
commit, {
author: {
login: "ardalanamini",
},
commit: {
message: "chore: update copyright year\n\nSigned-off-by: Ardalan Amini <[email protected]>",
},
sha: info.previous.sha,
},
],
);
const gitHub = new GitHub({ request: { fetch: fetch.fetchHandler } });
jest.mocked(getOctokit).mockImplementationOnce(() => gitHub);
const result = await generateChangelog(info.previous.sha);
expect(result).toBe("");
});
it("should return nothing (flagged to ignore)", async () => {
const info = {
releaseId : "latest",
prerelease: false,
previous : {
name: "1.0.0",
sha : "7a94b0db6150850cb1ae7243b13a4c972e9db261",
},
};
const gitHubTokenInputName = "github-token";
const gitHubTokenInputValue = "github-token-value";
const shouldUseGithubAutolink = true;
const defaultCommitType = "Other Changes";
const commitTypes = "chore: Chores\nci: CI";
jest.mocked(getBooleanInput).mockReturnValueOnce(shouldUseGithubAutolink);
jest.mocked(getInput).mockImplementation((input) => {
switch (input) {
case gitHubTokenInputName:
return gitHubTokenInputValue;
case "default-commit-type":
return defaultCommitType;
case "commit-types":
return commitTypes;
default:
return "";
}
});
const commit = {
author: {
login: "ardalanamini",
},
commit: {
message: "ci: update test workflow [ignore]\n\nSigned-off-by: Ardalan Amini <[email protected]>",
},
sha: "3c1177539c1a216084f922ea52e56dd719a25945",
};
const fetch = fetchMock.getOnce(
"begin:https://api.github.com/repos/ardalanamini/auto-changelog/commits",
[
commit, {
author: {
login: "ardalanamini",
},
commit: {
message: "chore: update copyright year\n\nSigned-off-by: Ardalan Amini <[email protected]>",
},
sha: info.previous.sha,
},
],
);
const gitHub = new GitHub({ request: { fetch: fetch.fetchHandler } });
jest.mocked(getOctokit).mockImplementationOnce(() => gitHub);
const result = await generateChangelog(info.previous.sha);
expect(result).toBe("");
});
it("should generate the changelog", async () => {
const info = {
releaseId : "latest",
prerelease: false,
previous : {
name: "1.0.0",
sha : "7a94b0db6150850cb1ae7243b13a4c972e9db261",
},
};
const gitHubTokenInputName = "github-token";
const gitHubTokenInputValue = "github-token-value";
const shouldUseGithubAutolink = true;
const defaultCommitType = "Other Changes";
const commitTypes = "chore: Chores\nci: CI";
jest.mocked(getBooleanInput).mockReturnValueOnce(shouldUseGithubAutolink);
jest.mocked(getInput).mockImplementation((input) => {
switch (input) {
case gitHubTokenInputName:
return gitHubTokenInputValue;
case "default-commit-type":
return defaultCommitType;
case "commit-types":
return commitTypes;
default:
return "";
}
});
const commit = {
author: {
login: "ardalanamini",
},
commit: {
message: "ci: update test workflow\n\nSigned-off-by: Ardalan Amini <[email protected]>",
},
sha: "3c1177539c1a216084f922ea52e56dd719a25945",
};
const fetch = fetchMock.getOnce(
"begin:https://api.github.com/repos/ardalanamini/auto-changelog/commits",
[
commit, {
author: {
login: "ardalanamini",
},
commit: {
message: "chore: update copyright year\n\nSigned-off-by: Ardalan Amini <[email protected]>",
},
sha: info.previous.sha,
},
],
);
const gitHub = new GitHub({ request: { fetch: fetch.fetchHandler } });
jest.mocked(getOctokit).mockImplementationOnce(() => gitHub);
const result = await generateChangelog(info.previous.sha);
expect(result).toBe("## CI\n* update test workflow\n");
});
+209
View File
@@ -0,0 +1,209 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* eslint-disable @typescript-eslint/no-magic-numbers */
import { getBooleanInput, getInput } from "@actions/core";
import { getOctokit } from "@actions/github";
import { GitHub } from "@actions/github/lib/utils";
import fetchMock from "fetch-mock";
import { generateFooter } from "../src/footer";
import { repository } from "../src/utils/index.js";
it("should return nothing", async () => {
const info = {
releaseId : "latest",
prerelease: false,
previous : {
name: "1.0.0",
sha : "3c1177539c1a216084f922ea52e56dd719a25945",
},
};
const result = await generateFooter(info.previous.name);
expect(result).toBe("");
});
it("should generate the changelog footer with new contributors", async () => {
const gitHubTokenInputName = "github-token";
const gitHubTokenInputValue = "github-token-value";
const releaseNameInputName = "release-name";
const releaseNameInputValue = "2.0.0";
jest.mocked(getBooleanInput).mockImplementation((name) => {
if (name === "mention-new-contributors") return true;
return false;
});
jest.mocked(getInput).mockImplementation((name) => {
switch (name) {
case gitHubTokenInputName: return gitHubTokenInputValue;
case releaseNameInputName: return releaseNameInputValue;
default: return "";
}
});
const info = {
releaseId : "latest",
prerelease: false,
previous : {
name: "1.0.0",
sha : "3c1177539c1a216084f922ea52e56dd719a25945",
},
};
const fetch = fetchMock.postOnce(
"begin:https://api.github.com/repos/ardalanamini/auto-changelog/releases/generate-notes",
{
body: {
body: "## New Contributors\n- Author Name",
},
},
);
const gitHub = new GitHub({ request: { fetch: fetch.fetchHandler } });
jest.mocked(getOctokit).mockImplementationOnce(() => gitHub);
const result = await generateFooter(info.previous.name);
expect(result).toEqual("\n\n## New Contributors\n- Author Name\n");
expect(getInput).toHaveBeenCalledTimes(2);
expect(getInput).toHaveBeenNthCalledWith(1, releaseNameInputName, { required: true });
expect(getInput).toHaveNthReturnedWith(1, releaseNameInputValue);
expect(getInput).toHaveBeenNthCalledWith(2, gitHubTokenInputName, { required: true });
expect(getInput).toHaveNthReturnedWith(2, gitHubTokenInputValue);
expect(getOctokit).toHaveBeenCalledTimes(1);
expect(getOctokit).toHaveBeenCalledWith(gitHubTokenInputValue);
});
it("should generate the changelog footer with the full changelog link", async () => {
const { url } = repository();
const gitHubTokenInputName = "github-token";
const gitHubTokenInputValue = "github-token-value";
const releaseNameInputName = "release-name";
const releaseNameInputValue = "2.0.0";
jest.mocked(getBooleanInput).mockImplementation((name) => {
if (name === "include-compare-link") return true;
return false;
});
jest.mocked(getInput).mockImplementation((name) => {
switch (name) {
case gitHubTokenInputName: return gitHubTokenInputValue;
case releaseNameInputName: return releaseNameInputValue;
default: return "";
}
});
const info = {
releaseId : "latest",
prerelease: false,
previous : {
name: "1.0.0",
sha : "3c1177539c1a216084f922ea52e56dd719a25945",
},
};
const result = await generateFooter(info.previous.name);
expect(result).toEqual(`\n\n**Full Changelog**: \`[${ info.previous.name }...${ releaseNameInputValue }](${ url }/compare/${ info.previous.name }...${ releaseNameInputValue })\``);
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith(releaseNameInputName, { required: true });
expect(getInput).toHaveReturnedWith(releaseNameInputValue);
expect(getOctokit).toHaveBeenCalledTimes(0);
});
it("should generate the changelog footer with new contributors and the full changelog short link", async () => {
const { url } = repository();
const gitHubTokenInputName = "github-token";
const gitHubTokenInputValue = "github-token-value";
const releaseNameInputName = "release-name";
const releaseNameInputValue = "2.0.0";
jest.mocked(getBooleanInput).mockImplementation(() => true);
jest.mocked(getInput).mockImplementation((name) => {
switch (name) {
case gitHubTokenInputName: return gitHubTokenInputValue;
case releaseNameInputName: return releaseNameInputValue;
default: return "";
}
});
const info = {
releaseId : "latest",
prerelease: false,
previous : {
name: "1.0.0",
sha : "3c1177539c1a216084f922ea52e56dd719a25945",
},
};
const fetch = fetchMock.postOnce(
"begin:https://api.github.com/repos/ardalanamini/auto-changelog/releases/generate-notes",
{
body: {
body: "## New Contributors\n- Author Name",
},
},
);
const gitHub = new GitHub({ request: { fetch: fetch.fetchHandler } });
jest.mocked(getOctokit).mockImplementationOnce(() => gitHub);
const result = await generateFooter(info.previous.name);
expect(result).toEqual(`\n\n## New Contributors\n- Author Name\n\n\n**Full Changelog**: ${ url }/compare/${ info.previous.name }...${ releaseNameInputValue }`);
expect(getInput).toHaveBeenCalledTimes(3);
expect(getInput).toHaveBeenNthCalledWith(1, releaseNameInputName, { required: true });
expect(getInput).toHaveNthReturnedWith(1, releaseNameInputValue);
expect(getInput).toHaveBeenNthCalledWith(2, gitHubTokenInputName, { required: true });
expect(getInput).toHaveNthReturnedWith(2, gitHubTokenInputValue);
expect(getInput).toHaveBeenNthCalledWith(3, "release-name-prefix", { required: false });
expect(getInput).toHaveNthReturnedWith(3, "");
expect(getOctokit).toHaveBeenCalledTimes(1);
expect(getOctokit).toHaveBeenCalledWith(gitHubTokenInputValue);
});
+133
View File
@@ -0,0 +1,133 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* eslint-disable @typescript-eslint/no-magic-numbers */
import { getBooleanInput, getInput, setOutput } from "@actions/core";
import { getOctokit } from "@actions/github";
import { GitHub } from "@actions/github/lib/utils";
import fetchMock from "fetch-mock";
import { generate } from "../src/generate.js";
it("should generate the outputs", async () => {
const info = {
releaseName: "2.0.0",
releaseId : "latest",
prerelease : false,
previous : {
name: "1.0.0",
sha : "7a94b0db6150850cb1ae7243b13a4c972e9db261",
},
};
const gitHubTokenInputName = "github-token";
const gitHubTokenInputValue = "github-token-value";
const defaultCommitType = "Other Changes";
const commitTypes = "chore: Chores\nci: CI";
jest.mocked(getBooleanInput).mockImplementation((name) => {
switch (name) {
case "use-github-autolink":
case "mention-new-contributors":
return true;
default:
return false;
}
});
jest.mocked(getInput).mockImplementation((input) => {
switch (input) {
case gitHubTokenInputName:
return gitHubTokenInputValue;
case "default-commit-type":
return defaultCommitType;
case "commit-types":
return commitTypes;
case "release-name":
return info.releaseName;
default:
return "";
}
});
const commit = {
author: {
login: "ardalanamini",
},
commit: {
message: "ci: update test workflow\n\nSigned-off-by: Ardalan Amini <[email protected]>",
},
sha: "3c1177539c1a216084f922ea52e56dd719a25945",
};
const fetch = fetchMock
.getOnce(
"begin:https://api.github.com/repos/ardalanamini/auto-changelog/tags",
[
{
name : info.previous.name,
commit: {
sha: info.previous.sha,
},
},
],
).getOnce(
"begin:https://api.github.com/repos/ardalanamini/auto-changelog/commits",
[
commit, {
author: {
login: "ardalanamini",
},
commit: {
message: "chore: update copyright year\n\nSigned-off-by: Ardalan Amini <[email protected]>",
},
sha: info.previous.sha,
},
],
)
.postOnce(
"begin:https://api.github.com/repos/ardalanamini/auto-changelog/releases/generate-notes",
{
body: {
body: "## New Contributors\n- Ardalan Amini",
},
},
);
const gitHub = new GitHub({ request: { fetch: fetch.fetchHandler } });
jest.mocked(getOctokit).mockImplementationOnce(() => gitHub);
await generate();
expect(setOutput).toHaveBeenCalledTimes(3);
expect(setOutput).toHaveBeenCalledWith("prerelease", info.prerelease);
expect(setOutput).toHaveBeenCalledWith("release-id", info.releaseId);
expect(setOutput).toHaveBeenCalledWith(
"changelog",
"## CI\n* update test workflow\n\n\n## New Contributors\n- Ardalan Amini\n",
);
});
+63
View File
@@ -0,0 +1,63 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getInput } from "@actions/core";
import { commitTypes } from "../../src/inputs";
it("should get and parse the \"commit-types\" input", () => {
const inputValue = `
feat : New Features
fix : Bug Fixes
build : Build System & Dependencies
perf : Performance Improvements
docs : Documentation
test : Tests
refactor: Refactors
chore : Chores
ci : CI
style : Code Style
revert : Reverts
`;
jest.mocked(getInput).mockReturnValueOnce(inputValue);
const result = commitTypes();
expect(result).toEqual({
feat : "New Features",
fix : "Bug Fixes",
build : "Build System & Dependencies",
perf : "Performance Improvements",
docs : "Documentation",
test : "Tests",
refactor: "Refactors",
chore : "Chores",
ci : "CI",
style : "Code Style",
revert : "Reverts",
});
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith("commit-types", { required: true });
});
+39
View File
@@ -0,0 +1,39 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getInput } from "@actions/core";
import { defaultCommitType } from "../../src/inputs";
it("should get and parse the \"default-commit-type\" input", () => {
const inputValue = "Other Changes";
jest.mocked(getInput).mockReturnValueOnce(inputValue);
const result = defaultCommitType();
expect(result).toEqual(inputValue);
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith("default-commit-type", { required: true });
});
+39
View File
@@ -0,0 +1,39 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getInput } from "@actions/core";
import { gitHubToken } from "../../src/inputs";
it("should get and parse the \"github-token\" input", () => {
const inputValue = "github-token-value";
jest.mocked(getInput).mockReturnValueOnce(inputValue);
const result = gitHubToken();
expect(result).toEqual(inputValue);
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith("github-token", { required: true });
});
+37
View File
@@ -0,0 +1,37 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { includeCommitLinks } from "../../src/inputs";
it.each([true, false])("should get and parse the \"include-commit-links\" input as %j", (inputValue) => {
jest.mocked(getBooleanInput).mockReturnValueOnce(inputValue);
const result = includeCommitLinks();
expect(result).toEqual(inputValue);
expect(getBooleanInput).toHaveBeenCalledTimes(1);
expect(getBooleanInput).toHaveBeenCalledWith("include-commit-links", { required: true });
});
+37
View File
@@ -0,0 +1,37 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { includeCompareLink } from "../../src/inputs";
it.each([true, false])("should get and parse the \"include-compare-link\" input as %j", (inputValue) => {
jest.mocked(getBooleanInput).mockReturnValueOnce(inputValue);
const result = includeCompareLink();
expect(result).toEqual(inputValue);
expect(getBooleanInput).toHaveBeenCalledTimes(1);
expect(getBooleanInput).toHaveBeenCalledWith("include-compare-link", { required: true });
});
+37
View File
@@ -0,0 +1,37 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { includePRLinks } from "../../src/inputs";
it.each([true, false])("should retrieve the \"include-pr-links\" input as %j", (inputValue) => {
jest.mocked(getBooleanInput).mockReturnValueOnce(inputValue);
const result = includePRLinks();
expect(result).toEqual(inputValue);
expect(getBooleanInput).toHaveBeenCalledTimes(1);
expect(getBooleanInput).toHaveBeenCalledWith("include-pr-links", { required: true });
});
+37
View File
@@ -0,0 +1,37 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { mentionAuthors } from "../../src/inputs";
it.each([true, false])("should get and parse the \"mention-authors\" input as %j", (inputValue) => {
jest.mocked(getBooleanInput).mockReturnValueOnce(inputValue);
const result = mentionAuthors();
expect(result).toEqual(inputValue);
expect(getBooleanInput).toHaveBeenCalledTimes(1);
expect(getBooleanInput).toHaveBeenCalledWith("mention-authors", { required: true });
});
@@ -0,0 +1,37 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { mentionNewContributors } from "../../src/inputs";
it.each([true, false])("should get and parse the \"mention-new-contributors\" input as %j", (inputValue) => {
jest.mocked(getBooleanInput).mockReturnValueOnce(inputValue);
const result = mentionNewContributors();
expect(result).toEqual(inputValue);
expect(getBooleanInput).toHaveBeenCalledTimes(1);
expect(getBooleanInput).toHaveBeenCalledWith("mention-new-contributors", { required: true });
});
+39
View File
@@ -0,0 +1,39 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getInput } from "@actions/core";
import { releaseNamePrefix } from "../../src/inputs";
it("should get and parse the \"release-name-prefix\" input", () => {
const inputValue = "@actions/github/";
jest.mocked(getInput).mockReturnValueOnce(inputValue);
const result = releaseNamePrefix();
expect(result).toEqual(inputValue);
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith("release-name-prefix", { required: false });
});
+39
View File
@@ -0,0 +1,39 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getInput } from "@actions/core";
import { releaseName } from "../../src/inputs";
it("should get and parse the \"release-name\" input", () => {
const inputValue = "v1.0.0";
jest.mocked(getInput).mockReturnValueOnce(inputValue);
const result = releaseName();
expect(result).toEqual(inputValue);
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith("release-name", { required: true });
});
+37
View File
@@ -0,0 +1,37 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { semver } from "../../src/inputs";
it.each([true, false])("should get and parse the \"semver\" input as %j", (inputValue) => {
jest.mocked(getBooleanInput).mockReturnValueOnce(inputValue);
const result = semver();
expect(result).toEqual(inputValue);
expect(getBooleanInput).toHaveBeenCalledTimes(1);
expect(getBooleanInput).toHaveBeenCalledWith("semver", { required: true });
});
+37
View File
@@ -0,0 +1,37 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { useGitHubAutolink } from "../../src/inputs";
it.each([true, false])("should retrieve the \"use-github-autolink\" input as %j", (inputValue) => {
jest.mocked(getBooleanInput).mockReturnValueOnce(inputValue);
const result = useGitHubAutolink();
expect(result).toEqual(inputValue);
expect(getBooleanInput).toHaveBeenCalledTimes(1);
expect(getBooleanInput).toHaveBeenCalledWith("use-github-autolink", { required: true });
});
+27
View File
@@ -0,0 +1,27 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { clearCache } from "../../src/utils";
afterEach(() => clearCache());
+26
View File
@@ -0,0 +1,26 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
jest.mock("@actions/core");
jest.mock("@actions/github");
+119
View File
@@ -0,0 +1,119 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput, getInput } from "@actions/core";
import { context } from "@actions/github";
import YAML from "yaml";
import { ChangelogNode, CommitNode, ScopeNode, TypeNode } from "../../src/nodes";
const repo = {
owner: "ardalanamini",
repo : "auto-changelog",
};
const url = `${ context.serverUrl }/${ repo.owner }/${ repo.repo }`;
beforeEach(() => {
jest.spyOn(context, "repo", "get").mockReturnValueOnce(repo);
});
it("should create an instance with common values", () => {
const shouldUseGithubAutolink = true;
const defaultCommitType = "Other Changes";
const commitTypes = "feat: Features\nbug: Bug Fixes";
jest.mocked(getBooleanInput).mockReturnValueOnce(shouldUseGithubAutolink);
jest.mocked(getInput).mockImplementation((input) => {
switch (input) {
case "default-commit-type":
return defaultCommitType;
case "commit-types":
return commitTypes;
default:
return "";
}
});
const changelogNode = (new ChangelogNode);
expect(changelogNode.shouldUseGithubAutolink).toBe(shouldUseGithubAutolink);
expect(changelogNode.defaultType).toBe(defaultCommitType);
expect(changelogNode.typeMap).toEqual(YAML.parse(commitTypes));
expect(changelogNode.repo).toEqual({
...repo,
url,
});
expect(changelogNode.print()).toBeNull();
});
it("should not print anything", () => {
jest.mocked(getBooleanInput).mockReturnValueOnce(true);
jest.mocked(getInput).mockImplementation((input) => {
switch (input) {
case "default-commit-type":
return "Other Changes";
case "commit-types":
return "feat: Features\nbug: Bug Fixes";
default:
return "";
}
});
const changelogNode = (new ChangelogNode);
const typeNode = changelogNode.addType("feat");
const scopeNode = typeNode.addScope();
expect(typeNode).toBeInstanceOf(TypeNode);
expect(scopeNode).toBeInstanceOf(ScopeNode);
expect(changelogNode.print()).toBeNull();
});
it("should print commit changelog", () => {
jest.mocked(getBooleanInput).mockReturnValueOnce(true);
jest.mocked(getInput).mockImplementation((input) => {
switch (input) {
case "default-commit-type":
return "Other Changes";
case "commit-types":
return "feat: Features\nbug: Bug Fixes";
default:
return "";
}
});
const changelogNode = (new ChangelogNode);
const commitNode1 = changelogNode.addType("feat").addScope()
.addCommit("implement awesome feature");
const commitNode2 = changelogNode.addType("bug").addScope()
.addCommit("fix some issue");
expect(commitNode1).toBeInstanceOf(CommitNode);
expect(commitNode2).toBeInstanceOf(CommitNode);
expect(changelogNode.print()).toBe("## Features\n* implement awesome feature\n\n## Bug Fixes\n* fix some issue");
});
+288
View File
@@ -0,0 +1,288 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { context } from "@actions/github";
import { CommitAuthorNode, CommitHashNode, Node, PullRequestNode } from "../../src/nodes";
const repo = {
owner: "ardalanamini",
repo : "auto-changelog",
};
const serverUrl = context.serverUrl;
const url = `${ serverUrl }/${ repo.owner }/${ repo.repo }`;
beforeEach(() => {
jest.spyOn(context, "repo", "get").mockReturnValueOnce(repo);
});
it("should print the username only to be autolinked", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const username = "ardalanamini";
const commitAuthorNode = new CommitAuthorNode(username);
expect(commitAuthorNode).toBeInstanceOf(Node);
expect(commitAuthorNode.username).toBe(username);
expect(commitAuthorNode.shouldMentionAuthor).toBe(true);
expect(commitAuthorNode.shouldUseGithubAutolink).toBe(true);
expect(commitAuthorNode.repo).toEqual({
...repo,
url,
});
expect(commitAuthorNode.print()).toBe(`@${ username }`);
});
it("should not print anything", () => {
jest.mocked(getBooleanInput).mockImplementation(name => name !== "mention-authors");
const username = "ardalanamini";
const commitAuthorNode = new CommitAuthorNode(username);
expect(commitAuthorNode.username).toBe(username);
expect(commitAuthorNode.shouldMentionAuthor).toBe(false);
expect(commitAuthorNode.shouldUseGithubAutolink).toBe(true);
expect(commitAuthorNode.print()).toBeNull();
});
it("should print the username with the link (not using autolink)", () => {
jest.mocked(getBooleanInput).mockImplementation(name => name !== "use-github-autolink");
const username = "ardalanamini";
const commitAuthorNode = new CommitAuthorNode(username);
expect(commitAuthorNode.username).toBe(username);
expect(commitAuthorNode.shouldMentionAuthor).toBe(true);
expect(commitAuthorNode.shouldUseGithubAutolink).toBe(false);
expect(commitAuthorNode.print()).toBe(`[@${ username }](${ serverUrl }/${ username })`);
});
describe("should print the username & commit sha", () => {
it("with autolink", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const username = "ardalanamini";
const sha = "3c1177539c1a216084f922ea52e56dd719a25945";
const commitAuthorNode = new CommitAuthorNode(username);
const reference = commitAuthorNode.addReference(sha);
expect(commitAuthorNode.username).toBe(username);
expect(commitAuthorNode.shouldMentionAuthor).toBe(true);
expect(commitAuthorNode.shouldUseGithubAutolink).toBe(true);
expect(reference).toBeInstanceOf(CommitHashNode);
expect(commitAuthorNode.print()).toBe(`${ reference.print() } by @${ username }`);
});
it("without autolink", () => {
jest.mocked(getBooleanInput).mockImplementation(name => name !== "use-github-autolink");
const username = "ardalanamini";
const sha = "3c1177539c1a216084f922ea52e56dd719a25945";
const commitAuthorNode = new CommitAuthorNode(username);
const reference = commitAuthorNode.addReference(sha);
expect(commitAuthorNode.username).toBe(username);
expect(commitAuthorNode.shouldMentionAuthor).toBe(true);
expect(commitAuthorNode.shouldUseGithubAutolink).toBe(false);
expect(reference).toBeInstanceOf(CommitHashNode);
expect(commitAuthorNode.print()).toBe(`${ reference.print() } by [@${ username }](${ serverUrl }/${ username })`);
});
});
describe("should print the username & pr (prioritized over commit sha)", () => {
it("with autolink", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const username = "ardalanamini";
const sha = "3c1177539c1a216084f922ea52e56dd719a25945";
const pr = "197";
const commitAuthorNode = new CommitAuthorNode(username);
const reference = commitAuthorNode.addReference(sha, pr);
expect(commitAuthorNode.username).toBe(username);
expect(commitAuthorNode.shouldMentionAuthor).toBe(true);
expect(commitAuthorNode.shouldUseGithubAutolink).toBe(true);
expect(reference).toBeInstanceOf(PullRequestNode);
expect(commitAuthorNode.print()).toBe(`${ reference.print() } by @${ username }`);
});
it("without autolink", () => {
jest.mocked(getBooleanInput).mockImplementation(name => name !== "use-github-autolink");
const username = "ardalanamini";
const sha = "3c1177539c1a216084f922ea52e56dd719a25945";
const pr = "197";
const commitAuthorNode = new CommitAuthorNode(username);
const reference = commitAuthorNode.addReference(sha, pr);
expect(commitAuthorNode.username).toBe(username);
expect(commitAuthorNode.shouldMentionAuthor).toBe(true);
expect(commitAuthorNode.shouldUseGithubAutolink).toBe(false);
expect(reference).toBeInstanceOf(PullRequestNode);
expect(commitAuthorNode.print()).toBe(`${ reference.print() } by [@${ username }](${ serverUrl }/${ username })`);
});
});
describe("should print the username & multiple references", () => {
it("with autolink", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const username = "ardalanamini";
const sha = "3c1177539c1a216084f922ea52e56dd719a25945";
const pr = "197";
const sha2 = "7a94b0db6150850cb1ae7243b13a4c972e9db261";
const commitAuthorNode = new CommitAuthorNode(username);
const reference = commitAuthorNode.addReference(sha, pr);
const reference2 = commitAuthorNode.addReference(sha2);
expect(commitAuthorNode.username).toBe(username);
expect(commitAuthorNode.shouldMentionAuthor).toBe(true);
expect(commitAuthorNode.shouldUseGithubAutolink).toBe(true);
expect(reference).toBeInstanceOf(PullRequestNode);
expect(reference2).toBeInstanceOf(CommitHashNode);
expect(commitAuthorNode.print()).toBe(`${ reference.print() } & ${ reference2.print() } by @${ username }`);
});
it("without autolink", () => {
jest.mocked(getBooleanInput).mockImplementation(name => name !== "use-github-autolink");
const username = "ardalanamini";
const sha = "3c1177539c1a216084f922ea52e56dd719a25945";
const pr = "197";
const sha2 = "7a94b0db6150850cb1ae7243b13a4c972e9db261";
const commitAuthorNode = new CommitAuthorNode(username);
const reference = commitAuthorNode.addReference(sha, pr);
const reference2 = commitAuthorNode.addReference(sha2);
expect(commitAuthorNode.username).toBe(username);
expect(commitAuthorNode.shouldMentionAuthor).toBe(true);
expect(commitAuthorNode.shouldUseGithubAutolink).toBe(false);
expect(reference).toBeInstanceOf(PullRequestNode);
expect(reference2).toBeInstanceOf(CommitHashNode);
expect(commitAuthorNode.print()).toBe(`${ reference.print() } & ${ reference2.print() } by [@${ username }](${ serverUrl }/${ username })`);
});
});
describe("should reuse reference", () => {
it("commit sha", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const username = "ardalanamini";
const commitAuthorNode = new CommitAuthorNode(username);
const sha = "3c1177539c1a216084f922ea52e56dd719a25945";
const reference1 = commitAuthorNode.addReference(sha);
const reference2 = commitAuthorNode.addReference(sha);
expect(commitAuthorNode).toBeInstanceOf(Node);
expect(reference1).toEqual(reference2);
expect(commitAuthorNode.username).toBe(username);
expect(commitAuthorNode.shouldMentionAuthor).toBe(true);
expect(commitAuthorNode.shouldUseGithubAutolink).toBe(true);
expect(commitAuthorNode.repo).toEqual({
...repo,
url,
});
expect(commitAuthorNode.print()).toBe(`${ sha } by @${ username }`);
});
it("pr number", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const username = "ardalanamini";
const commitAuthorNode = new CommitAuthorNode(username);
const pr = "1";
const sha = "3c1177539c1a216084f922ea52e56dd719a25945";
const reference1 = commitAuthorNode.addReference(sha, pr);
const reference2 = commitAuthorNode.addReference(sha, pr);
expect(commitAuthorNode).toBeInstanceOf(Node);
expect(reference1).toEqual(reference2);
expect(commitAuthorNode.username).toBe(username);
expect(commitAuthorNode.shouldMentionAuthor).toBe(true);
expect(commitAuthorNode.shouldUseGithubAutolink).toBe(true);
expect(commitAuthorNode.repo).toEqual({
...repo,
url,
});
expect(commitAuthorNode.print()).toBe(`#${ pr } by @${ username }`);
});
});
+88
View File
@@ -0,0 +1,88 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { context } from "@actions/github";
import { CommitHashNode, Node } from "../../src/nodes";
const repo = {
owner: "ardalanamini",
repo : "auto-changelog",
};
beforeEach(() => {
jest.spyOn(context, "repo", "get").mockReturnValueOnce(repo);
});
it("should print the sha only to be autolinked", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const sha = "3c1177539c1a216084f922ea52e56dd719a25945";
const commitHashNode = new CommitHashNode(sha);
expect(commitHashNode).toBeInstanceOf(Node);
expect(commitHashNode.sha).toBe(sha);
expect(commitHashNode.shouldNotPrint).toBe(false);
expect(commitHashNode.shouldUseGithubAutolink).toBe(true);
expect(commitHashNode.repo).toEqual({
...repo,
url: `${ context.serverUrl }/${ repo.owner }/${ repo.repo }`,
});
expect(commitHashNode.print()).toBe(sha);
});
it("should not print anything", () => {
jest.mocked(getBooleanInput).mockReturnValue(false);
const sha = "3c1177539c1a216084f922ea52e56dd719a25945";
const commitHashNode = new CommitHashNode(sha);
expect(commitHashNode.sha).toBe(sha);
expect(commitHashNode.shouldNotPrint).toBe(true);
expect(commitHashNode.shouldUseGithubAutolink).toBe(false);
expect(commitHashNode.print()).toBeNull();
});
it("should print the sha with the link (not using autolink)", () => {
jest.mocked(getBooleanInput).mockImplementation(name => name !== "use-github-autolink");
const sha = "3c1177539c1a216084f922ea52e56dd719a25945";
const commitHashNode = new CommitHashNode(sha);
expect(commitHashNode.sha).toBe(sha);
expect(commitHashNode.shouldNotPrint).toBe(false);
expect(commitHashNode.shouldUseGithubAutolink).toBe(false);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
expect(commitHashNode.print()).toBe(`\`[${ sha.slice(0, 7) }](${ context.serverUrl }/${ repo.owner }/${ repo.repo }/commit/${ sha })\``);
});
+172
View File
@@ -0,0 +1,172 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { context } from "@actions/github";
import { CommitAuthorNode, CommitHashNode, CommitNode, Node } from "../../src/nodes";
const repo = {
owner: "ardalanamini",
repo : "auto-changelog",
};
const url = `${ context.serverUrl }/${ repo.owner }/${ repo.repo }`;
beforeEach(() => {
jest.spyOn(context, "repo", "get").mockReturnValueOnce(repo);
});
it("should print a commit description only", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const description = "ci: update test workflow";
const commitNode = new CommitNode(description);
expect(commitNode).toBeInstanceOf(Node);
expect(commitNode.description).toBe(description);
expect(commitNode.breaking).toBe(false);
expect(commitNode.shouldUseGithubAutolink).toBe(true);
expect(commitNode.repo).toEqual({
...repo,
url,
});
expect(commitNode.print()).toBe(`* ${ description }`);
});
it("should print a commit description with prefix", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const description = "ci: update test workflow";
const commitNode = new CommitNode(description);
expect(commitNode.description).toBe(description);
expect(commitNode.breaking).toBe(false);
expect(commitNode.shouldUseGithubAutolink).toBe(true);
const prefix = " ";
expect(commitNode.print(prefix)).toBe(`${ prefix }* ${ description }`);
});
it("should print a breaking commit description only", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const description = "ci: update test workflow";
const commitNode = new CommitNode(description, true);
expect(commitNode.description).toBe(description);
expect(commitNode.breaking).toBe(true);
expect(commitNode.shouldUseGithubAutolink).toBe(true);
expect(commitNode.print()).toBe(`* ***BREAKING:*** ${ description }`);
});
it("should print the commit description and its author", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const description = "ci: update test workflow";
const username = "ardalanamini";
const commitNode = new CommitNode(description);
const author = commitNode.addAuthor(username);
expect(commitNode.description).toBe(description);
expect(commitNode.breaking).toBe(false);
expect(commitNode.shouldUseGithubAutolink).toBe(true);
expect(author).toBeInstanceOf(CommitAuthorNode);
expect(commitNode.print()).toBe(`* ${ description } (${ author.print() })`);
});
it("should print the commit description and its multiple authors", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const description = "ci: update test workflow";
const username = "ardalanamini";
const username2 = "not-ardalanamini";
const commitNode = new CommitNode(description);
const author = commitNode.addAuthor(username);
const author2 = commitNode.addAuthor(username2);
expect(commitNode.description).toBe(description);
expect(commitNode.breaking).toBe(false);
expect(commitNode.shouldUseGithubAutolink).toBe(true);
expect(author).toBeInstanceOf(CommitAuthorNode);
expect(author2).toBeInstanceOf(CommitAuthorNode);
expect(commitNode.print()).toBe(`* ${ description } (${ author.print() }, ${ author2.print() })`);
});
it("it should reuse the same author node for same authors", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const description = "ci: update test workflow";
const username = "ardalanamini";
const sha = "3c1177539c1a216084f922ea52e56dd719a25945";
const sha2 = "7a94b0db6150850cb1ae7243b13a4c972e9db261";
const commitNode = new CommitNode(description);
const author = commitNode.addAuthor(username);
const reference = author.addReference(sha);
const author2 = commitNode.addAuthor(username);
const reference2 = author.addReference(sha2);
expect(commitNode.description).toBe(description);
expect(commitNode.breaking).toBe(false);
expect(commitNode.shouldUseGithubAutolink).toBe(true);
expect(author).toBeInstanceOf(CommitAuthorNode);
expect(reference).toBeInstanceOf(CommitHashNode);
expect(author2).toBeInstanceOf(CommitAuthorNode);
expect(reference2).toBeInstanceOf(CommitHashNode);
expect(author).toBe(author2);
const result = commitNode.print();
expect(result).toBe(`* ${ description } (${ author.print() })`);
expect(result).toBe(`* ${ description } (${ author2.print() })`);
});
+56
View File
@@ -0,0 +1,56 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { context } from "@actions/github";
import { Node } from "../../src/nodes";
it("should create an instance with common values", () => {
const shouldUseGithubAutolink = true;
const repo = {
owner: "ardalanamini",
repo : "auto-changelog",
};
jest.mocked(getBooleanInput).mockReturnValueOnce(shouldUseGithubAutolink);
jest.spyOn(context, "repo", "get").mockReturnValueOnce(repo);
class TestNode extends Node {
public print(): string {
return this.repo.repo;
}
}
const node = (new TestNode);
expect(node.shouldUseGithubAutolink).toBe(shouldUseGithubAutolink);
expect(node.serverUrl).toBe(context.serverUrl);
expect(node.repo).toEqual({
...repo,
url: `${ context.serverUrl }/${ repo.owner }/${ repo.repo }`,
});
});
+88
View File
@@ -0,0 +1,88 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { context } from "@actions/github";
import { Node, PullRequestNode } from "../../src/nodes";
const repo = {
owner: "ardalanamini",
repo : "auto-changelog",
};
beforeEach(() => {
jest.spyOn(context, "repo", "get").mockReturnValueOnce(repo);
});
it("should print the pr only to be autolinked", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const pr = "197";
const pullRequestNode = new PullRequestNode(pr);
expect(pullRequestNode).toBeInstanceOf(Node);
expect(pullRequestNode.pr).toBe(pr);
expect(pullRequestNode.shouldNotPrint).toBe(false);
expect(pullRequestNode.shouldUseGithubAutolink).toBe(true);
expect(pullRequestNode.repo).toEqual({
...repo,
url: `${ context.serverUrl }/${ repo.owner }/${ repo.repo }`,
});
expect(pullRequestNode.print()).toBe(`#${ pr }`);
});
it("should not print anything", () => {
jest.mocked(getBooleanInput).mockReturnValue(false);
const pr = "197";
const pullRequestNode = new PullRequestNode(pr);
expect(pullRequestNode.pr).toBe(pr);
expect(pullRequestNode.shouldNotPrint).toBe(true);
expect(pullRequestNode.shouldUseGithubAutolink).toBe(false);
expect(pullRequestNode.print()).toBeNull();
});
it("should print the pr with the link (not using autolink)", () => {
// Enable PR links but disable GitHub autolink to test manual link generation
jest.mocked(getBooleanInput).mockImplementation(name => name !== "use-github-autolink");
const pr = "197";
const pullRequestNode = new PullRequestNode(pr);
expect(pullRequestNode.pr).toBe(pr);
expect(pullRequestNode.shouldNotPrint).toBe(false);
expect(pullRequestNode.shouldUseGithubAutolink).toBe(false);
expect(pullRequestNode.print()).toBe(`[#${ pr }](${ context.serverUrl }/${ repo.owner }/${ repo.repo }/issues/${ pr })`);
});
+188
View File
@@ -0,0 +1,188 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { context } from "@actions/github";
import { CommitNode, Node, ScopeNode } from "../../src/nodes";
const repo = {
owner: "ardalanamini",
repo : "auto-changelog",
};
const url = `${ context.serverUrl }/${ repo.owner }/${ repo.repo }`;
beforeEach(() => {
jest.spyOn(context, "repo", "get").mockReturnValueOnce(repo);
});
it("should not print anything", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const scope = "commit-scope";
const scopeNode = new ScopeNode(scope);
expect(scopeNode).toBeInstanceOf(Node);
expect(scopeNode.scope).toBe(scope);
expect(scopeNode.shouldUseGithubAutolink).toBe(true);
expect(scopeNode.repo).toEqual({
...repo,
url,
});
expect(scopeNode.print()).toBeNull();
});
it("should print a scope & its commit", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const scope = "commit-scope";
const description = "ci: update test workflow";
const scopeNode = new ScopeNode(scope);
const commitNode = scopeNode.addCommit(description);
expect(scopeNode.scope).toBe(scope);
expect(scopeNode.shouldUseGithubAutolink).toBe(true);
expect(commitNode).toBeInstanceOf(CommitNode);
expect(scopeNode.print()).toBe(`* **${ scope }:**\n${ commitNode.print(" ") }`);
});
it("should reuse the same commit message (in the case the breaking matches as well)", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const scope = "commit-scope";
const description = "ci: update test workflow";
const scopeNode = new ScopeNode(scope);
const commitNode = scopeNode.addCommit(description);
const commitNode2 = scopeNode.addCommit(description);
expect(scopeNode.scope).toBe(scope);
expect(scopeNode.shouldUseGithubAutolink).toBe(true);
expect(commitNode).toBeInstanceOf(CommitNode);
expect(commitNode2).toBeInstanceOf(CommitNode);
expect(commitNode).toBe(commitNode2);
const result = scopeNode.print();
expect(result).toBe(`* **${ scope }:**\n${ commitNode.print(" ") }`);
expect(result).toBe(`* **${ scope }:**\n${ commitNode2.print(" ") }`);
});
it("should print a scope & its commit with prefix", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const scope = "commit-scope";
const description = "ci: update test workflow";
const scopeNode = new ScopeNode(scope);
const commitNode = scopeNode.addCommit(description);
expect(scopeNode.scope).toBe(scope);
expect(scopeNode.shouldUseGithubAutolink).toBe(true);
expect(commitNode).toBeInstanceOf(CommitNode);
const prefix = " ";
expect(scopeNode.print(prefix)).toBe(`${ prefix }* **${ scope }:**\n${ commitNode.print(`${ prefix } `) }`);
});
it("should print a scope & its multiple commits", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const scope = "commit-scope";
const description = "ci: update test workflow";
const description2 = "chore: update copyright year";
const scopeNode = new ScopeNode(scope);
const commitNode = scopeNode.addCommit(description);
const commitNode2 = scopeNode.addCommit(description2);
expect(scopeNode.scope).toBe(scope);
expect(scopeNode.shouldUseGithubAutolink).toBe(true);
expect(commitNode).toBeInstanceOf(CommitNode);
expect(commitNode2).toBeInstanceOf(CommitNode);
expect(scopeNode.print()).toBe(`* **${ scope }:**\n${ commitNode.print(" ") }\n${ commitNode2.print(" ") }`);
});
it("should print a commit without scope", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const description = "ci: update test workflow";
const scopeNode = (new ScopeNode);
const commitNode = scopeNode.addCommit(description);
expect(scopeNode.scope).toBe("");
expect(scopeNode.shouldUseGithubAutolink).toBe(true);
expect(commitNode).toBeInstanceOf(CommitNode);
expect(scopeNode.print()).toBe(`${ commitNode.print() }`);
});
it("should print multiple commits without scope", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const description = "ci: update test workflow";
const description2 = "chore: update copyright year";
const scopeNode = (new ScopeNode);
const commitNode = scopeNode.addCommit(description);
const commitNode2 = scopeNode.addCommit(description2);
expect(scopeNode.scope).toBe("");
expect(scopeNode.shouldUseGithubAutolink).toBe(true);
expect(commitNode).toBeInstanceOf(CommitNode);
expect(commitNode2).toBeInstanceOf(CommitNode);
expect(scopeNode.print()).toBe(`${ commitNode.print() }\n${ commitNode2.print() }`);
});
+198
View File
@@ -0,0 +1,198 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { context } from "@actions/github";
import { CommitNode, Node, ScopeNode, TypeNode } from "../../src/nodes";
const repo = {
owner: "ardalanamini",
repo : "auto-changelog",
};
const url = `${ context.serverUrl }/${ repo.owner }/${ repo.repo }`;
beforeEach(() => {
jest.spyOn(context, "repo", "get").mockReturnValueOnce(repo);
});
it("should not print anything when no scopes/commits are added", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const commitType = "commit-type";
const typeNode = new TypeNode(commitType);
expect(typeNode).toBeInstanceOf(Node);
expect(typeNode.type).toBe(commitType);
expect(typeNode.shouldUseGithubAutolink).toBe(true);
expect(typeNode.repo).toEqual({
...repo,
url,
});
expect(typeNode.print()).toBeNull();
});
it("should not print anything when no commits are added", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const commitType = "commit-type";
const scope = "commit-scope";
const typeNode = new TypeNode(commitType);
const scopeNode = typeNode.addScope(scope);
expect(typeNode.type).toBe(commitType);
expect(typeNode.shouldUseGithubAutolink).toBe(true);
expect(scopeNode).toBeInstanceOf(ScopeNode);
expect(typeNode.print()).toBeNull();
});
it("should print a type & its scope/commit", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const commitType = "commit-type";
const scope = "commit-scope";
const description = "ci: update test workflow";
const typeNode = new TypeNode(commitType);
const scopeNode = typeNode.addScope(scope);
const commitNode = scopeNode.addCommit(description);
expect(typeNode.type).toBe(commitType);
expect(typeNode.shouldUseGithubAutolink).toBe(true);
expect(scopeNode).toBeInstanceOf(ScopeNode);
expect(commitNode).toBeInstanceOf(CommitNode);
expect(typeNode.print()).toBe(`## ${ commitType }\n${ scopeNode.print() }`);
});
it("should reuse the same scope (in the case the breaking matches as well)", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const commitType = "commit-type";
const scope = "commit-scope";
const description = "ci: update test workflow";
const description2 = "chore: update copyright year";
const typeNode = new TypeNode(commitType);
const scopeNode = typeNode.addScope(scope);
const scopeNode2 = typeNode.addScope(scope);
const commitNode = scopeNode.addCommit(description);
const commitNode2 = scopeNode2.addCommit(description2);
expect(typeNode.type).toBe(commitType);
expect(typeNode.shouldUseGithubAutolink).toBe(true);
expect(scopeNode).toBeInstanceOf(ScopeNode);
expect(scopeNode2).toBeInstanceOf(ScopeNode);
expect(scopeNode).toBe(scopeNode2);
expect(commitNode).toBeInstanceOf(CommitNode);
expect(commitNode2).toBeInstanceOf(CommitNode);
const result = typeNode.print();
expect(result).toBe(`## ${ commitType }\n${ scopeNode.print() }`);
expect(result).toBe(`## ${ commitType }\n${ scopeNode2.print() }`);
});
it("should print a type & its scope/commit with prefix", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const commitType = "commit-type";
const scope = "commit-scope";
const description = "ci: update test workflow";
const typeNode = new TypeNode(commitType);
const scopeNode = typeNode.addScope(scope);
const commitNode = scopeNode.addCommit(description);
expect(typeNode.type).toBe(commitType);
expect(typeNode.shouldUseGithubAutolink).toBe(true);
expect(scopeNode).toBeInstanceOf(ScopeNode);
expect(commitNode).toBeInstanceOf(CommitNode);
const prefix = " ";
expect(typeNode.print(prefix)).toBe(`${ prefix }## ${ commitType }\n${ scopeNode.print(prefix) }`);
});
it("should print a type & its multiple scope/commits", () => {
jest.mocked(getBooleanInput).mockReturnValue(true);
const commitType = "commit-type";
const scope = "commit-scope";
const description = "ci: update test workflow";
const description2 = "chore: update copyright year";
const typeNode = new TypeNode(commitType);
const scopeNode = typeNode.addScope(scope);
const commitNode = scopeNode.addCommit(description);
const scopeNode2 = typeNode.addScope();
const commitNode2 = scopeNode2.addCommit(description2);
expect(typeNode.type).toBe(commitType);
expect(typeNode.shouldUseGithubAutolink).toBe(true);
expect(scopeNode).toBeInstanceOf(ScopeNode);
expect(scopeNode2).toBeInstanceOf(ScopeNode);
expect(commitNode).toBeInstanceOf(CommitNode);
expect(commitNode2).toBeInstanceOf(CommitNode);
expect(typeNode.print()).toBe(`## ${ commitType }\n${ scopeNode2.print() }\n${ scopeNode.print() }`);
});
+40
View File
@@ -0,0 +1,40 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { info, setOutput } from "@actions/core";
import { setChangelog } from "../../src/outputs";
it("should log and set the changelog output", () => {
const outputValue = "Changelog Value";
setChangelog(outputValue);
const outputName = "changelog";
expect(info).toHaveBeenCalledTimes(1);
expect(info).toHaveBeenCalledWith(`output -> ${ outputName }: ${ outputValue }`);
expect(setOutput).toHaveBeenCalledTimes(1);
expect(setOutput).toHaveBeenCalledWith(outputName, outputValue);
});
+38
View File
@@ -0,0 +1,38 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { info, setOutput } from "@actions/core";
import { setPrerelease } from "../../src/outputs";
it.each([true, false])("should output \"prerelease\" value as %j", (outputValue) => {
setPrerelease(outputValue);
const outputName = "prerelease";
expect(info).toHaveBeenCalledTimes(1);
expect(info).toHaveBeenCalledWith(`output -> ${ outputName }: ${ outputValue }`);
expect(setOutput).toHaveBeenCalledTimes(1);
expect(setOutput).toHaveBeenCalledWith(outputName, outputValue);
});
+39
View File
@@ -0,0 +1,39 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { info, setOutput } from "@actions/core";
import { setReleaseId } from "../../src/outputs";
it("should output \"release-id\" value", () => {
const outputName = "release-id";
const outputValue = "latest";
setReleaseId(outputValue);
expect(info).toHaveBeenCalledTimes(1);
expect(info).toHaveBeenCalledWith(`output -> ${ outputName }: ${ outputValue }`);
expect(setOutput).toHaveBeenCalledTimes(1);
expect(setOutput).toHaveBeenCalledWith(outputName, outputValue);
});
+134
View File
@@ -0,0 +1,134 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput, getInput } from "@actions/core";
import { getOctokit } from "@actions/github";
import { GitHub } from "@actions/github/lib/utils";
import fetchMock from "fetch-mock";
import { getTagInfo } from "../src/tag";
it("should get tag information", async () => {
const gitHubTokenInputName = "github-token";
const gitHubTokenInputValue = "github-token-value";
jest.mocked(getInput).mockImplementationOnce((name) => {
if (name === gitHubTokenInputName) return gitHubTokenInputValue;
return "";
});
const info = {
releaseId : "latest",
prerelease: false,
previous : {
name: "1.0.0",
sha : "3c1177539c1a216084f922ea52e56dd719a25945",
},
};
const fetch = fetchMock.getOnce(
"begin:https://api.github.com/repos/ardalanamini/auto-changelog/tags",
[
{
name : info.previous.name,
commit: {
sha: info.previous.sha,
},
},
],
);
const gitHub = new GitHub({ request: { fetch: fetch.fetchHandler } });
jest.mocked(getOctokit).mockImplementationOnce(() => gitHub);
const result = await getTagInfo();
expect(result).toEqual(info);
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith(gitHubTokenInputName, { required: true });
expect(getOctokit).toHaveBeenCalledTimes(1);
expect(getOctokit).toHaveBeenCalledWith(gitHubTokenInputValue);
});
it("should get semver tag information", async () => {
const gitHubTokenInputName = "github-token";
const gitHubTokenInputValue = "github-token-value";
const releaseNameInputName = "release-name";
const releaseNameInputValue = "2.0.0-beta.1";
const releaseNamePrefixInputName = "release-name-prefix";
const releaseNamePrefixInputValue = "";
jest.mocked(getBooleanInput).mockReturnValueOnce(true);
jest.mocked(getInput).mockImplementation((name) => {
switch (name) {
case gitHubTokenInputName: return gitHubTokenInputValue;
case releaseNameInputName: return releaseNameInputValue;
case releaseNamePrefixInputName: return releaseNamePrefixInputValue;
default: return "";
}
});
const info = {
releaseId : "beta",
prerelease: true,
previous : {
name: "1.0.0",
sha : "3c1177539c1a216084f922ea52e56dd719a25945",
},
};
const fetch = fetchMock.getOnce(
"begin:https://api.github.com/repos/ardalanamini/auto-changelog/tags",
[
{
name : info.previous.name,
commit: {
sha: info.previous.sha,
},
},
],
);
const gitHub = new GitHub({ request: { fetch: fetch.fetchHandler } });
jest.mocked(getOctokit).mockImplementationOnce(() => gitHub);
const result = await getTagInfo();
expect(result).toEqual(info);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
expect(getInput).toHaveBeenCalledTimes(3);
expect(getInput).toHaveBeenCalledWith(gitHubTokenInputName, { required: true });
expect(getInput).toHaveBeenCalledWith(releaseNameInputName, { required: true });
expect(getInput).toHaveBeenCalledWith(releaseNamePrefixInputName, { required: false });
expect(getOctokit).toHaveBeenCalledTimes(1);
expect(getOctokit).toHaveBeenCalledWith(gitHubTokenInputValue);
});
+67
View File
@@ -0,0 +1,67 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getBooleanInput } from "@actions/core";
import { booleanInput, cache } from "../../src/utils";
it("should get and parse a boolean input", () => {
const inputName = "foo";
const inputValue = true;
jest.mocked(getBooleanInput).mockReturnValueOnce(inputValue);
const result = booleanInput(inputName);
expect(result).toEqual(inputValue);
expect(getBooleanInput).toHaveBeenCalledTimes(1);
expect(getBooleanInput).toHaveBeenCalledWith(inputName, { required: true });
});
it("should get a cached boolean input", () => {
const inputName = "foo";
const inputValue = true;
cache(inputName, () => inputValue);
const result = booleanInput(inputName);
expect(result).toEqual(inputValue);
expect(getBooleanInput).toHaveBeenCalledTimes(0);
});
it("should get and parse an optional boolean input", () => {
const inputName = "foo";
const inputValue = false;
jest.mocked(getBooleanInput).mockReturnValueOnce(inputValue);
const result = booleanInput(inputName, false);
expect(result).toEqual(inputValue);
expect(getBooleanInput).toHaveBeenCalledTimes(1);
expect(getBooleanInput).toHaveBeenCalledWith(inputName, { required: false });
});
+90
View File
@@ -0,0 +1,90 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { cache, clearCache } from "../../src/utils";
it("should cache value", () => {
const name = "foo";
const value = "bar";
const fn = jest.fn(() => value);
const firstCallResult = cache(name, fn);
expect(firstCallResult).toBe(value);
expect(fn).toHaveBeenCalledTimes(1);
fn.mockClear();
const secondCallResult = cache(name, fn);
expect(secondCallResult).toBe(value);
expect(fn).toHaveBeenCalledTimes(0);
});
it("should overwrite cache value", () => {
const name = "foo";
const value = "bar";
const fn = jest.fn(() => value);
const firstCallResult = cache(name, fn);
expect(firstCallResult).toBe(value);
expect(fn).toHaveBeenCalledTimes(1);
fn.mockClear();
const secondCallResult = cache(name, fn, true);
expect(secondCallResult).toBe(value);
expect(fn).toHaveBeenCalledTimes(1);
});
it("should clear cache", () => {
const name = "foo";
const value = "bar";
const fn = jest.fn(() => value);
const firstCallResult = cache(name, fn);
expect(firstCallResult).toBe(value);
expect(fn).toHaveBeenCalledTimes(1);
fn.mockClear();
clearCache();
const secondCallResult = cache(name, fn);
expect(secondCallResult).toBe(value);
expect(fn).toHaveBeenCalledTimes(1);
});
+92
View File
@@ -0,0 +1,92 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getInput } from "@actions/core";
import { getOctokit } from "@actions/github";
import { GitHub } from "@actions/github/lib/utils";
import fetchMock from "fetch-mock";
import { iterateCommits } from "../../src/utils";
it("should iterate over commits", async () => {
const repo = {
owner: "ardalanamini",
repo : "auto-changelog",
};
const gitHubTokenInputName = "github-token";
const gitHubTokenInputValue = "github-token-value";
jest.mocked(getInput).mockImplementationOnce((name) => {
if (name === gitHubTokenInputName) return gitHubTokenInputValue;
return "";
});
const commit = {
author: {
login: "ardalanamini",
},
commit: {
message: "ci: update test workflow\n\nSigned-off-by: Ardalan Amini <[email protected]>",
},
sha: "3c1177539c1a216084f922ea52e56dd719a25945",
};
const fromSha = "7a94b0db6150850cb1ae7243b13a4c972e9db261";
const fetch = fetchMock.getOnce(
"begin:https://api.github.com/repos/ardalanamini/auto-changelog/commits",
[
commit, {
author: {
login: "ardalanamini",
},
commit: {
message: "chore: update copyright year\n\nSigned-off-by: Ardalan Amini <[email protected]>",
},
sha: fromSha,
},
],
);
const gitHub = new GitHub({ request: { fetch: fetch.fetchHandler } });
jest.mocked(getOctokit).mockImplementationOnce(() => gitHub);
const result = iterateCommits(repo.owner, repo.repo, fromSha);
expect(await result.next()).toEqual({
done : false,
value: commit,
});
expect(await result.next()).toEqual({
done: true,
});
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith(gitHubTokenInputName, { required: true });
expect(getOctokit).toHaveBeenCalledTimes(1);
expect(getOctokit).toHaveBeenCalledWith(gitHubTokenInputValue);
});
+93
View File
@@ -0,0 +1,93 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getInput } from "@actions/core";
import { cache, input } from "../../src/utils";
it("should get input value", () => {
const name = "foo";
const value = "bar";
jest.mocked(getInput).mockReturnValueOnce(value);
const result = input(name);
expect(result).toBe(value);
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith(name, { required: true });
});
it("should get cached input value", () => {
const name = "foo";
const value = "bar";
cache(name, () => value);
const result = input(name);
expect(result).toBe(value);
expect(getInput).toHaveBeenCalledTimes(0);
});
it("should get optional input value", () => {
const name = "foo";
const value = "";
jest.mocked(getInput).mockReturnValueOnce(value);
const result = input(name, false);
expect(result).toBe(value);
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith(name, { required: false });
});
it("should get parsed input value", () => {
const name = "foo";
jest.mocked(getInput).mockReturnValueOnce("1");
const result = input(name, inputValue => +inputValue);
expect(result).toBe(1);
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith(name, { required: true });
});
it("should get parsed optional input value", () => {
const name = "foo";
jest.mocked(getInput).mockReturnValueOnce("");
const result = input(name, inputValue => +(inputValue || "1"), false);
expect(result).toBe(1);
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith(name, { required: false });
});
+51
View File
@@ -0,0 +1,51 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getInput } from "@actions/core";
import { getOctokit } from "@actions/github";
import { GitHub } from "@actions/github/lib/utils";
import { octokit } from "../../src/utils";
it("should get octokit instance", () => {
const gitHubTokenInputName = "github-token";
const gitHubTokenInputValue = "github-token-value";
jest.mocked(getInput).mockImplementationOnce((name) => {
if (name === gitHubTokenInputName) return gitHubTokenInputValue;
return "";
});
jest.mocked(getOctokit).mockImplementationOnce(() => new GitHub);
const result = octokit();
expect(result).toBeInstanceOf(GitHub);
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith(gitHubTokenInputName, { required: true });
expect(getOctokit).toHaveBeenCalledTimes(1);
expect(getOctokit).toHaveBeenCalledWith(gitHubTokenInputValue);
});
+39
View File
@@ -0,0 +1,39 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { info, setOutput } from "@actions/core";
import { output } from "../../src/utils";
it("should output value", () => {
const name = "foo";
const value = "bar";
output(name, value);
expect(info).toHaveBeenCalledTimes(1);
expect(info).toHaveBeenCalledWith(`output -> ${ name }: ${ value }`);
expect(setOutput).toHaveBeenCalledTimes(1);
expect(setOutput).toHaveBeenCalledWith(name, value);
});
+1 -2
View File
@@ -1,4 +1,4 @@
/*
/**
* MIT License
*
* Copyright (c) 2024-2025 Ardalan Amini
@@ -20,7 +20,6 @@
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
/* eslint-disable no-undefined */
+104
View File
@@ -0,0 +1,104 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { getInput } from "@actions/core";
import { parseSemVer } from "../../src/utils";
it("should parse the semver version string", () => {
const major = 1;
const minor = 2;
const patch = 3;
const prerelease = "alpha";
const prereleaseVersion = 4;
const version = `${ major }.${ minor }.${ patch }-${ prerelease }.${ prereleaseVersion }`;
const raw = `v${ version }`;
const releaseNamePrefix = "@actions/github/";
jest.mocked(getInput).mockImplementationOnce((name) => {
if (name === "release-name-prefix") return releaseNamePrefix;
return "";
});
const result = parseSemVer(raw);
expect(result).toBeDefined();
expect(result).toEqual({
build : [],
includePrerelease: true,
loose : false,
major,
minor,
options : { includePrerelease: true },
patch,
prerelease : [prerelease, prereleaseVersion],
raw,
version,
});
expect(getInput).toHaveBeenCalledTimes(1);
expect(getInput).toHaveBeenCalledWith("release-name-prefix", { required: false });
});
it("should parse the release name by default", () => {
const major = 1;
const minor = 2;
const patch = 3;
const prerelease = "alpha";
const prereleaseVersion = 4;
const version = `${ major }.${ minor }.${ patch }-${ prerelease }.${ prereleaseVersion }`;
const raw = `v${ version }`;
const releaseNamePrefix = "@actions/github/";
jest.mocked(getInput).mockImplementation((name) => {
switch (name) {
case "release-name":
return raw;
case "release-name-prefix":
return releaseNamePrefix;
default:
return "";
}
});
const result = parseSemVer();
expect(result).toBeDefined();
expect(result).toEqual({
build : [],
includePrerelease: true,
loose : false,
major,
minor,
options : { includePrerelease: true },
patch,
prerelease : [prerelease, prereleaseVersion],
raw,
version,
});
expect(getInput).toHaveBeenCalledTimes(2);
expect(getInput).toHaveBeenNthCalledWith(1, "release-name", { required: true });
expect(getInput).toHaveBeenNthCalledWith(2, "release-name-prefix", { required: false });
});
+46
View File
@@ -0,0 +1,46 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { context } from "@actions/github";
import { repository } from "../../src/utils";
it("should get the repository information with constructed URL", () => {
const repo = {
owner: "ardalanamini",
repo : "auto-changelog",
};
const serverUrl = context.serverUrl;
expect(serverUrl).toEqual("https://github.com");
jest.spyOn(context, "repo", "get").mockReturnValueOnce(repo);
const result = repository();
expect(result).toEqual({
...repo,
url: `${ serverUrl }/${ repo.owner }/${ repo.repo }`,
});
});
+63
View File
@@ -0,0 +1,63 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { context } from "@actions/github";
import { sha } from "../../src/utils";
it("should get the current commit sha", () => {
const shaValue = "3c1177539c1a216084f922ea52e56dd719a25945";
const original = jest.mocked(context).sha;
jest.mocked(context).sha = shaValue;
const result = sha();
jest.mocked(context).sha = original;
expect(result).toBe(shaValue);
});
it("should cache the sha value", () => {
const shaValue: string = "3c1177539c1a216084f922ea52e56dd719a25945";
const original = jest.mocked(context).sha;
jest.mocked(context).sha = shaValue;
// The first call should access context.sha
const result1 = sha();
// Change the mocked value
jest.mocked(context).sha = "different-sha";
// Second call should return cached value, not the new mocked value
const result2 = sha();
jest.mocked(context).sha = original;
expect(result1).toBe(shaValue);
// Should be cached
expect(result2).toBe(shaValue);
});
+54
View File
@@ -0,0 +1,54 @@
/**
* MIT License
*
* Copyright (c) 2025 Ardalan Amini
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { trim } from "../../src/utils/trim.js";
it("should remove leading and trailing whitespace", () => {
expect(trim(" hello ")).toBe("hello");
});
it("should replace multiple spaces with a single space", () => {
expect(trim("hello world")).toBe("hello world");
});
it("should handle null value", () => {
expect(trim(null)).toBeNull();
});
it("should handle undefined value", () => {
// eslint-disable-next-line no-undefined,@typescript-eslint/no-confusing-void-expression
expect(trim(undefined)).toBeUndefined();
});
it("should handle empty string", () => {
expect(trim("")).toBe("");
});
it("should handle string with no extra spaces", () => {
expect(trim("hello")).toBe("hello");
});
it("should handle strings with only spaces", () => {
expect(trim(" ")).toBe("");
});
+5 -1
View File
@@ -1,4 +1,8 @@
{
"extends": "./tsconfig.json",
"exclude": ["commitlint.config.cts", "jest.config.ts", "tests"]
"compilerOptions": {
"rootDir": "src",
"tsBuildInfoFile": "./.cache/typescript/tsconfig.build.tsbuildinfo"
},
"exclude": ["commitlint.config.cts", "jest.config.ts", "tests", "__mocks__"]
}
+2 -2
View File
@@ -15,9 +15,9 @@
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "dist", /* Redirect output structure to the directory. */
"rootDir": "src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"rootDir": ".", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
"tsBuildInfoFile": "./.cache/typescript/tsconfig.tsbuildinfo", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */