@@ -2,11 +2,27 @@ import * as fs from "node:fs";
22
33import { DryRunOption , PACKAGE_JSON } from "./config" ;
44
5+ export function withPackageJson < T > (
6+ transformer : ( content : string ) => { value : T ; content ?: string } ,
7+ options : DryRunOption ,
8+ ) : T {
9+ const content = fs . readFileSync ( PACKAGE_JSON , "utf8" ) ;
10+ const result = transformer ( content ) ;
11+
12+ if ( result . content !== undefined ) {
13+ if ( ! options . dryRun ) {
14+ fs . writeFileSync ( PACKAGE_JSON , result . content , "utf8" ) ;
15+ } else {
16+ console . info ( `[DRY RUN] Would have written an updated package.json` ) ;
17+ }
18+ }
19+
20+ return result . value ;
21+ }
22+
523/** Reads the current version from `package.json`. */
6- export function getCurrentVersion ( ) : string | undefined {
7- const pkg : { version : string } = JSON . parse (
8- fs . readFileSync ( PACKAGE_JSON , "utf8" ) ,
9- ) ;
24+ export function getCurrentVersion ( content : string ) : string | undefined {
25+ const pkg : { version : string } = JSON . parse ( content ) ;
1026 return pkg . version ;
1127}
1228
@@ -17,11 +33,11 @@ export function getCurrentVersion(): string | undefined {
1733 * replace the version in package.json textually.
1834 */
1935export function replaceVersionInPackageJson (
20- options : DryRunOption ,
2136 prevVersion : string ,
2237 newVersion : string ,
23- ) : void {
24- const lines = fs . readFileSync ( PACKAGE_JSON , "utf8" ) . split ( "\n" ) ;
38+ content : string ,
39+ ) : string {
40+ const lines = content . split ( "\n" ) ;
2541 let prevLineIsCodeql = false ;
2642 const output : string [ ] = [ ] ;
2743
@@ -34,11 +50,5 @@ export function replaceVersionInPackageJson(
3450 prevLineIsCodeql = line . includes ( '"name": "codeql",' ) ;
3551 }
3652
37- if ( ! options . dryRun ) {
38- fs . writeFileSync ( PACKAGE_JSON , `${ output . join ( "\n" ) } \n` , "utf8" ) ;
39- } else {
40- console . info (
41- `[DRY RUN] Would have replaced '${ prevVersion } ' with '${ newVersion } ' in package.json` ,
42- ) ;
43- }
53+ return output . join ( "\n" ) ;
4454}
0 commit comments