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

refactor(docs): consolidate logic #540

Merged
merged 3 commits into from
Jul 21, 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
102 changes: 4 additions & 98 deletions src/cmds/docs/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
const chalk = require('chalk');
const config = require('config');
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);
const pushDoc = require('../../lib/pushDoc');

module.exports = class DocsCommand {
constructor() {
Expand Down Expand Up @@ -88,98 +83,9 @@ module.exports = class DocsCommand {
return Promise.reject(new Error(`We were unable to locate Markdown files in ${folder}.`));
}

function createDoc(slug, file, filename, hash, err) {
if (err.error !== 'DOC_NOTFOUND') return Promise.reject(err);

if (dryRun) {
return `🎭 dry run! This will create '${slug}' with contents from ${filename} with the following metadata: ${JSON.stringify(
file.data
)}`;
}

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: file.content,
...file.data,
lastUpdatedHash: hash,
}),
})
.then(res => handleRes(res))
.then(res => `🌱 successfully created '${res.slug}' with contents from ${filename}`);
}

function updateDoc(slug, file, filename, hash, existingDoc) {
if (hash === existingDoc.lastUpdatedHash) {
return `${dryRun ? '🎭 dry run! ' : ''}\`${slug}\` ${
dryRun ? 'will not be' : 'was not'
} updated because there were no changes.`;
}

if (dryRun) {
return `🎭 dry run! This will update '${slug}' with contents from ${filename} with the following metadata: ${JSON.stringify(
file.data
)}`;
}

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: file.content,
...file.data,
lastUpdatedHash: hash,
})
),
})
.then(res => handleRes(res))
.then(res => `✏️ successfully updated '${res.slug}' with contents from ${filename}`);
}

const updatedDocs = await Promise.all(
files.map(async filename => {
debug(`reading file ${filename}`);
const file = await readFile(filename, 'utf8');
const matter = frontMatter(file);
debug(`frontmatter for ${filename}: ${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(filename).replace(path.extname(filename), '').toLowerCase();
const hash = crypto.createHash('sha1').update(file).digest('hex');

debug(`fetching data for ${slug}`);

return 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`);
return createDoc(slug, matter, filename, hash, res);
}
debug(`data received for ${slug}, updating doc`);
return updateDoc(slug, matter, filename, hash, res);
})
.catch(err => {
// eslint-disable-next-line no-param-reassign
err.message = `Error uploading ${chalk.underline(filename)}:\n\n${err.message}`;
throw err;
});
return pushDoc(key, selectedVersion, dryRun, filename);
})
);

Expand Down
103 changes: 4 additions & 99 deletions src/cmds/docs/single.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,9 @@
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);
const { debug } = require('../../lib/logger');
const { getProjectVersion } = require('../../lib/versionSelect');
const pushDoc = require('../../lib/pushDoc');

module.exports = class SingleDocCommand {
constructor() {
Expand Down Expand Up @@ -69,95 +62,7 @@ module.exports = class SingleDocCommand {

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

if (dryRun) {
return `🎭 dry run! This will create '${slug}' with contents from ${filepath} with the following metadata: ${JSON.stringify(
matter.data
)}`;
}

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) {
if (hash === existingDoc.lastUpdatedHash) {
return `${dryRun ? '🎭 dry run! ' : ''}\`${slug}\` ${
dryRun ? 'will not be' : 'was not'
} updated because there were no changes.`;
}

if (dryRun) {
return `🎭 dry run! This will update '${slug}' with contents from ${filepath} with the following metadata: ${JSON.stringify(
matter.data
)}`;
}

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`);
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;
});
const createdDoc = await pushDoc(key, selectedVersion, dryRun, filepath);

return chalk.green(createdDoc);
}
Expand Down
112 changes: 112 additions & 0 deletions src/lib/pushDoc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
const chalk = require('chalk');
const config = require('config');
const crypto = require('crypto');
const fs = require('fs');
const grayMatter = require('gray-matter');
const path = require('path');

const { cleanHeaders, handleRes } = require('./fetch');
const fetch = require('./fetch');
const { debug } = require('./logger');

/**
* Reads the contents of the specified Markdown file
* and creates/updates the doc in ReadMe
*
* @param {String} key the project API key
* @param {String} selectedVersion the project version
* @param {Boolean} dryRun boolean indicating dry run mode
* @param {String} filepath path to the Markdown file
* (file extension must end in `.md` or `.markdown`)
* @returns {Promise<String>} a string containing the result
*/
module.exports = async function pushDoc(key, selectedVersion, dryRun, filepath) {
debug(`reading file ${filepath}`);
const file = fs.readFileSync(filepath, 'utf8');
const matter = grayMatter(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);

if (dryRun) {
return `🎭 dry run! This will create '${slug}' with contents from ${filepath} with the following metadata: ${JSON.stringify(
matter.data
)}`;
}

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) {
if (hash === existingDoc.lastUpdatedHash) {
return `${dryRun ? '🎭 dry run! ' : ''}\`${slug}\` ${
dryRun ? 'will not be' : 'was not'
} updated because there were no changes.`;
}

if (dryRun) {
return `🎭 dry run! This will update '${slug}' with contents from ${filepath} with the following metadata: ${JSON.stringify(
matter.data
)}`;
}

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

return 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`);
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;
});
};