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 1 commit
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
102 changes: 102 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,103 @@ 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`.');
});

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();
});
});

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 getMocks = getNockWithVersionHeader(version)
.get('/api/v1/docs/simple-doc')
.basicAuth({ user: key })
.reply(200, { category, slug: simpleDoc.slug, lastUpdatedHash: 'anOldHash' });

const updateMocks = 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"
);

getMocks.done();
updateMocks.done();
versionMock.done();
});
});
});
});
140 changes: 140 additions & 0 deletions src/cmds/docs/create.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const config = require('config');
const crypto = require('crypto');
const frontMatter = require('gray-matter');
const { promisify } = require('util');
const { getProjectVersion } = require('../../lib/versionSelect');
const fetch = require('../../lib/fetch');
const { cleanHeaders, handleRes } = require('../../lib/fetch');
const { debug } = require('../../lib/logger');

const readFile = promisify(fs.readFile);

module.exports = class CreateDocCommand {
constructor() {
this.command = 'docs:create';
garrett-wade marked this conversation as resolved.
Show resolved Hide resolved
this.usage = 'docs:create <filepath> [options]';
this.description = 'Sync a single markdown file to your ReadMe project.';
this.category = 'docs';
this.position = 1;

this.hiddenArgs = ['filepath'];
this.args = [
{
name: 'key',
type: String,
description: 'Project API key',
},
{
name: 'version',
type: String,
description: 'Project version',
},
{
name: 'filepath',
type: String,
defaultOption: true,
},
];
}

async run(opts) {
const { filepath, key, version } = opts;
debug(`command: ${this.command}`);
debug(`opts: ${JSON.stringify(opts)}`);

if (!key) {
return Promise.reject(new Error('No project API key provided. Please use `--key`.'));
}

if (!filepath) {
return Promise.reject(new Error(`No filepath provided. Usage \`${config.get('cli')} ${this.usage}\`.`));
}

if (filepath.endsWith('.md') === false || !filepath.endsWith('.markdown') === false) {
return Promise.reject(new Error('The filepath specified is not a markdown file.'));
}

// TODO: should we allow version selection at all here?
// Let's revisit this once we re-evaluate our category logic in the API.
// Ideally we should ignore this parameter entirely if the category is included.
const selectedVersion = await getProjectVersion(version, key, false);

debug(`selectedVersion: ${selectedVersion}`);

debug(`reading file ${filepath}`);
const file = await readFile(filepath, 'utf8');
const matter = frontMatter(file);
debug(`frontmatter for ${filepath}: ${JSON.stringify(matter)}`);

// Stripping the subdirectories and markdown extension from the filename and lowercasing to get the default slug.
const slug = matter.data.slug || path.basename(filepath).replace(path.extname(filepath), '').toLowerCase();
const hash = crypto.createHash('sha1').update(file).digest('hex');

function createDoc(err) {
if (err.error !== 'DOC_NOTFOUND') return Promise.reject(err);
return fetch(`${config.get('host')}/api/v1/docs`, {
method: 'post',
headers: cleanHeaders(key, {
'x-readme-version': selectedVersion,
'Content-Type': 'application/json',
}),
body: JSON.stringify({
slug,
body: matter.content,
...matter.data,
lastUpdatedHash: hash,
}),
})
.then(res => handleRes(res))
.then(res => `🌱 successfully created '${res.slug}' with contents from ${filepath}`);
}

function updateDoc(existingDoc) {
return fetch(`${config.get('host')}/api/v1/docs/${slug}`, {
method: 'put',
headers: cleanHeaders(key, {
'x-readme-version': selectedVersion,
'Content-Type': 'application/json',
}),
body: JSON.stringify(
Object.assign(existingDoc, {
body: matter.content,
...matter.data,
lastUpdatedHash: hash,
})
),
})
.then(res => handleRes(res))
.then(res => `✏️ successfully updated '${res.slug}' with contents from ${filepath}`);
}

debug(`creating doc for ${slug}`);
const createdDoc = await fetch(`${config.get('host')}/api/v1/docs/${slug}`, {
method: 'get',
headers: cleanHeaders(key, {
'x-readme-version': selectedVersion,
Accept: 'application/json',
}),
})
.then(res => res.json())
.then(res => {
debug(`GET /docs/:slug API response for ${slug}: ${JSON.stringify(res)}`);
if (res.error) {
debug(`error retrieving data for ${slug}, creating doc`);
kanadgupta marked this conversation as resolved.
Show resolved Hide resolved
return createDoc(res);
}
debug(`data received for ${slug}, updating doc`);
return updateDoc(res);
})
.catch(err => {
// eslint-disable-next-line no-param-reassign
err.message = `Error uploading ${chalk.underline(filepath)}:\n\n${err.message}`;
throw err;
});

return chalk.green(createdDoc);
}
};