-
Notifications
You must be signed in to change notification settings - Fork 43
/
syncDocsPath.ts
215 lines (196 loc) · 6.5 KB
/
syncDocsPath.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import fs from 'fs/promises';
import path from 'path';
import chalk from 'chalk';
import config from 'config';
import { Headers } from 'node-fetch';
import APIError from './apiError';
import Command, { CommandCategories } from './baseCommand';
import fetch, { cleanHeaders, handleRes } from './fetch';
import { debug } from './logger';
import readdirRecursive from './readdirRecursive';
import readDoc from './readDoc';
/**
* Reads the contents of the specified Markdown or HTML file
* and creates/updates the corresponding doc in ReadMe
*
* @param key the project API key
* @param selectedVersion the project version
* @param dryRun boolean indicating dry run mode
* @param filepath path to file
* @param type module within ReadMe to update (e.g. docs, changelogs, etc.)
* @returns A promise-wrapped string with the result
*/
async function pushDoc(
key: string,
selectedVersion: string,
dryRun: boolean,
filepath: string,
type: CommandCategories
) {
const { content, data, hash, slug } = readDoc(filepath);
// TODO: ideally we should offer a zero-configuration approach that doesn't
// require YAML front matter, but that will have to be a breaking change
if (!Object.keys(data).length) {
debug(`No front matter attributes found for ${filepath}, not syncing`);
return `⏭️ no front matter attributes found for ${filepath}, skipping`;
}
let payload: {
body?: string;
html?: string;
htmlmode?: boolean;
lastUpdatedHash: string;
} = { body: content, ...data, lastUpdatedHash: hash };
if (type === CommandCategories.CUSTOM_PAGES) {
if (filepath.endsWith('.html')) {
payload = { html: content, htmlmode: true, ...data, lastUpdatedHash: hash };
} else {
payload = { body: content, htmlmode: false, ...data, lastUpdatedHash: hash };
}
}
function createDoc() {
if (dryRun) {
return `🎭 dry run! This will create '${slug}' with contents from ${filepath} with the following metadata: ${JSON.stringify(
data
)}`;
}
return (
fetch(`${config.get('host')}/api/v1/${type}`, {
method: 'post',
headers: cleanHeaders(
key,
new Headers({
'x-readme-version': selectedVersion,
'Content-Type': 'application/json',
})
),
body: JSON.stringify({
slug,
...payload,
}),
})
.then(handleRes)
// eslint-disable-next-line no-underscore-dangle
.then(res => `🌱 successfully created '${res.slug}' (ID: ${res._id}) with contents from ${filepath}`)
);
}
function updateDoc(existingDoc: typeof payload) {
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(
data
)}`;
}
return fetch(`${config.get('host')}/api/v1/${type}/${slug}`, {
method: 'put',
headers: cleanHeaders(
key,
new Headers({
'x-readme-version': selectedVersion,
'Content-Type': 'application/json',
})
),
body: JSON.stringify(
Object.assign(existingDoc, {
...payload,
})
),
})
.then(handleRes)
.then(res => `✏️ successfully updated '${res.slug}' with contents from ${filepath}`);
}
return fetch(`${config.get('host')}/api/v1/${type}/${slug}`, {
method: 'get',
headers: cleanHeaders(
key,
new Headers({
'x-readme-version': selectedVersion,
Accept: 'application/json',
})
),
})
.then(async res => {
const body = await handleRes(res, false);
if (!res.ok) {
if (res.status !== 404) return Promise.reject(new APIError(body));
debug(`error retrieving data for ${slug}, creating doc`);
return createDoc();
}
debug(`data received for ${slug}, updating doc`);
return updateDoc(body);
})
.catch(err => {
// eslint-disable-next-line no-param-reassign
err.message = `Error uploading ${chalk.underline(filepath)}:\n\n${err.message}`;
throw err;
});
}
/**
* Takes a path (either to a directory of files or to a single file)
* and syncs those (either via POST or PUT) to ReadMe.
* @returns A promise-wrapped string with the results
*/
export default async function syncDocsPath(
/** Project API key */
key: string,
/** ReadMe project version */
selectedVersion: string,
/** module within ReadMe to update (e.g. docs, changelogs, etc.) */
cmdType: CommandCategories,
/** Example command usage, used in error message */
usage: string,
/** Path input, can either be a directory or a single file */
pathInput: string,
/** boolean indicating dry run mode */
dryRun: boolean,
/** array of allowed file extensions */
allowedFileExtensions = ['.markdown', '.md']
) {
if (!pathInput) {
return Promise.reject(new Error(`No path provided. Usage \`${config.get('cli')} ${usage}\`.`));
}
const stat = await fs.stat(pathInput).catch(err => {
if (err.code === 'ENOENT') {
throw new Error("Oops! We couldn't locate a file or directory at the path you provided.");
}
throw err;
});
let output: string;
if (stat.isDirectory()) {
// Filter out any files that don't match allowedFileExtensions
const files = readdirRecursive(pathInput).filter(file =>
allowedFileExtensions.includes(path.extname(file).toLowerCase())
);
Command.debug(`number of files: ${files.length}`);
if (!files.length) {
return Promise.reject(
new Error(
`The directory you provided (${pathInput}) doesn't contain any of the following required files: ${allowedFileExtensions.join(
', '
)}.`
)
);
}
output = (
await Promise.all(
files.map(async filename => {
return pushDoc(key, selectedVersion, dryRun, filename, cmdType);
})
)
).join('\n');
} else {
const fileExtension = path.extname(pathInput).toLowerCase();
if (!allowedFileExtensions.includes(fileExtension)) {
return Promise.reject(
new Error(
`Invalid file extension (${fileExtension}). Must be one of the following: ${allowedFileExtensions.join(', ')}`
)
);
}
output = await pushDoc(key, selectedVersion, dryRun, pathInput, cmdType);
}
return Promise.resolve(chalk.green(output));
}