diff --git a/.all-contributorsrc b/.all-contributorsrc
deleted file mode 100644
index 3d5656a1..00000000
--- a/.all-contributorsrc
+++ /dev/null
@@ -1,142 +0,0 @@
-{
- "projectName": "kcd-scripts",
- "projectOwner": "kentcdodds",
- "files": [
- "README.md"
- ],
- "imageSize": 100,
- "commit": false,
- "contributors": [
- {
- "login": "kentcdodds",
- "name": "Kent C. Dodds",
- "avatar_url": "https://avatars.githubusercontent.com/u/1500684?v=3",
- "profile": "https://kentcdodds.com",
- "contributions": [
- "code",
- "doc",
- "infra",
- "test"
- ]
- },
- {
- "login": "sudo-suhas",
- "name": "Suhas Karanth",
- "avatar_url": "https://avatars2.githubusercontent.com/u/22251956?v=4",
- "profile": "https://github.com/sudo-suhas",
- "contributions": [
- "code",
- "bug",
- "test"
- ]
- },
- {
- "login": "pbomb",
- "name": "Matt Parrish",
- "avatar_url": "https://avatars0.githubusercontent.com/u/1402095?v=4",
- "profile": "https://github.com/pbomb",
- "contributions": [
- "code",
- "test"
- ]
- },
- {
- "login": "mateuscb",
- "name": "Mateus",
- "avatar_url": "https://avatars3.githubusercontent.com/u/1319157?v=4",
- "profile": "https://github.com/mateuscb",
- "contributions": [
- "code",
- "test"
- ]
- },
- {
- "login": "macklinu",
- "name": "Macklin Underdown",
- "avatar_url": "https://avatars1.githubusercontent.com/u/2344137?v=4",
- "profile": "http://macklin.underdown.me",
- "contributions": [
- "code",
- "test"
- ]
- },
- {
- "login": "stereobooster",
- "name": "stereobooster",
- "avatar_url": "https://avatars2.githubusercontent.com/u/179534?v=4",
- "profile": "https://github.com/stereobooster",
- "contributions": [
- "code",
- "test"
- ]
- },
- {
- "login": "donysukardi",
- "name": "Dony Sukardi",
- "avatar_url": "https://avatars0.githubusercontent.com/u/410792?v=4",
- "profile": "http://dsds.io",
- "contributions": [
- "bug",
- "code"
- ]
- },
- {
- "login": "alexandernanberg",
- "name": "Alexander Nanberg",
- "avatar_url": "https://avatars3.githubusercontent.com/u/8997319?v=4",
- "profile": "https://alexandernanberg.com",
- "contributions": [
- "code"
- ]
- },
- {
- "login": "fobbyal",
- "name": "Alex Liang",
- "avatar_url": "https://avatars2.githubusercontent.com/u/7818365?v=4",
- "profile": "https://github.com/fobbyal",
- "contributions": [
- "code"
- ]
- },
- {
- "login": "shellthor",
- "name": "Jeff Detmer",
- "avatar_url": "https://avatars1.githubusercontent.com/u/649578?v=4",
- "profile": "http://www.jeffdetmer.com",
- "contributions": [
- "code"
- ]
- },
- {
- "login": "alexzherdev",
- "name": "Alex Zherdev",
- "avatar_url": "https://avatars3.githubusercontent.com/u/93752?v=4",
- "profile": "https://twitter.com/endymion_r",
- "contributions": [
- "code"
- ]
- },
- {
- "login": "adamdharrington",
- "name": "Adam Harrington",
- "avatar_url": "https://avatars0.githubusercontent.com/u/5477801?v=4",
- "profile": "https://github.com/adamdharrington",
- "contributions": [
- "code",
- "test"
- ]
- },
- {
- "login": "afontcu",
- "name": "AdriΓ Fontcuberta",
- "avatar_url": "https://avatars0.githubusercontent.com/u/9197791?v=4",
- "profile": "https://afontcu.dev",
- "contributions": [
- "code"
- ]
- }
- ],
- "repoType": "github",
- "contributorsPerLine": 7,
- "repoHost": "https://github.com"
-}
diff --git a/.eslintignore b/.eslintignore
new file mode 100644
index 00000000..e848f859
--- /dev/null
+++ b/.eslintignore
@@ -0,0 +1,4 @@
+node_modules/
+dist/
+coverage/
+package-lock.json
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
index 8ffaf1ef..290edf53 100644
--- a/.github/ISSUE_TEMPLATE.md
+++ b/.github/ISSUE_TEMPLATE.md
@@ -11,7 +11,7 @@ never done that before, that's great! Check this free short video tutorial to
learn how: http://kcd.im/pull-request
-->
-- `kcd-scripts` version:
+- `cod-scripts` version:
- `node` version:
- `npm` (or `yarn`) version:
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index ddd7e738..fa9abbee 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -36,6 +36,7 @@ merge of your pull request!
- [ ] Documentation
- [ ] Tests
-- [ ] Ready to be merged
+- [ ] Ready to be merged
+
diff --git a/.github/workflows/commitlint.yml b/.github/workflows/commitlint.yml
new file mode 100644
index 00000000..8c0d9011
--- /dev/null
+++ b/.github/workflows/commitlint.yml
@@ -0,0 +1,20 @@
+name: Lint Commit Messages
+
+on: pull_request
+
+jobs:
+ commitlint:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@master
+
+ - run: npm install --no-save
+ env:
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+
+ - run:
+ npx commitlint --config="./src/config/commitlint.config.js" --from="origin/${{
+ github.base_ref }}" --to="origin/${{ github.head_ref }}"
+ env:
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 00000000..34abf300
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,34 @@
+name: Release
+
+on:
+ push:
+ branches:
+ - master
+
+jobs:
+ release:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@master
+
+ - uses: actions/setup-node@v1
+ with:
+ node-version: 12.x
+ registry-url: https://registry.ey.npme.io
+
+ - name: validate before release
+ run: |
+ npm install --no-save
+ npm run build
+ npm run lint
+ npm run test
+ env:
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+ CI: true
+
+ - name: semantic release
+ uses: codfish/semantic-release-action@v1
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml
new file mode 100644
index 00000000..e0245d9e
--- /dev/null
+++ b/.github/workflows/validate.yml
@@ -0,0 +1,39 @@
+name: Validate Code
+
+on: push
+
+jobs:
+ validate:
+ runs-on: ubuntu-latest
+
+ strategy:
+ matrix:
+ node: [10.x, 11.x, 12.x]
+
+ steps:
+ - uses: actions/checkout@master
+
+ - uses: actions/setup-node@v1
+ with:
+ node-version: ${{ matrix.node }}
+ registry-url: https://registry.ey.npme.io
+
+ - name: install dependencies
+ run: npm install --no-save
+ env:
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+
+ - run: npm run build
+ env:
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+
+ - name: lint js
+ run: npm run lint
+ env:
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+
+ - name: run tests
+ run: npm run test
+ env:
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+ CI: true
diff --git a/.npmrc b/.npmrc
index a57cc9e5..d2722898 100644
--- a/.npmrc
+++ b/.npmrc
@@ -1 +1,2 @@
registry=http://registry.npmjs.org/
+package-lock=false
diff --git a/.prettierignore b/.prettierignore
deleted file mode 100644
index 30117ea2..00000000
--- a/.prettierignore
+++ /dev/null
@@ -1,4 +0,0 @@
-package.json
-node_modules
-dist
-coverage
diff --git a/.prettierrc b/.prettierrc
deleted file mode 100644
index fb31ee19..00000000
--- a/.prettierrc
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "printWidth": 80,
- "tabWidth": 2,
- "useTabs": false,
- "semi": false,
- "singleQuote": true,
- "trailingComma": "all",
- "bracketSpacing": false,
- "jsxBracketSameLine": false
-}
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index e8b4d792..00000000
--- a/.travis.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-sudo: false
-language: node_js
-cache:
- directories:
- - node_modules
-notifications:
- email: false
-node_js:
- - '8'
- - '10'
- - '12'
-script: npm run validate
-after_success: node src travis-after-success
-branches:
- only:
- - master
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 06d221aa..e719b93a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,4 +1,5 @@
# CHANGELOG
-The changelog is automatically updated using [semantic-release](https://github.com/semantic-release/semantic-release).
-You can see it on the [releases page](../../releases).
+The changelog is automatically updated using
+[semantic-release](https://github.com/semantic-release/semantic-release). You can see it on the
+[releases page](../../releases).
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 63356964..88b0cd6c 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -2,8 +2,8 @@
Thanks for being willing to contribute!
-**Working on your first Pull Request?** You can learn how from this _free_ series
-[How to Contribute to an Open Source Project on GitHub][egghead]
+**Working on your first Pull Request?** You can learn how from this _free_ series [How to Contribute
+to an Open Source Project on GitHub][egghead]
## Project setup
@@ -12,51 +12,48 @@ Thanks for being willing to contribute!
3. `$ npm run validate` to validate you've got it working
4. Create a branch for your PR
-> Tip: Keep your `master` branch pointing at the original repository and make
-> pull requests from branches on your fork. To do this, run:
+> Tip: Keep your `master` branch pointing at the original repository and make pull requests from
+> branches on your fork. To do this, run:
>
> ```
-> git remote add upstream https://github.com/kentcdodds/kcd-scripts.git
+> git remote add upstream https://github.com/codfish/cod-scripts.git
> git fetch upstream
> git branch --set-upstream-to=upstream/master master
> ```
>
-> This will add the original repository as a "remote" called "upstream,"
-> Then fetch the git information from that remote, then set your local `master`
-> branch to use the upstream master branch whenever you run `git pull`.
-> Then you can make all of your pull request branches based on this `master`
-> branch. Whenever you want to update your version of `master`, do a regular
+> This will add the original repository as a "remote" called "upstream," Then fetch the git
+> information from that remote, then set your local `master` branch to use the upstream master
+> branch whenever you run `git pull`. Then you can make all of your pull request branches based on
+> this `master` branch. Whenever you want to update your version of `master`, do a regular
> `git pull`.
## Committing and Pushing changes
-This project uses [`semantic-release`][semantic-release] to do automatic
-releases and generate a changelog based on the commit history. So we follow
-[a convention][convention] for commit messages. You don't have to follow this
-convention if you don't want to. Just know that when we merge your commit, we'll
-probably use "Squash and Merge" so we can change the commit message :)
+This project uses [`semantic-release`][semantic-release] to do automatic releases and generate a
+changelog based on the commit history. So we follow [a convention][convention] for commit messages.
+You don't have to follow this convention if you don't want to. Just know that when we merge your
+commit, we'll probably use "Squash and Merge" so we can change the commit message :)
-Please make sure to run the tests before you commit your changes. You can run
-`npm run test:update` which will update any snapshots that need updating.
-Make sure to include those changes (if they exist) in your commit.
+Please make sure to run the tests before you commit your changes. You can run `npm run test:update`
+which will update any snapshots that need updating. Make sure to include those changes (if they
+exist) in your commit.
### opt in/out of git hooks
-There are git hooks set up with this project that are automatically installed
-when you install dependencies. They're really handy, but are turned off by
-default (so as to not hinder new contributors). You can opt into these by
-creating a file called `.opt-in` at the root of the project and putting this
-inside:
+There are git hooks set up with this project that are automatically installed when you install
+dependencies. They're really handy, but are turned off by default (so as to not hinder new
+contributors). You can opt into these by creating a file called `.opt-in` at the root of the project
+and putting this inside:
```
pre-commit
```
-One of the things that the git hooks does is automatically format the files you
-change. It does this by reformating the entire file and running `git add` on
-the file after. This breaks workflows where you're trying to commit portions of
-the file only. You can always run your commit with `--no-verify`, but if this
-is a bummer to your workflow, you can add an `.opt-out` file with the contents:
+One of the things that the git hooks does is automatically format the files you change. It does this
+by reformating the entire file and running `git add` on the file after. This breaks workflows where
+you're trying to commit portions of the file only. You can always run your commit with
+`--no-verify`, but if this is a bummer to your workflow, you can add an `.opt-out` file with the
+contents:
```
autoformat
@@ -66,10 +63,10 @@ autoformat
Please checkout the [the open issues][issues]
-Also, please watch the repo and respond to questions/bug reports/feature
-requests! Thanks!
+Also, please watch the repo and respond to questions/bug reports/feature requests! Thanks!
[egghead]: https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github
[semantic-release]: https://npmjs.com/package/semantic-release
-[convention]: https://github.com/conventional-changelog/conventional-changelog-angular/blob/ed32559941719a130bb0327f886d6a32a8cbc2ba/convention.md
-[issues]: https://github.com/kentcdodds/kcd-scripts/issues
+[convention]:
+ https://github.com/conventional-changelog/conventional-changelog-angular/blob/ed32559941719a130bb0327f886d6a32a8cbc2ba/convention.md
+[issues]: https://github.com/codfish/cod-scripts/issues
diff --git a/README.md b/README.md
index a6737b1c..a957faaf 100644
--- a/README.md
+++ b/README.md
@@ -1,34 +1,28 @@
-
kcd-scripts π π¦
+
cod-scripts π π¦
CLI toolbox for common scripts for my projects
-[![Build Status][build-badge]][build]
-[![Code Coverage][coverage-badge]][coverage]
-[![version][version-badge]][package]
-[![downloads][downloads-badge]][npmcharts]
+[![Build Status][build-badge]][build] [![Code Coverage][coverage-badge]][coverage]
+[![version][version-badge]][package] [![downloads][downloads-badge]][npmcharts]
[![MIT License][license-badge]][license]
-[](#contributors)
-[![PRs Welcome][prs-badge]][prs]
-[![Code of Conduct][coc-badge]][coc]
+[![PRs Welcome][prs-badge]][prs] [![Code of Conduct][coc-badge]][coc]
[![Watch on GitHub][github-watch-badge]][github-watch]
-[![Star on GitHub][github-star-badge]][github-star]
-[![Tweet][twitter-badge]][twitter]
+[![Star on GitHub][github-star-badge]][github-star] [![Tweet][twitter-badge]][twitter]
## The problem
-I do a bunch of open source and want to make it easier to maintain so many
-projects.
+I do a bunch of open source and want to make it easier to maintain so many projects.
## This solution
-This is a CLI that abstracts away all configuration for my open source projects
-for linting, testing, building, and more.
+This is a CLI that abstracts away all configuration for my open source projects for linting,
+testing, building, and more.
## Table of Contents
@@ -40,49 +34,44 @@ for linting, testing, building, and more.
- [Overriding Config](#overriding-config)
- [Flow support](#flow-support)
- [Inspiration](#inspiration)
-- [Other Solutions](#other-solutions)
-- [Contributors](#contributors)
- [LICENSE](#license)
## Installation
-This module is distributed via [npm][npm] which is bundled with [node][node] and
-should be installed as one of your project's `devDependencies`:
+This module is distributed via [npm][npm] which is bundled with [node][node] and should be installed
+as one of your project's `devDependencies`:
```
-npm install --save-dev kcd-scripts
+npm install --save-dev cod-scripts
```
## Usage
-This is a CLI and exposes a bin called `kcd-scripts`. I don't really plan on
-documenting or testing it super duper well because it's really specific to my
-needs. You'll find all available scripts in `src/scripts`.
+This is a CLI and exposes a bin called `cod-scripts`. I don't really plan on documenting or testing
+it super duper well because it's really specific to my needs. You'll find all available scripts in
+`src/scripts`.
-This project actually dogfoods itself. If you look in the `package.json`, you'll
-find scripts with `node src {scriptName}`. This serves as an example of some
-of the things you can do with `kcd-scripts`.
+This project actually dogfoods itself. If you look in the `package.json`, you'll find scripts with
+`node src {scriptName}`. This serves as an example of some of the things you can do with
+`cod-scripts`.
### Overriding Config
-Unlike `react-scripts`, `kcd-scripts` allows you to specify your own
-configuration for things and have that plug directly into the way things work
-with `kcd-scripts`. There are various ways that it works, but basically if you
-want to have your own config for something, just add the configuration and
-`kcd-scripts` will use that instead of it's own internal config. In addition,
-`kcd-scripts` exposes its configuration so you can use it and override only
-the parts of the config you need to.
+Unlike `react-scripts`, `cod-scripts` allows you to specify your own configuration for things and
+have that plug directly into the way things work with `cod-scripts`. There are various ways that it
+works, but basically if you want to have your own config for something, just add the configuration
+and `cod-scripts` will use that instead of it's own internal config. In addition, `cod-scripts`
+exposes its configuration so you can use it and override only the parts of the config you need to.
-This can be a very helpful way to make editor integration work for tools like
-ESLint which require project-based ESLint configuration to be present to work.
+This can be a very helpful way to make editor integration work for tools like ESLint which require
+project-based ESLint configuration to be present to work.
-So, if we were to do this for ESLint, you could create an `.eslintrc` with the
-contents of:
+So, if we were to do this for ESLint, you could create an `.eslintrc` with the contents of:
```
-{"extends": "./node_modules/kcd-scripts/eslint.js"}
+{"extends": "./node_modules/cod-scripts/eslint.js"}
```
> Note: for now, you'll have to include an `.eslintignore` in your project until
@@ -91,13 +80,14 @@ contents of:
Or, for `babel`, a `.babelrc` with:
```
-{"presets": ["kcd-scripts/babel"]}
+{ "presets": ["cod-scripts/babel"] }
```
Or, for `jest`:
-```javascript
-const {jest: jestConfig} = require('kcd-scripts/config')
+```js
+const { jest: jestConfig } = require('cod-scripts/config');
+
module.exports = Object.assign(jestConfig, {
// your overrides here
@@ -105,83 +95,49 @@ module.exports = Object.assign(jestConfig, {
transform: {
'\\.(ts|tsx)$': '/node_modules/ts-jest/preprocessor.js',
},
-})
+});
```
-> Note: `kcd-scripts` intentionally does not merge things for you when you start
-> configuring things to make it less magical and more straightforward. Extending
-> can take place on your terms. I think this is actually a great way to do this.
+> Note: `cod-scripts` intentionally does not merge things for you when you start configuring things
+> to make it less magical and more straightforward. Extending can take place on your terms. I think
+> this is actually a great way to do this.
### Flow support
-If the `flow-bin` is a dependency on the project the `@babel/preset-flow` will automatically get loaded when you use the default babel config that comes with `kcd-scripts`. If you customised your `.babelrc`-file you might need to manually add `@babel/preset-flow` to the `presets`-section.
+If the `flow-bin` is a dependency on the project the `@babel/preset-flow` will automatically get
+loaded when you use the default babel config that comes with `cod-scripts`. If you customised your
+`.babelrc`-file you might need to manually add `@babel/preset-flow` to the `presets`-section.
## Inspiration
This is inspired by `react-scripts`.
-## Other Solutions
-
-I'm not aware of any, if you are please [make a pull request][prs] and add it
-here! Again, this is a very specific-to-me solution.
-
-## Contributors
-
-Thanks goes to these people ([emoji key][emojis]):
-
-
-
-
-
-
-
-This project follows the [all-contributors][all-contributors] specification.
-Contributions of any kind welcome!
-
## LICENSE
MIT
[npm]: https://www.npmjs.com/
[node]: https://nodejs.org
-[build-badge]: https://img.shields.io/travis/kentcdodds/kcd-scripts.svg?style=flat-square
-[build]: https://travis-ci.org/kentcdodds/kcd-scripts
-[coverage-badge]: https://img.shields.io/codecov/c/github/kentcdodds/kcd-scripts.svg?style=flat-square
-[coverage]: https://codecov.io/github/kentcdodds/kcd-scripts
-[version-badge]: https://img.shields.io/npm/v/kcd-scripts.svg?style=flat-square
-[package]: https://www.npmjs.com/package/kcd-scripts
-[downloads-badge]: https://img.shields.io/npm/dm/kcd-scripts.svg?style=flat-square
-[npmcharts]: http://npmcharts.com/compare/kcd-scripts
-[license-badge]: https://img.shields.io/npm/l/kcd-scripts.svg?style=flat-square
-[license]: https://github.com/kentcdodds/kcd-scripts/blob/master/LICENSE
+[build-badge]: https://img.shields.io/travis/codfish/cod-scripts.svg?style=flat-square
+[build]: https://travis-ci.org/codfish/cod-scripts
+[coverage-badge]: https://img.shields.io/codecov/c/github/codfish/cod-scripts.svg?style=flat-square
+[coverage]: https://codecov.io/github/codfish/cod-scripts
+[version-badge]: https://img.shields.io/npm/v/cod-scripts.svg?style=flat-square
+[package]: https://www.npmjs.com/package/cod-scripts
+[downloads-badge]: https://img.shields.io/npm/dm/cod-scripts.svg?style=flat-square
+[npmcharts]: http://npmcharts.com/compare/cod-scripts
+[license-badge]: https://img.shields.io/npm/l/cod-scripts.svg?style=flat-square
+[license]: https://github.com/codfish/cod-scripts/blob/master/LICENSE
[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
[prs]: http://makeapullrequest.com
[donate-badge]: https://img.shields.io/badge/$-support-green.svg?style=flat-square
[coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square
-[coc]: https://github.com/kentcdodds/kcd-scripts/blob/master/other/CODE_OF_CONDUCT.md
-[github-watch-badge]: https://img.shields.io/github/watchers/kentcdodds/kcd-scripts.svg?style=social
-[github-watch]: https://github.com/kentcdodds/kcd-scripts/watchers
-[github-star-badge]: https://img.shields.io/github/stars/kentcdodds/kcd-scripts.svg?style=social
-[github-star]: https://github.com/kentcdodds/kcd-scripts/stargazers
-[twitter]: https://twitter.com/intent/tweet?text=Check%20out%20kcd-scripts!%20https://github.com/kentcdodds/kcd-scripts%20%F0%9F%91%8D
-[twitter-badge]: https://img.shields.io/twitter/url/https/github.com/kentcdodds/kcd-scripts.svg?style=social
-[emojis]: https://github.com/kentcdodds/all-contributors#emoji-key
-[all-contributors]: https://github.com/kentcdodds/all-contributors
+[coc]: https://github.com/codfish/cod-scripts/blob/master/other/CODE_OF_CONDUCT.md
+[github-watch-badge]: https://img.shields.io/github/watchers/codfish/cod-scripts.svg?style=social
+[github-watch]: https://github.com/codfish/cod-scripts/watchers
+[github-star-badge]: https://img.shields.io/github/stars/codfish/cod-scripts.svg?style=social
+[github-star]: https://github.com/codfish/cod-scripts/stargazers
+[twitter]:
+ https://twitter.com/intent/tweet?text=Check%20out%20cod-scripts!%20https://github.com/codfish/cod-scripts%20%F0%9F%91%8D
+[twitter-badge]:
+ https://img.shields.io/twitter/url/https/github.com/codfish/cod-scripts.svg?style=social
diff --git a/appveyor.yml b/appveyor.yml
deleted file mode 100644
index 6b490736..00000000
--- a/appveyor.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-environment:
- matrix:
- - node_version: "8"
-branches:
- only:
- - master
-install:
- - ps: Install-Product node $env:node_version
- - npm install
-test_script: npm run validate
-cache:
- - ~/.npm
-build: off
diff --git a/babel.js b/babel.js
index f46b0555..953754cd 100644
--- a/babel.js
+++ b/babel.js
@@ -1 +1 @@
-module.exports = require('./dist/config/babelrc')
+module.exports = require('./dist/config/babelrc');
diff --git a/commitlint.js b/commitlint.js
new file mode 100644
index 00000000..23a4bda0
--- /dev/null
+++ b/commitlint.js
@@ -0,0 +1 @@
+module.exports = require('./dist/config/commitlint.config');
diff --git a/config.js b/config.js
index bb07926b..6dc01060 100644
--- a/config.js
+++ b/config.js
@@ -1 +1 @@
-module.exports = require('./dist/config')
+module.exports = require('./dist/config');
diff --git a/eslint.js b/eslint.js
index 7cc6ee52..286e06ab 100644
--- a/eslint.js
+++ b/eslint.js
@@ -1 +1 @@
-module.exports = require('./dist/config/eslintrc')
+module.exports = require('./dist/config/eslintrc');
diff --git a/jest.config.js b/jest.config.js
index d28e0ab1..f0d8dab1 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -1,5 +1,6 @@
-const {jest: jestConfig} = require('./src/config')
+const { jest: jestConfig } = require('./src/config');
module.exports = Object.assign(jestConfig, {
coverageThreshold: null,
-})
+ testPathIgnorePatterns: [...jestConfig.testPathIgnorePatterns, './src/scripts/test.js'],
+});
diff --git a/jest.js b/jest.js
index 3a1bd4e9..70169854 100644
--- a/jest.js
+++ b/jest.js
@@ -1 +1 @@
-module.exports = require('./dist/config/jest.config')
+module.exports = require('./dist/config/jest.config');
diff --git a/other/CODE_OF_CONDUCT.md b/other/CODE_OF_CONDUCT.md
deleted file mode 100644
index 89dcd555..00000000
--- a/other/CODE_OF_CONDUCT.md
+++ /dev/null
@@ -1,89 +0,0 @@
-# Contributor Covenant Code of Conduct
-
-
-
-
-
-**Table of Contents**
-
-- [Our Pledge](#our-pledge)
-- [Our Standards](#our-standards)
-- [Our Responsibilities](#our-responsibilities)
-- [Scope](#scope)
-- [Enforcement](#enforcement)
-- [Attribution](#attribution)
-
-
-
-## Our Pledge
-
-In the interest of fostering an open and welcoming environment, we as
-contributors and maintainers pledge to making participation in our project and
-our community a harassment-free experience for everyone, regardless of age, body
-size, disability, ethnicity, gender identity and expression, level of experience,
-nationality, personal appearance, race, religion, or sexual identity and
-orientation.
-
-## Our Standards
-
-Examples of behavior that contributes to creating a positive environment
-include:
-
-- Using welcoming and inclusive language
-- Being respectful of differing viewpoints and experiences
-- Gracefully accepting constructive criticism
-- Focusing on what is best for the community
-- Showing empathy towards other community members
-
-Examples of unacceptable behavior by participants include:
-
-- The use of sexualized language or imagery and unwelcome sexual attention or
- advances
-- Trolling, insulting/derogatory comments, and personal or political attacks
-- Public or private harassment
-- Publishing others' private information, such as a physical or electronic
- address, without explicit permission
-- Other conduct which could reasonably be considered inappropriate in a
- professional setting
-
-## Our Responsibilities
-
-Project maintainers are responsible for clarifying the standards of acceptable
-behavior and are expected to take appropriate and fair corrective action in
-response to any instances of unacceptable behavior.
-
-Project maintainers have the right and responsibility to remove, edit, or
-reject comments, commits, code, wiki edits, issues, and other contributions
-that are not aligned to this Code of Conduct, or to ban temporarily or
-permanently any contributor for other behaviors that they deem inappropriate,
-threatening, offensive, or harmful.
-
-## Scope
-
-This Code of Conduct applies both within project spaces and in public spaces
-when an individual is representing the project or its community. Examples of
-representing a project or community include using an official project e-mail
-address, posting via an official social media account, or acting as an appointed
-representative at an online or offline event. Representation of a project may be
-further defined and clarified by project maintainers.
-
-## Enforcement
-
-Instances of abusive, harassing, or otherwise unacceptable behavior may be
-reported by contacting the project team at kent+coc@doddsfamily.us. All
-complaints will be reviewed and investigated and will result in a response that
-is deemed necessary and appropriate to the circumstances. The project team is
-obligated to maintain confidentiality with regard to the reporter of an incident.
-Further details of specific enforcement policies may be posted separately.
-
-Project maintainers who do not follow or enforce the Code of Conduct in good
-faith may face temporary or permanent repercussions as determined by other
-members of the project's leadership.
-
-## Attribution
-
-This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
-available at [http://contributor-covenant.org/version/1/4][version]
-
-[homepage]: http://contributor-covenant.org
-[version]: http://contributor-covenant.org/version/1/4/
diff --git a/other/MAINTAINING.md b/other/MAINTAINING.md
deleted file mode 100644
index cf87aabe..00000000
--- a/other/MAINTAINING.md
+++ /dev/null
@@ -1,77 +0,0 @@
-# Maintaining
-
-
-
-
-
-**Table of Contents**
-
-- [Code of Conduct](#code-of-conduct)
-- [Issues](#issues)
-- [Pull Requests](#pull-requests)
-- [Release](#release)
-- [Thanks!](#thanks)
-
-
-
-This is documentation for maintainers of this project.
-
-## Code of Conduct
-
-Please review, understand, and be an example of it. Violations of the code of conduct are
-taken seriously, even (especially) for maintainers.
-
-## Issues
-
-We want to support and build the community. We do that best by helping people learn to solve
-their own problems. We have an issue template and hopefully most folks follow it. If it's
-not clear what the issue is, invite them to create a minimal reproduction of what they're trying
-to accomplish or the bug they think they've found.
-
-Once it's determined that a code change is necessary, point people to
-[makeapullrequest.com](http://makeapullrequest.com) and invite them to make a pull request.
-If they're the one who needs the feature, they're the one who can build it. If they need
-some hand holding and you have time to lend a hand, please do so. It's an investment into
-another human being, and an investment into a potential maintainer.
-
-Remember that this is open source, so the code is not yours, it's ours. If someone needs a change
-in the codebase, you don't have to make it happen yourself. Commit as much time to the project
-as you want/need to. Nobody can ask any more of you than that.
-
-## Pull Requests
-
-As a maintainer, you're fine to make your branches on the main repo or on your own fork. Either
-way is fine.
-
-When we receive a pull request, a travis build is kicked off automatically (see the `.travis.yml`
-for what runs in the travis build). We avoid merging anything that breaks the travis build.
-
-Please review PRs and focus on the code rather than the individual. You never know when this is
-someone's first ever PR and we want their experience to be as positive as possible, so be
-uplifting and constructive.
-
-When you merge the pull request, 99% of the time you should use the
-[Squash and merge](https://help.github.com/articles/merging-a-pull-request/) feature. This keeps
-our git history clean, but more importantly, this allows us to make any necessary changes to the
-commit message so we release what we want to release. See the next section on Releases for more
-about that.
-
-## Release
-
-Our releases are automatic. They happen whenever code lands into `master`. A travis build gets
-kicked off and if it's successful, a tool called
-[`semantic-release`](https://github.com/semantic-release/semantic-release) is used to
-automatically publish a new release to npm as well as a changelog to GitHub. It is only able to
-determine the version and whether a release is necessary by the git commit messages. With this
-in mind, **please brush up on [the commit message convention][commit] which drives our releases.**
-
-> One important note about this: Please make sure that commit messages do NOT contain the words
-> "BREAKING CHANGE" in them unless we want to push a major version. I've been burned by this
-> more than once where someone will include "BREAKING CHANGE: None" and it will end up releasing
-> a new major version. Not a huge deal honestly, but kind of annoying...
-
-## Thanks!
-
-Thank you so much for helping to maintain this project!
-
-[commit]: https://github.com/conventional-changelog-archived-repos/conventional-changelog-angular/blob/ed32559941719a130bb0327f886d6a32a8cbc2ba/convention.md
diff --git a/other/USERS.md b/other/USERS.md
deleted file mode 100644
index 85c01cf2..00000000
--- a/other/USERS.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# Users
-
-
-
-
-
-
-
-If you or your company uses this project, add your name to this list! Eventually
-we may have a website to showcase these (wanna build it!?)
-
-> No users have been added yet!
-
-
diff --git a/other/manual-releases.md b/other/manual-releases.md
deleted file mode 100644
index dadf7d38..00000000
--- a/other/manual-releases.md
+++ /dev/null
@@ -1,49 +0,0 @@
-# manual-releases
-
-
-
-
-
-
-
-This project has an automated release set up. So things are only released when there are
-useful changes in the code that justify a release. But sometimes things get messed up one way or another
-and we need to trigger the release ourselves. When this happens, simply bump the number below and commit
-that with the following commit message based on your needs:
-
-**Major**
-
-```
-fix(release): manually release a major version
-
-There was an issue with a major release, so this manual-releases.md
-change is to release a new major version.
-
-Reference: #
-
-BREAKING CHANGE:
-```
-
-**Minor**
-
-```
-feat(release): manually release a minor version
-
-There was an issue with a minor release, so this manual-releases.md
-change is to release a new minor version.
-
-Reference: #
-```
-
-**Patch**
-
-```
-fix(release): manually release a patch version
-
-There was an issue with a patch release, so this manual-releases.md
-change is to release a new patch version.
-
-Reference: #
-```
-
-The number of times we've had to do a manual release is: 0
diff --git a/package.json b/package.json
index 6dae795b..deac74e0 100644
--- a/package.json
+++ b/package.json
@@ -1,5 +1,5 @@
{
- "name": "kcd-scripts",
+ "name": "cod-scripts",
"version": "0.0.0-semantically-released",
"description": "CLI for common scripts for my projects",
"engines": {
@@ -7,7 +7,7 @@
"npm": ">= 5"
},
"bin": {
- "kcd-scripts": "dist/index.js"
+ "cod-scripts": "dist/index.js"
},
"scripts": {
"test": "node src test",
@@ -31,7 +31,7 @@
"jest.js"
],
"keywords": [],
- "author": "Kent C. Dodds (http://kentcdodds.com/)",
+ "author": "Chris O'Donnell (http://codfish.io/)",
"license": "MIT",
"dependencies": {
"@babel/cli": "^7.5.5",
@@ -56,9 +56,8 @@
"cross-env": "^5.1.4",
"cross-spawn": "^6.0.5",
"doctoc": "^1.4.0",
- "eslint": "^6.1.0",
- "eslint-config-kentcdodds": "^14.3.4",
- "eslint-config-prettier": "^6.0.0",
+ "eslint": "^5.15.2",
+ "eslint-config-codfish": "^2.5.0",
"glob": "^7.1.4",
"husky": "^3.0.3",
"is-ci": "^2.0.0",
@@ -69,7 +68,7 @@
"lodash.has": "^4.5.2",
"lodash.omit": "^4.5.0",
"mkdirp": "^0.5.1",
- "prettier": "^1.18.2",
+ "prettier": "^1.16.4",
"read-pkg-up": "^6.0.0",
"resolve": "^1.12.0",
"rimraf": "^2.6.2",
@@ -89,32 +88,24 @@
},
"eslintConfig": {
"extends": [
- "kentcdodds",
- "kentcdodds/jest"
+ "./src/config/eslintrc.js"
],
"rules": {
- "no-process-exit": "off",
- "import/no-dynamic-require": "off",
- "import/no-unassigned-import": "off",
"no-console": "off",
- "no-nested-ternary": "off",
- "no-useless-catch": "off"
+ "global-require": "off"
}
},
- "eslintIgnore": [
- "node_modules",
- "coverage",
- "dist"
- ],
"repository": {
"type": "git",
- "url": "https://github.com/kentcdodds/kcd-scripts.git"
+ "url": "https://github.com/codfish/cod-scripts.git"
},
"bugs": {
- "url": "https://github.com/kentcdodds/kcd-scripts/issues"
+ "url": "https://github.com/codfish/cod-scripts/issues"
},
- "homepage": "https://github.com/kentcdodds/kcd-scripts#readme",
+ "homepage": "https://github.com/codfish/cod-scripts#readme",
"devDependencies": {
+ "@commitlint/cli": "^8.1.0",
+ "@commitlint/config-conventional": "^8.1.0",
"jest-in-case": "^1.0.2",
"slash": "^3.0.0"
}
diff --git a/prettier.js b/prettier.js
index de4ba09d..898d0336 100644
--- a/prettier.js
+++ b/prettier.js
@@ -1 +1 @@
-module.exports = require('./dist/config/prettierrc')
+module.exports = require('./dist/config/prettierrc');
diff --git a/src/__mocks__/cross-spawn.js b/src/__mocks__/cross-spawn.js
index a16265e8..fcad0923 100644
--- a/src/__mocks__/cross-spawn.js
+++ b/src/__mocks__/cross-spawn.js
@@ -1,3 +1,3 @@
module.exports = {
- sync: jest.fn(() => ({status: 0})),
-}
+ sync: jest.fn(() => ({ status: 0 })),
+};
diff --git a/src/__tests__/__snapshots__/index.js.snap b/src/__tests__/__snapshots__/index.js.snap
index 5e9e2333..3256635f 100644
--- a/src/__tests__/__snapshots__/index.js.snap
+++ b/src/__tests__/__snapshots__/index.js.snap
@@ -32,7 +32,6 @@ Available Scripts:
lint
pre-commit
test
- travis-after-success
validate
Options:
diff --git a/src/__tests__/index.js b/src/__tests__/index.js
index c5af4334..bc28db30 100644
--- a/src/__tests__/index.js
+++ b/src/__tests__/index.js
@@ -1,58 +1,58 @@
-import path from 'path'
-import slash from 'slash'
-import cases from 'jest-in-case'
-import {unquoteSerializer} from '../scripts/__tests__/helpers/serializers'
+import path from 'path';
+import slash from 'slash';
+import cases from 'jest-in-case';
+import { unquoteSerializer } from '../scripts/__tests__/helpers/serializers';
-const projectRoot = path.join(__dirname, '../../')
+const projectRoot = path.join(__dirname, '../../');
-expect.addSnapshotSerializer(unquoteSerializer)
+expect.addSnapshotSerializer(unquoteSerializer);
expect.addSnapshotSerializer({
print: val => slash(val.replace(projectRoot, '/')),
test: val => typeof val === 'string' && val.includes(projectRoot),
-})
+});
cases(
'format',
- ({snapshotLog = false, throws = false, signal = false, args = []}) => {
+ ({ snapshotLog = false, throws = false, signal = false, args = [] }) => {
// beforeEach
- const {sync: crossSpawnSyncMock} = require('cross-spawn')
- const originalExit = process.exit
- const originalArgv = process.argv
- const originalLog = console.log
- process.exit = jest.fn()
- console.log = jest.fn()
+ const { sync: crossSpawnSyncMock } = require('cross-spawn');
+ const originalExit = process.exit;
+ const originalArgv = process.argv;
+ const originalLog = console.log;
+ process.exit = jest.fn();
+ console.log = jest.fn();
try {
// tests
- process.argv = ['node', '../', ...args]
- crossSpawnSyncMock.mockClear()
+ process.argv = ['node', '../', ...args];
+ crossSpawnSyncMock.mockClear();
if (signal) {
- crossSpawnSyncMock.mockReturnValueOnce({result: 1, signal})
+ crossSpawnSyncMock.mockReturnValueOnce({ result: 1, signal });
}
- require('../')
+ require('../');
if (snapshotLog) {
- expect(console.log.mock.calls).toMatchSnapshot()
+ expect(console.log.mock.calls).toMatchSnapshot();
} else if (signal) {
- expect(process.exit).toHaveBeenCalledTimes(1)
- expect(process.exit).toHaveBeenCalledWith(1)
- expect(console.log.mock.calls).toMatchSnapshot()
+ expect(process.exit).toHaveBeenCalledTimes(1);
+ expect(process.exit).toHaveBeenCalledWith(1);
+ expect(console.log.mock.calls).toMatchSnapshot();
} else {
- expect(crossSpawnSyncMock).toHaveBeenCalledTimes(1)
- const [firstCall] = crossSpawnSyncMock.mock.calls
- const [script, calledArgs] = firstCall
- expect([script, ...calledArgs].join(' ')).toMatchSnapshot()
+ expect(crossSpawnSyncMock).toHaveBeenCalledTimes(1);
+ const [firstCall] = crossSpawnSyncMock.mock.calls;
+ const [script, calledArgs] = firstCall;
+ expect([script, ...calledArgs].join(' ')).toMatchSnapshot();
}
} catch (error) {
if (throws) {
- expect(error.message).toMatchSnapshot()
+ expect(error.message).toMatchSnapshot();
} else {
- throw error
+ throw error;
}
} finally {
// afterEach
- process.exit = originalExit
- process.argv = originalArgv
- console.log = originalLog
- jest.resetModules()
+ process.exit = originalExit;
+ process.argv = originalArgv;
+ console.log = originalLog;
+ jest.resetModules();
}
},
{
@@ -79,6 +79,6 @@ cases(
signal: 'SIGBREAK',
},
},
-)
+);
/* eslint complexity:0 */
diff --git a/src/__tests__/utils.js b/src/__tests__/utils.js
index e812bffe..322ed83f 100644
--- a/src/__tests__/utils.js
+++ b/src/__tests__/utils.js
@@ -1,74 +1,80 @@
jest.mock('read-pkg-up', () => ({
- sync: jest.fn(() => ({package: {}, path: '/blah/package.json'})),
-}))
-jest.mock('which', () => ({sync: jest.fn(() => {})}))
+ sync: jest.fn(() => ({ package: {}, path: '/blah/package.json' })),
+}));
+jest.mock('which', () => ({ sync: jest.fn(() => {}) }));
-let whichSyncMock, readPkgUpSyncMock
+let whichSyncMock;
+let readPkgUpSyncMock;
+
+function mockPkg({ package: pkg = {}, path = '/blah/package.json' }) {
+ readPkgUpSyncMock.mockImplementationOnce(() => ({ package: pkg, path }));
+}
beforeEach(() => {
- jest.resetModules()
- whichSyncMock = require('which').sync
- readPkgUpSyncMock = require('read-pkg-up').sync
-})
+ jest.resetModules();
+ whichSyncMock = require('which').sync;
+ readPkgUpSyncMock = require('read-pkg-up').sync;
+});
test('package is the package.json', () => {
- const myPkg = {name: 'blah'}
- mockPkg({package: myPkg})
- expect(require('../utils').pkg).toBe(myPkg)
-})
+ const myPkg = { name: 'blah' };
+ mockPkg({ package: myPkg });
+ expect(require('../utils').pkg).toBe(myPkg);
+});
test('appDirectory is the dirname to the package.json', () => {
- const pkgPath = '/some/path/to'
- mockPkg({path: `${pkgPath}/package.json`})
- expect(require('../utils').appDirectory).toBe(pkgPath)
-})
-
-test('resolveKcdScripts resolves to src/index.js when in the kcd-scripts package', () => {
- mockPkg({package: {name: 'kcd-scripts'}})
- expect(require('../utils').resolveKcdScripts()).toBe(
+ const pkgPath = '/some/path/to';
+ mockPkg({ path: `${pkgPath}/package.json` });
+ expect(require('../utils').appDirectory).toBe(pkgPath);
+});
+
+test('resolveCodScripts resolves to src/index.js when in the cod-scripts package', () => {
+ mockPkg({ package: { name: 'cod-scripts' } });
+ expect(require('../utils').resolveCodScripts()).toBe(
require.resolve('../').replace(process.cwd(), '.'),
- )
-})
+ );
+});
-test('resolveKcdScripts resolves to kcd-scripts if not in the kcd-scripts package', () => {
- mockPkg({package: {name: 'not-kcd-scripts'}})
- whichSyncMock.mockImplementationOnce(() => require.resolve('../'))
- expect(require('../utils').resolveKcdScripts()).toBe('kcd-scripts')
-})
+test('resolveCodScripts resolves to cod-scripts if not in the cod-scripts package', () => {
+ mockPkg({ package: { name: 'not-cod-scripts' } });
+ whichSyncMock.mockImplementationOnce(() => require.resolve('../'));
+ expect(require('../utils').resolveCodScripts()).toBe('cod-scripts');
+});
test(`resolveBin resolves to the full path when it's not in $PATH`, () => {
expect(require('../utils').resolveBin('cross-env')).toBe(
require.resolve('cross-env/dist/bin/cross-env').replace(process.cwd(), '.'),
- )
-})
+ );
+});
test(`resolveBin resolves to the binary if it's in $PATH`, () => {
whichSyncMock.mockImplementationOnce(() =>
require.resolve('cross-env/dist/bin/cross-env').replace(process.cwd(), '.'),
- )
- expect(require('../utils').resolveBin('cross-env')).toBe('cross-env')
- expect(whichSyncMock).toHaveBeenCalledTimes(1)
- expect(whichSyncMock).toHaveBeenCalledWith('cross-env')
-})
+ );
+ expect(require('../utils').resolveBin('cross-env')).toBe('cross-env');
+ expect(whichSyncMock).toHaveBeenCalledTimes(1);
+ expect(whichSyncMock).toHaveBeenCalledWith('cross-env');
+});
describe('for windows', () => {
- let realpathSync
+ let realpathSync;
beforeEach(() => {
- jest.doMock('fs', () => ({realpathSync: jest.fn()}))
- realpathSync = require('fs').realpathSync
- })
+ jest.doMock('fs', () => ({ realpathSync: jest.fn() }));
+ realpathSync = require('fs').realpathSync; // eslint-disable-line
+ });
+
afterEach(() => {
- jest.unmock('fs')
- })
+ jest.unmock('fs');
+ });
test('resolveBin resolves to .bin path when which returns a windows-style cmd', () => {
- const fullBinPath = '\\project\\node_modules\\.bin\\concurrently.CMD'
- realpathSync.mockImplementation(() => fullBinPath)
- expect(require('../utils').resolveBin('concurrently')).toBe(fullBinPath)
- expect(realpathSync).toHaveBeenCalledTimes(2)
- })
-})
+ const fullBinPath = '\\project\\node_modules\\.bin\\concurrently.CMD';
+ realpathSync.mockImplementation(() => fullBinPath);
+ expect(require('../utils').resolveBin('concurrently')).toBe(fullBinPath);
+ expect(realpathSync).toHaveBeenCalledTimes(2);
+ });
+});
test('getConcurrentlyArgs gives good args to pass to concurrently', () => {
expect(
@@ -88,55 +94,49 @@ test('getConcurrentlyArgs gives good args to pass to concurrently', () => {
i: 'echo i',
j: 'echo j',
}),
- ).toMatchSnapshot()
-})
+ ).toMatchSnapshot();
+});
test('parseEnv parses the existing environment variable', () => {
- const globals = {react: 'React', 'prop-types': 'PropTypes'}
- process.env.BUILD_GLOBALS = JSON.stringify(globals)
- expect(require('../utils').parseEnv('BUILD_GLOBALS')).toEqual(globals)
- delete process.env.BUILD_GLOBALS
-})
+ const globals = { react: 'React', 'prop-types': 'PropTypes' };
+ process.env.BUILD_GLOBALS = JSON.stringify(globals);
+ expect(require('../utils').parseEnv('BUILD_GLOBALS')).toEqual(globals);
+ delete process.env.BUILD_GLOBALS;
+});
test(`parseEnv returns the default if the environment variable doesn't exist`, () => {
- const defaultVal = {hello: 'world'}
- expect(require('../utils').parseEnv('DOES_NOT_EXIST', defaultVal)).toBe(
- defaultVal,
- )
-})
+ const defaultVal = { hello: 'world' };
+ expect(require('../utils').parseEnv('DOES_NOT_EXIST', defaultVal)).toBe(defaultVal);
+});
test('ifAnyDep returns the true argument if true and false argument if false', () => {
- mockPkg({package: {peerDependencies: {react: '*'}}})
- const t = {a: 'b'}
- const f = {c: 'd'}
- expect(require('../utils').ifAnyDep('react', t, f)).toBe(t)
- expect(require('../utils').ifAnyDep('preact', t, f)).toBe(f)
-})
+ mockPkg({ package: { peerDependencies: { react: '*' } } });
+ const t = { a: 'b' };
+ const f = { c: 'd' };
+ expect(require('../utils').ifAnyDep('react', t, f)).toBe(t);
+ expect(require('../utils').ifAnyDep('preact', t, f)).toBe(f);
+});
test('ifAnyDep works with arrays of dependencies', () => {
- mockPkg({package: {peerDependencies: {react: '*'}}})
- const t = {a: 'b'}
- const f = {c: 'd'}
- expect(require('../utils').ifAnyDep(['preact', 'react'], t, f)).toBe(t)
- expect(require('../utils').ifAnyDep(['preact', 'webpack'], t, f)).toBe(f)
-})
+ mockPkg({ package: { peerDependencies: { react: '*' } } });
+ const t = { a: 'b' };
+ const f = { c: 'd' };
+ expect(require('../utils').ifAnyDep(['preact', 'react'], t, f)).toBe(t);
+ expect(require('../utils').ifAnyDep(['preact', 'webpack'], t, f)).toBe(f);
+});
test('ifScript returns the true argument if true and the false argument if false', () => {
- mockPkg({package: {scripts: {build: 'echo build'}}})
- const t = {e: 'f'}
- const f = {g: 'h'}
- expect(require('../utils').ifScript('build', t, f)).toBe(t)
- expect(require('../utils').ifScript('lint', t, f)).toBe(f)
-})
+ mockPkg({ package: { scripts: { build: 'echo build' } } });
+ const t = { e: 'f' };
+ const f = { g: 'h' };
+ expect(require('../utils').ifScript('build', t, f)).toBe(t);
+ expect(require('../utils').ifScript('lint', t, f)).toBe(f);
+});
test('ifFile returns the true argument if true and the false argument if false', () => {
- mockPkg({path: require.resolve('../../package.json')})
- const t = {e: 'f'}
- const f = {g: 'h'}
- expect(require('../utils').ifFile('package.json', t, f)).toBe(t)
- expect(require('../utils').ifFile('does-not-exist.blah', t, f)).toBe(f)
-})
-
-function mockPkg({package: pkg = {}, path = '/blah/package.json'}) {
- readPkgUpSyncMock.mockImplementationOnce(() => ({package: pkg, path}))
-}
+ mockPkg({ path: require.resolve('../../package.json') });
+ const t = { e: 'f' };
+ const f = { g: 'h' };
+ expect(require('../utils').ifFile('package.json', t, f)).toBe(t);
+ expect(require('../utils').ifFile('does-not-exist.blah', t, f)).toBe(f);
+});
diff --git a/src/config/__tests__/lintstagedrc.js b/src/config/__tests__/lintstagedrc.js
index db4b52a4..25b8ced8 100644
--- a/src/config/__tests__/lintstagedrc.js
+++ b/src/config/__tests__/lintstagedrc.js
@@ -1,41 +1,39 @@
-import * as utilsMock from '../../utils'
+import * as utilsMock from '../../utils';
+
+function hasFormat(linter) {
+ return linter.some(l => l.includes('format'));
+}
+
+function hasGitAdd(linter) {
+ return linter.includes('git add');
+}
+
+function getJsLinter(linters) {
+ const key = Object.keys(linters).find(k => k.includes('*') && k.includes('js'));
+ return linters[key];
+}
jest.mock('../../utils', () => ({
...require.requireActual('../../utils'),
isOptedOut: jest.fn((key, t) => t),
-}))
+}));
afterEach(() => {
- jest.resetModules()
-})
+ jest.resetModules();
+});
test('includes format and git add when not opted out', () => {
- utilsMock.isOptedOut.mockImplementation((key, t, f) => f)
- const config = require('../lintstagedrc')
- const jsLinter = getJsLinter(config)
- expect(hasFormat(jsLinter)).toBe(true)
- expect(hasGitAdd(jsLinter)).toBe(true)
-})
+ utilsMock.isOptedOut.mockImplementation((key, t, f) => f);
+ const config = require('../lintstagedrc');
+ const jsLinter = getJsLinter(config);
+ expect(hasFormat(jsLinter)).toBe(true);
+ expect(hasGitAdd(jsLinter)).toBe(true);
+});
test('does not include format and git add when opted out', () => {
- utilsMock.isOptedOut.mockImplementation((key, t) => t)
- const config = require('../lintstagedrc')
- const jsLinter = getJsLinter(config)
- expect(hasFormat(jsLinter)).toBe(false)
- expect(hasGitAdd(jsLinter)).toBe(false)
-})
-
-function hasFormat(linter) {
- return linter.some(l => l.includes('format'))
-}
-
-function hasGitAdd(linter) {
- return linter.includes('git add')
-}
-
-function getJsLinter(linters) {
- const key = Object.keys(linters).find(
- k => k.includes('*') && k.includes('js'),
- )
- return linters[key]
-}
+ utilsMock.isOptedOut.mockImplementation((key, t) => t);
+ const config = require('../lintstagedrc');
+ const jsLinter = getJsLinter(config);
+ expect(hasFormat(jsLinter)).toBe(false);
+ expect(hasGitAdd(jsLinter)).toBe(false);
+});
diff --git a/src/config/__tests__/umbrella.js b/src/config/__tests__/umbrella.js
index c1e9c065..a104af05 100644
--- a/src/config/__tests__/umbrella.js
+++ b/src/config/__tests__/umbrella.js
@@ -1,10 +1,10 @@
test('requiring some files does not blow up', () => {
- require('../babel-transform')
- require('../babelrc')
- require('../eslintrc')
- require('../jest.config')
- require('../lintstagedrc')
- require('../prettierrc')
- require('../rollup.config')
- require('../').getRollupConfig()
-})
+ require('../babel-transform');
+ require('../babelrc');
+ require('../eslintrc');
+ require('../jest.config');
+ require('../lintstagedrc');
+ require('../prettierrc');
+ require('../rollup.config');
+ require('../').getRollupConfig();
+});
diff --git a/src/config/babel-transform.js b/src/config/babel-transform.js
index cbda1e7a..f0f1f482 100644
--- a/src/config/babel-transform.js
+++ b/src/config/babel-transform.js
@@ -1,5 +1,5 @@
-const babelJest = require('babel-jest')
+const babelJest = require('babel-jest');
module.exports = babelJest.createTransformer({
presets: [require.resolve('./babelrc')],
-})
+});
diff --git a/src/config/babelrc.js b/src/config/babelrc.js
index cadbb419..bcfbb2f0 100644
--- a/src/config/babelrc.js
+++ b/src/config/babelrc.js
@@ -1,97 +1,79 @@
-const browserslist = require('browserslist')
-const semver = require('semver')
+const browserslist = require('browserslist');
+const semver = require('semver');
-const {ifAnyDep, parseEnv, appDirectory, pkg} = require('../utils')
+const { ifAnyDep, parseEnv, appDirectory, pkg } = require('../utils');
-const {BABEL_ENV, NODE_ENV, BUILD_FORMAT} = process.env
-const isTest = (BABEL_ENV || NODE_ENV) === 'test'
-const isPreact = parseEnv('BUILD_PREACT', false)
-const isRollup = parseEnv('BUILD_ROLLUP', false)
-const isUMD = BUILD_FORMAT === 'umd'
-const isCJS = BUILD_FORMAT === 'cjs'
-const isWebpack = parseEnv('BUILD_WEBPACK', false)
-const treeshake = parseEnv('BUILD_TREESHAKE', isRollup || isWebpack)
-const alias = parseEnv('BUILD_ALIAS', isPreact ? {react: 'preact'} : null)
+const { BABEL_ENV, NODE_ENV, BUILD_FORMAT } = process.env;
+const isTest = (BABEL_ENV || NODE_ENV) === 'test';
+const isPreact = parseEnv('BUILD_PREACT', false);
+const isRollup = parseEnv('BUILD_ROLLUP', false);
+const isUMD = BUILD_FORMAT === 'umd';
+const isCJS = BUILD_FORMAT === 'cjs';
+const isWebpack = parseEnv('BUILD_WEBPACK', false);
+const treeshake = parseEnv('BUILD_TREESHAKE', isRollup || isWebpack);
+const alias = parseEnv('BUILD_ALIAS', isPreact ? { react: 'preact' } : null);
-const hasBabelRuntimeDep = Boolean(
- pkg.dependencies && pkg.dependencies['@babel/runtime'],
-)
+const hasBabelRuntimeDep = Boolean(pkg.dependencies && pkg.dependencies['@babel/runtime']);
const RUNTIME_HELPERS_WARN =
- 'You should add @babel/runtime as dependency to your package. It will allow reusing "babel helpers" from node_modules rather than bundling their copies into your files.'
+ 'You should add @babel/runtime as dependency to your package. It will allow reusing "babel helpers" from node_modules rather than bundling their copies into your files.';
if (!treeshake && !hasBabelRuntimeDep && !isTest) {
- throw new Error(RUNTIME_HELPERS_WARN)
+ throw new Error(RUNTIME_HELPERS_WARN);
} else if (treeshake && !isUMD && !hasBabelRuntimeDep) {
- console.warn(RUNTIME_HELPERS_WARN)
+ console.warn(RUNTIME_HELPERS_WARN);
+}
+
+function getNodeVersion({ engines: { node: nodeVersion = '8' } = {} }) {
+ const oldestVersion = semver
+ .validRange(nodeVersion)
+ .replace(/[>=<|]/g, ' ')
+ .split(' ')
+ .filter(Boolean)
+ .sort(semver.compare)[0];
+ if (!oldestVersion) {
+ throw new Error(
+ `Unable to determine the oldest version in the range in your package.json at engines.node: "${nodeVersion}". Please attempt to make it less ambiguous.`,
+ );
+ }
+ return oldestVersion;
}
/**
- * use the strategy declared by browserslist to load browsers configuration.
+ * Use the strategy declared by browserslist to load browsers configuration.
* fallback to the default if don't found custom configuration
+ *
* @see https://github.com/browserslist/browserslist/blob/master/node.js#L139
*/
-const browsersConfig = browserslist.loadConfig({path: appDirectory}) || [
- 'ie 10',
- 'ios 7',
-]
+const browsersConfig = browserslist.loadConfig({ path: appDirectory }) || ['ie 10', 'ios 7'];
+// eslint-disable-next-line
const envTargets = isTest
- ? {node: 'current'}
+ ? { node: 'current' }
: isWebpack || isRollup
- ? {browsers: browsersConfig}
- : {node: getNodeVersion(pkg)}
-const envOptions = {modules: false, loose: true, targets: envTargets}
+ ? { browsers: browsersConfig }
+ : { node: getNodeVersion(pkg) };
+const envOptions = { modules: false, loose: true, targets: envTargets };
module.exports = () => ({
presets: [
[require.resolve('@babel/preset-env'), envOptions],
ifAnyDep(
['react', 'preact'],
- [
- require.resolve('@babel/preset-react'),
- {pragma: isPreact ? 'React.h' : undefined},
- ],
+ [require.resolve('@babel/preset-react'), { pragma: isPreact ? 'React.h' : undefined }],
),
ifAnyDep(['flow-bin'], [require.resolve('@babel/preset-flow')]),
].filter(Boolean),
plugins: [
- [
- require.resolve('@babel/plugin-transform-runtime'),
- {useESModules: treeshake && !isCJS},
- ],
+ [require.resolve('@babel/plugin-transform-runtime'), { useESModules: treeshake && !isCJS }],
require.resolve('babel-plugin-macros'),
- alias
- ? [
- require.resolve('babel-plugin-module-resolver'),
- {root: ['./src'], alias},
- ]
- : null,
+ alias ? [require.resolve('babel-plugin-module-resolver'), { root: ['./src'], alias }] : null,
[
require.resolve('babel-plugin-transform-react-remove-prop-types'),
- isPreact ? {removeImport: true} : {mode: 'unsafe-wrap'},
+ isPreact ? { removeImport: true } : { mode: 'unsafe-wrap' },
],
- isUMD
- ? require.resolve('babel-plugin-transform-inline-environment-variables')
- : null,
- [require.resolve('@babel/plugin-proposal-class-properties'), {loose: true}],
+ isUMD ? require.resolve('babel-plugin-transform-inline-environment-variables') : null,
+ [require.resolve('@babel/plugin-proposal-class-properties'), { loose: true }],
require.resolve('babel-plugin-minify-dead-code-elimination'),
- treeshake
- ? null
- : require.resolve('@babel/plugin-transform-modules-commonjs'),
+ treeshake ? null : require.resolve('@babel/plugin-transform-modules-commonjs'),
].filter(Boolean),
-})
-
-function getNodeVersion({engines: {node: nodeVersion = '8'} = {}}) {
- const oldestVersion = semver
- .validRange(nodeVersion)
- .replace(/[>=<|]/g, ' ')
- .split(' ')
- .filter(Boolean)
- .sort(semver.compare)[0]
- if (!oldestVersion) {
- throw new Error(
- `Unable to determine the oldest version in the range in your package.json at engines.node: "${nodeVersion}". Please attempt to make it less ambiguous.`,
- )
- }
- return oldestVersion
-}
+});
diff --git a/src/config/commitlint.config.js b/src/config/commitlint.config.js
new file mode 100644
index 00000000..84dcb122
--- /dev/null
+++ b/src/config/commitlint.config.js
@@ -0,0 +1,3 @@
+module.exports = {
+ extends: ['@commitlint/config-conventional'],
+};
diff --git a/src/config/eslintignore b/src/config/eslintignore
index 5ab667c9..1d8518c4 100644
--- a/src/config/eslintignore
+++ b/src/config/eslintignore
@@ -1,6 +1,9 @@
node_modules/
-coverage/
dist/
build/
+coverage/
out/
.next/
+docs/
+package-lock.json
+serviceWorker.js
diff --git a/src/config/eslintrc.js b/src/config/eslintrc.js
index 741a3944..2aed3144 100644
--- a/src/config/eslintrc.js
+++ b/src/config/eslintrc.js
@@ -1,11 +1,8 @@
-const {ifAnyDep} = require('../utils')
+const prettierConfig = require('./prettierrc');
module.exports = {
- extends: [
- require.resolve('eslint-config-kentcdodds'),
- require.resolve('eslint-config-kentcdodds/jest'),
- ifAnyDep('react', require.resolve('eslint-config-kentcdodds/jsx-a11y')),
- ifAnyDep('react', require.resolve('eslint-config-kentcdodds/react')),
- ].filter(Boolean),
- rules: {},
-}
+ extends: [require.resolve('eslint-config-codfish')].filter(Boolean),
+ rules: {
+ 'prettier/prettier': ['error', prettierConfig],
+ },
+};
diff --git a/src/config/index.js b/src/config/index.js
index a06d99ac..86fe9ee0 100644
--- a/src/config/index.js
+++ b/src/config/index.js
@@ -5,4 +5,4 @@ module.exports = {
lintStaged: require('./lintstagedrc'),
prettier: require('./prettierrc'),
getRollupConfig: () => require('./rollup.config'),
-}
+};
diff --git a/src/config/jest.config.js b/src/config/jest.config.js
index 5c074d7e..4447eeb7 100644
--- a/src/config/jest.config.js
+++ b/src/config/jest.config.js
@@ -1,16 +1,12 @@
-const path = require('path')
-const {ifAnyDep, hasFile, hasPkgProp, fromRoot} = require('../utils')
+const path = require('path');
+const { ifAnyDep, hasFile, hasPkgProp, fromRoot } = require('../utils');
-const here = p => path.join(__dirname, p)
+const here = p => path.join(__dirname, p);
-const useBuiltInBabelConfig = !hasFile('.babelrc') && !hasPkgProp('babel')
+const useBuiltInBabelConfig =
+ !hasFile('.babelrc') && !hasFile('.babelrc.js') && !hasPkgProp('babel');
-const ignores = [
- '/node_modules/',
- '/fixtures/',
- '/__tests__/helpers/',
- '__mocks__',
-]
+const ignores = ['/node_modules/', '/fixtures/', '/__tests__/helpers/', '__mocks__'];
const jestConfig = {
roots: [fromRoot('src')],
@@ -18,7 +14,7 @@ const jestConfig = {
testURL: 'http://localhost',
moduleFileExtensions: ['js', 'jsx', 'json', 'ts', 'tsx'],
collectCoverageFrom: ['src/**/*.+(js|jsx|ts|tsx)'],
- testMatch: ['**/__tests__/**/*.+(js|jsx|ts|tsx)'],
+ testMatch: ['**/__tests__/**/*.+(js|jsx|ts|tsx)', '**/?(*.)+(spec|test).[jt]s?(x)'],
testPathIgnorePatterns: [...ignores],
coveragePathIgnorePatterns: [...ignores, 'src/(umd|cjs|esm)-entry.js$'],
transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$'],
@@ -34,14 +30,18 @@ const jestConfig = {
require.resolve('jest-watch-typeahead/filename'),
require.resolve('jest-watch-typeahead/testname'),
],
+};
+
+if (hasFile('setupTests.js')) {
+ jestConfig.setupFilesAfterEnv = [fromRoot('setupTests.js')];
}
if (hasFile('tests/setup-env.js')) {
- jestConfig.setupFilesAfterEnv = [fromRoot('tests/setup-env.js')]
+ jestConfig.setupFilesAfterEnv = [fromRoot('tests/setup-env.js')];
}
if (useBuiltInBabelConfig) {
- jestConfig.transform = {'^.+\\.js$': here('./babel-transform')}
+ jestConfig.transform = { '^.+\\.js$': here('./babel-transform') };
}
-module.exports = jestConfig
+module.exports = jestConfig;
diff --git a/src/config/lintstagedrc.js b/src/config/lintstagedrc.js
index bd5bdb4f..ba770af7 100644
--- a/src/config/lintstagedrc.js
+++ b/src/config/lintstagedrc.js
@@ -1,14 +1,22 @@
-const {resolveKcdScripts, resolveBin, isOptedOut} = require('../utils')
+const { resolveCodScripts, resolveBin, isOptedOut } = require('../utils');
-const kcdScripts = resolveKcdScripts()
-const doctoc = resolveBin('doctoc')
+const codScripts = resolveCodScripts();
+const doctoc = resolveBin('doctoc');
module.exports = {
'README.md': [`${doctoc} --maxlevel 3 --notitle`, 'git add'],
- '*.+(js|jsx|json|yml|yaml|css|less|scss|ts|tsx|md|graphql|mdx|vue)': [
- isOptedOut('autoformat', null, `${kcdScripts} format`),
- `${kcdScripts} lint`,
- `${kcdScripts} test --findRelatedTests`,
+ '*.+(json|yml|yaml|css|less|scss|graphql)': [
+ isOptedOut('autoformat', null, `${codScripts} format --no-eslint`),
isOptedOut('autoformat', null, 'git add'),
].filter(Boolean),
-}
+ '*.md': [
+ isOptedOut('autoformat', null, `${codScripts} format`),
+ // TODO: add markdownlint
+ isOptedOut('autoformat', null, 'git add'),
+ ].filter(Boolean),
+ '*.js': [
+ isOptedOut('autoformat', null, `${codScripts} lint --fix`),
+ `${codScripts} test --findRelatedTests`,
+ isOptedOut('autoformat', null, 'git add'),
+ ].filter(Boolean),
+};
diff --git a/src/config/prettierignore b/src/config/prettierignore
index 5ab667c9..7bd6773f 100644
--- a/src/config/prettierignore
+++ b/src/config/prettierignore
@@ -4,3 +4,6 @@ dist/
build/
out/
.next/
+docs/
+package-lock.json
+serviceWorker.js
diff --git a/src/config/prettierrc.js b/src/config/prettierrc.js
index 68703bc5..b61cfc01 100644
--- a/src/config/prettierrc.js
+++ b/src/config/prettierrc.js
@@ -1,10 +1,11 @@
module.exports = {
- printWidth: 80,
+ printWidth: 100,
tabWidth: 2,
useTabs: false,
- semi: false,
+ semi: true,
singleQuote: true,
trailingComma: 'all',
- bracketSpacing: false,
+ bracketSpacing: true,
jsxBracketSameLine: false,
-}
+ proseWrap: 'always',
+};
diff --git a/src/config/rollup.config.js b/src/config/rollup.config.js
index 268b5efe..bdf4b69f 100644
--- a/src/config/rollup.config.js
+++ b/src/config/rollup.config.js
@@ -1,140 +1,119 @@
-const path = require('path')
-const glob = require('glob')
-const camelcase = require('lodash.camelcase')
-const rollupBabel = require('rollup-plugin-babel')
-const commonjs = require('rollup-plugin-commonjs')
-const nodeResolve = require('rollup-plugin-node-resolve')
-const json = require('rollup-plugin-json')
-const replace = require('rollup-plugin-replace')
-const {terser} = require('rollup-plugin-terser')
-const nodeBuiltIns = require('rollup-plugin-node-builtins')
-const nodeGlobals = require('rollup-plugin-node-globals')
-const {sizeSnapshot} = require('rollup-plugin-size-snapshot')
-const omit = require('lodash.omit')
-const {
- pkg,
- hasFile,
- hasPkgProp,
- parseEnv,
- fromRoot,
- uniq,
- writeExtraEntry,
-} = require('../utils')
-
-const here = p => path.join(__dirname, p)
-const capitalize = s => s[0].toUpperCase() + s.slice(1)
-
-const minify = parseEnv('BUILD_MINIFY', false)
-const format = process.env.BUILD_FORMAT
-const isPreact = parseEnv('BUILD_PREACT', false)
-const isNode = parseEnv('BUILD_NODE', false)
-const name = process.env.BUILD_NAME || capitalize(camelcase(pkg.name))
-const useSizeSnapshot = parseEnv('BUILD_SIZE_SNAPSHOT', false)
-
-const esm = format === 'esm'
-const umd = format === 'umd'
-
-const defaultGlobals = Object.keys(pkg.peerDependencies || {}).reduce(
- (deps, dep) => {
- deps[dep] = capitalize(camelcase(dep))
- return deps
- },
- {},
-)
-
-const deps = Object.keys(pkg.dependencies || {})
-const peerDeps = Object.keys(pkg.peerDependencies || {})
-const defaultExternal = umd ? peerDeps : deps.concat(peerDeps)
-
-const input = glob.sync(fromRoot(process.env.BUILD_INPUT || 'src/index.js'))
-const codeSplitting = input.length > 1
-
-if (
- codeSplitting &&
- uniq(input.map(single => path.basename(single))).length !== input.length
-) {
+const path = require('path');
+const glob = require('glob');
+const camelcase = require('lodash.camelcase');
+const rollupBabel = require('rollup-plugin-babel');
+const commonjs = require('rollup-plugin-commonjs');
+const nodeResolve = require('rollup-plugin-node-resolve');
+const json = require('rollup-plugin-json');
+const replace = require('rollup-plugin-replace');
+const { terser } = require('rollup-plugin-terser');
+const nodeBuiltIns = require('rollup-plugin-node-builtins');
+const nodeGlobals = require('rollup-plugin-node-globals');
+const { sizeSnapshot } = require('rollup-plugin-size-snapshot');
+const omit = require('lodash.omit');
+const { pkg, hasFile, hasPkgProp, parseEnv, fromRoot, uniq, writeExtraEntry } = require('../utils');
+
+const here = p => path.join(__dirname, p);
+const capitalize = s => s[0].toUpperCase() + s.slice(1);
+
+const minify = parseEnv('BUILD_MINIFY', false);
+const format = process.env.BUILD_FORMAT;
+const isPreact = parseEnv('BUILD_PREACT', false);
+const isNode = parseEnv('BUILD_NODE', false);
+const name = process.env.BUILD_NAME || capitalize(camelcase(pkg.name));
+const useSizeSnapshot = parseEnv('BUILD_SIZE_SNAPSHOT', false);
+
+const esm = format === 'esm';
+const umd = format === 'umd';
+
+const defaultGlobals = Object.keys(pkg.peerDependencies || {}).reduce((deps, dep) => {
+ return { ...deps, [dep]: capitalize(camelcase(dep)) };
+}, {});
+
+const deps = Object.keys(pkg.dependencies || {});
+const peerDeps = Object.keys(pkg.peerDependencies || {});
+const defaultExternal = umd ? peerDeps : deps.concat(peerDeps);
+
+const input = glob.sync(fromRoot(process.env.BUILD_INPUT || 'src/index.js'));
+const codeSplitting = input.length > 1;
+
+if (codeSplitting && uniq(input.map(single => path.basename(single))).length !== input.length) {
throw new Error(
'Filenames of code-splitted entries should be unique to get deterministic output filenames.' +
`\nReceived those: ${input}.`,
- )
+ );
}
-const filenameSuffix = process.env.BUILD_FILENAME_SUFFIX || ''
-const filenamePrefix =
- process.env.BUILD_FILENAME_PREFIX || (isPreact ? 'preact/' : '')
+const filenameSuffix = process.env.BUILD_FILENAME_SUFFIX || '';
+const filenamePrefix = process.env.BUILD_FILENAME_PREFIX || (isPreact ? 'preact/' : '');
const globals = parseEnv(
'BUILD_GLOBALS',
- isPreact ? Object.assign(defaultGlobals, {preact: 'preact'}) : defaultGlobals,
-)
+ isPreact ? Object.assign(defaultGlobals, { preact: 'preact' }) : defaultGlobals,
+);
const external = parseEnv(
'BUILD_EXTERNAL',
isPreact ? defaultExternal.concat(['preact', 'prop-types']) : defaultExternal,
-).filter((e, i, arry) => arry.indexOf(e) === i)
+).filter((e, i, arry) => arry.indexOf(e) === i);
if (isPreact) {
- delete globals.react
- delete globals['prop-types'] // TODO: is this necessary?
- external.splice(external.indexOf('react'), 1)
+ delete globals.react;
+ delete globals['prop-types']; // TODO: is this necessary?
+ external.splice(external.indexOf('react'), 1);
}
-const externalPattern = new RegExp(`^(${external.join('|')})($|/)`)
+const externalPattern = new RegExp(`^(${external.join('|')})($|/)`);
function externalPredicate(id) {
- const isDep = external.length > 0 && externalPattern.test(id)
+ const isDep = external.length > 0 && externalPattern.test(id);
if (umd) {
// for UMD, we want to bundle all non-peer deps
- return isDep
+ return isDep;
}
// for esm/cjs we want to make all node_modules external
// TODO: support bundledDependencies if someone needs it ever...
- const isNodeModule = id.includes('node_modules')
- const isRelative = id.startsWith('.')
- return isDep || (!isRelative && !path.isAbsolute(id)) || isNodeModule
+ const isNodeModule = id.includes('node_modules');
+ const isRelative = id.startsWith('.');
+ return isDep || (!isRelative && !path.isAbsolute(id)) || isNodeModule;
}
-const filename = [
- pkg.name,
- filenameSuffix,
- `.${format}`,
- minify ? '.min' : null,
- '.js',
-]
+const filename = [pkg.name, filenameSuffix, `.${format}`, minify ? '.min' : null, '.js']
.filter(Boolean)
- .join('')
+ .join('');
-const dirpath = path.join(...[filenamePrefix, 'dist'].filter(Boolean))
+const dirpath = path.join(...[filenamePrefix, 'dist'].filter(Boolean));
const output = [
{
name,
...(codeSplitting
- ? {dir: path.join(dirpath, format)}
- : {file: path.join(dirpath, filename)}),
+ ? { dir: path.join(dirpath, format) }
+ : { file: path.join(dirpath, filename) }),
format: esm ? 'es' : format,
exports: esm ? 'named' : 'auto',
globals,
},
-]
+];
const useBuiltinConfig =
!hasFile('.babelrc') &&
!hasFile('.babelrc.js') &&
!hasFile('babel.config.js') &&
- !hasPkgProp('babel')
-const babelPresets = useBuiltinConfig ? [here('../config/babelrc.js')] : []
-
-const replacements = Object.entries(
- umd ? process.env : omit(process.env, ['NODE_ENV']),
-).reduce((acc, [key, value]) => {
- let val
- if (value === 'true' || value === 'false' || Number.isInteger(+value)) {
- val = value
- } else {
- val = JSON.stringify(value)
- }
- acc[`process.env.${key}`] = val
- return acc
-}, {})
+ !hasPkgProp('babel');
+const babelPresets = useBuiltinConfig ? [here('../config/babelrc.js')] : [];
+
+const replacements = Object.entries(umd ? process.env : omit(process.env, ['NODE_ENV'])).reduce(
+ (acc, [key, value]) => {
+ let val;
+ if (value === 'true' || value === 'false' || Number.isInteger(+value)) {
+ val = value;
+ } else {
+ val = JSON.stringify(value);
+ }
+ acc[`process.env.${key}`] = val;
+ return acc;
+ },
+ {},
+);
module.exports = {
input: codeSplitting ? input : input[0],
@@ -147,7 +126,7 @@ module.exports = {
preferBuiltins: isNode,
mainFields: ['module', 'main', 'jsnext', 'browser'],
}),
- commonjs({include: 'node_modules/**'}),
+ commonjs({ include: 'node_modules/**' }),
json(),
rollupBabel({
presets: babelPresets,
@@ -155,26 +134,27 @@ module.exports = {
runtimeHelpers: useBuiltinConfig,
}),
replace(replacements),
- useSizeSnapshot ? sizeSnapshot({printInfo: false}) : null,
+ useSizeSnapshot ? sizeSnapshot({ printInfo: false }) : null,
minify ? terser() : null,
codeSplitting &&
((writes = 0) => ({
onwrite() {
+ // eslint-disable-next-line
if (++writes !== input.length) {
- return
+ return;
}
input
.filter(single => single.indexOf('index.js') === -1)
.forEach(single => {
- const chunk = path.basename(single)
+ const chunk = path.basename(single);
writeExtraEntry(chunk.replace(/\..+$/, ''), {
cjs: `${dirpath}/cjs/${chunk}`,
esm: `${dirpath}/esm/${chunk}`,
- })
- })
+ });
+ });
},
}))(),
].filter(Boolean),
-}
+};
diff --git a/src/index.js b/src/index.js
index f0880373..dc17c418 100755
--- a/src/index.js
+++ b/src/index.js
@@ -1,18 +1,21 @@
#!/usr/bin/env node
-let shouldThrow
+
+let shouldThrow;
+
try {
shouldThrow =
- require(`${process.cwd()}/package.json`).name === 'kcd-scripts' &&
- Number(process.version.slice(1).split('.')[0]) < 8
+ // eslint-disable-next-line global-require,import/no-dynamic-require
+ require(`${process.cwd()}/package.json`).name === 'cod-scripts' &&
+ Number(process.version.slice(1).split('.')[0]) < 8;
} catch (error) {
// ignore
}
if (shouldThrow) {
throw new Error(
- 'You must use Node version 8 or greater to run the scripts within kcd-scripts ' +
+ 'You must use Node version 8 or greater to run the scripts within cod-scripts ' +
'because we dogfood the untranspiled version of the scripts.',
- )
+ );
}
-require('./run-script')
+require('./run-script');
diff --git a/src/run-script.js b/src/run-script.js
index d23fd17a..de8d5921 100755
--- a/src/run-script.js
+++ b/src/run-script.js
@@ -1,74 +1,17 @@
-const path = require('path')
-const spawn = require('cross-spawn')
-const glob = require('glob')
+const path = require('path');
+const spawn = require('cross-spawn');
+const glob = require('glob');
-const [executor, ignoredBin, script, ...args] = process.argv
-
-if (script) {
- spawnScript()
-} else {
- const scriptsPath = path.join(__dirname, 'scripts/')
- const scriptsAvailable = glob.sync(path.join(__dirname, 'scripts', '*'))
- // `glob.sync` returns paths with unix style path separators even on Windows.
- // So we normalize it before attempting to strip out the scripts path.
- const scriptsAvailableMessage = scriptsAvailable
- .map(path.normalize)
- .map(s =>
- s
- .replace(scriptsPath, '')
- .replace(/__tests__/, '')
- .replace(/\.js$/, ''),
- )
- .filter(Boolean)
- .join('\n ')
- .trim()
- const fullMessage = `
-Usage: ${ignoredBin} [script] [--flags]
-
-Available Scripts:
- ${scriptsAvailableMessage}
-
-Options:
- All options depend on the script. Docs will be improved eventually, but for most scripts you can assume that the args you pass will be forwarded to the respective tool that's being run under the hood.
-
-May the force be with you.
- `.trim()
- console.log(`\n${fullMessage}\n`)
-}
+const [executor, ignoredBin, script, ...args] = process.argv;
function getEnv() {
// this is required to address an issue in cross-spawn
// https://github.com/kentcdodds/kcd-scripts/issues/4
return Object.keys(process.env)
.filter(key => process.env[key] !== undefined)
- .reduce(
- (envCopy, key) => {
- envCopy[key] = process.env[key]
- return envCopy
- },
- {
- [`SCRIPTS_${script.toUpperCase()}`]: true,
- },
- )
-}
-
-function spawnScript() {
- const relativeScriptPath = path.join(__dirname, './scripts', script)
- const scriptPath = attemptResolve(relativeScriptPath)
-
- if (!scriptPath) {
- throw new Error(`Unknown script "${script}".`)
- }
- const result = spawn.sync(executor, [scriptPath, ...args], {
- stdio: 'inherit',
- env: getEnv(),
- })
-
- if (result.signal) {
- handleSignal(result)
- } else {
- process.exit(result.status)
- }
+ .reduce((envCopy, key) => ({ ...envCopy, [key]: process.env[key] }), {
+ [`SCRIPTS_${script.toUpperCase()}`]: true,
+ });
}
function handleSignal(result) {
@@ -77,21 +20,72 @@ function handleSignal(result) {
`The script "${script}" failed because the process exited too early. ` +
'This probably means the system ran out of memory or someone called ' +
'`kill -9` on the process.',
- )
+ );
} else if (result.signal === 'SIGTERM') {
console.log(
`The script "${script}" failed because the process exited too early. ` +
'Someone might have called `kill` or `killall`, or the system could ' +
'be shutting down.',
- )
+ );
}
- process.exit(1)
+ process.exit(1);
}
function attemptResolve(...resolveArgs) {
try {
- return require.resolve(...resolveArgs)
+ return require.resolve(...resolveArgs);
} catch (error) {
- return null
+ return null;
+ }
+}
+
+function spawnScript() {
+ const relativeScriptPath = path.join(__dirname, './scripts', script);
+ const scriptPath = attemptResolve(relativeScriptPath);
+
+ if (!scriptPath) {
+ throw new Error(`Unknown script "${script}".`);
+ }
+ const result = spawn.sync(executor, [scriptPath, ...args], {
+ stdio: 'inherit',
+ env: getEnv(),
+ });
+
+ if (result.signal) {
+ handleSignal(result);
+ } else {
+ process.exit(result.status);
}
}
+
+if (script) {
+ spawnScript();
+} else {
+ const scriptsPath = path.join(__dirname, 'scripts/');
+ const scriptsAvailable = glob.sync(path.join(__dirname, 'scripts', '*'));
+ // `glob.sync` returns paths with unix style path separators even on Windows.
+ // So we normalize it before attempting to strip out the scripts path.
+ const scriptsAvailableMessage = scriptsAvailable
+ .map(path.normalize)
+ .map(s =>
+ s
+ .replace(scriptsPath, '')
+ .replace(/__tests__/, '')
+ .replace(/\.js$/, ''),
+ )
+ .filter(Boolean)
+ .join('\n ')
+ .trim();
+ const fullMessage = `
+Usage: ${ignoredBin} [script] [--flags]
+
+Available Scripts:
+ ${scriptsAvailableMessage}
+
+Options:
+ All options depend on the script. Docs will be improved eventually, but for most scripts you can assume that the args you pass will be forwarded to the respective tool that's being run under the hood.
+
+May the force be with you.
+ `.trim();
+ console.log(`\n${fullMessage}\n`);
+}
diff --git a/src/scripts/__tests__/__snapshots__/format.js.snap b/src/scripts/__tests__/__snapshots__/format.js.snap
index e24746ef..4a54fbd0 100644
--- a/src/scripts/__tests__/__snapshots__/format.js.snap
+++ b/src/scripts/__tests__/__snapshots__/format.js.snap
@@ -1,9 +1,17 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
-exports[`format --config arg can be used for a custom config 1`] = `prettier --write **/*.+(js|json|less|css|ts|tsx|md) --config ./my-config.js`;
+exports[`format --config arg can be used for a custom config 1`] = `prettier --ignore-path ./src/config/prettierignore --write **/*.+(json|less|css|ts|tsx|md) --config ./my-config.js`;
-exports[`format --ignore-path arg can be used for a custom ignore file 1`] = `prettier --write **/*.+(js|json|less|css|ts|tsx|md) --ignore-path ./.myignore`;
+exports[`format --config arg can be used for a custom config 2`] = `prettier --ignore-path ./src/config/prettierignore --write **/*.+(json|less|css|ts|tsx|md) --config ./my-config.js`;
-exports[`format --no-write prevents --write argument from being added 1`] = `prettier **/*.+(js|json|less|css|ts|tsx|md) --no-write`;
+exports[`format --ignore-path arg can be used for a custom ignore file 1`] = `prettier --config ./src/config/prettierrc.js --write **/*.+(json|less|css|ts|tsx|md) --ignore-path ./.myignore`;
-exports[`format calls prettier CLI with args 1`] = `prettier --write my-src/**/*.js`;
+exports[`format --ignore-path arg can be used for a custom ignore file 2`] = `prettier --config ./src/config/prettierrc.js --write **/*.+(json|less|css|ts|tsx|md) --ignore-path ./.myignore`;
+
+exports[`format --no-write prevents --write argument from being added 1`] = `prettier --config ./src/config/prettierrc.js --ignore-path ./src/config/prettierignore **/*.+(json|less|css|ts|tsx|md) --no-write`;
+
+exports[`format --no-write prevents --write argument from being added 2`] = `prettier --config ./src/config/prettierrc.js --ignore-path ./src/config/prettierignore **/*.+(json|less|css|ts|tsx|md) --no-write`;
+
+exports[`format calls prettier CLI with args 1`] = `prettier --config ./src/config/prettierrc.js --ignore-path ./src/config/prettierignore --write my-src/**/*.js`;
+
+exports[`format calls prettier CLI with args 2`] = `prettier --config ./src/config/prettierrc.js --ignore-path ./src/config/prettierignore --write my-src/**/*.js`;
diff --git a/src/scripts/__tests__/__snapshots__/precommit.js.snap b/src/scripts/__tests__/__snapshots__/pre-commit.js.snap
similarity index 100%
rename from src/scripts/__tests__/__snapshots__/precommit.js.snap
rename to src/scripts/__tests__/__snapshots__/pre-commit.js.snap
diff --git a/src/scripts/__tests__/__snapshots__/travis-after-success.js.snap b/src/scripts/__tests__/__snapshots__/travis-after-success.js.snap
deleted file mode 100644
index 45c0eb21..00000000
--- a/src/scripts/__tests__/__snapshots__/travis-after-success.js.snap
+++ /dev/null
@@ -1,32 +0,0 @@
-// Jest Snapshot v1, https://goo.gl/fbAQLP
-
-exports[`travis-after-success calls concurrently with both scripts when on travis 1`] = `npx travis-deploy-once@5`;
-
-exports[`travis-after-success calls concurrently with both scripts when on travis 2`] = `concurrently --prefix [{name}] --names codecov,release --prefix-colors bgBlue.bold.reset,bgGreen.bold.reset "echo installing codecov && npx -p codecov@3 -c 'echo running codecov && codecov'" "echo installing semantic-release && npx -p semantic-release@15 -c 'echo running semantic-release && semantic-release'"`;
-
-exports[`travis-after-success does not do autorelease script when running on travis but in a pull request 1`] = `npx travis-deploy-once@5`;
-
-exports[`travis-after-success does not do autorelease script when running on travis but in a pull request 2`] = `concurrently --prefix [{name}] --names codecov --prefix-colors bgBlue.bold.reset "echo installing codecov && npx -p codecov@3 -c 'echo running codecov && codecov'"`;
-
-exports[`travis-after-success does not do the autorelease script when the version is different 1`] = `npx travis-deploy-once@5`;
-
-exports[`travis-after-success does not do the autorelease script when the version is different 2`] = `concurrently --prefix [{name}] --names codecov --prefix-colors bgBlue.bold.reset "echo installing codecov && npx -p codecov@3 -c 'echo running codecov && codecov'"`;
-
-exports[`travis-after-success does not do the codecov script when opted out 1`] = `npx travis-deploy-once@5`;
-
-exports[`travis-after-success does not do the codecov script when opted out 2`] = `concurrently --prefix [{name}] --names release --prefix-colors bgBlue.bold.reset "echo installing semantic-release && npx -p semantic-release@15 -c 'echo running semantic-release && semantic-release'"`;
-
-exports[`travis-after-success does not do the codecov script when there is no coverage directory 1`] = `npx travis-deploy-once@5`;
-
-exports[`travis-after-success does not do the codecov script when there is no coverage directory 2`] = `concurrently --prefix [{name}] --names release --prefix-colors bgBlue.bold.reset "echo installing semantic-release && npx -p semantic-release@15 -c 'echo running semantic-release && semantic-release'"`;
-
-exports[`travis-after-success does not run either script when no coverage dir and not the right version 1`] = `
-Array [
- Array [
- installing and running travis-deploy-once,
- ],
- Array [
- No need to autorelease or report coverage. Skipping travis-after-success script...,
- ],
-]
-`;
diff --git a/src/scripts/__tests__/format.js b/src/scripts/__tests__/format.js
index ec798516..d796bcae 100644
--- a/src/scripts/__tests__/format.js
+++ b/src/scripts/__tests__/format.js
@@ -1,32 +1,35 @@
-import cases from 'jest-in-case'
-import {unquoteSerializer, winPathSerializer} from './helpers/serializers'
+import cases from 'jest-in-case';
+import { unquoteSerializer, winPathSerializer } from './helpers/serializers';
-expect.addSnapshotSerializer(unquoteSerializer)
-expect.addSnapshotSerializer(winPathSerializer)
+expect.addSnapshotSerializer(unquoteSerializer);
+expect.addSnapshotSerializer(winPathSerializer);
cases(
'format',
- ({args}) => {
+ ({ args }) => {
// beforeEach
- const {sync: crossSpawnSyncMock} = require('cross-spawn')
- const originalExit = process.exit
- const originalArgv = process.argv
- const utils = require('../../utils')
- utils.resolveBin = (modName, {executable = modName} = {}) => executable
- process.exit = jest.fn()
+ const { sync: crossSpawnSyncMock } = require('cross-spawn');
+ const originalExit = process.exit;
+ const originalArgv = process.argv;
+ const utils = require('../../utils');
+ utils.resolveBin = (modName, { executable = modName } = {}) => executable;
+ process.exit = jest.fn();
// tests
- process.argv = ['node', '../format', ...args]
- require('../format')
- expect(crossSpawnSyncMock).toHaveBeenCalledTimes(1)
- const [firstCall] = crossSpawnSyncMock.mock.calls
- const [script, calledArgs] = firstCall
- expect([script, ...calledArgs].join(' ')).toMatchSnapshot()
+ process.argv = ['node', '../format', ...args];
+ require('../format');
+ expect(crossSpawnSyncMock).toHaveBeenCalledTimes(2);
+ const [firstCall] = crossSpawnSyncMock.mock.calls;
+ const [script, calledArgs] = firstCall;
+ expect([script, ...calledArgs].join(' ')).toMatchSnapshot();
+ const [secondCall] = crossSpawnSyncMock.mock.calls;
+ const [secondScript, secondCalledArgs] = secondCall;
+ expect([secondScript, ...secondCalledArgs].join(' ')).toMatchSnapshot();
// afterEach
- process.exit = originalExit
- process.argv = originalArgv
- jest.resetModules()
+ process.exit = originalExit;
+ process.argv = originalArgv;
+ jest.resetModules();
},
{
'calls prettier CLI with args': {
@@ -42,4 +45,4 @@ cases(
args: ['--ignore-path', './.myignore'],
},
},
-)
+);
diff --git a/src/scripts/__tests__/helpers/serializers.js b/src/scripts/__tests__/helpers/serializers.js
index 683d9dee..baede0a5 100644
--- a/src/scripts/__tests__/helpers/serializers.js
+++ b/src/scripts/__tests__/helpers/serializers.js
@@ -1,25 +1,25 @@
-import slash from 'slash'
+import slash from 'slash';
// this removes the quotes around strings...
export const unquoteSerializer = {
print: val => val,
test: val => typeof val === 'string',
-}
+};
// this converts windows style file paths to unix...
export const winPathSerializer = {
print: val => slash(val),
test: val => typeof val === 'string' && val.includes('\\'),
-}
-
-export const relativePathSerializer = {
- print: val => normalizePaths(val),
- test: val => normalizePaths(val) !== val,
-}
+};
function normalizePaths(value) {
if (typeof value !== 'string') {
- return value
+ return value;
}
- return slash(value.split(process.cwd()).join(''))
+ return slash(value.split(process.cwd()).join(''));
}
+
+export const relativePathSerializer = {
+ print: val => normalizePaths(val),
+ test: val => normalizePaths(val) !== val,
+};
diff --git a/src/scripts/__tests__/lint.js b/src/scripts/__tests__/lint.js
index 6f6022e2..c347a605 100644
--- a/src/scripts/__tests__/lint.js
+++ b/src/scripts/__tests__/lint.js
@@ -1,13 +1,13 @@
-import cases from 'jest-in-case'
+import cases from 'jest-in-case';
import {
unquoteSerializer,
winPathSerializer,
relativePathSerializer,
-} from './helpers/serializers'
+} from './helpers/serializers';
-expect.addSnapshotSerializer(unquoteSerializer)
-expect.addSnapshotSerializer(winPathSerializer)
-expect.addSnapshotSerializer(relativePathSerializer)
+expect.addSnapshotSerializer(unquoteSerializer);
+expect.addSnapshotSerializer(winPathSerializer);
+expect.addSnapshotSerializer(relativePathSerializer);
cases(
'lint',
@@ -19,34 +19,34 @@ cases(
setup = () => () => {},
}) => {
// beforeEach
- const {sync: crossSpawnSyncMock} = require('cross-spawn')
- const originalArgv = process.argv
- const originalExit = process.exit
+ const { sync: crossSpawnSyncMock } = require('cross-spawn');
+ const originalArgv = process.argv;
+ const originalExit = process.exit;
Object.assign(utils, {
hasPkgProp,
hasFile,
- resolveBin: (modName, {executable = modName} = {}) => executable,
- })
- process.exit = jest.fn()
- const teardown = setup()
+ resolveBin: (modName, { executable = modName } = {}) => executable,
+ });
+ process.exit = jest.fn();
+ const teardown = setup();
- process.argv = ['node', '../lint', ...args]
+ process.argv = ['node', '../lint', ...args];
try {
// tests
- require('../lint')
- expect(crossSpawnSyncMock).toHaveBeenCalledTimes(1)
- const [firstCall] = crossSpawnSyncMock.mock.calls
- const [script, calledArgs] = firstCall
- expect([script, ...calledArgs].join(' ')).toMatchSnapshot()
+ require('../lint');
+ expect(crossSpawnSyncMock).toHaveBeenCalledTimes(1);
+ const [firstCall] = crossSpawnSyncMock.mock.calls;
+ const [script, calledArgs] = firstCall;
+ expect([script, ...calledArgs].join(' ')).toMatchSnapshot();
} catch (error) {
- throw error
+ throw error;
} finally {
- teardown()
+ teardown();
// afterEach
- process.exit = originalExit
- process.argv = originalArgv
- jest.resetModules()
+ process.exit = originalExit;
+ process.argv = originalArgv;
+ jest.resetModules();
}
},
{
@@ -76,12 +76,7 @@ cases(
args: ['--no-cache'],
},
'runs on given files, but only js files': {
- args: [
- './src/index.js',
- './package.json',
- './src/index.css',
- './src/component.js',
- ],
+ args: ['./src/index.js', './package.json', './src/index.css', './src/component.js'],
},
},
-)
+);
diff --git a/src/scripts/__tests__/precommit.js b/src/scripts/__tests__/pre-commit.js
similarity index 54%
rename from src/scripts/__tests__/precommit.js
rename to src/scripts/__tests__/pre-commit.js
index d6107362..328f48d9 100644
--- a/src/scripts/__tests__/precommit.js
+++ b/src/scripts/__tests__/pre-commit.js
@@ -1,8 +1,8 @@
-import cases from 'jest-in-case'
-import {unquoteSerializer, winPathSerializer} from './helpers/serializers'
+import cases from 'jest-in-case';
+import { unquoteSerializer, winPathSerializer } from './helpers/serializers';
-expect.addSnapshotSerializer(unquoteSerializer)
-expect.addSnapshotSerializer(winPathSerializer)
+expect.addSnapshotSerializer(unquoteSerializer);
+expect.addSnapshotSerializer(winPathSerializer);
cases(
'pre-commit',
@@ -13,35 +13,35 @@ cases(
hasFile = () => false,
}) => {
// beforeEach
- const {sync: crossSpawnSyncMock} = require('cross-spawn')
- const originalArgv = process.argv
- const originalExit = process.exit
+ const { sync: crossSpawnSyncMock } = require('cross-spawn');
+ const originalArgv = process.argv;
+ const originalExit = process.exit;
Object.assign(utils, {
hasPkgProp,
hasFile,
- resolveBin: (modName, {executable = modName} = {}) => executable,
- })
- process.exit = jest.fn()
+ resolveBin: (modName, { executable = modName } = {}) => executable,
+ });
+ process.exit = jest.fn();
- process.argv = ['node', '../pre-commit', ...args]
- utils.isOptedIn = optIn => optIn === 'pre-commit'
+ process.argv = ['node', '../pre-commit', ...args];
+ utils.isOptedIn = optIn => optIn === 'pre-commit'; // eslint-disable-line
try {
// tests
- require('../pre-commit')
- expect(crossSpawnSyncMock).toHaveBeenCalledTimes(2)
- const [firstCall, secondCall] = crossSpawnSyncMock.mock.calls
- const [scriptOne, calledArgsOne] = firstCall
- expect([scriptOne, ...calledArgsOne].join(' ')).toMatchSnapshot()
- const [scriptTwo, calledArgsTwo] = secondCall
- expect([scriptTwo, ...calledArgsTwo].join(' ')).toMatchSnapshot()
+ require('../pre-commit');
+ expect(crossSpawnSyncMock).toHaveBeenCalledTimes(2);
+ const [firstCall, secondCall] = crossSpawnSyncMock.mock.calls;
+ const [scriptOne, calledArgsOne] = firstCall;
+ expect([scriptOne, ...calledArgsOne].join(' ')).toMatchSnapshot();
+ const [scriptTwo, calledArgsTwo] = secondCall;
+ expect([scriptTwo, ...calledArgsTwo].join(' ')).toMatchSnapshot();
} catch (error) {
- throw error
+ throw error;
} finally {
// afterEach
- process.exit = originalExit
- process.argv = originalArgv
- jest.resetModules()
+ process.exit = originalExit;
+ process.argv = originalArgv;
+ jest.resetModules();
}
},
{
@@ -62,4 +62,4 @@ cases(
args: ['--verbose'],
},
},
-)
+);
diff --git a/src/scripts/__tests__/test.js b/src/scripts/__tests__/test.js
index 3069a317..c8add504 100644
--- a/src/scripts/__tests__/test.js
+++ b/src/scripts/__tests__/test.js
@@ -1,12 +1,12 @@
-import cases from 'jest-in-case'
-import {unquoteSerializer} from './helpers/serializers'
+import cases from 'jest-in-case';
+import { unquoteSerializer } from './helpers/serializers';
-jest.mock('jest', () => ({run: jest.fn()}))
-jest.mock('../../config/jest.config', () => ({builtInConfig: true}))
-let mockIsCI = false
-jest.mock('is-ci', () => mockIsCI)
+jest.mock('jest', () => ({ run: jest.fn() }));
+jest.mock('../../config/jest.config', () => ({ builtInConfig: true }));
+let mockIsCI = false;
+jest.mock('is-ci', () => mockIsCI);
-expect.addSnapshotSerializer(unquoteSerializer)
+expect.addSnapshotSerializer(unquoteSerializer);
cases(
'test',
@@ -21,37 +21,37 @@ cases(
}) => {
// beforeEach
// eslint-disable-next-line jest/no-jest-import
- const {run: jestRunMock} = require('jest')
- const originalArgv = process.argv
- const prevCI = mockIsCI
- const prevPreCommit = process.env['SCRIPTS_PRE-COMMIT']
- mockIsCI = ci
- process.env['SCRIPTS_PRE-COMMIT'] = preCommit
+ const { run: jestRunMock } = require('jest');
+ const originalArgv = process.argv;
+ const prevCI = mockIsCI;
+ const prevPreCommit = process.env['SCRIPTS_PRE-COMMIT'];
+ mockIsCI = ci;
+ process.env['SCRIPTS_PRE-COMMIT'] = preCommit;
Object.assign(utils, {
hasPkgProp: () => pkgHasJestProp,
hasFile: () => hasJestConfigFile,
- })
- process.exit = jest.fn()
- const teardown = setup()
+ });
+ process.exit = jest.fn();
+ const teardown = setup();
- process.argv = ['node', '../test', ...args]
+ process.argv = ['node', '../test', ...args];
try {
// tests
- require('../test')
- expect(jestRunMock).toHaveBeenCalledTimes(1)
- const [firstCall] = jestRunMock.mock.calls
- const [jestArgs] = firstCall
- expect(jestArgs.join(' ')).toMatchSnapshot()
+ require('../test');
+ expect(jestRunMock).toHaveBeenCalledTimes(1);
+ const [firstCall] = jestRunMock.mock.calls;
+ const [jestArgs] = firstCall;
+ expect(jestArgs.join(' ')).toMatchSnapshot();
} catch (error) {
- throw error
+ throw error;
} finally {
- teardown()
+ teardown();
// afterEach
- process.argv = originalArgv
- mockIsCI = prevCI
- process.env['SCRIPTS_PRE-COMMIT'] = prevPreCommit
- jest.resetModules()
+ process.argv = originalArgv;
+ mockIsCI = prevCI;
+ process.env['SCRIPTS_PRE-COMMIT'] = prevPreCommit;
+ jest.resetModules();
}
},
{
@@ -84,4 +84,4 @@ cases(
args: ['--coverage', '--watch'],
},
},
-)
+);
diff --git a/src/scripts/__tests__/travis-after-success.js b/src/scripts/__tests__/travis-after-success.js
deleted file mode 100644
index fecd5569..00000000
--- a/src/scripts/__tests__/travis-after-success.js
+++ /dev/null
@@ -1,83 +0,0 @@
-import cases from 'jest-in-case'
-import {unquoteSerializer} from './helpers/serializers'
-
-expect.addSnapshotSerializer(unquoteSerializer)
-
-cases(
- 'travis-after-success',
- ({
- version = '0.0.0-semantically-released',
- hasCoverageDir = true,
- isOptedOutOfCoverage = false,
- env = {
- TRAVIS: 'true',
- TRAVIS_BRANCH: 'master',
- TRAVIS_PULL_REQUEST: 'false',
- },
- runsNothing = false,
- }) => {
- // beforeEach
- const {sync: crossSpawnSyncMock} = require('cross-spawn')
- const utils = require('../../utils')
- utils.resolveBin = (modName, {executable = modName} = {}) => executable
- const originalEnvs = Object.keys(env).map(envKey => {
- const orig = process.env[envKey]
- process.env[envKey] = env[envKey]
- return orig
- })
- const originalLog = console.log
- const originalExit = process.exit
- process.exit = jest.fn()
- console.log = jest.fn()
-
- // tests
- if (version) {
- utils.pkg.version = version
- }
- utils.hasFile = () => hasCoverageDir
- process.env.SKIP_CODECOV = isOptedOutOfCoverage
- require('../travis-after-success')
- if (runsNothing) {
- expect(console.log.mock.calls).toMatchSnapshot()
- } else {
- expect(crossSpawnSyncMock).toHaveBeenCalledTimes(2)
- const [firstCall, secondCall] = crossSpawnSyncMock.mock.calls
- const [scriptOne, calledArgsOne] = firstCall
- expect([scriptOne, ...calledArgsOne].join(' ')).toMatchSnapshot()
- const [scriptTwo, calledArgsTwo] = secondCall
- expect([scriptTwo, ...calledArgsTwo].join(' ')).toMatchSnapshot()
- }
-
- // afterEach
- process.exit = originalExit
- console.log = originalLog
- Object.keys(originalEnvs).forEach(envKey => {
- process.env[envKey] = env[envKey]
- })
- jest.resetModules()
- },
- {
- 'calls concurrently with both scripts when on travis': {},
- 'does not do the autorelease script when the version is different': {
- version: '1.2.3',
- },
- 'does not do the codecov script when there is no coverage directory': {
- hasCoverageDir: false,
- },
- 'does not do the codecov script when opted out': {
- isOptedOutOfCoverage: true,
- },
- 'does not do autorelease script when running on travis but in a pull request': {
- env: {
- TRAVIS: 'true',
- TRAVIS_BRANCH: 'master',
- TRAVIS_PULL_REQUEST: 'true',
- },
- },
- 'does not run either script when no coverage dir and not the right version': {
- runsNothing: true,
- hasCoverageDir: false,
- version: '1.2.3',
- },
- },
-)
diff --git a/src/scripts/__tests__/validate.js b/src/scripts/__tests__/validate.js
index f5435fe5..52727382 100644
--- a/src/scripts/__tests__/validate.js
+++ b/src/scripts/__tests__/validate.js
@@ -1,34 +1,74 @@
-import cases from 'jest-in-case'
-import {unquoteSerializer} from './helpers/serializers'
+import cases from 'jest-in-case';
+import { unquoteSerializer } from './helpers/serializers';
-expect.addSnapshotSerializer(unquoteSerializer)
+expect.addSnapshotSerializer(unquoteSerializer);
+
+function setupWithScripts(scripts = ['test', 'lint', 'build', 'flow']) {
+ return function setup() {
+ const utils = require('../../utils');
+ const originalIfScript = utils.ifScript;
+ utils.ifScript = (script, t, f) => (scripts.includes(script) ? t : f);
+ return function teardown() {
+ utils.ifScript = originalIfScript;
+ };
+ };
+}
+
+function setupWithArgs(args = []) {
+ return function setup() {
+ const utils = require('../../utils');
+ const originalResolveBin = utils.resolveBin;
+ utils.resolveBin = (modName, { executable = modName } = {}) => executable;
+ const originalArgv = process.argv;
+ process.argv = ['node', '../format', ...args];
+ return function teardown() {
+ process.argv = originalArgv;
+ utils.resolveBin = originalResolveBin;
+ };
+ };
+}
+
+function withDefaultSetup(setupFn) {
+ return function defaultSetup() {
+ const utils = require('../../utils');
+ utils.resolveBin = (modName, { executable = modName } = {}) => executable;
+ const argsTeardown = setupWithArgs()();
+ const teardownScripts = setupWithScripts()();
+ const teardownFn = setupFn();
+ return function defaultTeardown() {
+ argsTeardown();
+ teardownFn();
+ teardownScripts();
+ };
+ };
+}
cases(
'validate',
- ({setup = () => () => {}}) => {
+ ({ setup = () => () => {} }) => {
// beforeEach
- const {sync: crossSpawnSyncMock} = require('cross-spawn')
- const originalExit = process.exit
- process.exit = jest.fn()
- process.env['SCRIPTS_PRE-COMMIT'] = 'false'
- const teardown = setup()
+ const { sync: crossSpawnSyncMock } = require('cross-spawn');
+ const originalExit = process.exit;
+ process.exit = jest.fn();
+ process.env['SCRIPTS_PRE-COMMIT'] = 'false';
+ const teardown = setup();
try {
// tests
- require('../validate')
- expect(crossSpawnSyncMock).toHaveBeenCalledTimes(1)
- const [firstCall] = crossSpawnSyncMock.mock.calls
- const [script, calledArgs] = firstCall
- expect([script, ...calledArgs].join(' ')).toMatchSnapshot()
+ require('../validate');
+ expect(crossSpawnSyncMock).toHaveBeenCalledTimes(1);
+ const [firstCall] = crossSpawnSyncMock.mock.calls;
+ const [script, calledArgs] = firstCall;
+ expect([script, ...calledArgs].join(' ')).toMatchSnapshot();
} catch (error) {
- throw error
+ throw error;
} finally {
- teardown()
+ teardown();
}
// afterEach
- process.exit = originalExit
- jest.resetModules()
+ process.exit = originalExit;
+ jest.resetModules();
},
{
'calls concurrently with all scripts': {
@@ -51,52 +91,12 @@ cases(
},
[`doesn't use test or lint if it's in pre-commit`]: {
setup: withDefaultSetup(() => {
- const previousVal = process.env['SCRIPTS_PRE-COMMIT']
- process.env['SCRIPTS_PRE-COMMIT'] = 'true'
+ const previousVal = process.env['SCRIPTS_PRE-COMMIT'];
+ process.env['SCRIPTS_PRE-COMMIT'] = 'true';
return function teardown() {
- process.env['SCRIPTS_PRE-COMMIT'] = previousVal
- }
+ process.env['SCRIPTS_PRE-COMMIT'] = previousVal;
+ };
}),
},
},
-)
-
-function setupWithScripts(scripts = ['test', 'lint', 'build', 'flow']) {
- return function setup() {
- const utils = require('../../utils')
- const originalIfScript = utils.ifScript
- utils.ifScript = (script, t, f) => (scripts.includes(script) ? t : f)
- return function teardown() {
- utils.ifScript = originalIfScript
- }
- }
-}
-
-function setupWithArgs(args = []) {
- return function setup() {
- const utils = require('../../utils')
- const originalResolveBin = utils.resolveBin
- utils.resolveBin = (modName, {executable = modName} = {}) => executable
- const originalArgv = process.argv
- process.argv = ['node', '../format', ...args]
- return function teardown() {
- process.argv = originalArgv
- utils.resolveBin = originalResolveBin
- }
- }
-}
-
-function withDefaultSetup(setupFn) {
- return function defaultSetup() {
- const utils = require('../../utils')
- utils.resolveBin = (modName, {executable = modName} = {}) => executable
- const argsTeardown = setupWithArgs()()
- const teardownScripts = setupWithScripts()()
- const teardownFn = setupFn()
- return function defaultTeardown() {
- argsTeardown()
- teardownFn()
- teardownScripts()
- }
- }
-}
+);
diff --git a/src/scripts/build/babel.js b/src/scripts/build/babel.js
index 40249d9d..179da1a3 100644
--- a/src/scripts/build/babel.js
+++ b/src/scripts/build/babel.js
@@ -1,56 +1,51 @@
-const path = require('path')
-const spawn = require('cross-spawn')
-const yargsParser = require('yargs-parser')
-const rimraf = require('rimraf')
-const glob = require('glob')
-const {hasPkgProp, fromRoot, resolveBin, hasFile} = require('../../utils')
+const path = require('path');
+const spawn = require('cross-spawn');
+const yargsParser = require('yargs-parser');
+const rimraf = require('rimraf');
+const glob = require('glob');
+const { hasPkgProp, fromRoot, resolveBin, hasFile } = require('../../utils');
-const args = process.argv.slice(2)
-const here = p => path.join(__dirname, p)
+const args = process.argv.slice(2);
+const here = p => path.join(__dirname, p);
-const parsedArgs = yargsParser(args)
+const parsedArgs = yargsParser(args);
const useBuiltinConfig =
!args.includes('--presets') &&
!hasFile('.babelrc') &&
!hasFile('.babelrc.js') &&
!hasFile('babel.config.js') &&
- !hasPkgProp('babel')
-const config = useBuiltinConfig
- ? ['--presets', here('../../config/babelrc.js')]
- : []
+ !hasPkgProp('babel');
+const config = useBuiltinConfig ? ['--presets', here('../../config/babelrc.js')] : [];
-const builtInIgnore = '**/__tests__/**,**/__mocks__/**'
+const builtInIgnore = '**/__tests__/**,**/__mocks__/**';
-const ignore = args.includes('--ignore') ? [] : ['--ignore', builtInIgnore]
+const ignore = args.includes('--ignore') ? [] : ['--ignore', builtInIgnore];
-const copyFiles = args.includes('--no-copy-files') ? [] : ['--copy-files']
+const copyFiles = args.includes('--no-copy-files') ? [] : ['--copy-files'];
-const useSpecifiedOutDir = args.includes('--out-dir')
-const builtInOutDir = 'dist'
-const outDir = useSpecifiedOutDir ? [] : ['--out-dir', builtInOutDir]
+const useSpecifiedOutDir = args.includes('--out-dir') || args.includes('-d');
+const builtInOutDir = 'dist';
+const outDir = useSpecifiedOutDir ? [] : ['--out-dir', builtInOutDir];
if (!useSpecifiedOutDir && !args.includes('--no-clean')) {
- rimraf.sync(fromRoot('dist'))
+ rimraf.sync(fromRoot('dist'));
}
const result = spawn.sync(
- resolveBin('@babel/cli', {executable: 'babel'}),
+ resolveBin('@babel/cli', { executable: 'babel' }),
[...outDir, ...copyFiles, ...ignore, ...config, 'src'].concat(args),
- {stdio: 'inherit'},
-)
+ { stdio: 'inherit' },
+);
// because babel will copy even ignored files, we need to remove the ignored files
-const pathToOutDir = fromRoot(parsedArgs.outDir || builtInOutDir)
+const pathToOutDir = fromRoot(parsedArgs.outDir || builtInOutDir);
const ignoredPatterns = (parsedArgs.ignore || builtInIgnore)
.split(',')
- .map(pattern => path.join(pathToOutDir, pattern))
-const ignoredFiles = ignoredPatterns.reduce(
- (all, pattern) => [...all, ...glob.sync(pattern)],
- [],
-)
+ .map(pattern => path.join(pathToOutDir, pattern));
+const ignoredFiles = ignoredPatterns.reduce((all, pattern) => [...all, ...glob.sync(pattern)], []);
ignoredFiles.forEach(ignoredFile => {
- rimraf.sync(ignoredFile)
-})
+ rimraf.sync(ignoredFile);
+});
-process.exit(result.status)
+process.exit(result.status);
diff --git a/src/scripts/build/index.js b/src/scripts/build/index.js
index 9b96498f..f3f380db 100644
--- a/src/scripts/build/index.js
+++ b/src/scripts/build/index.js
@@ -1,9 +1,9 @@
if (process.argv.includes('--browser')) {
- console.error('--browser has been deprecated, use --bundle instead')
+ console.error('--browser has been deprecated, use --bundle instead');
}
-if (process.argv.includes('--bundle') || process.argv.includes('--browser')) {
- require('./rollup')
+if (process.argv.includes('--bundle')) {
+ require('./rollup');
} else {
- require('./babel')
+ require('./babel');
}
diff --git a/src/scripts/build/rollup.js b/src/scripts/build/rollup.js
index 62269b34..29617dcb 100644
--- a/src/scripts/build/rollup.js
+++ b/src/scripts/build/rollup.js
@@ -1,68 +1,101 @@
-const path = require('path')
-const spawn = require('cross-spawn')
-const glob = require('glob')
-const rimraf = require('rimraf')
-const yargsParser = require('yargs-parser')
+const path = require('path');
+const spawn = require('cross-spawn');
+const glob = require('glob');
+const rimraf = require('rimraf');
+const yargsParser = require('yargs-parser');
const {
hasFile,
resolveBin,
fromRoot,
getConcurrentlyArgs,
writeExtraEntry,
-} = require('../../utils')
+} = require('../../utils');
-const crossEnv = resolveBin('cross-env')
-const rollup = resolveBin('rollup')
-const args = process.argv.slice(2)
-const here = p => path.join(__dirname, p)
-const hereRelative = p => here(p).replace(process.cwd(), '.')
-const parsedArgs = yargsParser(args)
+const crossEnv = resolveBin('cross-env');
+const rollup = resolveBin('rollup');
+const args = process.argv.slice(2);
+const here = p => path.join(__dirname, p);
+const hereRelative = p => here(p).replace(process.cwd(), '.');
+const parsedArgs = yargsParser(args);
-const useBuiltinConfig =
- !args.includes('--config') && !hasFile('rollup.config.js')
+const useBuiltinConfig = !args.includes('--config') && !hasFile('rollup.config.js');
+// eslint-disable-next-line
const config = useBuiltinConfig
? `--config ${hereRelative('../../config/rollup.config.js')}`
: args.includes('--config')
? ''
- : '--config' // --config will pick up the rollup.config.js file
+ : '--config'; // --config will pick up the rollup.config.js file
-const environment = parsedArgs.environment
- ? `--environment ${parsedArgs.environment}`
- : ''
-const watch = parsedArgs.watch ? '--watch' : ''
-const sizeSnapshot = parsedArgs['size-snapshot']
+const environment = parsedArgs.environment ? `--environment ${parsedArgs.environment}` : '';
+const watch = parsedArgs.watch ? '--watch' : '';
+const sizeSnapshot = parsedArgs['size-snapshot'];
-let formats = ['esm', 'cjs', 'umd', 'umd.min']
+let formats = ['esm', 'cjs', 'umd', 'umd.min'];
if (typeof parsedArgs.bundle === 'string') {
- formats = parsedArgs.bundle.split(',')
+ formats = parsedArgs.bundle.split(',');
}
-const defaultEnv = 'BUILD_ROLLUP=true'
+const defaultEnv = 'BUILD_ROLLUP=true';
+
+function prefixKeys(prefix, object) {
+ return Object.entries(object).reduce((cmds, [key, value]) => {
+ return { ...cmds, [`${prefix}${key}`]: value };
+ }, {});
+}
const getCommand = (env, ...flags) =>
[crossEnv, defaultEnv, env, rollup, config, environment, watch, ...flags]
.filter(Boolean)
- .join(' ')
+ .join(' ');
+
+function getCommands({ preact = false } = {}) {
+ return formats.reduce((cmds, format) => {
+ const [formatName, minify = false] = format.split('.');
+ const nodeEnv = minify ? 'production' : 'development';
+ const sourceMap = formatName === 'umd' ? '--sourcemap' : '';
+ const buildMinify = Boolean(minify);
+
+ return {
+ ...cmds,
+ [format]: getCommand(
+ [
+ `BUILD_FORMAT=${formatName}`,
+ `BUILD_MINIFY=${buildMinify}`,
+ `NODE_ENV=${nodeEnv}`,
+ `BUILD_PREACT=${preact}`,
+ `BUILD_SIZE_SNAPSHOT=${sizeSnapshot}`,
+ `BUILD_NODE=${process.env.BUILD_NODE || false}`,
+ `BUILD_REACT_NATIVE=${process.env.BUILD_REACT_NATIVE || false}`,
+ ].join(' '),
+ sourceMap,
+ ),
+ };
+ }, {});
+}
+
+function getPReactScripts() {
+ const reactCommands = prefixKeys('react.', getCommands());
+ const preactCommands = prefixKeys('preact.', getCommands({ preact: true }));
+ return getConcurrentlyArgs(Object.assign(reactCommands, preactCommands));
+}
-const buildPreact = args.includes('--p-react')
-const scripts = buildPreact
- ? getPReactScripts()
- : getConcurrentlyArgs(getCommands())
+const buildPreact = args.includes('--p-react');
+const scripts = buildPreact ? getPReactScripts() : getConcurrentlyArgs(getCommands());
-const cleanBuildDirs = !args.includes('--no-clean')
+const cleanBuildDirs = !args.includes('--no-clean');
if (cleanBuildDirs) {
- rimraf.sync(fromRoot('dist'))
+ rimraf.sync(fromRoot('dist'));
if (buildPreact) {
- rimraf.sync(fromRoot('preact'))
+ rimraf.sync(fromRoot('preact'));
}
}
const result = spawn.sync(resolveBin('concurrently'), scripts, {
stdio: 'inherit',
-})
+});
if (result.status === 0 && buildPreact && !args.includes('--no-package-json')) {
writeExtraEntry(
@@ -72,43 +105,7 @@ if (result.status === 0 && buildPreact && !args.includes('--no-package-json')) {
esm: glob.sync(fromRoot('preact/**/*.esm.js'))[0],
},
false,
- )
-}
-
-function getPReactScripts() {
- const reactCommands = prefixKeys('react.', getCommands())
- const preactCommands = prefixKeys('preact.', getCommands({preact: true}))
- return getConcurrentlyArgs(Object.assign(reactCommands, preactCommands))
-}
-
-function prefixKeys(prefix, object) {
- return Object.entries(object).reduce((cmds, [key, value]) => {
- cmds[`${prefix}${key}`] = value
- return cmds
- }, {})
-}
-
-function getCommands({preact = false} = {}) {
- return formats.reduce((cmds, format) => {
- const [formatName, minify = false] = format.split('.')
- const nodeEnv = minify ? 'production' : 'development'
- const sourceMap = formatName === 'umd' ? '--sourcemap' : ''
- const buildMinify = Boolean(minify)
-
- cmds[format] = getCommand(
- [
- `BUILD_FORMAT=${formatName}`,
- `BUILD_MINIFY=${buildMinify}`,
- `NODE_ENV=${nodeEnv}`,
- `BUILD_PREACT=${preact}`,
- `BUILD_SIZE_SNAPSHOT=${sizeSnapshot}`,
- `BUILD_NODE=${process.env.BUILD_NODE || false}`,
- `BUILD_REACT_NATIVE=${process.env.BUILD_REACT_NATIVE || false}`,
- ].join(' '),
- sourceMap,
- )
- return cmds
- }, {})
+ );
}
-process.exit(result.status)
+process.exit(result.status);
diff --git a/src/scripts/format.js b/src/scripts/format.js
index 94b804ad..2bd04cf1 100644
--- a/src/scripts/format.js
+++ b/src/scripts/format.js
@@ -1,44 +1,46 @@
-const path = require('path')
-const spawn = require('cross-spawn')
-const yargsParser = require('yargs-parser')
-const {hasPkgProp, resolveBin, hasFile} = require('../utils')
+const path = require('path');
+const spawn = require('cross-spawn');
+const yargsParser = require('yargs-parser');
+const { hasPkgProp, resolveBin, hasFile, resolveCodScripts } = require('../utils');
-const args = process.argv.slice(2)
-const parsedArgs = yargsParser(args)
+const args = process.argv.slice(2);
+const parsedArgs = yargsParser(args);
-const here = p => path.join(__dirname, p)
-const hereRelative = p => here(p).replace(process.cwd(), '.')
+const here = p => path.join(__dirname, p);
+const hereRelative = p => here(p).replace(process.cwd(), '.');
const useBuiltinConfig =
!args.includes('--config') &&
!hasFile('.prettierrc') &&
!hasFile('prettier.config.js') &&
- !hasPkgProp('prettierrc')
-const config = useBuiltinConfig
- ? ['--config', hereRelative('../config/prettierrc.js')]
- : []
+ !hasPkgProp('prettierrc');
-const useBuiltinIgnore =
- !args.includes('--ignore-path') && !hasFile('.prettierignore')
-const ignore = useBuiltinIgnore
- ? ['--ignore-path', hereRelative('../config/prettierignore')]
- : []
+const config = useBuiltinConfig ? ['--config', hereRelative('../config/prettierrc.js')] : [];
+const useBuiltinIgnore = !args.includes('--ignore-path') && !hasFile('.prettierignore');
+const ignore = useBuiltinIgnore ? ['--ignore-path', hereRelative('../config/prettierignore')] : [];
-const write = args.includes('--no-write') ? [] : ['--write']
+const write = args.includes('--no-write') ? [] : ['--write'];
// this ensures that when running format as a pre-commit hook and we get
// the full file path, we make that non-absolute so it is treated as a glob,
// This way the prettierignore will be applied
-const relativeArgs = args.map(a => a.replace(`${process.cwd()}/`, ''))
+const relativeArgs = args.map(a => a.replace(`${process.cwd()}/`, ''));
+const filesToApply = parsedArgs._.length ? [] : ['**/*.+(json|less|css|ts|tsx|md)'];
-const filesToApply = parsedArgs._.length
- ? []
- : ['**/*.+(js|json|less|css|ts|tsx|md)']
-
-const result = spawn.sync(
+// run prettier on all non-js files
+const prettierResult = spawn.sync(
resolveBin('prettier'),
[...config, ...ignore, ...write, ...filesToApply].concat(relativeArgs),
- {stdio: 'inherit'},
-)
+ { stdio: 'inherit' },
+);
+
+if (prettierResult.status !== 0 || args.includes('--no-eslint')) {
+ process.exit(prettierResult.status);
+}
+
+// run eslint for js files (`eslint-plugin-prettier` will run prettier for us)
+const eslintResult = spawn.sync(resolveCodScripts(), ['lint', '--fix'].concat(args), {
+ stdio: 'inherit',
+});
-process.exit(result.status)
+process.exit(eslintResult.status);
diff --git a/src/scripts/lint.js b/src/scripts/lint.js
index 2a3be2b0..18cb817f 100644
--- a/src/scripts/lint.js
+++ b/src/scripts/lint.js
@@ -1,55 +1,44 @@
-const path = require('path')
-const spawn = require('cross-spawn')
-const yargsParser = require('yargs-parser')
-const {hasPkgProp, resolveBin, hasFile, fromRoot} = require('../utils')
+const path = require('path');
+const spawn = require('cross-spawn');
+const yargsParser = require('yargs-parser');
+const { hasPkgProp, resolveBin, hasFile, fromRoot } = require('../utils');
-let args = process.argv.slice(2)
-const here = p => path.join(__dirname, p)
-const hereRelative = p => here(p).replace(process.cwd(), '.')
-const parsedArgs = yargsParser(args)
+let args = process.argv.slice(2);
+const here = p => path.join(__dirname, p);
+const hereRelative = p => here(p).replace(process.cwd(), '.');
+const parsedArgs = yargsParser(args);
const useBuiltinConfig =
!args.includes('--config') &&
!hasFile('.eslintrc') &&
!hasFile('.eslintrc.js') &&
- !hasPkgProp('eslintConfig')
+ !hasPkgProp('eslintConfig');
-const config = useBuiltinConfig
- ? ['--config', hereRelative('../config/eslintrc.js')]
- : []
+const config = useBuiltinConfig ? ['--config', hereRelative('../config/eslintrc.js')] : [];
const useBuiltinIgnore =
- !args.includes('--ignore-path') &&
- !hasFile('.eslintignore') &&
- !hasPkgProp('eslintIgnore')
+ !args.includes('--ignore-path') && !hasFile('.eslintignore') && !hasPkgProp('eslintIgnore');
-const ignore = useBuiltinIgnore
- ? ['--ignore-path', hereRelative('../config/eslintignore')]
- : []
+const ignore = useBuiltinIgnore ? ['--ignore-path', hereRelative('../config/eslintignore')] : [];
const cache = args.includes('--no-cache')
? []
- : [
- '--cache',
- '--cache-location',
- fromRoot('node_modules/.cache/.eslintcache'),
- ]
+ : ['--cache', '--cache-location', fromRoot('node_modules/.cache/.eslintcache')];
-const filesGiven = parsedArgs._.length > 0
-
-const filesToApply = filesGiven ? [] : ['.']
+const filesGiven = parsedArgs._.length > 0;
+const filesToApply = filesGiven ? [] : ['.'];
if (filesGiven) {
// we need to take all the flag-less arguments (the files that should be linted)
// and filter out the ones that aren't js files. Otherwise json or css files
// may be passed through
- args = args.filter(a => !parsedArgs._.includes(a) || /\.jsx?$/.test(a))
+ args = args.filter(a => !parsedArgs._.includes(a) || /\.(jsx|js)?$/.test(a));
}
const result = spawn.sync(
resolveBin('eslint'),
[...config, ...ignore, ...cache, ...args, ...filesToApply],
- {stdio: 'inherit'},
-)
+ { stdio: 'inherit' },
+);
-process.exit(result.status)
+process.exit(result.status);
diff --git a/src/scripts/pre-commit.js b/src/scripts/pre-commit.js
index 03be42f5..e9188718 100644
--- a/src/scripts/pre-commit.js
+++ b/src/scripts/pre-commit.js
@@ -1,34 +1,30 @@
-const path = require('path')
-const spawn = require('cross-spawn')
-const {isOptedIn, hasPkgProp, hasFile, resolveBin} = require('../utils')
+const path = require('path');
+const spawn = require('cross-spawn');
+const { isOptedIn, hasPkgProp, hasFile, resolveBin } = require('../utils');
-const here = p => path.join(__dirname, p)
-const hereRelative = p => here(p).replace(process.cwd(), '.')
+const here = p => path.join(__dirname, p);
+const hereRelative = p => here(p).replace(process.cwd(), '.');
-const args = process.argv.slice(2)
+const args = process.argv.slice(2);
const useBuiltInConfig =
!args.includes('--config') &&
!hasFile('.lintstagedrc') &&
!hasFile('lint-staged.config.js') &&
- !hasPkgProp('lint-staged')
+ !hasPkgProp('lint-staged');
-const config = useBuiltInConfig
- ? ['--config', hereRelative('../config/lintstagedrc.js')]
- : []
+const config = useBuiltInConfig ? ['--config', hereRelative('../config/lintstagedrc.js')] : [];
-const lintStagedResult = spawn.sync(
- resolveBin('lint-staged'),
- [...config, ...args],
- {stdio: 'inherit'},
-)
+const lintStagedResult = spawn.sync(resolveBin('lint-staged'), [...config, ...args], {
+ stdio: 'inherit',
+});
if (lintStagedResult.status !== 0 || !isOptedIn('pre-commit')) {
- process.exit(lintStagedResult.status)
+ process.exit(lintStagedResult.status);
} else {
const validateResult = spawn.sync('npm', ['run', 'validate'], {
stdio: 'inherit',
- })
+ });
- process.exit(validateResult.status)
+ process.exit(validateResult.status);
}
diff --git a/src/scripts/test.js b/src/scripts/test.js
index 106a2d09..f00d3adb 100644
--- a/src/scripts/test.js
+++ b/src/scripts/test.js
@@ -1,10 +1,10 @@
-process.env.BABEL_ENV = 'test'
-process.env.NODE_ENV = 'test'
+process.env.BABEL_ENV = 'test';
+process.env.NODE_ENV = 'test';
-const isCI = require('is-ci')
-const {hasPkgProp, parseEnv, hasFile} = require('../utils')
+const isCI = require('is-ci');
+const { hasPkgProp, parseEnv, hasFile } = require('../utils');
-const args = process.argv.slice(2)
+const args = process.argv.slice(2);
const watch =
!isCI &&
@@ -13,14 +13,12 @@ const watch =
!args.includes('--coverage') &&
!args.includes('--updateSnapshot')
? ['--watch']
- : []
+ : [];
const config =
- !args.includes('--config') &&
- !hasFile('jest.config.js') &&
- !hasPkgProp('jest')
+ !args.includes('--config') && !hasFile('jest.config.js') && !hasPkgProp('jest')
? ['--config', JSON.stringify(require('../config/jest.config'))]
- : []
+ : [];
// eslint-disable-next-line jest/no-jest-import
-require('jest').run([...config, ...watch, ...args])
+require('jest').run([...config, ...watch, ...args]);
diff --git a/src/scripts/travis-after-success.js b/src/scripts/travis-after-success.js
deleted file mode 100644
index 5e76eaba..00000000
--- a/src/scripts/travis-after-success.js
+++ /dev/null
@@ -1,57 +0,0 @@
-const spawn = require('cross-spawn')
-const {
- resolveBin,
- getConcurrentlyArgs,
- hasFile,
- pkg,
- parseEnv,
-} = require('../utils')
-
-console.log('installing and running travis-deploy-once')
-const deployOnceResults = spawn.sync('npx', ['travis-deploy-once@5'], {
- stdio: 'inherit',
-})
-if (deployOnceResults.status === 0) {
- runAfterSuccessScripts()
-} else {
- console.log(
- 'travis-deploy-once exited with a non-zero exit code',
- deployOnceResults.status,
- )
- process.exit(deployOnceResults.status)
-}
-
-// eslint-disable-next-line complexity
-function runAfterSuccessScripts() {
- const autorelease =
- pkg.version === '0.0.0-semantically-released' &&
- parseEnv('TRAVIS', false) &&
- process.env.TRAVIS_BRANCH === 'master' &&
- !parseEnv('TRAVIS_PULL_REQUEST', false)
-
- const reportCoverage = hasFile('coverage') && !parseEnv('SKIP_CODECOV', false)
-
- if (!autorelease && !reportCoverage) {
- console.log(
- 'No need to autorelease or report coverage. Skipping travis-after-success script...',
- )
- } else {
- const result = spawn.sync(
- resolveBin('concurrently'),
- getConcurrentlyArgs(
- {
- codecov: reportCoverage
- ? `echo installing codecov && npx -p codecov@3 -c 'echo running codecov && codecov'`
- : null,
- release: autorelease
- ? `echo installing semantic-release && npx -p semantic-release@15 -c 'echo running semantic-release && semantic-release'`
- : null,
- },
- {killOthers: false},
- ),
- {stdio: 'inherit'},
- )
-
- process.exit(result.status)
- }
-}
diff --git a/src/scripts/validate.js b/src/scripts/validate.js
index 2706536e..5f15ecba 100644
--- a/src/scripts/validate.js
+++ b/src/scripts/validate.js
@@ -1,38 +1,28 @@
-const spawn = require('cross-spawn')
-const {
- parseEnv,
- resolveBin,
- ifScript,
- getConcurrentlyArgs,
-} = require('../utils')
+const spawn = require('cross-spawn');
+const { parseEnv, resolveBin, ifScript, getConcurrentlyArgs } = require('../utils');
// pre-commit runs linting and tests on the relevant files
// so those scripts don't need to be run if we're running
// this in the context of a pre-commit hook.
-const preCommit = parseEnv('SCRIPTS_PRE-COMMIT', false)
+const preCommit = parseEnv('SCRIPTS_PRE-COMMIT', false);
-const validateScripts = process.argv[2]
+const validateScripts = process.argv[2];
-const useDefaultScripts = typeof validateScripts !== 'string'
+const useDefaultScripts = typeof validateScripts !== 'string';
const scripts = useDefaultScripts
? {
build: ifScript('build', 'npm run build --silent'),
lint: preCommit ? null : ifScript('lint', 'npm run lint --silent'),
- test: preCommit
- ? null
- : ifScript('test', 'npm run test --silent -- --coverage'),
+ test: preCommit ? null : ifScript('test', 'npm run test --silent -- --coverage'),
flow: ifScript('flow', 'npm run flow --silent'),
}
: validateScripts.split(',').reduce((scriptsToRun, name) => {
- scriptsToRun[name] = `npm run ${name} --silent`
- return scriptsToRun
- }, {})
+ return { ...scriptsToRun, [name]: `npm run ${name} --silent` };
+ }, {});
-const result = spawn.sync(
- resolveBin('concurrently'),
- getConcurrentlyArgs(scripts),
- {stdio: 'inherit'},
-)
+const result = spawn.sync(resolveBin('concurrently'), getConcurrentlyArgs(scripts), {
+ stdio: 'inherit',
+});
-process.exit(result.status)
+process.exit(result.status);
diff --git a/src/utils.js b/src/utils.js
index 7847f776..d9822c33 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -1,96 +1,89 @@
-const fs = require('fs')
-const path = require('path')
-const rimraf = require('rimraf')
-const mkdirp = require('mkdirp')
-const arrify = require('arrify')
-const has = require('lodash.has')
-const readPkgUp = require('read-pkg-up')
-const which = require('which')
-
-const {package: pkg, path: pkgPath} = readPkgUp.sync({
+const fs = require('fs');
+const path = require('path');
+const rimraf = require('rimraf');
+const mkdirp = require('mkdirp');
+const arrify = require('arrify');
+const has = require('lodash.has');
+const readPkgUp = require('read-pkg-up');
+const which = require('which');
+
+const { package: pkg, path: pkgPath } = readPkgUp.sync({
cwd: fs.realpathSync(process.cwd()),
-})
-const appDirectory = path.dirname(pkgPath)
+});
+const appDirectory = path.dirname(pkgPath);
-function resolveKcdScripts() {
- if (pkg.name === 'kcd-scripts') {
- return require.resolve('./').replace(process.cwd(), '.')
- }
- return resolveBin('kcd-scripts')
-}
-
-// eslint-disable-next-line complexity
-function resolveBin(modName, {executable = modName, cwd = process.cwd()} = {}) {
- let pathFromWhich
+function resolveBin(modName, { executable = modName, cwd = process.cwd() } = {}) {
+ let pathFromWhich;
try {
- pathFromWhich = fs.realpathSync(which.sync(executable))
- if (pathFromWhich && pathFromWhich.includes('.CMD')) return pathFromWhich
+ pathFromWhich = fs.realpathSync(which.sync(executable));
+ if (pathFromWhich && pathFromWhich.includes('.CMD')) return pathFromWhich;
} catch (_error) {
// ignore _error
}
try {
- const modPkgPath = require.resolve(`${modName}/package.json`)
- const modPkgDir = path.dirname(modPkgPath)
- const {bin} = require(modPkgPath)
- const binPath = typeof bin === 'string' ? bin : bin[executable]
- const fullPathToBin = path.join(modPkgDir, binPath)
+ const modPkgPath = require.resolve(`${modName}/package.json`);
+ const modPkgDir = path.dirname(modPkgPath);
+ const { bin } = require(modPkgPath); // eslint-disable-line
+ const binPath = typeof bin === 'string' ? bin : bin[executable];
+ const fullPathToBin = path.join(modPkgDir, binPath);
if (fullPathToBin === pathFromWhich) {
- return executable
+ return executable;
}
- return fullPathToBin.replace(cwd, '.')
+ return fullPathToBin.replace(cwd, '.');
} catch (error) {
if (pathFromWhich) {
- return executable
+ return executable;
}
- throw error
+ throw error;
}
}
-const fromRoot = (...p) => path.join(appDirectory, ...p)
-const hasFile = (...p) => fs.existsSync(fromRoot(...p))
-const ifFile = (files, t, f) =>
- arrify(files).some(file => hasFile(file)) ? t : f
+function resolveCodScripts() {
+ if (pkg.name === 'cod-scripts') {
+ return require.resolve('./').replace(process.cwd(), '.');
+ }
+ return resolveBin('cod-scripts');
+}
+
+const fromRoot = (...p) => path.join(appDirectory, ...p);
+const hasFile = (...p) => fs.existsSync(fromRoot(...p));
+const ifFile = (files, t, f) => (arrify(files).some(file => hasFile(file)) ? t : f);
-const hasPkgProp = props => arrify(props).some(prop => has(pkg, prop))
+const hasPkgProp = props => arrify(props).some(prop => has(pkg, prop));
-const hasPkgSubProp = pkgProp => props =>
- hasPkgProp(arrify(props).map(p => `${pkgProp}.${p}`))
+const hasPkgSubProp = pkgProp => props => hasPkgProp(arrify(props).map(p => `${pkgProp}.${p}`));
-const ifPkgSubProp = pkgProp => (props, t, f) =>
- hasPkgSubProp(pkgProp)(props) ? t : f
+const ifPkgSubProp = pkgProp => (props, t, f) => (hasPkgSubProp(pkgProp)(props) ? t : f);
-const hasScript = hasPkgSubProp('scripts')
-const hasPeerDep = hasPkgSubProp('peerDependencies')
-const hasDep = hasPkgSubProp('dependencies')
-const hasDevDep = hasPkgSubProp('devDependencies')
-const hasAnyDep = args => [hasDep, hasDevDep, hasPeerDep].some(fn => fn(args))
+const hasScript = hasPkgSubProp('scripts');
+const hasPeerDep = hasPkgSubProp('peerDependencies');
+const hasDep = hasPkgSubProp('dependencies');
+const hasDevDep = hasPkgSubProp('devDependencies');
+const hasAnyDep = args => [hasDep, hasDevDep, hasPeerDep].some(fn => fn(args));
-const ifPeerDep = ifPkgSubProp('peerDependencies')
-const ifDep = ifPkgSubProp('dependencies')
-const ifDevDep = ifPkgSubProp('devDependencies')
-const ifAnyDep = (deps, t, f) => (hasAnyDep(arrify(deps)) ? t : f)
-const ifScript = ifPkgSubProp('scripts')
+const ifPeerDep = ifPkgSubProp('peerDependencies');
+const ifDep = ifPkgSubProp('dependencies');
+const ifDevDep = ifPkgSubProp('devDependencies');
+const ifAnyDep = (deps, t, f) => (hasAnyDep(arrify(deps)) ? t : f);
+const ifScript = ifPkgSubProp('scripts');
+
+function envIsSet(name) {
+ // eslint-disable-next-line no-prototype-builtins
+ return process.env.hasOwnProperty(name) && process.env[name] && process.env[name] !== 'undefined';
+}
function parseEnv(name, def) {
if (envIsSet(name)) {
try {
- return JSON.parse(process.env[name])
+ return JSON.parse(process.env[name]);
} catch (err) {
- return process.env[name]
+ return process.env[name];
}
}
- return def
-}
-
-function envIsSet(name) {
- return (
- process.env.hasOwnProperty(name) &&
- process.env[name] &&
- process.env[name] !== 'undefined'
- )
+ return def;
}
-function getConcurrentlyArgs(scripts, {killOthers = true} = {}) {
+function getConcurrentlyArgs(scripts, { killOthers = true } = {}) {
const colors = [
'bgBlue',
'bgGreen',
@@ -100,20 +93,18 @@ function getConcurrentlyArgs(scripts, {killOthers = true} = {}) {
'bgRed',
'bgBlack',
'bgYellow',
- ]
+ ];
+ // eslint-disable-next-line no-param-reassign
scripts = Object.entries(scripts).reduce((all, [name, script]) => {
if (script) {
- all[name] = script
+ // eslint-disable-next-line no-param-reassign
+ all[name] = script;
}
- return all
- }, {})
+ return all;
+ }, {});
const prefixColors = Object.keys(scripts)
- .reduce(
- (pColors, _s, i) =>
- pColors.concat([`${colors[i % colors.length]}.bold.reset`]),
- [],
- )
- .join(',')
+ .reduce((pColors, _s, i) => pColors.concat([`${colors[i % colors.length]}.bold.reset`]), [])
+ .join(',');
// prettier-ignore
return [
@@ -127,32 +118,32 @@ function getConcurrentlyArgs(scripts, {killOthers = true} = {}) {
function isOptedOut(key, t = true, f = false) {
if (!fs.existsSync(fromRoot('.opt-out'))) {
- return f
+ return f;
}
- const contents = fs.readFileSync(fromRoot('.opt-out'), 'utf-8')
- return contents.includes(key) ? t : f
+ const contents = fs.readFileSync(fromRoot('.opt-out'), 'utf-8');
+ return contents.includes(key) ? t : f;
}
function isOptedIn(key, t = true, f = false) {
if (!fs.existsSync(fromRoot('.opt-in'))) {
- return f
+ return f;
}
- const contents = fs.readFileSync(fromRoot('.opt-in'), 'utf-8')
- return contents.includes(key) ? t : f
+ const contents = fs.readFileSync(fromRoot('.opt-in'), 'utf-8');
+ return contents.includes(key) ? t : f;
}
function uniq(arr) {
- return Array.from(new Set(arr))
+ return Array.from(new Set(arr));
}
-function writeExtraEntry(name, {cjs, esm}, clean = true) {
+function writeExtraEntry(name, { cjs, esm }, clean = true) {
if (clean) {
- rimraf.sync(fromRoot(name))
+ rimraf.sync(fromRoot(name));
}
- mkdirp.sync(fromRoot(name))
+ mkdirp.sync(fromRoot(name));
- const pkgJson = fromRoot(`${name}/package.json`)
- const entryDir = fromRoot(name)
+ const pkgJson = fromRoot(`${name}/package.json`);
+ const entryDir = fromRoot(name);
fs.writeFileSync(
pkgJson,
@@ -165,7 +156,7 @@ function writeExtraEntry(name, {cjs, esm}, clean = true) {
null,
2,
),
- )
+ );
}
module.exports = {
@@ -187,7 +178,7 @@ module.exports = {
parseEnv,
pkg,
resolveBin,
- resolveKcdScripts,
+ resolveCodScripts,
uniq,
writeExtraEntry,
-}
+};