diff --git a/.github/ISSUE_TEMPLATE/01-bug.yml b/.github/ISSUE_TEMPLATE/01-bug.yml index 4a4c6fad..c217dc91 100644 --- a/.github/ISSUE_TEMPLATE/01-bug.yml +++ b/.github/ISSUE_TEMPLATE/01-bug.yml @@ -11,13 +11,11 @@ labels: body: - type: checkboxes attributes: - description: - If any of these required steps are not taken, we may not be able to + description: If any of these required steps are not taken, we may not be able to review your issue. Help us to help you! label: Bug Report Checklist options: - - label: - I have [searched for related + - label: I have [searched for related issues](https://github.com/all-contributors/cli/issues?q=is%3Aissue) and found none that matched my issue. required: true @@ -29,8 +27,7 @@ body: required: true - type: textarea attributes: - description: - Steps to Reproduce the bug. Please provide a minimal reproducible + description: Steps to Reproduce the bug. Please provide a minimal reproducible example if possible. label: Steps to Reproduce validations: @@ -51,8 +48,7 @@ body: required: false - type: input attributes: - description: - If possible, please create a repository that reproduces the issue with + description: If possible, please create a repository that reproduces the issue with the minimal amount of code possible. label: Minimal Reproduction placeholder: https://github.com/user/repo diff --git a/.github/ISSUE_TEMPLATE/02-documentation.yml b/.github/ISSUE_TEMPLATE/02-documentation.yml index 5e410c1f..bc01b942 100644 --- a/.github/ISSUE_TEMPLATE/02-documentation.yml +++ b/.github/ISSUE_TEMPLATE/02-documentation.yml @@ -11,15 +11,13 @@ labels: body: - type: checkboxes attributes: - description: - If any of these required steps are not taken, we may not be able to + description: If any of these required steps are not taken, we may not be able to review your issue. Help us to help you! label: Documentation Report Checklist options: - label: I have checked the latest `main` branch of the repository. required: true - - label: - I have [searched for related + - label: I have [searched for related issues](https://github.com/all-contributors/cli/issues?q=is%3Aissue) and found none that matched my issue. required: true diff --git a/.github/ISSUE_TEMPLATE/03-feature.yml b/.github/ISSUE_TEMPLATE/03-feature.yml index a138075b..e7de1e52 100644 --- a/.github/ISSUE_TEMPLATE/03-feature.yml +++ b/.github/ISSUE_TEMPLATE/03-feature.yml @@ -11,13 +11,11 @@ labels: body: - type: checkboxes attributes: - description: - If any of these required steps are not taken, we may not be able to + description: If any of these required steps are not taken, we may not be able to review your issue. Help us to help you! label: Feature Request Checklist options: - - label: - I have [searched for related + - label: I have [searched for related issues](https://github.com/all-contributors/cli/issues?q=is%3Aissue) and found none that matched my issue. required: true diff --git a/.github/ISSUE_TEMPLATE/04-tooling.yml b/.github/ISSUE_TEMPLATE/04-tooling.yml index ea0f5dac..fe41e565 100644 --- a/.github/ISSUE_TEMPLATE/04-tooling.yml +++ b/.github/ISSUE_TEMPLATE/04-tooling.yml @@ -11,15 +11,13 @@ labels: body: - type: checkboxes attributes: - description: - If any of these required steps are not taken, we may not be able to + description: If any of these required steps are not taken, we may not be able to review your issue. Help us to help you! label: Tooling Report Checklist options: - label: I have pulled the latest `main` branch of the repository. required: true - - label: - I have [searched for related + - label: I have [searched for related issues](https://github.com/all-contributors/cli/issues?q=is%3Aissue) and found none that matched my issue. required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index f26f694c..1bf45a42 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -35,9 +35,7 @@ merge of your pull request! - [ ] Documentation - [ ] Tests -- [ ] Ready to be merged - -- [ ] Added myself to contributors table - +- [ ] Ready to be merged +- [ ] Added myself to contributors table diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 15fabd31..c3ee3ef9 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -8,12 +8,12 @@ on: workflow_dispatch: ~ jobs: - format-check: + format_check: name: Format Check runs-on: ubuntu-latest steps: - uses: $/.github/actions/setup - - run: npm run format:check + - run: npm run format -- --list-different lint: name: Lint diff --git a/.github/workflows/test-deploy.yml b/.github/workflows/test-deploy.yml index a17a39a2..ac03faef 100644 --- a/.github/workflows/test-deploy.yml +++ b/.github/workflows/test-deploy.yml @@ -43,8 +43,7 @@ jobs: publish: name: >- Publish cli ๐Ÿ“ฆ to NPM - if: - github.repository_owner == 'all-contributors' && github.event_name == + if: github.repository_owner == 'all-contributors' && github.event_name == 'release' needs: - end-to-end diff --git a/.gitignore b/.gitignore index 03aa6ddc..69f50e64 100644 --- a/.gitignore +++ b/.gitignore @@ -10,7 +10,6 @@ dist # when working with contributors .husky .idea -.vscode cache pnpm-lock.yaml yarn.lock diff --git a/.prettierignore b/.prettierignore deleted file mode 100644 index 3ae2a557..00000000 --- a/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -coverage/** -dist/** -.all-contributorsrc -CHANGELOG* \ No newline at end of file diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index 68f9d033..00000000 --- a/.prettierrc +++ /dev/null @@ -1,20 +0,0 @@ -{ - "arrowParens": "avoid", - "bracketSameLine": false, - "bracketSpacing": false, - "embeddedLanguageFormatting": "auto", - "endOfLine": "lf", - "htmlWhitespaceSensitivity": "css", - "insertPragma": false, - "jsxSingleQuote": false, - "printWidth": 80, - "proseWrap": "always", - "quoteProps": "as-needed", - "requirePragma": false, - "semi": false, - "singleAttributePerLine": false, - "singleQuote": true, - "tabWidth": 2, - "trailingComma": "all", - "useTabs": false -} diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 00000000..61ce504a --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,8 @@ +{ + "recommendations": [ + "dbaeumer.vscode-eslint", + "oxc.oxc-vscode", + "vitest.explorer", + "webpro.vscode-knip" + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..3d803fad --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,15 @@ +{ + "editor.defaultFormatter": "oxc.oxc-vscode", + "editor.formatOnSave": true, + "editor.rulers": [100], + "eslint.probe": [ + "javascript", + "javascriptreact", + "json", + "jsonc", + "markdown", + "typescript", + "typescriptreact", + "yaml" + ] +} diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 9d5082ea..0fb6cd41 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -15,8 +15,7 @@ These are the npm scripts available when working on the CLI: | `npm run build` | Build the CLI (output in `dist/`) | | `npm run dev` | Run the CLI from source without building | | `npm run start` | Run the built CLI (`dist/cli.js`) | -| `npm run lint` | Fix format issues | -| `npm run format:check` | Check for format issues | +| `npm run format` | Fix format issues | | `npm run lint` | Check for lint issues | | `npm run lint -- --fix` | Fix lint issues | | `npm test` | Run the test suite (no coverage) | @@ -111,73 +110,53 @@ You don't need a Codecov account to view coverage locally. Run `npm run test:coverage` and open the HTML report. Codecov is mainly for tracking trends and CI. -## Linting +## Static Checks -The project uses ESLint. Linting was migrated from `kcd-scripts` to a native -ESLint setup that supports both CommonJS source files and ES module test files. +The project has several forms of static analysis. -### Overview +### Format -- Config: `eslint.config.mjs` -- Includes `eslint:recommended`, import rules, Vitest rules for test files, and - project overrides +We use Oxfmt for formatting. +Use `format` to reformat. -### How to run the linter +```sh +npm run format +``` -To check for issues you can run: +> [!NOTE] +> Be sure to install the `Oxc` extension to get the most out of Oxfmt. -```bash +### Lint + +We use ESLint as our primary linter. +You can check for violations with: + +```sh npm run lint ``` -To auto-fix what ESLint and Prettier can fix you can run: +To automatically address what ESLint can fix for you, run: -```bash -npm run lint-fix +```sh +npm run lint -- --fix ``` This will fix many issues (e.g. Vitest aliases, unused eslint-disable -directives, formatting). Some problems still need manual fixes (e.g. unused -variables, tests without assertions). +directives, formatting). +Some problems still need manual fixes (e.g. unused variables, tests without assertions). ### Pre-commit hooks -Husky runs a pre-commit hook that lints and fixes staged files before each -commit. - -1. On `git commit`, Husky runs the pre-commit hook. -2. The hook runs `lint-staged`, which runs ESLint and Prettier on staged - JavaScript files. -3. If that passes, the commit continues; if it fails, the commit is blocked. +`simple-git-hooks` runs a pre-commit hook that reformats staged files before each commit. -If the hook gives you trouble, run `npm run lint-fix` manually, then try -committing again. As a last resort you can skip the hook with -`git commit --no-verify`; if you do, mention it in your PR so maintainers can -help. +On `git commit`, `simple-git-hooks` runs the pre-commit hook. +The hook runs `lint-staged`, which runs Oxfmt on all staged files. **Configuration:** -- The hook lives in `.husky/pre-commit` (it runs `npx lint-staged`). +- The hook is configured on `simple-git-hooks` in the `package.json`. - `lint-staged` is configured in `package.json` under the `lint-staged` field. -- Linting uses `eslint.config.mjs`. - -### Lint-related dependencies - -- **eslint** โ€” Core -- **@eslint/js** โ€” Recommended rules -- **eslint-plugin-import** โ€” Import/export rules -- **@vitest/eslint-plugin** โ€” Vitest rules for test files -- **globals** โ€” Node and Vitest globals for the lint environment - -## Build system - -The build uses native Babel (migrated from `kcd-scripts build`). Key -dependencies: - -- **@babel/core** โ€” Compiler (parse, transform, generate) -- **@babel/cli** โ€” Runs `babel src --out-dir dist` -- **@babel/preset-env** โ€” Compiles modern JS for the target (e.g. Node 22) -- **@babel/runtime** โ€” Runtime helpers used by the transpiled code +- Linting uses `eslint.config.js`. ### How to build diff --git a/eslint.config.js b/eslint.config.js index b2475460..6f9daa44 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,22 +1,17 @@ -import js from '@eslint/js' -import markdown from '@eslint/markdown' -import vitestPlugin from '@vitest/eslint-plugin' -import {importX} from 'eslint-plugin-import-x' -import jsonc from 'eslint-plugin-jsonc' -import packageJson from 'eslint-plugin-package-json' -import perfectionist from 'eslint-plugin-perfectionist' -import yml from 'eslint-plugin-yml' -import {defineConfig, globalIgnores} from 'eslint/config' -import globals from 'globals' +import js from '@eslint/js'; +import markdown from '@eslint/markdown'; +import vitestPlugin from '@vitest/eslint-plugin'; +import { importX } from 'eslint-plugin-import-x'; +import jsonc from 'eslint-plugin-jsonc'; +import packageJson from 'eslint-plugin-package-json'; +import perfectionist from 'eslint-plugin-perfectionist'; +import yml from 'eslint-plugin-yml'; +import { defineConfig, globalIgnores } from 'eslint/config'; +import globals from 'globals'; export default defineConfig([ - globalIgnores([ - 'coverage/**', - 'dist/**', - '.all-contributorsrc', - 'CHANGELOG*', - ]), - {linterOptions: {reportUnusedDisableDirectives: 'error'}}, + globalIgnores(['coverage/**', 'dist/**', '.all-contributorsrc', 'CHANGELOG*']), + { linterOptions: { reportUnusedDisableDirectives: 'error' } }, { extends: [js.configs.recommended, importX.flatConfigs.recommended], files: ['**/*.{mjs,js}'], @@ -24,22 +19,18 @@ export default defineConfig([ ecmaVersion: 'latest', globals: globals.node, }, - plugins: {perfectionist}, + plugins: { perfectionist }, rules: { - 'import-x/no-unresolved': [ - 'error', - {ignore: ['^eslint/', '^prettier$', '^yargs']}, - ], + 'import-x/no-unresolved': ['error', { ignore: ['^eslint/', '^prettier$', '^yargs'] }], 'import-x/no-extraneous-dependencies': 'error', 'import-x/default': 'off', 'import-x/namespace': 'off', 'import-x/no-named-as-default-member': 'off', 'perfectionist/sort-exports': 'error', - 'perfectionist/sort-imports': 'error', 'perfectionist/sort-named-exports': 'error', 'perfectionist/sort-named-imports': 'error', }, - settings: {perfectionist: {partitionByComment: true, type: 'natural'}}, + settings: { perfectionist: { partitionByComment: true, type: 'natural' } }, }, { extends: [vitestPlugin.configs.recommended], @@ -76,11 +67,8 @@ export default defineConfig([ extends: [yml.configs['flat/standard'], yml.configs['flat/prettier']], files: ['**/*.{yml,yaml}'], rules: { - 'yml/file-extension': ['error', {extension: 'yml'}], - 'yml/sort-sequence-values': [ - 'error', - {order: {type: 'asc'}, pathPattern: '^.*$'}, - ], + 'yml/file-extension': ['error', { extension: 'yml' }], + 'yml/sort-sequence-values': ['error', { order: { type: 'asc' }, pathPattern: '^.*$' }], }, }, -]) +]); diff --git a/knip.json b/knip.json index e22aa28a..e1d4d2e0 100644 --- a/knip.json +++ b/knip.json @@ -1,10 +1,5 @@ { "$schema": "https://unpkg.com/knip@5.71.0/schema.json", - "entry": [ - "src/**/__tests__/*", - "src/api.js", - "src/repo/*.js", - "src/util/*.js" - ], + "entry": ["src/**/__tests__/*", "src/api.js", "src/repo/*.js", "src/util/*.js"], "treatConfigHintsAsErrors": true } diff --git a/oxfmt.config.ts b/oxfmt.config.ts new file mode 100644 index 00000000..9840a52f --- /dev/null +++ b/oxfmt.config.ts @@ -0,0 +1,17 @@ +import { defineConfig, type OxfmtConfig } from 'oxfmt'; + +const config: OxfmtConfig = defineConfig({ + ignorePatterns: [ + '/.all-contributorsrc', + '/CHANGELOG.md', + '/coverage', + '/dist', + '/package-lock.json', + ], + overrides: [{ files: ['.nvmrc'], options: { parser: 'yaml' } }], + singleQuote: true, + sortImports: true, + sortPackageJson: false, +}); + +export default config; diff --git a/package-lock.json b/package-lock.json index 4334a323..27966619 100644 --- a/package-lock.json +++ b/package-lock.json @@ -34,6 +34,7 @@ "knip": "^6.10.0", "lint-staged": "^17.6.0", "nock": "^15.0.5", + "oxfmt": "^0.77.0", "prettier": "^3.8.1", "simple-git-hooks": "^2.14.0", "vitest": "^5.1.0" @@ -1485,6 +1486,353 @@ "win32" ] }, + "node_modules/@oxfmt/binding-android-arm-eabi": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.77.0.tgz", + "integrity": "sha512-zmPiuOvkuu0csMx4U3gdMunIFWNcWulzikFMdAPBzLazVAA3LhdHzv9yzgUgAckv/zje5vz4XJcseNQKdSsWMw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-android-arm64": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.77.0.tgz", + "integrity": "sha512-shXOIK9sj3bvt4H6K47qFWNKaYBwEhzj97iUwoLGyyRDrXt1OdAAuCiupCinG1i7ETL81knjEKeB+JmhOOfPew==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-darwin-arm64": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.77.0.tgz", + "integrity": "sha512-lrTX0I54buv9CW2leEWchWLdfcrblZ5Rj8uAilKzBEyWif8CTN6zBHdFc12K1b6U2cnlvOFBd1LxdLdqLKX2EA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-darwin-x64": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.77.0.tgz", + "integrity": "sha512-SD44K3x/Im8EsOtdHxjVmTBi0cafAaunRpCeq+w91tkD2keqYagR8oAvxkJHUK+KPg5NQk7JZqQnzGHnVEBrDw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-freebsd-x64": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.77.0.tgz", + "integrity": "sha512-N+gUflsCx3FAVkxi5sxGlL5LwO+7pv5NexHJufBqPyl3BcPv1rXpfwqhL/Vj+XfshfoxMFTBbzrbJgGVaPVkAw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm-gnueabihf": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.77.0.tgz", + "integrity": "sha512-DXGwP8818IUZ4cxcfugg9PXqnI6fVCWIqgCgBoUKdl/QhJF4Po+lucJBrnrX/b5BNKwVMc3xSrvbI9rl8+RrBA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm-musleabihf": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.77.0.tgz", + "integrity": "sha512-HUiJTgdV10PkCW41nHqVYYlW8Uc+39YBOoluZLfJE2MBPKVTNElhL+vpdSEuVaCGhGkzOGR6XyxM37gu31L1Qw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm64-gnu": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.77.0.tgz", + "integrity": "sha512-+w3V07y6yy8FdACnGtzgDsG/CHgA0Y/W2/bzZuPYgvBAa23Lap/nmvyNQmCiGKkSaChTPlY7QpIShGGAC7IGEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm64-musl": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.77.0.tgz", + "integrity": "sha512-FASxWQAuLW4WXFViDa77ybd3Y1lbkBx5DTtL4OGl+pL64/ymtydTFvJM0xz/0vnCirNzPUDAI6TiTBDGsFbEVg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-ppc64-gnu": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.77.0.tgz", + "integrity": "sha512-WRdlgZahG35zCieq7Po7QU8mBgkFAIdEpgS5p3vVZrHt0FXTbFgzqC7xeBCceh9gpFGgr4VWblULNnU8gdw0DA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-riscv64-gnu": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.77.0.tgz", + "integrity": "sha512-CVzNO94x/UzQe/INVUu9qt5X1MjLEooqwc/5VcQ88eyLXiEIIsjubpPQgwEMKwfWtAA5hnpFL2GF74zSdCg07Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-riscv64-musl": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.77.0.tgz", + "integrity": "sha512-NrCcVheqL0kRUi9gptqjkQhxSFayotM+zycC3lSOSrsf5SroZq49u66ShyuZkHCCzKPHB0AT0pL/s+ET9R3qQQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-s390x-gnu": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.77.0.tgz", + "integrity": "sha512-LWDQ9T/Bo/kt/q223j9fYLiNTkUYyuMkk7ZrIsIAV7l19MmuKxgd/1tZ8xhoUuVIdsyET7sJrQ6X/vRG6V+bZQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-x64-gnu": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.77.0.tgz", + "integrity": "sha512-5JbOT3ucC/2kROUjyyOW06FjXO8trPjYb+kE7E7cLxmpGAnw0jjeU4Tjg4C8H9JR1MZ2oH4fXE1NqLNZ89ISnw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-x64-musl": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.77.0.tgz", + "integrity": "sha512-/q9p495bmmKtxqWlIrNiJ15hoddgk/jPvJwMW6Nh796UgVRMTCKD7yI+AAL7/7xWlC3+2ls5l1RPywuV4lOdlw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-openharmony-arm64": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.77.0.tgz", + "integrity": "sha512-tmN3OEI38xXr48UeAkQMAX1jMHszVHv4I9lzh44DKrMlIFxEU0aBYl3Zs7PzRBuJOLR7h77m6bUlCh0E06MVXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-arm64-msvc": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.77.0.tgz", + "integrity": "sha512-v//nJMk72xRT+/9QB9mJWEPV3/5XncMvxtYQAYbAsv5VcxLlRcbj2n2srQSERglVcTft4jI3MK30ceCoRcDTJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-ia32-msvc": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.77.0.tgz", + "integrity": "sha512-D3SMXWBkVogzAlzd3RfMaFuHOTdPpRDFT+jVbtXszWwck9PCK4hYoRoncjuAjWZuWzRFND3/Mk91qFvJyoJbLA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-x64-msvc": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.77.0.tgz", + "integrity": "sha512-2vyyODjP1Sb830rTVgfFqZoIUYF8uYdGx9S/Usih+Av6gQ9QyxXzwEGXS7poxfsxxQftZW1IbcFlhvQkeDRekQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, "node_modules/@pkgr/core": { "version": "0.3.6", "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz", @@ -5456,6 +5804,62 @@ "@oxc-resolver/binding-win32-x64-msvc": "11.24.2" } }, + "node_modules/oxfmt": { + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.77.0.tgz", + "integrity": "sha512-3bPDJwLZf4i6dOaQS+6GOI/YUFTHNif7qw4nknbZyzdB0uws57tD8jA/GLGC9J7kjyf6d/eVWm73b43VeMUqGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinypool": "2.2.0" + }, + "bin": { + "oxfmt": "bin/oxfmt" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + }, + "optionalDependencies": { + "@oxfmt/binding-android-arm-eabi": "0.77.0", + "@oxfmt/binding-android-arm64": "0.77.0", + "@oxfmt/binding-darwin-arm64": "0.77.0", + "@oxfmt/binding-darwin-x64": "0.77.0", + "@oxfmt/binding-freebsd-x64": "0.77.0", + "@oxfmt/binding-linux-arm-gnueabihf": "0.77.0", + "@oxfmt/binding-linux-arm-musleabihf": "0.77.0", + "@oxfmt/binding-linux-arm64-gnu": "0.77.0", + "@oxfmt/binding-linux-arm64-musl": "0.77.0", + "@oxfmt/binding-linux-ppc64-gnu": "0.77.0", + "@oxfmt/binding-linux-riscv64-gnu": "0.77.0", + "@oxfmt/binding-linux-riscv64-musl": "0.77.0", + "@oxfmt/binding-linux-s390x-gnu": "0.77.0", + "@oxfmt/binding-linux-x64-gnu": "0.77.0", + "@oxfmt/binding-linux-x64-musl": "0.77.0", + "@oxfmt/binding-openharmony-arm64": "0.77.0", + "@oxfmt/binding-win32-arm64-msvc": "0.77.0", + "@oxfmt/binding-win32-ia32-msvc": "0.77.0", + "@oxfmt/binding-win32-x64-msvc": "0.77.0" + }, + "peerDependencies": { + "@astrojs/compiler-rs": "^0.5.0", + "svelte": "^5.0.0", + "vite-plus": "*" + }, + "peerDependenciesMeta": { + "@astrojs/compiler-rs": { + "optional": true + }, + "svelte": { + "optional": true + }, + "vite-plus": { + "optional": true + } + } + }, "node_modules/p-limit": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", @@ -5997,6 +6401,16 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinypool": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.2.0.tgz", + "integrity": "sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.0.0 || >=22.0.0" + } + }, "node_modules/tinyrainbow": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz", diff --git a/package.json b/package.json index 7fba90f4..9fd2a673 100644 --- a/package.json +++ b/package.json @@ -30,8 +30,7 @@ "build": "cp -r src dist", "commit": "git-cz", "dev": "./src/cli.js", - "format": "prettier . --write", - "format:check": "prettier . --check", + "format": "oxfmt", "knip": "knip", "lint": "eslint .", "prepare": "simple-git-hooks", @@ -47,10 +46,7 @@ "pre-commit": "npx lint-staged" }, "lint-staged": { - "*.js": [ - "prettier --write" - ], - "!(*.js)": "prettier --ignore-unknown --write" + "*": "oxfmt --no-error-on-unmatched-pattern" }, "config": { "commitizen": { @@ -80,6 +76,7 @@ "knip": "^6.10.0", "lint-staged": "^17.6.0", "nock": "^15.0.5", + "oxfmt": "^0.77.0", "prettier": "^3.8.1", "simple-git-hooks": "^2.14.0", "vitest": "^5.1.0" diff --git a/release-please-config.json b/release-please-config.json index 6b49288d..a5e67505 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -6,22 +6,22 @@ "release-type": "node", "include-component-in-tag": false, "changelog-sections": [ - {"type": "feat", "section": "๐Ÿš€ New Features", "hidden": false}, - {"type": "enh", "section": "๐Ÿ’… Enhancements", "hidden": false}, - {"type": "fix", "section": "๐Ÿ”ฅ Bug Fixes", "hidden": false}, + { "type": "feat", "section": "๐Ÿš€ New Features", "hidden": false }, + { "type": "enh", "section": "๐Ÿ’… Enhancements", "hidden": false }, + { "type": "fix", "section": "๐Ÿ”ฅ Bug Fixes", "hidden": false }, { "type": "perf", "section": "๐Ÿƒ Performance Improvements", "hidden": false }, - {"type": "revert", "section": "โ†ฉ๏ธ Reverts", "hidden": true}, - {"type": "docs", "section": "๐Ÿ“š Documentation", "hidden": false}, - {"type": "style", "section": "๐ŸŽจ Chores", "hidden": false}, - {"type": "chore", "section": "โš™๏ธ Chores", "hidden": false}, - {"type": "refactor", "section": "โŒจ๏ธ Code Refactoring", "hidden": false}, - {"type": "test", "section": "๐Ÿงช Testing", "hidden": false}, - {"type": "build", "section": "๐Ÿ› ๏ธ Build System", "hidden": false}, - {"type": "ci", "section": "๐Ÿ“ฆ CI Improvements", "hidden": false} + { "type": "revert", "section": "โ†ฉ๏ธ Reverts", "hidden": true }, + { "type": "docs", "section": "๐Ÿ“š Documentation", "hidden": false }, + { "type": "style", "section": "๐ŸŽจ Chores", "hidden": false }, + { "type": "chore", "section": "โš™๏ธ Chores", "hidden": false }, + { "type": "refactor", "section": "โŒจ๏ธ Code Refactoring", "hidden": false }, + { "type": "test", "section": "๐Ÿงช Testing", "hidden": false }, + { "type": "build", "section": "๐Ÿ› ๏ธ Build System", "hidden": false }, + { "type": "ci", "section": "๐Ÿ“ฆ CI Improvements", "hidden": false } ] } } diff --git a/src/api.js b/src/api.js index 7feaa022..ac9e6d3d 100644 --- a/src/api.js +++ b/src/api.js @@ -3,11 +3,11 @@ // This is to support adding contributors using the AllContributors GitHub Bot (see github.com/all-contributors/all-contributors-bot // These Node API's are intended to be network and side effect free, everything should be in memory with no io to network/disk -import * as YoctoColors from 'yoctocolors' +import * as YoctoColors from 'yoctocolors'; -import {addContributorWithDetails} from './contributors/addWithDetails.js' -import {generate} from './generate/index.js' -import {addBadge, addContributorsList} from './init/init-content.js' +import { addContributorWithDetails } from './contributors/addWithDetails.js'; +import { generate } from './generate/index.js'; +import { addBadge, addContributorsList } from './init/init-content.js'; process.stdout.write( YoctoColors.yellow( @@ -15,9 +15,9 @@ process.stdout.write( 'WARNING', )} :: Using the all-contributors node-api comes with zero guarantees of stability and may contain breaking changes without warning\n`, ), -) +); -export const initContributorsList = addContributorsList -export const initBadge = addBadge +export const initContributorsList = addContributorsList; +export const initBadge = addBadge; -export {addContributorWithDetails, generate} +export { addContributorWithDetails, generate }; diff --git a/src/cli.js b/src/cli.js index 9c28f9f8..395fc36e 100755 --- a/src/cli.js +++ b/src/cli.js @@ -1,20 +1,21 @@ #!/usr/bin/env node -import {promises as fs} from 'fs' -import inquirer from 'inquirer' -import path from 'path' -import yargs from 'yargs' -import {hideBin} from 'yargs/helpers' -import * as YoctoColors from 'yoctocolors' - -import {addContributor} from './contributors/index.js' -import {generate} from './generate/index.js' -import {init} from './init/index.js' -import * as repo from './repo/index.js' -import * as util from './util/index.js' - -const cwd = process.cwd() -const defaultRCFile = path.join(cwd, '.all-contributorsrc') +import { promises as fs } from 'fs'; +import path from 'path'; + +import inquirer from 'inquirer'; +import yargs from 'yargs'; +import { hideBin } from 'yargs/helpers'; +import * as YoctoColors from 'yoctocolors'; + +import { addContributor } from './contributors/index.js'; +import { generate } from './generate/index.js'; +import { init } from './init/index.js'; +import * as repo from './repo/index.js'; +import * as util from './util/index.js'; + +const cwd = process.cwd(); +const defaultRCFile = path.join(cwd, '.all-contributorsrc'); function getArgs() { return yargs(hideBin(process.argv)) @@ -28,18 +29,14 @@ function getArgs() { .option('contributorsSortAlphabetically', { type: 'boolean', default: false, - description: - 'Sort the list of contributors alphabetically in the generated list', + description: 'Sort the list of contributors alphabetically in the generated list', }) .help('help') .alias('h', 'help') .alias('v', 'version') .version() .recommendCommands() - .command( - 'generate', - `Generate the list of contributors\n\nUSAGE: all-contributors generate`, - ) + .command('generate', `Generate the list of contributors\n\nUSAGE: all-contributors generate`) .command( 'add', `Add a new contributor\n\nUSAGE: all-contributors add `, @@ -55,84 +52,70 @@ function getArgs() { .boolean('commit') .default('files', ['README.md']) .default('contributorsPerLine', 7) - .default('contributors', []).argv + .default('contributors', []).argv; } async function startGeneration(argv) { await Promise.all( - argv.files.map(async file => { - const filePath = path.join(cwd, file) - const fileContent = await fs.readFile(filePath, 'utf8') - const newFileContent = generate(argv, argv.contributors, fileContent) + argv.files.map(async (file) => { + const filePath = path.join(cwd, file); + const fileContent = await fs.readFile(filePath, 'utf8'); + const newFileContent = generate(argv, argv.contributors, fileContent); - await fs.writeFile(filePath, newFileContent) + await fs.writeFile(filePath, newFileContent); }), - ) + ); } async function addContribution(argv) { - const username = argv._[1] === undefined ? undefined : String(argv._[1]) - const contributions = argv._[2] + const username = argv._[1] === undefined ? undefined : String(argv._[1]); + const contributions = argv._[2]; // Add or update contributor in the config file - const data = await addContributor(argv, username, contributions) + const data = await addContributor(argv, username, contributions); - argv.contributors = data.contributors + argv.contributors = data.contributors; - await startGeneration(argv) + await startGeneration(argv); // Commit if configured if (argv.commit) { - return util.git.commit(argv, data) + return util.git.commit(argv, data); } } async function checkContributors(argv) { return repo - .getContributors( - argv.projectOwner, - argv.projectName, - argv.repoType, - argv.repoHost, - ) - .then(repoContributors => { - const checkKey = repo.getCheckKey(argv.repoType) + .getContributors(argv.projectOwner, argv.projectName, argv.repoType, argv.repoHost) + .then((repoContributors) => { + const checkKey = repo.getCheckKey(argv.repoType); const knownContributions = argv.contributors.reduce((obj, item) => { - obj[item[checkKey]] = item.contributions - return obj - }, {}) - const knownContributors = argv.contributors.map( - contributor => contributor[checkKey], - ) - - const missingInConfig = repoContributors.filter( - key => !knownContributors.includes(key), - ) - const missingFromRepo = knownContributors.filter(key => { + obj[item[checkKey]] = item.contributions; + return obj; + }, {}); + const knownContributors = argv.contributors.map((contributor) => contributor[checkKey]); + + const missingInConfig = repoContributors.filter((key) => !knownContributors.includes(key)); + const missingFromRepo = knownContributors.filter((key) => { return ( !repoContributors.includes(key) && - (knownContributions[key].includes('code') || - knownContributions[key].includes('test')) - ) - }) + (knownContributions[key].includes('code') || knownContributions[key].includes('test')) + ); + }); if (missingInConfig.length) { - process.stdout.write( - YoctoColors.bold('Missing contributors in .all-contributorsrc:\n'), - ) - process.stdout.write(`${missingInConfig.join(', ')}\n`) + process.stdout.write(YoctoColors.bold('Missing contributors in .all-contributorsrc:\n')); + process.stdout.write(`${missingInConfig.join(', ')}\n`); } if (missingFromRepo.length) { - process.stdout.write('\n') + process.stdout.write('\n'); process.stdout.write( - YoctoColors.bold( - 'Unknown contributors found in .all-contributorsrc:\n', - ), - ) - process.stdout.write(`${missingFromRepo.join(', ')}\n`) + YoctoColors.bold('Unknown contributors found in .all-contributorsrc:\n'), + ); + process.stdout.write(`${missingFromRepo.join(', ')}\n`); } - }) + }); } function promptForCommand(argv) { @@ -149,7 +132,7 @@ function promptForCommand(argv) { name: 'Compare contributors from the repository with the credited ones', value: 'check', }, - ] + ]; const questions = [ { type: 'select', @@ -159,46 +142,46 @@ function promptForCommand(argv) { when: !argv._[0], default: choices[0].value, }, - ] + ]; - return inquirer.prompt(questions).then(answers => { - return answers.command || argv._[0] - }) + return inquirer.prompt(questions).then((answers) => { + return answers.command || argv._[0]; + }); } async function run() { try { - const argv = getArgs() + const argv = getArgs(); // Load and merge config file data into argv try { - const configData = await util.configFile.readConfig(argv.config) - Object.assign(argv, configData) + const configData = await util.configFile.readConfig(argv.config); + Object.assign(argv, configData); } catch (error) { if (error instanceof SyntaxError || argv.config !== defaultRCFile) { - throw error + throw error; } // If default config file doesn't exist, that's okay } - const command = await promptForCommand(argv) + const command = await promptForCommand(argv); switch (command) { case 'init': - return init() + return init(); case 'generate': - return startGeneration(argv) + return startGeneration(argv); case 'add': - return addContribution(argv) + return addContribution(argv); case 'check': - return checkContributors(argv) + return checkContributors(argv); default: - throw new Error(`Unknown command ${command}`) + throw new Error(`Unknown command ${command}`); } } catch (e) { - console.error(e.stack || e.message || e) - process.exit(1) + console.error(e.stack || e.message || e); + process.exit(1); } } -run() +run(); diff --git a/src/contributors/__tests__/add.js b/src/contributors/__tests__/add.js index 527191f7..5b60d8e0 100644 --- a/src/contributors/__tests__/add.js +++ b/src/contributors/__tests__/add.js @@ -1,7 +1,7 @@ -import {expect, test, vi} from 'vitest' +import { expect, test, vi } from 'vitest'; -import {add} from '../add.js' -import fixtures from './fixtures/index.js' +import { add } from '../add.js'; +import fixtures from './fixtures/index.js'; /** * Mock function that simulates fetching contributor info from an API. @@ -16,7 +16,7 @@ function mockInfoFetcher(username) { name: 'Some name', avatar_url: 'www.avatar.url', profile: 'www.profile.url', - }) + }); } /** @@ -36,184 +36,159 @@ function caseFixtures() { contributions: ['code'], }, ], - } - return {options} + }; + return { options }; } test('callback with error if infoFetcher fails', async () => { - const {options} = fixtures() - const username = 'login3' - const contributions = ['doc'] - const error = new Error('infoFetcher error') + const { options } = fixtures(); + const username = 'login3'; + const contributions = ['doc']; + const error = new Error('infoFetcher error'); function infoFetcher() { - return Promise.reject(error) + return Promise.reject(error); } - const resolvedError = await add( - options, - username, - contributions, - infoFetcher, - ).catch(e => e) + const resolvedError = await add(options, username, contributions, infoFetcher).catch((e) => e); - expect(resolvedError).toBe(error) -}) + expect(resolvedError).toBe(error); +}); test('calls infoFetcher with (username, options.repoType, options.repoHost) when adding new contributor', async () => { - const {options} = fixtures() - options.repoType = 'github' - options.repoHost = 'https://github.com' - const username = 'newuser' - const contributions = ['doc'] + const { options } = fixtures(); + options.repoType = 'github'; + options.repoHost = 'https://github.com'; + const username = 'newuser'; + const contributions = ['doc']; const infoFetcher = vi.fn().mockResolvedValue({ login: username, name: 'New User', avatar_url: '', profile: '', - }) + }); - await add(options, username, contributions, infoFetcher) + await add(options, username, contributions, infoFetcher); - expect(infoFetcher).toHaveBeenCalledWith( - username, - 'github', - 'https://github.com', - ) -}) + expect(infoFetcher).toHaveBeenCalledWith(username, 'github', 'https://github.com'); +}); test('add new contributor at the end of the list of contributors', () => { - const {options} = fixtures() - const username = 'login3' - const contributions = ['doc'] - - return add(options, username, contributions, mockInfoFetcher).then( - contributors => { - expect(contributors).toHaveLength(options.contributors.length + 1) - expect(contributors[options.contributors.length]).toEqual({ - login: 'login3', - name: 'Some name', - avatar_url: 'www.avatar.url', - profile: 'www.profile.url', - contributions: ['doc'], - }) - }, - ) -}) + const { options } = fixtures(); + const username = 'login3'; + const contributions = ['doc']; + + return add(options, username, contributions, mockInfoFetcher).then((contributors) => { + expect(contributors).toHaveLength(options.contributors.length + 1); + expect(contributors[options.contributors.length]).toEqual({ + login: 'login3', + name: 'Some name', + avatar_url: 'www.avatar.url', + profile: 'www.profile.url', + contributions: ['doc'], + }); + }); +}); test('add new contributor at the end of the list of contributors with a url link', () => { - const {options} = fixtures() - const username = 'login3' - const contributions = ['doc'] - options.url = 'www.foo.bar' - - return add(options, username, contributions, mockInfoFetcher).then( - contributors => { - expect(contributors).toHaveLength(options.contributors.length + 1) - expect(contributors[options.contributors.length]).toEqual({ - login: 'login3', - name: 'Some name', - avatar_url: 'www.avatar.url', - profile: 'www.profile.url', - contributions: [{type: 'doc', url: 'www.foo.bar'}], - }) - }, - ) -}) + const { options } = fixtures(); + const username = 'login3'; + const contributions = ['doc']; + options.url = 'www.foo.bar'; + + return add(options, username, contributions, mockInfoFetcher).then((contributors) => { + expect(contributors).toHaveLength(options.contributors.length + 1); + expect(contributors[options.contributors.length]).toEqual({ + login: 'login3', + name: 'Some name', + avatar_url: 'www.avatar.url', + profile: 'www.profile.url', + contributions: [{ type: 'doc', url: 'www.foo.bar' }], + }); + }); +}); test(`should not update an existing contributor's contributions where nothing has changed`, () => { - const {options} = fixtures() - const username = 'login2' - const contributions = ['blog', 'code'] + const { options } = fixtures(); + const username = 'login2'; + const contributions = ['blog', 'code']; - return add(options, username, contributions, mockInfoFetcher).then( - contributors => { - expect(contributors).toEqual(options.contributors) - }, - ) -}) + return add(options, username, contributions, mockInfoFetcher).then((contributors) => { + expect(contributors).toEqual(options.contributors); + }); +}); test(`should not update an existing contributor's contributions where nothing has changed but the casing`, () => { - const {options} = caseFixtures() - const username = 'login1' - const contributions = ['code'] + const { options } = caseFixtures(); + const username = 'login1'; + const contributions = ['code']; - return add(options, username, contributions, mockInfoFetcher).then( - contributors => { - expect(contributors).toEqual(options.contributors) - }, - ) -}) + return add(options, username, contributions, mockInfoFetcher).then((contributors) => { + expect(contributors).toEqual(options.contributors); + }); +}); test(`should update an existing contributor's contributions if a new type is added`, () => { - const {options} = fixtures() - const username = 'login1' - const contributions = ['bug'] - return add(options, username, contributions, mockInfoFetcher).then( - contributors => { - expect(contributors).toHaveLength(options.contributors.length) - expect(contributors[0]).toEqual({ - login: 'login1', - name: 'Some name', - avatar_url: 'www.avatar.url', - profile: 'www.profile.url', - contributions: ['code', 'bug'], - }) - }, - ) -}) + const { options } = fixtures(); + const username = 'login1'; + const contributions = ['bug']; + return add(options, username, contributions, mockInfoFetcher).then((contributors) => { + expect(contributors).toHaveLength(options.contributors.length); + expect(contributors[0]).toEqual({ + login: 'login1', + name: 'Some name', + avatar_url: 'www.avatar.url', + profile: 'www.profile.url', + contributions: ['code', 'bug'], + }); + }); +}); test(`should update an existing contributor's contributions if a new type is added with different username case`, () => { - const {options} = caseFixtures() - const username = 'login1' - const contributions = ['bug'] - return add(options, username, contributions, mockInfoFetcher).then( - contributors => { - expect(contributors).toHaveLength(1) - expect(contributors[0]).toEqual({ - login: 'Login1', - name: 'Some name', - avatar_url: 'www.avatar.url', - profile: 'www.profile.url', - contributions: ['code', 'bug'], - }) - }, - ) -}) + const { options } = caseFixtures(); + const username = 'login1'; + const contributions = ['bug']; + return add(options, username, contributions, mockInfoFetcher).then((contributors) => { + expect(contributors).toHaveLength(1); + expect(contributors[0]).toEqual({ + login: 'Login1', + name: 'Some name', + avatar_url: 'www.avatar.url', + profile: 'www.profile.url', + contributions: ['code', 'bug'], + }); + }); +}); test(`should update an existing contributor's contributions if a new type is added with a link`, () => { - const {options} = fixtures() - const username = 'login1' - const contributions = ['bug'] - options.url = 'www.foo.bar' - - return add(options, username, contributions, mockInfoFetcher).then( - contributors => { - expect(contributors).toHaveLength(options.contributors.length) - expect(contributors[0]).toEqual({ - login: 'login1', - name: 'Some name', - avatar_url: 'www.avatar.url', - profile: 'www.profile.url', - contributions: ['code', {type: 'bug', url: 'www.foo.bar'}], - }) - }, - ) -}) + const { options } = fixtures(); + const username = 'login1'; + const contributions = ['bug']; + options.url = 'www.foo.bar'; + + return add(options, username, contributions, mockInfoFetcher).then((contributors) => { + expect(contributors).toHaveLength(options.contributors.length); + expect(contributors[0]).toEqual({ + login: 'login1', + name: 'Some name', + avatar_url: 'www.avatar.url', + profile: 'www.profile.url', + contributions: ['code', { type: 'bug', url: 'www.foo.bar' }], + }); + }); +}); test(`should update an existing contributor's contributions if an existing type is removed`, () => { - const {options} = fixtures() - const username = 'login2' - const contributions = ['code'] - - return add(options, username, contributions, mockInfoFetcher).then( - contributors => { - expect(contributors).toHaveLength(options.contributors.length) - expect(contributors[1]).toEqual({ - login: 'login2', - name: 'Some name', - avatar_url: 'www.avatar.url', - profile: 'www.profile.url', - contributions: ['code'], - }) - }, - ) -}) + const { options } = fixtures(); + const username = 'login2'; + const contributions = ['code']; + + return add(options, username, contributions, mockInfoFetcher).then((contributors) => { + expect(contributors).toHaveLength(options.contributors.length); + expect(contributors[1]).toEqual({ + login: 'login2', + name: 'Some name', + avatar_url: 'www.avatar.url', + profile: 'www.profile.url', + contributions: ['code'], + }); + }); +}); diff --git a/src/contributors/__tests__/addWithDetails.js b/src/contributors/__tests__/addWithDetails.js index bab1384f..8238491d 100644 --- a/src/contributors/__tests__/addWithDetails.js +++ b/src/contributors/__tests__/addWithDetails.js @@ -1,17 +1,17 @@ -import {expect, test} from 'vitest' +import { expect, test } from 'vitest'; -import {addContributorWithDetails} from '../addWithDetails.js' -import fixtures from './fixtures/index.js' +import { addContributorWithDetails } from '../addWithDetails.js'; +import fixtures from './fixtures/index.js'; test('add new contributor without going to the network', async () => { - const {options} = fixtures() + const { options } = fixtures(); const userDetails = { login: 'jakebolam', contributions: ['code', 'security'], name: 'Jake Bolam', avatar_url: 'my-avatar.example.com', profile: 'jakebolam.com', - } + }; const contributors = await addContributorWithDetails({ options, @@ -20,8 +20,8 @@ test('add new contributor without going to the network', async () => { name: userDetails.name, avatar_url: userDetails.avatar_url, profile: userDetails.profile, - }) + }); - expect(contributors).toHaveLength(options.contributors.length + 1) - expect(contributors[options.contributors.length]).toEqual(userDetails) -}) + expect(contributors).toHaveLength(options.contributors.length + 1); + expect(contributors[options.contributors.length]).toEqual(userDetails); +}); diff --git a/src/contributors/__tests__/fixtures/index.js b/src/contributors/__tests__/fixtures/index.js index 6940fcc7..b0ee368c 100644 --- a/src/contributors/__tests__/fixtures/index.js +++ b/src/contributors/__tests__/fixtures/index.js @@ -1,8 +1,8 @@ -import contributors from './contributors.json' +import contributors from './contributors.json'; export default function fixtures() { const options = { contributors, - } - return {options} + }; + return { options }; } diff --git a/src/contributors/__tests__/prompt.js b/src/contributors/__tests__/prompt.js index d69e061f..cf7c524f 100644 --- a/src/contributors/__tests__/prompt.js +++ b/src/contributors/__tests__/prompt.js @@ -1,6 +1,6 @@ -import {expect, test} from 'vitest' +import { expect, test } from 'vitest'; -import {getQuestions, prompt} from '../prompt.js' +import { getQuestions, prompt } from '../prompt.js'; function fixtures() { const options = { @@ -28,90 +28,87 @@ function fixtures() { contributions: [], }, ], - } - return options + }; + return options; } test(`should throw error if all contribution types are invalid`, () => { - const options = fixtures() - const username = 'userName' - const contributions = 'invalidContributionType1,invalidContributionType2' + const options = fixtures(); + const username = 'userName'; + const contributions = 'invalidContributionType1,invalidContributionType2'; expect(() => prompt(options, username, contributions)).toThrow( 'invalidContributionType1,invalidContributionType2 is/are invalid contribution type(s)', - ) -}) + ); +}); test(`should not throw error if atleast one of the contribution types is valid`, () => { - const options = fixtures() - const username = 'userName' - const contributions = 'wrongContributionType,code' - return prompt(options, username, contributions).then(answers => { - expect(answers).toEqual({username: 'userName', contributions: ['code']}) - }) -}) + const options = fixtures(); + const username = 'userName'; + const contributions = 'wrongContributionType,code'; + return prompt(options, username, contributions).then((answers) => { + expect(answers).toEqual({ username: 'userName', contributions: ['code'] }); + }); +}); test(`should filter valid contribution types from user inserted types`, () => { - const options = fixtures() - const username = 'userName' - const contributions = - 'invalidContributionType1,code,invalidContributionType2,bug' - return prompt(options, username, contributions).then(answers => { - expect(answers.contributions).toHaveLength(2) - expect(answers.contributions).toEqual(['code', 'bug']) - }) -}) + const options = fixtures(); + const username = 'userName'; + const contributions = 'invalidContributionType1,code,invalidContributionType2,bug'; + return prompt(options, username, contributions).then((answers) => { + expect(answers.contributions).toHaveLength(2); + expect(answers.contributions).toEqual(['code', 'bug']); + }); +}); test(`should prompt for contributions when username is provided but contributions are undefined`, () => { - const options = fixtures() - const username = 'userName' - const contributions = undefined + const options = fixtures(); + const username = 'userName'; + const contributions = undefined; - const questions = getQuestions(options, username, contributions) - const contributionsQuestion = questions.find(q => q.name === 'contributions') + const questions = getQuestions(options, username, contributions); + const contributionsQuestion = questions.find((q) => q.name === 'contributions'); - expect(contributionsQuestion).toBeDefined() - expect(contributionsQuestion.message).toBe('What are the contribution types?') -}) + expect(contributionsQuestion).toBeDefined(); + expect(contributionsQuestion.message).toBe('What are the contribution types?'); +}); test(`should return prompt with username message when username and contributions are not provided`, () => { - const options = fixtures() - const username = undefined - const contributions = undefined - const questions = getQuestions(options, username, contributions) - const usernameQuestion = questions.find(q => q.name === 'username') - expect(usernameQuestion).toBeDefined() - expect(usernameQuestion.message).toBe( - "What is the contributor's GitHub username?", - ) -}) + const options = fixtures(); + const username = undefined; + const contributions = undefined; + const questions = getQuestions(options, username, contributions); + const usernameQuestion = questions.find((q) => q.name === 'username'); + expect(usernameQuestion).toBeDefined(); + expect(usernameQuestion.message).toBe("What is the contributor's GitHub username?"); +}); test(`username validation should return error when input is empty`, () => { - const options = fixtures() - const questions = getQuestions(options, undefined, undefined) - const usernameQuestion = questions.find(q => q.name === 'username') + const options = fixtures(); + const questions = getQuestions(options, undefined, undefined); + const usernameQuestion = questions.find((q) => q.name === 'username'); - const result = usernameQuestion.validate('') - expect(result).toBe('Username not provided') -}) + const result = usernameQuestion.validate(''); + expect(result).toBe('Username not provided'); +}); test(`username validation should return true when input is provided`, () => { - const options = fixtures() - const questions = getQuestions(options, undefined, undefined) - const usernameQuestion = questions.find(q => q.name === 'username') + const options = fixtures(); + const questions = getQuestions(options, undefined, undefined); + const usernameQuestion = questions.find((q) => q.name === 'username'); - const result = usernameQuestion.validate('lwasser') - expect(result).toBe(true) -}) + const result = usernameQuestion.validate('lwasser'); + expect(result).toBe(true); +}); test(`contributions validation should return error when no contributions selected`, () => { - const options = fixtures() - const questions = getQuestions(options, 'userName', undefined) - const contributionsQuestion = questions.find(q => q.name === 'contributions') + const options = fixtures(); + const questions = getQuestions(options, 'userName', undefined); + const contributionsQuestion = questions.find((q) => q.name === 'contributions'); // Simulate user selecting nothing (empty array) - const result = contributionsQuestion.validate([], {username: 'userName'}) - expect(result).toBe('Use space to select at least one contribution type.') -}) + const result = contributionsQuestion.validate([], { username: 'userName' }); + expect(result).toBe('Use space to select at least one contribution type.'); +}); test(`contributions validation should return error when selection matches previous contributions`, () => { const options = { @@ -123,28 +120,26 @@ test(`contributions validation should return error when selection matches previo contributions: ['code', 'doc'], // Existing contributions }, ], - } + }; - const questions = getQuestions(options, 'jfmengels', undefined) - const contributionsQuestion = questions.find(q => q.name === 'contributions') + const questions = getQuestions(options, 'jfmengels', undefined); + const contributionsQuestion = questions.find((q) => q.name === 'contributions'); // The user's contrib types already existing in the all-contribs file const result = contributionsQuestion.validate(['code', 'doc'], { username: 'jfmengels', - }) - expect(result).toBe( - 'Nothing changed, use space to select contribution types.', - ) -}) + }); + expect(result).toBe('Nothing changed, use space to select contribution types.'); +}); test(`contributions validation should return true when valid selection is made`, () => { - const options = fixtures() - const questions = getQuestions(options, 'userName', undefined) - const contributionsQuestion = questions.find(q => q.name === 'contributions') + const options = fixtures(); + const questions = getQuestions(options, 'userName', undefined); + const contributionsQuestion = questions.find((q) => q.name === 'contributions'); // Simulate user selecting valid contributions const result = contributionsQuestion.validate(['code', 'doc'], { username: 'userName', - }) - expect(result).toBe(true) -}) + }); + expect(result).toBe(true); +}); diff --git a/src/contributors/add.js b/src/contributors/add.js index 3f0c544b..558a5c20 100644 --- a/src/contributors/add.js +++ b/src/contributors/add.js @@ -1,83 +1,66 @@ function uniqueTypes(contribution) { - return contribution.type || contribution + return contribution.type || contribution; } function formatContributions(options, existing = [], types) { - const same = types.filter(type => - existing.some( - existingType => uniqueTypes(existingType) === uniqueTypes(type), - ), - ) - const remove = types.length < existing.length && same.length + const same = types.filter((type) => + existing.some((existingType) => uniqueTypes(existingType) === uniqueTypes(type)), + ); + const remove = types.length < existing.length && same.length; if (options.url) { return existing.concat( - types.map(type => { - return {type, url: options.url} + types.map((type) => { + return { type, url: options.url }; }), - ) + ); } if (remove) { - return same + return same; } - const combined = existing.concat(types) + const combined = existing.concat(types); return combined.filter( (item, index, arr) => - index === - arr.findIndex(other => uniqueTypes(other) === uniqueTypes(item)), - ) + index === arr.findIndex((other) => uniqueTypes(other) === uniqueTypes(item)), + ); } function updateContributor(options, contributor, contributions) { return { ...contributor, - contributions: formatContributions( - options, - contributor.contributions, - contributions, - ), - } + contributions: formatContributions(options, contributor.contributions, contributions), + }; } function updateExistingContributor(options, username, contributions) { - return options.contributors.map(contributor => { - if ( - !contributor.login || - username.toLowerCase() !== contributor.login.toLowerCase() - ) { - return contributor + return options.contributors.map((contributor) => { + if (!contributor.login || username.toLowerCase() !== contributor.login.toLowerCase()) { + return contributor; } - return updateContributor(options, contributor, contributions) - }) + return updateContributor(options, contributor, contributions); + }); } function addNewContributor(options, username, contributions, infoFetcher) { - return infoFetcher(username, options.repoType, options.repoHost).then( - userData => { - const contributor = { - ...userData, - contributions: formatContributions(options, [], contributions), - } - return options.contributors.concat(contributor) - }, - ) + return infoFetcher(username, options.repoType, options.repoHost).then((userData) => { + const contributor = { + ...userData, + contributions: formatContributions(options, [], contributions), + }; + return options.contributors.concat(contributor); + }); } export function add(options, username, contributions, infoFetcher) { // case insensitive find - const exists = options.contributors.find(contributor => { - return ( - contributor.login && - contributor.login.toLowerCase() === username.toLowerCase() - ) - }) + const exists = options.contributors.find((contributor) => { + return contributor.login && contributor.login.toLowerCase() === username.toLowerCase(); + }); if (exists) { - return Promise.resolve( - updateExistingContributor(options, username, contributions), - ) + return Promise.resolve(updateExistingContributor(options, username, contributions)); } - return addNewContributor(options, username, contributions, infoFetcher) + return addNewContributor(options, username, contributions, infoFetcher); } diff --git a/src/contributors/addWithDetails.js b/src/contributors/addWithDetails.js index 7a379b25..bcbe43c4 100644 --- a/src/contributors/addWithDetails.js +++ b/src/contributors/addWithDetails.js @@ -1,4 +1,4 @@ -import {add} from './add.js' +import { add } from './add.js'; // Adds a contributor without going to the network (you supply the additional fields) export function addContributorWithDetails({ @@ -15,7 +15,7 @@ export function addContributorWithDetails({ name, avatar_url, profile, - }) - } - return add(options, login, contributions, infoFetcherNoNetwork) + }); + }; + return add(options, login, contributions, infoFetcherNoNetwork); } diff --git a/src/contributors/index.js b/src/contributors/index.js index a84d4dab..7248ed34 100644 --- a/src/contributors/index.js +++ b/src/contributors/index.js @@ -1,35 +1,30 @@ -import * as repo from '../repo/index.js' -import * as util from '../util/index.js' -import {add} from './add.js' -import {prompt} from './prompt.js' +import * as repo from '../repo/index.js'; +import * as util from '../util/index.js'; +import { add } from './add.js'; +import { prompt } from './prompt.js'; function isNewContributor(contributorList, username) { - return !contributorList.find(contributor => contributor.login === username) + return !contributorList.find((contributor) => contributor.login === username); } export function addContributor(options, username, contributions) { - const answersP = prompt(options, username, contributions) - const contributorsP = answersP.then(answers => + const answersP = prompt(options, username, contributions); + const contributorsP = answersP.then((answers) => add(options, answers.username, answers.contributions, repo.getUserInfo), - ) + ); - const writeContributorsP = contributorsP.then(contributors => + const writeContributorsP = contributorsP.then((contributors) => util.configFile.writeContributors(options.config, contributors), - ) + ); - return Promise.all([answersP, contributorsP, writeContributorsP]).then( - res => { - const answers = res[0] - const contributors = res[1] - return { - username: answers.username, - contributions: answers.contributions, - contributors, - newContributor: isNewContributor( - options.contributors, - answers.username, - ), - } - }, - ) + return Promise.all([answersP, contributorsP, writeContributorsP]).then((res) => { + const answers = res[0]; + const contributors = res[1]; + return { + username: answers.username, + contributions: answers.contributions, + contributors, + newContributor: isNewContributor(options.contributors, answers.username), + }; + }); } diff --git a/src/contributors/prompt.js b/src/contributors/prompt.js index 2bca0706..6b407710 100644 --- a/src/contributors/prompt.js +++ b/src/contributors/prompt.js @@ -1,18 +1,16 @@ -import inquirer from 'inquirer' +import inquirer from 'inquirer'; -import * as repo from '../repo/index.js' -import * as util from '../util/index.js' +import * as repo from '../repo/index.js'; +import * as util from '../util/index.js'; function contributionChoices(options) { - const types = util.contributionTypes(options) - const pairs = Object.entries(types) - const sorted = pairs.sort((a, b) => - a[1].description.localeCompare(b[1].description), - ) - return sorted.map(pair => ({ + const types = util.contributionTypes(options); + const pairs = Object.entries(types); + const sorted = pairs.sort((a, b) => a[1].description.localeCompare(b[1].description)); + return sorted.map((pair) => ({ name: `${pair[1].symbol} ${pair[1].description}`, value: pair[0], - })) + })); } export function getQuestions(options, username, contributions) { @@ -20,15 +18,13 @@ export function getQuestions(options, username, contributions) { { type: 'input', name: 'username', - message: `What is the contributor's ${repo.getTypeName( - options.repoType, - )} username?`, + message: `What is the contributor's ${repo.getTypeName(options.repoType)} username?`, when: !username, validate: function validate(input) { if (!input) { - return 'Username not provided' + return 'Username not provided'; } - return true + return true; }, }, { @@ -38,74 +34,57 @@ export function getQuestions(options, username, contributions) { when: !contributions, default: function (answers) { // default values for contributions when updating existing users - answers.username = answers.username || username + answers.username = answers.username || username; return options.contributors .filter( - entry => - entry.login && - entry.login.toLowerCase() === answers.username.toLowerCase(), - ) - .reduce( - (allEntries, entry) => allEntries.concat(entry.contributions), - [], + (entry) => entry.login && entry.login.toLowerCase() === answers.username.toLowerCase(), ) + .reduce((allEntries, entry) => allEntries.concat(entry.contributions), []); }, choices: contributionChoices(options), validate: function (input, answers) { - answers.username = answers.username || username + answers.username = answers.username || username; const previousContributions = options.contributors .filter( - entry => - entry.login && - entry.login.toLowerCase() === answers.username.toLowerCase(), - ) - .reduce( - (allEntries, entry) => allEntries.concat(entry.contributions), - [], + (entry) => entry.login && entry.login.toLowerCase() === answers.username.toLowerCase(), ) + .reduce((allEntries, entry) => allEntries.concat(entry.contributions), []); if (!input.length) { - return 'Use space to select at least one contribution type.' - } else if ( - JSON.stringify(input.sort()) === - JSON.stringify(previousContributions.sort()) - ) { - return 'Nothing changed, use space to select contribution types.' + return 'Use space to select at least one contribution type.'; + } else if (JSON.stringify(input.sort()) === JSON.stringify(previousContributions.sort())) { + return 'Nothing changed, use space to select contribution types.'; } - return true + return true; }, }, - ] + ]; } function getValidUserContributions(options, contributions) { - const validContributionTypes = util.contributionTypes(options) - const userContributions = contributions && contributions.split(',') + const validContributionTypes = util.contributionTypes(options); + const userContributions = contributions && contributions.split(','); const validUserContributions = userContributions.filter( - userContribution => validContributionTypes[userContribution] !== undefined, - ) + (userContribution) => validContributionTypes[userContribution] !== undefined, + ); const invalidUserContributions = userContributions.filter( - userContribution => validContributionTypes[userContribution] === undefined, - ) + (userContribution) => validContributionTypes[userContribution] === undefined, + ); if (validUserContributions.length === 0) { - throw new Error( - `${invalidUserContributions.toString()} is/are invalid contribution type(s)`, - ) + throw new Error(`${invalidUserContributions.toString()} is/are invalid contribution type(s)`); } - return validUserContributions + return validUserContributions; } export function prompt(options, username, contributions) { const defaults = { username, contributions: - contributions === undefined - ? [] - : getValidUserContributions(options, contributions), - } - const questions = getQuestions(options, username, contributions) - return inquirer.prompt(questions).then(answers => ({...defaults, ...answers})) + contributions === undefined ? [] : getValidUserContributions(options, contributions), + }; + const questions = getQuestions(options, username, contributions); + return inquirer.prompt(questions).then((answers) => ({ ...defaults, ...answers })); } diff --git a/src/generate/__tests__/format-badge.js b/src/generate/__tests__/format-badge.js index bccaec96..68f0903f 100644 --- a/src/generate/__tests__/format-badge.js +++ b/src/generate/__tests__/format-badge.js @@ -1,25 +1,23 @@ -import {expect, test} from 'vitest' +import { expect, test } from 'vitest'; -import {formatBadge} from '../format-badge.js' +import { formatBadge } from '../format-badge.js'; test('return badge with the number of contributors', () => { - const options = {} + const options = {}; const expected8 = - '[![All Contributors](https://img.shields.io/badge/all_contributors-8-orange.svg?style=flat-square)](#contributors-)' + '[![All Contributors](https://img.shields.io/badge/all_contributors-8-orange.svg?style=flat-square)](#contributors-)'; const expected16 = - '[![All Contributors](https://img.shields.io/badge/all_contributors-16-orange.svg?style=flat-square)](#contributors-)' + '[![All Contributors](https://img.shields.io/badge/all_contributors-16-orange.svg?style=flat-square)](#contributors-)'; - expect(formatBadge(options, Array(8).fill({}))).toBe(expected8) - expect(formatBadge(options, Array(16).fill({}))).toBe(expected16) -}) + expect(formatBadge(options, Array(8).fill({}))).toBe(expected8); + expect(formatBadge(options, Array(16).fill({}))).toBe(expected16); +}); test('be able to specify custom badge template', () => { const options = { badgeTemplate: 'We have <%= contributors.length %> contributors', - } + }; - expect(formatBadge(options, Array(8).fill({}))).toBe('We have 8 contributors') - expect(formatBadge(options, Array(16).fill({}))).toBe( - 'We have 16 contributors', - ) -}) + expect(formatBadge(options, Array(8).fill({}))).toBe('We have 8 contributors'); + expect(formatBadge(options, Array(16).fill({}))).toBe('We have 16 contributors'); +}); diff --git a/src/generate/__tests__/format-contribution-type.js b/src/generate/__tests__/format-contribution-type.js index 1a4d9313..7ad36b62 100644 --- a/src/generate/__tests__/format-contribution-type.js +++ b/src/generate/__tests__/format-contribution-type.js @@ -1,7 +1,7 @@ -import {expect, test} from 'vitest' +import { expect, test } from 'vitest'; -import {formatContributionType} from '../format-contribution-type.js' -import contributors from './fixtures/contributors.json' +import { formatContributionType } from '../format-contribution-type.js'; +import contributors from './fixtures/contributors.json'; const fixtures = () => { const options = { @@ -10,167 +10,167 @@ const fixtures = () => { repoType: 'github', repoHost: 'https://github.com', imageSize: 100, - } - return {options} -} + }; + return { options }; +}; test('return corresponding symbol', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() + const contributor = contributors.kentcdodds; + const { options } = fixtures(); expect(formatContributionType(options, contributor, 'tool')).toBe( '๐Ÿ”ง', - ) + ); expect(formatContributionType(options, contributor, 'question')).toBe( '๐Ÿ’ฌ', - ) -}) + ); +}); test('return link to commits', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() + const contributor = contributors.kentcdodds; + const { options } = fixtures(); const expectedLink = - 'https://github.com/all-contributors/all-contributors-cli/commits?author=kentcdodds' + 'https://github.com/all-contributors/all-contributors-cli/commits?author=kentcdodds'; expect(formatContributionType(options, contributor, 'code')).toBe( `๐Ÿ’ป`, - ) + ); expect(formatContributionType(options, contributor, 'doc')).toBe( `๐Ÿ“–`, - ) + ); expect(formatContributionType(options, contributor, 'test')).toBe( `โš ๏ธ`, - ) -}) + ); +}); test('return link to issues', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() + const contributor = contributors.kentcdodds; + const { options } = fixtures(); const expected = - '๐Ÿ›' + '๐Ÿ›'; - expect(formatContributionType(options, contributor, 'bug')).toBe(expected) -}) + expect(formatContributionType(options, contributor, 'bug')).toBe(expected); +}); test('return link to reviews', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() + const contributor = contributors.kentcdodds; + const { options } = fixtures(); const expected = - '๐Ÿ‘€' + '๐Ÿ‘€'; - expect(formatContributionType(options, contributor, 'review')).toBe(expected) -}) + expect(formatContributionType(options, contributor, 'review')).toBe(expected); +}); test('make any symbol into a link if contribution is an object', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() + const contributor = contributors.kentcdodds; + const { options } = fixtures(); const contribution = { type: 'tool', url: 'www.foo.bar', - } + }; expect(formatContributionType(options, contributor, contribution)).toBe( '๐Ÿ”ง', - ) -}) + ); +}); test('override url for given types', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() + const contributor = contributors.kentcdodds; + const { options } = fixtures(); const contribution = { type: 'code', url: 'www.foo.bar', - } + }; expect(formatContributionType(options, contributor, contribution)).toBe( '๐Ÿ’ป', - ) -}) + ); +}); test('be able to add types to the symbol list', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() + const contributor = contributors.kentcdodds; + const { options } = fixtures(); options.types = { - cheerful: {symbol: ':smiley:'}, - } + cheerful: { symbol: ':smiley:' }, + }; expect(formatContributionType(options, contributor, 'cheerful')).toBe( ':smiley:', - ) + ); expect( formatContributionType(options, contributor, { type: 'cheerful', url: 'www.foo.bar', }), - ).toBe(':smiley:') -}) + ).toBe(':smiley:'); +}); test('be able to add types with template to the symbol list', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() + const contributor = contributors.kentcdodds; + const { options } = fixtures(); options.types = { web: { symbol: ':web:', link: 'www.<%= contributor.login %>.com', }, - } + }; expect(formatContributionType(options, contributor, 'web')).toBe( ':web:', - ) -}) + ); +}); test('be able to override existing types', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() + const contributor = contributors.kentcdodds; + const { options } = fixtures(); options.types = { - code: {symbol: ':smiley:'}, - } + code: { symbol: ':smiley:' }, + }; expect(formatContributionType(options, contributor, 'code')).toBe( ':smiley:', - ) + ); expect( formatContributionType(options, contributor, { type: 'code', url: 'www.foo.bar', }), - ).toBe(':smiley:') -}) + ).toBe(':smiley:'); +}); test('be able to override existing templates', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() + const contributor = contributors.kentcdodds; + const { options } = fixtures(); options.types = { code: { symbol: ':web:', link: 'www.<%= contributor.login %>.com', }, - } + }; expect(formatContributionType(options, contributor, 'code')).toBe( ':web:', - ) + ); expect( formatContributionType(options, contributor, { type: 'code', url: 'www.foo.bar', }), - ).toBe(':web:') -}) + ).toBe(':web:'); +}); test('throw a helpful error on unknown type', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() + const contributor = contributors.kentcdodds; + const { options } = fixtures(); expect(() => formatContributionType(options, contributor, 'docs')).toThrow( 'Unknown contribution type docs for contributor kentcdodds', - ) -}) + ); +}); test('throw a helpful error on unknown type and no login', () => { - const contributor = contributors.nologin_badrole - const {options} = fixtures() + const contributor = contributors.nologin_badrole; + const { options } = fixtures(); expect(() => formatContributionType(options, contributor, 'docs')).toThrow( 'Unknown contribution type docs for contributor Wildly Misconfigured', - ) -}) + ); +}); diff --git a/src/generate/__tests__/format-contributor.js b/src/generate/__tests__/format-contributor.js index 129db8d9..caf1bf4b 100644 --- a/src/generate/__tests__/format-contributor.js +++ b/src/generate/__tests__/format-contributor.js @@ -1,7 +1,7 @@ -import {expect, test} from 'vitest' +import { expect, test } from 'vitest'; -import {formatContributor} from '../format-contributor.js' -import contributors from './fixtures/contributors.json' +import { formatContributor } from '../format-contributor.js'; +import contributors from './fixtures/contributors.json'; function fixtures() { const options = { @@ -10,105 +10,105 @@ function fixtures() { repoType: 'github', repoHost: 'https://github.com', imageSize: 150, - } - return {options} + }; + return { options }; } test('format a simple contributor', () => { const contributor = { ...contributors.kentcdodds, contributions: ['review'], - } - const {options} = fixtures() + }; + const { options } = fixtures(); const expected = - 'Kent C. Dodds
Kent C. Dodds

๐Ÿ‘€' + 'Kent C. Dodds
Kent C. Dodds

๐Ÿ‘€'; - expect(formatContributor(options, contributor)).toBe(expected) -}) + expect(formatContributor(options, contributor)).toBe(expected); +}); test('format contributor with complex contribution types', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() + const contributor = contributors.kentcdodds; + const { options } = fixtures(); const expected = - 'Kent C. Dodds
Kent C. Dodds

๐Ÿ“– ๐Ÿ‘€ ๐Ÿ’ฌ' + 'Kent C. Dodds
Kent C. Dodds

๐Ÿ“– ๐Ÿ‘€ ๐Ÿ’ฌ'; - expect(formatContributor(options, contributor)).toBe(expected) -}) + expect(formatContributor(options, contributor)).toBe(expected); +}); test('format contributor using custom template', () => { - const contributor = contributors.kentcdodds - const {options} = fixtures() - options.contributorTemplate = '<%= contributor.name %> is awesome!' + const contributor = contributors.kentcdodds; + const { options } = fixtures(); + options.contributorTemplate = '<%= contributor.name %> is awesome!'; - const expected = 'Kent C. Dodds is awesome!' + const expected = 'Kent C. Dodds is awesome!'; - expect(formatContributor(options, contributor)).toBe(expected) -}) + expect(formatContributor(options, contributor)).toBe(expected); +}); test('default image size to 100', () => { const contributor = { ...contributors.kentcdodds, contributions: ['review'], - } - const {options} = fixtures() - delete options.imageSize + }; + const { options } = fixtures(); + delete options.imageSize; const expected = - 'Kent C. Dodds
Kent C. Dodds

๐Ÿ‘€' + 'Kent C. Dodds
Kent C. Dodds

๐Ÿ‘€'; - expect(formatContributor(options, contributor)).toBe(expected) -}) + expect(formatContributor(options, contributor)).toBe(expected); +}); test('format contributor with pipes in their name', () => { - const contributor = contributors.pipey - const {options} = fixtures() + const contributor = contributors.pipey; + const { options } = fixtures(); const expected = - 'Who | Needs | Pipes?
Who | Needs | Pipes?

๐Ÿ“–' + 'Who | Needs | Pipes?
Who | Needs | Pipes?

๐Ÿ“–'; - expect(formatContributor(options, contributor)).toBe(expected) -}) + expect(formatContributor(options, contributor)).toBe(expected); +}); test('format contributor with no GitHub account', () => { - const contributor = contributors.nologin - const {options} = fixtures() + const contributor = contributors.nologin; + const { options } = fixtures(); const expected = - 'No Github Account
No Github Account
๐ŸŒ' + 'No Github Account
No Github Account
๐ŸŒ'; - expect(formatContributor(options, contributor)).toBe(expected) -}) + expect(formatContributor(options, contributor)).toBe(expected); +}); test('format contributor with no complete name', () => { - const contributor = contributors.nocompletename - const {options} = fixtures() + const contributor = contributors.nocompletename; + const { options } = fixtures(); const expected = - 'nocompletename
nocompletename
๐ŸŒ' + 'nocompletename
nocompletename
๐ŸŒ'; - expect(formatContributor(options, contributor)).toBe(expected) -}) + expect(formatContributor(options, contributor)).toBe(expected); +}); test('format contributor with quotes in name', () => { - const contributor = contributors.name_with_quotes - const {options} = fixtures() + const contributor = contributors.name_with_quotes; + const { options } = fixtures(); const expected = - 'Name "Nickname" Lastname
Name "Nickname" Lastname

๐Ÿ“–' - expect(formatContributor(options, contributor)).toBe(expected) -}) + 'Name "Nickname" Lastname
Name "Nickname" Lastname

๐Ÿ“–'; + expect(formatContributor(options, contributor)).toBe(expected); +}); test('format contributor with a relative avatar url', () => { const contributor = { ...contributors.nologin, avatar_url: './assets/avatar.png', - } - const {options} = fixtures() + }; + const { options } = fixtures(); const expected = - 'No Github Account
No Github Account
๐ŸŒ' + 'No Github Account
No Github Account
๐ŸŒ'; - expect(formatContributor(options, contributor)).toBe(expected) -}) + expect(formatContributor(options, contributor)).toBe(expected); +}); diff --git a/src/generate/__tests__/index.js b/src/generate/__tests__/index.js index a1997e2c..b6f6343d 100644 --- a/src/generate/__tests__/index.js +++ b/src/generate/__tests__/index.js @@ -1,7 +1,7 @@ -import {expect, test} from 'vitest' +import { expect, test } from 'vitest'; -import {generate} from '../index.js' -import contributors from './fixtures/contributors.json' +import { generate } from '../index.js'; +import contributors from './fixtures/contributors.json'; /** * Returns test fixtures including options, sample contributor, and markdown content. @@ -18,7 +18,7 @@ function fixtures() { contributorsPerLine: 5, contributors, contributorTemplate: '<%= contributor.name %> is awesome!', - } + }; const jfmengels = { login: 'jfmengels', @@ -26,7 +26,7 @@ function fixtures() { html_url: 'https://github.com/jfmengels', avatar_url: 'https://avatars.githubusercontent.com/u/3869412?v=3', contributions: ['doc'], - } + }; const content = [ '# project', @@ -38,69 +38,59 @@ function fixtures() { 'FOO BAR BAZ', '', 'Thanks a lot everyone!', - ].join('\n') + ].join('\n'); - return {options, jfmengels, content} + return { options, jfmengels, content }; } test('throws when contributors is undefined (caller must await and pass resolved array)', () => { - const {options, content} = fixtures() - expect(() => generate(options, undefined, content)).toThrow( - 'contributors must be an array', - ) -}) + const { options, content } = fixtures(); + expect(() => generate(options, undefined, content)).toThrow('contributors must be an array'); +}); test('replace the content between the ALL-CONTRIBUTORS-LIST tags by a table of contributors', () => { - const {kentcdodds, bogas04} = contributors - const {options, jfmengels, content} = fixtures() - const contributorList = [kentcdodds, bogas04, jfmengels] - const result = generate(options, contributorList, content) + const { kentcdodds, bogas04 } = contributors; + const { options, jfmengels, content } = fixtures(); + const contributorList = [kentcdodds, bogas04, jfmengels]; + const result = generate(options, contributorList, content); - expect(result).toMatchSnapshot() -}) + expect(result).toMatchSnapshot(); +}); test('replace the content between the ALL-CONTRIBUTORS-LIST tags by a table of contributors with linkToUsage', () => { - const {kentcdodds, bogas04} = contributors - const {options, jfmengels, content} = fixtures() - const contributorList = [kentcdodds, bogas04, jfmengels] - const result = generate( - Object.assign(options, {linkToUsage: true}), - contributorList, - content, - ) + const { kentcdodds, bogas04 } = contributors; + const { options, jfmengels, content } = fixtures(); + const contributorList = [kentcdodds, bogas04, jfmengels]; + const result = generate(Object.assign(options, { linkToUsage: true }), contributorList, content); - expect(result).toMatchSnapshot() -}) + expect(result).toMatchSnapshot(); +}); test('replace the content between the ALL-CONTRIBUTORS-LIST tags by a table of contributors without linkToUsage', () => { - const {kentcdodds, bogas04} = contributors - const {options, jfmengels, content} = fixtures() - const contributorList = [kentcdodds, bogas04, jfmengels] - const result = generate( - Object.assign(options, {linkToUsage: false}), - contributorList, - content, - ) + const { kentcdodds, bogas04 } = contributors; + const { options, jfmengels, content } = fixtures(); + const contributorList = [kentcdodds, bogas04, jfmengels]; + const result = generate(Object.assign(options, { linkToUsage: false }), contributorList, content); - expect(result).toMatchSnapshot() -}) + expect(result).toMatchSnapshot(); +}); test('replace the content between the ALL-CONTRIBUTORS-LIST tags by a custom wrapper around the list of contributors contained in the "bodyContent" tag', () => { - const {kentcdodds, bogas04} = contributors - const {options, jfmengels, content} = fixtures() - const contributorList = [kentcdodds, bogas04, jfmengels] + const { kentcdodds, bogas04 } = contributors; + const { options, jfmengels, content } = fixtures(); + const contributorList = [kentcdodds, bogas04, jfmengels]; const result = generate( - Object.assign(options, {wrapperTemplate: '

<%= bodyContent %>

'}), + Object.assign(options, { wrapperTemplate: '

<%= bodyContent %>

' }), contributorList, content, - ) + ); - expect(result).toMatchSnapshot() -}) + expect(result).toMatchSnapshot(); +}); test('split contributors into multiples lines when there are too many', () => { - const {kentcdodds} = contributors - const {options, content} = fixtures() + const { kentcdodds } = contributors; + const { options, content } = fixtures(); const contributorList = [ kentcdodds, kentcdodds, @@ -109,15 +99,15 @@ test('split contributors into multiples lines when there are too many', () => { kentcdodds, kentcdodds, kentcdodds, - ] - const result = generate(options, contributorList, content) + ]; + const result = generate(options, contributorList, content); - expect(result).toMatchSnapshot() -}) + expect(result).toMatchSnapshot(); +}); test('split contributors into multiples lines when there are too many with linkToUsage', () => { - const {kentcdodds} = contributors - const {options, content} = fixtures() + const { kentcdodds } = contributors; + const { options, content } = fixtures(); const contributorList = [ kentcdodds, kentcdodds, @@ -126,39 +116,27 @@ test('split contributors into multiples lines when there are too many with linkT kentcdodds, kentcdodds, kentcdodds, - ] - const result = generate( - Object.assign(options, {linkToUsage: true}), - contributorList, - content, - ) + ]; + const result = generate(Object.assign(options, { linkToUsage: true }), contributorList, content); - expect(result).toMatchSnapshot() -}) + expect(result).toMatchSnapshot(); +}); test('sorts the list of contributors if contributorsSortAlphabetically=true', () => { - const {kentcdodds, bogas04} = contributors - const {options, jfmengels, content} = fixtures() + const { kentcdodds, bogas04 } = contributors; + const { options, jfmengels, content } = fixtures(); - const resultPreSorted = generate( - options, - [bogas04, jfmengels, kentcdodds], - content, - ) + const resultPreSorted = generate(options, [bogas04, jfmengels, kentcdodds], content); - options.contributorsSortAlphabetically = true - const resultAutoSorted = generate( - options, - [jfmengels, kentcdodds, bogas04], - content, - ) + options.contributorsSortAlphabetically = true; + const resultAutoSorted = generate(options, [jfmengels, kentcdodds, bogas04], content); - expect(resultPreSorted).toEqual(resultAutoSorted) -}) + expect(resultPreSorted).toEqual(resultAutoSorted); +}); test('sorts the list of contributors case-insensitively when contributorsSortAlphabetically=true', () => { - const {options, content} = fixtures() - options.contributorsSortAlphabetically = true + const { options, content } = fixtures(); + options.contributorsSortAlphabetically = true; const contributorA = { login: 'adam', @@ -166,86 +144,76 @@ test('sorts the list of contributors case-insensitively when contributorsSortAlp avatar_url: 'https://avatars.githubusercontent.com/u/1', profile: 'https://github.com/adam', contributions: ['doc'], - } + }; const contributorB = { login: 'Bob', name: 'Bob', avatar_url: 'https://avatars.githubusercontent.com/u/2', profile: 'https://github.com/Bob', contributions: ['code'], - } + }; const contributorC = { login: 'charlie', name: 'charlie', avatar_url: 'https://avatars.githubusercontent.com/u/3', profile: 'https://github.com/charlie', contributions: ['bug'], - } + }; - const resultAutoSorted = generate( - options, - [contributorB, contributorC, contributorA], - content, - ) + const resultAutoSorted = generate(options, [contributorB, contributorC, contributorA], content); const resultExpected = generate( - {...options, contributorsSortAlphabetically: false}, + { ...options, contributorsSortAlphabetically: false }, [contributorA, contributorB, contributorC], content, - ) + ); - expect(resultAutoSorted).toEqual(resultExpected) -}) + expect(resultAutoSorted).toEqual(resultExpected); +}); test('sorts contributors falling back to login when name is not provided', () => { - const {options, content} = fixtures() - options.contributorsSortAlphabetically = true + const { options, content } = fixtures(); + options.contributorsSortAlphabetically = true; const contributorNoNameA = { login: 'alice', avatar_url: 'https://avatars.githubusercontent.com/u/1', profile: 'https://github.com/alice', contributions: ['doc'], - } + }; const contributorWithNameB = { login: 'bob_user', name: 'Bob', avatar_url: 'https://avatars.githubusercontent.com/u/2', profile: 'https://github.com/bob_user', contributions: ['code'], - } + }; - const resultAutoSorted = generate( - options, - [contributorWithNameB, contributorNoNameA], - content, - ) + const resultAutoSorted = generate(options, [contributorWithNameB, contributorNoNameA], content); const resultExpected = generate( - {...options, contributorsSortAlphabetically: false}, + { ...options, contributorsSortAlphabetically: false }, [contributorNoNameA, contributorWithNameB], content, - ) + ); - expect(resultAutoSorted).toEqual(resultExpected) -}) + expect(resultAutoSorted).toEqual(resultExpected); +}); test('not inject anything if there is no tags to inject content in', () => { - const {kentcdodds} = contributors - const {options} = fixtures() - const contributorList = [kentcdodds] - const content = ['# project', '', 'Description', '', 'License: MIT'].join( - '\n', - ) + const { kentcdodds } = contributors; + const { options } = fixtures(); + const contributorList = [kentcdodds]; + const content = ['# project', '', 'Description', '', 'License: MIT'].join('\n'); - const result = generate(options, contributorList, content) - expect(result).toBe(content) -}) + const result = generate(options, contributorList, content); + expect(result).toBe(content); +}); test('not inject anything if start tag is malformed', () => { - const {kentcdodds} = contributors - const {options} = fixtures() - const contributorList = [kentcdodds] + const { kentcdodds } = contributors; + const { options } = fixtures(); + const contributorList = [kentcdodds]; const content = [ '# project', '', @@ -254,16 +222,16 @@ test('not inject anything if start tag is malformed', () => { '', '', 'License: MIT', - ].join('\n') + ].join('\n'); - const result = generate(options, contributorList, content) - expect(result).toBe(content) -}) + const result = generate(options, contributorList, content); + expect(result).toBe(content); +}); test('not inject anything if end tag is malformed', () => { - const {kentcdodds} = contributors - const {options} = fixtures() - const contributorList = [kentcdodds] + const { kentcdodds } = contributors; + const { options } = fixtures(); + const contributorList = [kentcdodds]; const content = [ '# project', '', @@ -272,15 +240,15 @@ test('not inject anything if end tag is malformed', () => { '', '', 'License: MIT', - ].join('\n') + ].join('\n'); - const result = generate(options, contributorList, content) - expect(result).toBe(content) -}) + const result = generate(options, contributorList, content); + expect(result).toBe(content); +}); test('inject nothing if there are no contributors', () => { - const {options, content} = fixtures() - const contributorList = [] + const { options, content } = fixtures(); + const contributorList = []; const expected = [ '# project', '', @@ -297,17 +265,17 @@ test('inject nothing if there are no contributors', () => { '', '', 'Thanks a lot everyone!', - ].join('\n') + ].join('\n'); - const result = generate(options, contributorList, content) + const result = generate(options, contributorList, content); - expect(result).toBe(expected) -}) + expect(result).toBe(expected); +}); test('replace all-contributors badge if present', () => { - const {kentcdodds} = contributors - const {options} = fixtures() - const contributorList = [kentcdodds] + const { kentcdodds } = contributors; + const { options } = fixtures(); + const contributorList = [kentcdodds]; const content = [ '# project', '', @@ -321,7 +289,7 @@ test('replace all-contributors badge if present', () => { ].join(''), '', 'License: MIT', - ].join('\n') + ].join('\n'); const expected = [ '# project', '', @@ -335,44 +303,44 @@ test('replace all-contributors badge if present', () => { ].join(''), '', 'License: MIT', - ].join('\n') + ].join('\n'); - const result = generate(options, contributorList, content) + const result = generate(options, contributorList, content); - expect(result).toBe(expected) -}) + expect(result).toBe(expected); +}); test('validate if cell width attribute is floored correctly', () => { - const {kentcdodds} = contributors - const {options, content} = fixtures() - const contributorList = [kentcdodds, kentcdodds, kentcdodds] + const { kentcdodds } = contributors; + const { options, content } = fixtures(); + const contributorList = [kentcdodds, kentcdodds, kentcdodds]; - options.contributorsPerLine = 7 - const result = generate(options, contributorList, content) + options.contributorsPerLine = 7; + const result = generate(options, contributorList, content); - expect(result).toMatchSnapshot() -}) + expect(result).toMatchSnapshot(); +}); test('inject the table when the ALL-CONTRIBUTORS-LIST tag starts the file', () => { - const {kentcdodds, bogas04} = contributors - const {options} = fixtures() - const contributorList = [kentcdodds, bogas04] + const { kentcdodds, bogas04 } = contributors; + const { options } = fixtures(); + const contributorList = [kentcdodds, bogas04]; const content = [ 'FOO BAR BAZ', '', 'Thanks a lot everyone!', - ].join('\n') + ].join('\n'); - const result = generate(options, contributorList, content) + const result = generate(options, contributorList, content); - expect(result).toContain('') - expect(result).toContain('') - expect(result).not.toContain('FOO BAR BAZ') -}) + expect(result).toContain('
'); + expect(result).toContain(''); + expect(result).not.toContain('FOO BAR BAZ'); +}); test('does not re-add markdownlint comments to a generated list that had them removed', () => { - const {kentcdodds} = contributors - const {options} = fixtures() + const { kentcdodds } = contributors; + const { options } = fixtures(); const content = [ '', '', @@ -381,17 +349,17 @@ test('does not re-add markdownlint comments to a generated list that had them re '', '', '', - ].join('\n') + ].join('\n'); - const result = generate(options, [kentcdodds], content) + const result = generate(options, [kentcdodds], content); - expect(result).not.toContain('markdownlint') - expect(result).toContain('
\n\n\n\n') -}) + expect(result).not.toContain('markdownlint'); + expect(result).toContain('\n\n\n\n'); +}); test('keeps markdownlint comments in a generated list that has them', () => { - const {kentcdodds} = contributors - const {options} = fixtures() + const { kentcdodds } = contributors; + const { options } = fixtures(); const content = [ '', '', @@ -402,35 +370,35 @@ test('keeps markdownlint comments in a generated list that has them', () => { '', '', '', - ].join('\n') + ].join('\n'); - const result = generate(options, [kentcdodds], content) + const result = generate(options, [kentcdodds], content); expect(result).toContain( '\n\n', - ) + ); expect(result).toContain( '
\n\n\n', - ) -}) + ); +}); test('adds markdownlint comments to a new list by default', () => { - const {kentcdodds} = contributors - const {options, content} = fixtures() + const { kentcdodds } = contributors; + const { options, content } = fixtures(); - const result = generate(options, [kentcdodds], content) + const result = generate(options, [kentcdodds], content); expect(result).toContain( '\n\n', - ) + ); expect(result).toContain( '
\n\n\n', - ) -}) + ); +}); test('adds markdownlint comments to a generated list that had them removed when withMarkdownlint=true', () => { - const {kentcdodds} = contributors - const {options} = fixtures() + const { kentcdodds } = contributors; + const { options } = fixtures(); const content = [ '', '', @@ -439,18 +407,18 @@ test('adds markdownlint comments to a generated list that had them removed when '', '', '', - ].join('\n') + ].join('\n'); const result = generate( - Object.assign(options, {withMarkdownlint: true}), + Object.assign(options, { withMarkdownlint: true }), [kentcdodds], content, - ) + ); expect(result).toContain( '\n\n', - ) + ); expect(result).toContain( '
\n\n\n', - ) -}) + ); +}); diff --git a/src/generate/format-badge.js b/src/generate/format-badge.js index 74c3d50d..46583f4f 100644 --- a/src/generate/format-badge.js +++ b/src/generate/format-badge.js @@ -1,10 +1,10 @@ -import * as util from '../util/index.js' +import * as util from '../util/index.js'; const defaultTemplate = - '[![All Contributors](https://img.shields.io/badge/all_contributors-<%= contributors.length %>-orange.svg?style=flat-square)](#contributors-)' + '[![All Contributors](https://img.shields.io/badge/all_contributors-<%= contributors.length %>-orange.svg?style=flat-square)](#contributors-)'; export function formatBadge(options, contributors) { return util.template(options.badgeTemplate || defaultTemplate)({ contributors, - }) + }); } diff --git a/src/generate/format-contribution-type.js b/src/generate/format-contribution-type.js index d95749ad..74a0e60d 100644 --- a/src/generate/format-contribution-type.js +++ b/src/generate/format-contribution-type.js @@ -1,23 +1,23 @@ -import * as util from '../util/index.js' +import * as util from '../util/index.js'; const linkTemplate = util.template( '<%= symbol %>', -) +); function getType(options, contribution) { - const types = util.contributionTypes(options) - return types[contribution.type || contribution] + const types = util.contributionTypes(options); + return types[contribution.type || contribution]; } export function formatContributionType(options, contributor, contribution) { - const type = getType(options, contribution) + const type = getType(options, contribution); if (!type) { throw new Error( `Unknown contribution type ${contribution} for contributor ${ contributor.login || contributor.name }`, - ) + ); } const templateData = { @@ -25,23 +25,23 @@ export function formatContributionType(options, contributor, contribution) { description: type.description || '', contributor, options, - } + }; - let url = getUrl(contribution, contributor) + let url = getUrl(contribution, contributor); if (contribution.url) { - url = contribution.url + url = contribution.url; } else if (type.link) { - url = util.template(type.link)(templateData) + url = util.template(type.link)(templateData); } - return linkTemplate({url, ...templateData}) + return linkTemplate({ url, ...templateData }); } function getUrl(contribution, contributor) { if (contributor.login) { - return `#${contribution}-${contributor.login}` + return `#${contribution}-${contributor.login}`; } else { - return `#${contribution}` + return `#${contribution}`; } } diff --git a/src/generate/format-contributor.js b/src/generate/format-contributor.js index 7d134f38..a256f88b 100644 --- a/src/generate/format-contributor.js +++ b/src/generate/format-contributor.js @@ -1,83 +1,73 @@ -import * as util from '../util/index.js' -import {formatContributionType} from './format-contribution-type.js' +import * as util from '../util/index.js'; +import { formatContributionType } from './format-contribution-type.js'; const avatarTemplate = util.template( '<%= name %>', -) +); const avatarBlockTemplate = util.template( '<%= avatar %>
<%= name %>
', -) +); const avatarBlockTemplateNoProfile = util.template( '<%= avatar %>
<%= name %>', -) -const contributorTemplate = util.template( - '<%= avatarBlock %>
<%= contributions %>', -) +); +const contributorTemplate = util.template('<%= avatarBlock %>
<%= contributions %>'); -const defaultImageSize = 100 +const defaultImageSize = 100; function defaultTemplate(templateData) { - const rawName = - templateData.contributor.name || templateData.contributor.login - const name = escapeName(rawName) + const rawName = templateData.contributor.name || templateData.contributor.login; + const name = escapeName(rawName); const avatar = avatarTemplate({ ...templateData, name, - }) + }); const avatarBlockTemplateData = { name, avatar, ...templateData, - } - let avatarBlock + }; + let avatarBlock; if (templateData.contributor.profile) { - avatarBlock = avatarBlockTemplate(avatarBlockTemplateData) + avatarBlock = avatarBlockTemplate(avatarBlockTemplateData); } else { - avatarBlock = avatarBlockTemplateNoProfile(avatarBlockTemplateData) + avatarBlock = avatarBlockTemplateNoProfile(avatarBlockTemplateData); } - return contributorTemplate({avatarBlock, ...templateData}) + return contributorTemplate({ avatarBlock, ...templateData }); } function escapeName(name) { - return name - .replace(new RegExp('\\|', 'g'), '|') - .replace(new RegExp('\\"', 'g'), '"') + return name.replace(new RegExp('\\|', 'g'), '|').replace(new RegExp('\\"', 'g'), '"'); } function formatAvatarUrl(avatarUrl, imageSize) { if (!URL.canParse(avatarUrl)) { - return avatarUrl + return avatarUrl; } - const url = new URL(avatarUrl) + const url = new URL(avatarUrl); - url.searchParams.append('size', imageSize) + url.searchParams.append('size', imageSize); - return url.toString() + return url.toString(); } export function formatContributor(options, contributor) { - const formatter = contribution => - formatContributionType(options, contributor, contribution) - const contributions = contributor.contributions.map(formatter).join(' ') + const formatter = (contribution) => formatContributionType(options, contributor, contribution); + const contributions = contributor.contributions.map(formatter).join(' '); const templateData = { contributions, contributor: { ...contributor, - avatar_url: formatAvatarUrl( - contributor.avatar_url, - options.imageSize ?? defaultImageSize, - ), + avatar_url: formatAvatarUrl(contributor.avatar_url, options.imageSize ?? defaultImageSize), }, - options: {imageSize: defaultImageSize, ...options}, - } + options: { imageSize: defaultImageSize, ...options }, + }; - const customTemplate = - options.contributorTemplate && util.template(options.contributorTemplate) + const customTemplate = options.contributorTemplate && util.template(options.contributorTemplate); - return (customTemplate || defaultTemplate)(templateData) + return (customTemplate || defaultTemplate)(templateData); } diff --git a/src/generate/index.js b/src/generate/index.js index c6cfeb41..15028cd8 100644 --- a/src/generate/index.js +++ b/src/generate/index.js @@ -1,57 +1,44 @@ -import * as util from '../util/index.js' -import {formatBadge} from './format-badge.js' -import {formatContributor} from './format-contributor.js' +import * as util from '../util/index.js'; +import { formatBadge } from './format-badge.js'; +import { formatContributor } from './format-contributor.js'; function chunk(array, size) { - const chunks = [] + const chunks = []; for (let i = 0; i < array.length; i += size) { - chunks.push(array.slice(i, i + size)) + chunks.push(array.slice(i, i + size)); } - return chunks + return chunks; } function injectListBetweenTags(newContent, options) { return function (previousContent) { - const tagToLookFor = `' - const startOfOpeningTagIndex = previousContent.indexOf( - `${tagToLookFor}START`, - ) - const endOfOpeningTagIndex = previousContent.indexOf( - closingTag, - startOfOpeningTagIndex, - ) + const tagToLookFor = `'; + const startOfOpeningTagIndex = previousContent.indexOf(`${tagToLookFor}START`); + const endOfOpeningTagIndex = previousContent.indexOf(closingTag, startOfOpeningTagIndex); const startOfClosingTagIndex = previousContent.indexOf( `${tagToLookFor}END`, endOfOpeningTagIndex, - ) + ); if ( startOfOpeningTagIndex === -1 || endOfOpeningTagIndex === -1 || startOfClosingTagIndex === -1 ) { - return previousContent + return previousContent; } - const startIndent = Math.max( - 0, - previousContent.lastIndexOf('\n', startOfOpeningTagIndex), - ) + const startIndent = Math.max(0, previousContent.lastIndexOf('\n', startOfOpeningTagIndex)); const nbSpaces = Math.max( 0, - startOfOpeningTagIndex - - Math.min(startOfOpeningTagIndex, startIndent) - - 1, - ) - const previousList = previousContent.slice( - endOfOpeningTagIndex, - startOfClosingTagIndex, - ) + startOfOpeningTagIndex - Math.min(startOfOpeningTagIndex, startIndent) - 1, + ); + const previousList = previousContent.slice(endOfOpeningTagIndex, startOfClosingTagIndex); const withMarkdownlint = options.withMarkdownlint === true || previousList.includes('') || // Lists without prettier-ignore-start were never generated // (e.g. hand-written tags), so they default to including markdownlint - !previousList.includes('') + !previousList.includes(''); return [ previousContent.slice(0, endOfOpeningTagIndex + closingTag.length), '\n', @@ -61,127 +48,111 @@ function injectListBetweenTags(newContent, options) { '', '\n\n', previousContent.slice(startOfClosingTagIndex), - ].join('') - } + ].join(''); + }; } function formatLine(options, contributors) { - const width = Math.floor((100 / options.contributorsPerLine) * 100) / 100 - const attributes = `align="center" valign="top" width="${width}%"` + const width = Math.floor((100 / options.contributorsPerLine) * 100) / 100; + const attributes = `align="center" valign="top" width="${width}%"`; - return `${contributors.join( - `\n `, - )}` + return `${contributors.join(`\n `)}`; } function formatFooter(options) { if (!options.linkToUsage) { - return '' + return ''; } const smallLogoURL = - 'https://raw.githubusercontent.com/all-contributors/all-contributors-cli/1b8533af435da9854653492b1327a23a4dbd0a10/assets/logo-small.svg' - const linkToBotAdd = 'https://all-contributors.js.org/docs/en/bot/usage' + 'https://raw.githubusercontent.com/all-contributors/all-contributors-cli/1b8533af435da9854653492b1327a23a4dbd0a10/assets/logo-small.svg'; + const linkToBotAdd = 'https://all-contributors.js.org/docs/en/bot/usage'; - return `\n \n \n Add your contributions\n \n \n ` + return `\n \n \n Add your contributions\n \n \n `; } function generateContributorsList(options, contributors) { - const tableFooter = formatFooter(options) + const tableFooter = formatFooter(options); const defaultWrapperTemplate = util.template( '\n\n <%= bodyContent %> \n<%= tableFooterContent %>
\n\n', - ) + ); const wrapperTemplate = options.wrapperTemplate ? util.template(`\n${options.wrapperTemplate}\n\n`) - : defaultWrapperTemplate + : defaultWrapperTemplate; const seperator = options.wrapperTemplate ? '\n
\n \n ' - : '\n \n \n ' + : '\n \n \n '; - let tableFooterContent = '' + let tableFooterContent = ''; - const sortedContributors = [...contributors] + const sortedContributors = [...contributors]; if (options.contributorsSortAlphabetically) { sortedContributors.sort((a, b) => { - const nameA = a.name || a.login || '' - const nameB = b.name || b.login || '' - return nameA.localeCompare(nameB, undefined, {sensitivity: 'base'}) - }) + const nameA = a.name || a.login || ''; + const nameB = b.name || b.login || ''; + return nameA.localeCompare(nameB, undefined, { sensitivity: 'base' }); + }); } - const formattedContributors = sortedContributors.map(contributor => + const formattedContributors = sortedContributors.map((contributor) => formatContributor(options, contributor), - ) + ); - const chunkedContributors = chunk( - formattedContributors, - options.contributorsPerLine, - ) + const chunkedContributors = chunk(formattedContributors, options.contributorsPerLine); - const formattedLines = chunkedContributors.map(currentLineContributors => + const formattedLines = chunkedContributors.map((currentLineContributors) => formatLine(options, currentLineContributors), - ) + ); - const newContent = formattedLines.join(seperator) + const newContent = formattedLines.join(seperator); if (options.linkToUsage) { - tableFooterContent = ` \n ${tableFooter}\n \n` + tableFooterContent = ` \n ${tableFooter}\n \n`; } - const bodyContent = `\n \n ${newContent}\n \n` + const bodyContent = `\n \n ${newContent}\n \n`; - return wrapperTemplate({bodyContent, tableFooterContent}) + return wrapperTemplate({ bodyContent, tableFooterContent }); } function replaceBadge(newContent) { return function (previousContent) { - const tagToLookFor = `' - const startOfOpeningTagIndex = previousContent.indexOf( - `${tagToLookFor}START`, - ) - const endOfOpeningTagIndex = previousContent.indexOf( - closingTag, - startOfOpeningTagIndex, - ) + const tagToLookFor = `'; + const startOfOpeningTagIndex = previousContent.indexOf(`${tagToLookFor}START`); + const endOfOpeningTagIndex = previousContent.indexOf(closingTag, startOfOpeningTagIndex); const startOfClosingTagIndex = previousContent.indexOf( `${tagToLookFor}END`, endOfOpeningTagIndex, - ) + ); if ( startOfOpeningTagIndex === -1 || endOfOpeningTagIndex === -1 || startOfClosingTagIndex === -1 ) { - return previousContent + return previousContent; } - const startIndent = Math.max( - 0, - previousContent.lastIndexOf('\n', startOfOpeningTagIndex), - ) - const nbSpaces = - startOfOpeningTagIndex - Math.min(startOfOpeningTagIndex, startIndent) + const startIndent = Math.max(0, previousContent.lastIndexOf('\n', startOfOpeningTagIndex)); + const nbSpaces = startOfOpeningTagIndex - Math.min(startOfOpeningTagIndex, startIndent); return [ previousContent.slice(0, endOfOpeningTagIndex + closingTag.length), '\n', newContent.replace('\n', `\n${' '.repeat(nbSpaces)}`), '\n', previousContent.slice(startOfClosingTagIndex), - ].join('') - } + ].join(''); + }; } export function generate(options, contributors, fileContent) { if (contributors === undefined || !Array.isArray(contributors)) { - throw new Error('contributors must be an array') + throw new Error('contributors must be an array'); } const contributorsList = - contributors.length === 0 - ? '\n' - : generateContributorsList(options, contributors) - const badge = formatBadge(options, contributors) - - let result = fileContent - result = injectListBetweenTags(contributorsList, options)(result) - result = replaceBadge(badge)(result) - return result + contributors.length === 0 ? '\n' : generateContributorsList(options, contributors); + const badge = formatBadge(options, contributors); + + let result = fileContent; + result = injectListBetweenTags(contributorsList, options)(result); + result = replaceBadge(badge)(result); + return result; } diff --git a/src/init/__tests__/init-content.js b/src/init/__tests__/init-content.js index c1a83519..bbf2cd93 100644 --- a/src/init/__tests__/init-content.js +++ b/src/init/__tests__/init-content.js @@ -1,10 +1,10 @@ -import {describe, expect, test} from 'vitest' +import { describe, expect, test } from 'vitest'; -import {addBadge, addContributorsList} from '../init-content.js' +import { addBadge, addContributorsList } from '../init-content.js'; describe('addBadge', () => { test('insert badge under title', () => { - const content = ['# project', '', 'Description', '', 'Foo bar'].join('\n') + const content = ['# project', '', 'Description', '', 'Foo bar'].join('\n'); const expected = [ '# project', '', @@ -14,54 +14,47 @@ describe('addBadge', () => { 'Description', '', 'Foo bar', - ].join('\n') + ].join('\n'); - const result = addBadge(content) + const result = addBadge(content); - expect(result).toBe(expected) - }) + expect(result).toBe(expected); + }); test('add badge if content is empty', () => { - const content = '' + const content = ''; const expected = [ '', '', '[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)', '', - ].join('\n') + ].join('\n'); - const result = addBadge(content) + const result = addBadge(content); - expect(result).toBe(expected) - }) -}) + expect(result).toBe(expected); + }); +}); describe('addContributorsList', () => { test('insert list under contributors section', () => { - const content = [ - '# project', - '', - 'Description', - '', - '## Contributors', - '', - ].join('\n') - const result = addContributorsList(content) + const content = ['# project', '', 'Description', '', '## Contributors', ''].join('\n'); + const result = addContributorsList(content); - expect(result).toMatchSnapshot() - }) + expect(result).toMatchSnapshot(); + }); test('create contributors section if it is absent', () => { - const content = ['# project', '', 'Description'].join('\n') - const result = addContributorsList(content) + const content = ['# project', '', 'Description'].join('\n'); + const result = addContributorsList(content); - expect(result).toMatchSnapshot() - }) + expect(result).toMatchSnapshot(); + }); test('create contributors section if content is empty', () => { - const content = '' - const result = addContributorsList(content) + const content = ''; + const result = addContributorsList(content); - expect(result).toMatchSnapshot() - }) -}) + expect(result).toMatchSnapshot(); + }); +}); diff --git a/src/init/__tests__/prompt.js b/src/init/__tests__/prompt.js index 9b663d3d..695826db 100644 --- a/src/init/__tests__/prompt.js +++ b/src/init/__tests__/prompt.js @@ -1,12 +1,12 @@ -import inquirer from 'inquirer' -import {expect, test} from 'vitest' +import inquirer from 'inquirer'; +import { expect, test } from 'vitest'; -import {questions} from '../prompt.js' +import { questions } from '../prompt.js'; test('uses only prompt types registered by inquirer', () => { - const registered = Object.keys(inquirer.prompt.prompts) + const registered = Object.keys(inquirer.prompt.prompts); const unknown = questions - .map(question => question.type) - .filter(type => type !== undefined && !registered.includes(type)) - expect(unknown).toEqual([]) -}) + .map((question) => question.type) + .filter((type) => type !== undefined && !registered.includes(type)); + expect(unknown).toEqual([]); +}); diff --git a/src/init/commit-conventions.js b/src/init/commit-conventions.js index cac27e4b..123cae6a 100644 --- a/src/init/commit-conventions.js +++ b/src/init/commit-conventions.js @@ -7,7 +7,7 @@ const conventions = { return msg.replace( /(^.*?) ([A-Z][a-z]+) \w*/, (_, ...words) => `${words[0]} ${words[1].toLowerCase()} `, - ) + ); }, }, atom: { @@ -34,10 +34,10 @@ const conventions = { name: 'None', msg: '', }, -} +}; -Object.keys(conventions).forEach(style => { - conventions[style].value = style -}) +Object.keys(conventions).forEach((style) => { + conventions[style].value = style; +}); -export {conventions} +export { conventions }; diff --git a/src/init/index.js b/src/init/index.js index d0107cad..9fdcf511 100644 --- a/src/init/index.js +++ b/src/init/index.js @@ -1,35 +1,35 @@ -import {promises as fs} from 'fs' +import { promises as fs } from 'fs'; -import {configFile} from '../util/index.js' -import {addBadge, addContributorsList} from './init-content.js' -import {prompt} from './prompt.js' +import { configFile } from '../util/index.js'; +import { addBadge, addContributorsList } from './init-content.js'; +import { prompt } from './prompt.js'; async function ensureFileExists(file) { try { - await fs.access(file) - return file + await fs.access(file); + return file; } catch { - await fs.writeFile(file, '') - return file + await fs.writeFile(file, ''); + return file; } } async function injectInFile(file, fn) { - const content = await fs.readFile(file, 'utf8') + const content = await fs.readFile(file, 'utf8'); - await fs.writeFile(file, fn(content)) + await fs.writeFile(file, fn(content)); } export async function init() { - const promptResult = await prompt() + const promptResult = await prompt(); - await configFile.writeConfig('.all-contributorsrc', promptResult.config) + await configFile.writeConfig('.all-contributorsrc', promptResult.config); - await ensureFileExists(promptResult.contributorFile) + await ensureFileExists(promptResult.contributorFile); - await injectInFile(promptResult.contributorFile, addContributorsList) + await injectInFile(promptResult.contributorFile, addContributorsList); if (promptResult.badgeFile) { - await injectInFile(promptResult.badgeFile, addBadge) + await injectInFile(promptResult.badgeFile, addBadge); } } diff --git a/src/init/init-content.js b/src/init/init-content.js index 7760305f..7b0e4898 100644 --- a/src/init/init-content.js +++ b/src/init/init-content.js @@ -2,10 +2,10 @@ const badgeContent = [ '', '[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)', '', -].join('\n') +].join('\n'); const headerContent = - 'Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/en/reference/emoji-key/)):' + 'Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/en/reference/emoji-key/)):'; const listContent = [ '', '', @@ -13,34 +13,32 @@ const listContent = [ '', '', '', -].join('\n') +].join('\n'); const footerContent = - 'This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!' + 'This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!'; function injectContentBetween(lines, content, startIndex, endIndex) { - return [].concat(lines.slice(0, startIndex), content, lines.slice(endIndex)) + return [].concat(lines.slice(0, startIndex), content, lines.slice(endIndex)); } function addBadgeImpl(lines) { - return injectContentBetween(lines, badgeContent, 1, 1) + return injectContentBetween(lines, badgeContent, 1, 1); } function splitAndRejoin(fn) { return function (content) { - const lines = content.split('\n') - const result = fn(lines) - return result.join('\n') - } + const lines = content.split('\n'); + const result = fn(lines); + return result.join('\n'); + }; } function findContributorsSection(lines) { - return lines.findIndex( - str => str.toLowerCase().indexOf('# contributors') === 1, - ) + return lines.findIndex((str) => str.toLowerCase().indexOf('# contributors') === 1); } function addContributorsListImpl(lines) { - const insertionLine = findContributorsSection(lines) + const insertionLine = findContributorsSection(lines); if (insertionLine === -1) { return lines.concat([ @@ -51,16 +49,11 @@ function addContributorsListImpl(lines) { listContent, '', footerContent, - ]) + ]); } - return injectContentBetween( - lines, - listContent, - insertionLine + 3, - insertionLine + 3, - ) + return injectContentBetween(lines, listContent, insertionLine + 3, insertionLine + 3); } -export const addBadge = splitAndRejoin(addBadgeImpl) -export const addContributorsList = splitAndRejoin(addContributorsListImpl) +export const addBadge = splitAndRejoin(addBadgeImpl); +export const addContributorsList = splitAndRejoin(addContributorsListImpl); diff --git a/src/init/prompt.js b/src/init/prompt.js index 524f007b..1d3079db 100644 --- a/src/init/prompt.js +++ b/src/init/prompt.js @@ -1,10 +1,10 @@ -import inquirer from 'inquirer' +import inquirer from 'inquirer'; -import {git} from '../util/index.js' -import {conventions} from './commit-conventions.js' +import { git } from '../util/index.js'; +import { conventions } from './commit-conventions.js'; function uniqueFiles(files) { - return [...new Set(files.filter(Boolean))] + return [...new Set(files.filter(Boolean))]; } export const questions = [ @@ -37,13 +37,12 @@ export const questions = [ { type: 'input', name: 'repoHost', - message: - "Where is the repository hosted? Hit Enter if it's on GitHub or GitLab", + message: "Where is the repository hosted? Hit Enter if it's on GitHub or GitLab", default: function (answers) { if (answers.repoType === 'github') { - return 'https://github.com' + return 'https://github.com'; } else if (answers.repoType === 'gitlab') { - return 'https://gitlab.com' + return 'https://gitlab.com'; } }, }, @@ -63,10 +62,10 @@ export const questions = [ name: 'badgeFile', message: 'In which file should the badge be shown?', when: function (answers) { - return answers.needBadge + return answers.needBadge; }, default: function (answers) { - return answers.contributorFile + return answers.contributorFile; }, }, { @@ -79,8 +78,7 @@ export const questions = [ { type: 'confirm', name: 'commit', - message: - 'Do you want this badge to auto-commit when contributors are added?', + message: 'Do you want this badge to auto-commit when contributors are added?', default: true, }, { @@ -96,19 +94,19 @@ export const questions = [ message: 'Do you want to add a footer with link to usage?', default: true, }, -] +]; export function prompt() { return git .getRepoInfo() - .then(repoInfo => { + .then((repoInfo) => { if (repoInfo) { - questions[0].default = repoInfo.projectName - questions[1].default = repoInfo.projectOwner + questions[0].default = repoInfo.projectName; + questions[1].default = repoInfo.projectOwner; } - return inquirer.prompt(questions) + return inquirer.prompt(questions); }) - .then(answers => { + .then((answers) => { return { config: { projectName: answers.projectName, @@ -125,6 +123,6 @@ export function prompt() { }, contributorFile: answers.contributorFile, badgeFile: answers.badgeFile, - } - }) + }; + }); } diff --git a/src/repo/__tests__/github.js b/src/repo/__tests__/github.js index a3a0aec6..22e3ae17 100644 --- a/src/repo/__tests__/github.js +++ b/src/repo/__tests__/github.js @@ -1,24 +1,22 @@ -import nock from 'nock' -import {beforeAll, expect, test} from 'vitest' +import nock from 'nock'; +import { beforeAll, expect, test } from 'vitest'; -import * as githubAPI from '../github.js' -import allContributorsCliResponse from './github/all-contributors.response.json' -import allContributorsCliTransformed from './github/all-contributors.transformed.json' -import reactNativeResponse1 from './github/react-native.response.1.json' -import reactNativeResponse2 from './github/react-native.response.2.json' -import reactNativeResponse3 from './github/react-native.response.3.json' -import reactNativeResponse4 from './github/react-native.response.4.json' -import reactNativeTransformed from './github/react-native.transformed.json' +import * as githubAPI from '../github.js'; +import allContributorsCliResponse from './github/all-contributors.response.json'; +import allContributorsCliTransformed from './github/all-contributors.transformed.json'; +import reactNativeResponse1 from './github/react-native.response.1.json'; +import reactNativeResponse2 from './github/react-native.response.2.json'; +import reactNativeResponse3 from './github/react-native.response.3.json'; +import reactNativeResponse4 from './github/react-native.response.4.json'; +import reactNativeTransformed from './github/react-native.transformed.json'; -const getUserInfo = githubAPI.getUserInfo -const check = githubAPI.getContributors +const getUserInfo = githubAPI.getUserInfo; +const check = githubAPI.getContributors; beforeAll(() => { nock('https://api.github.com') .persist() - .get( - '/repos/all-contributors/all-contributors-cli/contributors?per_page=100', - ) + .get('/repos/all-contributors/all-contributors-cli/contributors?per_page=100') .reply(200, allContributorsCliResponse) .get('/repos/facebook/react-native/contributors?per_page=100') .reply(200, reactNativeResponse1, { @@ -35,75 +33,68 @@ beforeAll(() => { .get('/repositories/29028775/contributors?per_page=100&page=4') .reply(200, reactNativeResponse4, { Link: '; rel="first", ; rel="prev"', - }) -}) + }); +}); test('Handle a single results page correctly', async () => { - const transformed = await check('all-contributors', 'all-contributors-cli') - expect(transformed).toEqual(allContributorsCliTransformed) -}) + const transformed = await check('all-contributors', 'all-contributors-cli'); + expect(transformed).toEqual(allContributorsCliTransformed); +}); test('Handle multiple results pages correctly', async () => { - const transformed = await check('facebook', 'react-native') - expect(transformed).toEqual(reactNativeTransformed) -}) + const transformed = await check('facebook', 'react-native'); + expect(transformed).toEqual(reactNativeTransformed); +}); async function rejects(promise) { - const error = await promise.catch(e => e) - expect(error).toBeTruthy() + const error = await promise.catch((e) => e); + expect(error).toBeTruthy(); } // When we move to vitest this might not be an issue anymore // eslint-disable-next-line vitest/expect-expect test('handle errors', async () => { - nock('https://api.github.com').get('/users/nodisplayname').replyWithError(404) + nock('https://api.github.com').get('/users/nodisplayname').replyWithError(404); - await rejects(getUserInfo('nodisplayname')) -}) + await rejects(getUserInfo('nodisplayname')); +}); test('Throw error when no username is provided', () => { - expect(getUserInfo).toThrow( - 'No login when adding a contributor. Please specify a username.', - ) -}) + expect(getUserInfo).toThrow('No login when adding a contributor. Please specify a username.'); +}); test('Throw error when non existent username is provided', async () => { - const username = 'thisusernamedoesntexist' + const username = 'thisusernamedoesntexist'; nock('https://api.github.com').get(`/users/${username}`).reply(404, { message: 'Not Found', - documentation_url: - 'https://developer.github.com/v3/users/#get-a-single-user', - }) + documentation_url: 'https://developer.github.com/v3/users/#get-a-single-user', + }); await expect(getUserInfo(username)).rejects.toThrow( `The username ${username} doesn't exist on GitHub.`, - ) -}) + ); +}); test('Throw error when missing enterprise authentication', async () => { - const username = 'notauthenticated' - nock('http://github.myhost.com:3000/api/v3') - .get(`/users/${username}`) - .reply(401, { - message: 'Must authenticate to access this API.', - documentation_url: 'https://developer.github.com/enterprise/2.17/v3', - }) - await expect( - getUserInfo(username, 'http://github.myhost.com:3000'), - ).rejects.toThrow( + const username = 'notauthenticated'; + nock('http://github.myhost.com:3000/api/v3').get(`/users/${username}`).reply(401, { + message: 'Must authenticate to access this API.', + documentation_url: 'https://developer.github.com/enterprise/2.17/v3', + }); + await expect(getUserInfo(username, 'http://github.myhost.com:3000')).rejects.toThrow( `Missing authentication for GitHub API. Did you set PRIVATE_TOKEN?`, - ) -}) + ); +}); test('handle API rate GitHub errors', async () => { const githubErrorMessage = - "API rate limit exceeded for 0.0.0.0. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details." + "API rate limit exceeded for 0.0.0.0. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details."; nock('https://api.github.com').get('/users/nodisplayname').reply(200, { message: githubErrorMessage, documentation_url: 'https://developer.github.com/v3/#rate-limiting', - }) + }); - await expect(getUserInfo('nodisplayname')).rejects.toThrow(githubErrorMessage) -}) + await expect(getUserInfo('nodisplayname')).rejects.toThrow(githubErrorMessage); +}); test('fill in the name when null is returned', async () => { nock('https://api.github.com').get('/users/nodisplayname').reply(200, { @@ -111,25 +102,25 @@ test('fill in the name when null is returned', async () => { name: null, avatar_url: 'https://avatars2.githubusercontent.com/u/3869412?v=3&s=400', html_url: 'https://github.com/nodisplayname', - }) + }); - const info = await getUserInfo('nodisplayname') - expect(info.name).toBe('nodisplayname') -}) + const info = await getUserInfo('nodisplayname'); + expect(info.name).toBe('nodisplayname'); +}); // When we move to vitest this might not be an issue anymore // eslint-disable-next-line vitest/expect-expect test('attaches token when supplied', async () => { - const mockAuthToken = 'myMock-token-adaskjda' + const mockAuthToken = 'myMock-token-adaskjda'; nock('https://api.github.com') .matchHeader('authorization', `token ${mockAuthToken}`) .get('/users/test-token') .reply(200, { html_url: 'test-token', - }) + }); - await getUserInfo('test-token', 'https://github.com', mockAuthToken) -}) + await getUserInfo('test-token', 'https://github.com', mockAuthToken); +}); // When we move to vitest this might not be an issue anymore // eslint-disable-next-line vitest/expect-expect @@ -139,10 +130,10 @@ test('attaches no token when supplied empty', async () => { .get('/users/test-token') .reply(200, { html_url: 'test-token', - }) + }); - await getUserInfo('test-token', 'https://github.com', '') -}) + await getUserInfo('test-token', 'https://github.com', ''); +}); // When we move to vitest this might not be an issue anymore // eslint-disable-next-line vitest/expect-expect @@ -152,10 +143,10 @@ test('attaches no token when not supplied', async () => { .get('/users/test-token') .reply(200, { html_url: 'test-token', - }) + }); - await getUserInfo('test-token') -}) + await getUserInfo('test-token'); +}); test('fill in the name when an empty string is returned', async () => { nock('https://api.github.com').get('/users/nodisplayname').reply(200, { @@ -163,11 +154,11 @@ test('fill in the name when an empty string is returned', async () => { name: '', avatar_url: 'https://avatars2.githubusercontent.com/u/3869412?v=3&s=400', html_url: 'https://github.com/nodisplayname', - }) + }); - const info = await getUserInfo('nodisplayname') - expect(info.name).toBe('nodisplayname') -}) + const info = await getUserInfo('nodisplayname'); + expect(info.name).toBe('nodisplayname'); +}); test('append http when no absolute link is provided', async () => { nock('https://api.github.com').get('/users/nodisplayname').reply(200, { @@ -175,25 +166,20 @@ test('append http when no absolute link is provided', async () => { name: '', avatar_url: 'https://avatars2.githubusercontent.com/u/3869412?v=3&s=400', html_url: 'www.github.com/nodisplayname', - }) + }); - const info = await getUserInfo('nodisplayname') - expect(info.profile).toBe('http://www.github.com/nodisplayname') -}) + const info = await getUserInfo('nodisplayname'); + expect(info.profile).toBe('http://www.github.com/nodisplayname'); +}); test('retrieve user from a different GitHub registry', async () => { - nock('http://github.myhost.com:3000/api/v3') - .get('/users/nodisplayname') - .reply(200, { - login: 'nodisplayname', - name: 'No Display Name', - avatar_url: 'https://avatars2.githubusercontent.com/u/3869412?v=3&s=400', - html_url: 'http://github.myhost.com:3000/nodisplayname', - }) + nock('http://github.myhost.com:3000/api/v3').get('/users/nodisplayname').reply(200, { + login: 'nodisplayname', + name: 'No Display Name', + avatar_url: 'https://avatars2.githubusercontent.com/u/3869412?v=3&s=400', + html_url: 'http://github.myhost.com:3000/nodisplayname', + }); - const info = await getUserInfo( - 'nodisplayname', - 'http://github.myhost.com:3000', - ) - expect(info.name).toBe('No Display Name') -}) + const info = await getUserInfo('nodisplayname', 'http://github.myhost.com:3000'); + expect(info.name).toBe('No Display Name'); +}); diff --git a/src/repo/__tests__/gitlab.js b/src/repo/__tests__/gitlab.js index 6a14a44c..4ebd5d5d 100644 --- a/src/repo/__tests__/gitlab.js +++ b/src/repo/__tests__/gitlab.js @@ -1,24 +1,22 @@ -import nock from 'nock' -import {expect, test} from 'vitest' +import nock from 'nock'; +import { expect, test } from 'vitest'; -import * as gitlabAPI from '../gitlab.js' +import * as gitlabAPI from '../gitlab.js'; -const getUserInfo = gitlabAPI.getUserInfo +const getUserInfo = gitlabAPI.getUserInfo; async function rejects(promise) { - const error = await promise.catch(e => e) - expect(error).toBeTruthy() + const error = await promise.catch((e) => e); + expect(error).toBeTruthy(); } // TODO: Review whether to add explicit expect() or keep implicit assertion via helper // eslint-disable-next-line vitest/expect-expect test('handle errors', async () => { - nock('https://gitlab.com') - .get('/api/v4/users?username=nodisplayname') - .reply(200, []) + nock('https://gitlab.com').get('/api/v4/users?username=nodisplayname').reply(200, []); - await rejects(getUserInfo('nodisplayname')) -}) + await rejects(getUserInfo('nodisplayname')); +}); test('fill in the name when it is returned', async () => { nock('https://gitlab.com') @@ -31,11 +29,11 @@ test('fill in the name when it is returned', async () => { 'http://www.gravatar.com/avatar/3186450a99d1641bf75a44baa23f0826?s=80\u0026d=identicon', web_url: 'https://gitlab.com/nodisplayname', }, - ]) + ]); - const info = await getUserInfo('nodisplayname') - expect(info.name).toBe('No Display Name') -}) + const info = await getUserInfo('nodisplayname'); + expect(info.name).toBe('No Display Name'); +}); test('fill in the name when null is returned', async () => { nock('https://gitlab.com') @@ -48,11 +46,11 @@ test('fill in the name when null is returned', async () => { 'http://www.gravatar.com/avatar/3186450a99d1641bf75a44baa23f0826?s=80\u0026d=identicon', web_url: 'https://gitlab.com/nodisplayname', }, - ]) + ]); - const info = await getUserInfo('nodisplayname') - expect(info.name).toBe('nodisplayname') -}) + const info = await getUserInfo('nodisplayname'); + expect(info.name).toBe('nodisplayname'); +}); test('fill in the name when an empty string is returned', async () => { nock('https://gitlab.com') @@ -65,11 +63,11 @@ test('fill in the name when an empty string is returned', async () => { 'http://www.gravatar.com/avatar/3186450a99d1641bf75a44baa23f0826?s=80\u0026d=identicon', web_url: 'https://gitlab.com/nodisplayname', }, - ]) + ]); - const info = await getUserInfo('nodisplayname') - expect(info.name).toBe('nodisplayname') -}) + const info = await getUserInfo('nodisplayname'); + expect(info.name).toBe('nodisplayname'); +}); test('append http when no absolute link is provided', async () => { nock('https://gitlab.com') @@ -82,11 +80,11 @@ test('append http when no absolute link is provided', async () => { 'http://www.gravatar.com/avatar/3186450a99d1641bf75a44baa23f0826?s=80\u0026d=identicon', web_url: 'www.gitlab.com/nodisplayname', }, - ]) + ]); - const info = await getUserInfo('nodisplayname') - expect(info.profile).toBe('http://www.gitlab.com/nodisplayname') -}) + const info = await getUserInfo('nodisplayname'); + expect(info.profile).toBe('http://www.gitlab.com/nodisplayname'); +}); test('retrieve user from a different gitlab registry', async () => { nock('http://gitlab.myhost.com:3000') @@ -99,14 +97,11 @@ test('retrieve user from a different gitlab registry', async () => { 'http://www.gravatar.com/avatar/3186450a99d1641bf75a44baa23f0826?s=80\u0026d=identicon', web_url: 'https://gitlab.com/nodisplayname', }, - ]) + ]); - const info = await getUserInfo( - 'nodisplayname', - 'http://gitlab.myhost.com:3000', - ) - expect(info.name).toBe('No Display Name') -}) + const info = await getUserInfo('nodisplayname', 'http://gitlab.myhost.com:3000'); + expect(info.name).toBe('No Display Name'); +}); test('retrieve user from a gitlab registry that needs a token', async () => { nock('http://gitlab.needtoken.com:3000') @@ -119,27 +114,21 @@ test('retrieve user from a gitlab registry that needs a token', async () => { 'http://www.gravatar.com/avatar/3186450a99d1641bf75a44baa23f0826?s=80\u0026d=identicon', web_url: 'https://gitlab.com/nodisplayname', }, - ]) + ]); - const info = await getUserInfo( - 'nodisplayname', - 'http://gitlab.needtoken.com:3000', - 'faketoken', - ) - expect(info.name).toBe('No Display Name') -}) + const info = await getUserInfo('nodisplayname', 'http://gitlab.needtoken.com:3000', 'faketoken'); + expect(info.name).toBe('No Display Name'); +}); // TODO: Review whether to add explicit expect() or keep implicit assertion via helper // eslint-disable-next-line vitest/expect-expect test('handle error when no token is offered', async () => { nock('http://gitlab.needtoken.com:3000') .get('/api/v4/users?username=nodisplayname') - .reply(200, []) + .reply(200, []); - await rejects( - getUserInfo('nodisplayname', 'http://gitlab.needtoken.com:3000', ''), - ) -}) + await rejects(getUserInfo('nodisplayname', 'http://gitlab.needtoken.com:3000', '')); +}); test.each([ 'file:///etc/passwd', @@ -147,15 +136,13 @@ test.each([ 'javascript:alert(1)', 'gitlab.example.com', 'not a url', -])('rejects non-http(s) hostname %s without making a request', hostname => { - const scope = nock('https://gitlab.com').get(/.*/).reply(200, []) +])('rejects non-http(s) hostname %s without making a request', (hostname) => { + const scope = nock('https://gitlab.com').get(/.*/).reply(200, []); - expect(() => getUserInfo('someuser', hostname)).toThrow( - `Invalid GitLab hostname: ${hostname}`, - ) - expect(scope.isDone()).toBe(false) - nock.cleanAll() -}) + expect(() => getUserInfo('someuser', hostname)).toThrow(`Invalid GitLab hostname: ${hostname}`); + expect(scope.isDone()).toBe(false); + nock.cleanAll(); +}); test('accepts a valid custom http(s) hostname', async () => { nock('https://gitlab.example.com') @@ -167,8 +154,8 @@ test('accepts a valid custom http(s) hostname', async () => { avatar_url: 'https://gitlab.example.com/avatar.png', web_url: 'https://gitlab.example.com/customhost', }, - ]) + ]); - const info = await getUserInfo('customhost', 'https://gitlab.example.com') - expect(info.login).toBe('customhost') -}) + const info = await getUserInfo('customhost', 'https://gitlab.example.com'); + expect(info.login).toBe('customhost'); +}); diff --git a/src/repo/__tests__/index.js b/src/repo/__tests__/index.js index 3838c2e1..bf615e61 100644 --- a/src/repo/__tests__/index.js +++ b/src/repo/__tests__/index.js @@ -1,11 +1,11 @@ -import nock from 'nock' -import {beforeEach, expect, test} from 'vitest' +import nock from 'nock'; +import { beforeEach, expect, test } from 'vitest'; -import * as repo from '../index.js' +import * as repo from '../index.js'; beforeEach(() => { - nock.cleanAll() -}) + nock.cleanAll(); +}); test('get choices for init command', () => { expect(repo.getChoices()).toEqual([ @@ -17,26 +17,24 @@ test('get choices for init command', () => { value: 'gitlab', name: 'GitLab', }, - ]) -}) + ]); +}); test('get hostname for a given repo type', () => { - expect(repo.getHostname('github')).toEqual('https://github.com') - expect(repo.getHostname('github', 'http://my-github.com')).toEqual( - 'http://my-github.com', - ) - expect(repo.getHostname('gitlab')).toEqual('https://gitlab.com') + expect(repo.getHostname('github')).toEqual('https://github.com'); + expect(repo.getHostname('github', 'http://my-github.com')).toEqual('http://my-github.com'); + expect(repo.getHostname('gitlab')).toEqual('https://gitlab.com'); expect(repo.getHostname('gitlab', 'http://my-gitlab.com:3000')).toEqual( 'http://my-gitlab.com:3000', - ) - expect(repo.getHostname('other')).toBe(null) -}) + ); + expect(repo.getHostname('other')).toBe(null); +}); test('get repo name given a repo type', () => { - expect(repo.getTypeName('github')).toEqual('GitHub') - expect(repo.getTypeName('gitlab')).toEqual('GitLab') - expect(repo.getTypeName('other')).toBe(null) -}) + expect(repo.getTypeName('github')).toEqual('GitHub'); + expect(repo.getTypeName('gitlab')).toEqual('GitLab'); + expect(repo.getTypeName('other')).toBe(null); +}); test('get user info calls underlying APIs', async () => { nock('https://api.github.com').get('/users/nodisplayname').reply(200, { @@ -44,7 +42,7 @@ test('get user info calls underlying APIs', async () => { name: 'nodisplayname', avatar_url: 'https://avatars2.githubusercontent.com/u/3869412?v=3&s=400', html_url: 'https://github.com/nodisplayname', - }) + }); nock('https://gitlab.com') .get('/api/v4/users?username=nodisplayname') @@ -56,20 +54,20 @@ test('get user info calls underlying APIs', async () => { 'http://www.gravatar.com/avatar/3186450a99d1641bf75a44baa23f0826?s=80\u0026d=identicon', web_url: 'https://gitlab.com/nodisplayname', }, - ]) + ]); expect(await repo.getUserInfo('nodisplayname', 'github')).toEqual({ login: 'nodisplayname', name: 'nodisplayname', avatar_url: 'https://avatars2.githubusercontent.com/u/3869412?v=3&s=400', profile: 'https://github.com/nodisplayname', - }) + }); expect(await repo.getUserInfo('nodisplayname', 'gitlab')).toEqual({ login: 'nodisplayname', name: 'nodisplayname', avatar_url: 'http://www.gravatar.com/avatar/3186450a99d1641bf75a44baa23f0826?s=80\u0026d=identicon', profile: 'https://gitlab.com/nodisplayname', - }) - expect(await repo.getUserInfo('nodisplayname', 'other')).toBe(null) -}) + }); + expect(await repo.getUserInfo('nodisplayname', 'other')).toBe(null); +}); diff --git a/src/repo/github.js b/src/repo/github.js index 88420684..bfe9129e 100644 --- a/src/repo/github.js +++ b/src/repo/github.js @@ -1,6 +1,6 @@ -import url from 'url' +import url from 'url'; -import {isValidHttpUrl, parseHttpUrl} from '../util/url.js' +import { isValidHttpUrl, parseHttpUrl } from '../util/url.js'; /** * Get the host based on public or enterprise GitHub. @@ -11,123 +11,109 @@ import {isValidHttpUrl, parseHttpUrl} from '../util/url.js' */ function getApiHost(hostname) { if (!hostname) { - hostname = 'https://github.com' + hostname = 'https://github.com'; } if (hostname !== 'https://github.com') { // Assume Github Enterprise - return url.resolve(hostname, '/api/v3') + return url.resolve(hostname, '/api/v3'); } - return hostname.replace(/:\/\//, '://api.') + return hostname.replace(/:\/\//, '://api.'); } function getFetchHeaders(optionalPrivateToken = '') { const fetchHeaders = { 'User-Agent': 'node-fetch', - } + }; if (optionalPrivateToken && optionalPrivateToken.length > 0) { - fetchHeaders.Authorization = `token ${optionalPrivateToken}` + fetchHeaders.Authorization = `token ${optionalPrivateToken}`; } - return fetchHeaders + return fetchHeaders; } function getNextLink(link) { if (!link) { - return null + return null; } - const nextLink = link.split(',').find(s => s.includes('rel="next"')) + const nextLink = link.split(',').find((s) => s.includes('rel="next"')); if (!nextLink) { - return null + return null; } - return nextLink.split(';')[0].trim().slice(1, -1) + return nextLink.split(';')[0].trim().slice(1, -1); } function getContributorsPage(githubUrl, optionalPrivateToken) { return fetch(githubUrl, { headers: getFetchHeaders(optionalPrivateToken), - }).then(res => { + }).then((res) => { if (res.status === 404 || res.status >= 500) { - throw new Error('No contributors found on the GitHub repository') + throw new Error('No contributors found on the GitHub repository'); } - return res.json().then(body => { + return res.json().then((body) => { if (res.status >= 400 || !res.ok) { - throw new Error(body.message) + throw new Error(body.message); } - const contributorsIds = body.map(contributor => contributor.login) + const contributorsIds = body.map((contributor) => contributor.login); - const nextLink = getNextLink(res.headers.get('link')) + const nextLink = getNextLink(res.headers.get('link')); if (nextLink) { - return getContributorsPage(nextLink, optionalPrivateToken).then( - nextContributors => { - return contributorsIds.concat(nextContributors) - }, - ) + return getContributorsPage(nextLink, optionalPrivateToken).then((nextContributors) => { + return contributorsIds.concat(nextContributors); + }); } - return contributorsIds - }) - }) + return contributorsIds; + }); + }); } export const getUserInfo = function (username, hostname, optionalPrivateToken) { if (!username) { - throw new Error( - `No login when adding a contributor. Please specify a username.`, - ) + throw new Error(`No login when adding a contributor. Please specify a username.`); } - const root = getApiHost(hostname) + const root = getApiHost(hostname); return fetch(`${root}/users/${username}`, { headers: getFetchHeaders(optionalPrivateToken), - }).then(res => - res.json().then(body => { - let profile = isValidHttpUrl(body.blog) ? body.blog : body.html_url + }).then((res) => + res.json().then((body) => { + let profile = isValidHttpUrl(body.blog) ? body.blog : body.html_url; // Check for authentication required - if ( - (!profile && body.message.includes('Must authenticate')) || - res.status === 401 - ) { - throw new Error( - `Missing authentication for GitHub API. Did you set PRIVATE_TOKEN?`, - ) + if ((!profile && body.message.includes('Must authenticate')) || res.status === 401) { + throw new Error(`Missing authentication for GitHub API. Did you set PRIVATE_TOKEN?`); } // Github throwing specific errors as 200... if (!profile && body.message) { if (body.message.toLowerCase().includes('api rate limit exceeded')) { - throw new Error(body.message) + throw new Error(body.message); } else { - throw new Error(`The username ${username} doesn't exist on GitHub.`) + throw new Error(`The username ${username} doesn't exist on GitHub.`); } } - profile = parseHttpUrl(profile) + profile = parseHttpUrl(profile); return { login: body.login, name: body.name || username, avatar_url: body.avatar_url, profile, - } + }; }), - ) -} - -export const getContributors = function ( - owner, - name, - hostname, - optionalPrivateToken, -) { - const root = getApiHost(hostname) - const contributorsUrl = `${root}/repos/${owner}/${name}/contributors?per_page=100` - return getContributorsPage(contributorsUrl, optionalPrivateToken) -} + ); +}; + +export const getContributors = function (owner, name, hostname, optionalPrivateToken) { + const root = getApiHost(hostname); + const contributorsUrl = `${root}/repos/${owner}/${name}/contributors?per_page=100`; + return getContributorsPage(contributorsUrl, optionalPrivateToken); +}; diff --git a/src/repo/gitlab.js b/src/repo/gitlab.js index ca53c5bc..30b614e6 100644 --- a/src/repo/gitlab.js +++ b/src/repo/gitlab.js @@ -1,81 +1,70 @@ -import {isValidHttpUrl} from '../util/url.js' +import { isValidHttpUrl } from '../util/url.js'; const addPrivateToken = (url, privateToken = '') => { - if (privateToken === '') return url + if (privateToken === '') return url; - return `${url}&private_token=${privateToken}` - .replace(/\?/g, '&') - .replace('&', '?') -} + return `${url}&private_token=${privateToken}`.replace(/\?/g, '&').replace('&', '?'); +}; const getUserInfo = function (username, hostname, privateToken) { if (!hostname) { - hostname = 'https://gitlab.com' + hostname = 'https://gitlab.com'; } else if (!isValidHttpUrl(hostname)) { - throw new Error(`Invalid GitLab hostname: ${hostname}`) + throw new Error(`Invalid GitLab hostname: ${hostname}`); } - return fetch( - addPrivateToken( - `${hostname}/api/v4/users?username=${username}`, - privateToken, - ), - { - headers: { - 'User-Agent': 'node-fetch', - }, + return fetch(addPrivateToken(`${hostname}/api/v4/users?username=${username}`, privateToken), { + headers: { + 'User-Agent': 'node-fetch', }, - ).then(res => - res.json().then(body => { + }).then((res) => + res.json().then((body) => { // Gitlab returns an array of users. If it is empty, it means the username provided does not exist if (!body || body.length === 0) { - throw new Error(`User ${username} not found`) + throw new Error(`User ${username} not found`); } // no private token present if (body.message) { - throw new Error(body.message) + throw new Error(body.message); } - const user = body[0] + const user = body[0]; return { login: user.username, name: user.name || username, avatar_url: user.avatar_url, - profile: user.web_url.startsWith('http') - ? user.web_url - : `http://${user.web_url}`, - } + profile: user.web_url.startsWith('http') ? user.web_url : `http://${user.web_url}`, + }; }), - ) -} + ); +}; const getContributors = function (owner, name, hostname, privateToken) { if (!hostname) { - hostname = 'https://gitlab.com' + hostname = 'https://gitlab.com'; } - return fetch( - addPrivateToken(`${hostname}/api/v4/projects?search=${name}`, privateToken), - {headers: {'User-Agent': 'node-fetch'}}, - ).then(res => - res.json().then(projects => { + return fetch(addPrivateToken(`${hostname}/api/v4/projects?search=${name}`, privateToken), { + headers: { 'User-Agent': 'node-fetch' }, + }).then((res) => + res.json().then((projects) => { // Gitlab returns an array of users. If it is empty, it means the username provided does not exist if (!projects || projects.length === 0) { - throw new Error(`Project ${owner}/${name} not found`) + throw new Error(`Project ${owner}/${name} not found`); } - let project = null + let project = null; for (let i = 0; i < projects.length; i++) { if (projects[i].path_with_namespace === `${owner}/${name}`) { - project = projects[i] - break + project = projects[i]; + break; } } if (!project) { - throw new Error(`Project ${owner}/${name} not found`) + throw new Error(`Project ${owner}/${name} not found`); } return fetch( @@ -83,20 +72,20 @@ const getContributors = function (owner, name, hostname, privateToken) { `${hostname}/api/v4/projects/${project.id}/repository/contributors`, privateToken, ), - {headers: {'User-Agent': 'node-fetch'}}, - ).then(newRes => { + { headers: { 'User-Agent': 'node-fetch' } }, + ).then((newRes) => { if (newRes.status === 404 || newRes.status >= 500) { - throw new Error('No contributors found on the GitLab repository') + throw new Error('No contributors found on the GitLab repository'); } - return newRes.json().then(contributors => { + return newRes.json().then((contributors) => { if (newRes.status >= 400 || !newRes.ok) { - throw new Error(contributors.message) + throw new Error(contributors.message); } - return contributors.map(item => item.name) - }) - }) + return contributors.map((item) => item.name); + }); + }); }), - ) -} + ); +}; -export {getContributors, getUserInfo} +export { getContributors, getUserInfo }; diff --git a/src/repo/index.js b/src/repo/index.js index 8ff6887a..642262db 100644 --- a/src/repo/index.js +++ b/src/repo/index.js @@ -1,11 +1,8 @@ -import * as githubAPI from './github.js' -import * as gitlabAPI from './gitlab.js' +import * as githubAPI from './github.js'; +import * as gitlabAPI from './gitlab.js'; const privateToken = - (process.env && - (process.env.ALL_CONTRIBUTORS_PRIVATE_TOKEN || - process.env.PRIVATE_TOKEN)) || - '' + (process.env && (process.env.ALL_CONTRIBUTORS_PRIVATE_TOKEN || process.env.PRIVATE_TOKEN)) || ''; const SUPPORTED_REPO_TYPES = { github: { value: 'github', @@ -35,62 +32,62 @@ const SUPPORTED_REPO_TYPES = { getUserInfo: gitlabAPI.getUserInfo, getContributors: gitlabAPI.getContributors, }, -} +}; export const getChoices = function () { return Object.keys(SUPPORTED_REPO_TYPES) - .map(key => SUPPORTED_REPO_TYPES[key]) - .map(item => { + .map((key) => SUPPORTED_REPO_TYPES[key]) + .map((item) => { return { value: item.value, name: item.name, - } - }) -} + }; + }); +}; export const getHostname = function (repoType, repoHost) { if (repoHost) { - return repoHost + return repoHost; } else if (repoType in SUPPORTED_REPO_TYPES) { - return SUPPORTED_REPO_TYPES[repoType].defaultHost + return SUPPORTED_REPO_TYPES[repoType].defaultHost; } - return null -} + return null; +}; export const getCheckKey = function (repoType) { if (repoType in SUPPORTED_REPO_TYPES) { - return SUPPORTED_REPO_TYPES[repoType].checkKey + return SUPPORTED_REPO_TYPES[repoType].checkKey; } - return null -} + return null; +}; export const getTypeName = function (repoType) { if (repoType in SUPPORTED_REPO_TYPES) { - return SUPPORTED_REPO_TYPES[repoType].name + return SUPPORTED_REPO_TYPES[repoType].name; } - return null -} + return null; +}; export const getLinkToCommits = function (repoType) { if (repoType in SUPPORTED_REPO_TYPES) { - return SUPPORTED_REPO_TYPES[repoType].linkToCommits + return SUPPORTED_REPO_TYPES[repoType].linkToCommits; } - return null -} + return null; +}; export const getLinkToIssues = function (repoType) { if (repoType in SUPPORTED_REPO_TYPES) { - return SUPPORTED_REPO_TYPES[repoType].linkToIssues + return SUPPORTED_REPO_TYPES[repoType].linkToIssues; } - return null -} + return null; +}; export const getLinkToReviews = function (repoType) { if (repoType in SUPPORTED_REPO_TYPES) { - return SUPPORTED_REPO_TYPES[repoType].linkToReviews + return SUPPORTED_REPO_TYPES[repoType].linkToReviews; } - return null -} + return null; +}; export const getUserInfo = function (username, repoType, repoHost) { if (repoType in SUPPORTED_REPO_TYPES) { @@ -98,10 +95,10 @@ export const getUserInfo = function (username, repoType, repoHost) { username, getHostname(repoType, repoHost), privateToken, - ) + ); } - return null -} + return null; +}; export const getContributors = function (owner, name, repoType, repoHost) { if (repoType in SUPPORTED_REPO_TYPES) { @@ -110,7 +107,7 @@ export const getContributors = function (owner, name, repoType, repoHost) { name, getHostname(repoType, repoHost), privateToken, - ) + ); } - return null -} + return null; +}; diff --git a/src/util/__tests__/__stubs__/.prettierrc.json b/src/util/__tests__/__stubs__/.prettierrc.json index c9590876..661f2536 100644 --- a/src/util/__tests__/__stubs__/.prettierrc.json +++ b/src/util/__tests__/__stubs__/.prettierrc.json @@ -1,3 +1,3 @@ { - "useTabs": true + "useTabs": true } diff --git a/src/util/__tests__/config-file.js b/src/util/__tests__/config-file.js index 5e646882..2325b327 100644 --- a/src/util/__tests__/config-file.js +++ b/src/util/__tests__/config-file.js @@ -1,13 +1,14 @@ -import {promises as fs} from 'fs' -import os from 'os' -import path from 'path' -import {expect, test} from 'vitest' +import { promises as fs } from 'fs'; +import os from 'os'; +import path from 'path'; -import {readConfig, writeConfig, writeContributors} from '../config-file.js' +import { expect, test } from 'vitest'; -const absentFile = './abc' -const absentConfigFileExpected = `Configuration file not found: ${absentFile}` -const incompleteConfigFilePath = './.all-contributorsrc' +import { readConfig, writeConfig, writeContributors } from '../config-file.js'; + +const absentFile = './abc'; +const absentConfigFileExpected = `Configuration file not found: ${absentFile}`; +const incompleteConfigFilePath = './.all-contributorsrc'; const NoOwnerConfigFile = { projectOwner: '', projectName: 'all-contributors-cli', @@ -15,7 +16,7 @@ const NoOwnerConfigFile = { commit: false, contributorsPerLine: 6, contributors: [], -} +}; const NoNameConfigFile = { projectOwner: 'all-contributors', projectName: '', @@ -23,7 +24,7 @@ const NoNameConfigFile = { commit: false, contributorsPerLine: 6, contributors: [], -} +}; const NoFilesConfigFile = { projectOwner: 'all-contributors', projectName: 'all-contributors-cli', @@ -32,73 +33,63 @@ const NoFilesConfigFile = { contributorsPerLine: 6, contributors: [], files: [], -} +}; test('Reading an absent configuration file throws a helpful error', async () => { - await expect(readConfig(absentFile)).rejects.toThrow(absentConfigFileExpected) -}) + await expect(readConfig(absentFile)).rejects.toThrow(absentConfigFileExpected); +}); test('Writing contributors in an absent configuration file throws a helpful error', async () => { - await expect(writeContributors(absentFile, [])).rejects.toThrow( - absentConfigFileExpected, - ) -}) + await expect(writeContributors(absentFile, [])).rejects.toThrow(absentConfigFileExpected); +}); test('Should throw error and not allow editing config file if project name or owner is not set', async () => { - await expect( - writeConfig(incompleteConfigFilePath, NoOwnerConfigFile), - ).rejects.toThrow( + await expect(writeConfig(incompleteConfigFilePath, NoOwnerConfigFile)).rejects.toThrow( `Error! Project owner is not set in ${incompleteConfigFilePath}`, - ) + ); - await expect( - writeConfig(incompleteConfigFilePath, NoNameConfigFile), - ).rejects.toThrow( + await expect(writeConfig(incompleteConfigFilePath, NoNameConfigFile)).rejects.toThrow( `Error! Project name is not set in ${incompleteConfigFilePath}`, - ) -}) + ); +}); test(`throws if 'files' was overridden in .all-contributorsrc and is empty`, async () => { - await expect( - writeConfig(incompleteConfigFilePath, NoFilesConfigFile), - ).rejects.toThrow( + await expect(writeConfig(incompleteConfigFilePath, NoFilesConfigFile)).rejects.toThrow( `Error! Project files was overridden and is empty in ${incompleteConfigFilePath}`, - ) -}) + ); +}); async function createConfigFile(content) { - const directory = await fs.mkdtemp( - path.join(os.tmpdir(), 'all-contributors-'), - ) - const configPath = path.join(directory, '.all-contributorsrc') - await fs.writeFile(configPath, JSON.stringify(content, null, 2)) - return configPath + const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'all-contributors-')); + const configPath = path.join(directory, '.all-contributorsrc'); + await fs.writeFile(configPath, JSON.stringify(content, null, 2)); + return configPath; } const MinimalConfigFile = { projectOwner: 'all-contributors', projectName: 'all-contributors-cli', contributors: [], -} +}; test('reading a config file without repoType or commitConvention applies their defaults', async () => { - const configPath = await createConfigFile(MinimalConfigFile) + const configPath = await createConfigFile(MinimalConfigFile); expect(await readConfig(configPath)).toEqual({ ...MinimalConfigFile, commitConvention: 'angular', repoType: 'github', - }) -}) + }); +}); test('writing contributors does not add default repoType or commitConvention to the config file', async () => { - const configPath = await createConfigFile(MinimalConfigFile) - const contributors = [{login: 'jfmengels', contributions: ['code']}] + const configPath = await createConfigFile(MinimalConfigFile); + const contributors = [{ login: 'jfmengels', contributions: ['code'] }]; - await writeContributors(configPath, contributors) + await writeContributors(configPath, contributors); expect(JSON.parse(await fs.readFile(configPath, 'utf-8'))).toEqual({ ...MinimalConfigFile, contributors, - }) -}) + }); +}); diff --git a/src/util/__tests__/formatting.js b/src/util/__tests__/formatting.js index 250ddebd..ddef6cf2 100644 --- a/src/util/__tests__/formatting.js +++ b/src/util/__tests__/formatting.js @@ -1,36 +1,37 @@ -import path from 'path' -import {expect, test} from 'vitest' +import path from 'path'; -import {formatConfig} from '../formatting.js' +import { expect, test } from 'vitest'; -const content = {contributors: [{id: 'abc123'}]} +import { formatConfig } from '../formatting.js'; -const absentFile = '/!@#*&^DefinitelyDoesNotExistAllContributorsCLI$!@#' +const content = { contributors: [{ id: 'abc123' }] }; + +const absentFile = '/!@#*&^DefinitelyDoesNotExistAllContributorsCLI$!@#'; const absentConfigFileExpected = `{ "contributors": [ { "id": "abc123" } ] -}` +}`; -const presentFile = path.join(__dirname, '__stubs__', 'file.json') +const presentFile = path.join(__dirname, '__stubs__', 'file.json'); const presentConfigFileExpected = `{ "contributors": [ { "id": "abc123" } ] -}` +}`; test('falls back to JSON.stringify when the configPath cannot resolve to a config', async () => { - const output = await formatConfig(absentFile, content) + const output = await formatConfig(absentFile, content); - expect(output).toBe(absentConfigFileExpected) -}) + expect(output).toBe(absentConfigFileExpected); +}); test('uses Prettier when the configPath can resolve to a config', async () => { - const output = await formatConfig(presentFile, content) + const output = await formatConfig(presentFile, content); - expect(output).toBe(presentConfigFileExpected) -}) + expect(output).toBe(presentConfigFileExpected); +}); diff --git a/src/util/__tests__/git.js b/src/util/__tests__/git.js index a1b2d530..7d3e2a28 100644 --- a/src/util/__tests__/git.js +++ b/src/util/__tests__/git.js @@ -1,171 +1,163 @@ -import path from 'path' -import {promisify} from 'util' -import {beforeEach, describe, expect, test, vi} from 'vitest' +import path from 'path'; +import { promisify } from 'util'; -import {commit, getRepoInfo} from '../git' +import { beforeEach, describe, expect, test, vi } from 'vitest'; -vi.mock('child_process') -vi.mock('util') +import { commit, getRepoInfo } from '../git'; + +vi.mock('child_process'); +vi.mock('util'); vi.mock('../config-file', () => ({ readConfig: vi.fn(() => Promise.resolve({ commitConvention: 'gitmoji', }), ), -})) +})); describe('getRepoInfo', () => { beforeEach(() => { - vi.clearAllMocks() - }) + vi.clearAllMocks(); + }); test('should parse GitHub SSH URLs correctly', async () => { const mockExecAsync = vi.fn().mockResolvedValue({ stdout: 'git@github.com:all-contributors/all-contributors-cli.git\n', stderr: '', - }) + }); - vi.mocked(promisify).mockReturnValue(mockExecAsync) + vi.mocked(promisify).mockReturnValue(mockExecAsync); - const result = await getRepoInfo() + const result = await getRepoInfo(); expect(result).toEqual({ projectOwner: 'all-contributors', projectName: 'all-contributors-cli', - }) - }) + }); + }); test('should parse GitHub HTTPS URLs correctly', async () => { const mockExecAsync = vi.fn().mockResolvedValue({ stdout: 'https://github.com/all-contributors/all-contributors-cli.git\n', stderr: '', - }) + }); - vi.mocked(promisify).mockReturnValue(mockExecAsync) + vi.mocked(promisify).mockReturnValue(mockExecAsync); - const result = await getRepoInfo() + const result = await getRepoInfo(); expect(result).toEqual({ projectOwner: 'all-contributors', projectName: 'all-contributors-cli', - }) - }) + }); + }); test('should return null for invalid URLs', async () => { const mockExecAsync = vi.fn().mockResolvedValue({ stdout: 'invalid-url\n', stderr: '', - }) + }); - vi.mocked(promisify).mockReturnValue(mockExecAsync) + vi.mocked(promisify).mockReturnValue(mockExecAsync); - const result = await getRepoInfo() + const result = await getRepoInfo(); - expect(result).toBeNull() - }) + expect(result).toBeNull(); + }); test('should handle git command errors', async () => { - const mockExecAsync = vi - .fn() - .mockRejectedValue(new Error('Git command failed')) + const mockExecAsync = vi.fn().mockRejectedValue(new Error('Git command failed')); - vi.mocked(promisify).mockReturnValue(mockExecAsync) + vi.mocked(promisify).mockReturnValue(mockExecAsync); - await expect(getRepoInfo()).rejects.toThrow('Git command failed') - }) -}) + await expect(getRepoInfo()).rejects.toThrow('Git command failed'); + }); +}); describe('commit', () => { beforeEach(() => { - vi.clearAllMocks() - }) + vi.clearAllMocks(); + }); const mockOptions = { files: ['README.md', 'package.json'], config: '.all-contributorsrc', commitTemplate: undefined, commitConvention: 'gitmoji', - } + }; const mockData = { username: 'jdoe', newContributor: true, - } + }; const expectedAddedFiles = [ path.resolve(process.cwd(), 'README.md'), path.resolve(process.cwd(), 'package.json'), path.resolve(process.cwd(), '.all-contributorsrc'), - ].join(' ') + ].join(' '); test('should add files and commit with correct message', async () => { - const mockExecAsync = vi.fn().mockResolvedValue({stdout: '', stderr: ''}) - vi.mocked(promisify).mockReturnValue(mockExecAsync) + const mockExecAsync = vi.fn().mockResolvedValue({ stdout: '', stderr: '' }); + vi.mocked(promisify).mockReturnValue(mockExecAsync); - await commit(mockOptions, mockData) + await commit(mockOptions, mockData); - expect(mockExecAsync).toHaveBeenCalledTimes(2) - expect(mockExecAsync).toHaveBeenNthCalledWith( - 1, - `git add ${expectedAddedFiles}`, - ) + expect(mockExecAsync).toHaveBeenCalledTimes(2); + expect(mockExecAsync).toHaveBeenNthCalledWith(1, `git add ${expectedAddedFiles}`); expect(mockExecAsync).toHaveBeenNthCalledWith( 2, 'git commit -m :busts_in_silhouette: Add @jdoe as a contributor', - ) - }) + ); + }); test('should handle custom commit templates', async () => { - const mockExecAsync = vi.fn().mockResolvedValue({stdout: '', stderr: ''}) - vi.mocked(promisify).mockReturnValue(mockExecAsync) + const mockExecAsync = vi.fn().mockResolvedValue({ stdout: '', stderr: '' }); + vi.mocked(promisify).mockReturnValue(mockExecAsync); const customOptions = { ...mockOptions, - commitTemplate: - 'docs: <%= newContributor ? "Add" : "Update" %> @<%= username %>', - } + commitTemplate: 'docs: <%= newContributor ? "Add" : "Update" %> @<%= username %>', + }; - await commit(customOptions, mockData) + await commit(customOptions, mockData); - expect(mockExecAsync).toHaveBeenNthCalledWith( - 2, - 'git commit -m docs: Add @jdoe', - ) - }) + expect(mockExecAsync).toHaveBeenNthCalledWith(2, 'git commit -m docs: Add @jdoe'); + }); test('should handle git add errors with proper error message', async () => { - const gitError = new Error('Command failed') - gitError.stderr = 'fatal: pathspec README.md did not match any files' - gitError.code = 128 - const mockExecAsync = vi.fn().mockRejectedValueOnce(gitError) - vi.mocked(promisify).mockReturnValue(mockExecAsync) + const gitError = new Error('Command failed'); + gitError.stderr = 'fatal: pathspec README.md did not match any files'; + gitError.code = 128; + const mockExecAsync = vi.fn().mockRejectedValueOnce(gitError); + vi.mocked(promisify).mockReturnValue(mockExecAsync); await expect(commit(mockOptions, mockData)).rejects.toThrow( 'fatal: pathspec README.md did not match any files', - ) - }) + ); + }); test('should handle git add errors with exit code fallback', async () => { - const gitError = new Error('Command failed') - gitError.code = 1 - const mockExecAsync = vi.fn().mockRejectedValueOnce(gitError) - vi.mocked(promisify).mockReturnValue(mockExecAsync) + const gitError = new Error('Command failed'); + gitError.code = 1; + const mockExecAsync = vi.fn().mockRejectedValueOnce(gitError); + vi.mocked(promisify).mockReturnValue(mockExecAsync); await expect(commit(mockOptions, mockData)).rejects.toThrow( `git add ${expectedAddedFiles} - exit code: 1`, - ) - }) + ); + }); test('should handle git commit errors', async () => { const mockExecAsync = vi .fn() - .mockResolvedValueOnce({stdout: '', stderr: ''}) // git add succeeds + .mockResolvedValueOnce({ stdout: '', stderr: '' }) // git add succeeds .mockRejectedValueOnce({ stderr: 'nothing to commit, working tree clean', code: 1, - }) // git commit fails - vi.mocked(promisify).mockReturnValue(mockExecAsync) + }); // git commit fails + vi.mocked(promisify).mockReturnValue(mockExecAsync); await expect(commit(mockOptions, mockData)).rejects.toThrow( 'nothing to commit, working tree clean', - ) - }) -}) + ); + }); +}); diff --git a/src/util/__tests__/url.js b/src/util/__tests__/url.js index 18b259d5..2bf67678 100644 --- a/src/util/__tests__/url.js +++ b/src/util/__tests__/url.js @@ -1,57 +1,53 @@ -import {expect, test} from 'vitest' +import { expect, test } from 'vitest'; -import {isHttpProtocol, isValidHttpUrl, parseHttpUrl} from '../url.js' +import { isHttpProtocol, isValidHttpUrl, parseHttpUrl } from '../url.js'; test(`Result of protocol validation should be true`, () => { - expect(isHttpProtocol('http:')).toBe(true) - expect(isHttpProtocol('https:')).toBe(true) -}) + expect(isHttpProtocol('http:')).toBe(true); + expect(isHttpProtocol('https:')).toBe(true); +}); test(`Result of protocol validation should be false`, () => { - expect(isHttpProtocol('ftp:')).toBe(false) -}) + expect(isHttpProtocol('ftp:')).toBe(false); +}); test(`Result of url validation should be true`, () => { - expect(isValidHttpUrl('https://api.github.com/users/octocat')).toBe(true) -}) + expect(isValidHttpUrl('https://api.github.com/users/octocat')).toBe(true); +}); test(`Result of url validation should be false when url uses wrong protocol`, () => { - expect( - isValidHttpUrl( - 'git://git@github.com:all-contributors/all-contributors-cli.git', - ), - ).toBe(false) -}) + expect(isValidHttpUrl('git://git@github.com:all-contributors/all-contributors-cli.git')).toBe( + false, + ); +}); test(`Result of url validation should be false when input isn't url`, () => { - expect(isValidHttpUrl('github-octocat')).toBe(false) -}) + expect(isValidHttpUrl('github-octocat')).toBe(false); +}); test(`Result of parsed url should be equal`, () => { - const input = 'https://api.github.com/users/octocat' - const expected = 'https://api.github.com/users/octocat' - expect(parseHttpUrl(input)).toBe(expected) -}) + const input = 'https://api.github.com/users/octocat'; + const expected = 'https://api.github.com/users/octocat'; + expect(parseHttpUrl(input)).toBe(expected); +}); test(`Result of parsed url without protocol should be equal`, () => { - const input = 'example.com' - const expected = 'http://example.com/' - expect(parseHttpUrl(input)).toBe(expected) -}) + const input = 'example.com'; + const expected = 'http://example.com/'; + expect(parseHttpUrl(input)).toBe(expected); +}); test(`Throw an error when parsed input isn't a string`, () => { - const input = 123 - expect(parseHttpUrl.bind(null, input)).toThrow('input must be a string') -}) + const input = 123; + expect(parseHttpUrl.bind(null, input)).toThrow('input must be a string'); +}); test(`Throw an error when parsed url has wrong protocol`, () => { - const input = 'ftp://domain.xyz' - expect(parseHttpUrl.bind(null, input)).toThrow( - 'Provided URL has an invalid protocol', - ) -}) + const input = 'ftp://domain.xyz'; + expect(parseHttpUrl.bind(null, input)).toThrow('Provided URL has an invalid protocol'); +}); test(`Throw an error when parsed input isn't a URL`, () => { - const input = 'some string' - expect(parseHttpUrl.bind(null, input)).toThrow('Invalid URL') -}) + const input = 'some string'; + expect(parseHttpUrl.bind(null, input)).toThrow('Invalid URL'); +}); diff --git a/src/util/config-file.js b/src/util/config-file.js index a6215dc1..76659f39 100644 --- a/src/util/config-file.js +++ b/src/util/config-file.js @@ -1,74 +1,70 @@ -import {promises as fs} from 'fs' -import jf from 'json-fixer' +import { promises as fs } from 'fs'; -import {formatConfig} from './formatting.js' +import jf from 'json-fixer'; + +import { formatConfig } from './formatting.js'; export async function readConfig(configPath) { - const config = await readConfigFile(configPath) + const config = await readConfigFile(configPath); - return {repoType: 'github', commitConvention: 'angular', ...config} + return { repoType: 'github', commitConvention: 'angular', ...config }; } async function readConfigFile(configPath) { try { - const configFileContents = await fs.readFile(configPath, 'utf-8') - const {data: config, changed} = jf(configFileContents) + const configFileContents = await fs.readFile(configPath, 'utf-8'); + const { data: config, changed } = jf(configFileContents); if (changed) { - const formatterConfig = await formatConfig(configPath, config) + const formatterConfig = await formatConfig(configPath, config); //Updates the file with fixes - await fs.writeFile(configPath, formatterConfig) + await fs.writeFile(configPath, formatterConfig); } - return config + return config; } catch (error) { if (error instanceof SyntaxError) { throw new SyntaxError( `Configuration file has malformed JSON: ${configPath}. Error:: ${error.message}`, - {cause: error}, - ) + { cause: error }, + ); } if (error.code === 'ENOENT') { throw new Error(`Configuration file not found: ${configPath}`, { cause: error, - }) + }); } - throw error + throw error; } } export async function writeConfig(configPath, content) { if (!content.projectOwner) { - throw new Error(`Error! Project owner is not set in ${configPath}`) + throw new Error(`Error! Project owner is not set in ${configPath}`); } if (!content.projectName) { - throw new Error(`Error! Project name is not set in ${configPath}`) + throw new Error(`Error! Project name is not set in ${configPath}`); } if (content.files && !content.files.length) { - throw new Error( - `Error! Project files was overridden and is empty in ${configPath}`, - ) + throw new Error(`Error! Project files was overridden and is empty in ${configPath}`); } - return fs.writeFile( - configPath, - `${await formatConfig(configPath, content)}\n`, - ) + return fs.writeFile(configPath, `${await formatConfig(configPath, content)}\n`); } export async function writeContributors(configPath, contributors) { - let config + let config; try { - config = await readConfigFile(configPath) + config = await readConfigFile(configPath); } catch (error) { - return Promise.reject(error) + return Promise.reject(error); } - const content = {...config, contributors} + const content = { ...config, contributors }; - return writeConfig(configPath, content) + return writeConfig(configPath, content); } diff --git a/src/util/contribution-types.js b/src/util/contribution-types.js index 68e28cd6..60f7d23f 100644 --- a/src/util/contribution-types.js +++ b/src/util/contribution-types.js @@ -1,4 +1,4 @@ -import * as repo from '../repo/index.js' +import * as repo from '../repo/index.js'; const defaultTypes = function (repoType) { return { @@ -139,9 +139,9 @@ const defaultTypes = function (repoType) { symbol: '๐Ÿ“ฃ', description: 'Promotion', }, - } -} + }; +}; export function contributionTypes(options) { - return {...defaultTypes(options.repoType), ...options.types} + return { ...defaultTypes(options.repoType), ...options.types }; } diff --git a/src/util/formatting.js b/src/util/formatting.js index 2d7c5569..6bb48f85 100644 --- a/src/util/formatting.js +++ b/src/util/formatting.js @@ -1,24 +1,24 @@ -import prettier from 'prettier' +import prettier from 'prettier'; export async function formatConfig(configPath, content) { - const stringified = JSON.stringify(content, null, 2) + const stringified = JSON.stringify(content, null, 2); try { const prettierConfig = await prettier.resolveConfig(configPath, { useCache: false, - }) + }); - if (!prettierConfig) return stringified + if (!prettierConfig) return stringified; const formattedOutput = await prettier.format(stringified, { ...prettierConfig, parser: 'json', - }) + }); - return formattedOutput.trimEnd() + return formattedOutput.trimEnd(); } catch { // If Prettier can't be required or throws in general, // assume it's not usable and we should fall back to JSON.stringify - return stringified + return stringified; } } diff --git a/src/util/git.js b/src/util/git.js index e46deb56..38a1edef 100644 --- a/src/util/git.js +++ b/src/util/git.js @@ -1,67 +1,62 @@ -import {exec} from 'child_process' -import path from 'path' -import {promisify} from 'util' +import { exec } from 'child_process'; +import path from 'path'; +import { promisify } from 'util'; -import {conventions} from '../init/commit-conventions.js' -import * as util from '../util/index.js' +import { conventions } from '../init/commit-conventions.js'; +import * as util from '../util/index.js'; const commitTemplate = - '<%= prefix %> <%= (newContributor ? "Add" : "Update") %> @<%= username %> as a contributor' + '<%= prefix %> <%= (newContributor ? "Add" : "Update") %> @<%= username %> as a contributor'; const getRemoteOriginData = async () => { - const execAsync = promisify(exec) - const {stdout} = await execAsync('git config --get remote.origin.url') + const execAsync = promisify(exec); + const { stdout } = await execAsync('git config --get remote.origin.url'); - return stdout -} + return stdout; +}; function parse(originUrl) { - const result = /[:/]([A-Za-z0-9-_]+)\/([A-Za-z0-9-_]+)(?:\.git)?/.exec( - originUrl, - ) + const result = /[:/]([A-Za-z0-9-_]+)\/([A-Za-z0-9-_]+)(?:\.git)?/.exec(originUrl); if (!result) { - return null + return null; } return { projectOwner: result[1], projectName: result[2], - } + }; } export function getRepoInfo() { - return getRemoteOriginData().then(parse) + return getRemoteOriginData().then(parse); } -const spawnGitCommand = async args => { +const spawnGitCommand = async (args) => { try { - await promisify(exec)(`git ${args.join(' ')}`) + await promisify(exec)(`git ${args.join(' ')}`); } catch (error) { - const msg = - error.stderr || `git ${args.join(' ')} - exit code: ${error.code}` + const msg = error.stderr || `git ${args.join(' ')} - exit code: ${error.code}`; - throw new Error(msg, {cause: error}) + throw new Error(msg, { cause: error }); } -} +}; export async function commit(options, data) { - const files = options.files.concat(options.config) - const absolutePathFiles = files.map(file => path.resolve(process.cwd(), file)) - const commitConvention = conventions[options.commitConvention] + const files = options.files.concat(options.config); + const absolutePathFiles = files.map((file) => path.resolve(process.cwd(), file)); + const commitConvention = conventions[options.commitConvention]; return spawnGitCommand(['add'].concat(absolutePathFiles)).then(() => { - let commitMessage = util.template(options.commitTemplate || commitTemplate)( - { - ...data, - prefix: commitConvention.msg, - }, - ) + let commitMessage = util.template(options.commitTemplate || commitTemplate)({ + ...data, + prefix: commitConvention.msg, + }); if (commitConvention.lowercase) { - commitMessage = commitConvention.transform(commitMessage) + commitMessage = commitConvention.transform(commitMessage); } - return spawnGitCommand(['commit', '-m', commitMessage]) - }) + return spawnGitCommand(['commit', '-m', commitMessage]); + }); } diff --git a/src/util/index.js b/src/util/index.js index 6a74bf1a..937319ec 100644 --- a/src/util/index.js +++ b/src/util/index.js @@ -1,7 +1,7 @@ -import * as configFile from './config-file.js' -import {contributionTypes} from './contribution-types.js' -import * as git from './git.js' -import {template} from './template.js' -import * as url from './url.js' +import * as configFile from './config-file.js'; +import { contributionTypes } from './contribution-types.js'; +import * as git from './git.js'; +import { template } from './template.js'; +import * as url from './url.js'; -export {configFile, contributionTypes, git, template, url} +export { configFile, contributionTypes, git, template, url }; diff --git a/src/util/template.js b/src/util/template.js index 4a7d4dde..adbeba18 100644 --- a/src/util/template.js +++ b/src/util/template.js @@ -1,9 +1,8 @@ -import {Eta} from 'eta' +import { Eta } from 'eta'; const eta = new Eta({ useWith: true, autoEscape: false, -}) +}); -export const template = templateString => data => - eta.renderString(templateString, data) +export const template = (templateString) => (data) => eta.renderString(templateString, data); diff --git a/src/util/url.js b/src/util/url.js index a03208aa..386c9b75 100644 --- a/src/util/url.js +++ b/src/util/url.js @@ -1,29 +1,27 @@ export function isHttpProtocol(input) { - return new RegExp('^https?\\:?$').test(input) + return new RegExp('^https?\\:?$').test(input); } export function isValidHttpUrl(input) { try { - const url = new URL(input) + const url = new URL(input); - return isHttpProtocol(url.protocol) + return isHttpProtocol(url.protocol); } catch { - return false + return false; } } export function parseHttpUrl(input) { if (typeof input !== 'string') { - throw new TypeError('input must be a string') + throw new TypeError('input must be a string'); } - const url = new URL( - new RegExp('^\\w+\\:\\/\\/').test(input) ? input : `http://${input}`, - ) + const url = new URL(new RegExp('^\\w+\\:\\/\\/').test(input) ? input : `http://${input}`); if (!isHttpProtocol(url.protocol)) { - throw new TypeError('Provided URL has an invalid protocol') + throw new TypeError('Provided URL has an invalid protocol'); } - return url.toString() + return url.toString(); } diff --git a/test/e2e/cli.test.js b/test/e2e/cli.test.js index d39163e6..7b54e7d9 100644 --- a/test/e2e/cli.test.js +++ b/test/e2e/cli.test.js @@ -1,44 +1,43 @@ -import {readdir, readFile, rm} from 'node:fs/promises' -import path from 'node:path' -import {expect} from 'vitest' +import { readdir, readFile, rm } from 'node:fs/promises'; +import path from 'node:path'; -import {it as baseIt} from './fixtures.js' -import {runCli} from './run-cli.js' +import { expect } from 'vitest'; + +import { it as baseIt } from './fixtures.js'; +import { runCli } from './run-cli.js'; const it = baseIt.extend({ - projectWithoutReadme: async ({project}, use) => { - await rm(path.join(project, 'README.md')) - await use(project) + projectWithoutReadme: async ({ project }, use) => { + await rm(path.join(project, 'README.md')); + await use(project); }, -}) +}); -it('--help exits 0 and lists the commands', async ({tmpDir}) => { - const result = await runCli(['--help'], {cwd: tmpDir}) +it('--help exits 0 and lists the commands', async ({ tmpDir }) => { + const result = await runCli(['--help'], { cwd: tmpDir }); - expect(result.code).toBe(0) - expect(result.stdout).toContain('generate') -}) + expect(result.code).toBe(0); + expect(result.stdout).toContain('generate'); +}); -it('--help does not create any files', async ({tmpDir}) => { - await runCli(['--help'], {cwd: tmpDir}) +it('--help does not create any files', async ({ tmpDir }) => { + await runCli(['--help'], { cwd: tmpDir }); - expect(await readdir(tmpDir)).toEqual([]) -}) + expect(await readdir(tmpDir)).toEqual([]); +}); -it('generate adds contributors to the README', async ({project}) => { - const result = await runCli(['generate'], {cwd: project}) - const newReadme = await readFile(path.join(project, 'README.md'), 'utf8') +it('generate adds contributors to the README', async ({ project }) => { + const result = await runCli(['generate'], { cwd: project }); + const newReadme = await readFile(path.join(project, 'README.md'), 'utf8'); - expect(result.code).toBe(0) - expect(newReadme).toContain('The Octocat') - expect(newReadme).toContain('https://github.com/octocat') -}) + expect(result.code).toBe(0); + expect(newReadme).toContain('The Octocat'); + expect(newReadme).toContain('https://github.com/octocat'); +}); -it('generate exits 1 when the README is missing', async ({ - projectWithoutReadme, -}) => { - const result = await runCli(['generate'], {cwd: projectWithoutReadme}) +it('generate exits 1 when the README is missing', async ({ projectWithoutReadme }) => { + const result = await runCli(['generate'], { cwd: projectWithoutReadme }); - expect(result.code).toBe(1) - expect(result.stderr).toContain('README.md') -}) + expect(result.code).toBe(1); + expect(result.stderr).toContain('README.md'); +}); diff --git a/test/e2e/fixtures.js b/test/e2e/fixtures.js index f267ed4a..1fe8b3df 100644 --- a/test/e2e/fixtures.js +++ b/test/e2e/fixtures.js @@ -1,8 +1,9 @@ // Fixtures for the CLI E2E tests. -import {mkdtemp, rm, writeFile} from 'node:fs/promises' -import {tmpdir} from 'node:os' -import path from 'node:path' -import {test} from 'vitest' +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; + +import { test } from 'vitest'; const config = { projectName: 'test-project', @@ -17,29 +18,26 @@ const config = { contributions: ['code'], }, ], -} +}; const readme = `# Test project -` +`; export const it = test.extend({ // Vitest requires the first argument to be destructured, even when empty // eslint-disable-next-line no-empty-pattern tmpDir: async ({}, use) => { - const dir = await mkdtemp(path.join(tmpdir(), 'ac-e2e-')) - await use(dir) - await rm(dir, {recursive: true, force: true}) + const dir = await mkdtemp(path.join(tmpdir(), 'ac-e2e-')); + await use(dir); + await rm(dir, { recursive: true, force: true }); }, - project: async ({tmpDir}, use) => { - await writeFile( - path.join(tmpDir, '.all-contributorsrc'), - JSON.stringify(config, null, 2), - ) - await writeFile(path.join(tmpDir, 'README.md'), readme) - await use(tmpDir) + project: async ({ tmpDir }, use) => { + await writeFile(path.join(tmpDir, '.all-contributorsrc'), JSON.stringify(config, null, 2)); + await writeFile(path.join(tmpDir, 'README.md'), readme); + await use(tmpDir); }, -}) +}); diff --git a/test/e2e/run-cli.js b/test/e2e/run-cli.js index 982be2f5..6c7a82b8 100644 --- a/test/e2e/run-cli.js +++ b/test/e2e/run-cli.js @@ -1,20 +1,15 @@ // Helper that runs the CLI and returns the code, stdout, and stderr. -import {execFile} from 'node:child_process' -import process from 'node:process' -import {fileURLToPath} from 'node:url' +import { execFile } from 'node:child_process'; +import process from 'node:process'; +import { fileURLToPath } from 'node:url'; -const cliPath = fileURLToPath(new URL('../../src/cli.js', import.meta.url)) +const cliPath = fileURLToPath(new URL('../../src/cli.js', import.meta.url)); -export function runCli(args, {cwd = process.cwd()} = {}) { - return new Promise(resolve => { +export function runCli(args, { cwd = process.cwd() } = {}) { + return new Promise((resolve) => { // run the CLI - execFile( - process.execPath, - [cliPath, ...args], - {cwd}, - (error, stdout, stderr) => { - resolve({code: error ? error.code : 0, stdout, stderr}) - }, - ) - }) + execFile(process.execPath, [cliPath, ...args], { cwd }, (error, stdout, stderr) => { + resolve({ code: error ? error.code : 0, stdout, stderr }); + }); + }); } diff --git a/vitest.config.ts b/vitest.config.ts index 160d2621..8057db67 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,4 +1,4 @@ -import {defineConfig} from 'vitest/config' +import { defineConfig } from 'vitest/config'; export default defineConfig({ resolve: { @@ -23,4 +23,4 @@ export default defineConfig({ globals: false, include: ['src/**/__tests__/**/*.js'], }, -}) +}); diff --git a/vitest.e2e.config.ts b/vitest.e2e.config.ts index 953d3a77..a56ce7cb 100644 --- a/vitest.e2e.config.ts +++ b/vitest.e2e.config.ts @@ -1,8 +1,8 @@ -import {defineConfig} from 'vitest/config' +import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { environment: 'node', include: ['test/e2e/**/*.test.js'], }, -}) +});