-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathfilename-utils.ts
79 lines (71 loc) · 2.54 KB
/
filename-utils.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
import * as _ from "lodash"
import * as path from "path"
/**
* Shortens the length of a directory in a pretty way.
* @param pathName The path to shorten
* @param maxLength The maximum length of the path. Must be at least 4.
* @returns The shortened directory name.
*/
export function getPrettyPathName(pathName: string, maxLength: number): string {
if (maxLength < 4) {
throw Error("maxLength must be at least 4")
}
if (pathName.length <= maxLength) {
return pathName
}
const parts = path.parse(pathName)
const dirWithoutRoot = parts.dir.slice(parts.root.length, parts.dir.length - parts.root.length + 1)
const dirs = dirWithoutRoot.split(path.sep)
const root = `${parts.root}..${path.sep}`
// Save the first directory, we want to try and prioritize keeping it in the path.
let firstDir = dirs.shift()
firstDir = firstDir ? firstDir : ""
while (dirs.length > 0) {
// Except for the first directory, start removing dirs from left to right.
dirs.shift()
const middle = ["..", ...dirs].join(path.sep)
const newPath = `${parts.root}${firstDir}${path.sep}${middle}${path.sep}${parts.base}`
if (newPath.length <= maxLength) {
return newPath
}
}
const rootAndName = `..${path.sep}${parts.base}`
if (rootAndName.length <= maxLength) {
return rootAndName
}
return `${rootAndName.slice(0, maxLength - 2)}..`
}
/**
* Escapes the characters |()[]#*{}-+_!\,`> from a string.
* @param source The source to escape
* @returns An escaped version of the string
*/
export function escapeMarkdownCharacters(source: string) {
const escapedCharacters = ["|", "(", ")", "[", "]", "#", "*", "{", "}", "-", "+", "_", "!", "\\", "`"]
return [...source].map(c => (_.includes(escapedCharacters, c) ? `\\${c}` : c)).join("")
}
/**
* Parses the output from the git root directory command, removing newlines and adding a platform
* native separator.
* @param stdout The output to cleanup
* @param seperator The separator the path should end in. Defaults to platform native.
* @returns A cleaned up git root directory.
*/
export function parseGitRootPathOutput(stdout: string, seperator?: string): string {
if (seperator === undefined) {
seperator = path.sep
}
stdout = trimLineEnding(stdout)
if (stdout.endsWith(seperator)) {
return stdout
}
return `${stdout}${seperator}`
}
/**
* Trims the line endings from the end of a string
* @param input The string to cleanup
* @returns The string without line endings
*/
export function trimLineEnding(input: string): string {
return input.replace(/[\r\n]*/g, "")
}