-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
75 lines (62 loc) · 2.53 KB
/
index.js
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
import path from 'node:path';
import {pathExists, pathExistsSync} from 'path-exists';
import escapeStringRegexp from 'escape-string-regexp';
export class MaxTryError extends Error {
constructor(originalPath, lastTriedPath) {
super('Max tries reached.');
this.originalPath = originalPath;
this.lastTriedPath = lastTriedPath;
}
}
const parenthesesIncrementer = (inputFilename, extension) => {
const match = inputFilename.match(/^(?<filename>.*)\((?<index>\d+)\)$/);
let {filename, index} = match ? match.groups : {filename: inputFilename, index: 0};
filename = filename.trim();
return [`${filename}${extension}`, `${filename} (${++index})${extension}`];
};
const incrementPath = (filePath, incrementer) => {
const ext = path.extname(filePath);
const dirname = path.dirname(filePath);
const [originalFilename, incrementedFilename] = incrementer(path.basename(filePath, ext), ext);
return [path.join(dirname, originalFilename), path.join(dirname, incrementedFilename)];
};
export const separatorIncrementer = separator => {
const escapedSeparator = escapeStringRegexp(separator);
return (inputFilename, extension) => {
const match = new RegExp(`^(?<filename>.*)${escapedSeparator}(?<index>\\d+)$`).exec(inputFilename);
let {filename, index} = match ? match.groups : {filename: inputFilename, index: 0};
return [`${filename}${extension}`, `${filename.trim()}${separator}${++index}${extension}`];
};
};
export async function unusedFilename(filePath, {incrementer = parenthesesIncrementer, maxTries = Number.POSITIVE_INFINITY} = {}) {
let tries = 0;
let [originalPath] = incrementPath(filePath, incrementer);
let unusedPath = filePath;
/* eslint-disable no-await-in-loop, no-constant-condition */
while (true) {
if (!(await pathExists(unusedPath))) {
return unusedPath;
}
if (++tries > maxTries) {
throw new MaxTryError(originalPath, unusedPath);
}
[originalPath, unusedPath] = incrementPath(unusedPath, incrementer);
}
/* eslint-enable no-await-in-loop, no-constant-condition */
}
export function unusedFilenameSync(filePath, {incrementer = parenthesesIncrementer, maxTries = Number.POSITIVE_INFINITY} = {}) {
let tries = 0;
let [originalPath] = incrementPath(filePath, incrementer);
let unusedPath = filePath;
/* eslint-disable no-constant-condition */
while (true) {
if (!pathExistsSync(unusedPath)) {
return unusedPath;
}
if (++tries > maxTries) {
throw new MaxTryError(originalPath, unusedPath);
}
[originalPath, unusedPath] = incrementPath(unusedPath, incrementer);
}
/* eslint-enable no-constant-condition */
}