11import { OPTIONS_TYPES } from './utils/constance'
2- import { parseOptions , getPathsAsync , replaceFactory } from './utils/index'
2+ import { parseOptions , getPathsAsync , getPathsSync , replaceFactory } from './utils/index'
33import * as fs from 'fs' ;
44/**
55 * Async main
66 */
7- const replaceStringInFiles = ( options : OPTIONS_TYPES ) => {
7+ export const replaceStringInFiles = ( options : OPTIONS_TYPES ) => {
88 try {
99 options = parseOptions ( options )
1010 } catch ( error ) {
1111 return Promise . reject ( error )
1212 }
1313
14- const { files, from , to , freeze } = options
14+ const { files, freeze } = options
1515
1616 // freeze mode, do not replace
1717 if ( freeze ) {
@@ -27,12 +27,22 @@ const replaceStringInFiles = (options: OPTIONS_TYPES) => {
2727/**
2828 * Sync replaceStringInFiles
2929 */
30- const replaceStringInFilesSync = ( options : OPTIONS_TYPES ) => {
30+ export const replaceStringInFilesSync = ( options : OPTIONS_TYPES ) => {
31+ options = parseOptions ( options )
3132
33+ const { files, freeze } = options
34+ const paths = getPathsSync ( files , options ) ;
35+
36+ // freeze mode, do not replace
37+ if ( freeze ) {
38+ console . warn ( 'running in freeze mode, no change...' )
39+ }
40+ if ( ! Array . isArray ( paths ) ) return replaceFileSync ( paths , options )
41+ return paths . map ( ( path ) => replaceFileSync ( path , options ) )
3242}
3343
3444/**
35- * replace string in single file
45+ * async replace string in single file
3646 */
3747const replaceFileAsync = ( file : string , options : OPTIONS_TYPES ) => {
3848 const { from, to, encoding, freeze, countMatches } = options
@@ -54,3 +64,17 @@ const replaceFileAsync = (file: string, options: OPTIONS_TYPES) => {
5464 } )
5565 } )
5666}
67+
68+ /**
69+ * sync replace string in single file
70+ */
71+ const replaceFileSync = ( file : string , options : OPTIONS_TYPES ) => {
72+ const { from, to, encoding, freeze, countMatches } = options
73+ const contents = fs . readFileSync ( file , encoding ) ;
74+
75+ const { result, newContents } = replaceFactory ( contents , from , to , file , countMatches )
76+
77+ if ( ! result . changed || freeze ) return result
78+
79+ fs . writeFileSync ( file , newContents , encoding )
80+ }
0 commit comments