Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed May 25, 2016
0 parents commit 1b6d059
Show file tree
Hide file tree
Showing 13 changed files with 498 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[{package.json,*.yml}]
indent_style = space
indent_size = 2
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* text=auto
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
4 changes: 4 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
os: osx
language: node_js
node_js:
- 'node'
20 changes: 20 additions & 0 deletions appveyor.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
os: unstable
environment:
matrix:
- nodejs_version: '6'
install:
- ps: Install-Product node $env:nodejs_version
- set CI=true
- npm -g install npm@latest
- set PATH=%APPDATA%\npm;%PATH%
- npm install
matrix:
fast_finish: true
build: off
version: '{build}'
shallow_clone: true
clone_depth: 1
test_script:
- node --version
- npm --version
- npm test
83 changes: 83 additions & 0 deletions config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
'use strict';
const fs = require('fs');
const path = require('path');
const dotProp = require('dot-prop');
const mkdirp = require('mkdirp');

const obj = () => Object.create(null);

class Config {
constructor(opts) {
opts = Object.assign({}, opts);

if (typeof opts.path !== 'string') {
throw new TypeError(`Expected \`options.path\` to be a string, got ${typeof opts.path}`);
}

this.path = path.resolve(opts.path);
this.store = Object.assign(obj(), opts.defaults, this.store);
}
get(key) {
return dotProp.get(this.store, key);
}
set(key, val) {
const store = this.store;

if (val === undefined) {
Object.keys(key).forEach(k => {
dotProp.set(store, k, key[k]);
});
} else {
dotProp.set(store, key, val);
}

this.store = store;
}
has(key) {
return dotProp.has(this.store, key);
}
delete(key) {
const store = this.store;
dotProp.delete(store, key);
this.store = store;
}
clear() {
this.store = obj();
}
get size() {
return Object.keys(this.store).length;
}
get store() {
try {
return Object.assign(obj(), JSON.parse(fs.readFileSync(this.path, 'utf8')));
} catch (err) {
if (err.code === 'ENOENT') {
mkdirp.sync(path.dirname(this.path));
return obj();
}

if (err.name === 'SyntaxError') {
return obj();
}

throw err;
}
}
set store(val) {
// ensure the directory exists as it
// could have been deleted in the meantime
mkdirp.sync(path.dirname(this.path));

fs.writeFileSync(this.path, JSON.stringify(val, null, '\t'));
}
// TODO: use `Object.entries()` here at some point
* [Symbol.iterator]() {
const store = this.store;

for (const key of Object.keys(store)) {
yield [key, store[key]];
}
}
}

module.exports = Config;
19 changes: 19 additions & 0 deletions fixture.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use strict';
const assert = require('assert');
const electron = require('electron');
const Config = require('./');

const conf = new Config({name: 'electron-config'});

conf.set('unicorn', '🦄');
assert.equal(conf.get('unicorn'), '🦄');

conf.delete('unicorn');
assert.equal(conf.get('unicorn'), undefined);

// to be checked in AVA
conf.set('ava', '🚀');

console.log(conf.path);

electron.app.quit();
18 changes: 18 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';
const path = require('path');
const electron = require('electron');
const Config = require('./config');

class ElectronConfig extends Config {
constructor(opts) {
opts = Object.assign({
name: 'config'
}, opts);

opts.path = path.join(electron.app.getPath('userData'), `${opts.name}.json`);

super(opts);
}
}

module.exports = ElectronConfig;
21 changes: 21 additions & 0 deletions license
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
54 changes: 54 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"name": "electron-config",
"version": "0.0.0",
"description": "Simple config handling for your Electron app or module",
"license": "MIT",
"repository": "sindresorhus/electron-config",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"scripts": {
"start": "electron test.js",
"test": "xo && ava"
},
"files": [
"index.js",
"config.js"
],
"keywords": [
"electron",
"app",
"config",
"store",
"storage",
"conf",
"configuration",
"settings",
"preferences",
"json",
"data",
"persist",
"persistent",
"save"
],
"dependencies": {
"dot-prop": "^3.0.0",
"mkdirp": "^0.5.1"
},
"devDependencies": {
"ava": "*",
"electron-prebuilt": "1.1.1",
"execa": "^0.4.0",
"tempfile": "^1.1.1",
"xo": "*"
},
"xo": {
"esnext": true,
"envs": [
"node",
"browser"
]
}
}
115 changes: 115 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# electron-config [![Build Status: Linux and OS X](https://travis-ci.org/sindresorhus/electron-config.svg?branch=master)](https://travis-ci.org/sindresorhus/electron-config) [![Build status: Windows](https://ci.appveyor.com/api/projects/status/m2m9o6gq77xxi2eg/branch/master?svg=true)](https://ci.appveyor.com/project/sindresorhus/electron-config/branch/master)

> Simple config handling for your [Electron](http://electron.atom.io) app or module
Electron doesn't have a built-in way to persist user settings and other data. This module handles that for you, so you can focus on building your app. Config is saved in a JSON file in [`app.getPath('userData')`](http://electron.atom.io/docs/api/app/#appgetpathname).


## Install

```
$ npm install --save electron-config
```


## Usage

```js
const Config = require('electron-config');
const conf = new Config();

conf.set('unicorn', '🦄');
console.log(conf.get('unicorn'));
//=> '🦄'

// use dot-notation to access nested properties
conf.set('foo.bar', true);
console.log(conf.get('foo'));
//=> {bar: true}

conf.delete('unicorn');
console.log(conf.get('unicorn'));
//=> undefined
```


## API

### Config([options])

Returns a new instance.

### options

#### defaults

Type: `Object`

Default config.

#### name

Type: `string`<br>
Default: `config`

Name of the config file.

This is useful if you want multiple config files for your app. Or if you're making a reusable Electron module that persists some config, in which case you should **not** use the name `config`.

### Instance

You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a `key` to access nested properties.

The instance is [`iterable`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) so you can use it directly in a [`for…of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) loop.

#### .set(key, value)

Set an item.

#### .set(object)

Set multiple items at once.

#### .get(key)

Get an item.

#### .has(key)

Check if an item exists.

#### .delete(key)

Delete an item.

#### .clear()

Delete all items.

#### .size

Get the item count.

#### .store

Get all the config as an object or replace the current config with an object:

```js
conf.store = {
hello: 'world'
};
```

#### .path

Get the path to the config file.


## Related

- [electron-debug](https://github.com/sindresorhus/electron-debug) - Adds useful debug features to your Electron app


## License

MIT © [Sindre Sorhus](https://sindresorhus.com)
23 changes: 23 additions & 0 deletions test-electron.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import fs from 'fs';
import test from 'ava';
import execa from 'execa';
import electron from 'electron-prebuilt';

// TODO: test with Spectron

test(async t => {
let configPath = await execa.stdout(electron, ['fixture.js'], {
cwd: __dirname,
env: {
ELECTRON_ENABLE_LOGGING: true,
ELECTRON_ENABLE_STACK_DUMPING: true,
ELECTRON_NO_ATTACH_CONSOLE: true
}
});

// stupid Windows
configPath = configPath.trim();

t.deepEqual(JSON.parse(fs.readFileSync(configPath.trim(), 'utf8')), {ava: '🚀'});
fs.unlinkSync(configPath);
});
Loading

0 comments on commit 1b6d059

Please sign in to comment.