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

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

2
.gitignore vendored

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

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

@ -4,28 +4,35 @@
const parse = require('{%= name %}'); const parse = require('{%= name %}');
// sync // sync
const config = parse.sync(); console.log(parse.sync());
// or async // using async/await
parse(function (err, config) { (async () => console.log(await parse()))();
// do stuff with err/config
});
``` ```
**Custom path and/or cwd** ## Options
```js ### cwd
parse.sync({cwd: 'foo', path: '.git/config'});
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 ```js
{ core: { core:
@ -44,7 +51,7 @@ Config object will be something like:
## API ## API
{%= apidocs('index.js') %} {%= apidocs('index.js') %}
### .keys examples ### .expandKeys examples
Converts ini-style keys into objects: Converts ini-style keys into objects:
@ -57,7 +64,7 @@ const config = {
'foo "baz"': { doStuff: true } 'foo "baz"': { doStuff: true }
}; };
console.log(parse.keys(config)); console.log(parse.expandKeys(config));
``` ```
Results in: Results in:
@ -91,7 +98,7 @@ const config = {
} }
}; };
console.log(parse.keys(config)); console.log(parse.expandKeys(config));
``` ```
Results in: Results in:

@ -18,28 +18,33 @@ $ npm install --save parse-git-config
const parse = require('parse-git-config'); const parse = require('parse-git-config');
// sync // sync
const config = parse.sync(); console.log(parse.sync());
// or async // using async/await
parse(function (err, config) { (async () => console.log(await parse()))();
// do stuff with err/config
});
``` ```
**Custom path and/or cwd** ## Options
```js ### cwd
parse.sync({cwd: 'foo', path: '.git/config'});
// async The starting directory to search from.
parse({cwd: 'foo', path: '.git/config'}, function (err, config) {
// do stuff **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 ```js
{ core: { core:
@ -57,7 +62,7 @@ Config object will be something like:
## API ## 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. 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** **Example**
```js ```js
parse(function(err, config) { parse((err, config) => {
if (err) throw err; if (err) throw err;
// do stuff with config // do stuff with config
}); });
```
### [.sync](index.js#L62) // or, using async/await
(async () => {
Parse the given console.log(await parse());
console.log(await parse({ cwd: 'foo' }));
**Params** console.log(await parse({ cwd: 'foo', path: 'some/.git/config' }));
})();
* `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));
``` ```
### [.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. 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** **Example**
```js ```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. 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); const obj = parse.expandKeys(config);
``` ```
### .keys examples ### .expandKeys examples
Converts ini-style keys into objects: Converts ini-style keys into objects:
@ -136,7 +134,7 @@ const config = {
'foo "baz"': { doStuff: true } 'foo "baz"': { doStuff: true }
}; };
console.log(parse.keys(config)); console.log(parse.expandKeys(config));
``` ```
Results in: Results in:
@ -170,7 +168,7 @@ const config = {
} }
}; };
console.log(parse.keys(config)); console.log(parse.expandKeys(config));
``` ```
Results in: Results in:
@ -243,14 +241,14 @@ You might also be interested in these projects:
### Contributors ### Contributors
| **Commits** | **Contributor** | | **Commits** | **Contributor** |
| --- | --- | | --- | --- |
| 63 | [jonschlinkert](https://github.com/jonschlinkert) | | 66 | [jonschlinkert](https://github.com/jonschlinkert) |
| 4 | [doowb](https://github.com/doowb) | | 4 | [doowb](https://github.com/doowb) |
| 1 | [daviwil](https://github.com/daviwil) | | 1 | [daviwil](https://github.com/daviwil) |
| 1 | [LexSwed](https://github.com/LexSwed) | | 1 | [LexSwed](https://github.com/LexSwed) |
| 1 | [sam3d](https://github.com/sam3d) | | 1 | [sam3d](https://github.com/sam3d) |
| 1 | [suarasaur](https://github.com/suarasaur) | | 1 | [suarasaur](https://github.com/suarasaur) |
### Author ### 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'; 'use strict';
const fs = require('fs'); const fs = require('fs');
const os = require('os');
const path = require('path'); const path = require('path');
const util = require('util'); const util = require('util');
const ini = require('ini'); const ini = require('ini');
const configPath = require('git-config-path'); 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, * Asynchronously parse a `.git/config` file. If only the callback is passed,
* the `.git/config` file relative to `process.cwd()` is used. * the `.git/config` file relative to `process.cwd()` is used.
* *
* ```js * ```js
* parse(function(err, config) { * parse((err, config) => {
* if (err) throw err; * if (err) throw err;
* // do stuff with config * // 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 {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. * @param {Function} `callback` callback function if the first argument is options or cwd.
* @return {Object} * @return {Object}
* @api public * @api public
*/ */
function parse(options, callback) { const parse = (options, callback) => {
if (typeof options === 'function') { if (typeof options === 'function') {
callback = options; callback = options;
options = null; options = null;
@ -43,30 +52,13 @@ function parse(options, callback) {
return parse.promise(options) return parse.promise(options)
.then(config => callback(null, config)) .then(config => callback(null, config))
.catch(callback); .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 => { parse.promise = options => {
const filepath = parse.resolveConfigPath(options); let filepath = parse.resolveConfigPath(options);
const read = util.promisify(fs.readFile); let read = util.promisify(fs.readFile);
const stat = util.promisify(fs.stat); let stat = util.promisify(fs.stat);
if (!filepath) return Promise.resolve(null);
if (!filepath) {
return Promise.resolve(null);
}
return stat(filepath) return stat(filepath)
.then(() => read(filepath, 'utf8')) .then(() => read(filepath, 'utf8'))
@ -83,9 +75,10 @@ parse.promise = options => {
* the `.git/config` file relative to `process.cwd()` is used. * the `.git/config` file relative to `process.cwd()` is used.
* *
* ```js * ```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 * @name .sync
* @param {Object|String} `options` Options with `cwd` or `path`, or the cwd to use. * @param {Object|String} `options` Options with `cwd` or `path`, or the cwd to use.
* @return {Object} * @return {Object}
@ -93,19 +86,17 @@ parse.promise = options => {
*/ */
parse.sync = options => { parse.sync = options => {
const opts = Object.assign({}, options); let filepath = parse.resolveConfigPath(options);
const filepath = parse.resolveConfigPath(opts);
if (filepath && fs.existsSync(filepath)) {
const input = fs.readFileSync(filepath, 'utf8');
if (opts.include === true) { if (filepath && fs.existsSync(filepath)) {
const cwd = path.resolve(path.dirname(filepath)); let input = fs.readFileSync(filepath, 'utf8');
const str = injectInclude(input, cwd); if (options && options.include === true) {
return parseIni(str, opts); let cwd = path.resolve(path.dirname(filepath));
input = injectInclude(input, cwd);
} }
return parseIni(input, options);
return parseIni(input, opts);
} }
return {}; return {};
}; };
@ -114,10 +105,8 @@ parse.sync = options => {
*/ */
parse.resolveConfigPath = options => { parse.resolveConfigPath = options => {
if (typeof options === 'string') { if (typeof options === 'string') options = { type: options };
options = { type: options }; const opts = Object.assign({ cwd: process.cwd() }, options);
}
const opts = Object.assign({cwd: process.cwd()}, options);
const fp = opts.path ? expand(opts.path) : configPath(opts.type); const fp = opts.path ? expand(opts.path) : configPath(opts.type);
return fp ? path.resolve(opts.cwd, fp) : null; 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 config = parse.sync({ path: '/path/to/.gitconfig' });
* const obj = parse.expandKeys(config); * const obj = parse.expandKeys(config);
* ``` * ```
* @name .expandKeys
* @param {Object} `config` The parsed git config object. * @param {Object} `config` The parsed git config object.
* @return {Object} * @return {Object}
* @api public * @api public
*/ */
parse.expandKeys = config => { parse.expandKeys = config => {
for (const key of Object.keys(config)) { for (let key of Object.keys(config)) {
const m = /(\S+) "(.*)"/.exec(key); let m = /(\S+) "(.*)"/.exec(key);
if (!m) continue; if (!m) continue;
const prop = m[1]; let prop = m[1];
config[prop] = config[prop] || {}; config[prop] = config[prop] || {};
config[prop][m[2]] = config[key]; config[prop][m[2]] = config[key];
delete config[key]; delete config[key];
@ -154,13 +144,13 @@ parse.expandKeys = config => {
}; };
function parseIni(str, options) { 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; return $1 && $2 ? `[${$1} "${$2.split('.').join('\\.')}"]` : m;
}); });
const config = ini.parse(str); let config = ini.parse(str);
if (opts.expandKeys === true) { if (opts.expandKeys === true) {
return parse.expandKeys(config); return parse.expandKeys(config);
} }
@ -168,17 +158,16 @@ function parseIni(str, options) {
} }
function injectInclude(input, cwd) { function injectInclude(input, cwd) {
const lines = input.split('\n').filter(line => line.trim() !== ''); let lines = input.split('\n').filter(line => line.trim() !== '');
const len = lines.length; let len = lines.length;
const res = []; let res = [];
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
const line = lines[i]; let line = lines[i];
if (line.indexOf('[include]') === 0) { if (line.indexOf('[include]') === 0) {
const filepath = lines[i + 1].replace(/^\s*path\s*=\s*/, ''); let filepath = lines[i + 1].replace(/^\s*path\s*=\s*/, '');
const fp = path.resolve(cwd, expand(filepath)); let fp = path.resolve(cwd, expand(filepath));
res.push(fs.readFileSync(fp)); res.push(fs.readFileSync(fp));
} else { } else {
res.push(line); res.push(line);
} }

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

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

Loading…
Cancel
Save