Skip to content

Commit

Permalink
Add chmod.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaywcjlove committed Jun 27, 2018
1 parent 3c04f02 commit 86f6e6e
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 10 deletions.
58 changes: 49 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const fs = require('fs');
const path = require('path');
const nicki = require('nicki');
const Mode = require('stat-mode');
const deepExtend = require('deep-extend');

exports.getStat = async (currentPath, names) => {
if (!names) names = await this.uidToName();
Expand All @@ -10,21 +11,20 @@ exports.getStat = async (currentPath, names) => {
if (err) reject(err);
else {
const mode = new Mode(stat);
if (names && names[stat.uid]) {
stat.uidToName = names[stat.uid];
}
stat.mode = {
stat.extend = {
number: stat.mode,
isSymbolicLink: mode.isSymbolicLink(),
string: mode.toString(),
owner: { ...mode.owner },
group: { ...mode.group },
others: { ...mode.others },
};
// stat.modeStr = mode.toString();
stat.path = currentPath;
stat.basename = path.basename(currentPath);
stat.extname = path.extname(stat.basename);
}
if (names && names[stat.uid]) {
stat.extend.uidToName = names[stat.uid];
}
stat.extend.path = currentPath;
stat.extend.basename = path.basename(currentPath);
stat.extend.extname = path.extname(stat.extend.basename);
resolve(stat);
};
})
Expand Down Expand Up @@ -55,4 +55,44 @@ exports.readdir = (dirPath) => {
return this.getStat(path.join(dirPath, filename), names);
}));
})
}

exports.chmod = async (file, mode) => {
if (typeof mode !== 'number' && typeof mode !== 'object') {
throw new TypeError('Expected a number or object');
}
const stat = await this.getStat(file);
delete stat.extend;
let newMode;

if (typeof mode === 'object') {
const statMode = new Mode(stat);
deepExtend(statMode, normalize(mode));
newMode = statMode.stat.mode;
} else {
newMode = parseInt(mode, 8);
}
return new Promise((resolve, reject) => {
fs.chmod(file, newMode, (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
}

function normalize(mode) {
var called = false, newOne = {
owner: {},
group: {},
others: {}
};
['read', 'write', 'execute'].forEach(function (key) {
if (typeof mode[key] === 'boolean') {
newOne.owner[key] = mode[key];
newOne.group[key] = mode[key];
newOne.others[key] = mode[key];
called = true;
}
});
return called ? newOne : mode;
}
7 changes: 6 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"author": "kenny",
"license": "MIT",
"dependencies": {
"deep-extend": "^0.6.0",
"nicki": "^3.0.1",
"stat-mode": "^0.2.2"
}
Expand Down

0 comments on commit 86f6e6e

Please sign in to comment.