.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / @mrmlnc / readdir-enhanced / lib / stat.js
1 'use strict';
2
3 const call = require('./call');
4
5 module.exports = stat;
6
7 /**
8  * Retrieves the {@link fs.Stats} for the given path. If the path is a symbolic link,
9  * then the Stats of the symlink's target are returned instead.  If the symlink is broken,
10  * then the Stats of the symlink itself are returned.
11  *
12  * @param {object} fs - Synchronous or Asynchronouse facade for the "fs" module
13  * @param {string} path - The path to return stats for
14  * @param {function} callback
15  */
16 function stat (fs, path, callback) {
17   let isSymLink = false;
18
19   call.safe(fs.lstat, path, (err, lstats) => {
20     if (err) {
21       // fs.lstat threw an eror
22       return callback(err);
23     }
24
25     try {
26       isSymLink = lstats.isSymbolicLink();
27     }
28     catch (err2) {
29       // lstats.isSymbolicLink() threw an error
30       // (probably because fs.lstat returned an invalid result)
31       return callback(err2);
32     }
33
34     if (isSymLink) {
35       // Try to resolve the symlink
36       symlinkStat(fs, path, lstats, callback);
37     }
38     else {
39       // It's not a symlink, so return the stats as-is
40       callback(null, lstats);
41     }
42   });
43 }
44
45 /**
46  * Retrieves the {@link fs.Stats} for the target of the given symlink.
47  * If the symlink is broken, then the Stats of the symlink itself are returned.
48  *
49  * @param {object} fs - Synchronous or Asynchronouse facade for the "fs" module
50  * @param {string} path - The path of the symlink to return stats for
51  * @param {object} lstats - The stats of the symlink
52  * @param {function} callback
53  */
54 function symlinkStat (fs, path, lstats, callback) {
55   call.safe(fs.stat, path, (err, stats) => {
56     if (err) {
57       // The symlink is broken, so return the stats for the link itself
58       return callback(null, lstats);
59     }
60
61     try {
62       // Return the stats for the resolved symlink target,
63       // and override the `isSymbolicLink` method to indicate that it's a symlink
64       stats.isSymbolicLink = () => true;
65     }
66     catch (err2) {
67       // Setting stats.isSymbolicLink threw an error
68       // (probably because fs.stat returned an invalid result)
69       return callback(err2);
70     }
71
72     callback(null, stats);
73   });
74 }