Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(GHA): workflow file creation onboarding #577

Merged
merged 87 commits into from
Sep 6, 2022
Merged
Show file tree
Hide file tree
Changes from 47 commits
Commits
Show all changes
87 commits
Select commit Hold shift + click to select a range
63a955f
fix: make command type more specific
kanadgupta Aug 22, 2022
2b732b8
refactor: consolidate `key` opt definition
kanadgupta Aug 22, 2022
072d8fc
fix: stricter type definition
kanadgupta Aug 22, 2022
9fb264b
chore: small copy change
kanadgupta Aug 22, 2022
0ebda16
refactor: small function change
kanadgupta Aug 22, 2022
1c5f333
fix: lint
kanadgupta Aug 22, 2022
81db4ae
feat: first pass at GHA generation
kanadgupta Aug 22, 2022
787f1cc
feat: add `--github` flag
kanadgupta Aug 22, 2022
464ff94
fix: allow user to not pass in spec path
kanadgupta Aug 22, 2022
60abfab
chore: small copy change
kanadgupta Aug 22, 2022
45b8569
fix: cleaning up a type, adding a smol doc
kanadgupta Aug 22, 2022
41b3754
test: add coverage for if user says no
kanadgupta Aug 22, 2022
33c46b5
refactor: new function signature, better typings
kanadgupta Aug 23, 2022
bbb21e0
Merge branch 'main' into kanad/rm-5048-add-prompt-flow-to-cli-for-cre…
kanadgupta Aug 23, 2022
8696f0e
test: smol refactor
kanadgupta Aug 23, 2022
21dadf8
test: remove unused mock
kanadgupta Aug 23, 2022
bb4c5d8
fix: better type
kanadgupta Aug 23, 2022
a70d917
fix: remove unused async
kanadgupta Aug 23, 2022
aa649ef
refactor: remove github API fetch
kanadgupta Aug 23, 2022
fa4a8be
refactor: better command string construction
kanadgupta Aug 23, 2022
95bff68
chore: some base file copy updates
kanadgupta Aug 23, 2022
86d4d87
refactor: make isGitHub file more generic
kanadgupta Aug 23, 2022
feb7434
refactor: consolidate CI checks into shared function
kanadgupta Aug 23, 2022
59720aa
feat: prevent user from running --github in CI env
kanadgupta Aug 23, 2022
dee97b9
feat: first pass at git detection
kanadgupta Aug 23, 2022
0e0a621
test: add some test cases
kanadgupta Aug 23, 2022
9cbc5d9
chore: skip failing tests to see if CI passes
kanadgupta Aug 23, 2022
b3e2a6e
fix: move regex to inside function
kanadgupta Aug 24, 2022
d28d780
test:: smol refactor
kanadgupta Aug 24, 2022
a5fce90
test: refactor to describe.each()
kanadgupta Aug 24, 2022
4e64fcb
test: add test for git check failure
kanadgupta Aug 24, 2022
93fdf1f
feat: add openapi command extension
kanadgupta Aug 24, 2022
6033109
fix: shorten github search
kanadgupta Aug 24, 2022
53f2f3a
test: oops
kanadgupta Aug 24, 2022
12a5e3d
test: add workflow file schema validation
kanadgupta Aug 24, 2022
a6d6e51
test: reorganizing test bed a bit
kanadgupta Aug 24, 2022
3a9a7ea
chore: better test coverage, smol nits
kanadgupta Aug 24, 2022
5e063b5
fix: better filename input validation
kanadgupta Aug 24, 2022
6beb84a
chore: clean up unused interfaces
kanadgupta Aug 24, 2022
70b1820
fix(openapi): add `update` param to ignored params
kanadgupta Aug 24, 2022
6744b94
fix: use `.yml` instead of `.yaml`
kanadgupta Aug 24, 2022
2c07512
test: more CI tests
kanadgupta Aug 24, 2022
e659b37
refactor: move helper function to separate file
kanadgupta Aug 24, 2022
13f9de8
chore: different language
kanadgupta Aug 24, 2022
5254b2f
test: stronger test
kanadgupta Aug 24, 2022
f662106
chore: smol refactor
kanadgupta Aug 24, 2022
e14d671
test(validate): e2e tests
kanadgupta Aug 24, 2022
ca998bc
chore: rename function
kanadgupta Aug 25, 2022
f03902b
fix: use JS string instead of YAML file
kanadgupta Aug 29, 2022
65a209a
fix: handle directory creation
kanadgupta Aug 29, 2022
f3c4db2
chore: smol link comment
kanadgupta Aug 29, 2022
6a19afd
feat: configstore to ensure we don't ask user too many times
kanadgupta Aug 29, 2022
f9ae5f2
test: fix tests
kanadgupta Aug 29, 2022
a91c259
chore: command comment
kanadgupta Aug 29, 2022
06895f4
chore(openapi): update args
kanadgupta Aug 29, 2022
2f51194
chore: clean up some comments
kanadgupta Aug 29, 2022
1ff606d
refactor: stricter types
kanadgupta Aug 29, 2022
81a3f6f
feat: support for docs/index
kanadgupta Aug 29, 2022
859bbe4
feat: add GHA functionality for docs-adjacent cmds
kanadgupta Aug 29, 2022
08362ac
Merge branch 'main' into kanad/rm-5048-add-prompt-flow-to-cli-for-cre…
kanadgupta Aug 29, 2022
c7d3576
fix: clean up command name prior to using as YAML keys
kanadgupta Aug 29, 2022
d3ca47a
test: add tests for docs-adjacent cmds
kanadgupta Aug 29, 2022
e303ceb
test: consolidate certain test mocks
kanadgupta Aug 29, 2022
4fc4207
Merge branch 'main' into kanad/rm-5048-add-prompt-flow-to-cli-for-cre…
kanadgupta Aug 30, 2022
6aec02a
Merge branch 'main' into kanad/rm-5048-add-prompt-flow-to-cli-for-cre…
kanadgupta Aug 30, 2022
8f6a9e8
fix(openapi): parameter logic fixes
kanadgupta Aug 30, 2022
4424c9a
fix: lint
kanadgupta Aug 30, 2022
b43825d
fix: console.log that i forgot to commit lol
kanadgupta Aug 30, 2022
77c3c89
test: smol refactor
kanadgupta Aug 30, 2022
64db3c5
feat: do major version check for configstore
kanadgupta Aug 30, 2022
01cf659
fix: separate out package version retrieval into function
kanadgupta Aug 30, 2022
70e950c
chore: error message language
kanadgupta Aug 30, 2022
7ba3dfc
docs: github **actions** workflow, not github action (singular)
kanadgupta Aug 30, 2022
19bf47e
docs: better intro language
kanadgupta Aug 30, 2022
ab39f20
docs: better success language
kanadgupta Aug 30, 2022
442767c
chore: fix snapshot, de-localize docs link
kanadgupta Aug 30, 2022
7d1610c
chore: smol language update per Spang
kanadgupta Aug 31, 2022
3d08179
Merge branch 'main' into kanad/rm-5048-add-prompt-flow-to-cli-for-cre…
kanadgupta Sep 6, 2022
f88459f
test: don't fetch schema from URL
kanadgupta Sep 6, 2022
c53ed7b
test: update broken test
kanadgupta Sep 6, 2022
0f956f9
test(GHA): extract setup/teardowns into common lib
kanadgupta Sep 6, 2022
050424d
test: better describe.each signature
kanadgupta Sep 6, 2022
f348c95
Merge branch 'main' into kanad/rm-5048-add-prompt-flow-to-cli-for-cre…
kanadgupta Sep 6, 2022
8bbc896
chore: debug statements
kanadgupta Sep 6, 2022
aee7b04
fix: weird flaky TS error
kanadgupta Sep 6, 2022
4188332
refactor: use decorator
kanadgupta Sep 6, 2022
a72f9ae
chore(mock/fs): clearer var names
kanadgupta Sep 6, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 144 additions & 0 deletions __tests__/cmds/__snapshots__/validate.test.ts.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,149 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`rdme validate GHA onboarding E2E tests should create GHA workflow if user passes in spec via opt (github flag enabled) 1`] = `
"
Your GitHub Action has been created! ✨

You're almost finished! Just a couple more steps:
1. Commit and push your newly created file (.github/workflows/validate-test-opt-spec-github-file.yml) to GitHub 🚀
2. Create a GitHub secret called \`README_API_KEY\` and populate that with a ReadMe API key 🔑"
`;

exports[`rdme validate GHA onboarding E2E tests should create GHA workflow if user passes in spec via opt (github flag enabled) 2`] = `
"# This GitHub Action workflow was auto-generated by the \`rdme\` cli on 2022-01-01T00:00:00.000Z
# You can view our full documentation here: https://docs.readme.com/docs/rdme
name: ReadMe GitHub Action 🦉

on:
push:
branches:
# This workflow will run every time you push code to the following branch: \`validate-test-opt-spec-github-branch\`
# Check out GitHub's docs for more info on configuring this:
# https://docs.github.com/actions/using-workflows/events-that-trigger-workflows
- validate-test-opt-spec-github-branch

jobs:
rdme-validate:
runs-on: ubuntu-latest
steps:
- name: Check out repo 📚
uses: actions/checkout@v3

- name: Run \`validate\` command 🚀
uses: readmeio/[email protected]
with:
rdme: validate __tests__/__fixtures__/petstore-simple-weird-version.json
"
`;

exports[`rdme validate GHA onboarding E2E tests should create GHA workflow if user passes in spec via opt (including workingDirectory) 1`] = `
"
Your GitHub Action has been created! ✨

You're almost finished! Just a couple more steps:
1. Commit and push your newly created file (.github/workflows/validate-test-opt-spec-workdir-file.yml) to GitHub 🚀
2. Create a GitHub secret called \`README_API_KEY\` and populate that with a ReadMe API key 🔑"
`;

exports[`rdme validate GHA onboarding E2E tests should create GHA workflow if user passes in spec via opt (including workingDirectory) 2`] = `
"# This GitHub Action workflow was auto-generated by the \`rdme\` cli on 2022-01-01T00:00:00.000Z
# You can view our full documentation here: https://docs.readme.com/docs/rdme
name: ReadMe GitHub Action 🦉

on:
push:
branches:
# This workflow will run every time you push code to the following branch: \`validate-test-opt-spec-github-branch\`
# Check out GitHub's docs for more info on configuring this:
# https://docs.github.com/actions/using-workflows/events-that-trigger-workflows
- validate-test-opt-spec-github-branch

jobs:
rdme-validate:
runs-on: ubuntu-latest
steps:
- name: Check out repo 📚
uses: actions/checkout@v3

- name: Run \`validate\` command 🚀
uses: readmeio/[email protected]
with:
rdme: validate petstore.json --workingDirectory=./__tests__/__fixtures__/relative-ref-oas
"
`;

exports[`rdme validate GHA onboarding E2E tests should create GHA workflow if user passes in spec via opt 1`] = `
"
Your GitHub Action has been created! ✨

You're almost finished! Just a couple more steps:
1. Commit and push your newly created file (.github/workflows/validate-test-opt-spec-file.yml) to GitHub 🚀
2. Create a GitHub secret called \`README_API_KEY\` and populate that with a ReadMe API key 🔑"
`;

exports[`rdme validate GHA onboarding E2E tests should create GHA workflow if user passes in spec via opt 2`] = `
"# This GitHub Action workflow was auto-generated by the \`rdme\` cli on 2022-01-01T00:00:00.000Z
# You can view our full documentation here: https://docs.readme.com/docs/rdme
name: ReadMe GitHub Action 🦉

on:
push:
branches:
# This workflow will run every time you push code to the following branch: \`validate-test-opt-spec-branch\`
# Check out GitHub's docs for more info on configuring this:
# https://docs.github.com/actions/using-workflows/events-that-trigger-workflows
- validate-test-opt-spec-branch

jobs:
rdme-validate:
runs-on: ubuntu-latest
steps:
- name: Check out repo 📚
uses: actions/checkout@v3

- name: Run \`validate\` command 🚀
uses: readmeio/[email protected]
with:
rdme: validate __tests__/__fixtures__/petstore-simple-weird-version.json
"
`;

exports[`rdme validate GHA onboarding E2E tests should create GHA workflow if user passes in spec via prompts 1`] = `
"
Your GitHub Action has been created! ✨

You're almost finished! Just a couple more steps:
1. Commit and push your newly created file (.github/workflows/validate-test-file.yml) to GitHub 🚀
2. Create a GitHub secret called \`README_API_KEY\` and populate that with a ReadMe API key 🔑"
`;

exports[`rdme validate GHA onboarding E2E tests should create GHA workflow if user passes in spec via prompts 2`] = `
"# This GitHub Action workflow was auto-generated by the \`rdme\` cli on 2022-01-01T00:00:00.000Z
# You can view our full documentation here: https://docs.readme.com/docs/rdme
name: ReadMe GitHub Action 🦉

on:
push:
branches:
# This workflow will run every time you push code to the following branch: \`validate-test-branch\`
# Check out GitHub's docs for more info on configuring this:
# https://docs.github.com/actions/using-workflows/events-that-trigger-workflows
- validate-test-branch

jobs:
rdme-validate:
runs-on: ubuntu-latest
steps:
- name: Check out repo 📚
uses: actions/checkout@v3

- name: Run \`validate\` command 🚀
uses: readmeio/[email protected]
with:
rdme: validate __tests__/__fixtures__/petstore-simple-weird-version.json
"
`;

exports[`rdme validate error handling should throw an error if an invalid OpenAPI 3.1 definition is supplied 1`] = `
[SyntaxError: OpenAPI schema validation failed.

Expand Down
2 changes: 0 additions & 2 deletions __tests__/cmds/openapi/reduce.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ const getCommandOutput = () => consoleInfoSpy.mock.calls.join('\n\n');

describe('rdme openapi:reduce', () => {
beforeEach(() => {
jest.mock('fs');
erunion marked this conversation as resolved.
Show resolved Hide resolved

consoleInfoSpy = jest.spyOn(console, 'info').mockImplementation();
});

Expand Down
144 changes: 144 additions & 0 deletions __tests__/cmds/validate.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
/* eslint-disable no-console */
import type { Response } from 'simple-git';

import fs from 'fs';

import chalk from 'chalk';
import prompts from 'prompts';

import Command from '../../src/cmds/validate';
import { git } from '../../src/lib/createGHA';
import createGitRemoteMock from '../helpers/get-git-mock';

const testWorkingDir = process.cwd();

Expand Down Expand Up @@ -105,4 +109,144 @@ describe('rdme validate', () => {
return expect(validate.run({ spec: './__tests__/__fixtures__/invalid-swagger.json' })).rejects.toMatchSnapshot();
});
});

describe('CI tests', () => {
beforeEach(() => {
process.env.TEST_CI = 'true';
});

afterEach(() => {
delete process.env.TEST_CI;
});

it('should successfully validate prompt and not run GHA onboarding', async () => {
process.env.TEST_CREATEGHA = 'true';
const spec = '__tests__/__fixtures__/petstore-simple-weird-version.json';
await expect(validate.run({ spec })).resolves.toBe(chalk.green(`${spec} is a valid OpenAPI API definition!`));
delete process.env.TEST_CREATEGHA;
});

it('should fail if user attempts to pass `--github` flag in CI environment', () => {
return expect(
validate.run({ github: true, spec: '__tests__/__fixtures__/petstore-simple-weird-version.json' })
).rejects.toStrictEqual(new Error('The `--github` flag is only for usage in non-CI environments.'));
});
});

describe('GHA onboarding E2E tests', () => {
let consoleInfoSpy;

beforeEach(() => {
consoleInfoSpy = jest.spyOn(console, 'info').mockImplementation();

// global Date override to handle timestamp generation
// stolen from here: https://github.com/facebook/jest/issues/2234#issuecomment-294873406
const DATE_TO_USE = new Date('2022');
// @ts-expect-error we're just overriding the constructor for tests,
// no need to construct everything
global.Date = jest.fn(() => DATE_TO_USE);

git.checkIsRepo = jest.fn(() => {
return Promise.resolve(true) as unknown as Response<boolean>;
});

git.remote = createGitRemoteMock();

process.env.TEST_CREATEGHA = 'true';
});

afterEach(() => {
consoleInfoSpy.mockRestore();
delete process.env.TEST_CREATEGHA;
jest.clearAllMocks();
});

it('should create GHA workflow if user passes in spec via prompts', async () => {
expect.assertions(6);
let yamlOutput;
const spec = '__tests__/__fixtures__/petstore-simple-weird-version.json';
const fileName = 'validate-test-file';
prompts.inject([spec, true, 'validate-test-branch', fileName]);

fs.writeFileSync = jest.fn((f, d) => {
yamlOutput = d;
return true;
});

await expect(validate.run({})).resolves.toMatchSnapshot();

expect(yamlOutput).toMatchSnapshot();
expect(fs.writeFileSync).toHaveBeenCalledWith(`.github/workflows/${fileName}.yml`, expect.any(String));
expect(console.info).toHaveBeenCalledTimes(2);
const output = getCommandOutput();
expect(output).toMatch('GitHub Repository detected!');
expect(output).toMatch('is a valid OpenAPI API definition!');
});

it('should create GHA workflow if user passes in spec via opt', async () => {
expect.assertions(3);
let yamlOutput;
const spec = '__tests__/__fixtures__/petstore-simple-weird-version.json';
const fileName = 'validate-test-opt-spec-file';
prompts.inject([true, 'validate-test-opt-spec-branch', fileName]);

fs.writeFileSync = jest.fn((f, d) => {
yamlOutput = d;
return true;
});

await expect(validate.run({ spec })).resolves.toMatchSnapshot();

expect(yamlOutput).toMatchSnapshot();
expect(fs.writeFileSync).toHaveBeenCalledWith(`.github/workflows/${fileName}.yml`, expect.any(String));
});

it('should create GHA workflow if user passes in spec via opt (github flag enabled)', async () => {
expect.assertions(3);
let yamlOutput;
const spec = '__tests__/__fixtures__/petstore-simple-weird-version.json';
const fileName = 'validate-test-opt-spec-github-file';
prompts.inject(['validate-test-opt-spec-github-branch', fileName]);

fs.writeFileSync = jest.fn((f, d) => {
yamlOutput = d;
return true;
});

await expect(validate.run({ spec, github: true })).resolves.toMatchSnapshot();

expect(yamlOutput).toMatchSnapshot();
expect(fs.writeFileSync).toHaveBeenCalledWith(`.github/workflows/${fileName}.yml`, expect.any(String));
});

it('should create GHA workflow if user passes in spec via opt (including workingDirectory)', async () => {
expect.assertions(3);
let yamlOutput;
const spec = 'petstore.json';
const fileName = 'validate-test-opt-spec-workdir-file';
prompts.inject([true, 'validate-test-opt-spec-github-branch', fileName]);

fs.writeFileSync = jest.fn((f, d) => {
yamlOutput = d;
return true;
});

await expect(
validate.run({ spec, workingDirectory: './__tests__/__fixtures__/relative-ref-oas' })
).resolves.toMatchSnapshot();

expect(yamlOutput).toMatchSnapshot();
expect(fs.writeFileSync).toHaveBeenCalledWith(`.github/workflows/${fileName}.yml`, expect.any(String));
});

it('should reject if user says no to creating GHA workflow', () => {
const spec = '__tests__/__fixtures__/petstore-simple-weird-version.json';
prompts.inject([spec, false]);
return expect(validate.run({})).rejects.toStrictEqual(
new Error(
'GitHub Action Workflow cancelled. If you ever change your mind, you can run this command again with the `--github` flag.'
)
);
});
});
});
40 changes: 40 additions & 0 deletions __tests__/helpers/get-git-mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { Response } from 'simple-git';

/**
* Creates a Jest mock function for testing `git.remote`
* @param remote remote to return (usually `origin`)
* @param remoteUrl git URL for the given remote
* @param defaultBranch the HEAD branch
*/
export default function createGitRemoteMock(
remote = 'origin',
remoteUrl = 'https://github.com/readmeio/rdme.git',
defaultBranch = 'main'
) {
return jest.fn(arr => {
// first call (used to grab remote for usage in subsequent commands)
if (!arr.length) {
if (!remote) return Promise.reject(new Error('Bad mock uh oh')) as unknown as Response<string>;
return Promise.resolve(remote) as unknown as Response<string>;
}
// second call (used to grab default branch)
if (arr.length === 2 && arr[0] === 'show' && arr[1] === remote) {
if (!defaultBranch) return Promise.reject(new Error('Bad mock uh oh')) as unknown as Response<string>;
return Promise.resolve(`* remote origin
Fetch URL: ${remoteUrl}
Push URL: ${remoteUrl}
HEAD branch: ${defaultBranch}
`) as unknown as Response<string>;
}

// third call (used to grab remote URLs)
if (arr.length === 1 && arr[0] === '-v') {
if (!remoteUrl) return Promise.reject(new Error('Bad mock uh oh')) as unknown as Response<string>;
return Promise.resolve(`origin ${remoteUrl} (fetch)
origin ${remoteUrl} (push)
`) as unknown as Response<string>;
}

return Promise.reject(new Error('Bad mock uh oh')) as unknown as Response<string>;
});
}
Loading