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: add docs:single #529

Merged
merged 7 commits into from
Jul 1, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,11 @@ rdme docs path-to-markdown-files --version={project-version}

This command also has a dry run mode, which can be useful for initial setup and debugging. You can read more about dry run mode [in our docs](https://docs.readme.com/docs/rdme#dry-run-mode).

#### Syncing a single Markdown File to ReadMe
garrett-wade marked this conversation as resolved.
Show resolved Hide resolved
```sh
rdme docs:create path-to-markdown-file --version={project-version}
```

#### Edit a Single ReadMe Doc on Your Local Machine

```sh
Expand Down
307 changes: 307 additions & 0 deletions __tests__/cmds/docs.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ const getApiNock = require('../get-api-nock');

const DocsCommand = require('../../src/cmds/docs');
const DocsEditCommand = require('../../src/cmds/docs/edit');
const DocsCreateCommand = require('../../src/cmds/docs/create');

const docs = new DocsCommand();
const docsEdit = new DocsEditCommand();
const docsCreate = new DocsCreateCommand();

const fixturesDir = `${__dirname}./../__fixtures__`;
const key = 'API_KEY';
Expand Down Expand Up @@ -542,3 +544,308 @@ describe('rdme docs:edit', () => {
fs.unlinkSync(`${slug}.md`);
});
});

describe('rdme docs:create', () => {
beforeAll(() => nock.disableNetConnect());

afterAll(() => nock.cleanAll());

it('should error if no api key provided', () => {
return expect(docsCreate.run({})).rejects.toThrow('No project API key provided. Please use `--key`.');
});

it('should error if no filepath provided', () => {
return expect(docsCreate.run({ key, version: '1.0.0' })).rejects.toThrow(
'No filepath provided. Usage `rdme docs:create <filepath> [options]`.'
);
});

it('should error if the argument isnt a folder', async () => {
await expect(docsCreate.run({ key, version: '1.0.0', filepath: 'not-a-markdown-file' })).rejects.toThrow(
'The filepath specified is not a markdown file.'
);
});

describe('new docs', () => {
it('should create new doc', async () => {
const slug = 'new-doc';
const doc = frontMatter(fs.readFileSync(path.join(fixturesDir, `/new-docs/${slug}.md`)));
const hash = hashFileContents(fs.readFileSync(path.join(fixturesDir, `/new-docs/${slug}.md`)));

const getMock = getNockWithVersionHeader(version)
.get(`/api/v1/docs/${slug}`)
.basicAuth({ user: key })
.reply(404, {
error: 'DOC_NOTFOUND',
message: `The doc with the slug '${slug}' couldn't be found`,
suggestion: '...a suggestion to resolve the issue...',
help: 'If you need help, email [email protected] and mention log "fake-metrics-uuid".',
});

const postMock = getNockWithVersionHeader(version)
.post('/api/v1/docs', { slug, body: doc.content, ...doc.data, lastUpdatedHash: hash })
.basicAuth({ user: key })
.reply(201, { slug, body: doc.content, ...doc.data, lastUpdatedHash: hash });

const versionMock = getApiNock()
.get(`/api/v1/version/${version}`)
.basicAuth({ user: key })
.reply(200, { version });

await expect(
docsCreate.run({ filepath: './__tests__/__fixtures__/new-docs/new-doc.md', key, version })
).resolves.toBe(
"🌱 successfully created 'new-doc' with contents from ./__tests__/__fixtures__/new-docs/new-doc.md"
);

getMock.done();
postMock.done();
versionMock.done();
});

it('should return creation info for dry run', async () => {
const slug = 'new-doc';
const doc = frontMatter(fs.readFileSync(path.join(fixturesDir, `/new-docs/${slug}.md`)));

const getMock = getNockWithVersionHeader(version)
.get(`/api/v1/docs/${slug}`)
.basicAuth({ user: key })
.reply(404, {
error: 'DOC_NOTFOUND',
message: `The doc with the slug '${slug}' couldn't be found`,
suggestion: '...a suggestion to resolve the issue...',
help: 'If you need help, email [email protected] and mention log "fake-metrics-uuid".',
});

const versionMock = getApiNock()
.get(`/api/v1/version/${version}`)
.basicAuth({ user: key })
.reply(200, { version });

await expect(
docsCreate.run({ dryRun: true, filepath: './__tests__/__fixtures__/new-docs/new-doc.md', key, version })
).resolves.toBe(
`🎭 dry run! This will create 'new-doc' with contents from ./__tests__/__fixtures__/new-docs/new-doc.md with the following metadata: ${JSON.stringify(
doc.data
)}`
);

getMock.done();
versionMock.done();
});

it('should fail if the doc is invalid', async () => {
const folder = 'failure-docs';
const slug = 'fail-doc';

const errorObject = {
error: 'DOC_INVALID',
message: "We couldn't save this doc (Path `category` is required.).",
};

const doc = frontMatter(fs.readFileSync(path.join(fixturesDir, `/${folder}/${slug}.md`)));

const hash = hashFileContents(fs.readFileSync(path.join(fixturesDir, `/${folder}/${slug}.md`)));

const getMock = getNockWithVersionHeader(version)
.get(`/api/v1/docs/${slug}`)
.basicAuth({ user: key })
.reply(404, {
error: 'DOC_NOTFOUND',
message: `The doc with the slug '${slug}' couldn't be found`,
suggestion: '...a suggestion to resolve the issue...',
help: 'If you need help, email [email protected] and mention log "fake-metrics-uuid".',
});

const postMock = getNockWithVersionHeader(version)
.post('/api/v1/docs', { slug, body: doc.content, ...doc.data, lastUpdatedHash: hash })
.basicAuth({ user: key })
.reply(400, errorObject);

const versionMock = getApiNock()
.get(`/api/v1/version/${version}`)
.basicAuth({ user: key })
.reply(200, { version });

const filepath = './__tests__/__fixtures__/failure-docs/fail-doc.md';

const formattedErrorObject = {
...errorObject,
message: `Error uploading ${chalk.underline(`${filepath}`)}:\n\n${errorObject.message}`,
};

await expect(docsCreate.run({ filepath: `${filepath}`, key, version })).rejects.toStrictEqual(
new APIError(formattedErrorObject)
);

getMock.done();
postMock.done();
versionMock.done();
});
});

describe('slug metadata', () => {
it('should use provided slug', async () => {
const slug = 'new-doc-slug';
const doc = frontMatter(fs.readFileSync(path.join(fixturesDir, `/slug-docs/${slug}.md`)));
const hash = hashFileContents(fs.readFileSync(path.join(fixturesDir, `/slug-docs/${slug}.md`)));

const getMock = getApiNock()
.get(`/api/v1/docs/${doc.data.slug}`)
.basicAuth({ user: key })
.reply(404, {
error: 'DOC_NOTFOUND',
message: `The doc with the slug '${slug}' couldn't be found`,
suggestion: '...a suggestion to resolve the issue...',
help: 'If you need help, email [email protected] and mention log "fake-metrics-uuid".',
});

const postMock = getApiNock()
.post('/api/v1/docs', { slug, body: doc.content, ...doc.data, lastUpdatedHash: hash })
.basicAuth({ user: key })
.reply(201, { slug: doc.data.slug, body: doc.content, ...doc.data, lastUpdatedHash: hash });

const versionMock = getApiNock()
.get(`/api/v1/version/${version}`)
.basicAuth({ user: key })
.reply(200, { version });

await expect(
docsCreate.run({ filepath: './__tests__/__fixtures__/slug-docs/new-doc-slug.md', key, version })
).resolves.toBe(
"🌱 successfully created 'marc-actually-wrote-a-test' with contents from ./__tests__/__fixtures__/slug-docs/new-doc-slug.md"
);

getMock.done();
postMock.done();
versionMock.done();
});
});

describe('existing docs', () => {
let simpleDoc;

beforeEach(() => {
const fileContents = fs.readFileSync(path.join(fixturesDir, '/existing-docs/simple-doc.md'));
simpleDoc = {
slug: 'simple-doc',
doc: frontMatter(fileContents),
hash: hashFileContents(fileContents),
};
});

it('should fetch doc and merge with what is returned', () => {
const getMock = getNockWithVersionHeader(version)
.get('/api/v1/docs/simple-doc')
.basicAuth({ user: key })
.reply(200, { category, slug: simpleDoc.slug, lastUpdatedHash: 'anOldHash' });

const updateMock = getNockWithVersionHeader(version)
.put('/api/v1/docs/simple-doc', {
category,
slug: simpleDoc.slug,
body: simpleDoc.doc.content,
lastUpdatedHash: simpleDoc.hash,
...simpleDoc.doc.data,
})
.basicAuth({ user: key })
.reply(200, {
category,
slug: simpleDoc.slug,
body: simpleDoc.doc.content,
});

const versionMock = getApiNock()
.get(`/api/v1/version/${version}`)
.basicAuth({ user: key })
.reply(200, { version });

return docsCreate
.run({ filepath: './__tests__/__fixtures__/existing-docs/simple-doc.md', key, version })
.then(updatedDocs => {
expect(updatedDocs).toBe(
"✏️ successfully updated 'simple-doc' with contents from ./__tests__/__fixtures__/existing-docs/simple-doc.md"
);

getMock.done();
updateMock.done();
versionMock.done();
});
});

it('should return doc update info for dry run', () => {
expect.assertions(1);

const getMock = getNockWithVersionHeader(version)
.get('/api/v1/docs/simple-doc')
.basicAuth({ user: key })
.reply(200, { category, slug: simpleDoc.slug, lastUpdatedHash: 'anOldHash' });

const versionMock = getApiNock()
.get(`/api/v1/version/${version}`)
.basicAuth({ user: key })
.reply(200, { version });

return docsCreate
.run({ dryRun: true, filepath: './__tests__/__fixtures__/existing-docs/simple-doc.md', key, version })
.then(updatedDocs => {
// All docs should have been updated because their hashes from the GET request were different from what they
// are currently.
expect(updatedDocs).toBe(
[
`🎭 dry run! This will update 'simple-doc' with contents from ./__tests__/__fixtures__/existing-docs/simple-doc.md with the following metadata: ${JSON.stringify(
simpleDoc.doc.data
)}`,
].join('\n')
);

getMock.done();
versionMock.done();
});
});

it('should not send requests for docs that have not changed', () => {
expect.assertions(1);

const getMock = getNockWithVersionHeader(version)
.get('/api/v1/docs/simple-doc')
.basicAuth({ user: key })
.reply(200, { category, slug: simpleDoc.slug, lastUpdatedHash: simpleDoc.hash });

const versionMock = getApiNock()
.get(`/api/v1/version/${version}`)
.basicAuth({ user: key })
.reply(200, { version });

return docsCreate
.run({ filepath: './__tests__/__fixtures__/existing-docs/simple-doc.md', key, version })
.then(skippedDocs => {
expect(skippedDocs).toBe('`simple-doc` was not updated because there were no changes.');

getMock.done();
versionMock.done();
});
});

it('should adjust "no changes" message if in dry run', () => {
const getMock = getNockWithVersionHeader(version)
.get('/api/v1/docs/simple-doc')
.basicAuth({ user: key })
.reply(200, { category, slug: simpleDoc.slug, lastUpdatedHash: simpleDoc.hash });

const versionMock = getApiNock()
.get(`/api/v1/version/${version}`)
.basicAuth({ user: key })
.reply(200, { version });

return docsCreate
.run({ dryRun: true, filepath: './__tests__/__fixtures__/existing-docs/simple-doc.md', key, version })
.then(skippedDocs => {
expect(skippedDocs).toBe('🎭 dry run! `simple-doc` will not be updated because there were no changes.');

getMock.done();
versionMock.done();
});
});
});
});
Loading