2
2
const fs = require ( 'fs' )
3
3
const path = require ( 'path' )
4
4
5
+ /* istanbul ignore next */
6
+ const LCHOWN = fs . lchown ? 'lchown' : 'chown'
7
+ /* istanbul ignore next */
8
+ const LCHOWNSYNC = fs . lchownSync ? 'lchownSync' : 'chownSync'
9
+
5
10
const chownr = ( p , uid , gid , cb ) => {
6
11
fs . readdir ( p , ( er , children ) => {
7
12
// any error other than ENOTDIR means it's not readable, or
8
13
// doesn't exist. give up.
9
14
if ( er && er . code !== 'ENOTDIR' ) return cb ( er )
10
- if ( er || ! children . length ) return fs . lchown ( p , uid , gid , cb )
15
+ if ( er || ! children . length ) return fs [ LCHOWN ] ( p , uid , gid , cb )
11
16
12
17
let len = children . length
13
18
let errState = null
14
19
const then = er => {
15
20
if ( errState ) return
16
21
if ( er ) return cb ( errState = er )
17
- if ( -- len === 0 ) return fs . lchown ( p , uid , gid , cb )
22
+ if ( -- len === 0 ) return fs [ LCHOWN ] ( p , uid , gid , cb )
18
23
}
19
24
20
25
children . forEach ( child => {
@@ -36,10 +41,10 @@ const chownrSync = (p, uid, gid) => {
36
41
try {
37
42
children = fs . readdirSync ( p )
38
43
} catch ( er ) {
39
- if ( er && er . code === 'ENOTDIR' ) return fs . lchownSync ( p , uid , gid )
44
+ if ( er && er . code === 'ENOTDIR' ) return fs [ LCHOWNSYNC ] ( p , uid , gid )
40
45
throw er
41
46
}
42
- if ( ! children . length ) return fs . lchownSync ( p , uid , gid )
47
+ if ( ! children . length ) return fs [ LCHOWNSYNC ] ( p , uid , gid )
43
48
44
49
children . forEach ( child => {
45
50
const pathChild = path . resolve ( p , child )
@@ -48,7 +53,7 @@ const chownrSync = (p, uid, gid) => {
48
53
chownrSync ( pathChild , uid , gid )
49
54
} )
50
55
51
- return fs . lchownSync ( p , uid , gid )
56
+ return fs [ LCHOWNSYNC ] ( p , uid , gid )
52
57
}
53
58
54
59
module . exports = chownr
0 commit comments