@tryghost/mg-fs-utils 0.7.12

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2013-2021 Ghost Foundation
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # Migrate Fs Utils
2
+
3
+ ## Install
4
+
5
+ `npm install @tryghost/mg-fs-utils --save`
6
+
7
+ or
8
+
9
+ `yarn add @tryghost/mg-fs-utils`
10
+
11
+
12
+ ## Usage
13
+
14
+
15
+ ## Develop
16
+
17
+ This is a mono repository, managed with [lerna](https://lernajs.io/).
18
+
19
+ Follow the instructions for the top-level repo.
20
+ 1. `git clone` this repo & `cd` into it as usual
21
+ 2. Run `yarn` to install top-level dependencies.
22
+
23
+
24
+ ## Run
25
+
26
+ - `yarn dev`
27
+
28
+
29
+ ## Test
30
+
31
+ - `yarn lint` run just eslint
32
+ - `yarn test` run lint and tests
33
+
34
+
35
+
36
+
37
+ # Copyright & License
38
+
39
+ Copyright (c) 2013-2021 Ghost Foundation - Released under the [MIT license](LICENSE).
package/index.js ADDED
@@ -0,0 +1,4 @@
1
+ module.exports.FileCache = require('./lib/FileCache');
2
+ module.exports.zip = require('./lib/zip');
3
+ module.exports.ghostJSON = require('./lib/ghostJSON');
4
+ module.exports.csv = require('./lib/csv');
@@ -0,0 +1,309 @@
1
+ const _ = require('lodash');
2
+ const fs = require('fs-extra');
3
+ const path = require('path');
4
+ const crypto = require('crypto');
5
+ const os = require('os');
6
+ const imageTransform = require('@tryghost/image-transform');
7
+ const errors = require('@tryghost/errors');
8
+
9
+ const basePath = 'mg';
10
+ const knownExtensions = ['.jpg', '.jpeg', '.gif', '.png', '.svg', '.svgz', '.ico', 'webp'];
11
+
12
+ class FileCache {
13
+ constructor(cacheName, options = {}) {
14
+ this.originalName = cacheName;
15
+ this.options = Object.assign({contentDir: true}, options);
16
+
17
+ // Remove any extension, handles removing TLDs as well if the name is based on a URL
18
+ let ext = path.extname(cacheName);
19
+ this.cacheName = path.basename(cacheName, ext);
20
+
21
+ if (options.batchName) {
22
+ this.batchName = options.batchName;
23
+ }
24
+ }
25
+
26
+ get cacheBaseDir() {
27
+ return path.join(os.tmpdir(), basePath);
28
+ }
29
+
30
+ get cacheKey() {
31
+ if (!this._cacheKey) {
32
+ // Unique hash based on full zip path + the original filename
33
+ this._cacheKey = `${crypto.createHash('md5').update(this.originalName).digest('hex')}-${this.cacheName}`;
34
+ }
35
+ return this._cacheKey;
36
+ }
37
+
38
+ /**
39
+ * Cache Dir
40
+ * We maintain a folder structure like:
41
+ * /mg/<hash>
42
+ * - /tmp
43
+ * - temporary backup files
44
+ * - /zip
45
+ * - json file
46
+ * - /content/images
47
+ * - image files
48
+ */
49
+ get cacheDir() {
50
+ if (!this._cacheDir) {
51
+ this._cacheDir = path.join(os.tmpdir(), basePath, this.cacheKey);
52
+ fs.mkdirpSync(path.join(this.tmpDir));
53
+
54
+ // don't create the content directory when migrating members
55
+ if (this.options && this.options.contentDir) {
56
+ fs.mkdirpSync(path.join(this.imageDir));
57
+ } else {
58
+ fs.mkdirpSync(path.join(this.zipDir));
59
+ }
60
+ }
61
+ return this._cacheDir;
62
+ }
63
+
64
+ get tmpDir() {
65
+ return path.join(this.cacheDir, 'tmp');
66
+ }
67
+
68
+ get zipDir() {
69
+ return path.join(this.cacheDir, 'zip');
70
+ }
71
+
72
+ get jsonDir() {
73
+ return this.zipDir;
74
+ }
75
+
76
+ get imagePath() {
77
+ return path.join('content', 'images');
78
+ }
79
+
80
+ get imageDir() {
81
+ return path.join(this.zipDir, this.imagePath);
82
+ }
83
+
84
+ get defaultCacheFileName() {
85
+ if (this.batchName) {
86
+ return `gh-${this.cacheName}-batch-${this.batchName}-${Date.now()}`;
87
+ }
88
+ return `gh-${this.cacheName}-${Date.now()}`;
89
+ }
90
+
91
+ get defaultTmpJSONFileName() {
92
+ return `${this.defaultCacheFileName}.json`;
93
+ }
94
+
95
+ get defaultTmpCSVFileName() {
96
+ return `${this.defaultCacheFileName}.csv`;
97
+ }
98
+
99
+ get defaultZipFileName() {
100
+ return `${this.defaultCacheFileName}.zip`;
101
+ }
102
+
103
+ get defaultErrorFileName() {
104
+ return `${this.defaultCacheFileName}.errors.json`;
105
+ }
106
+
107
+ // @TODO: move this somewhere shared,
108
+ // it's currently duplicated from https://github.com/TryGhost/Ghost-Storage-Base/blob/master/BaseStorage.js#L62
109
+ sanitizeFileName(src) {
110
+ let basename;
111
+
112
+ // remove unsupported characters from the dir name first
113
+ src = src.replace(src, this.sanitizeDirName(src));
114
+
115
+ basename = path.basename(src);
116
+ // below only matches ascii characters, @, and .
117
+ // unicode filenames like город.zip would therefore resolve to ----.zip
118
+ return src.replace(basename, basename.replace(/[^\w@.]/gi, '-'));
119
+ }
120
+
121
+ sanitizeDirName(src) {
122
+ // Slighly different regex from sanitizing the filename, as we still want to
123
+ // support characters like `/`, `_`, and `-`
124
+ return src.replace(/[^\w@./-_]/gi, '-');
125
+ }
126
+
127
+ resolveImageFileName(filename) {
128
+ let ext = path.extname(filename);
129
+
130
+ // remove the base imagePath if it already exists in the path, so we don't get nested imagePath directories
131
+ filename = filename.replace(`/${this.imagePath}`, '');
132
+
133
+ // replace the basename part with a sanitized version
134
+ filename = filename.replace(filename, this.sanitizeFileName(filename));
135
+
136
+ // @TODO: use content type on request to infer this, rather than assuming jpeg?
137
+ if (!_.includes(knownExtensions, ext)) {
138
+ if (!ext) {
139
+ filename += '.jpeg';
140
+ } else {
141
+ filename.replace(ext, '.jpeg');
142
+ }
143
+ }
144
+
145
+ return {
146
+ filename: filename,
147
+ storagePath: path.join(this.imageDir, filename),
148
+ outputPath: path.join('/', this.imagePath, filename)
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Create a file to store temporary data
154
+ *
155
+ * @param {Object} data - a valid Ghost JSON object or data to store
156
+ * @param {String} filename - name of file to write
157
+ * @param {Boolean} isJSON - defaults to write a JSON file
158
+ */
159
+ async writeTmpFile(data, filename, isJSON = true) {
160
+ let filepath = path.join(this.tmpDir, filename);
161
+
162
+ if (isJSON) {
163
+ await fs.outputJson(filepath, data, {spaces: 2});
164
+ } else {
165
+ await fs.writeFile(filepath, data);
166
+ }
167
+
168
+ return filepath;
169
+ }
170
+
171
+ /**
172
+ * Read a JSON file containing temporary data
173
+ *
174
+ * @param {String} filename - name of file to read
175
+ */
176
+ async readTmpJSONFile(filename) {
177
+ let filepath = path.join(this.tmpDir, filename);
178
+
179
+ return await fs.readJson(filepath);
180
+ }
181
+
182
+ /**
183
+ * Create a CSV or JSON file with our processed data
184
+ *
185
+ * @param {Object} data - a valid Ghost JSON object or CSV Members data
186
+ * @param {Object} options - config
187
+ */
188
+ async writeGhostImportFile(data, options = {}) {
189
+ options = Object.assign({isJSON: true}, options);
190
+ const {isJSON} = options;
191
+
192
+ // Create a temporary version first
193
+ let filename = options.tmpFilename
194
+ || (isJSON ? this.defaultTmpJSONFileName : this.defaultTmpCSVFileName);
195
+
196
+ await this.writeTmpFile(data, filename, isJSON);
197
+
198
+ // Then also write it as "the" JSON file in the zip folder
199
+ filename = options.filename || `ghost-import.json`;
200
+ let basepath = options.path ? path.dirname(options.path) : this.zipDir;
201
+ let filepath = path.join(basepath, filename);
202
+
203
+ if (isJSON) {
204
+ await fs.outputJson(filepath, data, {spaces: 2});
205
+ } else {
206
+ await fs.writeFile(filepath, data);
207
+ }
208
+
209
+ return filepath;
210
+ }
211
+
212
+ /**
213
+ * Create a JSON file with our errors
214
+ *
215
+ * @param {Object} data - a valid JSON object containing errors
216
+ * @param {Object} options - config
217
+ */
218
+ async writeErrorJSONFile(data, options = {}) {
219
+ const filename = options.filename || this.defaultErrorFileName;
220
+
221
+ return await this.writeTmpFile(data, filename);
222
+ }
223
+
224
+ /**
225
+ * Create a binary image file with fetched data
226
+ *
227
+ * @param {String} data - a valid binary image
228
+ * @param {Object} options - a resolved file name
229
+ */
230
+ async writeImageFile(data, options) {
231
+ if (!options.storagePath || !options.outputPath) {
232
+ options = this.resolveImageFileName(options.filename);
233
+ }
234
+
235
+ // CASE: image manipulator is uncapable of transforming file (e.g. .gif)
236
+ let fileExt = path.parse(options.filename).ext;
237
+ if (options.optimize && imageTransform.canTransformFileExtension(fileExt)) {
238
+ const optimizedStoragePath = options.storagePath;
239
+ const originalStoragePath = imageTransform.generateOriginalImageName(options.storagePath);
240
+ const optimizedData = await imageTransform.resizeFromBuffer(data, {width: 2000});
241
+
242
+ await fs.outputFile(optimizedStoragePath, optimizedData);
243
+ await fs.outputFile(originalStoragePath, data);
244
+ } else {
245
+ await fs.outputFile(options.storagePath, data);
246
+ }
247
+
248
+ return options.outputPath;
249
+ }
250
+
251
+ /**
252
+ * Check if we've got this file already
253
+ *
254
+ * @param {String} filename
255
+ * @param {String} type - one of tmp, json, image
256
+ */
257
+ hasFile(filename, type) {
258
+ let pathToCheck = filename;
259
+
260
+ if (type && !_.includes(['tmp', 'json', 'image'], type)) {
261
+ throw new errors.GhostError({message: 'Unknown file type'});
262
+ } else if (type) {
263
+ pathToCheck = path.join(this[`${type}Dir`], filename);
264
+ }
265
+
266
+ return fs.existsSync(pathToCheck);
267
+ }
268
+
269
+ /**
270
+ * Empties the local cache directory
271
+ */
272
+ async emptyCacheDir() {
273
+ const directory = this.cacheBaseDir + '/';
274
+
275
+ fs.existsSync(directory, (err) => {
276
+ if (err) {
277
+ throw err;
278
+ }
279
+ return true;
280
+ });
281
+
282
+ let itemsToDelete = [];
283
+ const dirContents = fs.readdirSync(directory).map((fileName) => {
284
+ return path.join(directory, fileName);
285
+ });
286
+
287
+ dirContents.forEach((item) => {
288
+ if (fs.lstatSync(item).isDirectory()) {
289
+ itemsToDelete.push(item);
290
+ }
291
+ });
292
+
293
+ itemsToDelete.forEach((item) => {
294
+ fs.rmdir(item, {recursive: true}, (err) => {
295
+ if (err) {
296
+ throw err;
297
+ }
298
+ return true;
299
+ });
300
+ });
301
+
302
+ return {
303
+ directory: directory,
304
+ files: itemsToDelete
305
+ };
306
+ }
307
+ }
308
+
309
+ module.exports = FileCache;
package/lib/csv.js ADDED
@@ -0,0 +1,67 @@
1
+ const parse = require('csv-parse');
2
+ const fs = require('fs-extra');
3
+ const {isDate} = require('date-fns');
4
+
5
+ /**
6
+ * Parse a CSV file and make available as JSON
7
+ * @param {String} filePath - name of file to write
8
+ * @param {Object} options - optional options to pass to `csv-parse`
9
+ */
10
+ module.exports.parse = (filePath, options = {skip_lines_with_error: true, columns: true, skip_empty_lines: true}) => {
11
+ const parser = parse(options);
12
+ const data = [];
13
+ return new Promise((resolve, reject) => {
14
+ const fileStream = fs.createReadStream(filePath);
15
+ fileStream
16
+ .pipe(parser)
17
+ .on('data', async (row) => {
18
+ data.push(row);
19
+ }).on('end', () => {
20
+ return resolve(data);
21
+ }).on('error', (error) => {
22
+ return reject(error);
23
+ });
24
+ });
25
+ };
26
+
27
+ /**
28
+ * Convert a JSON file into a CSV format
29
+ * @param {Array} data - the data to format
30
+ * @param {Array} fields - the fields to pick and use as column header
31
+ */
32
+ module.exports.jsonToCSV = (data, fields = Object.keys(data[0])) => {
33
+ let csv = `${fields.join(',')}\r\n`;
34
+ let entry;
35
+ let field;
36
+ let j;
37
+ let i;
38
+
39
+ for (j = 0; j < data.length; j = j + 1) {
40
+ entry = data[j];
41
+
42
+ for (i = 0; i < fields.length; i = i + 1) {
43
+ field = fields[i];
44
+
45
+ let fieldToAdd;
46
+
47
+ if (entry[field] !== null) {
48
+ if (isDate(entry[field])) {
49
+ fieldToAdd = entry[field].toISOString();
50
+ } else {
51
+ fieldToAdd = entry[field];
52
+ }
53
+ } else {
54
+ fieldToAdd = '';
55
+ }
56
+
57
+ csv += fieldToAdd !== undefined ? fieldToAdd : '';
58
+ if (i !== fields.length - 1) {
59
+ csv += ',';
60
+ }
61
+ }
62
+ csv += '\r\n';
63
+ }
64
+
65
+ return csv;
66
+ };
67
+
@@ -0,0 +1,15 @@
1
+ const fs = require('fs-extra');
2
+
3
+ /**
4
+ * Read a JSON file containing Ghost JSON data
5
+ *
6
+ * @TODO: validate the path
7
+ * @TODO: validate that we have a genuine Ghost JSON file
8
+ * Right now this is the simplest version and so looks a bit weird in a file on it's own
9
+ * but it will make more sense when there is validation in here.
10
+ *
11
+ * @param {String} jsonPath - name of file to read
12
+ */
13
+ module.exports.read = async (jsonPath) => {
14
+ return await fs.readJson(jsonPath);
15
+ };
package/lib/zip.js ADDED
@@ -0,0 +1,50 @@
1
+ const AdmZip = require('adm-zip');
2
+ const {compress} = require('@tryghost/zip');
3
+ const path = require('path');
4
+ const _private = {};
5
+ const errors = require('@tryghost/errors');
6
+
7
+ _private.openZipForRead = (zipPath) => {
8
+ return AdmZip(zipPath);
9
+ };
10
+
11
+ /**
12
+ * Read a Zip File
13
+ * - Flattens the structure if there's one top-level directory, so we only get the files inside
14
+ * @TODO: Refactor to use @tryghost/zip to extract zip files and drop adm-zip dependency
15
+ */
16
+ module.exports.read = (zipPath, callback) => {
17
+ let zip;
18
+ try {
19
+ zip = _private.openZipForRead(zipPath);
20
+ } catch (error) {
21
+ throw new errors.GhostError({message: `Unable to read zip file ${zipPath}: ${error}`});
22
+ }
23
+
24
+ // Entries is cleaned first
25
+ let entries = zip.getEntries().filter((entry) => {
26
+ return !(entry.entryName.match(/^__MACOSX/) || entry.entryName.match(/\.DS_Store$/));
27
+ });
28
+ // If the first entry is a directory, and every entry starts with the same directory, we have a top level directory
29
+ let firstEntry = entries[0];
30
+ let hasTopLevelDir = firstEntry.isDirectory && entries.every(x => x.entryName.startsWith(firstEntry.entryName));
31
+
32
+ // If we have a topLevelDirectory, remove it
33
+ if (hasTopLevelDir) {
34
+ entries.shift();
35
+ }
36
+
37
+ entries.forEach((zipEntry) => {
38
+ // If we have a topLevelDirectory, remove reference to it from the entry name
39
+ let entryName = hasTopLevelDir ? zipEntry.entryName.replace(firstEntry.entryName, '') : zipEntry.entryName;
40
+ callback(entryName, zipEntry);
41
+ });
42
+ };
43
+
44
+ module.exports.write = (zipPath, contentFolder, fileName) => {
45
+ const outputPath = path.join(zipPath, fileName || `ghost-import-${Date.now()}.zip`);
46
+
47
+ return compress(contentFolder, outputPath);
48
+ };
49
+
50
+ module.exports._private = _private;
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@tryghost/mg-fs-utils",
3
+ "version": "0.7.12",
4
+ "repository": "https://github.com/TryGhost/migrate/tree/master/packages/mg-fs-utils",
5
+ "author": "Ghost Foundation",
6
+ "license": "MIT",
7
+ "main": "index.js",
8
+ "scripts": {
9
+ "dev": "echo \"Implement me!\"",
10
+ "test": "NODE_ENV=testing mocha './test/**/*.test.js'",
11
+ "lint": "eslint . --ext .js --cache",
12
+ "posttest": "yarn lint"
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "lib"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "dependencies": {
22
+ "@tryghost/errors": "^0.2.13",
23
+ "@tryghost/image-transform": "1.0.14",
24
+ "@tryghost/zip": "1.1.15",
25
+ "adm-zip": "0.5.6",
26
+ "csv-parse": "4.16.3",
27
+ "date-fns": "2.24.0",
28
+ "fs-extra": "10.0.0",
29
+ "lodash": "4.17.21",
30
+ "sharp": "0.29.1"
31
+ },
32
+ "gitHead": "85e549003415ecdf4fd6b2a0df075db20cafe531"
33
+ }