Browse Source

🎉 Initial commit

pull/1/head
Nicolas Beaussart 7 years ago
commit
6589ea37c7
  1. 7
      .gitignore
  2. 21
      LICENSE
  3. 29
      __tests__/cli-integration.test.ts
  4. 21
      bin/nbx
  5. 3
      docs/commands.md
  6. 47
      docs/plugins.md
  7. 55
      package.json
  8. 25
      readme.md
  9. 23
      src/cli.ts
  10. 23
      src/commands/generate.ts
  11. 10
      src/commands/nbx.ts
  12. 77
      src/commands/wallhaven/wallhaven.ts
  13. 26
      src/extensions/cli-extension.ts
  14. 66
      src/extensions/wallhaven.ts
  15. 3
      src/templates/model.ts.ejs
  16. 26
      tsconfig.json
  17. 9
      tslint.json
  18. 5036
      yarn.lock

7
.gitignore

@ -0,0 +1,7 @@
.DS_Store
node_modules
npm-debug.log
coverage
.nyc_output
dist
build

21
LICENSE

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017
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.

29
__tests__/cli-integration.test.ts

@ -0,0 +1,29 @@
const { system, filesystem } = require('gluegun')
const src = filesystem.path(__dirname, '..')
const cli = async cmd =>
system.run('node ' + filesystem.path(src, 'bin', 'nbx') + ` ${cmd}`)
test('outputs version', async () => {
const output = await cli('--version')
expect(output).toContain('0.0.1')
})
test('outputs help', async () => {
const output = await cli('--help')
expect(output).toContain('0.0.1')
})
test('generates file', async () => {
const output = await cli('generate foo')
expect(output).toContain('Generated file at models/foo-model.ts')
const foomodel = filesystem.read('models/foo-model.ts')
expect(foomodel).toContain(`module.exports = {`)
expect(foomodel).toContain(`name: 'foo'`)
// cleanup artifact
filesystem.remove('models')
})

21
bin/nbx

@ -0,0 +1,21 @@
#!/usr/bin/env node
/* tslint:disable */
// check if we're running in dev mode
var devMode = require('fs').existsSync(`${__dirname}/../src`)
// or want to "force" running the compiled version with --compiled-build
var wantsCompiled = process.argv.indexOf('--compiled-build') >= 0
if (wantsCompiled || !devMode) {
// this runs from the compiled javascript source
require(`${__dirname}/../build/cli`).run(process.argv)
} else {
// this runs from the typescript source (for dev only)
// hook into ts-node so we can run typescript on the fly
require('ts-node').register({ project: `${__dirname}/../tsconfig.json` })
// run the CLI with the current process arguments
require(`${__dirname}/../src/cli`).run(process.argv)
}

3
docs/commands.md

@ -0,0 +1,3 @@
# Command Reference for nbx
TODO: Add your command reference here

47
docs/plugins.md

@ -0,0 +1,47 @@
# Plugin guide for nbx
Plugins allow you to add features to nbx, such as commands and
extensions to the `toolbox` object that provides the majority of the functionality
used by nbx.
Creating a nbx plugin is easy. Just create a repo with two folders:
```
commands/
extensions/
```
A command is a file that looks something like this:
```js
// commands/foo.js
module.exports = {
run: (toolbox) => {
const { print, filesystem } = toolbox
const desktopDirectories = filesystem.subdirectories(`~/Desktop`)
print.info(desktopDirectories)
}
}
```
An extension lets you add additional features to the `toolbox`.
```js
// extensions/bar-extension.js
module.exports = (toolbox) => {
const { print } = toolbox
toolbox.bar = () => { print.info('Bar!') }
}
```
This is then accessible in your plugin's commands as `toolbox.bar`.
# Loading a plugin
To load a particular plugin (which has to start with `nbx-*`),
install it to your project using `npm install --save-dev nbx-PLUGINNAME`,
and nbx will pick it up automatically.

55
package.json

@ -0,0 +1,55 @@
{
"name": "nbx",
"version": "0.0.1",
"description": "nbx CLI",
"private": true,
"bin": {
"nbx": "bin/nbx"
},
"scripts": {
"format": "prettier --write **/*.{js,ts,tsx,json}",
"lint": "tslint -p .",
"compile": "tsc -p .",
"clean-build": "rm -rf ./build",
"copy-templates": "if [ -e ./src/templates ]; then cp -a ./src/templates ./build/; fi",
"build": "yarn format && yarn lint && yarn clean-build && yarn compile && yarn copy-templates",
"test": "jest",
"watch": "jest --watch",
"snapupdate": "jest --updateSnapshot",
"coverage": "jest --coverage"
},
"files": [
"tsconfig.json",
"tslint.json",
"build",
"LICENSE",
"readme.md",
"docs",
"bin"
],
"license": "MIT",
"dependencies": {
"gluegun": "^2.1.0",
"querystring": "^0.2.0",
"ts-node": "^7.0.1",
"typescript": "3.2.2"
},
"devDependencies": {
"@types/jest": "^23.3.10",
"@types/node": "^10.12.12",
"jest": "^23.6.0",
"prettier": "^1.12.1",
"ts-jest": "^23.10.5",
"tslint": "^5.12.0",
"tslint-config-prettier": "^1.17.0",
"tslint-config-standard": "^8.0.1"
},
"jest": {
"preset": "ts-jest",
"testEnvironment": "node"
},
"prettier": {
"semi": false,
"singleQuote": true
}
}

25
readme.md

@ -0,0 +1,25 @@
# nbx CLI
A CLI for nbx.
## Customizing your CLI
Check out the documentation at https://github.com/infinitered/gluegun/tree/master/docs.
## Publishing to NPM
To package your CLI up for NPM, do this:
```shell
$ npm login
$ npm whoami
$ npm lint
$ npm test
(if typescript, run `npm run build` here)
$ npm publish
```
# License
MIT - see LICENSE

23
src/cli.ts

@ -0,0 +1,23 @@
const { build } = require('gluegun')
/**
* Create the cli and kick it off
*/
async function run(argv) {
// create a CLI runtime
const cli = build()
.brand('nbx')
.src(__dirname)
.plugins('./node_modules', { matching: 'nbx-*', hidden: true })
.help() // provides default for help, h, --help, -h
.version() // provides default for version, v, --version, -v
.create()
// and run it
const toolbox = await cli.run(argv)
// send it back (for testing, mostly)
return toolbox
}
module.exports = { run }

23
src/commands/generate.ts

@ -0,0 +1,23 @@
import { GluegunToolbox } from 'gluegun'
module.exports = {
name: 'generate',
alias: ['g'],
run: async (toolbox: GluegunToolbox) => {
const {
parameters,
template: { generate },
print: { info }
} = toolbox
const name = parameters.first
await generate({
template: 'model.ts.ejs',
target: `models/${name}-model.ts`,
props: { name }
})
info(`Generated file at models/${name}-model.ts`)
}
}

10
src/commands/nbx.ts

@ -0,0 +1,10 @@
import { GluegunToolbox } from 'gluegun'
module.exports = {
name: 'nbx',
run: async (toolbox: GluegunToolbox) => {
const { print } = toolbox
print.info('Welcome to your CLI')
}
}

77
src/commands/wallhaven/wallhaven.ts

@ -0,0 +1,77 @@
import { GluegunToolbox } from 'gluegun'
module.exports = {
name: 'wallhaven',
description: 'Fetch a wallpaper on wallhaven',
alias: ['w'],
run: async (toolbox: GluegunToolbox) => {
const {
parameters,
print: { info, error, spin },
wallhaven: { search, downloadWallpaper },
utils: { verboseDebug },
} = toolbox
const showHelp = () => {
info('Usage: wallhaven-cli <terms ...>')
info('')
info('Options')
info(' -r, --random Pick one randomly')
info(' --general Enable general category')
info(' --anime Enable anime category')
info(' --people Enable people category')
info(' -o --output [file] Path to output the file')
info(' -h, --help Output usage information')
info(' -v, --verbose Verbose output')
}
// set up initial props (to pass into templates)
const o = parameters.options
const props = {
random: Boolean(o.r || o.random),
terms: parameters.string,
sketchy: Boolean(o.sketchy),
general: Boolean(o.general),
anime: Boolean(o.anime),
people: Boolean(o.people),
useCustomOutput: Boolean(o.o || o.output),
customOutput: o.o || o.output,
help: Boolean(o.h || o.help),
verbose: Boolean(o.v || o.verbose),
}
verboseDebug(props, 'Params')
if (props.help) {
showHelp()
return
}
if (!props.general && !props.anime && !props.people) {
error('You must use at least one category flag\n')
showHelp()
process.exit(0)
}
if (!props.terms) {
error('You should use search terms\n')
showHelp()
process.exit(0)
}
const spinFetchList = spin('Searching wallpapers');
const data = await search(props);
spinFetchList.succeed();
const firstImage = data[0];
verboseDebug(firstImage, 'Image raw data')
const filename = props.useCustomOutput ? props.customOutput : `wallhaven-${firstImage.id}.jpg`;
const spinner = spin('Downloading wallpaper');
await downloadWallpaper(filename, firstImage.path);
spinner.succeed();
}
}

26
src/extensions/cli-extension.ts

@ -0,0 +1,26 @@
import { GluegunToolbox } from 'gluegun'
// add your CLI-specific functionality here, which will then be accessible
// to your commands
module.exports = (toolbox: GluegunToolbox) => {
toolbox.foo = () => {
toolbox.print.info('called foo extension')
}
toolbox.utils = {
verboseDebug: (value: any, title?: string) => {
const o = toolbox.parameters.options;
if (Boolean(o.v || o.verbose)) {
toolbox.print.debug(value, title);
}
}
}
// enable this if you want to read configuration in from
// the current folder's package.json (in a "nbx" property),
// nbx.config.json, etc.
// toolbox.config = {
// ...toolbox.config,
// ...toolbox.config.loadConfig(process.cwd(), "nbx")
// }
}

66
src/extensions/wallhaven.ts

@ -0,0 +1,66 @@
import { GluegunToolbox } from 'gluegun'
import { stringify } from 'querystring'
function boolanToNumber(value) {
return value ? '1' : '0'
}
// add your CLI-specific functionality here, which will then be accessible
// to your commands
module.exports = (toolbox: GluegunToolbox) => {
const api = toolbox.http.create({
baseURL: 'https://wallhaven.cc/api/v1/'
})
const search = async ({
random = false,
sketchy = false,
terms = '',
people = false,
anime = false,
general = false
}) => {
const categories = `${boolanToNumber(general)}${boolanToNumber(
anime
)}${boolanToNumber(people)}`
const params = stringify({
q: `${terms}`,
sorting: random ? 'random' : 'relevance',
categories,
purity: `1${boolanToNumber(sketchy)}0`,
atleast: '1920x1080',
ratios: '16x9'
})
const { data } = await api.get(`search?${params}`)
return data.data
}
const downloadWallpaper = async (filename, url) => {
const writer = toolbox.filesystem.createWriteStream(filename, {});
const response = await api.axiosInstance.get(url, {
method: 'GET',
responseType: 'stream',
});
response.data
.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
}
toolbox.wallhaven = {
search,
downloadWallpaper,
}
// enable this if you want to read configuration in from
// the current folder's package.json (in a "nbx" property),
// nbx.config.json, etc.
// toolbox.config = {
// ...toolbox.config,
// ...toolbox.config.loadConfig(process.cwd(), "nbx")
// }
}

3
src/templates/model.ts.ejs

@ -0,0 +1,3 @@
module.exports = {
name: '<%= props.name %>'
}

26
tsconfig.json

@ -0,0 +1,26 @@
{
"compilerOptions": {
"allowSyntheticDefaultImports": false,
"experimentalDecorators": true,
"lib": [
"es2015",
"scripthost",
"es2015.promise",
"es2015.generator",
"es2015.iterable",
"dom"
],
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": false,
"noImplicitThis": true,
"noUnusedLocals": true,
"sourceMap": false,
"inlineSourceMap": true,
"outDir": "build",
"strict": false,
"target": "es5"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}

9
tslint.json

@ -0,0 +1,9 @@
{
"extends": ["tslint-config-standard", "tslint-config-prettier"],
"rules": {
"strict-type-predicates": false
},
"env": {
"jest": true
}
}

5036
yarn.lock
File diff suppressed because it is too large
View File

Loading…
Cancel
Save