7
7
IBuildstamp ,
8
8
IBuildstampOptions ,
9
9
IBuildstampOptionsNormalized ,
10
- IGitInfo
10
+ IGitInfo ,
11
+ ICallable
11
12
} from './interface'
12
13
13
14
export const normalizeOpts = ( {
@@ -16,6 +17,7 @@ export const normalizeOpts = ({
16
17
ci = true ,
17
18
git = true ,
18
19
date = true ,
20
+ safe = false ,
19
21
extra = { }
20
22
} : IBuildstampOptions = { } ) : IBuildstampOptionsNormalized => ( {
21
23
ci,
@@ -24,25 +26,27 @@ export const normalizeOpts = ({
24
26
git,
25
27
date,
26
28
extra,
29
+ safe
27
30
} )
28
31
29
32
export const buildstamp = async ( opts ?: IBuildstampOptions ) : Promise < IBuildstamp > => {
30
- const { ci, git, date, cwd, output, extra} = normalizeOpts ( opts )
33
+ const { ci, git, date, cwd, output, extra, safe } = normalizeOpts ( opts )
31
34
const stamp : IBuildstamp = { ...extra }
35
+ const s = safe ? safify : ( v : any ) => v
32
36
33
37
if ( date ) {
34
38
stamp . date = new Date ( ) . toISOString ( )
35
39
}
36
40
if ( git ) {
37
- Object . assign ( stamp , await getGitInfo ( cwd , process . env ) )
41
+ Object . assign ( stamp , await s ( getGitInfo ) ( cwd , process . env ) )
38
42
}
39
43
if ( ci ) {
40
- Object . assign ( stamp , getCIInfo ( process . env ) )
44
+ Object . assign ( stamp , s ( getCIInfo ) ( process . env ) )
41
45
}
42
46
if ( output ) {
43
- const file = path . resolve ( cwd , output )
44
- await fs . mkdir ( path . dirname ( file ) , { recursive : true } )
45
- await fs . writeFile ( file , JSON . stringify ( stamp , null , 2 ) )
47
+ const file = s ( path . resolve ) ( cwd , output )
48
+ await s ( fs . mkdir ) ( s ( path . dirname ) ( file ) , { recursive : true } )
49
+ await s ( fs . writeFile ) ( file , JSON . stringify ( stamp , null , 2 ) )
46
50
}
47
51
48
52
return stamp
@@ -106,3 +110,12 @@ export const spawn = (
106
110
} )
107
111
} )
108
112
} )
113
+
114
+ export const safify = < T extends ICallable > ( fn : T , value : any = { } ) : T => ( ( ...args : any [ ] ) => {
115
+ try {
116
+ const result = fn ( ...args )
117
+ return result ?. then ( ( v : any ) => v , ( ) => value ) || result
118
+ } catch {
119
+ return value
120
+ }
121
+ } ) as T
0 commit comments