From a0ec4c34393e76c6764e392e36d5fddcf98335e1 Mon Sep 17 00:00:00 2001 From: DJ Mountney Date: Tue, 1 Oct 2024 16:02:24 -0700 Subject: [PATCH] chore: Apply prettier formatting (#13) - Matching config from other projects --- .eslintrc.js | 2 +- .github/workflows/publish.yaml | 8 +- .github/workflows/unit-test.yaml | 6 +- .prettierrc | 6 + README.md | 1 - examples/babel.config.js | 10 +- examples/jest.config.js | 10 +- examples/src/basic/basic.spec.ts | 14 +- examples/src/basic/basic2.spec.ts | 14 +- examples/src/basic/delay.spec.ts | 4 +- examples/src/basic/sum.test.ts | 4 +- examples/src/basic/sum.ts | 4 +- examples/src/flaky.test.ts | 6 +- examples/src/same-title.test.ts | 8 +- examples/src/skipped/skipped.test.ts | 4 +- examples/src/sum.test.ts | 4 +- examples/src/sum.ts | 4 +- examples/src/tag.test.ts | 6 +- package.json | 4 +- packages/cmd/CHANGELOG.md | 19 +- packages/cmd/README.md | 4 +- packages/cmd/publish.js | 20 +- packages/cmd/src/api/cache.ts | 24 +- packages/cmd/src/api/create-run.ts | 36 +- packages/cmd/src/api/get-run.ts | 18 +- packages/cmd/src/api/index.ts | 7 +- packages/cmd/src/bin/index.ts | 6 +- packages/cmd/src/bin/program.ts | 12 +- packages/cmd/src/commands/api/get-run.ts | 16 +- packages/cmd/src/commands/api/index.ts | 18 +- packages/cmd/src/commands/api/options.ts | 44 +- packages/cmd/src/commands/cache/get.ts | 18 +- packages/cmd/src/commands/cache/index.ts | 22 +- packages/cmd/src/commands/cache/options.ts | 56 +-- packages/cmd/src/commands/cache/set.ts | 18 +- .../cmd/src/commands/upload/cli-config.ts | 20 +- packages/cmd/src/commands/upload/index.ts | 16 +- packages/cmd/src/commands/upload/options.ts | 54 +-- packages/cmd/src/commands/upload/tmp-file.ts | 2 +- packages/cmd/src/commands/upload/upload.ts | 18 +- packages/cmd/src/commands/utils.ts | 14 +- packages/cmd/src/config/api/config.ts | 16 +- packages/cmd/src/config/api/env.ts | 38 +- packages/cmd/src/config/api/index.ts | 4 +- packages/cmd/src/config/cache/config.ts | 28 +- packages/cmd/src/config/cache/env.ts | 62 +-- packages/cmd/src/config/cache/index.ts | 6 +- packages/cmd/src/config/cache/options.ts | 6 +- packages/cmd/src/config/upload/config.ts | 16 +- packages/cmd/src/config/upload/env.ts | 58 +-- packages/cmd/src/config/upload/index.ts | 6 +- packages/cmd/src/config/upload/options.ts | 10 +- packages/cmd/src/config/utils.ts | 12 +- packages/cmd/src/debug/index.ts | 16 +- .../cmd/src/env/__tests__/ciProvider.test.ts | 38 +- .../cmd/src/env/__tests__/git-info.test.ts | 18 +- packages/cmd/src/env/ciProvider.ts | 442 +++++++++--------- packages/cmd/src/env/git-ci-provider.ts | 18 +- packages/cmd/src/env/gitInfo.ts | 6 +- packages/cmd/src/env/platform.ts | 14 +- packages/cmd/src/env/types.ts | 5 +- packages/cmd/src/env/versions.ts | 2 +- packages/cmd/src/http/axios.ts | 12 +- packages/cmd/src/http/client.ts | 38 +- packages/cmd/src/http/http.ts | 18 +- packages/cmd/src/http/httpConfig.ts | 4 +- packages/cmd/src/http/httpErrors.ts | 32 +- packages/cmd/src/http/httpRetry.ts | 32 +- packages/cmd/src/http/index.ts | 2 +- packages/cmd/src/index.ts | 4 +- packages/cmd/src/lib/execa.ts | 4 +- packages/cmd/src/lib/fs.ts | 10 +- packages/cmd/src/lib/index.ts | 8 +- packages/cmd/src/lib/nano.ts | 4 +- packages/cmd/src/logger/index.ts | 4 +- packages/cmd/src/logger/logger.ts | 52 +-- packages/cmd/src/services/api/index.ts | 18 +- .../src/services/cache/__tests__/fs.spec.ts | 62 +-- packages/cmd/src/services/cache/fs.ts | 30 +- packages/cmd/src/services/cache/get.ts | 36 +- packages/cmd/src/services/cache/index.ts | 4 +- packages/cmd/src/services/cache/lib.ts | 16 +- packages/cmd/src/services/cache/network.ts | 40 +- packages/cmd/src/services/cache/presets.ts | 50 +- packages/cmd/src/services/cache/set.ts | 32 +- packages/cmd/src/services/index.ts | 6 +- .../upload/discovery/createScanner.ts | 8 +- .../src/services/upload/discovery/index.ts | 4 +- .../upload/discovery/jest/args/args.ts | 88 ++-- .../upload/discovery/jest/args/config.ts | 128 ++--- .../upload/discovery/jest/args/index.ts | 22 +- .../services/upload/discovery/jest/index.ts | 10 +- .../upload/discovery/jest/reporter.ts | 34 +- .../services/upload/discovery/jest/scanner.ts | 42 +- .../services/upload/discovery/jest/utils.ts | 2 - .../upload/discovery/jest/utils/fs.ts | 6 +- .../upload/discovery/jest/utils/index.ts | 4 +- .../upload/discovery/jest/utils/test.ts | 20 +- .../src/services/upload/discovery/scanner.ts | 4 +- packages/cmd/src/services/upload/fs.ts | 20 +- packages/cmd/src/services/upload/index.ts | 70 +-- packages/cmd/src/services/upload/types.ts | 8 +- packages/cmd/tsup.config.ts | 14 +- packages/cmd/vitest.config.ts | 10 +- packages/eslint-config-custom/index.js | 6 +- packages/jest/CHANGELOG.md | 5 +- packages/jest/README.md | 4 +- packages/jest/publish.js | 20 +- packages/jest/src/index.ts | 4 +- packages/jest/src/lib/args.ts | 6 +- packages/jest/src/lib/debug.ts | 4 +- packages/jest/src/lib/error.ts | 38 +- packages/jest/src/lib/fs.ts | 18 +- packages/jest/src/lib/getReportConfig.ts | 18 +- packages/jest/src/lib/hash.ts | 10 +- packages/jest/src/lib/index.ts | 18 +- packages/jest/src/lib/relativeFileLocation.ts | 2 +- packages/jest/src/lib/test.ts | 64 +-- packages/jest/src/lib/versions.ts | 12 +- packages/jest/src/logger/index.ts | 4 +- packages/jest/src/logger/logger.ts | 52 +-- packages/jest/src/reporter.ts | 50 +- packages/jest/src/types.ts | 8 +- packages/jest/tsup.config.ts | 10 +- 124 files changed, 1382 insertions(+), 1385 deletions(-) create mode 100644 .prettierrc diff --git a/.eslintrc.js b/.eslintrc.js index 46722ae..0c3dcfe 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,5 +1,5 @@ module.exports = { root: true, // This tells ESLint to load the config from the package `eslint-config-custom` - extends: ["custom"], + extends: ['custom'], }; diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index 5551531..6e3e73e 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -18,8 +18,8 @@ on: type: choice description: Package to publish options: - - "@currents/cmd" - - "@currents/jest" + - '@currents/cmd' + - '@currents/jest' jobs: publish: @@ -35,8 +35,8 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: "20.x" - registry-url: "https://registry.npmjs.org" + node-version: '20.x' + registry-url: 'https://registry.npmjs.org' - run: npm ci - name: Publish to NPM diff --git a/.github/workflows/unit-test.yaml b/.github/workflows/unit-test.yaml index aed3aa7..0a87a1e 100644 --- a/.github/workflows/unit-test.yaml +++ b/.github/workflows/unit-test.yaml @@ -5,15 +5,15 @@ on: jobs: currentsUnitTests: if: "!contains(toJSON(github.event.commits.*.message), '[skip ci]')" - name: "Unit Tests" + name: 'Unit Tests' runs-on: ubuntu-22.04 container: mcr.microsoft.com/playwright:v1.28.1-focal steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: "20.x" - cache: "npm" + node-version: '20.x' + cache: 'npm' - name: Install dependencies run: | diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..0a72520 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,6 @@ +{ + "trailingComma": "es5", + "tabWidth": 2, + "semi": true, + "singleQuote": true +} diff --git a/README.md b/README.md index a412d5f..eca589f 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,6 @@ Run `npx currents api --help` to see all available api commands. To explore additional examples and filtering options for receiving runs, you can utilize the `npx currents api get-run --help` command. - ### Caching artifacts The `currents cache` command allows you to archive files from specified locations and save them under an ID in Currents storage. It also stores a meta file with configuration data. You can provide the ID manually or it can be generated based on CI environment variables (only GitHub and GitLab are supported). The files to archive can be defined using the `paths ` CLI option or predefined using a `preset`. diff --git a/examples/babel.config.js b/examples/babel.config.js index a50f080..8165fe4 100644 --- a/examples/babel.config.js +++ b/examples/babel.config.js @@ -1,6 +1,6 @@ module.exports = { - presets: [ - ['@babel/preset-env', {targets: {node: 'current'}}], - '@babel/preset-typescript', - ], - }; \ No newline at end of file + presets: [ + ['@babel/preset-env', { targets: { node: 'current' } }], + '@babel/preset-typescript', + ], +}; diff --git a/examples/jest.config.js b/examples/jest.config.js index 97b0902..363c51d 100644 --- a/examples/jest.config.js +++ b/examples/jest.config.js @@ -2,18 +2,18 @@ const config = { reporters: [ // "default", - ["@currents/jest", {}], + ['@currents/jest', {}], ], projects: [ { - displayName: "spec", + displayName: 'spec', testLocationInResults: true, - testMatch: ["/**/*.spec.ts"], + testMatch: ['/**/*.spec.ts'], }, { - displayName: "test", + displayName: 'test', testLocationInResults: true, - testMatch: ["/**/*.test.ts"], + testMatch: ['/**/*.test.ts'], }, ], }; diff --git a/examples/src/basic/basic.spec.ts b/examples/src/basic/basic.spec.ts index 58b1a02..cac6d29 100644 --- a/examples/src/basic/basic.spec.ts +++ b/examples/src/basic/basic.spec.ts @@ -1,21 +1,21 @@ -describe("describe block 1", () => { - it("expect 1 to match 1", () => { +describe('describe block 1', () => { + it('expect 1 to match 1', () => { expect(1).toBe(1); }); - it.todo("todo test"); + it.todo('todo test'); - it.skip("skipped test case", () => { + it.skip('skipped test case', () => { expect(2).toBe(2); }); }); -describe.skip("skipped describe block", () => { - it("expect 3 to match 3", () => { +describe.skip('skipped describe block', () => { + it('expect 3 to match 3', () => { expect(3).toBe(3); }); - it("expect 4 to match 4", () => { + it('expect 4 to match 4', () => { expect(4).toBe(4); }); }); diff --git a/examples/src/basic/basic2.spec.ts b/examples/src/basic/basic2.spec.ts index dcc95d4..4a0c7d2 100644 --- a/examples/src/basic/basic2.spec.ts +++ b/examples/src/basic/basic2.spec.ts @@ -1,20 +1,20 @@ -describe("describe parent", () => { - describe("describe block 3", () => { - it("expect 1 to match 1", () => { +describe('describe parent', () => { + describe('describe block 3', () => { + it('expect 1 to match 1', () => { expect(1).toBe(1); }); - it("expect 2 to match 2", () => { + it('expect 2 to match 2', () => { expect(2).toBe(2); }); }); - describe("describe block 4", () => { - it("expect 3 to match 3", () => { + describe('describe block 4', () => { + it('expect 3 to match 3', () => { expect(3).toBe(3); }); - it("expect 4 to match 4", () => { + it('expect 4 to match 4', () => { expect(4).toBe(4); }); }); diff --git a/examples/src/basic/delay.spec.ts b/examples/src/basic/delay.spec.ts index 983833e..ce13d16 100644 --- a/examples/src/basic/delay.spec.ts +++ b/examples/src/basic/delay.spec.ts @@ -1,5 +1,5 @@ -describe("delay", () => { - test("example test", async () => { +describe('delay', () => { + test('example test', async () => { await new Promise((resolve) => setTimeout(resolve, 2000)); expect(true).toBe(true); }); diff --git a/examples/src/basic/sum.test.ts b/examples/src/basic/sum.test.ts index af2d6ac..90ce67f 100644 --- a/examples/src/basic/sum.test.ts +++ b/examples/src/basic/sum.test.ts @@ -1,5 +1,5 @@ -import { sum } from "./sum"; +import { sum } from './sum'; -test("adds 1 + 2 to equal 3", () => { +test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); }); diff --git a/examples/src/basic/sum.ts b/examples/src/basic/sum.ts index 118bc98..506a413 100644 --- a/examples/src/basic/sum.ts +++ b/examples/src/basic/sum.ts @@ -1,3 +1,3 @@ export function sum(a, b) { - return a + b; - } \ No newline at end of file + return a + b; +} diff --git a/examples/src/flaky.test.ts b/examples/src/flaky.test.ts index 2fb18cd..bca041e 100644 --- a/examples/src/flaky.test.ts +++ b/examples/src/flaky.test.ts @@ -1,11 +1,11 @@ jest.retryTimes(2); let j = 0; -describe("Flaky", () => { - it("should pass only on second run", async () => { +describe('Flaky', () => { + it('should pass only on second run', async () => { expect(j++).toEqual(1); }); - it("AAA", async () => { + it('AAA', async () => { expect(1).toEqual(1); }); }); diff --git a/examples/src/same-title.test.ts b/examples/src/same-title.test.ts index f0300f1..fdd6b19 100644 --- a/examples/src/same-title.test.ts +++ b/examples/src/same-title.test.ts @@ -1,17 +1,17 @@ jest.retryTimes(2); -describe("Test cases with same title", () => { +describe('Test cases with same title', () => { let j = 0; - test("Test case example", () => { + test('Test case example', () => { expect(j++).toBe(2); }); - test.skip("Test case example", () => { + test.skip('Test case example', () => { expect(1).toBe(1); }); - test("Test case example", () => { + test('Test case example', () => { expect(1).toBe(1); }); }); diff --git a/examples/src/skipped/skipped.test.ts b/examples/src/skipped/skipped.test.ts index 87b2b5b..50e395d 100644 --- a/examples/src/skipped/skipped.test.ts +++ b/examples/src/skipped/skipped.test.ts @@ -1,5 +1,5 @@ -describe.skip("skipped block", () => { - it("test inside skipped block", () => { +describe.skip('skipped block', () => { + it('test inside skipped block', () => { expect(1).toBe(1); }, 5000); }); diff --git a/examples/src/sum.test.ts b/examples/src/sum.test.ts index ef229f9..a9b7017 100644 --- a/examples/src/sum.test.ts +++ b/examples/src/sum.test.ts @@ -1,5 +1,5 @@ -import { sum } from "./sum"; +import { sum } from './sum'; -test("[failed] adds 1 + 2 to equal 3", () => { +test('[failed] adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(4); }); diff --git a/examples/src/sum.ts b/examples/src/sum.ts index 118bc98..506a413 100644 --- a/examples/src/sum.ts +++ b/examples/src/sum.ts @@ -1,3 +1,3 @@ export function sum(a, b) { - return a + b; - } \ No newline at end of file + return a + b; +} diff --git a/examples/src/tag.test.ts b/examples/src/tag.test.ts index bd0591b..dc230fe 100644 --- a/examples/src/tag.test.ts +++ b/examples/src/tag.test.ts @@ -1,9 +1,9 @@ -describe("Test with @tag", () => { - test("Test A @tagA", () => { +describe('Test with @tag', () => { + test('Test A @tagA', () => { expect(1).toBe(1); }); - test.skip("Test B @tagB", () => { + test.skip('Test B @tagB', () => { expect(1).toBe(1); }); }); diff --git a/package.json b/package.json index 470722d..e0eec57 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,9 @@ "scripts": { "build": "turbo run build", "dev": "turbo run dev --parallel", - "lint": "turbo run lint" + "lint": "turbo run lint", + "format": "prettier --check .", + "format-fix": "prettier --write ." }, "devDependencies": { "eslint-config-custom": "*", diff --git a/packages/cmd/CHANGELOG.md b/packages/cmd/CHANGELOG.md index 2bab67d..7ee7ea0 100644 --- a/packages/cmd/CHANGELOG.md +++ b/packages/cmd/CHANGELOG.md @@ -8,32 +8,28 @@ ## [1.0.5](https://github.com/currents-dev/currents-reporter/compare/@currents/cmd-v1.0.4...${npm.name}-v1.0.5) (2024-09-09) - ### Bug Fixes -* make missing config variables user-friendly ([2a2b7ab](https://github.com/currents-dev/currents-reporter/commit/2a2b7abb97cbf78546465538d7c48b97d6934bc4)) +- make missing config variables user-friendly ([2a2b7ab](https://github.com/currents-dev/currents-reporter/commit/2a2b7abb97cbf78546465538d7c48b97d6934bc4)) ## [1.0.4](https://github.com/currents-dev/currents-reporter/compare/@currents/cmd-v1.0.3...${npm.name}-v1.0.4) (2024-09-03) - ### Bug Fixes -* use .currents directory ([611132b](https://github.com/currents-dev/currents-reporter/commit/611132b286403fce4dcbf4343d82e9927611255d)) -* use currents instead of currents-reporter CLI command ([2617004](https://github.com/currents-dev/currents-reporter/commit/26170046044f94dffda5bc967f2ab87a72cc0d8c)) +- use .currents directory ([611132b](https://github.com/currents-dev/currents-reporter/commit/611132b286403fce4dcbf4343d82e9927611255d)) +- use currents instead of currents-reporter CLI command ([2617004](https://github.com/currents-dev/currents-reporter/commit/26170046044f94dffda5bc967f2ab87a72cc0d8c)) ## [1.0.3](https://github.com/currents-dev/currents-reporter/compare/@currents/cmd-v1.0.2...${npm.name}-v1.0.3) (2024-08-01) - ### Bug Fixes -* use v1/runs endpoint [CSR-1336] ([#6](https://github.com/currents-dev/currents-reporter/issues/6)) ([d9a799d](https://github.com/currents-dev/currents-reporter/commit/d9a799dbcfa4db5908a2a168ce78adc544df45b5)) +- use v1/runs endpoint [CSR-1336] ([#6](https://github.com/currents-dev/currents-reporter/issues/6)) ([d9a799d](https://github.com/currents-dev/currents-reporter/commit/d9a799dbcfa4db5908a2a168ce78adc544df45b5)) ## [1.0.2](https://github.com/currents-dev/currents-reporter/compare/@currents/cmd-v1.0.1...${npm.name}-v1.0.2) (2024-07-25) - ### Bug Fixes -* filter irrelevant options from jest configuration ([#5](https://github.com/currents-dev/currents-reporter/issues/5)) ([3031b3d](https://github.com/currents-dev/currents-reporter/commit/3031b3d78a394b0946daa1fd3ce4d2b73c32f9f3)) +- filter irrelevant options from jest configuration ([#5](https://github.com/currents-dev/currents-reporter/issues/5)) ([3031b3d](https://github.com/currents-dev/currents-reporter/commit/3031b3d78a394b0946daa1fd3ce4d2b73c32f9f3)) ## [1.0.1](https://github.com/currents-dev/currents-reporter/compare/@currents/cmd-v1.0.0...${npm.name}-v1.0.1) (2024-07-23) @@ -41,10 +37,9 @@ # [1.0.0-beta.4](https://github.com/currents-dev/currents-reporter/compare/@currents/cmd-v1.0.0-beta.3...${npm.name}-v1.0.0-beta.4) (2024-07-16) - ### Bug Fixes -* include test case location in the report, when available ([#3](https://github.com/currents-dev/currents-reporter/issues/3)) ([f074021](https://github.com/currents-dev/currents-reporter/commit/f074021627ba44d130abeea0d608edf71440840a)) +- include test case location in the report, when available ([#3](https://github.com/currents-dev/currents-reporter/issues/3)) ([f074021](https://github.com/currents-dev/currents-reporter/commit/f074021627ba44d130abeea0d608edf71440840a)) # [1.0.0-beta.3](https://github.com/currents-dev/currents-reporter/compare/@currents/cmd-v1.0.0-beta.2...${npm.name}-v1.0.0-beta.3) (2024-07-10) @@ -62,4 +57,4 @@ ### Features - add reportDir option to jest-reporter ([887fae6](https://github.com/currents-dev/currents-reporter/commit/887fae637f5d08243323e30abedba919075939b6)) -- add vitest ([2b25624](https://github.com/currents-dev/currents-reporter/commit/2b2562410adcce06de4e54abcc63c4a16603d27b)) \ No newline at end of file +- add vitest ([2b25624](https://github.com/currents-dev/currents-reporter/commit/2b2562410adcce06de4e54abcc63c4a16603d27b)) diff --git a/packages/cmd/README.md b/packages/cmd/README.md index 31e7d8c..023b41e 100644 --- a/packages/cmd/README.md +++ b/packages/cmd/README.md @@ -71,14 +71,16 @@ For more examples and usage options, run `npx currents api --help`. ## Cache test artifacts -The `currents cache` command allows you to archive files from specified locations and save them under an ID in Currents storage. It also stores a meta file with configuration data. You can provide the ID manually or it can be generated based on CI environment variables (only GitHub and GitLab are supported). +The `currents cache` command allows you to archive files from specified locations and save them under an ID in Currents storage. It also stores a meta file with configuration data. You can provide the ID manually or it can be generated based on CI environment variables (only GitHub and GitLab are supported). To cache files, use the following command: + ```sh npx currents cache set --key --id --paths ``` To download files, use the following command: + ```sh npx currents cache set --key --preset last-run ``` diff --git a/packages/cmd/publish.js b/packages/cmd/publish.js index 65ed897..9b957ac 100755 --- a/packages/cmd/publish.js +++ b/packages/cmd/publish.js @@ -1,26 +1,26 @@ #!/usr/bin/env node -const { execSync } = require("child_process"); -const fs = require("fs"); -const pkg = require("./package.json"); -const { Command } = require("commander"); +const { execSync } = require('child_process'); +const fs = require('fs'); +const pkg = require('./package.json'); +const { Command } = require('commander'); const program = new Command() - .name("publish") - .option("-t, --tag ", "npm dist-tag to publish to"); + .name('publish') + .option('-t, --tag ', 'npm dist-tag to publish to'); program.parse(process.argv); const options = program.opts(); console.log(options); if (!options.tag) { - console.log("No tag supplied: beta or latest"); + console.log('No tag supplied: beta or latest'); process.exit(1); } console.log(process.cwd()); // fs.copyFileSync("./CHANGELOG.md", "./CHANGELOG.md"); -fs.copyFileSync("../../LICENSE.md", "./LICENSE.md"); +fs.copyFileSync('../../LICENSE.md', './LICENSE.md'); execSync(`npm pack --dry-run && npm publish --tag ${options.tag}`, { - cwd: "./", - stdio: "inherit", + cwd: './', + stdio: 'inherit', }); diff --git a/packages/cmd/src/api/cache.ts b/packages/cmd/src/api/cache.ts index 1107583..4a3220d 100644 --- a/packages/cmd/src/api/cache.ts +++ b/packages/cmd/src/api/cache.ts @@ -1,8 +1,8 @@ -import { debug as _debug } from "../debug"; -import { makeRequest } from "../http"; -import { ClientType } from "../http/client"; +import { debug as _debug } from '../debug'; +import { makeRequest } from '../http'; +import { ClientType } from '../http/client'; -const debug = _debug.extend("api"); +const debug = _debug.extend('api'); export type CacheRequestConfigParams = { matrixIndex?: number; @@ -32,36 +32,36 @@ export type CacheRetrievalResponse = { export async function createCache(params: CacheRequestParams) { try { - debug("Request params: %o", params); + debug('Request params: %o', params); return makeRequest( ClientType.API, { - url: "cache/upload", - method: "POST", + url: 'cache/upload', + method: 'POST', data: params, } ).then((res) => res.data); } catch (err) { - debug("Failed to create cache:", err); + debug('Failed to create cache:', err); throw err; } } export async function retrieveCache(params: CacheRequestParams) { try { - debug("Request params: %o", params); + debug('Request params: %o', params); return makeRequest( ClientType.API, { - url: "cache/download", - method: "POST", + url: 'cache/download', + method: 'POST', data: params, } ).then((res) => res.data); } catch (err) { - debug("Failed to retrieve cache:", err); + debug('Failed to retrieve cache:', err); throw err; } } diff --git a/packages/cmd/src/api/create-run.ts b/packages/cmd/src/api/create-run.ts index 81f40be..302c941 100644 --- a/packages/cmd/src/api/create-run.ts +++ b/packages/cmd/src/api/create-run.ts @@ -1,16 +1,16 @@ -import { Commit } from "@env/gitInfo"; -import { CiProvider, CiProviderData } from "@env/types"; -import { error } from "@logger"; -import { promisify } from "node:util"; -import { gzip } from "node:zlib"; -import { CurrentsConfig } from "../config/upload"; -import { debug as _debug } from "../debug"; -import { makeRequest } from "../http"; -import { FullTestSuite } from "../services/upload/discovery"; -import { InstanceReport } from "../services/upload/types"; -import { ClientType } from "../http/client"; +import { Commit } from '@env/gitInfo'; +import { CiProvider, CiProviderData } from '@env/types'; +import { error } from '@logger'; +import { promisify } from 'node:util'; +import { gzip } from 'node:zlib'; +import { CurrentsConfig } from '../config/upload'; +import { debug as _debug } from '../debug'; +import { makeRequest } from '../http'; +import { FullTestSuite } from '../services/upload/discovery'; +import { InstanceReport } from '../services/upload/types'; +import { ClientType } from '../http/client'; -const debug = _debug.extend("api"); +const debug = _debug.extend('api'); const gzipPromise = promisify(gzip); export type Platform = { @@ -74,20 +74,20 @@ export type CreateRunResponse = { export async function createRun(params: CreateRunParams) { try { - debug("Run params: %o", params); + debug('Run params: %o', params); const data = await compressData(JSON.stringify(params)); return makeRequest(ClientType.API, { url: `v1/runs`, - method: "POST", + method: 'POST', headers: { - "Content-Type": "application/json", - "Content-Encoding": "gzip", + 'Content-Type': 'application/json', + 'Content-Encoding': 'gzip', }, data, }).then((res) => res.data); } catch (err) { - debug("Failed to create the run:", err); + debug('Failed to create the run:', err); throw err; } } @@ -96,7 +96,7 @@ async function compressData(data: string | Buffer): Promise { try { return await gzipPromise(data); } catch (err) { - error("Failed to compress run payload:", err); + error('Failed to compress run payload:', err); throw err; } } diff --git a/packages/cmd/src/api/get-run.ts b/packages/cmd/src/api/get-run.ts index 78447e2..3c74bda 100644 --- a/packages/cmd/src/api/get-run.ts +++ b/packages/cmd/src/api/get-run.ts @@ -1,8 +1,8 @@ -import { debug as _debug } from "../debug"; -import { makeRequest } from "../http"; -import { ClientType } from "../http/client"; +import { debug as _debug } from '../debug'; +import { makeRequest } from '../http'; +import { ClientType } from '../http/client'; -const debug = _debug.extend("api"); +const debug = _debug.extend('api'); export type GetRunParams = { projectId: string; @@ -18,24 +18,24 @@ export type GetRunResponse< }, > = { data: T; - status: "OK"; + status: 'OK'; }; export async function getRun(apiKey: string, params: GetRunParams) { try { - debug("Run params: %o", params); + debug('Run params: %o', params); return makeRequest(ClientType.REST_API, { url: `v1/runs/previous`, params, - method: "GET", + method: 'GET', headers: { - "Content-Type": "application/json", + 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}`, }, }).then((res) => res.data); } catch (err) { - debug("Failed to obtain run data:", err); + debug('Failed to obtain run data:', err); throw err; } } diff --git a/packages/cmd/src/api/index.ts b/packages/cmd/src/api/index.ts index f2414a5..2e7cc0f 100644 --- a/packages/cmd/src/api/index.ts +++ b/packages/cmd/src/api/index.ts @@ -1,4 +1,3 @@ -export * from "./cache"; -export * from "./create-run"; -export * from "./get-run"; - +export * from './cache'; +export * from './create-run'; +export * from './get-run'; diff --git a/packages/cmd/src/bin/index.ts b/packages/cmd/src/bin/index.ts index 039aada..eae2013 100644 --- a/packages/cmd/src/bin/index.ts +++ b/packages/cmd/src/bin/index.ts @@ -1,10 +1,10 @@ #! /usr/bin/env node -import "source-map-support/register"; +import 'source-map-support/register'; -import("dotenv/config"); +import('dotenv/config'); -import { getProgram } from "./program"; +import { getProgram } from './program'; function runScript() { getProgram().parse(); diff --git a/packages/cmd/src/bin/program.ts b/packages/cmd/src/bin/program.ts index b35233a..d4d0edb 100644 --- a/packages/cmd/src/bin/program.ts +++ b/packages/cmd/src/bin/program.ts @@ -1,8 +1,8 @@ -import { Command } from "@commander-js/extra-typings"; -import { reporterVersion } from "@env/versions"; -import { getApiCommand } from "../commands/api"; -import { getCacheCommand } from "../commands/cache"; -import { getUploadCommand } from "../commands/upload"; +import { Command } from '@commander-js/extra-typings'; +import { reporterVersion } from '@env/versions'; +import { getApiCommand } from '../commands/api'; +import { getCacheCommand } from '../commands/cache'; +import { getUploadCommand } from '../commands/upload'; const example = ` ---------------------------------------------------- @@ -11,7 +11,7 @@ const example = ` ---------------------------------------------------- `; -const NAME = "currents"; +const NAME = 'currents'; export const getProgram = () => new Command(NAME) .version(reporterVersion) diff --git a/packages/cmd/src/commands/api/get-run.ts b/packages/cmd/src/commands/api/get-run.ts index 452bb19..5d24db4 100644 --- a/packages/cmd/src/commands/api/get-run.ts +++ b/packages/cmd/src/commands/api/get-run.ts @@ -1,22 +1,22 @@ -import { debug as _debug } from "@debug"; -import { getRunCommand } from "."; +import { debug as _debug } from '@debug'; +import { getRunCommand } from '.'; import { getAPIGetRunCommandConfig, setAPIGetRunCommandConfig, -} from "../../config/api"; -import { handleGetRun } from "../../services"; -import { commandHandler } from "../utils"; +} from '../../config/api'; +import { handleGetRun } from '../../services'; +import { commandHandler } from '../utils'; -const debug = _debug.extend("cli"); +const debug = _debug.extend('cli'); export async function getRunHandler( - options: ReturnType["opts"]> + options: ReturnType['opts']> ) { await commandHandler(async (opts) => { setAPIGetRunCommandConfig(opts); const config = getAPIGetRunCommandConfig(); - debug("Config: %o", config); + debug('Config: %o', config); await handleGetRun(); }, options); } diff --git a/packages/cmd/src/commands/api/index.ts b/packages/cmd/src/commands/api/index.ts index 94bd5ec..923d253 100644 --- a/packages/cmd/src/commands/api/index.ts +++ b/packages/cmd/src/commands/api/index.ts @@ -1,7 +1,7 @@ -import { Command } from "@commander-js/extra-typings"; -import { dim } from "@logger"; -import chalk from "chalk"; -import { getRunHandler } from "./get-run"; +import { Command } from '@commander-js/extra-typings'; +import { dim } from '@logger'; +import chalk from 'chalk'; +import { getRunHandler } from './get-run'; import { apiKeyOption, branchOption, @@ -11,12 +11,12 @@ import { projectOption, pwLastRunOption, tagOption, -} from "./options"; +} from './options'; -const COMMAND_NAME = "api"; +const COMMAND_NAME = 'api'; const getExample = (name: string) => ` -${chalk.bold("Examples")} +${chalk.bold('Examples')} Obtain run data by --ci-build-id: ${dim(`${name} ${COMMAND_NAME} get-run --api-key --ci-build-id `)} @@ -32,7 +32,7 @@ ${dim(`${name} ${COMMAND_NAME} get-run --api-key --ci-build-id { const command = new Command() .command(COMMAND_NAME) - .showHelpAfterError("(add --help for additional information)") + .showHelpAfterError('(add --help for additional information)') .allowUnknownOption() .addCommand(getRunCommand(name)); @@ -41,7 +41,7 @@ export const getApiCommand = (name: string) => { export const getRunCommand = (name: string) => { const command = new Command() - .name("get-run") + .name('get-run') .description(`Receive information from Currents API ${getExample(name)}`) .allowUnknownOption() .addOption(apiKeyOption) diff --git a/packages/cmd/src/commands/api/options.ts b/packages/cmd/src/commands/api/options.ts index 6997a10..30696da 100644 --- a/packages/cmd/src/commands/api/options.ts +++ b/packages/cmd/src/commands/api/options.ts @@ -1,43 +1,43 @@ -import { Option } from "@commander-js/extra-typings"; -import { configKeys } from "../../config/api"; -import { getEnvironmentVariableName } from "../../config/utils"; -import { parseCommaSeparatedList } from "../utils"; +import { Option } from '@commander-js/extra-typings'; +import { configKeys } from '../../config/api'; +import { getEnvironmentVariableName } from '../../config/utils'; +import { parseCommaSeparatedList } from '../utils'; export const apiKeyOption = new Option( - "--api-key ", - "API key from Currents dashboard for authentication" -).env(getEnvironmentVariableName(configKeys, "apiKey")); + '--api-key ', + 'API key from Currents dashboard for authentication' +).env(getEnvironmentVariableName(configKeys, 'apiKey')); export const outputOption = new Option( - "-o, --output ", - "Path to the file where output will be written" -).env(getEnvironmentVariableName(configKeys, "output")); + '-o, --output ', + 'Path to the file where output will be written' +).env(getEnvironmentVariableName(configKeys, 'output')); export const ciBuildIdOption = new Option( - "--ci-build-id ", - "Unique identifier for the run" + '--ci-build-id ', + 'Unique identifier for the run' ); export const projectOption = new Option( - "-p, --project-id ", - "Project ID from Currents associated with the run" -).env(getEnvironmentVariableName(configKeys, "projectId")); + '-p, --project-id ', + 'Project ID from Currents associated with the run' +).env(getEnvironmentVariableName(configKeys, 'projectId')); export const tagOption = new Option( - "-t, --tag ", - "Comma-separated list of tags for the run" + '-t, --tag ', + 'Comma-separated list of tags for the run' ).argParser(parseCommaSeparatedList); -export const debugOption = new Option("--debug", "Enable debug logging") - .env(getEnvironmentVariableName(configKeys, "debug")) +export const debugOption = new Option('--debug', 'Enable debug logging') + .env(getEnvironmentVariableName(configKeys, 'debug')) .default(false); export const branchOption = new Option( - "-b, --branch ", - "Branch name for the recorded run" + '-b, --branch ', + 'Branch name for the recorded run' ); export const pwLastRunOption = new Option( - "--pw-last-run", + '--pw-last-run', 'Generate output formatted for Playwright ".last-run.json"' ); diff --git a/packages/cmd/src/commands/cache/get.ts b/packages/cmd/src/commands/cache/get.ts index 427d8fd..d9c3c3a 100644 --- a/packages/cmd/src/commands/cache/get.ts +++ b/packages/cmd/src/commands/cache/get.ts @@ -1,17 +1,17 @@ -import { debug as _debug } from "@debug"; -import { getCacheGetCommand } from "."; +import { debug as _debug } from '@debug'; +import { getCacheGetCommand } from '.'; import { cacheGetCommandOptsToConfig, getCacheCommandConfig, setCacheGetCommandConfig, -} from "../../config/cache"; -import { handleGetCache } from "../../services"; -import { commandHandler } from "../utils"; +} from '../../config/cache'; +import { handleGetCache } from '../../services'; +import { commandHandler } from '../utils'; -const debug = _debug.extend("cli"); +const debug = _debug.extend('cli'); export type CacheGetCommandOpts = ReturnType< - ReturnType["opts"] + ReturnType['opts'] >; export async function getCacheGetHandler(options: CacheGetCommandOpts) { @@ -19,9 +19,9 @@ export async function getCacheGetHandler(options: CacheGetCommandOpts) { setCacheGetCommandConfig(cacheGetCommandOptsToConfig(opts)); const config = getCacheCommandConfig(); - debug("Config: %o", { + debug('Config: %o', { ...config.values, - recordKey: config.values?.recordKey ? "*****" : undefined, + recordKey: config.values?.recordKey ? '*****' : undefined, }); await handleGetCache(); diff --git a/packages/cmd/src/commands/cache/index.ts b/packages/cmd/src/commands/cache/index.ts index 51e1044..01b32b3 100644 --- a/packages/cmd/src/commands/cache/index.ts +++ b/packages/cmd/src/commands/cache/index.ts @@ -1,7 +1,7 @@ -import { Command } from "@commander-js/extra-typings"; -import { dim } from "@logger"; -import chalk from "chalk"; -import { getCacheGetHandler } from "./get"; +import { Command } from '@commander-js/extra-typings'; +import { dim } from '@logger'; +import chalk from 'chalk'; +import { getCacheGetHandler } from './get'; import { debugOption, idOption, @@ -13,13 +13,13 @@ import { presetOutputOption, pwOutputDirOption, recordKeyOption, -} from "./options"; -import { getCacheSetHandler } from "./set"; +} from './options'; +import { getCacheSetHandler } from './set'; -const COMMAND_NAME = "cache"; +const COMMAND_NAME = 'cache'; const getExample = (name: string) => ` -${chalk.bold("Examples")} +${chalk.bold('Examples')} Save files to the cache under a specific ID: ${dim(`${name} ${COMMAND_NAME} set --key --id --paths `)} @@ -42,7 +42,7 @@ export const getCacheCommand = (name: string) => { const command = new Command() .command(COMMAND_NAME) .description(`Cache data to Currents ${getExample(name)}`) - .showHelpAfterError("(add --help for additional information)") + .showHelpAfterError('(add --help for additional information)') .allowUnknownOption() .addCommand(getCacheSetCommand()) .addCommand(getCacheGetCommand()); @@ -52,7 +52,7 @@ export const getCacheCommand = (name: string) => { export const getCacheSetCommand = () => { const command = new Command() - .name("set") + .name('set') .allowUnknownOption() .addOption(recordKeyOption) .addOption(idOption) @@ -69,7 +69,7 @@ export const getCacheSetCommand = () => { export const getCacheGetCommand = () => { const command = new Command() - .name("get") + .name('get') .allowUnknownOption() .addOption(recordKeyOption) .addOption(idOption) diff --git a/packages/cmd/src/commands/cache/options.ts b/packages/cmd/src/commands/cache/options.ts index 5cbe955..b01700d 100644 --- a/packages/cmd/src/commands/cache/options.ts +++ b/packages/cmd/src/commands/cache/options.ts @@ -1,62 +1,62 @@ -import { InvalidArgumentError, Option } from "@commander-js/extra-typings"; -import { configKeys } from "../../config/cache"; -import { getEnvironmentVariableName } from "../../config/utils"; -import { parseCommaSeparatedList } from "../utils"; +import { InvalidArgumentError, Option } from '@commander-js/extra-typings'; +import { configKeys } from '../../config/cache'; +import { getEnvironmentVariableName } from '../../config/utils'; +import { parseCommaSeparatedList } from '../utils'; export const recordKeyOption = new Option( - "-k, --key ", - "Your secret Record Key obtained from Currents" -).env(getEnvironmentVariableName(configKeys, "recordKey")); + '-k, --key ', + 'Your secret Record Key obtained from Currents' +).env(getEnvironmentVariableName(configKeys, 'recordKey')); -export const debugOption = new Option("--debug", "Enable debug logging") - .env(getEnvironmentVariableName(configKeys, "debug")) +export const debugOption = new Option('--debug', 'Enable debug logging') + .env(getEnvironmentVariableName(configKeys, 'debug')) .default(false); export const idOption = new Option( - "--id ", - "The ID the data is saved under in the cache" + '--id ', + 'The ID the data is saved under in the cache' ); export const pathsOption = new Option( - "--paths ", - "Comma-separated list of paths to cache" + '--paths ', + 'Comma-separated list of paths to cache' ).argParser(parseCommaSeparatedList); export enum PRESETS { - lastRun = "last-run", + lastRun = 'last-run', } export const presetOption = new Option( - "--preset ", + '--preset ', 'A set of predefined options. Use "last-run" to get the last run data' ).choices(Object.values(PRESETS)); export const outputDirOption = new Option( - "--output-dir ", - "Path to the directory where output will be written" + '--output-dir ', + 'Path to the directory where output will be written' ); export const pwOutputDirOption = new Option( - "--pw-output-dir ", - "Directory for artifacts produced by Playwright tests" -).default("test-results"); + '--pw-output-dir ', + 'Directory for artifacts produced by Playwright tests' +).default('test-results'); -export const PRESET_OUTPUT_PATH = ".currents_env"; +export const PRESET_OUTPUT_PATH = '.currents_env'; export const presetOutputOption = new Option( - "--preset-output ", - "Path to the file containing the preset output" + '--preset-output ', + 'Path to the file containing the preset output' ).default(PRESET_OUTPUT_PATH); export const matrixIndexOption = new Option( - "--matrix-index ", - "The index of the matrix to use" + '--matrix-index ', + 'The index of the matrix to use' ) .default(1) .argParser(validatePositiveInteger); export const matrixTotalOption = new Option( - "--matrix-total ", - "The total number of matrices available" + '--matrix-total ', + 'The total number of matrices available' ) .default(1) .argParser(validatePositiveInteger); @@ -68,7 +68,7 @@ function validatePositiveInteger(value: string) { parsedValue <= 0 || !Number.isInteger(parsedValue) ) { - throw new InvalidArgumentError("A positive integer is expected."); + throw new InvalidArgumentError('A positive integer is expected.'); } return parsedValue; } diff --git a/packages/cmd/src/commands/cache/set.ts b/packages/cmd/src/commands/cache/set.ts index 749f0af..c118af5 100644 --- a/packages/cmd/src/commands/cache/set.ts +++ b/packages/cmd/src/commands/cache/set.ts @@ -1,17 +1,17 @@ -import { debug as _debug } from "@debug"; -import { getCacheSetCommand } from "."; +import { debug as _debug } from '@debug'; +import { getCacheSetCommand } from '.'; import { cacheSetCommandOptsToConfig, getCacheCommandConfig, setCacheSetCommandConfig, -} from "../../config/cache"; -import { handleSetCache } from "../../services"; -import { commandHandler } from "../utils"; +} from '../../config/cache'; +import { handleSetCache } from '../../services'; +import { commandHandler } from '../utils'; -const debug = _debug.extend("cli"); +const debug = _debug.extend('cli'); export type CacheSetCommandOpts = ReturnType< - ReturnType["opts"] + ReturnType['opts'] >; export async function getCacheSetHandler(options: CacheSetCommandOpts) { @@ -19,9 +19,9 @@ export async function getCacheSetHandler(options: CacheSetCommandOpts) { setCacheSetCommandConfig(cacheSetCommandOptsToConfig(opts)); const config = getCacheCommandConfig(); - debug("Config: %o", { + debug('Config: %o', { ...config.values, - recordKey: config.values?.recordKey ? "*****" : undefined, + recordKey: config.values?.recordKey ? '*****' : undefined, }); await handleSetCache(); diff --git a/packages/cmd/src/commands/upload/cli-config.ts b/packages/cmd/src/commands/upload/cli-config.ts index 5b253ea..c401bb1 100644 --- a/packages/cmd/src/commands/upload/cli-config.ts +++ b/packages/cmd/src/commands/upload/cli-config.ts @@ -1,9 +1,13 @@ -import { debug as _debug } from "@debug"; -import fs from "fs"; -import { CLIOptions, cliOptionsToConfig, CurrentsConfig } from "../../config/upload"; -import { createTempFile } from "./tmp-file"; +import { debug as _debug } from '@debug'; +import fs from 'fs'; +import { + CLIOptions, + cliOptionsToConfig, + CurrentsConfig, +} from '../../config/upload'; +import { createTempFile } from './tmp-file'; -const debug = _debug.extend("cli"); +const debug = _debug.extend('cli'); export class CLIManager { cliOptions: CLIOptions; @@ -12,10 +16,10 @@ export class CLIManager { constructor(opts: CLIOptions) { this.cliOptions = opts; - debug("CLI options: %o", this.cliOptions); + debug('CLI options: %o', this.cliOptions); this.parsedConfig = cliOptionsToConfig(this.cliOptions); - debug("Parsed config from CLI options: %o", this.parsedConfig); + debug('Parsed config from CLI options: %o', this.parsedConfig); } async getConfigFilePath() { @@ -24,7 +28,7 @@ export class CLIManager { } const tempFilePath = await createTempFile(); fs.writeFileSync(tempFilePath, JSON.stringify(this.parsedConfig)); - debug("CLI options temp file path: %s", tempFilePath); + debug('CLI options temp file path: %s', tempFilePath); this.configFilePath = tempFilePath; return tempFilePath; } diff --git a/packages/cmd/src/commands/upload/index.ts b/packages/cmd/src/commands/upload/index.ts index bbaf36b..13073af 100644 --- a/packages/cmd/src/commands/upload/index.ts +++ b/packages/cmd/src/commands/upload/index.ts @@ -1,6 +1,6 @@ -import { Command } from "@commander-js/extra-typings"; -import chalk from "chalk"; -import { dim } from "@logger"; +import { Command } from '@commander-js/extra-typings'; +import chalk from 'chalk'; +import { dim } from '@logger'; import { ciBuildIdOption, debugOption, @@ -11,14 +11,14 @@ import { removeTagOption, reportDirOption, tagOption, -} from "./options"; -import { uploadHandler } from "./upload"; +} from './options'; +import { uploadHandler } from './upload'; -const COMMAND_NAME = "upload"; +const COMMAND_NAME = 'upload'; const getExample = (name: string) => ` -${chalk.bold("Examples")} +${chalk.bold('Examples')} Upload test results to Currents: ${dim(`${name} ${COMMAND_NAME} --key --project-id --ci-build-id `)} @@ -39,7 +39,7 @@ export const getUploadCommand = (name: string) => { const command = new Command() .name(COMMAND_NAME) .command(COMMAND_NAME) - .showHelpAfterError("(add --help for additional information)") + .showHelpAfterError('(add --help for additional information)') .allowUnknownOption() .description( `Upload test results generated by Currents reporters to https://currents.dev diff --git a/packages/cmd/src/commands/upload/options.ts b/packages/cmd/src/commands/upload/options.ts index a9fb3d4..e24282f 100644 --- a/packages/cmd/src/commands/upload/options.ts +++ b/packages/cmd/src/commands/upload/options.ts @@ -1,49 +1,49 @@ -import { Option } from "@commander-js/extra-typings"; +import { Option } from '@commander-js/extra-typings'; -import { configKeys } from "../../config/upload"; -import { getEnvironmentVariableName } from "../../config/utils"; -import { parseCommaSeparatedList } from "../utils"; +import { configKeys } from '../../config/upload'; +import { getEnvironmentVariableName } from '../../config/utils'; +import { parseCommaSeparatedList } from '../utils'; export const ciBuildIdOption = new Option( - "--ci-build-id ", - "the unique identifier for the recorded build (run)" -).env(getEnvironmentVariableName(configKeys, "ciBuildId")); + '--ci-build-id ', + 'the unique identifier for the recorded build (run)' +).env(getEnvironmentVariableName(configKeys, 'ciBuildId')); export const recordKeyOption = new Option( - "-k, --key ", - "your secret Record Key obtained from Currents" -).env(getEnvironmentVariableName(configKeys, "recordKey")); + '-k, --key ', + 'your secret Record Key obtained from Currents' +).env(getEnvironmentVariableName(configKeys, 'recordKey')); export const projectOption = new Option( - "-p, --project-id ", - "the project ID for results reporting obtained from Currents" -).env(getEnvironmentVariableName(configKeys, "projectId")); + '-p, --project-id ', + 'the project ID for results reporting obtained from Currents' +).env(getEnvironmentVariableName(configKeys, 'projectId')); export const tagOption = new Option( - "-t, --tag ", - "comma-separated tag(s) for recorded runs in Currents" + '-t, --tag ', + 'comma-separated tag(s) for recorded runs in Currents' ).argParser(parseCommaSeparatedList); export const removeTagOption = new Option( - "--remove-title-tags", - "remove tags from test names in Currents, e.g. `Test name @smoke` becomes `Test name` in the dashboard" + '--remove-title-tags', + 'remove tags from test names in Currents, e.g. `Test name @smoke` becomes `Test name` in the dashboard' ).default(false); export const disableTitleTagsOption = new Option( - "--disable-title-tags", - "disable parsing tags from test title, e.g. `Test name @smoke` would not be tagged with `smoke` in the dashboard" + '--disable-title-tags', + 'disable parsing tags from test title, e.g. `Test name @smoke` would not be tagged with `smoke` in the dashboard' ).default(false); export const machineIdOption = new Option( - "--machine-id ", - "unique identifier of the machine running the tests. If not provided, it will be generated automatically. See: https://docs.currents.dev/?q=machineId" -).env(getEnvironmentVariableName(configKeys, "machineId")); + '--machine-id ', + 'unique identifier of the machine running the tests. If not provided, it will be generated automatically. See: https://docs.currents.dev/?q=machineId' +).env(getEnvironmentVariableName(configKeys, 'machineId')); export const reportDirOption = new Option( - "--report-dir ", - "explicit path to the report directory" -).env(getEnvironmentVariableName(configKeys, "reportDir")); + '--report-dir ', + 'explicit path to the report directory' +).env(getEnvironmentVariableName(configKeys, 'reportDir')); -export const debugOption = new Option("--debug", "enable debug logs") - .env(getEnvironmentVariableName(configKeys, "debug")) +export const debugOption = new Option('--debug', 'enable debug logs') + .env(getEnvironmentVariableName(configKeys, 'debug')) .default(false); diff --git a/packages/cmd/src/commands/upload/tmp-file.ts b/packages/cmd/src/commands/upload/tmp-file.ts index 7ecbb6d..13d5459 100644 --- a/packages/cmd/src/commands/upload/tmp-file.ts +++ b/packages/cmd/src/commands/upload/tmp-file.ts @@ -1,4 +1,4 @@ -import { file } from "tmp-promise"; +import { file } from 'tmp-promise'; export const createTempFile = async () => { const { path } = await file(); diff --git a/packages/cmd/src/commands/upload/upload.ts b/packages/cmd/src/commands/upload/upload.ts index b4522da..0a9c033 100644 --- a/packages/cmd/src/commands/upload/upload.ts +++ b/packages/cmd/src/commands/upload/upload.ts @@ -1,22 +1,22 @@ -import { info } from "@logger"; -import { getUploadCommand } from "."; +import { info } from '@logger'; +import { getUploadCommand } from '.'; -import { getCurrentsConfig, setCurrentsConfig } from "../../config/upload"; -import { handleCurrentsReport } from "../../services"; -import { commandHandler } from "../utils"; -import { CLIManager } from "./cli-config"; +import { getCurrentsConfig, setCurrentsConfig } from '../../config/upload'; +import { handleCurrentsReport } from '../../services'; +import { commandHandler } from '../utils'; +import { CLIManager } from './cli-config'; export async function uploadHandler( - options: ReturnType["opts"]> + options: ReturnType['opts']> ) { await commandHandler(async (opts) => { const cliManager = new CLIManager(opts); setCurrentsConfig(cliManager.parsedConfig); const config = getCurrentsConfig(); - info("Currents config: %o", { + info('Currents config: %o', { ...config, - recordKey: config?.recordKey ? "*****" : undefined, + recordKey: config?.recordKey ? '*****' : undefined, }); await handleCurrentsReport(); diff --git a/packages/cmd/src/commands/utils.ts b/packages/cmd/src/commands/utils.ts index f279cbd..0573156 100644 --- a/packages/cmd/src/commands/utils.ts +++ b/packages/cmd/src/commands/utils.ts @@ -1,15 +1,15 @@ -import { CommanderError } from "@commander-js/extra-typings"; -import { ValidationError } from "@lib"; -import { error } from "@logger"; -import { isAxiosError } from "axios"; -import { enableDebug } from "../debug"; +import { CommanderError } from '@commander-js/extra-typings'; +import { ValidationError } from '@lib'; +import { error } from '@logger'; +import { isAxiosError } from 'axios'; +import { enableDebug } from '../debug'; export function parseCommaSeparatedList( value: string, previous: string[] = [] ) { if (value) { - return previous.concat(value.split(",").map((t) => t.trim())); + return previous.concat(value.split(',').map((t) => t.trim())); } return previous; } @@ -40,7 +40,7 @@ export async function commandHandler>( process.exit(1); } - error("Script execution failed: %o", e); + error('Script execution failed: %o', e); process.exit(1); } } diff --git a/packages/cmd/src/config/api/config.ts b/packages/cmd/src/config/api/config.ts index bf0b30f..e4615a3 100644 --- a/packages/cmd/src/config/api/config.ts +++ b/packages/cmd/src/config/api/config.ts @@ -1,9 +1,9 @@ -import { debug as _debug } from "@debug"; +import { debug as _debug } from '@debug'; -import { getValidatedConfig } from "../utils"; -import { configKeys, getEnvVariables } from "./env"; +import { getValidatedConfig } from '../utils'; +import { configKeys, getEnvVariables } from './env'; -const debug = _debug.extend("config"); +const debug = _debug.extend('config'); export type APICommandConfig = { /** @@ -60,11 +60,11 @@ export type APIGetRunCommandConfig = { output?: string; }; -type MandatoryAPICommandConfigKeys = "apiKey" | "projectId"; +type MandatoryAPICommandConfigKeys = 'apiKey' | 'projectId'; const mandatoryConfigKeys: MandatoryAPICommandConfigKeys[] = [ - "apiKey", - "projectId", + 'apiKey', + 'projectId', ]; let _config: (APICommandConfig & APIGetRunCommandConfig) | null = null; @@ -78,7 +78,7 @@ export function setAPIGetRunCommandConfig( getEnvVariables, options ); - debug("Resolved config: %o", _config); + debug('Resolved config: %o', _config); } export function getAPIGetRunCommandConfig() { diff --git a/packages/cmd/src/config/api/env.ts b/packages/cmd/src/config/api/env.ts index eb4fe28..b83004c 100644 --- a/packages/cmd/src/config/api/env.ts +++ b/packages/cmd/src/config/api/env.ts @@ -1,40 +1,40 @@ -import { APICommandConfig } from "./config"; +import { APICommandConfig } from './config'; const apiCommandConfigKeys = { apiKey: { - name: "Api Key", - env: "CURRENTS_API_KEY", - cli: "--api-key", + name: 'Api Key', + env: 'CURRENTS_API_KEY', + cli: '--api-key', }, debug: { - name: "Debug", - env: "CURRENTS_DEBUG", - cli: "--debug", + name: 'Debug', + env: 'CURRENTS_DEBUG', + cli: '--debug', }, } as const; const apiGetRunCommandConfigKeys = { branch: { - name: "Run Branch", - cli: "--branch", + name: 'Run Branch', + cli: '--branch', }, output: { - name: "Output Path", - env: "CURRENTS_OUTPUT", - cli: "--output", + name: 'Output Path', + env: 'CURRENTS_OUTPUT', + cli: '--output', }, ciBuildId: { - name: "CI Build ID", - cli: "--ci-build-id", + name: 'CI Build ID', + cli: '--ci-build-id', }, projectId: { - name: "Project ID", - env: "CURRENTS_PROJECT_ID", - cli: "--project-id", + name: 'Project ID', + env: 'CURRENTS_PROJECT_ID', + cli: '--project-id', }, tag: { - name: "Run Tag", - cli: "--tag", + name: 'Run Tag', + cli: '--tag', }, } as const; diff --git a/packages/cmd/src/config/api/index.ts b/packages/cmd/src/config/api/index.ts index 55623fe..01e26b3 100644 --- a/packages/cmd/src/config/api/index.ts +++ b/packages/cmd/src/config/api/index.ts @@ -1,2 +1,2 @@ -export * from "./config"; -export * from "./env"; +export * from './config'; +export * from './env'; diff --git a/packages/cmd/src/config/cache/config.ts b/packages/cmd/src/config/cache/config.ts index 322f5dd..4a02f48 100644 --- a/packages/cmd/src/config/cache/config.ts +++ b/packages/cmd/src/config/cache/config.ts @@ -1,9 +1,9 @@ -import { debug as _debug } from "@debug"; +import { debug as _debug } from '@debug'; -import { getValidatedConfig } from "../utils"; -import { configKeys, getEnvVariables } from "./env"; +import { getValidatedConfig } from '../utils'; +import { configKeys, getEnvVariables } from './env'; -const debug = _debug.extend("config"); +const debug = _debug.extend('config'); export type CacheCommandConfig = { /** @@ -36,25 +36,25 @@ export type CacheGetCommandConfig = CacheCommandConfig & presetOutput?: string; }; -type MandatoryCacheCommandKeys = "recordKey"; +type MandatoryCacheCommandKeys = 'recordKey'; -const mandatoryConfigKeys: MandatoryCacheCommandKeys[] = ["recordKey"]; +const mandatoryConfigKeys: MandatoryCacheCommandKeys[] = ['recordKey']; let _config: | { - type: "SET_COMMAND_CONFIG"; + type: 'SET_COMMAND_CONFIG'; values: (CacheCommandConfig & CacheSetCommandConfig) | null; } | { - type: "GET_COMMAND_CONFIG"; + type: 'GET_COMMAND_CONFIG'; values: (CacheCommandConfig & CacheGetCommandConfig) | null; }; export function setCacheSetCommandConfig( - options?: Partial> + options?: Partial> ) { _config = { - type: "SET_COMMAND_CONFIG", + type: 'SET_COMMAND_CONFIG', values: getValidatedConfig( configKeys, mandatoryConfigKeys, @@ -62,14 +62,14 @@ export function setCacheSetCommandConfig( options ), }; - debug("Resolved config: %o", _config); + debug('Resolved config: %o', _config); } export function setCacheGetCommandConfig( - options?: Partial> + options?: Partial> ) { _config = { - type: "GET_COMMAND_CONFIG", + type: 'GET_COMMAND_CONFIG', values: getValidatedConfig( configKeys, mandatoryConfigKeys, @@ -77,7 +77,7 @@ export function setCacheGetCommandConfig( options ), }; - debug("Resolved config: %o", _config); + debug('Resolved config: %o', _config); } export function getCacheCommandConfig() { diff --git a/packages/cmd/src/config/cache/env.ts b/packages/cmd/src/config/cache/env.ts index ccc0610..9e71e6c 100644 --- a/packages/cmd/src/config/cache/env.ts +++ b/packages/cmd/src/config/cache/env.ts @@ -1,69 +1,69 @@ -import { CacheCommandConfig } from "./config"; +import { CacheCommandConfig } from './config'; const cacheCommandConfigKeys = { recordKey: { - name: "Record Key", - env: "CURRENTS_RECORD_KEY", - cli: "--key", + name: 'Record Key', + env: 'CURRENTS_RECORD_KEY', + cli: '--key', }, debug: { - name: "Debug", - env: "CURRENTS_DEBUG", - cli: "--debug", + name: 'Debug', + env: 'CURRENTS_DEBUG', + cli: '--debug', }, } as const; const cacheSetCommandConfigKeys = { id: { - name: "Cache id", - cli: "--id", + name: 'Cache id', + cli: '--id', }, preset: { - name: "Preset", - cli: "--preset", + name: 'Preset', + cli: '--preset', }, pwOutputDir: { - name: "Playwright output directory", - cli: "--pw-output-dir", + name: 'Playwright output directory', + cli: '--pw-output-dir', }, presetOutput: { - name: "Preset output path", - cli: "--preset-output", + name: 'Preset output path', + cli: '--preset-output', }, paths: { - name: "Paths to cache", - cli: "--paths", + name: 'Paths to cache', + cli: '--paths', }, matrixIndex: { - name: "Matrix index", - cli: "--matrix-index", + name: 'Matrix index', + cli: '--matrix-index', }, matrixTotal: { - name: "Matrix total", - cli: "--matrix-total", + name: 'Matrix total', + cli: '--matrix-total', }, } as const; const cacheGetCommandConfigKeys = { id: { - name: "Cache id", - cli: "--id", + name: 'Cache id', + cli: '--id', }, preset: { - name: "Preset", - cli: "--preset", + name: 'Preset', + cli: '--preset', }, outputDir: { - name: "Custom directory to write output", - cli: "--output-dir", + name: 'Custom directory to write output', + cli: '--output-dir', }, matrixIndex: { - name: "Matrix index", - cli: "--matrix-index", + name: 'Matrix index', + cli: '--matrix-index', }, matrixTotal: { - name: "Matrix total", - cli: "--matrix-total", + name: 'Matrix total', + cli: '--matrix-total', }, } as const; diff --git a/packages/cmd/src/config/cache/index.ts b/packages/cmd/src/config/cache/index.ts index b2d445e..4568c72 100644 --- a/packages/cmd/src/config/cache/index.ts +++ b/packages/cmd/src/config/cache/index.ts @@ -1,3 +1,3 @@ -export * from "./config"; -export * from "./env"; -export * from "./options"; +export * from './config'; +export * from './env'; +export * from './options'; diff --git a/packages/cmd/src/config/cache/options.ts b/packages/cmd/src/config/cache/options.ts index ff727c6..3ef7121 100644 --- a/packages/cmd/src/config/cache/options.ts +++ b/packages/cmd/src/config/cache/options.ts @@ -1,6 +1,6 @@ -import { CacheGetCommandOpts } from "../../commands/cache/get"; -import { CacheSetCommandOpts } from "../../commands/cache/set"; -import { CacheGetCommandConfig, CacheSetCommandConfig } from "./config"; +import { CacheGetCommandOpts } from '../../commands/cache/get'; +import { CacheSetCommandOpts } from '../../commands/cache/set'; +import { CacheGetCommandConfig, CacheSetCommandConfig } from './config'; export function cacheGetCommandOptsToConfig( options: CacheGetCommandOpts diff --git a/packages/cmd/src/config/upload/config.ts b/packages/cmd/src/config/upload/config.ts index 006692f..800d177 100644 --- a/packages/cmd/src/config/upload/config.ts +++ b/packages/cmd/src/config/upload/config.ts @@ -1,9 +1,9 @@ -import { debug as _debug } from "@debug"; +import { debug as _debug } from '@debug'; -import { getValidatedConfig } from "../utils"; -import { configKeys, getEnvVariables } from "./env"; +import { getValidatedConfig } from '../utils'; +import { configKeys, getEnvVariables } from './env'; -const debug = _debug.extend("config"); +const debug = _debug.extend('config'); export type CurrentsConfig = { /** @@ -52,11 +52,11 @@ export type CurrentsConfig = { debug?: boolean; }; -type MandatoryCurrentsConfigKeys = "projectId" | "recordKey"; +type MandatoryCurrentsConfigKeys = 'projectId' | 'recordKey'; const mandatoryConfigKeys: MandatoryCurrentsConfigKeys[] = [ - "projectId", - "recordKey", + 'projectId', + 'recordKey', ]; let _config: CurrentsConfig | null = null; @@ -72,7 +72,7 @@ export function setCurrentsConfig(reporterOptions?: Partial) { getEnvVariables, reporterOptions ); - debug("Resolved Currents config: %o", _config); + debug('Resolved Currents config: %o', _config); } export function getCurrentsConfig() { diff --git a/packages/cmd/src/config/upload/env.ts b/packages/cmd/src/config/upload/env.ts index 2985cdd..b39cb40 100644 --- a/packages/cmd/src/config/upload/env.ts +++ b/packages/cmd/src/config/upload/env.ts @@ -1,50 +1,50 @@ -import { CurrentsConfig } from "./config"; +import { CurrentsConfig } from './config'; export const configKeys = { debug: { - name: "Debug", - env: "CURRENTS_DEBUG", - cli: "--debug", + name: 'Debug', + env: 'CURRENTS_DEBUG', + cli: '--debug', }, ciBuildId: { - name: "CI Build ID", - env: "CURRENTS_CI_BUILD_ID", - cli: "--ci-build-id", + name: 'CI Build ID', + env: 'CURRENTS_CI_BUILD_ID', + cli: '--ci-build-id', }, recordKey: { - name: "Record Key", - env: "CURRENTS_RECORD_KEY", - cli: "--key", + name: 'Record Key', + env: 'CURRENTS_RECORD_KEY', + cli: '--key', }, projectId: { - name: "Project ID", - env: "CURRENTS_PROJECT_ID", - cli: "--project-id", + name: 'Project ID', + env: 'CURRENTS_PROJECT_ID', + cli: '--project-id', }, tag: { - name: "Currents Tag", - env: "CURRENTS_TAG", - cli: "--tag", + name: 'Currents Tag', + env: 'CURRENTS_TAG', + cli: '--tag', }, disableTitleTags: { - name: "Disable Title Tags", - env: "CURRENTS_DISABLE_TITLE_TAGS", - cli: "--disable-title-tags", + name: 'Disable Title Tags', + env: 'CURRENTS_DISABLE_TITLE_TAGS', + cli: '--disable-title-tags', }, removeTitleTags: { - name: "Remove Title Tags", - env: "CURRENTS_REMOVE_TITLE_TAGS", - cli: "--remove-title-tags", + name: 'Remove Title Tags', + env: 'CURRENTS_REMOVE_TITLE_TAGS', + cli: '--remove-title-tags', }, machineId: { - name: "Machine ID", - env: "CURRENTS_MACHINE_ID", - cli: "--machine-id", + name: 'Machine ID', + env: 'CURRENTS_MACHINE_ID', + cli: '--machine-id', }, reportDir: { - name: "Report Directory", - env: "CURRENTS_REPORT_DIR", - cli: "--report-dir", + name: 'Report Directory', + env: 'CURRENTS_REPORT_DIR', + cli: '--report-dir', }, } as const; @@ -60,7 +60,7 @@ export function getEnvVariables(): Partial< recordKey: process.env[configKeys.recordKey.env], ciBuildId: process.env[configKeys.ciBuildId.env], tag: process.env[configKeys.tag.env] - ? process.env[configKeys.tag.env]?.split(",").map((i) => i.trim()) + ? process.env[configKeys.tag.env]?.split(',').map((i) => i.trim()) : undefined, disableTitleTags: !!process.env[configKeys.disableTitleTags.env], removeTitleTags: !!process.env[configKeys.removeTitleTags.env], diff --git a/packages/cmd/src/config/upload/index.ts b/packages/cmd/src/config/upload/index.ts index b2d445e..4568c72 100644 --- a/packages/cmd/src/config/upload/index.ts +++ b/packages/cmd/src/config/upload/index.ts @@ -1,3 +1,3 @@ -export * from "./config"; -export * from "./env"; -export * from "./options"; +export * from './config'; +export * from './env'; +export * from './options'; diff --git a/packages/cmd/src/config/upload/options.ts b/packages/cmd/src/config/upload/options.ts index c05f24f..634af00 100644 --- a/packages/cmd/src/config/upload/options.ts +++ b/packages/cmd/src/config/upload/options.ts @@ -1,11 +1,9 @@ -import { Command } from "@commander-js/extra-typings"; -import { getUploadCommand } from "../../commands/upload"; -import { CurrentsConfig } from "./config"; +import { Command } from '@commander-js/extra-typings'; +import { getUploadCommand } from '../../commands/upload'; +import { CurrentsConfig } from './config'; type ExtractSecondTags = T extends Command ? U : never; -export type CLIOptions = ExtractSecondTags< - ReturnType ->; +export type CLIOptions = ExtractSecondTags>; /** * Converts CLI options to Currents config. diff --git a/packages/cmd/src/config/utils.ts b/packages/cmd/src/config/utils.ts index 31679ce..6ab9dfc 100644 --- a/packages/cmd/src/config/utils.ts +++ b/packages/cmd/src/config/utils.ts @@ -1,6 +1,6 @@ -import { debug as _debug } from "@debug"; -import { ValidationError } from "@lib/error"; -import { dim, error } from "@logger"; +import { debug as _debug } from '@debug'; +import { ValidationError } from '@lib/error'; +import { dim, error } from '@logger'; type ConfigKeys = Record< string, @@ -27,9 +27,9 @@ export function getEnvironmentVariableName( configKeys: T, variable: keyof T ) { - return "env" in configKeys[variable] && !!configKeys[variable].env + return 'env' in configKeys[variable] && !!configKeys[variable].env ? configKeys[variable].env - : ""; + : ''; } export function getCLIOptionName( @@ -69,7 +69,7 @@ export function getValidatedConfig( - as environment variable: ${dim(getEnvironmentVariableName(configKeys, i as string))} - as CLI flag of the command: ${dim(getCLIOptionName(configKeys, i as string))}` ); - throw new ValidationError("Missing required config variable"); + throw new ValidationError('Missing required config variable'); } }); diff --git a/packages/cmd/src/debug/index.ts b/packages/cmd/src/debug/index.ts index c7c816f..ae8b6b7 100644 --- a/packages/cmd/src/debug/index.ts +++ b/packages/cmd/src/debug/index.ts @@ -1,12 +1,12 @@ -import { debug as Debug, Debugger } from "debug"; -import fs from "fs-extra"; +import { debug as Debug, Debugger } from 'debug'; +import fs from 'fs-extra'; -export const debug = Debug("currents"); +export const debug = Debug('currents'); let _traceFilePath: string | null = null; export function enableDebug() { - Debug.enable("currents,currents:*"); + Debug.enable('currents,currents:*'); } export function setTraceFilePath(path: string) { @@ -15,25 +15,25 @@ export function setTraceFilePath(path: string) { export function captureDebugToFile(debugInstance: Debugger) { if (!_traceFilePath) { - throw new Error("Trace file path is not set!"); + throw new Error('Trace file path is not set!'); } const { namespace, enabled } = debugInstance; Debug.enable(namespace); - const traceStream = fs.createWriteStream(_traceFilePath, { flags: "a" }); + const traceStream = fs.createWriteStream(_traceFilePath, { flags: 'a' }); const originalLog = Debug.log; Debug.log = (...args: any[]) => { - const message = args.map(String).join(" ") + "\n"; + const message = args.map(String).join(' ') + '\n'; traceStream.write(`[${new Date().toISOString()}]${message}}`); if (enabled) { originalLog.apply(Debug, args); } }; - process.on("exit", () => { + process.on('exit', () => { traceStream.end(); }); diff --git a/packages/cmd/src/env/__tests__/ciProvider.test.ts b/packages/cmd/src/env/__tests__/ciProvider.test.ts index 83ae0c0..214c362 100644 --- a/packages/cmd/src/env/__tests__/ciProvider.test.ts +++ b/packages/cmd/src/env/__tests__/ciProvider.test.ts @@ -1,44 +1,44 @@ -import { beforeEach, expect, it, vi } from "vitest"; -import { getCI } from "../ciProvider"; +import { beforeEach, expect, it, vi } from 'vitest'; +import { getCI } from '../ciProvider'; beforeEach(() => { vi.unstubAllEnvs(); }); -it("should return explicit ci build id", () => { - vi.stubEnv("GITHUB_ACTIONS", ""); // stub env to make sure CI doesn't fail the test - expect(getCI("ciBuildId")).toEqual({ +it('should return explicit ci build id', () => { + vi.stubEnv('GITHUB_ACTIONS', ''); // stub env to make sure CI doesn't fail the test + expect(getCI('ciBuildId')).toEqual({ ciBuildId: { - source: "user", - value: "ciBuildId", + source: 'user', + value: 'ciBuildId', }, params: {}, provider: null, }); }); -it("should return random ci build id", () => { - vi.stubEnv("GITHUB_ACTIONS", ""); // stub env to make sure CI doesn't fail the test +it('should return random ci build id', () => { + vi.stubEnv('GITHUB_ACTIONS', ''); // stub env to make sure CI doesn't fail the test expect(getCI(undefined)).toEqual({ ciBuildId: { - source: "random", - value: expect.stringContaining("auto:"), + source: 'random', + value: expect.stringContaining('auto:'), }, params: {}, provider: null, }); }); -it("should return server-detectable ci build id", () => { - vi.stubEnv("GITHUB_ACTIONS", "true"); - vi.stubEnv("GITHUB_WORKFLOW", "GITHUB_WORKFLOW"); - vi.stubEnv("GITHUB_ACTION", "GITHUB_ACTION"); - vi.stubEnv("GITHUB_RUN_ID", "GITHUB_RUN_ID"); - vi.stubEnv("GITHUB_RUN_ATTEMPT", "GITHUB_RUN_ATTEMPT"); +it('should return server-detectable ci build id', () => { + vi.stubEnv('GITHUB_ACTIONS', 'true'); + vi.stubEnv('GITHUB_WORKFLOW', 'GITHUB_WORKFLOW'); + vi.stubEnv('GITHUB_ACTION', 'GITHUB_ACTION'); + vi.stubEnv('GITHUB_RUN_ID', 'GITHUB_RUN_ID'); + vi.stubEnv('GITHUB_RUN_ATTEMPT', 'GITHUB_RUN_ATTEMPT'); expect(getCI(undefined)).toEqual({ ciBuildId: { - source: "server", + source: 'server', value: null, }, params: expect.objectContaining({ @@ -47,6 +47,6 @@ it("should return server-detectable ci build id", () => { githubRunId: expect.any(String), githubWorkflow: expect.any(String), }), - provider: "githubActions", + provider: 'githubActions', }); }); diff --git a/packages/cmd/src/env/__tests__/git-info.test.ts b/packages/cmd/src/env/__tests__/git-info.test.ts index 164f0f6..98d7f40 100644 --- a/packages/cmd/src/env/__tests__/git-info.test.ts +++ b/packages/cmd/src/env/__tests__/git-info.test.ts @@ -1,18 +1,18 @@ -import { describe, expect, it } from "vitest"; -import { mergeGitCommit } from "../git-ci-provider"; +import { describe, expect, it } from 'vitest'; +import { mergeGitCommit } from '../git-ci-provider'; -describe("git-info", () => { - it("should merge the git info for teamcity", () => { +describe('git-info', () => { + it('should merge the git info for teamcity', () => { const expected = { - branch: "main", - remoteOrigin: "origin", + branch: 'main', + remoteOrigin: 'origin', ghaEventData: null, }; // eslint-disable-next-line turbo/no-undeclared-env-vars - process.env.TEAMCITY_VERSION = "1"; + process.env.TEAMCITY_VERSION = '1'; const result = mergeGitCommit({ - branch: "main", - remoteOrigin: "origin", + branch: 'main', + remoteOrigin: 'origin', ghaEventData: null, }); expect(result).toMatchObject(expected); diff --git a/packages/cmd/src/env/ciProvider.ts b/packages/cmd/src/env/ciProvider.ts index 1ba1007..24fce9d 100644 --- a/packages/cmd/src/env/ciProvider.ts +++ b/packages/cmd/src/env/ciProvider.ts @@ -27,7 +27,7 @@ SOFTWARE. // import debugFn from "debug"; // @ts-ignore -import { userFacingNanoid } from "@lib/nano"; +import { userFacingNanoid } from '@lib/nano'; import { camelCase, chain, @@ -38,11 +38,11 @@ import { set, some, transform, -} from "lodash"; -import { debug as _debug } from "../debug"; -import { CiProvider, CiProviderData } from "./types"; +} from 'lodash'; +import { debug as _debug } from '../debug'; +import { CiProvider, CiProviderData } from './types'; -const debug = _debug.extend("ci"); +const debug = _debug.extend('ci'); const join = (char: string, ...pieces: (string | undefined)[]) => { return chain(pieces).compact().join(char).value(); @@ -86,7 +86,7 @@ const isBamboo = () => { const isCodeshipBasic = () => { return ( process.env.CI_NAME && - process.env.CI_NAME === "codeship" && + process.env.CI_NAME === 'codeship' && process.env.CODESHIP ); }; @@ -94,7 +94,7 @@ const isCodeshipBasic = () => { const isCodeshipPro = () => { return ( process.env.CI_NAME && - process.env.CI_NAME === "codeship" && + process.env.CI_NAME === 'codeship' && !process.env.CODESHIP ); }; @@ -146,31 +146,31 @@ const isWercker = () => { * variable "APPVEYOR" set during run */ const CI_PROVIDERS = { - appveyor: "APPVEYOR", + appveyor: 'APPVEYOR', azure: isAzureCi, awsCodeBuild: isAWSCodeBuild, bamboo: isBamboo, - bitbucket: "BITBUCKET_BUILD_NUMBER", - buildkite: "BUILDKITE", - circle: "CIRCLECI", + bitbucket: 'BITBUCKET_BUILD_NUMBER', + buildkite: 'BUILDKITE', + circle: 'CIRCLECI', codeshipBasic: isCodeshipBasic, codeshipPro: isCodeshipPro, concourse: isConcourse, - codeFresh: "CF_BUILD_ID", - drone: "DRONE", - githubActions: "GITHUB_ACTIONS", + codeFresh: 'CF_BUILD_ID', + drone: 'DRONE', + githubActions: 'GITHUB_ACTIONS', gitlab: isGitlab, - goCD: "GO_JOB_NAME", + goCD: 'GO_JOB_NAME', googleCloud: isGoogleCloud, jenkins: isJenkins, - semaphore: "SEMAPHORE", - shippable: "SHIPPABLE", - teamcity: "TEAMCITY_VERSION", + semaphore: 'SEMAPHORE', + shippable: 'SHIPPABLE', + teamcity: 'TEAMCITY_VERSION', teamfoundation: isTeamFoundation, - travis: "TRAVIS", + travis: 'TRAVIS', wercker: isWercker, - netlify: "NETLIFY", - layerci: "LAYERCI", + netlify: 'NETLIFY', + layerci: 'LAYERCI', }; function _detectProviderName(): string | undefined { @@ -192,109 +192,109 @@ function _detectProviderName(): string | undefined { const _providerCiParams = (): ProviderCiParamsRes => { return { appveyor: extract([ - "APPVEYOR_JOB_ID", - "APPVEYOR_ACCOUNT_NAME", - "APPVEYOR_PROJECT_SLUG", - "APPVEYOR_BUILD_NUMBER", - "APPVEYOR_BUILD_VERSION", - "APPVEYOR_PULL_REQUEST_NUMBER", - "APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH", + 'APPVEYOR_JOB_ID', + 'APPVEYOR_ACCOUNT_NAME', + 'APPVEYOR_PROJECT_SLUG', + 'APPVEYOR_BUILD_NUMBER', + 'APPVEYOR_BUILD_VERSION', + 'APPVEYOR_PULL_REQUEST_NUMBER', + 'APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH', ]), azure: extract([ - "BUILD_BUILDID", - "BUILD_BUILDNUMBER", - "BUILD_CONTAINERID", - "BUILD_REPOSITORY_URI", - "SYSTEM_TEAMPROJECT", - "SYSTEM_COLLECTIONURI", + 'BUILD_BUILDID', + 'BUILD_BUILDNUMBER', + 'BUILD_CONTAINERID', + 'BUILD_REPOSITORY_URI', + 'SYSTEM_TEAMPROJECT', + 'SYSTEM_COLLECTIONURI', ]), awsCodeBuild: extract([ - "CODEBUILD_BUILD_ID", - "CODEBUILD_BUILD_NUMBER", - "CODEBUILD_RESOLVED_SOURCE_VERSION", - "CODEBUILD_SOURCE_REPO_URL", - "CODEBUILD_SOURCE_VERSION", + 'CODEBUILD_BUILD_ID', + 'CODEBUILD_BUILD_NUMBER', + 'CODEBUILD_RESOLVED_SOURCE_VERSION', + 'CODEBUILD_SOURCE_REPO_URL', + 'CODEBUILD_SOURCE_VERSION', ]), bamboo: extract([ - "bamboo_buildNumber", - "bamboo_buildResultsUrl", - "bamboo_planRepository_repositoryUrl", - "bamboo_buildKey", + 'bamboo_buildNumber', + 'bamboo_buildResultsUrl', + 'bamboo_planRepository_repositoryUrl', + 'bamboo_buildKey', ]), bitbucket: extract([ - "BITBUCKET_REPO_SLUG", - "BITBUCKET_REPO_OWNER", - "BITBUCKET_BUILD_NUMBER", - "BITBUCKET_PARALLEL_STEP", - "BITBUCKET_STEP_RUN_NUMBER", + 'BITBUCKET_REPO_SLUG', + 'BITBUCKET_REPO_OWNER', + 'BITBUCKET_BUILD_NUMBER', + 'BITBUCKET_PARALLEL_STEP', + 'BITBUCKET_STEP_RUN_NUMBER', // the PR variables are only set on pull request builds - "BITBUCKET_PR_ID", - "BITBUCKET_PR_DESTINATION_BRANCH", - "BITBUCKET_PR_DESTINATION_COMMIT", + 'BITBUCKET_PR_ID', + 'BITBUCKET_PR_DESTINATION_BRANCH', + 'BITBUCKET_PR_DESTINATION_COMMIT', ]), buildkite: extract([ - "BUILDKITE_REPO", - "BUILDKITE_SOURCE", - "BUILDKITE_JOB_ID", - "BUILDKITE_BUILD_ID", - "BUILDKITE_BUILD_URL", - "BUILDKITE_BUILD_NUMBER", - "BUILDKITE_PULL_REQUEST", - "BUILDKITE_PULL_REQUEST_REPO", - "BUILDKITE_PULL_REQUEST_BASE_BRANCH", + 'BUILDKITE_REPO', + 'BUILDKITE_SOURCE', + 'BUILDKITE_JOB_ID', + 'BUILDKITE_BUILD_ID', + 'BUILDKITE_BUILD_URL', + 'BUILDKITE_BUILD_NUMBER', + 'BUILDKITE_PULL_REQUEST', + 'BUILDKITE_PULL_REQUEST_REPO', + 'BUILDKITE_PULL_REQUEST_BASE_BRANCH', ]), circle: extract([ - "CIRCLE_JOB", - "CIRCLE_BUILD_NUM", - "CIRCLE_BUILD_URL", - "CIRCLE_PR_NUMBER", - "CIRCLE_PR_REPONAME", - "CIRCLE_PR_USERNAME", - "CIRCLE_COMPARE_URL", - "CIRCLE_WORKFLOW_ID", - "CIRCLE_PULL_REQUEST", - "CIRCLE_REPOSITORY_URL", - "CI_PULL_REQUEST", + 'CIRCLE_JOB', + 'CIRCLE_BUILD_NUM', + 'CIRCLE_BUILD_URL', + 'CIRCLE_PR_NUMBER', + 'CIRCLE_PR_REPONAME', + 'CIRCLE_PR_USERNAME', + 'CIRCLE_COMPARE_URL', + 'CIRCLE_WORKFLOW_ID', + 'CIRCLE_PULL_REQUEST', + 'CIRCLE_REPOSITORY_URL', + 'CI_PULL_REQUEST', ]), codeshipBasic: extract([ - "CI_BUILD_ID", - "CI_REPO_NAME", - "CI_BUILD_URL", - "CI_PROJECT_ID", - "CI_BUILD_NUMBER", - "CI_PULL_REQUEST", + 'CI_BUILD_ID', + 'CI_REPO_NAME', + 'CI_BUILD_URL', + 'CI_PROJECT_ID', + 'CI_BUILD_NUMBER', + 'CI_PULL_REQUEST', ]), // CodeshipPro provides very few CI variables // https://documentation.codeship.com/pro/builds-and-configuration/environment-variables/ - codeshipPro: extract(["CI_BUILD_ID", "CI_REPO_NAME", "CI_PROJECT_ID"]), + codeshipPro: extract(['CI_BUILD_ID', 'CI_REPO_NAME', 'CI_PROJECT_ID']), // https://concourse-ci.org/implementing-resource-types.html#resource-metadata concourse: extract([ - "BUILD_ID", - "BUILD_NAME", - "BUILD_JOB_NAME", - "BUILD_PIPELINE_NAME", - "BUILD_TEAM_NAME", - "ATC_EXTERNAL_URL", + 'BUILD_ID', + 'BUILD_NAME', + 'BUILD_JOB_NAME', + 'BUILD_PIPELINE_NAME', + 'BUILD_TEAM_NAME', + 'ATC_EXTERNAL_URL', ]), // https://codefresh.io/docs/docs/codefresh-yaml/variables/ codeFresh: extract([ - "CF_BUILD_ID", - "CF_BUILD_URL", - "CF_CURRENT_ATTEMPT", - "CF_STEP_NAME", - "CF_PIPELINE_NAME", - "CF_PIPELINE_TRIGGER_ID", + 'CF_BUILD_ID', + 'CF_BUILD_URL', + 'CF_CURRENT_ATTEMPT', + 'CF_STEP_NAME', + 'CF_PIPELINE_NAME', + 'CF_PIPELINE_TRIGGER_ID', // variables added for pull requests - "CF_PULL_REQUEST_ID", - "CF_PULL_REQUEST_IS_FORK", - "CF_PULL_REQUEST_NUMBER", - "CF_PULL_REQUEST_TARGET", + 'CF_PULL_REQUEST_ID', + 'CF_PULL_REQUEST_IS_FORK', + 'CF_PULL_REQUEST_NUMBER', + 'CF_PULL_REQUEST_TARGET', ]), drone: extract([ - "DRONE_JOB_NUMBER", - "DRONE_BUILD_LINK", - "DRONE_BUILD_NUMBER", - "DRONE_PULL_REQUEST", + 'DRONE_JOB_NUMBER', + 'DRONE_BUILD_LINK', + 'DRONE_BUILD_NUMBER', + 'DRONE_PULL_REQUEST', ]), // https://help.github.com/en/actions/automating-your-workflow-with-github-actions/using-environment-variables#default-environment-variables githubActions: extract([ @@ -308,153 +308,153 @@ const _providerCiParams = (): ProviderCiParamsRes => { // see https://docs.gitlab.com/ee/ci/variables/ gitlab: extract([ // pipeline is common among all jobs - "CI_PIPELINE_ID", - "CI_PIPELINE_URL", + 'CI_PIPELINE_ID', + 'CI_PIPELINE_URL', // individual jobs - "CI_BUILD_ID", // build id and job id are aliases - "CI_JOB_ID", - "CI_JOB_URL", - "CI_JOB_NAME", + 'CI_BUILD_ID', // build id and job id are aliases + 'CI_JOB_ID', + 'CI_JOB_URL', + 'CI_JOB_NAME', // matrix information - "CI_NODE_INDEX", - "CI_NODE_TOTAL", + 'CI_NODE_INDEX', + 'CI_NODE_TOTAL', // other information - "GITLAB_HOST", - "CI_PROJECT_ID", - "CI_PROJECT_URL", - "CI_REPOSITORY_URL", - "CI_ENVIRONMENT_URL", - "CI_DEFAULT_BRANCH", + 'GITLAB_HOST', + 'CI_PROJECT_ID', + 'CI_PROJECT_URL', + 'CI_REPOSITORY_URL', + 'CI_ENVIRONMENT_URL', + 'CI_DEFAULT_BRANCH', // custom variables - "RUN_ATTEMPT", // custom param that we ourselves sometimes add for retrying jobs + 'RUN_ATTEMPT', // custom param that we ourselves sometimes add for retrying jobs // for PRs: https://gitlab.com/gitlab-org/gitlab-ce/issues/23902 ]), // https://docs.gocd.org/current/faq/dev_use_current_revision_in_build.html#standard-gocd-environment-variables goCD: extract([ - "GO_SERVER_URL", - "GO_ENVIRONMENT_NAME", - "GO_PIPELINE_NAME", - "GO_PIPELINE_COUNTER", - "GO_PIPELINE_LABEL", - "GO_STAGE_NAME", - "GO_STAGE_COUNTER", - "GO_JOB_NAME", - "GO_TRIGGER_USER", - "GO_REVISION", - "GO_TO_REVISION", - "GO_FROM_REVISION", - "GO_MATERIAL_HAS_CHANGED", + 'GO_SERVER_URL', + 'GO_ENVIRONMENT_NAME', + 'GO_PIPELINE_NAME', + 'GO_PIPELINE_COUNTER', + 'GO_PIPELINE_LABEL', + 'GO_STAGE_NAME', + 'GO_STAGE_COUNTER', + 'GO_JOB_NAME', + 'GO_TRIGGER_USER', + 'GO_REVISION', + 'GO_TO_REVISION', + 'GO_FROM_REVISION', + 'GO_MATERIAL_HAS_CHANGED', ]), googleCloud: extract([ // individual jobs - "BUILD_ID", - "PROJECT_ID", + 'BUILD_ID', + 'PROJECT_ID', // other information - "REPO_NAME", - "BRANCH_NAME", - "TAG_NAME", - "COMMIT_SHA", - "SHORT_SHA", + 'REPO_NAME', + 'BRANCH_NAME', + 'TAG_NAME', + 'COMMIT_SHA', + 'SHORT_SHA', // https://cloud.google.com/cloud-build/docs/api/reference/rest/Shared.Types/Build ]), - jenkins: extract(["BUILD_ID", "BUILD_URL", "BUILD_NUMBER", "ghprbPullId"]), + jenkins: extract(['BUILD_ID', 'BUILD_URL', 'BUILD_NUMBER', 'ghprbPullId']), // https://semaphoreci.com/docs/available-environment-variables.html // some come from v1, some from v2 of semaphore semaphore: extract([ - "SEMAPHORE_BRANCH_ID", - "SEMAPHORE_BUILD_NUMBER", - "SEMAPHORE_CURRENT_JOB", - "SEMAPHORE_CURRENT_THREAD", - "SEMAPHORE_EXECUTABLE_UUID", - "SEMAPHORE_GIT_BRANCH", - "SEMAPHORE_GIT_DIR", - "SEMAPHORE_GIT_REF", - "SEMAPHORE_GIT_REF_TYPE", - "SEMAPHORE_GIT_REPO_SLUG", - "SEMAPHORE_GIT_SHA", - "SEMAPHORE_GIT_URL", - "SEMAPHORE_JOB_COUNT", - "SEMAPHORE_JOB_ID", // v2 - "SEMAPHORE_JOB_NAME", - "SEMAPHORE_JOB_UUID", // v1 - "SEMAPHORE_PIPELINE_ID", - "SEMAPHORE_PLATFORM", - "SEMAPHORE_PROJECT_DIR", - "SEMAPHORE_PROJECT_HASH_ID", - "SEMAPHORE_PROJECT_ID", // v2 - "SEMAPHORE_PROJECT_NAME", - "SEMAPHORE_PROJECT_UUID", // v1 - "SEMAPHORE_REPO_SLUG", - "SEMAPHORE_TRIGGER_SOURCE", - "SEMAPHORE_WORKFLOW_ID", - "PULL_REQUEST_NUMBER", // pull requests from forks ONLY + 'SEMAPHORE_BRANCH_ID', + 'SEMAPHORE_BUILD_NUMBER', + 'SEMAPHORE_CURRENT_JOB', + 'SEMAPHORE_CURRENT_THREAD', + 'SEMAPHORE_EXECUTABLE_UUID', + 'SEMAPHORE_GIT_BRANCH', + 'SEMAPHORE_GIT_DIR', + 'SEMAPHORE_GIT_REF', + 'SEMAPHORE_GIT_REF_TYPE', + 'SEMAPHORE_GIT_REPO_SLUG', + 'SEMAPHORE_GIT_SHA', + 'SEMAPHORE_GIT_URL', + 'SEMAPHORE_JOB_COUNT', + 'SEMAPHORE_JOB_ID', // v2 + 'SEMAPHORE_JOB_NAME', + 'SEMAPHORE_JOB_UUID', // v1 + 'SEMAPHORE_PIPELINE_ID', + 'SEMAPHORE_PLATFORM', + 'SEMAPHORE_PROJECT_DIR', + 'SEMAPHORE_PROJECT_HASH_ID', + 'SEMAPHORE_PROJECT_ID', // v2 + 'SEMAPHORE_PROJECT_NAME', + 'SEMAPHORE_PROJECT_UUID', // v1 + 'SEMAPHORE_REPO_SLUG', + 'SEMAPHORE_TRIGGER_SOURCE', + 'SEMAPHORE_WORKFLOW_ID', + 'PULL_REQUEST_NUMBER', // pull requests from forks ONLY ]), // see http://docs.shippable.com/ci/env-vars/ shippable: extract([ // build variables - "SHIPPABLE_BUILD_ID", // "5b93354cabfabb07007f01fd" - "SHIPPABLE_BUILD_NUMBER", // "4" - "SHIPPABLE_COMMIT_RANGE", // "sha1...sha2" - "SHIPPABLE_CONTAINER_NAME", // "c.exec.cypress-example-kitchensink.4.1" - "SHIPPABLE_JOB_ID", // "1" - "SHIPPABLE_JOB_NUMBER", // "1" - "SHIPPABLE_REPO_SLUG", // "/" + 'SHIPPABLE_BUILD_ID', // "5b93354cabfabb07007f01fd" + 'SHIPPABLE_BUILD_NUMBER', // "4" + 'SHIPPABLE_COMMIT_RANGE', // "sha1...sha2" + 'SHIPPABLE_CONTAINER_NAME', // "c.exec.cypress-example-kitchensink.4.1" + 'SHIPPABLE_JOB_ID', // "1" + 'SHIPPABLE_JOB_NUMBER', // "1" + 'SHIPPABLE_REPO_SLUG', // "/" // additional information that Shippable provides - "IS_FORK", // "true" - "IS_GIT_TAG", // "false" - "IS_PRERELEASE", // "false" - "IS_RELEASE", // "false" - "REPOSITORY_URL", // "https://github.com/....git" - "REPO_FULL_NAME", // "/" - "REPO_NAME", // "cypress-example-kitchensink" - "BUILD_URL", // "https://app.shippable.com/github///runs/1" + 'IS_FORK', // "true" + 'IS_GIT_TAG', // "false" + 'IS_PRERELEASE', // "false" + 'IS_RELEASE', // "false" + 'REPOSITORY_URL', // "https://github.com/....git" + 'REPO_FULL_NAME', // "/" + 'REPO_NAME', // "cypress-example-kitchensink" + 'BUILD_URL', // "https://app.shippable.com/github///runs/1" // Pull request information - "BASE_BRANCH", // Name of the target branch into which the pull request changes will be merged. - "HEAD_BRANCH", // This is only set for pull requests and is the name of the branch the pull request was opened from. - "IS_PULL_REQUEST", // "false" or "true" - "PULL_REQUEST", // Pull request number if the job is a pull request. If not, this will be set to false. - "PULL_REQUEST_BASE_BRANCH", // Name of the branch that the pull request will be merged into. It should be the same as BASE_BRANCH. - "PULL_REQUEST_REPO_FULL_NAME", // Full name of the repository from where the pull request originated. + 'BASE_BRANCH', // Name of the target branch into which the pull request changes will be merged. + 'HEAD_BRANCH', // This is only set for pull requests and is the name of the branch the pull request was opened from. + 'IS_PULL_REQUEST', // "false" or "true" + 'PULL_REQUEST', // Pull request number if the job is a pull request. If not, this will be set to false. + 'PULL_REQUEST_BASE_BRANCH', // Name of the branch that the pull request will be merged into. It should be the same as BASE_BRANCH. + 'PULL_REQUEST_REPO_FULL_NAME', // Full name of the repository from where the pull request originated. ]), teamcity: null, teamfoundation: extract([ - "BUILD_BUILDID", - "BUILD_BUILDNUMBER", - "BUILD_CONTAINERID", + 'BUILD_BUILDID', + 'BUILD_BUILDNUMBER', + 'BUILD_CONTAINERID', ]), travis: extract([ - "TRAVIS_JOB_ID", - "TRAVIS_BUILD_ID", - "TRAVIS_BUILD_WEB_URL", - "TRAVIS_REPO_SLUG", - "TRAVIS_JOB_NUMBER", - "TRAVIS_EVENT_TYPE", - "TRAVIS_COMMIT_RANGE", - "TRAVIS_BUILD_NUMBER", - "TRAVIS_PULL_REQUEST", - "TRAVIS_PULL_REQUEST_BRANCH", - "TRAVIS_PULL_REQUEST_SHA", + 'TRAVIS_JOB_ID', + 'TRAVIS_BUILD_ID', + 'TRAVIS_BUILD_WEB_URL', + 'TRAVIS_REPO_SLUG', + 'TRAVIS_JOB_NUMBER', + 'TRAVIS_EVENT_TYPE', + 'TRAVIS_COMMIT_RANGE', + 'TRAVIS_BUILD_NUMBER', + 'TRAVIS_PULL_REQUEST', + 'TRAVIS_PULL_REQUEST_BRANCH', + 'TRAVIS_PULL_REQUEST_SHA', ]), wercker: null, // https://docs.netlify.com/configure-builds/environment-variables/#deploy-urls-and-metadata netlify: extract([ - "BUILD_ID", - "CONTEXT", - "URL", - "DEPLOY_URL", - "DEPLOY_PRIME_URL", - "DEPLOY_ID", + 'BUILD_ID', + 'CONTEXT', + 'URL', + 'DEPLOY_URL', + 'DEPLOY_PRIME_URL', + 'DEPLOY_ID', ]), // https://layerci.com/docs/layerfile-reference/build-env layerci: extract([ - "LAYERCI_JOB_ID", - "LAYERCI_RUNNER_ID", - "RETRY_INDEX", - "LAYERCI_PULL_REQUEST", - "LAYERCI_REPO_NAME", - "LAYERCI_REPO_OWNER", - "LAYERCI_BRANCH", - "GIT_TAG", // short hex for commits + 'LAYERCI_JOB_ID', + 'LAYERCI_RUNNER_ID', + 'RETRY_INDEX', + 'LAYERCI_PULL_REQUEST', + 'LAYERCI_REPO_NAME', + 'LAYERCI_REPO_OWNER', + 'LAYERCI_BRANCH', + 'GIT_TAG', // short hex for commits ]), }; }; @@ -475,7 +475,7 @@ const _providerCommitParams = (): ProviderCommitParamsRes => { branch: env.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH || env.APPVEYOR_REPO_BRANCH, message: join( - "\n", + '\n', env.APPVEYOR_REPO_COMMIT_MESSAGE, env.APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED ), @@ -687,7 +687,7 @@ export function isCiBuildIdDetectable(ciProvider: string | null) { function getCiProvider(): CiProvider { const providerName = _detectProviderName(); - debug("detected CI provider name: %s", providerName); + debug('detected CI provider name: %s', providerName); return providerName || null; } @@ -704,9 +704,9 @@ export function getCI(explicitCiBuildId?: string | undefined) { const provider = getCiProvider(); const ciBuildId = getCIBuildId(explicitCiBuildId, provider); - debug("detected CI provider: %s", provider); - debug("detected CI params: %O", params); - debug("detected CI build ID: %o", ciBuildId); + debug('detected CI provider: %s', provider); + debug('detected CI params: %O', params); + debug('detected CI build ID: %o', ciBuildId); return { params, @@ -717,15 +717,15 @@ export function getCI(explicitCiBuildId?: string | undefined) { type CIBuildIdStruct = | { - source: "user"; // provided by the user + source: 'user'; // provided by the user value: string; } | { - source: "server"; // expected to be generated by the Currents server + source: 'server'; // expected to be generated by the Currents server value: null; } | { - source: "random"; // generated by the reporter + source: 'random'; // generated by the reporter value: string; }; @@ -742,18 +742,18 @@ function getCIBuildId( ): CIBuildIdStruct { if (explicitValue) { return { - source: "user" as const, + source: 'user' as const, value: explicitValue, }; } if (!isCiBuildIdDetectable(provider)) { return { - source: "random" as const, + source: 'random' as const, value: `auto:${userFacingNanoid()}`, }; } return { - source: "server" as const, + source: 'server' as const, value: null, }; } diff --git a/packages/cmd/src/env/git-ci-provider.ts b/packages/cmd/src/env/git-ci-provider.ts index 2eb01f5..ca1ba68 100644 --- a/packages/cmd/src/env/git-ci-provider.ts +++ b/packages/cmd/src/env/git-ci-provider.ts @@ -1,16 +1,16 @@ -import { defaultTo, transform } from "lodash"; -import { debug as _debug } from "../debug"; -import { getCommitParams } from "./ciProvider"; -import { GhaEventData } from "./gitInfo"; -import { CiProvider, CiProviderData } from "./types"; +import { defaultTo, transform } from 'lodash'; +import { debug as _debug } from '../debug'; +import { getCommitParams } from './ciProvider'; +import { GhaEventData } from './gitInfo'; +import { CiProvider, CiProviderData } from './types'; -const debug = _debug.extend("ci-git"); +const debug = _debug.extend('ci-git'); export function mergeGitCommit(existingInfo: CiProviderData) { - debug("git commit existing info: %O", existingInfo); + debug('git commit existing info: %O', existingInfo); const commitParamsObj = getCommitParams(); - debug("commit info from provider environment variables: %O", commitParamsObj); + debug('commit info from provider environment variables: %O', commitParamsObj); // based on the existingInfo properties // merge in the commitParams if null or undefined @@ -30,7 +30,7 @@ export function mergeGitCommit(existingInfo: CiProviderData) { } ); - debug("combined git and environment variables from provider: %O", combined); + debug('combined git and environment variables from provider: %O', combined); return combined; } diff --git a/packages/cmd/src/env/gitInfo.ts b/packages/cmd/src/env/gitInfo.ts index a1d47fd..414101e 100644 --- a/packages/cmd/src/env/gitInfo.ts +++ b/packages/cmd/src/env/gitInfo.ts @@ -1,7 +1,7 @@ // @ts-ignore -import { commitInfo } from "@currents/commit-info"; -import { memoize } from "lodash"; -import { mergeGitCommit } from "./git-ci-provider"; +import { commitInfo } from '@currents/commit-info'; +import { memoize } from 'lodash'; +import { mergeGitCommit } from './git-ci-provider'; export type GhaEventData = { headRef: string; diff --git a/packages/cmd/src/env/platform.ts b/packages/cmd/src/env/platform.ts index 4719338..f4ba231 100644 --- a/packages/cmd/src/env/platform.ts +++ b/packages/cmd/src/env/platform.ts @@ -1,14 +1,14 @@ -import getos from "getos"; -import { memoize } from "lodash"; -import { freemem, platform, release, totalmem } from "os"; -import { promisify } from "util"; +import getos from 'getos'; +import { memoize } from 'lodash'; +import { freemem, platform, release, totalmem } from 'os'; +import { promisify } from 'util'; const getOsVersion = async () => { - if (platform() === "linux") { + if (platform() === 'linux') { try { const linuxOs = await promisify(getos)(); - if ("dist" in linuxOs && "release" in linuxOs) { - return [linuxOs.dist, linuxOs.release].join(" - "); + if ('dist' in linuxOs && 'release' in linuxOs) { + return [linuxOs.dist, linuxOs.release].join(' - '); } else { return release(); } diff --git a/packages/cmd/src/env/types.ts b/packages/cmd/src/env/types.ts index e9818f8..e70debc 100644 --- a/packages/cmd/src/env/types.ts +++ b/packages/cmd/src/env/types.ts @@ -1,4 +1,4 @@ -import { GhaEventData } from "./gitInfo"; +import { GhaEventData } from './gitInfo'; export type CiProvider = string | null; export type CiProviderData = { @@ -23,7 +23,6 @@ export type GithubActionsParams = { githubRepository: string; }; - export type GitLabParams = { gitlabCi: string; ciPipelineId: string; @@ -41,4 +40,4 @@ export type GitLabParams = { ciNodeIndex?: string; ciNodeTotal?: string; runAttempt?: string; -}; \ No newline at end of file +}; diff --git a/packages/cmd/src/env/versions.ts b/packages/cmd/src/env/versions.ts index 3a01b5b..ca03b88 100644 --- a/packages/cmd/src/env/versions.ts +++ b/packages/cmd/src/env/versions.ts @@ -1,3 +1,3 @@ -import pkg from "../../package.json"; +import pkg from '../../package.json'; export const reporterVersion = pkg.version; diff --git a/packages/cmd/src/http/axios.ts b/packages/cmd/src/http/axios.ts index 1e4ba4a..cfccbb3 100644 --- a/packages/cmd/src/http/axios.ts +++ b/packages/cmd/src/http/axios.ts @@ -1,10 +1,10 @@ -import axios, { CreateAxiosDefaults } from "axios"; -import { HttpsProxyAgent } from "https-proxy-agent"; -import proxyFromEnv from "proxy-from-env"; +import axios, { CreateAxiosDefaults } from 'axios'; +import { HttpsProxyAgent } from 'https-proxy-agent'; +import proxyFromEnv from 'proxy-from-env'; -import { debug as _debug } from "../debug"; +import { debug as _debug } from '../debug'; -const debug = _debug.extend("axios"); +const debug = _debug.extend('axios'); export function getAxios(config: CreateAxiosDefaults = {}) { const instance = axios.create(config); @@ -14,7 +14,7 @@ export function getAxios(config: CreateAxiosDefaults = {}) { const uri = instance.getUri(config); const proxyURL = proxyFromEnv.getProxyForUrl(uri); if (proxyURL) { - debug("Using HTTP proxy %s for %s ", proxyURL, uri); + debug('Using HTTP proxy %s for %s ', proxyURL, uri); _config.proxy = false; _config.httpsAgent = getHTTPSProxyAgent(proxyURL); } diff --git a/packages/cmd/src/http/client.ts b/packages/cmd/src/http/client.ts index e45be20..22640b5 100644 --- a/packages/cmd/src/http/client.ts +++ b/packages/cmd/src/http/client.ts @@ -1,21 +1,21 @@ -import axios, { AxiosInstance } from "axios"; -import axiosRetry from "axios-retry"; -import _ from "lodash"; +import axios, { AxiosInstance } from 'axios'; +import axiosRetry from 'axios-retry'; +import _ from 'lodash'; -import { debug as _debug } from "../debug"; -import { getAPIBaseUrl, getRestAPIBaseUrl, getTimeout } from "./httpConfig"; +import { debug as _debug } from '../debug'; +import { getAPIBaseUrl, getRestAPIBaseUrl, getTimeout } from './httpConfig'; import { getDelay, getMaxRetries, isRetriableError, onRetry, -} from "./httpRetry"; +} from './httpRetry'; -const debug = _debug.extend("http"); +const debug = _debug.extend('http'); export enum ClientType { - API = "api", - REST_API = "restApi", + API = 'api', + REST_API = 'restApi', } let _clients: Record = { @@ -38,7 +38,7 @@ export function createClient(type: ClientType) { client.interceptors.request.use((config) => { // @ts-ignore - const retry = config["axios-retry"]?.retryCount ?? 0; + const retry = config['axios-retry']?.retryCount ?? 0; // const currentsConfig = getCurrentsConfig(); // config.headers.set({ @@ -53,20 +53,20 @@ export function createClient(type: ClientType) { // config.headers.set("x-currents-machine-id", currentsConfig.machineId); // } - if (!config.headers.get("Content-Type")) { - config.headers.set("Content-Type", "application/json"); + if (!config.headers.get('Content-Type')) { + config.headers.set('Content-Type', 'application/json'); } const args = { - ..._.pick(config, "method", "url", "headers"), - data: Buffer.isBuffer(config.data) ? "buffer" : (config.data as unknown), + ..._.pick(config, 'method', 'url', 'headers'), + data: Buffer.isBuffer(config.data) ? 'buffer' : (config.data as unknown), }; if (!retry) { - debug("network request: %o", getNetworkRequestDebugData(args)); + debug('network request: %o', getNetworkRequestDebugData(args)); } else { debug( - "network request retry: %o", + 'network request retry: %o', getNetworkRequestDebugData({ ...args, isRetry: true, @@ -106,10 +106,10 @@ function getNetworkRequestDebugData(data: { method: data.method, baseUrl: getAPIBaseUrl(), url: data.url, - data: data.isRetry ? "" : getPayloadDebugData(data.data), + data: data.isRetry ? '' : getPayloadDebugData(data.data), headers: { ...data.headers, - ["x-currents-key"]: "***", + ['x-currents-key']: '***', }, }; } @@ -120,7 +120,7 @@ function getPayloadDebugData(data: any) { ...data, results: { ...data.results, - raw: "***", + raw: '***', }, }; } diff --git a/packages/cmd/src/http/http.ts b/packages/cmd/src/http/http.ts index 261dfa6..7f4323c 100644 --- a/packages/cmd/src/http/http.ts +++ b/packages/cmd/src/http/http.ts @@ -1,11 +1,11 @@ -import { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios"; -import _ from "lodash"; +import { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'; +import _ from 'lodash'; -import { debug as _debug } from "../debug"; -import { ClientType, getClient } from "./client"; -import { handleHTTPError } from "./httpErrors"; +import { debug as _debug } from '../debug'; +import { ClientType, getClient } from './client'; +import { handleHTTPError } from './httpErrors'; -const debug = _debug.extend("http"); +const debug = _debug.extend('http'); export async function makeRequest( clientType: ClientType, @@ -16,15 +16,15 @@ export async function makeRequest( const res = await _getClient(clientType).request>( config ); - debug("network response: %o", { - ..._.omit(res, "request", "config"), + debug('network response: %o', { + ..._.omit(res, 'request', 'config'), url: res.config.url, method: res.config.method, }); return res; } catch (_error) { const error = _error as AxiosError; - debug("network error: %o", { + debug('network error: %o', { code: error.code, message: error.message, url: error.config?.url, diff --git a/packages/cmd/src/http/httpConfig.ts b/packages/cmd/src/http/httpConfig.ts index 8891323..5e442e3 100644 --- a/packages/cmd/src/http/httpConfig.ts +++ b/packages/cmd/src/http/httpConfig.ts @@ -1,7 +1,7 @@ export const getAPIBaseUrl = () => - process.env.CURRENTS_API_URL ?? "https://cy.currents.dev"; + process.env.CURRENTS_API_URL ?? 'https://cy.currents.dev'; export const getRestAPIBaseUrl = () => - process.env.CURRENTS_REST_API_URL ?? "https://api.currents.dev"; + process.env.CURRENTS_REST_API_URL ?? 'https://api.currents.dev'; export const getTimeout = () => 30000; diff --git a/packages/cmd/src/http/httpErrors.ts b/packages/cmd/src/http/httpErrors.ts index 19a42b3..9f1d76e 100644 --- a/packages/cmd/src/http/httpErrors.ts +++ b/packages/cmd/src/http/httpErrors.ts @@ -1,7 +1,7 @@ -import * as log from "@logger"; -import { AxiosError, isAxiosError } from "axios"; -import _ from "lodash"; -import { P, match } from "ts-pattern"; +import * as log from '@logger'; +import { AxiosError, isAxiosError } from 'axios'; +import _ from 'lodash'; +import { P, match } from 'ts-pattern'; export function handleHTTPError(error: unknown) { match(error) @@ -15,16 +15,16 @@ function handleAxiosError(error: AxiosError) { return ( match(error) // Generic network errors - .with({ code: "ECONNABORTED" }, () => { + .with({ code: 'ECONNABORTED' }, () => { log.warn(`Network connection aborted`); }) - .with({ code: "ECONNREFUSED" }, () => { + .with({ code: 'ECONNREFUSED' }, () => { log.warn(`Network connection aborted`); }) - .with({ code: "ECONNRESET" }, () => { + .with({ code: 'ECONNRESET' }, () => { log.warn(`Network connection reset`); }) - .with({ code: "ETIMEDOUT" }, () => { + .with({ code: 'ETIMEDOUT' }, () => { log.warn(`Network connection timeout`); }) .with({ response: P.not(P.nullish) }, (i) => { @@ -34,7 +34,7 @@ function handleAxiosError(error: AxiosError) { }); }) .otherwise((i) => { - log.warn("[currents] Unexpected network error: %s\n%O", error.message, { + log.warn('[currents] Unexpected network error: %s\n%O', error.message, { method: error.response?.config.method, url: error.response?.config.url, status: error.response?.status, @@ -76,7 +76,7 @@ function handle4xx( }) .otherwise(() => { log.warn( - "[currents] Unexpected network response: %s\n%O", + '[currents] Unexpected network response: %s\n%O', error.message, { method: error.response?.config.method, @@ -113,7 +113,7 @@ function handle422Error(error: AxiosError, data: unknown) { }) .otherwise(() => { log.warn( - "[currents] Unexpected network response: %s\n%O", + '[currents] Unexpected network response: %s\n%O', error.message, { method: error.response?.config.method, @@ -124,9 +124,9 @@ function handle422Error(error: AxiosError, data: unknown) { }); } const ErrorCodes = { - RUN_CANCELLED: "RUN_CANCELLED", - RUN_EXPIRED: "RUN_EXPIRED", - MISSING_SUITE: "MISSING_SUITE", + RUN_CANCELLED: 'RUN_CANCELLED', + RUN_EXPIRED: 'RUN_EXPIRED', + MISSING_SUITE: 'MISSING_SUITE', } as const; export function formatGenericCloudError( @@ -134,7 +134,7 @@ export function formatGenericCloudError( errors?: string[] ): string[] { if (!_.isString(message)) { - return ["Unexpected network error"]; + return ['Unexpected network error']; } if (errors?.length === 0) { @@ -143,7 +143,7 @@ export function formatGenericCloudError( return [ message as string, ` -${(errors ?? []).map((e) => ` - ${e}`).join("\n")} +${(errors ?? []).map((e) => ` - ${e}`).join('\n')} `, ]; } diff --git a/packages/cmd/src/http/httpRetry.ts b/packages/cmd/src/http/httpRetry.ts index be36cb2..4ab935a 100644 --- a/packages/cmd/src/http/httpRetry.ts +++ b/packages/cmd/src/http/httpRetry.ts @@ -1,33 +1,33 @@ -import { AxiosError, AxiosRequestConfig, isAxiosError } from "axios"; -import prettyMilliseconds from "pretty-ms"; +import { AxiosError, AxiosRequestConfig, isAxiosError } from 'axios'; +import prettyMilliseconds from 'pretty-ms'; -import { warn } from "@logger"; -import { debug as _debug } from "../debug"; +import { warn } from '@logger'; +import { debug as _debug } from '../debug'; -const debug = _debug.extend("http"); +const debug = _debug.extend('http'); export const getDelay = (i: number) => [3 * 1000, 15 * 1000, 30 * 1000][i - 1]; export const isRetriableError = (err: AxiosError | Error): boolean => { - debug("isRetriableError: %o", { + debug('isRetriableError: %o', { message: err.message, - code: "code" in err ? err.code : undefined, - status: "response" in err ? err.response?.status : undefined, - headers: "response" in err ? err.response?.headers : undefined, - data: "response" in err ? err.response?.data : undefined, + code: 'code' in err ? err.code : undefined, + status: 'response' in err ? err.response?.status : undefined, + headers: 'response' in err ? err.response?.headers : undefined, + data: 'response' in err ? err.response?.data : undefined, isAxiosError: isAxiosError(err), }); if ( - "code" in err && + 'code' in err && err.code && // https://man7.org/linux/man-pages/man3/errno.3.html [ - "ECONNABORTED", - "ECONNREFUSED", - "ECONNRESET", - "ETIMEDOUT", - "ENETRESET", + 'ECONNABORTED', + 'ECONNREFUSED', + 'ECONNRESET', + 'ETIMEDOUT', + 'ENETRESET', ].includes(err.code) ) { return true; diff --git a/packages/cmd/src/http/index.ts b/packages/cmd/src/http/index.ts index b4f0c19..c202386 100644 --- a/packages/cmd/src/http/index.ts +++ b/packages/cmd/src/http/index.ts @@ -1 +1 @@ -export * from "./http"; +export * from './http'; diff --git a/packages/cmd/src/index.ts b/packages/cmd/src/index.ts index add7769..6343d1d 100644 --- a/packages/cmd/src/index.ts +++ b/packages/cmd/src/index.ts @@ -1,2 +1,2 @@ -export { handleCurrentsReport } from "./services/upload"; -export type * from "./services/upload/types"; +export { handleCurrentsReport } from './services/upload'; +export type * from './services/upload/types'; diff --git a/packages/cmd/src/lib/execa.ts b/packages/cmd/src/lib/execa.ts index 78170f8..8fc22f2 100644 --- a/packages/cmd/src/lib/execa.ts +++ b/packages/cmd/src/lib/execa.ts @@ -1,10 +1,10 @@ -let _execa: null | (typeof import("execa"))["execa"]; +let _execa: null | (typeof import('execa'))['execa']; export async function getExeca() { if (_execa) { return _execa; } - const { execa } = await import("execa"); + const { execa } = await import('execa'); _execa = execa; return execa; } diff --git a/packages/cmd/src/lib/fs.ts b/packages/cmd/src/lib/fs.ts index f8678ee..e119f22 100644 --- a/packages/cmd/src/lib/fs.ts +++ b/packages/cmd/src/lib/fs.ts @@ -1,20 +1,20 @@ -import { error } from "@logger"; -import fs from "fs-extra"; -import { dirname } from "path"; +import { error } from '@logger'; +import fs from 'fs-extra'; +import { dirname } from 'path'; export async function readJsonFile(filePath: string): Promise { try { const data = await fs.readJson(filePath); return data as T; } catch (err) { - error("Error while reading JSON file: %s", filePath, err); + error('Error while reading JSON file: %s', filePath, err); throw error; } } export async function writeFileAsync(filePath: string, content: string) { try { - await fs.writeFile(filePath, content, "utf8"); + await fs.writeFile(filePath, content, 'utf8'); return filePath; } catch (err) { error(`Error writing file at ${filePath}:`, err); diff --git a/packages/cmd/src/lib/index.ts b/packages/cmd/src/lib/index.ts index 5d56350..8aac5f7 100644 --- a/packages/cmd/src/lib/index.ts +++ b/packages/cmd/src/lib/index.ts @@ -1,4 +1,4 @@ -export * from "./error"; -export * from "./execa"; -export * from "./fs"; -export * as nanoid from "./nano"; +export * from './error'; +export * from './execa'; +export * from './fs'; +export * as nanoid from './nano'; diff --git a/packages/cmd/src/lib/nano.ts b/packages/cmd/src/lib/nano.ts index d4bbfaf..42dd80d 100644 --- a/packages/cmd/src/lib/nano.ts +++ b/packages/cmd/src/lib/nano.ts @@ -1,6 +1,6 @@ -import { customAlphabet } from "nanoid"; +import { customAlphabet } from 'nanoid'; const alphabet = - "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; export const getNanoid = (length = 16) => customAlphabet(alphabet, length)(); export const userFacingNanoid = customAlphabet(alphabet, 12); diff --git a/packages/cmd/src/logger/index.ts b/packages/cmd/src/logger/index.ts index 57d79f6..cf3fa78 100644 --- a/packages/cmd/src/logger/index.ts +++ b/packages/cmd/src/logger/index.ts @@ -1,2 +1,2 @@ -export * from "./logDrain"; -export * from "./logger"; +export * from './logDrain'; +export * from './logger'; diff --git a/packages/cmd/src/logger/logger.ts b/packages/cmd/src/logger/logger.ts index e624544..6ba1570 100644 --- a/packages/cmd/src/logger/logger.ts +++ b/packages/cmd/src/logger/logger.ts @@ -1,9 +1,9 @@ -import chalk from "chalk"; -import util from "util"; +import chalk from 'chalk'; +import util from 'util'; -import { debug } from "../debug"; -import { addToLogDrain } from "./logDrain"; -import { errors, warnings } from "./notices"; +import { debug } from '../debug'; +import { addToLogDrain } from './logDrain'; +import { errors, warnings } from './notices'; const log = (...args: unknown[]) => { const stringToRender = util.format(...args); @@ -22,19 +22,19 @@ export const info = log; export const warn = (...args: unknown[]) => { const msg = util.format(...args); warnings.push(msg); - debug("WARNING: ", msg); - return log(chalk.bgYellow.black(" WARNING "), msg); + debug('WARNING: ', msg); + return log(chalk.bgYellow.black(' WARNING '), msg); }; export const warnWithNoTrace = (...args: unknown[]) => { const msg = util.format(...args); - debug("WARNING: ", msg); - return log(chalk.bgYellow.black(" WARNING "), msg); + debug('WARNING: ', msg); + return log(chalk.bgYellow.black(' WARNING '), msg); }; export const errorWithNoTrace = (...args: unknown[]) => { const msg = util.format(...args); - debug("ERRRO: ", msg); - return log(chalk.bgRed.white(" ERROR "), msg); + debug('ERRRO: ', msg); + return log(chalk.bgRed.white(' ERROR '), msg); }; export const success = (...args: unknown[]) => @@ -43,8 +43,8 @@ export const success = (...args: unknown[]) => export const error = (...args: unknown[]) => { const msg = util.format(...args); errors.push(msg); - debug("ERROR: ", msg); - return _error(chalk.bgRed.white(" ERROR "), msg); + debug('ERROR: ', msg); + return _error(chalk.bgRed.white(' ERROR '), msg); }; export const title = (...args: unknown[]) => @@ -53,38 +53,38 @@ export const title = (...args: unknown[]) => export const titleContent = (...args: unknown[]) => chalk.blue.bold(util.format(...args)); -export const divider = () => console.log("\n" + dividerContent() + "\n"); +export const divider = () => console.log('\n' + dividerContent() + '\n'); -export const dividerContent = () => chalk.dim(Array(64).fill("=").join("")); +export const dividerContent = () => chalk.dim(Array(64).fill('=').join('')); -export const blockStart = (label = "", lineLength = 64) => { - const _label = ` start of ${label ?? "block"} `; +export const blockStart = (label = '', lineLength = 64) => { + const _label = ` start of ${label ?? 'block'} `; const padding = Math.max(lineLength - _label.length, 0) / 2; const padStart = Math.floor(padding); const padEnd = Math.ceil(padding); return chalk.dim( - `${Array(padStart).fill("-").join("")}${_label}${Array(padEnd) - .fill("-") - .join("")}` + `${Array(padStart).fill('-').join('')}${_label}${Array(padEnd) + .fill('-') + .join('')}` ); }; -export const blockEnd = (label = "", lineLength = 64) => { - const _label = ` end of ${label ?? "block"} `; +export const blockEnd = (label = '', lineLength = 64) => { + const _label = ` end of ${label ?? 'block'} `; const padding = Math.max(lineLength - _label.length, 0) / 2; const padStart = Math.floor(padding); const padEnd = Math.ceil(padding); return chalk.dim( - `${Array(padStart).fill("-").join("")}${_label}${Array(padEnd) - .fill("-") - .join("")}` + `${Array(padStart).fill('-').join('')}${_label}${Array(padEnd) + .fill('-') + .join('')}` ); }; export const spacer = (n: number = 2) => - console.log(Array(n).fill("").join("\n")); + console.log(Array(n).fill('').join('\n')); export const cyan = chalk.cyan; export const blue = chalk.blueBright; diff --git a/packages/cmd/src/services/api/index.ts b/packages/cmd/src/services/api/index.ts index 99ec8df..cb1f0c8 100644 --- a/packages/cmd/src/services/api/index.ts +++ b/packages/cmd/src/services/api/index.ts @@ -1,19 +1,19 @@ -import { debug } from "@debug"; -import { ensurePathExists } from "@lib"; -import { writeFile } from "fs/promises"; -import { getRun } from "../../api"; +import { debug } from '@debug'; +import { ensurePathExists } from '@lib'; +import { writeFile } from 'fs/promises'; +import { getRun } from '../../api'; import { APICommandConfig, APIGetRunCommandConfig, getAPIGetRunCommandConfig, -} from "../../config/api"; -import { info } from "../../logger"; +} from '../../config/api'; +import { info } from '../../logger'; export async function handleGetRun() { try { const config = getAPIGetRunCommandConfig(); if (!config) { - throw new Error("Config is missing!"); + throw new Error('Config is missing!'); } const params = config.ciBuildId @@ -37,7 +37,7 @@ export async function handleGetRun() { config ); } catch (e) { - debug("Failed to get run data"); + debug('Failed to get run data'); throw e; } } @@ -50,7 +50,7 @@ async function handleOutput( if (config.output) { await ensurePathExists(config.output); - await writeFile(config.output, data, "utf-8"); + await writeFile(config.output, data, 'utf-8'); } else { info(data); } diff --git a/packages/cmd/src/services/cache/__tests__/fs.spec.ts b/packages/cmd/src/services/cache/__tests__/fs.spec.ts index fdaa63c..a38b0db 100644 --- a/packages/cmd/src/services/cache/__tests__/fs.spec.ts +++ b/packages/cmd/src/services/cache/__tests__/fs.spec.ts @@ -1,43 +1,43 @@ -import fs from "fs-extra"; -import path from "path"; -import { Readable } from "stream"; -import unzipper from "unzipper"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { zipFilesToBuffer } from "../fs"; +import fs from 'fs-extra'; +import path from 'path'; +import { Readable } from 'stream'; +import unzipper from 'unzipper'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { zipFilesToBuffer } from '../fs'; -describe("zipFilesToBuffer", () => { - const testDir = path.join(__dirname, "test-files"); +describe('zipFilesToBuffer', () => { + const testDir = path.join(__dirname, 'test-files'); - const file1Path = path.join(testDir, "file1.txt"); - const file2Path = path.join(testDir, "file2.txt"); - const subdirPath = path.join(testDir, "subdir"); - const file3Path = path.join(subdirPath, "file3.txt"); + const file1Path = path.join(testDir, 'file1.txt'); + const file2Path = path.join(testDir, 'file2.txt'); + const subdirPath = path.join(testDir, 'subdir'); + const file3Path = path.join(subdirPath, 'file3.txt'); beforeAll(async () => { await fs.ensureDir(testDir); - await fs.writeFile(file1Path, ""); - await fs.writeFile(file2Path, ""); + await fs.writeFile(file1Path, ''); + await fs.writeFile(file2Path, ''); await fs.ensureDir(subdirPath); - await fs.writeFile(file3Path, ""); + await fs.writeFile(file3Path, ''); }); afterAll(async () => { await fs.remove(testDir); }); - it("should zip a single file", async () => { + it('should zip a single file', async () => { const buffer = await zipFilesToBuffer([file1Path]); const entries = await unzipBuffer(buffer); expect(entries.length).toBe(1); }); - it("should zip multiple files", async () => { + it('should zip multiple files', async () => { const buffer = await zipFilesToBuffer([file1Path, file2Path]); const entries = await unzipBuffer(buffer); expect(entries.length).toBe(2); }); - it("should zip a directory", async () => { + it('should zip a directory', async () => { const buffer = await zipFilesToBuffer([testDir]); const entries = await unzipBuffer(buffer); const entryNames = entries.map((entry) => entry.path); @@ -46,11 +46,11 @@ describe("zipFilesToBuffer", () => { expect(entryNames).toContain(path.relative(process.cwd(), file2Path)); expect(entryNames).toContain(path.relative(process.cwd(), file3Path)); expect(entryNames).toContain( - path.relative(process.cwd(), subdirPath) + "/" + path.relative(process.cwd(), subdirPath) + '/' ); // "/" is added by archiver for directories }); - it("should zip mixed files and directories", async () => { + it('should zip mixed files and directories', async () => { const buffer = await zipFilesToBuffer([file1Path, subdirPath]); const entries = await unzipBuffer(buffer); const entryNames = entries.map((entry) => entry.path); @@ -59,27 +59,27 @@ describe("zipFilesToBuffer", () => { expect(entryNames).toContain(path.relative(process.cwd(), file3Path)); // inside subdir }); - it("should handle empty input", async () => { + it('should handle empty input', async () => { const buffer = await zipFilesToBuffer([]); expect(buffer).toBeDefined(); const zip = Readable.from(buffer).pipe(unzipper.Parse()); const entries = []; await new Promise((resolve) => { - zip.on("entry", (entry) => entries.push(entry)); - zip.on("close", resolve); + zip.on('entry', (entry) => entries.push(entry)); + zip.on('close', resolve); }); expect(entries.length).toBe(0); }); - it("should throw an error for non-existing paths", async () => { - await expect(zipFilesToBuffer(["non-existing-file.txt"])).rejects.toThrow(); + it('should throw an error for non-existing paths', async () => { + await expect(zipFilesToBuffer(['non-existing-file.txt'])).rejects.toThrow(); }); - it("should throw an error if zip size exceeds limit", async () => { - const largeFilePath = path.join(testDir, "largeFile.txt"); - await fs.writeFile(largeFilePath, "A".repeat(1_000_000)); // on "data" event is fired after + it('should throw an error if zip size exceeds limit', async () => { + const largeFilePath = path.join(testDir, 'largeFile.txt'); + await fs.writeFile(largeFilePath, 'A'.repeat(1_000_000)); // on "data" event is fired after await expect(zipFilesToBuffer([largeFilePath], 500)).rejects.toThrow( - "Zip size exceeded the limit" + 'Zip size exceeded the limit' ); }); }); @@ -88,12 +88,12 @@ const unzipBuffer = async (buffer: Buffer) => { const entries: any[] = []; const zip = Readable.from(buffer).pipe(unzipper.Parse()); - zip.on("entry", (entry) => { + zip.on('entry', (entry) => { entries.push(entry); }); await new Promise((resolve) => { - zip.on("close", resolve); + zip.on('close', resolve); }); return entries; diff --git a/packages/cmd/src/services/cache/fs.ts b/packages/cmd/src/services/cache/fs.ts index 897914b..c0548d6 100644 --- a/packages/cmd/src/services/cache/fs.ts +++ b/packages/cmd/src/services/cache/fs.ts @@ -1,19 +1,19 @@ -import Archiver from "archiver"; -import fs from "fs-extra"; -import path from "path"; -import unzipper from "unzipper"; -import { warn } from "../../logger"; +import Archiver from 'archiver'; +import fs from 'fs-extra'; +import path from 'path'; +import unzipper from 'unzipper'; +import { warn } from '../../logger'; const MAX_ZIP_SIZE = 50 * 1024 * 1024; // 50MB /** * Adds files and directories to an archive while preserving their original folder structure. * - * This function supports various types of paths, including individual files, entire directories, - * and files located within subdirectories. When the archive is extracted, the original organization + * This function supports various types of paths, including individual files, entire directories, + * and files located within subdirectories. When the archive is extracted, the original organization * will be restored, making navigation straightforward. * - * Paths based on a specific starting point will be stored relative to that point, helping to avoid + * Paths based on a specific starting point will be stored relative to that point, helping to avoid * naming conflicts and maintaining the logical arrangement of files and directories. */ export async function zipFilesToBuffer( @@ -21,11 +21,11 @@ export async function zipFilesToBuffer( maxSize: number = MAX_ZIP_SIZE ): Promise { return new Promise((resolve, reject) => { - const archive = Archiver("zip", { zlib: { level: 9 } }); + const archive = Archiver('zip', { zlib: { level: 9 } }); const chunks: Buffer[] = []; let totalSize = 0; - archive.on("data", (chunk) => { + archive.on('data', (chunk) => { chunks.push(chunk); totalSize += chunk.length; if (totalSize > maxSize) { @@ -33,17 +33,17 @@ export async function zipFilesToBuffer( } }); - archive.on("warning", (err) => { - if (err.code === "ENOENT") { + archive.on('warning', (err) => { + if (err.code === 'ENOENT') { warn(err); } else { reject(err); } }); - archive.on("error", (err) => reject(err)); + archive.on('error', (err) => reject(err)); - archive.on("end", () => { + archive.on('end', () => { const buffer = Buffer.concat(chunks); resolve(buffer); }); @@ -90,7 +90,7 @@ export function filterPaths(filePaths: string[]) { const absolutePath = path.resolve(filePath); const relativePath = path.relative(baseDir, absolutePath); - if (filePath.startsWith("..") || path.isAbsolute(relativePath)) { + if (filePath.startsWith('..') || path.isAbsolute(relativePath)) { warn( `Invalid path: "${filePath}". Path traversal detected. The path was skipped.` ); diff --git a/packages/cmd/src/services/cache/get.ts b/packages/cmd/src/services/cache/get.ts index 2466648..1990e15 100644 --- a/packages/cmd/src/services/cache/get.ts +++ b/packages/cmd/src/services/cache/get.ts @@ -1,20 +1,20 @@ -import { debug } from "@debug"; -import { isAxiosError } from "axios"; -import { retrieveCache } from "../../api"; -import { PRESETS } from "../../commands/cache/options"; -import { getCacheCommandConfig } from "../../config/cache"; -import { getCI } from "../../env/ciProvider"; -import { warnWithNoTrace } from "../../logger"; -import { unzipBuffer } from "./fs"; -import { MetaFile, warn } from "./lib"; -import { download } from "./network"; -import { handlePostLastRunPreset, handlePreLastRunPreset } from "./presets"; +import { debug } from '@debug'; +import { isAxiosError } from 'axios'; +import { retrieveCache } from '../../api'; +import { PRESETS } from '../../commands/cache/options'; +import { getCacheCommandConfig } from '../../config/cache'; +import { getCI } from '../../env/ciProvider'; +import { warnWithNoTrace } from '../../logger'; +import { unzipBuffer } from './fs'; +import { MetaFile, warn } from './lib'; +import { download } from './network'; +import { handlePostLastRunPreset, handlePreLastRunPreset } from './presets'; export async function handleGetCache() { try { const config = getCacheCommandConfig(); - if (config.type !== "GET_COMMAND_CONFIG" || !config.values) { - throw new Error("Config is missing!"); + if (config.type !== 'GET_COMMAND_CONFIG' || !config.values) { + throw new Error('Config is missing!'); } const { recordKey, id, preset, matrixIndex, matrixTotal } = config.values; @@ -58,7 +58,7 @@ export async function handleGetCache() { throw e; } } catch (e) { - warn(e, "Failed to obtain cache"); + warn(e, 'Failed to obtain cache'); } } @@ -70,13 +70,13 @@ async function handleArchiveDownload({ outputDir?: string; }) { const buffer = await download(readUrl); - await unzipBuffer(buffer, outputDir || "."); - debug("Cache downloaded"); + await unzipBuffer(buffer, outputDir || '.'); + debug('Cache downloaded'); } async function handleMetaDownload(readUrl: string) { const buffer = await download(readUrl); - const meta = JSON.parse(buffer.toString("utf-8")) as MetaFile; - debug("Meta file: %O", meta); + const meta = JSON.parse(buffer.toString('utf-8')) as MetaFile; + debug('Meta file: %O', meta); return meta; } diff --git a/packages/cmd/src/services/cache/index.ts b/packages/cmd/src/services/cache/index.ts index c0718e0..b990690 100644 --- a/packages/cmd/src/services/cache/index.ts +++ b/packages/cmd/src/services/cache/index.ts @@ -1,2 +1,2 @@ -export * from "./get"; -export * from "./set"; +export * from './get'; +export * from './set'; diff --git a/packages/cmd/src/services/cache/lib.ts b/packages/cmd/src/services/cache/lib.ts index fd81792..5ede6c9 100644 --- a/packages/cmd/src/services/cache/lib.ts +++ b/packages/cmd/src/services/cache/lib.ts @@ -1,7 +1,7 @@ -import path from "path"; -import { CacheSetCommandConfig } from "../../config/cache"; -import { warnWithNoTrace } from "../../logger"; -import { omit } from "lodash"; +import path from 'path'; +import { CacheSetCommandConfig } from '../../config/cache'; +import { warnWithNoTrace } from '../../logger'; +import { omit } from 'lodash'; export type MetaFile = { id: string; @@ -28,7 +28,7 @@ export function createMeta({ const meta = { id: cacheId, orgId, - config: omit(config, "recordKey"), + config: omit(config, 'recordKey'), paths, ci, createdAt: new Date().toISOString(), @@ -38,12 +38,12 @@ export function createMeta({ } export const getLastRunFilePath = (output?: string) => - path.resolve(output ?? "test-results", ".last-run.json"); + path.resolve(output ?? 'test-results', '.last-run.json'); export function warn(error: unknown, msg: string) { if (error instanceof Error) { - warnWithNoTrace("%s. %s.", msg, error.message); + warnWithNoTrace('%s. %s.', msg, error.message); } else { - warnWithNoTrace("%s. %s.", msg, "Unknown error"); + warnWithNoTrace('%s. %s.', msg, 'Unknown error'); } } diff --git a/packages/cmd/src/services/cache/network.ts b/packages/cmd/src/services/cache/network.ts index c91dd30..96628b8 100644 --- a/packages/cmd/src/services/cache/network.ts +++ b/packages/cmd/src/services/cache/network.ts @@ -1,16 +1,16 @@ -import retry from "async-retry"; -import { AxiosProgressEvent, isAxiosError, RawAxiosRequestConfig } from "axios"; -import { debug as _debug } from "../../debug"; -import { getAxios } from "../../http/axios"; -import { error, warn } from "../../logger"; +import retry from 'async-retry'; +import { AxiosProgressEvent, isAxiosError, RawAxiosRequestConfig } from 'axios'; +import { debug as _debug } from '../../debug'; +import { getAxios } from '../../http/axios'; +import { error, warn } from '../../logger'; -const debug = _debug.extend("upload"); +const debug = _debug.extend('upload'); const UPLOAD_RETRY_COUNT = 5; export enum ContentType { - JSON = "application/json", - ZIP = "application/zip", + JSON = 'application/json', + ZIP = 'application/zip', } export type BufferUpload = { @@ -23,9 +23,9 @@ export type BufferUpload = { export async function sendBuffer( upload: BufferUpload, contentType: string, - onUploadProgress: RawAxiosRequestConfig["onUploadProgress"] + onUploadProgress: RawAxiosRequestConfig['onUploadProgress'] ) { - debug("Uploading buffer %s", upload.name, { + debug('Uploading buffer %s', upload.name, { buffer: Buffer.byteLength(upload.buffer), }); return send(upload.buffer, upload.uploadUrl, contentType, onUploadProgress); @@ -35,34 +35,34 @@ async function _send( buffer: Buffer, url: string, contentType: string, - onUploadProgress: RawAxiosRequestConfig["onUploadProgress"] + onUploadProgress: RawAxiosRequestConfig['onUploadProgress'] ) { return getAxios().request({ - method: "put", + method: 'put', url, data: buffer, onUploadProgress, headers: { - "Content-Disposition": `inline`, - "Content-Type": contentType, + 'Content-Disposition': `inline`, + 'Content-Type': contentType, }, }); } export async function download( url: string, - onDownloadProgress?: RawAxiosRequestConfig["onDownloadProgress"] + onDownloadProgress?: RawAxiosRequestConfig['onDownloadProgress'] ): Promise { try { const response = await getAxios().get(url, { - responseType: "arraybuffer", + responseType: 'arraybuffer', onDownloadProgress, }); return Buffer.from(response.data); } catch (error) { if (isAxiosError(error)) { - debug("Failed to download %s: %s", url, error.message); + debug('Failed to download %s: %s', url, error.message); } throw error; } @@ -77,7 +77,7 @@ async function send(...args: Parameters) { retries: UPLOAD_RETRY_COUNT, onRetry: (e: Error, retryCount: number) => { debug( - "Upload failed %d out of %d attempts: %s", + 'Upload failed %d out of %d attempts: %s', retryCount, UPLOAD_RETRY_COUNT, e.message @@ -99,7 +99,7 @@ export const getDefautUploadProgressHandler = ({ total, loaded }: AxiosProgressEvent) => { () => { debug( - "Uploading %s: %d / %d", + 'Uploading %s: %d / %d', label, bytesToMb(loaded), bytesToMb(total ?? 0) @@ -113,7 +113,7 @@ export const getDefaultDownloadProgressHandler = () => { const percentCompleted = total ? Math.round((loaded * 100) / total) : 0; debug( - "Downloaded %s: %d / %d (%d%)", + 'Downloaded %s: %d / %d (%d%)', label, bytesToMb(loaded), bytesToMb(total ?? 0), diff --git a/packages/cmd/src/services/cache/presets.ts b/packages/cmd/src/services/cache/presets.ts index 3ec9381..c3d3148 100644 --- a/packages/cmd/src/services/cache/presets.ts +++ b/packages/cmd/src/services/cache/presets.ts @@ -1,22 +1,22 @@ -import { debug } from "@debug"; -import _ from "lodash"; -import { PRESET_OUTPUT_PATH } from "../../commands/cache/options"; +import { debug } from '@debug'; +import _ from 'lodash'; +import { PRESET_OUTPUT_PATH } from '../../commands/cache/options'; -import { CacheGetCommandConfig } from "../../config/cache"; -import { getCI } from "../../env/ciProvider"; -import { GithubActionsParams, GitLabParams } from "../../env/types"; -import { writeFileAsync } from "../../lib"; -import { MetaFile } from "./lib"; +import { CacheGetCommandConfig } from '../../config/cache'; +import { getCI } from '../../env/ciProvider'; +import { GithubActionsParams, GitLabParams } from '../../env/types'; +import { writeFileAsync } from '../../lib'; +import { MetaFile } from './lib'; export async function handlePreLastRunPreset( config: CacheGetCommandConfig, - ci: ReturnType, + ci: ReturnType ) { switch (ci.provider) { - case "githubActions": + case 'githubActions': await dumpPWConfigForGHA(config, ci); break; - case "gitlab": + case 'gitlab': await dumpPwConfigForGitlab(config, ci); break; default: @@ -27,10 +27,10 @@ export async function handlePreLastRunPreset( export async function handlePostLastRunPreset( config: CacheGetCommandConfig, ci: ReturnType, - meta: MetaFile, + meta: MetaFile ) { switch (ci.provider) { - case "gitlab": + case 'gitlab': await dumpPwConfigForGitlab(config, ci, meta); break; default: @@ -41,7 +41,7 @@ export async function handlePostLastRunPreset( async function dumpPwConfigForGitlab( config: CacheGetCommandConfig, ci: ReturnType, - meta: MetaFile | null = null, + meta: MetaFile | null = null ) { const ciParams = ci.params as GitLabParams; const prevCiParams = meta?.ci.params as null | GitLabParams; @@ -52,46 +52,46 @@ async function dumpPwConfigForGitlab( const nodeIndex = parseIntSafe(ciParams.ciNodeIndex, 1); const jobTotal = parseIntSafe(ciParams.ciNodeTotal, 1); - const lastFailedOption = runAttempt > 1 ? "--last-failed" : ""; + const lastFailedOption = runAttempt > 1 ? '--last-failed' : ''; - let shardOption = ""; + let shardOption = ''; if (jobTotal > 1) { shardOption = - runAttempt > 1 ? "--shard=1/1" : `--shard=${nodeIndex}/${jobTotal}`; + runAttempt > 1 ? '--shard=1/1' : `--shard=${nodeIndex}/${jobTotal}`; } const pwCliOptions = [lastFailedOption, shardOption] .filter(Boolean) - .join(" "); + .join(' '); await writeFileAsync( config.presetOutput ?? PRESET_OUTPUT_PATH, `EXTRA_PW_FLAGS="${pwCliOptions}" EXTRA_PWCP_FLAGS="${lastFailedOption}" RUN_ATTEMPT="${runAttempt}" -`, +` ); } async function dumpPWConfigForGHA( config: CacheGetCommandConfig, - ci: ReturnType, + ci: ReturnType ) { const { matrixIndex, matrixTotal } = config; const ciParams = ci.params as GithubActionsParams; const runAttempt = parseIntSafe(ciParams.githubRunAttempt, 1); - const lastFailedOption = runAttempt > 1 ? "--last-failed" : ""; + const lastFailedOption = runAttempt > 1 ? '--last-failed' : ''; - let shardOption = ""; + let shardOption = ''; if (matrixTotal > 1) { shardOption = - runAttempt > 1 ? "--shard=1/1" : `--shard=${matrixIndex}/${matrixTotal}`; + runAttempt > 1 ? '--shard=1/1' : `--shard=${matrixIndex}/${matrixTotal}`; } const pwCliOptions = [lastFailedOption, shardOption] .filter(Boolean) - .join(" "); + .join(' '); const dumpPath = config.presetOutput ?? PRESET_OUTPUT_PATH; await writeFileAsync(dumpPath, pwCliOptions); debug('Dumped PW config: "%s" for GHA to %s', pwCliOptions, dumpPath); @@ -99,7 +99,7 @@ async function dumpPWConfigForGHA( const parseIntSafe = ( value: string | undefined, - defaultValue: number, + defaultValue: number ): number => { const parsed = _.toNumber(value); return _.isNaN(parsed) ? defaultValue : parsed; diff --git a/packages/cmd/src/services/cache/set.ts b/packages/cmd/src/services/cache/set.ts index 0b80b74..7fa3ee1 100644 --- a/packages/cmd/src/services/cache/set.ts +++ b/packages/cmd/src/services/cache/set.ts @@ -1,21 +1,21 @@ -import { debug } from "@debug"; -import { createCache } from "../../api"; -import { PRESETS } from "../../commands/cache/options"; -import { getCacheCommandConfig } from "../../config/cache"; -import { getCI } from "../../env/ciProvider"; -import { filterPaths, zipFilesToBuffer } from "./fs"; -import { createMeta, getLastRunFilePath, warn } from "./lib"; +import { debug } from '@debug'; +import { createCache } from '../../api'; +import { PRESETS } from '../../commands/cache/options'; +import { getCacheCommandConfig } from '../../config/cache'; +import { getCI } from '../../env/ciProvider'; +import { filterPaths, zipFilesToBuffer } from './fs'; +import { createMeta, getLastRunFilePath, warn } from './lib'; import { ContentType, getDefautUploadProgressHandler, sendBuffer, -} from "./network"; +} from './network'; export async function handleSetCache() { try { const config = getCacheCommandConfig(); - if (config.type !== "SET_COMMAND_CONFIG" || !config.values) { - throw new Error("Config is missing!"); + if (config.type !== 'SET_COMMAND_CONFIG' || !config.values) { + throw new Error('Config is missing!'); } const { recordKey, id, preset, pwOutputDir, matrixIndex, matrixTotal } = @@ -37,7 +37,7 @@ export async function handleSetCache() { } if (uploadPaths.length === 0) { - throw new Error("No paths available to upload"); + throw new Error('No paths available to upload'); } const result = await createCache({ @@ -68,7 +68,7 @@ export async function handleSetCache() { uploadUrl: result.metaUploadUrl, }); } catch (e) { - warn(e, "Failed to save cache"); + warn(e, 'Failed to save cache'); } } @@ -93,9 +93,9 @@ async function handleArchiveUpload({ contentType, getDefautUploadProgressHandler(cacheId) ); - debug("Cache archive uploaded", { cacheId }); + debug('Cache archive uploaded', { cacheId }); } catch (error) { - debug("Failed to upload cache archive", error); + debug('Failed to upload cache archive', error); throw error; } } @@ -123,9 +123,9 @@ async function handleMetaUpload({ getDefautUploadProgressHandler(name) ); - debug("Cache meta uploaded", { cacheId }); + debug('Cache meta uploaded', { cacheId }); } catch (error) { - debug("Failed to upload cache meta", error); + debug('Failed to upload cache meta', error); throw error; } } diff --git a/packages/cmd/src/services/index.ts b/packages/cmd/src/services/index.ts index 64d7b83..8d85a2c 100644 --- a/packages/cmd/src/services/index.ts +++ b/packages/cmd/src/services/index.ts @@ -1,3 +1,3 @@ -export { handleGetRun } from "./api"; -export { handleGetCache, handleSetCache } from "./cache"; -export { handleCurrentsReport } from "./upload"; +export { handleGetRun } from './api'; +export { handleGetCache, handleSetCache } from './cache'; +export { handleCurrentsReport } from './upload'; diff --git a/packages/cmd/src/services/upload/discovery/createScanner.ts b/packages/cmd/src/services/upload/discovery/createScanner.ts index b3c95c5..c74f984 100644 --- a/packages/cmd/src/services/upload/discovery/createScanner.ts +++ b/packages/cmd/src/services/upload/discovery/createScanner.ts @@ -1,10 +1,10 @@ -import { ReportConfig } from "../types"; -import { JestScanner } from "./jest"; -import { Scanner } from "./scanner"; +import { ReportConfig } from '../types'; +import { JestScanner } from './jest'; +import { Scanner } from './scanner'; export function createScanner(config: ReportConfig): Scanner { switch (config.framework) { - case "jest": + case 'jest': return new JestScanner(config); default: diff --git a/packages/cmd/src/services/upload/discovery/index.ts b/packages/cmd/src/services/upload/discovery/index.ts index 0c258f2..6b5e091 100644 --- a/packages/cmd/src/services/upload/discovery/index.ts +++ b/packages/cmd/src/services/upload/discovery/index.ts @@ -1,2 +1,2 @@ -export * from "./createScanner"; -export * from "./types"; +export * from './createScanner'; +export * from './types'; diff --git a/packages/cmd/src/services/upload/discovery/jest/args/args.ts b/packages/cmd/src/services/upload/discovery/jest/args/args.ts index ea82730..b57fd91 100644 --- a/packages/cmd/src/services/upload/discovery/jest/args/args.ts +++ b/packages/cmd/src/services/upload/discovery/jest/args/args.ts @@ -1,46 +1,46 @@ -import { omit } from "lodash"; +import { omit } from 'lodash'; const ignoredOptions = [ - "bail", // causes unexpected behaviour - "clearCache", - "collectCoverage", - "collectCoverageFrom", - "color", - "colors", - "config", - "coverage", - "coverageDirectory", - "coveragePathIgnorePatterns", - "coverageProvider", - "coverageReporters", - "coverageThreshold", - "debug", - "detectLeaks", - "detectOpenHandles", - "errorOnDeprecated", - "expand", - "forceExit", - "json", - "listTests", - "logHeapUsage", - "noStackTrace", - "notify", - "notifyMode", - "openHandlesTimeout", - "outputFile", - "reporters", - "runner", - "shard", - "showConfig", - "showSeed", - "silent", - "testNamePattern", - "verbose", - "waitNextEventLoopTurnForUnhandledRejectionEvents", - "watch", - "watchAll", - "watchPathIgnorePatterns", - "watchman", + 'bail', // causes unexpected behaviour + 'clearCache', + 'collectCoverage', + 'collectCoverageFrom', + 'color', + 'colors', + 'config', + 'coverage', + 'coverageDirectory', + 'coveragePathIgnorePatterns', + 'coverageProvider', + 'coverageReporters', + 'coverageThreshold', + 'debug', + 'detectLeaks', + 'detectOpenHandles', + 'errorOnDeprecated', + 'expand', + 'forceExit', + 'json', + 'listTests', + 'logHeapUsage', + 'noStackTrace', + 'notify', + 'notifyMode', + 'openHandlesTimeout', + 'outputFile', + 'reporters', + 'runner', + 'shard', + 'showConfig', + 'showSeed', + 'silent', + 'testNamePattern', + 'verbose', + 'waitNextEventLoopTurnForUnhandledRejectionEvents', + 'watch', + 'watchAll', + 'watchPathIgnorePatterns', + 'watchman', ]; export function getDiscoveryOptions(options: Record) { @@ -51,9 +51,9 @@ export function argvToString(argv: Record) { let args = []; for (const [key, value] of Object.entries(argv)) { - if (key === "_" || key === "$0" || key.includes("-")) continue; // skip _, script name and the kebab case properties added by yargs + if (key === '_' || key === '$0' || key.includes('-')) continue; // skip _, script name and the kebab case properties added by yargs - if (typeof value === "boolean") { + if (typeof value === 'boolean') { if (value) { args.push(`--${key}`); } @@ -66,5 +66,5 @@ export function argvToString(argv: Record) { } } - return args.join(" "); + return args.join(' '); } diff --git a/packages/cmd/src/services/upload/discovery/jest/args/config.ts b/packages/cmd/src/services/upload/discovery/jest/args/config.ts index 01a43fb..23b0764 100644 --- a/packages/cmd/src/services/upload/discovery/jest/args/config.ts +++ b/packages/cmd/src/services/upload/discovery/jest/args/config.ts @@ -1,13 +1,13 @@ -import { debug as _debug } from "@debug"; -import { error } from "@logger"; -import fs from "fs"; -import { readInitialOptions } from "jest-config"; -import { omit } from "lodash"; -import path from "path"; -import { retryWithBackoff } from "../utils"; -import { readFileContents } from "../utils/fs"; +import { debug as _debug } from '@debug'; +import { error } from '@logger'; +import fs from 'fs'; +import { readInitialOptions } from 'jest-config'; +import { omit } from 'lodash'; +import path from 'path'; +import { retryWithBackoff } from '../utils'; +import { readFileContents } from '../utils/fs'; -const debug = _debug.extend("jest-discovery"); +const debug = _debug.extend('jest-discovery'); export async function getConfigFilePath( explicitConfigFilePath?: string @@ -19,63 +19,63 @@ export async function getConfigFilePath( const configOptionsToAvoid = [ // from docs: https://jestjs.io/docs/configuration - "collectCoverage", - "collectCoverageFrom", - "coverageDirectory", - "coveragePathIgnorePatterns", - "coverageProvider", - "coverageReporters", - "coverageThreshold", - "errorOnDeprecated", - "forceCoverageMatch", - "notify", - "notifyMode", - "openHandlesTimeout", - "reporters", - "runner", - "showSeed", - "testFailureExitCode", - "verbose", - "watchPathIgnorePatterns", - "watchPlugins", - "watchman", + 'collectCoverage', + 'collectCoverageFrom', + 'coverageDirectory', + 'coveragePathIgnorePatterns', + 'coverageProvider', + 'coverageReporters', + 'coverageThreshold', + 'errorOnDeprecated', + 'forceCoverageMatch', + 'notify', + 'notifyMode', + 'openHandlesTimeout', + 'reporters', + 'runner', + 'showSeed', + 'testFailureExitCode', + 'verbose', + 'watchPathIgnorePatterns', + 'watchPlugins', + 'watchman', // from Config type - "bail", // causes unexpected behaviour - "clearCache", - "color", - "colors", - "debug", - "detectLeaks", - "detectOpenHandles", - "expand", - "forceExit", - "json", - "listTests", - "logHeapUsage", - "noStackTrace", - "outputFile", - "shard", - "showConfig", - "silent", - "testNamePattern", - "waitNextEventLoopTurnForUnhandledRejectionEvents", - "watch", - "watchAll", + 'bail', // causes unexpected behaviour + 'clearCache', + 'color', + 'colors', + 'debug', + 'detectLeaks', + 'detectOpenHandles', + 'expand', + 'forceExit', + 'json', + 'listTests', + 'logHeapUsage', + 'noStackTrace', + 'outputFile', + 'shard', + 'showConfig', + 'silent', + 'testNamePattern', + 'waitNextEventLoopTurnForUnhandledRejectionEvents', + 'watch', + 'watchAll', ]; // from InitialProjectOptions type const projectConfigOptionsToAvoid = [ - "collectCoverageFrom", - "coverageDirectory", - "coveragePathIgnorePatterns", - "detectLeaks", - "detectOpenHandles", - "errorOnDeprecated", - "forceCoverageMatch", - "openHandlesTimeout", - "runner", - "watchPathIgnorePatterns", + 'collectCoverageFrom', + 'coverageDirectory', + 'coveragePathIgnorePatterns', + 'detectLeaks', + 'detectOpenHandles', + 'errorOnDeprecated', + 'forceCoverageMatch', + 'openHandlesTimeout', + 'runner', + 'watchPathIgnorePatterns', ]; const parsedConfigObject = omit(initialConfig, configOptionsToAvoid); @@ -83,7 +83,7 @@ export async function getConfigFilePath( if (parsedConfigObject.projects) { parsedConfigObject.projects = parsedConfigObject.projects.map( (project) => - typeof project !== "string" + typeof project !== 'string' ? omit(project, projectConfigOptionsToAvoid) : project ); @@ -102,7 +102,7 @@ export async function getConfigFilePath( ); const configFileContents = `module.exports=${JSON.stringify(parsedConfigObject, null, 2)}`; - debug("configFileContent: %O", configFileContents); + debug('configFileContent: %O', configFileContents); fs.writeFileSync(tmpFilePath, configFileContents); await retryWithBackoff( @@ -112,8 +112,8 @@ export async function getConfigFilePath( return tmpFilePath; } catch (err) { - error("Failed to recreate the config file"); - debug("error %o", err); + error('Failed to recreate the config file'); + debug('error %o', err); return null; } } diff --git a/packages/cmd/src/services/upload/discovery/jest/args/index.ts b/packages/cmd/src/services/upload/discovery/jest/args/index.ts index 3a9e3e0..78df84c 100644 --- a/packages/cmd/src/services/upload/discovery/jest/args/index.ts +++ b/packages/cmd/src/services/upload/discovery/jest/args/index.ts @@ -1,27 +1,27 @@ -import { isEmpty } from "lodash"; -import { CLIArgs } from "../../../types"; -import { argvToString, getDiscoveryOptions } from "./args"; -import { getConfigFilePath } from "./config"; +import { isEmpty } from 'lodash'; +import { CLIArgs } from '../../../types'; +import { argvToString, getDiscoveryOptions } from './args'; +import { getConfigFilePath } from './config'; export async function getCLIArgs( cliArgsFromConfig: CLIArgs ): Promise<{ cliArgs: string[]; configFilePath: string | null }> { - const testNamePattern = "!!##ThisPatternWillNotMatchAnyTestName##!!"; + const testNamePattern = '!!##ThisPatternWillNotMatchAnyTestName##!!'; const jestOptions = cliArgsFromConfig.options; const discoveryOptions = getDiscoveryOptions(jestOptions); const discoveryOptionsString = argvToString(discoveryOptions); - const explicitConfigFilePath = jestOptions["config"] as string | undefined; + const explicitConfigFilePath = jestOptions['config'] as string | undefined; const configFilePath = await getConfigFilePath(explicitConfigFilePath); const cliArgs = [ discoveryOptionsString, - "--testNamePattern", + '--testNamePattern', testNamePattern, - "--reporters", - "@currents/cmd/discovery/jest", - "--shard=1/1", - configFilePath ? `--config=${configFilePath}` : "", + '--reporters', + '@currents/cmd/discovery/jest', + '--shard=1/1', + configFilePath ? `--config=${configFilePath}` : '', ...(cliArgsFromConfig.args as string[]), ].filter((value) => !isEmpty(value)); diff --git a/packages/cmd/src/services/upload/discovery/jest/index.ts b/packages/cmd/src/services/upload/discovery/jest/index.ts index 75d1930..4de60bf 100644 --- a/packages/cmd/src/services/upload/discovery/jest/index.ts +++ b/packages/cmd/src/services/upload/discovery/jest/index.ts @@ -1,8 +1,8 @@ -import { Config } from "@jest/types"; -import { ReportConfig } from "../../types"; -import { FullTestSuite } from "../types"; -import { jestScanner } from "./scanner"; -import { Scanner } from "../scanner"; +import { Config } from '@jest/types'; +import { ReportConfig } from '../../types'; +import { FullTestSuite } from '../types'; +import { jestScanner } from './scanner'; +import { Scanner } from '../scanner'; export class JestScanner extends Scanner { constructor(config: ReportConfig) { diff --git a/packages/cmd/src/services/upload/discovery/jest/reporter.ts b/packages/cmd/src/services/upload/discovery/jest/reporter.ts index 0188e69..b2fe863 100644 --- a/packages/cmd/src/services/upload/discovery/jest/reporter.ts +++ b/packages/cmd/src/services/upload/discovery/jest/reporter.ts @@ -1,12 +1,12 @@ -import { debug as _debug } from "@debug"; +import { debug as _debug } from '@debug'; import { AggregatedResult, Reporter, Test, TestContext, TestResult, -} from "@jest/reporters"; -import fs from "fs-extra"; +} from '@jest/reporters'; +import fs from 'fs-extra'; import { getDefaultProjectId, getProjectId, @@ -14,25 +14,25 @@ import { getTestCaseId, getTestTags, testToSpecName, -} from "./utils/test"; +} from './utils/test'; -import { dim, error } from "@logger"; -import { FullSuiteProject, FullSuiteTest, FullTestSuite } from "../types"; +import { dim, error } from '@logger'; +import { FullSuiteProject, FullSuiteTest, FullTestSuite } from '../types'; -const debug = _debug.extend("jest-discovery"); +const debug = _debug.extend('jest-discovery'); export default class DiscoveryReporter implements Reporter { private specsWithoutResultsCount = 0; private fullTestSuite: Record< string, - Omit & { + Omit & { tests: FullSuiteTest[]; } > = {}; onRunStart(results: AggregatedResult) { - debug("onRunStart, results: %O", results); - console.time(dim("@currents/jest-discovery")); + debug('onRunStart, results: %O', results); + console.time(dim('@currents/jest-discovery')); } onTestFileResult(test: Test, testResult: TestResult): Promise | void { @@ -47,11 +47,11 @@ export default class DiscoveryReporter implements Reporter { } const spec = testToSpecName(test); - debug("onTestFileResult [%s][%s]", projectId, spec); + debug('onTestFileResult [%s][%s]', projectId, spec); if (testResult.testResults.length === 0) { debug( - "Failed to obtain spec results, error:", + 'Failed to obtain spec results, error:', spec, testResult.failureMessage ); @@ -78,20 +78,20 @@ export default class DiscoveryReporter implements Reporter { // eslint-disable-next-line turbo/no-undeclared-env-vars const filePath = process.env.CURRENTS_DISCOVERY_PATH; if (!filePath) { - throw new Error("CURRENTS_DISCOVERY_PATH is not set"); + throw new Error('CURRENTS_DISCOVERY_PATH is not set'); } let fullTestSuite: FullTestSuite = []; if (this.specsWithoutResultsCount > 0) { - error("Incomplete full test suite! Run the command with --debug flag."); + error('Incomplete full test suite! Run the command with --debug flag.'); } else { fullTestSuite = this.getFullTestSuite(testContexts); - debug("onRunComplete %s, %o", filePath, fullTestSuite); + debug('onRunComplete %s, %o', filePath, fullTestSuite); } - await fs.writeFile(filePath, JSON.stringify(fullTestSuite), "utf8"); + await fs.writeFile(filePath, JSON.stringify(fullTestSuite), 'utf8'); - console.timeEnd(dim("@currents/jest-discovery")); + console.timeEnd(dim('@currents/jest-discovery')); } // this is required to prevent different projectId in the full test suite and reported results diff --git a/packages/cmd/src/services/upload/discovery/jest/scanner.ts b/packages/cmd/src/services/upload/discovery/jest/scanner.ts index 6277faa..df639aa 100644 --- a/packages/cmd/src/services/upload/discovery/jest/scanner.ts +++ b/packages/cmd/src/services/upload/discovery/jest/scanner.ts @@ -1,46 +1,46 @@ -import { Config } from "@jest/types"; -import fs from "fs-extra"; -import { run } from "jest-cli"; -import tmp from "tmp"; - -import { debug as _debug } from "@debug"; -import { dim, error } from "@logger"; -import { CLIArgs } from "../../types"; -import { FullTestSuite } from "../types"; -import { getCLIArgs } from "./args"; -import { retryWithBackoff } from "./utils"; -import { readFileContents } from "./utils/fs"; -import { readJsonFile } from "@lib"; - -const debug = _debug.extend("jest-discovery"); +import { Config } from '@jest/types'; +import fs from 'fs-extra'; +import { run } from 'jest-cli'; +import tmp from 'tmp'; + +import { debug as _debug } from '@debug'; +import { dim, error } from '@logger'; +import { CLIArgs } from '../../types'; +import { FullTestSuite } from '../types'; +import { getCLIArgs } from './args'; +import { retryWithBackoff } from './utils'; +import { readFileContents } from './utils/fs'; +import { readJsonFile } from '@lib'; + +const debug = _debug.extend('jest-discovery'); export async function jestScanner( _config: Config.GlobalConfig, cliArgsFromConfig: CLIArgs ) { - console.time(dim("@currents/jest:fullTestSuite-ready")); + console.time(dim('@currents/jest:fullTestSuite-ready')); const { cliArgs, configFilePath } = await getCLIArgs(cliArgsFromConfig); try { - const tmpFile = tmp.fileSync({ postfix: ".json" }); + const tmpFile = tmp.fileSync({ postfix: '.json' }); - debug("running scanner: %o", cliArgs); + debug('running scanner: %o', cliArgs); // eslint-disable-next-line turbo/no-undeclared-env-vars process.env.CURRENTS_DISCOVERY_PATH = tmpFile.name; // set openHandlesTimeout to 0 to avoid Jest "open handles" warning - await run(cliArgs.concat(["--openHandlesTimeout=0"])); + await run(cliArgs.concat(['--openHandlesTimeout=0'])); await retryWithBackoff( readFileContents, Array.from({ length: 300 }, () => 100) // 30s )(tmpFile.name); - console.timeEnd(dim("@currents/jest:fullTestSuite-ready")); + console.timeEnd(dim('@currents/jest:fullTestSuite-ready')); return await readJsonFile(tmpFile.name); } catch (err) { - error("Failed to obtain the jest full test suite:", err); + error('Failed to obtain the jest full test suite:', err); return []; } finally { if (configFilePath) { diff --git a/packages/cmd/src/services/upload/discovery/jest/utils.ts b/packages/cmd/src/services/upload/discovery/jest/utils.ts index 432707a..dc8b9b2 100644 --- a/packages/cmd/src/services/upload/discovery/jest/utils.ts +++ b/packages/cmd/src/services/upload/discovery/jest/utils.ts @@ -24,5 +24,3 @@ export function retryWithBackoff( }); }; } - - diff --git a/packages/cmd/src/services/upload/discovery/jest/utils/fs.ts b/packages/cmd/src/services/upload/discovery/jest/utils/fs.ts index 505de2f..8e32d8e 100644 --- a/packages/cmd/src/services/upload/discovery/jest/utils/fs.ts +++ b/packages/cmd/src/services/upload/discovery/jest/utils/fs.ts @@ -1,5 +1,5 @@ -import fs from "fs-extra"; -import path from "path"; +import fs from 'fs-extra'; +import path from 'path'; export function getRelativeFileLocation(aPath: string, rootDir: string) { return toPosixPath(path.relative(rootDir, aPath)); @@ -11,7 +11,7 @@ function toPosixPath(aPath: string): string { export async function readFileContents(filePath: string) { const exists = await fs.pathExists(filePath); - if (!exists) throw new Error("File does not exist"); + if (!exists) throw new Error('File does not exist'); return exists; } diff --git a/packages/cmd/src/services/upload/discovery/jest/utils/index.ts b/packages/cmd/src/services/upload/discovery/jest/utils/index.ts index b6b3657..c5d9291 100644 --- a/packages/cmd/src/services/upload/discovery/jest/utils/index.ts +++ b/packages/cmd/src/services/upload/discovery/jest/utils/index.ts @@ -1,2 +1,2 @@ -export * from "fs"; -export * from "./test"; +export * from 'fs'; +export * from './test'; diff --git a/packages/cmd/src/services/upload/discovery/jest/utils/test.ts b/packages/cmd/src/services/upload/discovery/jest/utils/test.ts index 552f9c7..3846364 100644 --- a/packages/cmd/src/services/upload/discovery/jest/utils/test.ts +++ b/packages/cmd/src/services/upload/discovery/jest/utils/test.ts @@ -1,10 +1,10 @@ -import { Test, TestCaseResult } from "@jest/reporters"; -import type { Circus } from "@jest/types"; -import crypto from "node:crypto"; -import { getRelativeFileLocation } from "./fs"; +import { Test, TestCaseResult } from '@jest/reporters'; +import type { Circus } from '@jest/types'; +import crypto from 'node:crypto'; +import { getRelativeFileLocation } from './fs'; export function getDefaultProjectId() { - return "root"; + return 'root'; } export function getProjectId(test: Test) { @@ -34,16 +34,16 @@ export function getTestCaseId( const specName = testToSpecName(test); // Concatenate values - const combinedString: string = title.join(" ") + specName; + const combinedString: string = title.join(' ') + specName; // + testCaseResult.location?.column ?? // "" + testCaseResult.location?.line ?? // ""; // Hash the combined string using SHA-256 const fullHash: string = crypto - .createHash("sha256") + .createHash('sha256') .update(combinedString) - .digest("hex"); + .digest('hex'); // Take the first 16 characters of the hash const shortenedHash: string = fullHash.substring(0, 16); @@ -52,12 +52,12 @@ export function getTestCaseId( } export function getTestTags(testTitle: string[]) { - const titleTags = (testTitle.join(" ").match(/@(\S+)/g) ?? []) + const titleTags = (testTitle.join(' ').match(/@(\S+)/g) ?? []) .filter(Boolean) .map((t) => t as string); return Array.from( - new Set([...titleTags].map((i) => i.trim()).map((i) => i.replace("@", ""))) + new Set([...titleTags].map((i) => i.trim()).map((i) => i.replace('@', ''))) ); } diff --git a/packages/cmd/src/services/upload/discovery/scanner.ts b/packages/cmd/src/services/upload/discovery/scanner.ts index f6e0000..fdc8ee5 100644 --- a/packages/cmd/src/services/upload/discovery/scanner.ts +++ b/packages/cmd/src/services/upload/discovery/scanner.ts @@ -1,5 +1,5 @@ -import { ReportConfig } from "../types"; -import { FullTestSuite } from "./types"; +import { ReportConfig } from '../types'; +import { FullTestSuite } from './types'; export class Scanner { constructor(protected config: ReportConfig) {} diff --git a/packages/cmd/src/services/upload/fs.ts b/packages/cmd/src/services/upload/fs.ts index bcd8edd..31a79d3 100644 --- a/packages/cmd/src/services/upload/fs.ts +++ b/packages/cmd/src/services/upload/fs.ts @@ -1,7 +1,7 @@ -import fs from "fs-extra"; -import path, { join, resolve } from "path"; -import { error } from "@logger"; -import { ReportOptions } from "./types"; +import fs from 'fs-extra'; +import path, { join, resolve } from 'path'; +import { error } from '@logger'; +import { ReportOptions } from './types'; export async function resolveReportOptions( options?: ReportOptions @@ -9,13 +9,13 @@ export async function resolveReportOptions( const reportDir = await findReportDir(options?.reportDir); if (!reportDir) { - throw new Error("Failed to find the report dir"); + throw new Error('Failed to find the report dir'); } return { reportDir, configFilePath: - options?.configFilePath ?? path.join(reportDir, "config.json"), + options?.configFilePath ?? path.join(reportDir, 'config.json'), }; } @@ -25,7 +25,7 @@ async function findReportDir(reportDir?: string): Promise { return reportDir; } - return getLastCreatedDirectory(join(process.cwd(), ".currents")); + return getLastCreatedDirectory(join(process.cwd(), '.currents')); } async function getLastCreatedDirectory(dir: string): Promise { @@ -51,13 +51,13 @@ export async function checkPathExists(path: string): Promise { const exists = await fs.pathExists(path); return exists; } catch (err) { - error("Error checking if path exists:", error); + error('Error checking if path exists:', error); return false; } } export async function getInstanceReportList(reportDir: string) { - const instancesDir = path.join(reportDir, "instances"); + const instancesDir = path.join(reportDir, 'instances'); return getAllFilePaths(instancesDir); } @@ -76,5 +76,3 @@ async function getAllFilePaths(dir: string): Promise { return filePaths; } - - diff --git a/packages/cmd/src/services/upload/index.ts b/packages/cmd/src/services/upload/index.ts index a6267e6..8d41bd5 100644 --- a/packages/cmd/src/services/upload/index.ts +++ b/packages/cmd/src/services/upload/index.ts @@ -1,49 +1,49 @@ -import { debug, setTraceFilePath } from "@debug"; -import { getCI } from "@env/ciProvider"; -import { getGitInfo } from "@env/gitInfo"; -import { getPlatformInfo } from "@env/platform"; -import { reporterVersion } from "@env/versions"; -import { nanoid, readJsonFile, writeFileAsync } from "@lib"; -import { info, warn } from "@logger"; -import { mapValues } from "lodash"; -import path from "path"; -import semver from "semver"; +import { debug, setTraceFilePath } from '@debug'; +import { getCI } from '@env/ciProvider'; +import { getGitInfo } from '@env/gitInfo'; +import { getPlatformInfo } from '@env/platform'; +import { reporterVersion } from '@env/versions'; +import { nanoid, readJsonFile, writeFileAsync } from '@lib'; +import { info, warn } from '@logger'; +import { mapValues } from 'lodash'; +import path from 'path'; +import semver from 'semver'; import { Framework, RunCreationConfig, createRun as createRunApi, -} from "../../api"; -import { getCurrentsConfig } from "../../config/upload"; -import { FullTestSuite, createScanner } from "./discovery"; +} from '../../api'; +import { getCurrentsConfig } from '../../config/upload'; +import { FullTestSuite, createScanner } from './discovery'; import { checkPathExists, getInstanceReportList, resolveReportOptions, -} from "./fs"; -import { InstanceReport, ReportConfig, UploadMarkerInfo } from "./types"; +} from './fs'; +import { InstanceReport, ReportConfig, UploadMarkerInfo } from './types'; export async function handleCurrentsReport() { const currentsConfig = getCurrentsConfig(); if (!currentsConfig) { - throw new Error("Currents config is missing!"); + throw new Error('Currents config is missing!'); } const reportOptions = await resolveReportOptions(currentsConfig); // set the trace file path setTraceFilePath(getTraceFilePath(reportOptions.reportDir)); - debug("Reporter options: %o", reportOptions); + debug('Reporter options: %o', reportOptions); - info("Report directory: %s", reportOptions.reportDir); + info('Report directory: %s', reportOptions.reportDir); const config = await readJsonFile(reportOptions.configFilePath); - debug("Report config: %o", config); + debug('Report config: %o', config); const instanceReportList = await getInstanceReportList( reportOptions.reportDir ); debug( - "Found %d instance results in the reportDir: %s", + 'Found %d instance results in the reportDir: %s', instanceReportList.length, reportOptions.reportDir ); @@ -58,7 +58,7 @@ export async function handleCurrentsReport() { let fullTestSuite: FullTestSuite | null = null; if (markerFileExists) { const markerInfo = await readJsonFile(markerFilePath); - warn("Marker file detected. The report was already uploaded: %o", { + warn('Marker file detected. The report was already uploaded: %o', { runUrl: markerInfo.response.runUrl, isoDate: markerInfo.isoDate, }); @@ -69,7 +69,7 @@ export async function handleCurrentsReport() { if (fullTestSuiteFileExists) { fullTestSuite = await readJsonFile(fullTestSuiteFilePath); - debug("Full test suite file detected: %s", fullTestSuiteFilePath); + debug('Full test suite file detected: %s', fullTestSuiteFilePath); } } @@ -78,12 +78,12 @@ export async function handleCurrentsReport() { fullTestSuite = await scanner.getFullTestSuite(); if (isEmptyTestSuite(fullTestSuite)) { - throw new Error("Failed to discover the full test suite!"); + throw new Error('Failed to discover the full test suite!'); } await writeFileAsync(fullTestSuiteFilePath, JSON.stringify(fullTestSuite)); } else { - debug("The discovery stage was skipped"); + debug('The discovery stage was skipped'); } const defaultGroup = @@ -117,7 +117,7 @@ export async function handleCurrentsReport() { if (defaultGroup) { debug( - "Default group found: %s, overwriting the group in the results", + 'Default group found: %s, overwriting the group in the results', defaultGroup ); @@ -139,9 +139,9 @@ export async function handleCurrentsReport() { framework, }); - debug("Api response: %o", response); + debug('Api response: %o', response); - info("[%s] Run created: %s", group, response.runUrl); + info('[%s] Run created: %s', group, response.runUrl); const markerInfo = { response, @@ -151,12 +151,12 @@ export async function handleCurrentsReport() { await writeFileAsync(markerFilePath, JSON.stringify(markerInfo)); debug( - "Marker file %s: %s", - markerFileExists ? "overwritten" : "created", + 'Marker file %s: %s', + markerFileExists ? 'overwritten' : 'created', markerFilePath ); } catch (e) { - debug("Failed to upload the results to the dashboard"); + debug('Failed to upload the results to the dashboard'); throw e; } } @@ -182,7 +182,7 @@ async function createRun({ const commit = await getGitInfo(); const platformInfo = await getPlatformInfo(); const browserInfo = { - browserName: "node", + browserName: 'node', browserVersion: semver.coerce(process.version)?.version, }; @@ -206,19 +206,19 @@ async function createRun({ }; debug( - "Creating run: %o", - mapValues(payload, (v, k) => (k === "recordKey" ? "******" : v)) + 'Creating run: %o', + mapValues(payload, (v, k) => (k === 'recordKey' ? '******' : v)) ); return createRunApi(payload); } function getMarkerFilePath(reportDir: string) { - return path.join(reportDir, "upload.marker.json"); + return path.join(reportDir, 'upload.marker.json'); } function getFullTestSuiteFilePath(reportDir: string) { - return path.join(reportDir, "fullTestSuite.json"); + return path.join(reportDir, 'fullTestSuite.json'); } function getTraceFilePath(reportDir: string) { diff --git a/packages/cmd/src/services/upload/types.ts b/packages/cmd/src/services/upload/types.ts index 3629c7b..e1e07de 100644 --- a/packages/cmd/src/services/upload/types.ts +++ b/packages/cmd/src/services/upload/types.ts @@ -1,14 +1,14 @@ // possible currents test case statuses from reported results -export type TestCaseStatus = "passed" | "failed" | "pending"; +export type TestCaseStatus = 'passed' | 'failed' | 'pending'; // currents values suitable for jest status -export type TestRunnerStatus = "passed" | "failed" | "skipped"; +export type TestRunnerStatus = 'passed' | 'failed' | 'skipped'; // currents values suitable for jest expected status -export type ExpectedStatus = "passed" | "skipped"; +export type ExpectedStatus = 'passed' | 'skipped'; // jest test case statuses available in results -export type JestTestCaseStatus = "pending" | "todo" | "failed" | "passed"; +export type JestTestCaseStatus = 'pending' | 'todo' | 'failed' | 'passed'; export type InstanceReportStats = { suites: number; diff --git a/packages/cmd/tsup.config.ts b/packages/cmd/tsup.config.ts index 15b6c1a..b6ec203 100644 --- a/packages/cmd/tsup.config.ts +++ b/packages/cmd/tsup.config.ts @@ -1,18 +1,18 @@ -import { defineConfig } from "tsup"; +import { defineConfig } from 'tsup'; export default defineConfig({ entry: [ - "src/index.ts", - "src/bin/index.ts", - "src/services/upload/discovery/jest/reporter.ts", + 'src/index.ts', + 'src/bin/index.ts', + 'src/services/upload/discovery/jest/reporter.ts', ], esbuildOptions: (options) => { - options.legalComments = "linked"; + options.legalComments = 'linked'; }, splitting: false, shims: true, clean: true, sourcemap: true, - platform: "node", - target: "esnext", + platform: 'node', + target: 'esnext', }); diff --git a/packages/cmd/vitest.config.ts b/packages/cmd/vitest.config.ts index c54968c..c89e3d7 100644 --- a/packages/cmd/vitest.config.ts +++ b/packages/cmd/vitest.config.ts @@ -1,12 +1,12 @@ -import path from "path"; +import path from 'path'; const config = { resolve: { alias: { - "@debug": path.resolve(__dirname, "./src/debug"), - "@env": path.resolve(__dirname, "./src/env"), - "@lib": path.resolve(__dirname, "./src/lib"), - "@logger": path.resolve(__dirname, "./src/logger"), + '@debug': path.resolve(__dirname, './src/debug'), + '@env': path.resolve(__dirname, './src/env'), + '@lib': path.resolve(__dirname, './src/lib'), + '@logger': path.resolve(__dirname, './src/logger'), }, }, }; diff --git a/packages/eslint-config-custom/index.js b/packages/eslint-config-custom/index.js index 2ea526a..8065497 100644 --- a/packages/eslint-config-custom/index.js +++ b/packages/eslint-config-custom/index.js @@ -1,7 +1,7 @@ module.exports = { - extends: ["next", "turbo", "prettier"], + extends: ['next', 'turbo', 'prettier'], rules: { - "@next/next/no-html-link-for-pages": "off", - "react/jsx-key": "off", + '@next/next/no-html-link-for-pages': 'off', + 'react/jsx-key': 'off', }, }; diff --git a/packages/jest/CHANGELOG.md b/packages/jest/CHANGELOG.md index fe855f1..f2984ca 100644 --- a/packages/jest/CHANGELOG.md +++ b/packages/jest/CHANGELOG.md @@ -8,10 +8,9 @@ # [1.0.0-beta.5](https://github.com/currents-dev/currents-reporter/compare/@currents/jest-v1.0.0-beta.4...${npm.name}-v1.0.0-beta.5) (2024-07-16) - ### Bug Fixes -* include test case location in the report, when available ([#3](https://github.com/currents-dev/currents-reporter/issues/3)) ([f074021](https://github.com/currents-dev/currents-reporter/commit/f074021627ba44d130abeea0d608edf71440840a)) +- include test case location in the report, when available ([#3](https://github.com/currents-dev/currents-reporter/issues/3)) ([f074021](https://github.com/currents-dev/currents-reporter/commit/f074021627ba44d130abeea0d608edf71440840a)) # [1.0.0-beta.4](https://github.com/currents-dev/currents-reporter/compare/@currents/jest-v1.0.0-beta.3...${npm.name}-v1.0.0-beta.4) (2024-07-10) @@ -29,4 +28,4 @@ ### Features - add reportDir option to jest-reporter ([887fae6](https://github.com/currents-dev/currents-reporter/commit/887fae637f5d08243323e30abedba919075939b6)) -- add vitest ([2b25624](https://github.com/currents-dev/currents-reporter/commit/2b2562410adcce06de4e54abcc63c4a16603d27b)) \ No newline at end of file +- add vitest ([2b25624](https://github.com/currents-dev/currents-reporter/commit/2b2562410adcce06de4e54abcc63c4a16603d27b)) diff --git a/packages/jest/README.md b/packages/jest/README.md index 6858c73..2ebc28c 100644 --- a/packages/jest/README.md +++ b/packages/jest/README.md @@ -26,10 +26,10 @@ npm install @currents/jest --save-dev Add the reporter to Jest configuration: ```ts -import type { Config } from "jest"; +import type { Config } from 'jest'; const config: Config = { - reporters: ["default", ["@currents/jest"]], + reporters: ['default', ['@currents/jest']], }; export default config; diff --git a/packages/jest/publish.js b/packages/jest/publish.js index 77e3a68..80b9aa8 100755 --- a/packages/jest/publish.js +++ b/packages/jest/publish.js @@ -1,26 +1,26 @@ #!/usr/bin/env node -const { execSync } = require("child_process"); -const fs = require("fs"); -const pkg = require("./package.json"); -const { Command } = require("commander"); +const { execSync } = require('child_process'); +const fs = require('fs'); +const pkg = require('./package.json'); +const { Command } = require('commander'); const program = new Command() - .name("publish") - .option("-t, --tag ", "npm dist-tag to publish to"); + .name('publish') + .option('-t, --tag ', 'npm dist-tag to publish to'); program.parse(process.argv); const options = program.opts(); console.log(options); if (!options.tag) { - console.log("No tag supplied: beta or latest"); + console.log('No tag supplied: beta or latest'); process.exit(1); } console.log(process.cwd()); // fs.copyFileSync("../CHANGELOG.md", "./CHANGELOG.md"); -fs.copyFileSync("../../LICENSE.md", "./LICENSE.md"); +fs.copyFileSync('../../LICENSE.md', './LICENSE.md'); execSync(`npm pack --dry-run && npm publish --tag ${options.tag}`, { - cwd: "./", - stdio: "inherit", + cwd: './', + stdio: 'inherit', }); diff --git a/packages/jest/src/index.ts b/packages/jest/src/index.ts index 443ce14..b49b342 100644 --- a/packages/jest/src/index.ts +++ b/packages/jest/src/index.ts @@ -1,3 +1,3 @@ -import "source-map-support/register"; +import 'source-map-support/register'; -export { default } from "./reporter"; +export { default } from './reporter'; diff --git a/packages/jest/src/lib/args.ts b/packages/jest/src/lib/args.ts index 5bf18a9..3c21406 100644 --- a/packages/jest/src/lib/args.ts +++ b/packages/jest/src/lib/args.ts @@ -1,6 +1,6 @@ -import { yargsOptions } from "jest-cli"; -import { hideBin } from "yargs/helpers"; -import yargs from "yargs/yargs"; +import { yargsOptions } from 'jest-cli'; +import { hideBin } from 'yargs/helpers'; +import yargs from 'yargs/yargs'; export function getJestArgv() { const argv = yargs(hideBin(process.argv)) diff --git a/packages/jest/src/lib/debug.ts b/packages/jest/src/lib/debug.ts index d8dc419..54be0d9 100644 --- a/packages/jest/src/lib/debug.ts +++ b/packages/jest/src/lib/debug.ts @@ -1,3 +1,3 @@ -import Debug from "debug"; +import Debug from 'debug'; -export const debug = Debug("currents-jest"); +export const debug = Debug('currents-jest'); diff --git a/packages/jest/src/lib/error.ts b/packages/jest/src/lib/error.ts index 2a08c3e..ded46bb 100644 --- a/packages/jest/src/lib/error.ts +++ b/packages/jest/src/lib/error.ts @@ -13,17 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { codeFrameColumns } from "@babel/code-frame"; -import chalk from "chalk"; -import fs from "fs-extra"; -import path from "path"; -import StackUtils from "stack-utils"; -import url from "url"; -import { ErrorSchema, LocationSchema } from "../types"; +import { codeFrameColumns } from '@babel/code-frame'; +import chalk from 'chalk'; +import fs from 'fs-extra'; +import path from 'path'; +import StackUtils from 'stack-utils'; +import url from 'url'; +import { ErrorSchema, LocationSchema } from '../types'; function parseErrorString(errorString: string) { // Remove ANSI escape codes for easier parsing - const cleanString = errorString.replace(/\u001b\[[0-9;]*m/g, ""); + const cleanString = errorString.replace(/\u001b\[[0-9;]*m/g, ''); // Extract the error name, message, and stack trace const nameMatch = cleanString.match(/^(.+?):/); @@ -38,7 +38,7 @@ function parseErrorString(errorString: string) { const codeFrameMatch = cleanString.match(/at (.+):(\d+):(\d+)/); const fileWithFunction = codeFrameMatch ? codeFrameMatch[1] : null; const file = fileWithFunction - ? fileWithFunction.replace(/^.*\(([^)]+)\).*$/, "$1") + ? fileWithFunction.replace(/^.*\(([^)]+)\).*$/, '$1') : null; const line = codeFrameMatch ? parseInt(codeFrameMatch[2], 10) : null; const column = codeFrameMatch ? parseInt(codeFrameMatch[3], 10) : null; @@ -94,10 +94,10 @@ function prepareErrorStack(stack: string): { stackLines: string[]; location?: LocationSchema; } { - const lines = stack.split("\n"); - let firstStackLine = lines.findIndex((line) => line.startsWith(" at ")); + const lines = stack.split('\n'); + let firstStackLine = lines.findIndex((line) => line.startsWith(' at ')); if (firstStackLine === -1) firstStackLine = lines.length; - const message = lines.slice(0, firstStackLine).join("\n"); + const message = lines.slice(0, firstStackLine).join('\n'); const stackLines = lines.slice(firstStackLine); let location: LocationSchema | undefined; for (const line of stackLines) { @@ -124,7 +124,7 @@ function parseStackTraceLine(line: string): { let fileName: string | null = null; if (frame.file) { // ESM files return file:// URLs, see here: https://github.com/tapjs/stack-utils/issues/60 - fileName = frame.file.startsWith("file://") + fileName = frame.file.startsWith('file://') ? url.fileURLToPath(frame.file) : path.resolve(process.cwd(), frame.file); } @@ -156,20 +156,20 @@ export function formatError( !error.snippet && (!file || fs.realpathSync(file) !== location.file) ) { - tokens.push(""); + tokens.push(''); tokens.push( chalk.gray(` at `) + `${relativeFilePath(rootDir, location.file)}:${location.line}` ); } - tokens.push(""); + tokens.push(''); // @ts-ignore if (error.snippet) { // @ts-ignore tokens.push(error.snippet); } else { try { - const source = fs.readFileSync(location.file, "utf8"); + const source = fs.readFileSync(location.file, 'utf8'); const codeFrame = codeFrameColumns( source, { start: location }, @@ -181,8 +181,8 @@ export function formatError( } } } - tokens.push(""); - tokens.push(parsed.stackLines.join("\n")); + tokens.push(''); + tokens.push(parsed.stackLines.join('\n')); } else if (error.message) { tokens.push(error.message); // @ts-ignore @@ -192,7 +192,7 @@ export function formatError( } return { location, - message: tokens.join("\n"), + message: tokens.join('\n'), }; } diff --git a/packages/jest/src/lib/fs.ts b/packages/jest/src/lib/fs.ts index 6dd41dc..4e112b9 100644 --- a/packages/jest/src/lib/fs.ts +++ b/packages/jest/src/lib/fs.ts @@ -1,11 +1,11 @@ -import fs from "fs-extra"; -import { join } from "path"; -import { v4 as uuidv4 } from "uuid"; -import { error } from "../logger"; -import { debug } from "./debug"; +import fs from 'fs-extra'; +import { join } from 'path'; +import { v4 as uuidv4 } from 'uuid'; +import { error } from '../logger'; +import { debug } from './debug'; export function generateUniqueDirName(): string { - const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); + const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); const uniqueId = uuidv4(); return `${timestamp}-${uniqueId}`; } @@ -23,7 +23,7 @@ export async function createUniqueFolder( export async function createFolder(folderPath: string) { try { await fs.ensureDir(folderPath); - debug("Folder created", folderPath); + debug('Folder created', folderPath); return folderPath; } catch (err) { error(`Failed to create folder at ${folderPath}:`, err); @@ -39,8 +39,8 @@ export async function writeFileAsync( const filePath = join(basePath, fileName); try { - await fs.writeFile(filePath, content, "utf8"); - debug("File created", filePath); + await fs.writeFile(filePath, content, 'utf8'); + debug('File created', filePath); return filePath; } catch (err) { error(`Error writing file at ${filePath}:`, err); diff --git a/packages/jest/src/lib/getReportConfig.ts b/packages/jest/src/lib/getReportConfig.ts index 23050fa..5f2d6bb 100644 --- a/packages/jest/src/lib/getReportConfig.ts +++ b/packages/jest/src/lib/getReportConfig.ts @@ -1,19 +1,17 @@ -import { omit } from "lodash"; -import { getJestArgv } from "./args"; -import { Config } from "@jest/types"; -import { getJestVersion } from "./versions"; -import { ReportConfig } from "../types"; +import { omit } from 'lodash'; +import { getJestArgv } from './args'; +import { Config } from '@jest/types'; +import { getJestVersion } from './versions'; +import { ReportConfig } from '../types'; -export function getReportConfig( - config: Config.GlobalConfig -): ReportConfig { +export function getReportConfig(config: Config.GlobalConfig): ReportConfig { const argv = getJestArgv(); return { - framework: "jest", + framework: 'jest', frameworkVersion: getJestVersion(), cliArgs: { - options: omit(argv, "_", "$0"), + options: omit(argv, '_', '$0'), args: argv._ as string[], }, frameworkConfig: config, diff --git a/packages/jest/src/lib/hash.ts b/packages/jest/src/lib/hash.ts index 094ca3e..2048cc9 100644 --- a/packages/jest/src/lib/hash.ts +++ b/packages/jest/src/lib/hash.ts @@ -1,16 +1,16 @@ -import * as crypto from "crypto"; +import * as crypto from 'crypto'; export function generateShortHash(specName: string): string { // Create a SHA-256 hash of the specName - const hash = crypto.createHash("sha256").update(specName).digest("base64"); + const hash = crypto.createHash('sha256').update(specName).digest('base64'); // Optionally, you can shorten the hash and make it URL-safe // Here, we take the first 8 characters for a shorter hash and replace URL-unsafe characters const shortHash = hash .slice(0, 8) - .replace(/\+/g, "-") - .replace(/\//g, "_") - .replace(/=+$/, ""); + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=+$/, ''); return shortHash; } diff --git a/packages/jest/src/lib/index.ts b/packages/jest/src/lib/index.ts index fe9d09e..99f144b 100644 --- a/packages/jest/src/lib/index.ts +++ b/packages/jest/src/lib/index.ts @@ -1,9 +1,9 @@ -export * from "./args"; -export * from "./debug"; -export * from "./deferred"; -export * from "./fs"; -export * from "./error"; -export * from "./hash"; -export * from "./relativeFileLocation"; -export * from "./test"; -export * from "./versions"; +export * from './args'; +export * from './debug'; +export * from './deferred'; +export * from './fs'; +export * from './error'; +export * from './hash'; +export * from './relativeFileLocation'; +export * from './test'; +export * from './versions'; diff --git a/packages/jest/src/lib/relativeFileLocation.ts b/packages/jest/src/lib/relativeFileLocation.ts index b51c8a4..4905f6e 100644 --- a/packages/jest/src/lib/relativeFileLocation.ts +++ b/packages/jest/src/lib/relativeFileLocation.ts @@ -1,4 +1,4 @@ -import path from "path"; +import path from 'path'; export function getRelativeFileLocation(aPath: string, rootDir: string) { return toPosixPath(path.relative(rootDir, aPath)); diff --git a/packages/jest/src/lib/test.ts b/packages/jest/src/lib/test.ts index 3fae0c4..9322b15 100644 --- a/packages/jest/src/lib/test.ts +++ b/packages/jest/src/lib/test.ts @@ -1,20 +1,20 @@ -import { Test, TestCaseResult } from "@jest/reporters"; -import type { Circus } from "@jest/types"; -import crypto from "node:crypto"; +import { Test, TestCaseResult } from '@jest/reporters'; +import type { Circus } from '@jest/types'; +import crypto from 'node:crypto'; import { ExpectedStatus, JestTestCaseStatus, TestCaseStatus, TestRunnerStatus, -} from "../types"; -import { getRelativeFileLocation } from "./relativeFileLocation"; +} from '../types'; +import { getRelativeFileLocation } from './relativeFileLocation'; export type TestCaseInvocationStart = { testCaseStartInfo: Circus.TestCaseStartInfo; }; export function getDefaultProjectId() { - return "root"; + return 'root'; } export function getProjectId(test: Test) { @@ -44,16 +44,16 @@ export function getTestCaseId( const specName = testToSpecName(test); // Concatenate values - const combinedString: string = title.join(" ") + specName; + const combinedString: string = title.join(' ') + specName; // + testCaseResult.location?.column ?? // "" + testCaseResult.location?.line ?? // ""; // Hash the combined string using SHA-256 const fullHash: string = crypto - .createHash("sha256") + .createHash('sha256') .update(combinedString) - .digest("hex"); + .digest('hex'); // Take the first 16 characters of the hash const shortenedHash: string = fullHash.substring(0, 16); @@ -74,16 +74,16 @@ export function getTestCaseStatus( testStatus: JestTestCaseStatus ): TestCaseStatus { switch (testStatus) { - case "passed": - return "passed"; - case "failed": - return "failed"; - case "pending": - case "todo": - return "pending"; + case 'passed': + return 'passed'; + case 'failed': + return 'failed'; + case 'pending': + case 'todo': + return 'pending'; default: - throw new Error("Invalid Jest test case status"); + throw new Error('Invalid Jest test case status'); } } @@ -91,27 +91,27 @@ export function getTestRunnerStatus( status: JestTestCaseStatus ): TestRunnerStatus { switch (status) { - case "passed": - return "passed"; - case "failed": - return "failed"; - case "pending": - case "todo": - return "skipped"; + case 'passed': + return 'passed'; + case 'failed': + return 'failed'; + case 'pending': + case 'todo': + return 'skipped'; default: - throw new Error("Invalid Jest test case status"); + throw new Error('Invalid Jest test case status'); } } export function getExpectedStatus(status: JestTestCaseStatus): ExpectedStatus { switch (status) { - case "pending": - case "todo": - return "skipped"; + case 'pending': + case 'todo': + return 'skipped'; default: - return "passed"; + return 'passed'; } } @@ -121,7 +121,7 @@ export function jestStatusFromInvocations(testResults: TestCaseResult[]) { return statuses[0]; } - return "failed"; + return 'failed'; } export function getAttemptNumber(result: TestCaseResult) { @@ -133,7 +133,7 @@ export function isTestFlaky(testResults: TestCaseResult[]): boolean { const statuses = testResults.map((r) => r.status); return ( testResults.length > 1 && - statuses.includes("failed") && - statuses.includes("passed") + statuses.includes('failed') && + statuses.includes('passed') ); } diff --git a/packages/jest/src/lib/versions.ts b/packages/jest/src/lib/versions.ts index c2da3ad..3d0107b 100644 --- a/packages/jest/src/lib/versions.ts +++ b/packages/jest/src/lib/versions.ts @@ -1,15 +1,15 @@ -import path from "path"; -import fs from "fs"; -import { debug } from "./debug"; +import path from 'path'; +import fs from 'fs'; +import { debug } from './debug'; export function getJestVersion() { - return getPackageVersion("jest"); + return getPackageVersion('jest'); } export function getPackageVersion(packageName: string): string | null { try { - const packagePath = require.resolve(path.join(packageName, "package.json")); - const packageJsonContent = fs.readFileSync(packagePath, "utf8"); + const packagePath = require.resolve(path.join(packageName, 'package.json')); + const packageJsonContent = fs.readFileSync(packagePath, 'utf8'); const packageJson = JSON.parse(packageJsonContent); return packageJson.version; } catch (error) { diff --git a/packages/jest/src/logger/index.ts b/packages/jest/src/logger/index.ts index 57d79f6..cf3fa78 100644 --- a/packages/jest/src/logger/index.ts +++ b/packages/jest/src/logger/index.ts @@ -1,2 +1,2 @@ -export * from "./logDrain"; -export * from "./logger"; +export * from './logDrain'; +export * from './logger'; diff --git a/packages/jest/src/logger/logger.ts b/packages/jest/src/logger/logger.ts index fbec9ab..fa47cc4 100644 --- a/packages/jest/src/logger/logger.ts +++ b/packages/jest/src/logger/logger.ts @@ -1,9 +1,9 @@ -import chalk from "chalk"; -import util from "util"; +import chalk from 'chalk'; +import util from 'util'; -import { debug } from "../lib/debug"; -import { addToLogDrain } from "./logDrain"; -import { errors, warnings } from "./notices"; +import { debug } from '../lib/debug'; +import { addToLogDrain } from './logDrain'; +import { errors, warnings } from './notices'; const log = (...args: unknown[]) => { const stringToRender = util.format(...args); @@ -16,19 +16,19 @@ export const info = log; export const warn = (...args: unknown[]) => { const msg = util.format(...args); warnings.push(msg); - debug("WARNING: ", msg); - return log(chalk.bgYellow.black(" WARNING "), msg); + debug('WARNING: ', msg); + return log(chalk.bgYellow.black(' WARNING '), msg); }; export const warnWithNoTrace = (...args: unknown[]) => { const msg = util.format(...args); - debug("WARNING: ", msg); - return log(chalk.bgYellow.black(" WARNING "), msg); + debug('WARNING: ', msg); + return log(chalk.bgYellow.black(' WARNING '), msg); }; export const errorWithNoTrace = (...args: unknown[]) => { const msg = util.format(...args); - debug("ERROR: ", msg); - return log(chalk.bgRed.white(" ERROR "), msg); + debug('ERROR: ', msg); + return log(chalk.bgRed.white(' ERROR '), msg); }; export const success = (...args: unknown[]) => @@ -37,8 +37,8 @@ export const success = (...args: unknown[]) => export const error = (...args: unknown[]) => { const msg = util.format(...args); errors.push(msg); - debug("ERROR: ", msg); - return log(chalk.bgRed.white(" ERROR "), msg); + debug('ERROR: ', msg); + return log(chalk.bgRed.white(' ERROR '), msg); }; export const title = (...args: unknown[]) => @@ -47,38 +47,38 @@ export const title = (...args: unknown[]) => export const titleContent = (...args: unknown[]) => chalk.blue.bold(util.format(...args)); -export const divider = () => console.log("\n" + dividerContent() + "\n"); +export const divider = () => console.log('\n' + dividerContent() + '\n'); -export const dividerContent = () => chalk.dim(Array(64).fill("=").join("")); +export const dividerContent = () => chalk.dim(Array(64).fill('=').join('')); -export const blockStart = (label = "", lineLength = 64) => { - const _label = ` start of ${label ?? "block"} `; +export const blockStart = (label = '', lineLength = 64) => { + const _label = ` start of ${label ?? 'block'} `; const padding = Math.max(lineLength - _label.length, 0) / 2; const padStart = Math.floor(padding); const padEnd = Math.ceil(padding); return chalk.dim( - `${Array(padStart).fill("-").join("")}${_label}${Array(padEnd) - .fill("-") - .join("")}` + `${Array(padStart).fill('-').join('')}${_label}${Array(padEnd) + .fill('-') + .join('')}` ); }; -export const blockEnd = (label = "", lineLength = 64) => { - const _label = ` end of ${label ?? "block"} `; +export const blockEnd = (label = '', lineLength = 64) => { + const _label = ` end of ${label ?? 'block'} `; const padding = Math.max(lineLength - _label.length, 0) / 2; const padStart = Math.floor(padding); const padEnd = Math.ceil(padding); return chalk.dim( - `${Array(padStart).fill("-").join("")}${_label}${Array(padEnd) - .fill("-") - .join("")}` + `${Array(padStart).fill('-').join('')}${_label}${Array(padEnd) + .fill('-') + .join('')}` ); }; export const spacer = (n: number = 2) => - console.log(Array(n).fill("").join("\n")); + console.log(Array(n).fill('').join('\n')); export const cyan = chalk.cyan; export const blue = chalk.blueBright; diff --git a/packages/jest/src/reporter.ts b/packages/jest/src/reporter.ts index 7edb2d4..adbbb1c 100644 --- a/packages/jest/src/reporter.ts +++ b/packages/jest/src/reporter.ts @@ -7,10 +7,10 @@ import type { TestCaseResult, TestContext, TestResult, -} from "@jest/reporters"; -import { Circus } from "@jest/types"; +} from '@jest/reporters'; +import { Circus } from '@jest/types'; -import { join } from "path"; +import { join } from 'path'; import { Deferred, createFolder, @@ -31,10 +31,10 @@ import { jestStatusFromInvocations, testToSpecName, writeFileAsync, -} from "./lib"; -import { getReportConfig } from "./lib/getReportConfig"; -import { info } from "./logger"; -import { InstanceReport, JestTestCaseStatus, WorkerInfo } from "./types"; +} from './lib'; +import { getReportConfig } from './lib/getReportConfig'; +import { info } from './logger'; +import { InstanceReport, JestTestCaseStatus, WorkerInfo } from './types'; type TestCase = { id: string; @@ -42,7 +42,7 @@ type TestCase = { title: string[]; result: TestCaseResult[]; worker: WorkerInfo; - config: Test["context"]["config"]; + config: Test['context']['config']; location?: { column?: number; line?: number; @@ -63,8 +63,8 @@ type ReporterOptions = { export default class CustomReporter implements Reporter { private rootDir: string; - private reportDir: string = ""; - private instancesDir: string = ""; + private reportDir: string = ''; + private instancesDir: string = ''; private specInfo: Record = {}; private projectBySpecMap: Record = {}; private specsCount = 0; @@ -87,25 +87,25 @@ export default class CustomReporter implements Reporter { aggregatedResults: AggregatedResult, options: ReporterOnStartOptions ): Promise { - debug("Run started"); + debug('Run started'); this.specsCount = aggregatedResults.numTotalTestSuites; this.reportDir = this.options?.reportDir ? await createFolder(this.options.reportDir) - : await createUniqueFolder(this.rootDir, ".currents"); + : await createUniqueFolder(this.rootDir, '.currents'); - info("[currents]: Run started"); - info("[currents]: Report directory is set to - %s", this.reportDir); + info('[currents]: Run started'); + info('[currents]: Report directory is set to - %s', this.reportDir); - this.instancesDir = await createFolder(join(this.reportDir, "instances")); + this.instancesDir = await createFolder(join(this.reportDir, 'instances')); const reportConfig = getReportConfig(this.globalConfig); - debug("Report config:", reportConfig); + debug('Report config:', reportConfig); await writeFileAsync( this.reportDir, - "config.json", + 'config.json', JSON.stringify(reportConfig) ); @@ -130,7 +130,7 @@ export default class CustomReporter implements Reporter { this.specInfoDeferred[specKey] = new Deferred(); this.specInfoDeferred[specKey].resolve(); - debug("Spec execution started [%s]: %o", specName, this.specInfo[specKey]); + debug('Spec execution started [%s]: %o', specName, this.specInfo[specKey]); } /** @@ -181,7 +181,7 @@ export default class CustomReporter implements Reporter { } debug( - "Test case execution started [%s]: %o", + 'Test case execution started [%s]: %o', testId, this.specInfo[specKey].testCaseList[testCaseKey] ); @@ -219,7 +219,7 @@ export default class CustomReporter implements Reporter { location: testCaseResult.location, }; debug( - "Test case execution was skipped [%s]: %o", + 'Test case execution was skipped [%s]: %o', testId, this.specInfo[specKey].testCaseList[testCaseKey] ); @@ -232,7 +232,7 @@ export default class CustomReporter implements Reporter { this.resultsDeferred[testCaseKey] = new Deferred(); this.resultsDeferred[testCaseKey].resolve(); debug( - "Test case execution completed [%s]: %o", + 'Test case execution completed [%s]: %o', testId, this.specInfo[specKey].testCaseList[testCaseKey] ); @@ -244,7 +244,7 @@ export default class CustomReporter implements Reporter { const specKey = getSpecKey(projectId, specName); debug( - "Spec execution completed [%s], jest test result: %o", + 'Spec execution completed [%s], jest test result: %o', specName, testResult ); @@ -267,7 +267,7 @@ export default class CustomReporter implements Reporter { this.resultsDeferred[testCaseKey].resolve(); debug( - "Spec execution completed [%s][%s], adding skipped tests: %o", + 'Spec execution completed [%s][%s], adding skipped tests: %o', specName, testId, this.specInfo[specKey].testCaseList[testCaseKey] @@ -370,7 +370,7 @@ export default class CustomReporter implements Reporter { }; debug( - "Spec execution completed [%s], result payload: %o", + 'Spec execution completed [%s], result payload: %o', specName, result ); @@ -391,7 +391,7 @@ export default class CustomReporter implements Reporter { } async onRunComplete(test: Set, fullResult: AggregatedResult) { - info("[currents]: Run completed"); + info('[currents]: Run completed'); } } diff --git a/packages/jest/src/types.ts b/packages/jest/src/types.ts index 3629c7b..e1e07de 100644 --- a/packages/jest/src/types.ts +++ b/packages/jest/src/types.ts @@ -1,14 +1,14 @@ // possible currents test case statuses from reported results -export type TestCaseStatus = "passed" | "failed" | "pending"; +export type TestCaseStatus = 'passed' | 'failed' | 'pending'; // currents values suitable for jest status -export type TestRunnerStatus = "passed" | "failed" | "skipped"; +export type TestRunnerStatus = 'passed' | 'failed' | 'skipped'; // currents values suitable for jest expected status -export type ExpectedStatus = "passed" | "skipped"; +export type ExpectedStatus = 'passed' | 'skipped'; // jest test case statuses available in results -export type JestTestCaseStatus = "pending" | "todo" | "failed" | "passed"; +export type JestTestCaseStatus = 'pending' | 'todo' | 'failed' | 'passed'; export type InstanceReportStats = { suites: number; diff --git a/packages/jest/tsup.config.ts b/packages/jest/tsup.config.ts index 9bc6918..1d2693f 100644 --- a/packages/jest/tsup.config.ts +++ b/packages/jest/tsup.config.ts @@ -1,14 +1,14 @@ -import { defineConfig } from "tsup"; +import { defineConfig } from 'tsup'; export default defineConfig({ - entry: ["src/index.ts"], + entry: ['src/index.ts'], esbuildOptions: (options) => { - options.legalComments = "linked"; + options.legalComments = 'linked'; }, splitting: false, shims: true, clean: true, sourcemap: true, - platform: "node", - target: "esnext", + platform: 'node', + target: 'esnext', });