-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
337 lines (301 loc) · 8.53 KB
/
index.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import path from 'node:path';
import process from 'node:process';
import fs from 'fs-extra';
import {Args, Flags} from '@oclif/core';
import JSON5 from 'json5';
import YAML from 'yaml';
import TOML from '@ltd/j-toml';
// Removing the extension will make the built cli crash
import {
addExtension,
parseDataFile,
removeExtension,
updateMetadata,
} from '../../utils.js';
import {BaseCommandWithCompression} from '../../base-command-with-compression.js';
function parsePageRanges(pageRanges: string): string[] {
const splittedRanges = pageRanges.split(/,+/);
return splittedRanges.map((range) => range.trim().replaceAll(/[\s-]+/g, '-'));
}
export default class Process extends BaseCommandWithCompression {
static aliases = ['p'];
static description =
'Merge PDFs, extract pages and update metadata using simple file';
static examples = ['<%= config.bin %> <%= command.id %> data.json'];
static args = {
file: Args.string({
description: `Data file to process (JSON5 or YAML or TOML)
See: https://github.com/bader-nasser/pdftools/blob/main/test/docs/data.json (or .yaml or .toml)
Use / in the paths. On Windows, \\ can be changed to either / or \\\\`,
required: true,
}),
};
static flags = {
keep: Flags.boolean({
char: 'k',
description: `Keep output's name`,
}),
};
async run(): Promise<void> {
const {args, flags} = await this.parse(Process);
const {compress, 'dry-run': dryRun, silent, keep} = flags;
const {file} = args;
let isCompressing = compress;
let isDryRunning = dryRun;
let isSilencing = silent;
try {
const filePath = path.join(process.cwd(), file);
const fileDirname = path.dirname(filePath);
// credit:
// https://github.com/vercel/next.js/blob/962ce0dcee7993cedeb949c7f31ef34afc829578/packages/next/src/lib/find-config.ts#L53-L56
const fileContents = await fs.readFile(filePath, 'utf8');
let fileObject: JsonFileObject;
if (filePath.endsWith('.json') || filePath.endsWith('.json5')) {
fileObject = JSON5.parse<JsonFileObject>(fileContents);
} else if (filePath.endsWith('.yaml') || filePath.endsWith('.yml')) {
fileObject = YAML.parse(fileContents) as JsonFileObject;
} else if (filePath.endsWith('.toml')) {
fileObject = TOML.parse(fileContents) as JsonFileObject;
} else {
this.log('Supported formats are: JSON, YAML and TOML.');
this.log(
'Allowed extensions are: .json, .json5, .yaml, .yml and .toml.',
);
this.exit(1);
}
const {
output,
files,
compress: compressJson = false,
dryRun: dryRunJson = false,
silent: silentJson = false,
...meta
} = fileObject;
isCompressing = compress || compressJson;
isDryRunning = dryRun || dryRunJson;
isSilencing = silent || silentJson;
let relativeOutput = path.relative(
process.cwd(),
path.resolve(fileDirname, output),
);
const processedData: ProcessedDataType = {data: [], useShare: false};
let outerIndex = 0;
let innerIndex = 0;
for (const file of files) {
const fileHandle = `${String.fromCodePoint(
65 + outerIndex,
)}${String.fromCodePoint(65 + innerIndex)}`;
innerIndex += 1;
if (innerIndex > 25) {
innerIndex = 0;
outerIndex += 1;
}
let fileName = file as string;
const pageRanges: PageRanges = {all: [], shared: []};
if (typeof file === 'object') {
// @ts-expect-error Silence TS error!
const {name, pages, data} = file;
if (pages && data) {
console.log(file);
this.log(
'File object can NOT contain pages & data at the same time!',
);
this.exit(1);
}
if (pages ?? data) {
fileName = name;
if (pages) {
if (Array.isArray(pages)) {
for (const page of pages) {
const parsedPage = parsePageRanges(`${page}`);
pageRanges.all.push(...parsedPage);
}
} else {
// number or string
const parsedPage = parsePageRanges(`${pages}`);
pageRanges.all.push(...parsedPage);
}
} else {
const dataPath = path.resolve(fileDirname, `${data}`);
const parsedData = await parseDataFile(dataPath);
if (parsedData.error) {
throw new Error(`Error while parsing data file: ${dataPath}`);
}
if (parsedData.all) {
pageRanges.all.push(...parsedData.all);
}
if (parsedData.shared) {
processedData.useShare = true;
pageRanges.shared.push(...parsedData.shared);
}
}
} else {
console.log(file);
throw new Error(
'File object should have either pages or data attriute!',
);
}
}
fileName = path.relative(
process.cwd(),
path.resolve(fileDirname, fileName),
);
const fileData: FileData = {fileHandle, fileName, pageRanges};
// console.log(fileData)
processedData.data.push(fileData);
}
const {useShare, data} = processedData;
const handles = data.map(
({fileHandle, fileName}) => `${fileHandle}=${fileName}`,
);
const allRanges = data
.map(
({fileHandle, pageRanges}) =>
`${fileHandle}${pageRanges.all.join(' ' + fileHandle)}`,
)
.join(' ')
.split(' ');
relativeOutput = removeExtension(relativeOutput);
let relativeShareOutput = `${relativeOutput}-share`;
if (isCompressing && !keep) {
relativeOutput = `${relativeOutput}-compressed`;
relativeShareOutput = `${relativeShareOutput}-compressed`;
}
relativeOutput = addExtension(relativeOutput);
relativeShareOutput = addExtension(relativeShareOutput);
await this.ensureDirExists(relativeOutput);
if (useShare) {
this.logger(
`Output files: ${relativeOutput}, ${relativeShareOutput}`,
isSilencing,
);
} else {
this.logger(`Output files: ${relativeOutput}`, isSilencing);
}
this.logger(
`Creating ${relativeOutput} using file: ${file}...`,
isSilencing,
);
const args = [...handles, 'cat', ...allRanges, 'output', relativeOutput];
if (compress) {
args.push('compress');
}
await this.execute('pdftk', args, isDryRunning);
await updateMetadata({
filePath: relativeOutput,
meta,
dryRun: isDryRunning,
});
if (useShare) {
const outputShareStrings: string[] = [];
for (const {fileHandle, pageRanges} of data) {
let catString = `${fileHandle}`;
const ranges = [];
if (pageRanges.shared && pageRanges.shared.length > 0) {
ranges.push(...pageRanges.shared);
} else {
ranges.push(...pageRanges.all);
}
catString = `${catString}${ranges.join(' ' + fileHandle)}`;
outputShareStrings.push(catString);
}
const allShareRanges = outputShareStrings.join(' ').split(' ');
this.logger(
`Creating ${relativeShareOutput} using file: ${file}...`,
isSilencing,
);
const args = [
...handles,
'cat',
...allShareRanges,
'output',
relativeShareOutput,
];
if (compress) {
args.push('compress');
}
await this.execute('pdftk', args, isDryRunning);
await updateMetadata({
filePath: relativeShareOutput,
meta,
dryRun: isDryRunning,
});
}
} catch (error) {
console.error(error);
}
this.logger('Done.', isSilencing);
}
}
type PageRanges = {
all: string[];
shared: string[];
};
type FileData = {
fileHandle: string;
fileName: string;
pageRanges: PageRanges;
};
type ProcessedDataType = {
data: FileData[];
useShare: boolean;
};
type NumberOrString = number | string;
type InputFileObject =
| {
/**
* Name of input file.
*/
name: string;
/**
* Page ranges.
* See: https://github.com/bader-nasser/pdftools/blob/main/test/docs/data.txt
*/
pages: NumberOrString | NumberOrString[];
}
| {
/**
* Name of input file.
*/
name: string;
/**
* A text file that contains page ranges.
* See: https://github.com/bader-nasser/pdftools/blob/main/test/docs/data.txt
*/
data: string;
};
export type Metadata = {
title?: string;
author?: string;
subject?: string;
keywords?: string[];
producer?: string;
/**
* @default 'pdftools (https://github.com/bader-nasser/pdftools)'
*/
creator?: string;
creationDate?: string;
modificationDate?: string;
};
export type JsonFileObject = Metadata & {
$schema?: string;
output: string;
/**
* An array of file entries that forms the output.
* The entry can be a simple string of file name or an object which specifies
* the file name with selected pages OR applied data file.
*/
files: Array<string | InputFileObject>;
/**
* Reduce file size
*/
compress?: boolean;
/**
* Pretend to work!
*/
dryRun?: boolean;
/**
* Work silently.
*/
silent?: boolean;
};