File size: 2,308 Bytes
71174bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { IFileParts } from "./FileUtils";
import memoize from "lodash.memoize";
const regexAcceptableChars = "\\w\\-.";

/**
 * Make sure a filename is valid by removing non-alphanumeric characters.
 *
 * @param  {string} filename The filename to check.
 * @returns {string} The filename with all non-alphanumeric characters removed.
 */
export function fileNameFilter(filename: string): string {
    // Keep numbers and letters and period. Also - and _.
    // filename = filename.replace(/[^a-zA-Z\d.]/g, "");
    const re = new RegExp(`[^${regexAcceptableChars}]`, "g");
    filename = filename.replace(re, "");
    // filename = filename.replace(/[^\w.-]/g, '');

    return filename;
}

/**
 * Make sure a given filename is acceptable and valid.
 *
 * @param  {string} filename The filename to check.
 * @returns {boolean} Whether the filename is acceptable.
 */
export function matchesFilename(filename: string): boolean {
    // Create regex for any number of letters and numbers and period
    // const r = /^[a-zA-Z\d.]+$/;
    const r = new RegExp(`^[${regexAcceptableChars}]+$`, "g");

    // Return bool whether text matches regex
    return filename.match(r) !== null;
}

/**
 * Get the basename and extension of a filename.
 *
 * @param  {string} filename The filename to get the parts of.
 * @returns {IFileParts} The basename and extension of the filename.
 */
export const getFileNameParts = memoize(function (
    filename: string
): IFileParts {
    // Handle dotfiles (e.g., .bashrc) where the dot is at the beginning
    // and there are no other dots.
    if (filename.startsWith('.') && filename.lastIndexOf('.') === 0) {
        return {
            basename: filename,
            ext: "",
        };
    }

    if (filename.indexOf(".") === -1) {
        return {
            basename: filename,
            ext: "",
        };
    }
    // Split filename into parts
    const parts = filename.split(".");
    // If subsequent parts are all small, treat them as extensions. So
    // filename.pdb.txt, extension will be pdb.txt.
    let ext = parts.pop();
    while (parts.length > 1 && parts[parts.length - 1].length <= 3) {
        ext = parts.pop() + "." + ext;
    }
    // Return parts
    return {
        basename: parts.join("."),
        ext: ext,
    } as IFileParts;
});