@tryghost/mg-jekyll-export 0.1.3 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,6 +28,16 @@ To run a Jekyll migration, the required command is:
28
28
  migrate jekyll <path to zip file>
29
29
  ```
30
30
 
31
+ The `<path to zip file>` value should be the location of a zip file that has a structure like:
32
+
33
+ ```
34
+ _posts/
35
+ ├── 2020-10-27-my-post.md
36
+ ├── 2021-05-19-another-post.markdown
37
+ └── 2022-06-03-newest-post.html
38
+ _drafts/
39
+ └── 2022-06-03-some-draft.md
40
+ ```
31
41
  It's possible to pass more options, in order to achieve a better migration file for Ghost:
32
42
 
33
43
  - **`-V` `--verbose`**
@@ -51,7 +61,8 @@ It's possible to pass more options, in order to achieve a better migration file
51
61
  - Provide an email domain for users e.g. example.com
52
62
  - **`--addTags`**
53
63
  - string - default: `null`
54
- - Provide one or more tag names which should be added to every post in this migration
64
+ - Provide one or more tag names which should be added to every post in this migration.
65
+ This is addition to a '#jekyll' tag, which is always added.
55
66
  - **`--datedPermalinks`**
56
67
  - Set the dated permalink structure
57
68
  - string - default: `none`
@@ -1,27 +1,29 @@
1
- const MarkdownIt = require('markdown-it');
2
- const md = new MarkdownIt({
3
- html: true
4
- });
5
- const fm = require('front-matter');
6
1
  const $ = require('cheerio');
7
2
 
8
- module.exports = (markdown, options = {}) => {
9
- const frontmatter = fm(markdown);
10
- const processedMarkdown = md.render(frontmatter.body);
11
- const $html = $.load(processedMarkdown, {
3
+ /*
4
+ Process the HTML of a single Jekyll Post.
5
+
6
+ Receives raw HTML, returns processed HTML
7
+ */
8
+
9
+ module.exports = (rawHtml, options = {}) => {
10
+ const $html = $.load(rawHtml, {
12
11
  decodeEntities: false
13
12
  });
14
13
 
15
14
  // Convert relative links and image paths to absolute
16
15
  if (options.url) {
17
16
  const urlData = new URL(options.url);
18
- const urlOrigin = urlData.href;
17
+ // The "origin" the URL truncated to the domain.
18
+ // The difference between the "href" matters for blogs that were hosted
19
+ // in sub-directories so that relative and relative-to-root URLs resolve correctly.
20
+ const urlOrigin = urlData.origin;
19
21
 
20
22
  $html('a').each((i, anchor) => {
21
23
  const thisURL = $(anchor).attr('href');
22
24
 
23
25
  // If it starts with a slash, append the base URL
24
- if (thisURL.indexOf('/') === 0) {
26
+ if (thisURL && thisURL.indexOf('/') === 0) {
25
27
  const updatedURL = `${urlOrigin.replace(/^\/|\/$/g, '')}/${thisURL.replace(/^\/|\/$/g, '')}`;
26
28
  $(anchor).attr('href', updatedURL);
27
29
  }
@@ -31,7 +33,7 @@ module.exports = (markdown, options = {}) => {
31
33
  const thisSrc = $(img).attr('src');
32
34
 
33
35
  // If it starts with a slash, append the base URL
34
- if (thisSrc.indexOf('/') === 0) {
36
+ if (thisSrc && thisSrc.indexOf('/') === 0) {
35
37
  const updatedURL = `${urlOrigin.replace(/^\/|\/$/g, '')}/${thisSrc.replace(/^\/|\/$/g, '')}`;
36
38
  $(img).attr('src', updatedURL);
37
39
  }
@@ -1,11 +1,39 @@
1
+ const MarkdownIt = require('markdown-it');
2
+ const md = new MarkdownIt({
3
+ html: true
4
+ });
1
5
  const string = require('@tryghost/string');
6
+ const errors = require('@tryghost/errors');
2
7
  const fm = require('front-matter');
3
- const processContent = require('./process-content');
8
+ const processHtml = require('./process-html');
4
9
 
5
- const processMeta = (fileName, markdown, options) => {
6
- const isDraft = fileName.startsWith('drafts/');
10
+ // The frontmatter date may be a Date object or a string
11
+ function _parseFrontMatterDate(fmDate) {
12
+ let postDate;
13
+ // The date was unquoted in the frontmatter, it gets parsed into a data object
14
+ if (typeof fmDate === 'object') {
15
+ postDate = fmDate;
16
+ // Otherwise the date gets parsed as a string
17
+ } else {
18
+ const frontMaterDateRegex = new RegExp('([0-9]{4})[-:/\\ ]([0-9]{2})[-:/\\ ]([0-9]{2})');
19
+
20
+ const dateParts = fmDate.match(frontMaterDateRegex);
21
+ postDate = new Date(Date.UTC(dateParts[1], (dateParts[2] - 1), dateParts[3])); // Months are zero-index, so 11 equals December
22
+ }
23
+
24
+ return postDate;
25
+ }
26
+
27
+ /*
28
+ Process both the frontmatter metadata and content of a single Jekyll Markdown post.
29
+
30
+ The body may be in Markdown or HTML.
31
+ */
7
32
 
8
- let frontmatter = fm(markdown);
33
+ const processMeta = (fileName, fileContents, options) => {
34
+ const inDraftsDir = fileName.startsWith('_drafts/');
35
+
36
+ let frontmatter = fm(fileContents);
9
37
  let frontmatterAttributes = frontmatter.attributes;
10
38
 
11
39
  let postDate = false;
@@ -17,23 +45,29 @@ const processMeta = (fileName, markdown, options) => {
17
45
  // Get an ISO 8601 date
18
46
  const dateNow = new Date().toISOString();
19
47
 
20
- if (isDraft) {
21
- const slugRegex = new RegExp('(drafts/)(.*).md');
22
- slugParts = fileName.match(slugRegex);
23
- postSlug = slugParts[2];
24
- } else if (frontmatterAttributes.date) {
25
- const frontMaterDateRegex = new RegExp('([0-9]{4})[-:/\\ ]([0-9]{2})[-:/\\ ]([0-9]{2})');
26
- const dateParts = frontmatterAttributes.date.match(frontMaterDateRegex);
27
- postDate = new Date(Date.UTC(dateParts[1], (dateParts[2] - 1), dateParts[3], 12, 0, 0)); // Months are zero-index, so 12 equals December
48
+ // If `basename` is supposed in the frontmatter, use that as the `slug`
49
+ if (frontmatterAttributes.basename) {
50
+ postSlug = frontmatterAttributes.basename;
51
+ }
28
52
 
29
- const slugRegex = new RegExp('([0-9a-zA-Z-_]+)/(.*).md');
53
+ if (inDraftsDir && !postSlug) {
54
+ // Posts in _drafts don't have a date in the filename
55
+ const slugRegex = new RegExp('(_drafts/)(.*).(md|markdown|html)');
30
56
  slugParts = fileName.match(slugRegex);
31
57
  postSlug = slugParts[2];
58
+ } else if (!inDraftsDir && frontmatterAttributes.date) {
59
+ postDate = _parseFrontMatterDate(frontmatterAttributes.date);
60
+ if (!postSlug) {
61
+ const slugRegex = new RegExp('([0-9a-zA-Z-_]+)/(.*).(md|markdown|html)');
62
+ slugParts = fileName.match(slugRegex);
63
+ postSlug = slugParts[2];
64
+ }
65
+ // If it's a post with no `date` frontmatter
32
66
  } else {
33
- const datedSlugRegex = new RegExp('([0-9a-zA-Z-_]+)/([0-9]{4}-[0-9]{1,2}-[0-9]{1,2})-(.*).md');
67
+ const datedSlugRegex = new RegExp('([0-9a-zA-Z-_]+)/([0-9]{4}-[0-9]{1,2}-[0-9]{1,2})-(.*).(md|markdown|html)');
34
68
  slugParts = fileName.match(datedSlugRegex);
35
69
 
36
- if (slugParts[1] !== 'posts') {
70
+ if (slugParts[1] !== '_posts') {
37
71
  postType = slugParts[1];
38
72
  nonStandardPostType = true;
39
73
  }
@@ -42,8 +76,10 @@ const processMeta = (fileName, markdown, options) => {
42
76
  const dateYear = slugParts[2].split(/[-/]/)[0];
43
77
  const dateMonth = ('0' + slugParts[2].split(/[-/]/)[1]).slice(-2);
44
78
  const dateDay = ('0' + slugParts[2].split(/[-/]/)[2]).slice(-2);
45
- postDate = new Date(Date.UTC(dateYear, (dateMonth - 1), dateDay, 12, 0, 0)); // Months are zero-index, so 12 equals December
46
- postSlug = slugParts[3];
79
+ postDate = new Date(Date.UTC(dateYear, (dateMonth - 1), dateDay)); // Months are zero-index, so 11 equals December
80
+ if (!postSlug) {
81
+ postSlug = slugParts[3];
82
+ }
47
83
  }
48
84
 
49
85
  const post = {
@@ -53,6 +89,11 @@ const processMeta = (fileName, markdown, options) => {
53
89
  }
54
90
  };
55
91
 
92
+ const isDraft = (inDraftsDir || frontmatterAttributes.published === false);
93
+
94
+ // This will be processed more later and deleted
95
+ post._body = frontmatter.body;
96
+
56
97
  post.data.status = 'published';
57
98
  post.data.created_at = postDate || dateNow;
58
99
  post.data.published_at = postDate || dateNow;
@@ -69,7 +110,7 @@ const processMeta = (fileName, markdown, options) => {
69
110
  post.data.author = {
70
111
  url: string.slugify(frontmatterAttributes.author),
71
112
  data: {
72
- email: `${string.slugify(frontmatterAttributes.author)}@${(options.email) ? options.email : 'dummyemail.com'}`,
113
+ email: `${string.slugify(frontmatterAttributes.author)}@${(options.email) ? options.email : 'example.com'}`,
73
114
  name: frontmatterAttributes.author,
74
115
  slug: string.slugify(frontmatterAttributes.author),
75
116
  roles: [
@@ -79,16 +120,79 @@ const processMeta = (fileName, markdown, options) => {
79
120
  };
80
121
  }
81
122
 
82
- // Add post-specific tags
123
+ // Add tags ^ categories from front matter
124
+ // `tag` & `category` are interpreted as a single item
125
+ // `tags` & `categories` are interpreted as a list of items
126
+ // `category` and `categories` are processed first so that they become the "primary tag"
83
127
  post.data.tags = [];
84
128
 
129
+ if (frontmatterAttributes.category) {
130
+ post.data.tags.push({
131
+ url: `migrator-added-tag-category-${string.slugify(frontmatterAttributes.category)}`,
132
+ data: {
133
+ name: frontmatterAttributes.category,
134
+ slug: `category-${string.slugify(frontmatterAttributes.category)}`
135
+ }
136
+ });
137
+ }
138
+
139
+ if (frontmatterAttributes.categories) {
140
+ // Jekyll allows tags to be space separated or a YAML list. We support both cases.
141
+ let normalizedCats;
142
+ if (typeof frontmatterAttributes.categories === 'object') {
143
+ normalizedCats = frontmatterAttributes.categories;
144
+ } else {
145
+ normalizedCats = frontmatterAttributes.categories.split(' ');
146
+ }
147
+
148
+ normalizedCats.forEach((tag) => {
149
+ post.data.tags.push({
150
+ url: `migrator-added-tag-category-${string.slugify(tag)}`,
151
+ data: {
152
+ name: tag,
153
+ slug: `category-${string.slugify(tag)}`
154
+ }
155
+ });
156
+ });
157
+ }
158
+
159
+ if (frontmatterAttributes.tag) {
160
+ post.data.tags.push({
161
+ url: `migrator-added-tag-${string.slugify(frontmatterAttributes.tag)}`,
162
+ data: {
163
+ name: frontmatterAttributes.tag,
164
+ slug: string.slugify(frontmatterAttributes.tag)
165
+ }
166
+ });
167
+ }
168
+
169
+ if (frontmatterAttributes.tags) {
170
+ // Jekyll allows tags to be space separated or a YAML list. We support both cases.
171
+ let normalizedTags;
172
+ if (typeof frontmatterAttributes.tags === 'object') {
173
+ normalizedTags = frontmatterAttributes.tags;
174
+ } else {
175
+ normalizedTags = frontmatterAttributes.tags.split(' ');
176
+ }
177
+
178
+ normalizedTags.forEach((tag) => {
179
+ post.data.tags.push({
180
+ url: `migrator-added-tag-${string.slugify(tag)}`,
181
+ data: {
182
+ name: tag,
183
+ slug: string.slugify(tag)
184
+ }
185
+ });
186
+ });
187
+ }
188
+
189
+ // Add post-specific tags
85
190
  if (nonStandardPostType) {
86
- let typeTagSlug = `hash-${string.slugify(postType)}`;
87
191
  post.data.tags.push({
88
- url: `migrator-added-tag-${typeTagSlug}`,
192
+ url: `migrator-added-tag-hash-${string.slugify(postType)}`,
89
193
  data: {
90
194
  name: `#${postType}`,
91
- slug: typeTagSlug
195
+ slug: `hash-${string.slugify(postType)}`
92
196
  }
93
197
  });
94
198
  }
@@ -96,11 +200,30 @@ const processMeta = (fileName, markdown, options) => {
96
200
  return post;
97
201
  };
98
202
 
99
- module.exports = (fileName, markdown, globalUser = false, options = {}) => {
100
- const post = processMeta(fileName, markdown, options);
203
+ module.exports = (fileName, fileContents, globalUser = false, options = {}) => {
204
+ const post = processMeta(fileName, fileContents, options);
205
+
206
+ // The post body may be in Markdown or HTML.
207
+ // If it's in Markdown, convert the Markdown to HTML
208
+ const htmlRegex = new RegExp('.*.html$');
209
+ const markdownRegex = new RegExp('.*.(md|markdown)$');
210
+ const isHtml = fileName.match(htmlRegex);
211
+ const isMarkdown = fileName.match(markdownRegex);
212
+ let rawHtml;
213
+ if (isHtml) {
214
+ rawHtml = post._body;
215
+ } else if (isMarkdown) {
216
+ rawHtml = md.render(post._body);
217
+ } else {
218
+ throw new errors.InternalServerError({
219
+ message: 'Unrecognized file extension. Only .md, .markdown and .html are supported'
220
+ });
221
+ }
222
+ // Now we are done with this temporary attribute
223
+ delete post._body;
101
224
 
102
- // Process content
103
- post.data.html = processContent(markdown, options);
225
+ // Clean up the HTML
226
+ post.data.html = processHtml(rawHtml, options);
104
227
 
105
228
  // Process author
106
229
  if (!post.data.author) {
package/lib/process.js CHANGED
@@ -4,11 +4,11 @@ module.exports = (input, options = {}) => {
4
4
  let output = {};
5
5
 
6
6
  let globalUser = {
7
- url: `/author/dummyuser`,
7
+ url: `/author/exampleuser`,
8
8
  data: {
9
- email: `dummyuser@dummyemail.com`,
10
- name: 'Dummy User',
11
- slug: 'dummyuser',
9
+ email: `exampleuser@example.com`,
10
+ name: 'Example User',
11
+ slug: 'exampleuser',
12
12
  roles: [
13
13
  'Contributor'
14
14
  ]
@@ -16,7 +16,7 @@ module.exports = (input, options = {}) => {
16
16
  };
17
17
 
18
18
  if (input.posts && input.posts.length > 0) {
19
- output.posts = input.posts.map(post => processPost(post.fileName, post.markdown, globalUser, options));
19
+ output.posts = input.posts.map(post => processPost(post.fileName, post.fileContents, globalUser, options));
20
20
  }
21
21
 
22
22
  return output;
package/lib/read-zip.js CHANGED
@@ -1,3 +1,4 @@
1
+ const errors = require('@tryghost/errors');
1
2
  const fsUtils = require('@tryghost/mg-fs-utils');
2
3
  const ui = require('@tryghost/pretty-cli').ui;
3
4
 
@@ -8,23 +9,26 @@ module.exports = (zipPath, options) => {
8
9
 
9
10
  let skippedFileCount = 0;
10
11
 
11
- // We only support the current Medium export file structure:
12
- // - posts
12
+ // We only support the current Jekyll export file structure:
13
+ // - _posts
13
14
  // - 2020-10-27-my-post.md
14
15
  // - 2021-05-19-2020-was-quite-a-year.md
15
-
16
+ // The file extension may be ".md", ".markdown" or ".html"
16
17
  fsUtils.zip.read(zipPath, (entryName, zipEntry) => {
17
- // Catch all HTML files inside `profile/`
18
- if (/^posts\/.*\.md$/.test(entryName)) {
18
+ // The `entryName` arg here lacks the directory name.
19
+ // We need zipEntry.entryName instead, which contains it.
20
+ entryName = zipEntry.entryName;
21
+
22
+ if (/^_(posts|drafts)\/.*\.(md|markdown|html)$/.test(entryName)) {
19
23
  content.posts.push({
20
24
  fileName: entryName,
21
- markdown: zipEntry.getData().toString('utf8')
25
+ fileContents: zipEntry.getData().toString('utf8')
22
26
  });
23
27
 
24
28
  // Skip if not matched above, and report skipped files if `--verbose`
25
29
  } else {
26
30
  if (options.verbose) {
27
- ui.log.info('Skipped: ' + entryName);
31
+ ui.log.info('Skipped: ' + zipEntry.entryName);
28
32
  }
29
33
  skippedFileCount += 1;
30
34
  }
@@ -32,5 +36,10 @@ module.exports = (zipPath, options) => {
32
36
 
33
37
  ui.log.info('Skipped files: ' + skippedFileCount);
34
38
 
39
+ if (!content.posts.length) {
40
+ ui.log.error('No content found to import! Quitting.');
41
+ throw new errors.InternalServerError();
42
+ }
43
+
35
44
  return content;
36
45
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tryghost/mg-jekyll-export",
3
- "version": "0.1.3",
3
+ "version": "0.1.7",
4
4
  "description": "tbc",
5
5
  "repository": "https://github.com/TryGhost/migrate/tree/main/packages/mg-jekyll-export",
6
6
  "author": "Ghost Foundation",
@@ -20,16 +20,17 @@
20
20
  "access": "public"
21
21
  },
22
22
  "devDependencies": {
23
- "mocha": "9.2.2",
23
+ "mocha": "10.0.0",
24
24
  "should": "13.2.3",
25
- "sinon": "13.0.2"
25
+ "sinon": "14.0.0"
26
26
  },
27
27
  "dependencies": {
28
- "@tryghost/mg-fs-utils": "^0.8.0",
28
+ "@tryghost/errors": "^1.2.14",
29
+ "@tryghost/mg-fs-utils": "^0.9.0",
29
30
  "@tryghost/string": "^0.1.17",
30
31
  "cheerio": "0.22.0",
31
32
  "front-matter": "4.0.2",
32
- "markdown-it": "13.0.0"
33
+ "markdown-it": "13.0.1"
33
34
  },
34
- "gitHead": "0b3c4695d98527db9559444d81eaf9afcf2d1b6a"
35
+ "gitHead": "7f4422a89070611f2500548c14d286cccfd4c861"
35
36
  }