@@ -4,6 +4,48 @@ import path from "node:path";
4
4
5
5
import { fallbackLogger , type Logger } from "./shared/cli/logger.js" ;
6
6
7
+ export function appendAuthBlockContent ( {
8
+ npmrc,
9
+ existingContent = "" ,
10
+ logger = fallbackLogger ,
11
+ } : {
12
+ npmrc : string ;
13
+ existingContent ?: string ;
14
+ logger ?: Logger ;
15
+ } ) : string {
16
+ // find our auth token block in the existing content
17
+ const authTokenPattern = / ; b e g i n a u t h t o k e n \n [ \s \S ] * ?\n ; e n d a u t h t o k e n \n ? / ;
18
+
19
+ let newContent : string ;
20
+ if ( existingContent && authTokenPattern . test ( existingContent ) ) {
21
+ logger . info ( "Found existing auth token block(s), replacing all of them" ) ;
22
+ // using global flag to find all blocks and replace them with a single new block
23
+ const replacePattern = / ; b e g i n a u t h t o k e n \n [ \s \S ] * ?\n ; e n d a u t h t o k e n \n ? / g;
24
+ let replacedFirst = false ;
25
+ newContent = existingContent . replace ( replacePattern , ( ) => {
26
+ if ( ! replacedFirst ) {
27
+ replacedFirst = true ;
28
+ return npmrc ;
29
+ }
30
+ // empty string for subsequent matches to remove duplicates
31
+ return "" ;
32
+ } ) ;
33
+ } else {
34
+ if ( existingContent ) {
35
+ logger . info (
36
+ "No existing auth token block found, appending to existing content" ,
37
+ ) ;
38
+
39
+ const separator = existingContent . endsWith ( "\n" ) ? "" : "\n" ;
40
+ newContent = existingContent + separator + npmrc ;
41
+ } else {
42
+ newContent = npmrc ;
43
+ }
44
+ }
45
+
46
+ return newContent ;
47
+ }
48
+
7
49
export async function writeNpmrc ( {
8
50
npmrc,
9
51
logger = fallbackLogger ,
@@ -20,9 +62,24 @@ export async function writeNpmrc({
20
62
logger . info ( `Writing users .npmrc to: ${ userNpmrcPath } ` ) ;
21
63
22
64
try {
23
- // Write the content to the .npmrc file
24
- // fs.appendFile will create the file if it doesn't exist
25
- await fs . appendFile ( userNpmrcPath , npmrc , "utf8" ) ;
65
+ let existingContent = "" ;
66
+ try {
67
+ existingContent = await fs . readFile ( userNpmrcPath , "utf8" ) ;
68
+ } catch ( error ) {
69
+ // gracefully fail, file will be created later
70
+ if ( ( error as NodeJS . ErrnoException ) . code !== "ENOENT" ) {
71
+ throw error ;
72
+ }
73
+ }
74
+
75
+ const newContent = appendAuthBlockContent ( {
76
+ npmrc,
77
+ existingContent,
78
+ logger,
79
+ } ) ;
80
+
81
+ // Write the updated content to the .npmrc file
82
+ await fs . writeFile ( userNpmrcPath , newContent , "utf8" ) ;
26
83
logger . info ( "Successfully wrote .npmrc file" ) ;
27
84
} catch ( error ) {
28
85
const errorMessage = `Error writing users .npmrc to ${ userNpmrcPath } : ${ error instanceof Error ? error . message : "" } ` ;
0 commit comments