1- import path from 'node:path' ;
2- import fs from 'node:fs' ;
1+ import * as path from 'node:path' ;
32import { ConfigModel , OutputFormat } from '../models/ConfigModel' ;
43import { BundleName , getMessage } from '../messages' ;
54import { Display } from '../Display' ;
6- import { exists } from '../utils/FileUtil' ;
5+ import { FileSystem , RealFileSystem } from '../utils/FileUtil' ;
76
87export interface ConfigWriter {
98 write ( model : ConfigModel ) : Promise < boolean > ;
@@ -13,27 +12,29 @@ export class ConfigFileWriter implements ConfigWriter {
1312 private readonly file : string ;
1413 private readonly format : OutputFormat ;
1514 private readonly display : Display ;
15+ private readonly fileSystem : FileSystem ;
1616
17- private constructor ( file : string , format : OutputFormat , display : Display ) {
17+ private constructor ( file : string , format : OutputFormat , display : Display , fileSystem : FileSystem ) {
1818 this . file = file ;
1919 this . format = format ;
2020 this . display = display ;
21+ this . fileSystem = fileSystem ;
2122 }
2223
2324 public async write ( model : ConfigModel ) : Promise < boolean > {
2425 // Only write to the file if it doesn't already exist, or if the user confirms that they want to overwrite it.
25- if ( ! ( await exists ( this . file ) ) || await this . display . confirm ( getMessage ( BundleName . ConfigWriter , 'prompt.overwrite-existing-file' , [ this . file ] ) ) ) {
26- fs . writeFileSync ( this . file , model . toFormattedOutput ( this . format ) ) ;
26+ if ( ! ( await this . fileSystem . exists ( this . file ) ) || await this . display . confirm ( getMessage ( BundleName . ConfigWriter , 'prompt.overwrite-existing-file' , [ this . file ] ) ) ) {
27+ this . fileSystem . writeFileSync ( this . file , model . toFormattedOutput ( this . format ) ) ;
2728 return true ;
2829 } else {
2930 return false ;
3031 }
3132 }
3233
33- public static fromFile ( file : string , display : Display ) : ConfigFileWriter {
34+ public static fromFile ( file : string , display : Display , fileSystem : FileSystem = new RealFileSystem ( ) ) : ConfigFileWriter {
3435 const ext = path . extname ( file ) . toLowerCase ( ) ;
3536 if ( ext === '.yaml' || ext === '.yml' ) {
36- return new ConfigFileWriter ( file , OutputFormat . RAW_YAML , display ) ;
37+ return new ConfigFileWriter ( file , OutputFormat . RAW_YAML , display , fileSystem ) ;
3738 } else {
3839 throw new Error ( getMessage ( BundleName . ConfigWriter , 'error.unrecognized-file-format' , [ file ] ) ) ;
3940 }
0 commit comments