master
Jon Schlinkert 6 years ago
parent 407ce2443c
commit 60d1e75fe7

@ -9,6 +9,5 @@ indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[{**/{actual,fixtures,expected,templates}/**,*.md}]
[*.md]
trim_trailing_whitespace = false
insert_final_newline = false

2
.gitignore vendored

@ -27,4 +27,4 @@ vendor
temp
tmp
TODO.md
package-lock.json
package-lock.json

@ -2,11 +2,11 @@ sudo: false
os:
- linux
- osx
- windows
language: node_js
node_js:
- node
- '11'
- '10'
- '9'
- '8'
- '7'
- '6'

@ -4,28 +4,35 @@
const parse = require('{%= name %}');
// sync
const config = parse.sync();
console.log(parse.sync());
// or async
parse(function (err, config) {
// do stuff with err/config
});
// using async/await
(async () => console.log(await parse()))();
```
**Custom path and/or cwd**
## Options
```js
parse.sync({cwd: 'foo', path: '.git/config'});
### cwd
The starting directory to search from.
**Type**: `string`
**Default**: `process.cwd()` (current working directory)
### path
Either the absolute path to .git `config`, or the path relative to the current working directory.
**Type**: `string`
**Default**: `.git/config`
// async
parse({cwd: 'foo', path: '.git/config'}, function (err, config) {
// do stuff
});
```
**Example result**
### Examples config object
Config object will be something like:
Parsed config object will look something like:
```js
{ core:
@ -44,7 +51,7 @@ Config object will be something like:
## API
{%= apidocs('index.js') %}
### .keys examples
### .expandKeys examples
Converts ini-style keys into objects:
@ -57,7 +64,7 @@ const config = {
'foo "baz"': { doStuff: true }
};
console.log(parse.keys(config));
console.log(parse.expandKeys(config));
```
Results in:
@ -91,7 +98,7 @@ const config = {
}
};
console.log(parse.keys(config));
console.log(parse.expandKeys(config));
```
Results in:

@ -18,28 +18,33 @@ $ npm install --save parse-git-config
const parse = require('parse-git-config');
// sync
const config = parse.sync();
console.log(parse.sync());
// or async
parse(function (err, config) {
// do stuff with err/config
});
// using async/await
(async () => console.log(await parse()))();
```
**Custom path and/or cwd**
## Options
```js
parse.sync({cwd: 'foo', path: '.git/config'});
### cwd
// async
parse({cwd: 'foo', path: '.git/config'}, function (err, config) {
// do stuff
});
```
The starting directory to search from.
**Type**: `string`
**Default**: `process.cwd()` (current working directory)
**Example result**
### path
Config object will be something like:
Either the absolute path to .git `config`, or the path relative to the current working directory.
**Type**: `string`
**Default**: `.git/config`
### Examples config object
Parsed config object will look something like:
```js
{ core:
@ -57,7 +62,7 @@ Config object will be something like:
## API
### [parse](index.js#L33)
### [parse](index.js#L42)
Asynchronously parse a `.git/config` file. If only the callback is passed, the `.git/config` file relative to `process.cwd()` is used.
@ -70,29 +75,20 @@ Asynchronously parse a `.git/config` file. If only the callback is passed, the `
**Example**
```js
parse(function(err, config) {
parse((err, config) => {
if (err) throw err;
// do stuff with config
});
```
### [.sync](index.js#L62)
Parse the given
**Params**
* `options` **{Object|String}**: Options with `cwd` or `path`, or the cwd to use.
* `returns` **{Object}**
**Example**
```js
parse.promise({ path: '/path/to/.gitconfig' })
.then(config => console.log(config));
// or, using async/await
(async () => {
console.log(await parse());
console.log(await parse({ cwd: 'foo' }));
console.log(await parse({ cwd: 'foo', path: 'some/.git/config' }));
})();
```
### [.sync](index.js#L95)
### [.sync](index.js#L88)
Synchronously parse a `.git/config` file. If no arguments are passed, the `.git/config` file relative to `process.cwd()` is used.
@ -104,10 +100,12 @@ Synchronously parse a `.git/config` file. If no arguments are passed, the `.git/
**Example**
```js
const config = parse.sync();
console.log(parse.sync());
console.log(parse.sync({ cwd: 'foo' }));
console.log(parse.sync({ cwd: 'foo', path: 'some/.git/config' }));
```
### [.expandKeys](index.js#L144)
### [.expandKeys](index.js#L134)
Returns an object with only the properties that had ini-style keys converted to objects.
@ -123,7 +121,7 @@ const config = parse.sync({ path: '/path/to/.gitconfig' });
const obj = parse.expandKeys(config);
```
### .keys examples
### .expandKeys examples
Converts ini-style keys into objects:
@ -136,7 +134,7 @@ const config = {
'foo "baz"': { doStuff: true }
};
console.log(parse.keys(config));
console.log(parse.expandKeys(config));
```
Results in:
@ -170,7 +168,7 @@ const config = {
}
};
console.log(parse.keys(config));
console.log(parse.expandKeys(config));
```
Results in:
@ -243,14 +241,14 @@ You might also be interested in these projects:
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 63 | [jonschlinkert](https://github.com/jonschlinkert) |
| 4 | [doowb](https://github.com/doowb) |
| 1 | [daviwil](https://github.com/daviwil) |
| 1 | [LexSwed](https://github.com/LexSwed) |
| 1 | [sam3d](https://github.com/sam3d) |
| 1 | [suarasaur](https://github.com/suarasaur) |
| **Commits** | **Contributor** |
| --- | --- |
| 66 | [jonschlinkert](https://github.com/jonschlinkert) |
| 4 | [doowb](https://github.com/doowb) |
| 1 | [daviwil](https://github.com/daviwil) |
| 1 | [LexSwed](https://github.com/LexSwed) |
| 1 | [sam3d](https://github.com/sam3d) |
| 1 | [suarasaur](https://github.com/suarasaur) |
### Author
@ -267,4 +265,4 @@ Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on August 19, 2018._
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on November 20, 2018._

@ -8,29 +8,38 @@
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const util = require('util');
const ini = require('ini');
const configPath = require('git-config-path');
const expand = require('expand-tilde');
const expand = str => (str ? str.replace(/^~/, os.homedir()) : '');
/**
* Asynchronously parse a `.git/config` file. If only the callback is passed,
* the `.git/config` file relative to `process.cwd()` is used.
*
* ```js
* parse(function(err, config) {
* parse((err, config) => {
* if (err) throw err;
* // do stuff with config
* });
*
* // or, using async/await
* (async () => {
* console.log(await parse());
* console.log(await parse({ cwd: 'foo' }));
* console.log(await parse({ cwd: 'foo', path: 'some/.git/config' }));
* })();
* ```
* @name parse
* @param {Object|String|Function} `options` Options with `cwd` or `path`, the cwd to use, or the callback function.
* @param {Function} `callback` callback function if the first argument is options or cwd.
* @return {Object}
* @api public
*/
function parse(options, callback) {
const parse = (options, callback) => {
if (typeof options === 'function') {
callback = options;
options = null;
@ -43,30 +52,13 @@ function parse(options, callback) {
return parse.promise(options)
.then(config => callback(null, config))
.catch(callback);
}
/**
* Parse the given
*
* ```js
* parse.promise({ path: '/path/to/.gitconfig' })
* .then(config => console.log(config));
* ```
*
* @name .sync
* @param {Object|String} `options` Options with `cwd` or `path`, or the cwd to use.
* @return {Object}
* @api public
*/
};
parse.promise = options => {
const filepath = parse.resolveConfigPath(options);
const read = util.promisify(fs.readFile);
const stat = util.promisify(fs.stat);
if (!filepath) {
return Promise.resolve(null);
}
let filepath = parse.resolveConfigPath(options);
let read = util.promisify(fs.readFile);
let stat = util.promisify(fs.stat);
if (!filepath) return Promise.resolve(null);
return stat(filepath)
.then(() => read(filepath, 'utf8'))
@ -83,9 +75,10 @@ parse.promise = options => {
* the `.git/config` file relative to `process.cwd()` is used.
*
* ```js
* const config = parse.sync();
* console.log(parse.sync());
* console.log(parse.sync({ cwd: 'foo' }));
* console.log(parse.sync({ cwd: 'foo', path: 'some/.git/config' }));
* ```
*
* @name .sync
* @param {Object|String} `options` Options with `cwd` or `path`, or the cwd to use.
* @return {Object}
@ -93,19 +86,17 @@ parse.promise = options => {
*/
parse.sync = options => {
const opts = Object.assign({}, options);
const filepath = parse.resolveConfigPath(opts);
if (filepath && fs.existsSync(filepath)) {
const input = fs.readFileSync(filepath, 'utf8');
let filepath = parse.resolveConfigPath(options);
if (opts.include === true) {
const cwd = path.resolve(path.dirname(filepath));
const str = injectInclude(input, cwd);
return parseIni(str, opts);
if (filepath && fs.existsSync(filepath)) {
let input = fs.readFileSync(filepath, 'utf8');
if (options && options.include === true) {
let cwd = path.resolve(path.dirname(filepath));
input = injectInclude(input, cwd);
}
return parseIni(input, opts);
return parseIni(input, options);
}
return {};
};
@ -114,10 +105,8 @@ parse.sync = options => {
*/
parse.resolveConfigPath = options => {
if (typeof options === 'string') {
options = { type: options };
}
const opts = Object.assign({cwd: process.cwd()}, options);
if (typeof options === 'string') options = { type: options };
const opts = Object.assign({ cwd: process.cwd() }, options);
const fp = opts.path ? expand(opts.path) : configPath(opts.type);
return fp ? path.resolve(opts.cwd, fp) : null;
};
@ -136,16 +125,17 @@ parse.resolve = options => parse.resolveConfigPath(options);
* const config = parse.sync({ path: '/path/to/.gitconfig' });
* const obj = parse.expandKeys(config);
* ```
* @name .expandKeys
* @param {Object} `config` The parsed git config object.
* @return {Object}
* @api public
*/
parse.expandKeys = config => {
for (const key of Object.keys(config)) {
const m = /(\S+) "(.*)"/.exec(key);
for (let key of Object.keys(config)) {
let m = /(\S+) "(.*)"/.exec(key);
if (!m) continue;
const prop = m[1];
let prop = m[1];
config[prop] = config[prop] || {};
config[prop][m[2]] = config[key];
delete config[key];
@ -154,13 +144,13 @@ parse.expandKeys = config => {
};
function parseIni(str, options) {
const opts = Object.assign({}, options);
let opts = Object.assign({}, options);
str = str.replace(/\[(\S+) "(.*)"\]/g, function(m, $1, $2) {
str = str.replace(/\[(\S+) "(.*)"\]/g, (m, $1, $2) => {
return $1 && $2 ? `[${$1} "${$2.split('.').join('\\.')}"]` : m;
});
const config = ini.parse(str);
let config = ini.parse(str);
if (opts.expandKeys === true) {
return parse.expandKeys(config);
}
@ -168,17 +158,16 @@ function parseIni(str, options) {
}
function injectInclude(input, cwd) {
const lines = input.split('\n').filter(line => line.trim() !== '');
const len = lines.length;
const res = [];
let lines = input.split('\n').filter(line => line.trim() !== '');
let len = lines.length;
let res = [];
for (let i = 0; i < len; i++) {
const line = lines[i];
let line = lines[i];
if (line.indexOf('[include]') === 0) {
const filepath = lines[i + 1].replace(/^\s*path\s*=\s*/, '');
const fp = path.resolve(cwd, expand(filepath));
let filepath = lines[i + 1].replace(/^\s*path\s*=\s*/, '');
let fp = path.resolve(cwd, expand(filepath));
res.push(fs.readFileSync(fp));
} else {
res.push(line);
}

@ -19,20 +19,18 @@
],
"main": "index.js",
"engines": {
"node": ">=6"
"node": ">=8"
},
"scripts": {
"test": "mocha"
},
"dependencies": {
"expand-tilde": "^2.0.2",
"git-config-path": "^1.0.1",
"git-config-path": "^2.0.0",
"ini": "^1.3.5"
},
"devDependencies": {
"gulp-format-md": "^1.0.0",
"homedir-polyfill": "^1.0.1",
"mocha": "^3.5.3"
"gulp-format-md": "^2.0.0",
"mocha": "^5.2.0"
},
"keywords": [
"config",
@ -63,4 +61,4 @@
"reflinks": true
}
}
}
}

@ -5,7 +5,6 @@ const isTravis = process.env.TRAVIS || process.env.CLI;
const os = require('os');
const assert = require('assert');
const path = require('path');
const homedir = require('homedir-polyfill');
const parse = require('..');
const cwd = (...args) => path.resolve(__dirname, ...args);
@ -111,7 +110,7 @@ describe('parse-git-config', function() {
});
it('should allow override path', function() {
const fp = path.resolve(homedir(), '.gitconfig');
const fp = path.resolve(os.homedir(), '.gitconfig');
assert.equal(parse.resolve({ path: fp }), fp);
});
@ -127,7 +126,7 @@ describe('parse-git-config', function() {
it('should resolve relative path to the global git config when `global` is passed', function() {
if (isTravis && os.platform() === 'darwin') return this.skip();
assert.equal(parse.resolve('global'), path.resolve(homedir(), '.gitconfig'));
assert.equal(parse.resolve('global'), path.resolve(os.homedir(), '.gitconfig'));
});
it('should allow override of cwd', function() {

Loading…
Cancel
Save