@bemoje/fs 0.0.10 → 0.0.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.
Files changed (102) hide show
  1. package/package.json +6 -4
  2. package/src/index.ts +35 -0
  3. package/src/lib/AppData.ts +25 -0
  4. package/src/lib/JsonFile.ts +158 -0
  5. package/src/lib/LogFile.ts +117 -0
  6. package/src/lib/absoluteToRelativePath.test.ts +11 -0
  7. package/{dist/types/lib/absoluteToRelativePath.d.ts → src/lib/absoluteToRelativePath.ts} +20 -14
  8. package/src/lib/appendLineToFile.test.ts +49 -0
  9. package/src/lib/appendLineToFile.ts +21 -0
  10. package/src/lib/cleanDirectorySync.test.ts +57 -0
  11. package/{dist/types/lib/cleanDirectorySync.d.ts → src/lib/cleanDirectorySync.ts} +24 -17
  12. package/src/lib/createDirectory.test.ts +14 -0
  13. package/{dist/types/lib/createDirectory.d.ts → src/lib/createDirectory.ts} +5 -2
  14. package/src/lib/createDirectorySync.test.ts +14 -0
  15. package/{dist/types/lib/createDirectorySync.d.ts → src/lib/createDirectorySync.ts} +6 -2
  16. package/src/lib/createFileExtensionFilter.test.ts +17 -0
  17. package/{dist/types/lib/createFileExtensionFilter.d.ts → src/lib/createFileExtensionFilter.ts} +14 -2
  18. package/src/lib/cwdpath.test.ts +48 -0
  19. package/{dist/types/lib/cwdpath.d.ts → src/lib/cwdpath.ts} +16 -13
  20. package/src/lib/deleteDirectory.test.ts +24 -0
  21. package/{dist/types/lib/deleteDirectory.d.ts → src/lib/deleteDirectory.ts} +5 -2
  22. package/src/lib/deleteDirectorySafe.test.ts +40 -0
  23. package/{dist/types/lib/deleteDirectorySafe.d.ts → src/lib/deleteDirectorySafe.ts} +5 -2
  24. package/src/lib/deleteDirectorySafeSync.test.ts +30 -0
  25. package/{dist/types/lib/deleteDirectorySafeSync.d.ts → src/lib/deleteDirectorySafeSync.ts} +7 -2
  26. package/src/lib/deleteDirectorySync.test.ts +23 -0
  27. package/{dist/types/lib/deleteDirectorySync.d.ts → src/lib/deleteDirectorySync.ts} +6 -2
  28. package/src/lib/ensureValidWindowsPath.test.ts +80 -0
  29. package/{dist/types/lib/ensureValidWindowsPath.d.ts → src/lib/ensureValidWindowsPath.ts} +57 -23
  30. package/src/lib/getDiskDrivesWindows.ts +13 -0
  31. package/src/lib/getDownloadsDirectory.ts +6 -0
  32. package/src/lib/getHomeDirectory.ts +7 -0
  33. package/src/lib/getLastMofifiedFileIn.ts +15 -0
  34. package/src/lib/getRootDir.ts +5 -0
  35. package/src/lib/isWindows.ts +3 -0
  36. package/src/lib/normalizeFileExtension.test.ts +15 -0
  37. package/{dist/types/lib/normalizeFileExtension.d.ts → src/lib/normalizeFileExtension.ts} +29 -23
  38. package/src/lib/readFileLastLines.ts +12 -0
  39. package/src/lib/readJsonFile.test.ts +34 -0
  40. package/{dist/types/lib/readJsonFile.d.ts → src/lib/readJsonFile.ts} +16 -13
  41. package/src/lib/readJsonFileSync.test.ts +36 -0
  42. package/{dist/types/lib/readJsonFileSync.d.ts → src/lib/readJsonFileSync.ts} +16 -13
  43. package/src/lib/readPackageJson.ts +9 -0
  44. package/src/lib/removeIllegalFilenameCharacters.ts +3 -0
  45. package/src/lib/tempFile.ts +20 -0
  46. package/src/lib/types/IEnsureValidWindowsPathOptions.ts +10 -0
  47. package/src/lib/types/ILogFileData.ts +5 -0
  48. package/src/lib/unzipFile.ts +5 -0
  49. package/src/lib/unzipMergeFiles.ts +20 -0
  50. package/src/lib/wipeDirectorySafe.ts +7 -0
  51. package/src/lib/writeJsonFile.test.ts +26 -0
  52. package/{dist/types/lib/writeJsonFile.d.ts → src/lib/writeJsonFile.ts} +5 -2
  53. package/src/lib/writeJsonFileSync.test.ts +28 -0
  54. package/{dist/types/lib/writeJsonFileSync.d.ts → src/lib/writeJsonFileSync.ts} +5 -2
  55. package/dist/index.cjs.js +0 -6
  56. package/dist/index.cjs.js.map +0 -1
  57. package/dist/index.esm.js +0 -6
  58. package/dist/index.esm.js.map +0 -1
  59. package/dist/types/index.d.ts +0 -30
  60. package/dist/types/index.d.ts.map +0 -1
  61. package/dist/types/lib/absoluteToRelativePath.d.ts.map +0 -1
  62. package/dist/types/lib/appendLineToFile.d.ts +0 -12
  63. package/dist/types/lib/appendLineToFile.d.ts.map +0 -1
  64. package/dist/types/lib/cleanDirectorySync.d.ts.map +0 -1
  65. package/dist/types/lib/createDirectory.d.ts.map +0 -1
  66. package/dist/types/lib/createDirectorySync.d.ts.map +0 -1
  67. package/dist/types/lib/createFileExtensionFilter.d.ts.map +0 -1
  68. package/dist/types/lib/cwdpath.d.ts.map +0 -1
  69. package/dist/types/lib/deleteDirectory.d.ts.map +0 -1
  70. package/dist/types/lib/deleteDirectorySafe.d.ts.map +0 -1
  71. package/dist/types/lib/deleteDirectorySafeSync.d.ts.map +0 -1
  72. package/dist/types/lib/deleteDirectorySync.d.ts.map +0 -1
  73. package/dist/types/lib/ensureValidWindowsPath.d.ts.map +0 -1
  74. package/dist/types/lib/getDiskDrivesWindows.d.ts +0 -2
  75. package/dist/types/lib/getDiskDrivesWindows.d.ts.map +0 -1
  76. package/dist/types/lib/getDownloadsDirectory.d.ts +0 -2
  77. package/dist/types/lib/getDownloadsDirectory.d.ts.map +0 -1
  78. package/dist/types/lib/getHomeDirectory.d.ts +0 -2
  79. package/dist/types/lib/getHomeDirectory.d.ts.map +0 -1
  80. package/dist/types/lib/getLastMofifiedFileIn.d.ts +0 -2
  81. package/dist/types/lib/getLastMofifiedFileIn.d.ts.map +0 -1
  82. package/dist/types/lib/getRootDir.d.ts +0 -2
  83. package/dist/types/lib/getRootDir.d.ts.map +0 -1
  84. package/dist/types/lib/isWindows.d.ts +0 -2
  85. package/dist/types/lib/isWindows.d.ts.map +0 -1
  86. package/dist/types/lib/normalizeFileExtension.d.ts.map +0 -1
  87. package/dist/types/lib/readJsonFile.d.ts.map +0 -1
  88. package/dist/types/lib/readJsonFileSync.d.ts.map +0 -1
  89. package/dist/types/lib/readPackageJson.d.ts +0 -2
  90. package/dist/types/lib/readPackageJson.d.ts.map +0 -1
  91. package/dist/types/lib/removeIllegalFilenameCharacters.d.ts +0 -2
  92. package/dist/types/lib/removeIllegalFilenameCharacters.d.ts.map +0 -1
  93. package/dist/types/lib/types/IEnsureValidWindowsPathOptions.d.ts +0 -11
  94. package/dist/types/lib/types/IEnsureValidWindowsPathOptions.d.ts.map +0 -1
  95. package/dist/types/lib/unzipFile.d.ts +0 -2
  96. package/dist/types/lib/unzipFile.d.ts.map +0 -1
  97. package/dist/types/lib/unzipMergeFiles.d.ts +0 -5
  98. package/dist/types/lib/unzipMergeFiles.d.ts.map +0 -1
  99. package/dist/types/lib/wipeDirectorySafe.d.ts +0 -2
  100. package/dist/types/lib/wipeDirectorySafe.d.ts.map +0 -1
  101. package/dist/types/lib/writeJsonFile.d.ts.map +0 -1
  102. package/dist/types/lib/writeJsonFileSync.d.ts.map +0 -1
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@bemoje/fs",
3
- "version": "0.0.10",
3
+ "version": "0.0.12",
4
4
  "description": "Tools for working with the local filesystem in nodejs.",
5
- "main": "dist/index.cjs.js",
5
+ "main": "src/index.ts",
6
6
  "module": "dist/index.esm.js",
7
7
  "types": "dist/types/index.d.ts",
8
8
  "scripts": {
@@ -17,7 +17,9 @@
17
17
  "keywords": [],
18
18
  "dependencies": {
19
19
  "@bemoje/string": "latest",
20
- "extract-zip": "^2.0.1"
20
+ "appdata-path": "^1.0.0",
21
+ "extract-zip": "^2.0.1",
22
+ "read-last-lines": "^1.8.0"
21
23
  },
22
24
  "repository": {
23
25
  "type": "git",
@@ -34,4 +36,4 @@
34
36
  "devDependencies": {
35
37
  "@types/extract-zip": "^2.0.1"
36
38
  }
37
- }
39
+ }
package/src/index.ts ADDED
@@ -0,0 +1,35 @@
1
+ export * from './lib/absoluteToRelativePath'
2
+ export * from './lib/AppData'
3
+ export * from './lib/appendLineToFile'
4
+ export * from './lib/cleanDirectorySync'
5
+ export * from './lib/createDirectory'
6
+ export * from './lib/createDirectorySync'
7
+ export * from './lib/createFileExtensionFilter'
8
+ export * from './lib/cwdpath'
9
+ export * from './lib/deleteDirectory'
10
+ export * from './lib/deleteDirectorySafe'
11
+ export * from './lib/deleteDirectorySafeSync'
12
+ export * from './lib/deleteDirectorySync'
13
+ export * from './lib/ensureValidWindowsPath'
14
+ export * from './lib/getDiskDrivesWindows'
15
+ export * from './lib/getDownloadsDirectory'
16
+ export * from './lib/getHomeDirectory'
17
+ export * from './lib/getLastMofifiedFileIn'
18
+ export * from './lib/getRootDir'
19
+ export * from './lib/isWindows'
20
+ export * from './lib/JsonFile'
21
+ export * from './lib/LogFile'
22
+ export * from './lib/normalizeFileExtension'
23
+ export * from './lib/readFileLastLines'
24
+ export * from './lib/readJsonFile'
25
+ export * from './lib/readJsonFileSync'
26
+ export * from './lib/readPackageJson'
27
+ export * from './lib/removeIllegalFilenameCharacters'
28
+ export * from './lib/tempFile'
29
+ export * from './lib/types/IEnsureValidWindowsPathOptions'
30
+ export * from './lib/types/ILogFileData'
31
+ export * from './lib/unzipFile'
32
+ export * from './lib/unzipMergeFiles'
33
+ export * from './lib/wipeDirectorySafe'
34
+ export * from './lib/writeJsonFile'
35
+ export * from './lib/writeJsonFileSync'
@@ -0,0 +1,25 @@
1
+ import getAppDataPath from 'appdata-path'
2
+ import path from 'path'
3
+ import { JsonFile } from './JsonFile'
4
+ import { LogFile } from './LogFile'
5
+ import { ILogFileData } from './types/ILogFileData'
6
+
7
+ export class AppData<A extends Record<string, unknown>, C extends Record<string, unknown>> {
8
+ directory: string
9
+ app: JsonFile<A>
10
+ user: JsonFile<C>
11
+ history: LogFile<ILogFileData<C>>
12
+
13
+ constructor(appAuthor: string, appName: string, configName: string) {
14
+ this.directory = path.join(getAppDataPath(), appAuthor, appName, configName)
15
+ this.app = new JsonFile(path.join(this.directory, 'appdata.json'), false)
16
+ this.user = new JsonFile(path.join(this.directory, 'config.json'), true)
17
+ this.history = new LogFile(path.join(this.directory, 'history.log'))
18
+ this.app.on('set', async (time, k: string, v: C) => {
19
+ await this.history.append({ source: 'app', key: k, value: v }, time)
20
+ })
21
+ this.user.on('set', async (time, k: string, v: C) => {
22
+ await this.history.append({ source: 'user', key: k, value: v }, time)
23
+ })
24
+ }
25
+ }
@@ -0,0 +1,158 @@
1
+ import EventEmitter from 'events'
2
+ import fs from 'fs'
3
+ import path from 'path'
4
+ import { readJsonFileSync } from './readJsonFileSync'
5
+ import { writeJsonFileSync } from './writeJsonFileSync'
6
+
7
+ /**
8
+ * Represents a JSON file manager that ensures immutable data since everything is serialized and deserialized before receiving or returning any data.
9
+ */
10
+ export class JsonFile<T extends Record<string, any>> extends EventEmitter {
11
+ /**
12
+ * The filepath of the JSON file.
13
+ */
14
+ readonly filepath: string
15
+
16
+ /**
17
+ * The data stored in the JSON file.
18
+ */
19
+ #data: T
20
+
21
+ /**
22
+ * Determines whether the JSON file should be pretty-printed.
23
+ */
24
+ prettyPrint: boolean
25
+
26
+ /**
27
+ * Gets the data stored in the JSON file.
28
+ * @returns A deep copy of the data.
29
+ */
30
+ get data(): T {
31
+ return JSON.parse(JSON.stringify(this.#data))
32
+ }
33
+
34
+ /**
35
+ * Constructs a new instance of the JsonFile class.
36
+ * @param filepath - The filepath of the JSON file.
37
+ * @param prettyPrint - Determines whether the JSON file should be pretty-printed.
38
+ */
39
+ constructor(filepath: string, prettyPrint = false) {
40
+ super()
41
+ this.filepath = filepath
42
+ this.#data = {} as T
43
+ this.prettyPrint = prettyPrint
44
+ this.ensureDirectoryExists()
45
+ if (fs.existsSync(this.filepath)) {
46
+ this.loadFile()
47
+ } else {
48
+ writeJsonFileSync(this.filepath, this.#data, this.prettyPrint)
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Gets the value associated with the specified key.
54
+ * @param key - The key to retrieve the value for.
55
+ * @returns The value associated with the key.
56
+ */
57
+ get(key: keyof T): any {
58
+ return JSON.parse(JSON.stringify(this.#data[key]))
59
+ }
60
+
61
+ /**
62
+ * Sets the value associated with the specified key.
63
+ * @param key - The key to set the value for.
64
+ * @param value - The value to set.
65
+ */
66
+ set(key: keyof T, value: any): void {
67
+ if (this.#data[key] === value) return
68
+ const json = JSON.stringify(value)
69
+ if (json === JSON.stringify(this.#data[key])) return
70
+ value = JSON.parse(json)
71
+ this.#data[key] = value
72
+ this.saveFile()
73
+ this.emit('set', Date.now(), key, value)
74
+ }
75
+
76
+ /**
77
+ * Checks if the specified key exists in the JSON file.
78
+ * @param key - The key to check.
79
+ * @returns True if the key exists, false otherwise.
80
+ */
81
+ has(key: keyof T): boolean {
82
+ return this.#data[key] !== undefined
83
+ }
84
+
85
+ /**
86
+ * Deletes the value associated with the specified key.
87
+ * @param key - The key to delete.
88
+ */
89
+ delete(key: keyof T): void {
90
+ delete this.#data[key]
91
+ this.saveFile()
92
+ this.emit('set', Date.now(), key, void 0)
93
+ }
94
+
95
+ /**
96
+ * Gets the value associated with the specified key, or sets it to the provided default value if it doesn't exist.
97
+ * @param key - The key to get or set.
98
+ * @param getValue - A function that returns the default value if the key doesn't exist.
99
+ * @returns The value associated with the key, or the default value if it doesn't exist.
100
+ */
101
+ getOrElse(key: string, getValue: () => any): any {
102
+ if (this.has(key)) {
103
+ return JSON.parse(JSON.stringify(this.get(key)))
104
+ }
105
+ const value = JSON.parse(JSON.stringify(getValue()))
106
+ this.set(key, value)
107
+ return value
108
+ }
109
+
110
+ /**
111
+ * Clears all the data in the JSON file.
112
+ */
113
+ clear(): void {
114
+ const time = Date.now()
115
+ for (const key of Object.keys(this.#data)) {
116
+ this.emit('set', time, key, void 0)
117
+ }
118
+ this.#data = {} as T
119
+ fs.writeFileSync(this.filepath, '{}', 'utf8')
120
+ }
121
+
122
+ /**
123
+ * Assigns new data to the JSON file.
124
+ * @param data - The data to assign.
125
+ */
126
+ assign(data: T): void {
127
+ data = JSON.parse(JSON.stringify(data))
128
+ const time = Date.now()
129
+ for (const [key, value] of Object.entries(data)) {
130
+ if (this.#data[key] && JSON.stringify(this.#data[key]) !== JSON.stringify(value)) {
131
+ this.emit('set', time, key, value)
132
+ }
133
+ }
134
+ Object.assign(this.#data, data)
135
+ this.saveFile()
136
+ }
137
+
138
+ /**
139
+ * Ensures that the directory containing the JSON file exists.
140
+ */
141
+ ensureDirectoryExists(): void {
142
+ fs.mkdirSync(path.dirname(this.filepath), { recursive: true })
143
+ }
144
+
145
+ /**
146
+ * Saves the data to the JSON file.
147
+ */
148
+ saveFile(): void {
149
+ writeJsonFileSync(this.filepath, this.#data, this.prettyPrint)
150
+ }
151
+
152
+ /**
153
+ * Loads the data from the JSON file.
154
+ */
155
+ loadFile(): void {
156
+ this.#data = readJsonFileSync(this.filepath) as T
157
+ }
158
+ }
@@ -0,0 +1,117 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import readline from 'readline'
4
+
5
+ /**
6
+ * Represents a log file manager that appends log entries to a file.
7
+ * It does not ensure extremely precise ordering of log entries' timestamps if used asynchronously. It logs them as they are received.
8
+ */
9
+ export class LogFile<T> {
10
+ /**
11
+ * The path to the log file.
12
+ */
13
+ filepath: string
14
+
15
+ /**
16
+ * Creates a new instance of the LogFile class.
17
+ * @param filepath - The path to the log file.
18
+ */
19
+ constructor(filepath: string) {
20
+ this.filepath = filepath
21
+ this.ensureDirectoryExists()
22
+ }
23
+
24
+ /**
25
+ * Appends a log entry to the log file.
26
+ * @param data - The data to be logged.
27
+ * @param time - The timestamp of the log entry. Defaults to the current time.
28
+ * @returns A promise that resolves when the log entry is appended.
29
+ */
30
+ async append(data: T, time = Date.now()): Promise<void> {
31
+ await fs.promises.appendFile(this.filepath, time + '|' + JSON.stringify(data) + '\n', 'utf8')
32
+ }
33
+
34
+ /**
35
+ * Resets the log file by removing it.
36
+ */
37
+ reset(): void {
38
+ fs.rmSync(this.filepath)
39
+ }
40
+
41
+ /**
42
+ * Reads the log entire file and returns an array of log entries, sorted by timestamp in descending order.
43
+ * @returns An array of log entries, sorted by timestamp in descending order.
44
+ */
45
+ readFile(): [number, T][] {
46
+ const data = fs.readFileSync(this.filepath, 'utf8')
47
+ const lines = data.split('\n')
48
+ const result = [] as [number, T][]
49
+ for (const line of lines) {
50
+ const i = line.indexOf('|')
51
+ if (i === -1) continue
52
+ const time = parseInt(line.substring(0, i))
53
+ const data = JSON.parse(line.substring(i + 1)) as T
54
+ result.push([time, data])
55
+ }
56
+ return result.sort((a, b) => b[0] - a[0])
57
+ }
58
+
59
+ /**
60
+ * Returns an async generator that yields the timestamps of log entries in the log file.
61
+ * @yields The timestamps of log entries.
62
+ */
63
+ async *keys(): AsyncGenerator<number> {
64
+ const fileStream = fs.createReadStream(this.filepath, 'utf8')
65
+ const rl = readline.createInterface({
66
+ input: fileStream,
67
+ crlfDelay: Infinity,
68
+ })
69
+ for await (const line of rl) {
70
+ const i = line.indexOf('|')
71
+ const time = parseInt(line.substring(0, i))
72
+ yield time
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Returns an async generator that yields the values of log entries in the log file.
78
+ * @yields The values of log entries.
79
+ */
80
+ async *values(): AsyncGenerator<T> {
81
+ const fileStream = fs.createReadStream(this.filepath, 'utf8')
82
+ const rl = readline.createInterface({
83
+ input: fileStream,
84
+ crlfDelay: Infinity,
85
+ })
86
+ for await (const line of rl) {
87
+ const i = line.indexOf('|')
88
+ const data = JSON.parse(line.substring(i + 1)) as T
89
+ yield data
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Returns an async generator that yields the entries (timestamp and value) of log entries in the log file.
95
+ * @yields The entries (timestamp and value) of log entries.
96
+ */
97
+ async *entries(): AsyncGenerator<[number, T]> {
98
+ const fileStream = fs.createReadStream(this.filepath, 'utf8')
99
+ const rl = readline.createInterface({
100
+ input: fileStream,
101
+ crlfDelay: Infinity,
102
+ })
103
+ for await (const line of rl) {
104
+ const i = line.indexOf('|')
105
+ const time = parseInt(line.substring(0, i))
106
+ const data = JSON.parse(line.substring(i + 1)) as T
107
+ yield [time, data]
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Ensures that the directory containing the log file exists.
113
+ */
114
+ ensureDirectoryExists(): void {
115
+ fs.mkdirSync(path.dirname(this.filepath), { recursive: true })
116
+ }
117
+ }
@@ -0,0 +1,11 @@
1
+ import path from 'path'
2
+ import { absoluteToRelativePath } from './absoluteToRelativePath'
3
+
4
+ describe('absoluteToRelativePath', () => {
5
+ it('should convert an absolute path to a relative path', () => {
6
+ const filepath = path.join(process.cwd(), 'pkg', 'fs', 'src', 'index.ts')
7
+ const expected = 'pkg' + path.sep + 'fs' + path.sep + 'src' + path.sep + 'index.ts'
8
+ const result = absoluteToRelativePath(filepath)
9
+ expect(result).toEqual(expected)
10
+ })
11
+ })
@@ -1,14 +1,20 @@
1
- /**
2
- * If the filepath is somewhere in the current working directory, it can be converted into a relative path.
3
- * @remarks This function takes an absolute path as input and returns a relative path. It replaces the current working directory in the path with an empty string,
4
- * replaces all backslashes with forward slashes, and removes any leading forward slashes.
5
- * @param workingDirectory The directory relative to which the path should be converted. Defaults to the current working directory.
6
- * @returns The relative path.
7
- * @param absolute the absolute filepath to convert.
8
- * @example ```ts
9
- * absoluteToRelativePath(__filename)
10
- * //=> 'src/absoluteToRelativePath.ts'
11
- * ```
12
- */
13
- export declare function absoluteToRelativePath(absolute: string, workingDirectory?: string): string;
14
- //# sourceMappingURL=absoluteToRelativePath.d.ts.map
1
+ import { regexEscapeString } from '@bemoje/string'
2
+ import path from 'path'
3
+
4
+ /**
5
+ * If the filepath is somewhere in the current working directory, it can be converted into a relative path.
6
+ * @remarks This function takes an absolute path as input and returns a relative path. It replaces the current working directory in the path with an empty string,
7
+ * replaces all backslashes with forward slashes, and removes any leading forward slashes.
8
+ * @param workingDirectory The directory relative to which the path should be converted. Defaults to the current working directory.
9
+ * @returns The relative path.
10
+ * @param absolute the absolute filepath to convert.
11
+ * @example ```ts
12
+ * absoluteToRelativePath(__filename)
13
+ * //=> 'src/absoluteToRelativePath.ts'
14
+ * ```
15
+ */
16
+ export function absoluteToRelativePath(absolute: string, workingDirectory = process.cwd()): string {
17
+ return path
18
+ .normalize(absolute)
19
+ .replace(new RegExp(regexEscapeString(path.normalize(workingDirectory) + path.sep), 'i'), '')
20
+ }
@@ -0,0 +1,49 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import { appendLineToFile } from './appendLineToFile'
4
+
5
+ describe(appendLineToFile.name, () => {
6
+ it('should append the line to the file', async () => {
7
+ const dirpath = path.join(process.env.TEMP as string, Date.now().toString())
8
+ const filepath = path.join(dirpath, 'file.txt')
9
+ const line = 'content'
10
+ expect(fs.existsSync(dirpath)).toBe(false)
11
+ await appendLineToFile(filepath, line)
12
+ expect(fs.existsSync(dirpath)).toBe(true)
13
+ expect(fs.existsSync(filepath)).toBe(true)
14
+ const result = fs.readFileSync(filepath, 'utf8')
15
+ expect(result).toBe(line + '\n')
16
+ fs.rmSync(dirpath, { recursive: true, force: true })
17
+ expect(fs.existsSync(dirpath)).toBe(false)
18
+ })
19
+
20
+ it('should append the line to the file with a linebreak before inserted string', async () => {
21
+ const dirpath = path.join(process.env.TEMP as string, Date.now().toString())
22
+ const filepath = path.join(dirpath, 'file.txt')
23
+ const line = 'content'
24
+ expect(fs.existsSync(dirpath)).toBe(false)
25
+ await appendLineToFile(filepath, line, true)
26
+ expect(fs.existsSync(dirpath)).toBe(true)
27
+ expect(fs.existsSync(filepath)).toBe(true)
28
+ const result = fs.readFileSync(filepath, 'utf8')
29
+ expect(result).toBe('\n' + line)
30
+ fs.rmSync(dirpath, { recursive: true, force: true })
31
+ expect(fs.existsSync(dirpath)).toBe(false)
32
+ })
33
+
34
+ it('should append multiple lines', async () => {
35
+ const dirpath = path.join(process.env.TEMP as string, Date.now().toString())
36
+ const filepath = path.join(dirpath, 'file.txt')
37
+ const line1 = 'content1'
38
+ const line2 = 'content2'
39
+ expect(fs.existsSync(dirpath)).toBe(false)
40
+ await appendLineToFile(filepath, line1)
41
+ expect(fs.existsSync(dirpath)).toBe(true)
42
+ expect(fs.existsSync(filepath)).toBe(true)
43
+ expect(fs.readFileSync(filepath, 'utf8')).toBe(line1 + '\n')
44
+ await appendLineToFile(filepath, line2)
45
+ expect(fs.readFileSync(filepath, 'utf8')).toBe(line1 + '\n' + line2 + '\n')
46
+ fs.rmSync(dirpath, { recursive: true, force: true })
47
+ expect(fs.existsSync(dirpath)).toBe(false)
48
+ })
49
+ })
@@ -0,0 +1,21 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import { createDirectory } from './createDirectory'
4
+
5
+ /**
6
+ * Append a line to a file. Creates the file if it does not exist.
7
+ * @param filepath The path of the file.
8
+ * @param line The string data to append.
9
+ * @returns A Promise that resolves when the line has been appended to the file.
10
+ * @throws Will throw an error if the operation fails.
11
+ * @example ```ts
12
+ * await appendLineToFile('/path/to/file', 'This is a new line')
13
+ * ```
14
+ */
15
+ export async function appendLineToFile(filepath: string, line: string, linebreakBefore = false): Promise<void> {
16
+ if (!fs.existsSync(filepath)) {
17
+ await createDirectory(path.dirname(filepath))
18
+ await fs.promises.writeFile(filepath, '')
19
+ }
20
+ await fs.promises.appendFile(filepath, linebreakBefore ? '\n' + line : line + '\n')
21
+ }
@@ -0,0 +1,57 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import { cleanDirectorySync } from './cleanDirectorySync'
4
+
5
+ // Mock fs.readdirSync
6
+ jest.mock('fs', () => ({
7
+ readdirSync: jest.fn(),
8
+ statSync: jest.fn(),
9
+ unlinkSync: jest.fn(),
10
+ }))
11
+
12
+ describe(cleanDirectorySync.name, () => {
13
+ beforeEach(() => {
14
+ // Clear mock function calls and return values before each test
15
+ jest.clearAllMocks()
16
+ })
17
+
18
+ it('should remove files that satisfy the predicate', () => {
19
+ // Mock fs.readdirSync to return an array of filenames
20
+ const mockFilenames = ['file1.txt', 'file2.txt', 'file3.txt']
21
+ ;(fs.readdirSync as jest.Mock).mockReturnValue(mockFilenames)
22
+
23
+ // Mock fs.statSync to return a mock stat object
24
+ const mockStat = { isFile: jest.fn().mockReturnValue(true) }
25
+ ;(fs.statSync as jest.Mock).mockReturnValue(mockStat)
26
+
27
+ // Mock the predicate function to return true for file2.txt
28
+ const mockPredicate = jest.fn().mockImplementation((filepath, stat) => {
29
+ return filepath === path.join('path/to/directory', 'file2.txt')
30
+ })
31
+
32
+ // Call the function
33
+ cleanDirectorySync('path/to/directory', mockPredicate)
34
+
35
+ // Verify that fs.unlinkSync was called only for file2.txt
36
+ expect((fs.unlinkSync as jest.Mock).mock.calls).toEqual([[path.join('path/to/directory', 'file2.txt')]])
37
+ })
38
+
39
+ it('should not remove any files if the predicate returns false for all files', () => {
40
+ // Mock fs.readdirSync to return an array of filenames
41
+ const mockFilenames = ['file1.txt', 'file2.txt', 'file3.txt']
42
+ ;(fs.readdirSync as jest.Mock).mockReturnValue(mockFilenames)
43
+
44
+ // Mock fs.statSync to return a mock stat object
45
+ const mockStat = { isFile: jest.fn().mockReturnValue(true) }
46
+ ;(fs.statSync as jest.Mock).mockReturnValue(mockStat)
47
+
48
+ // Mock the predicate function to always return false
49
+ const mockPredicate = jest.fn().mockReturnValue(false)
50
+
51
+ // Call the function
52
+ cleanDirectorySync('path/to/directory', mockPredicate)
53
+
54
+ // Verify that fs.unlinkSync was not called
55
+ expect((fs.unlinkSync as jest.Mock).mock.calls).toEqual([])
56
+ })
57
+ })
@@ -1,17 +1,24 @@
1
- /// <reference types="node" />
2
- import type { Stats } from 'fs';
3
- /**
4
- * Synchronously cleans a directory by removing files that satisfy a given predicate.
5
- * @remarks This function is a part of the File System module.
6
- * @param dirpath - The path to the directory that needs to be cleaned.
7
- * @param predicate - A function that takes a filepath and its stats as arguments and returns a boolean. If the function returns true for a file, that file is removed from the directory.
8
- * @throws If the directory at the provided path does not exist or cannot be read.
9
- * @example ```ts
10
- * import { Stats } from 'fs';
11
- * const dirpath = './my-directory';
12
- * const predicate = (filepath: string, stat: Stats) => stat.size > 1024;
13
- * cleanDirectorySync(dirpath, predicate);
14
- * ```
15
- */
16
- export declare function cleanDirectorySync(dirpath: string, predicate: (filepath: string, stat: Stats) => boolean): void;
17
- //# sourceMappingURL=cleanDirectorySync.d.ts.map
1
+ import type { Stats } from 'fs'
2
+ import fs from 'fs'
3
+ import path from 'path'
4
+
5
+ /**
6
+ * Synchronously cleans a directory by removing files that satisfy a given predicate.
7
+ * @remarks This function is a part of the File System module.
8
+ * @param dirpath - The path to the directory that needs to be cleaned.
9
+ * @param predicate - A function that takes a filepath and its stats as arguments and returns a boolean. If the function returns true for a file, that file is removed from the directory.
10
+ * @throws If the directory at the provided path does not exist or cannot be read.
11
+ * @example ```ts
12
+ * import { Stats } from 'fs';
13
+ * const dirpath = './my-directory';
14
+ * const predicate = (filepath: string, stat: Stats) => stat.size > 1024;
15
+ * cleanDirectorySync(dirpath, predicate);
16
+ * ```
17
+ */
18
+ export function cleanDirectorySync(dirpath: string, predicate: (filepath: string, stat: Stats) => boolean): void {
19
+ for (const filename of fs.readdirSync(dirpath)) {
20
+ const filepath = path.join(dirpath, filename)
21
+ const stat = fs.statSync(filepath)
22
+ if (predicate(filepath, stat)) fs.unlinkSync(filepath)
23
+ }
24
+ }
@@ -0,0 +1,14 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import { createDirectory } from './createDirectory'
4
+
5
+ describe(createDirectory.name, () => {
6
+ it('should create directory successfully', async () => {
7
+ const dirpath = path.join(process.env.TEMP as string, Date.now().toString())
8
+ expect(fs.existsSync(dirpath)).toBe(false)
9
+ await createDirectory(dirpath)
10
+ expect(fs.existsSync(dirpath)).toBe(true)
11
+ fs.rmSync(dirpath, { recursive: true, force: true })
12
+ expect(fs.existsSync(dirpath)).toBe(false)
13
+ })
14
+ })
@@ -1,3 +1,4 @@
1
+ import fs from 'fs'
1
2
  /**
2
3
  * Create a directory at a given path if it does not exist.
3
4
  * Automatically creates parent directories if they do not exist.
@@ -10,5 +11,7 @@
10
11
  * });
11
12
  * ```
12
13
  */
13
- export declare function createDirectory(dirpath: string): Promise<string>;
14
- //# sourceMappingURL=createDirectory.d.ts.map
14
+ export async function createDirectory(dirpath: string): Promise<string> {
15
+ await fs.promises.mkdir(dirpath, { recursive: true })
16
+ return dirpath
17
+ }
@@ -0,0 +1,14 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import { createDirectorySync } from './createDirectorySync'
4
+
5
+ describe(createDirectorySync.name, () => {
6
+ it('should create directory successfully', () => {
7
+ const dirpath = path.join(process.env.TEMP as string, Date.now().toString())
8
+ expect(fs.existsSync(dirpath)).toBe(false)
9
+ createDirectorySync(dirpath)
10
+ expect(fs.existsSync(dirpath)).toBe(true)
11
+ fs.rmSync(dirpath, { recursive: true, force: true })
12
+ expect(fs.existsSync(dirpath)).toBe(false)
13
+ })
14
+ })
@@ -1,3 +1,5 @@
1
+ import fs from 'fs'
2
+
1
3
  /**
2
4
  * Create a directory at a given path if it does not exist.
3
5
  * Automatically creates parent directories if they do not exist.
@@ -7,5 +9,7 @@
7
9
  * createDirectorySync('/path/to/directory')
8
10
  * ```
9
11
  */
10
- export declare function createDirectorySync(dirpath: string): string;
11
- //# sourceMappingURL=createDirectorySync.d.ts.map
12
+ export function createDirectorySync(dirpath: string): string {
13
+ fs.mkdirSync(dirpath, { recursive: true })
14
+ return dirpath
15
+ }
@@ -0,0 +1,17 @@
1
+ import { createFileExtensionFilter } from './createFileExtensionFilter'
2
+
3
+ describe('createFileExtensionFilter', () => {
4
+ const paths = ['./src/file', './src/file.js', './src/file.ts', './src/file.md', './src/file.json']
5
+ it('creates filter that accepts any extension', () => {
6
+ const filter = createFileExtensionFilter()
7
+ expect(paths.filter(filter)).toStrictEqual(paths)
8
+ })
9
+ it('creates filter that accepts one extension', () => {
10
+ const filter = createFileExtensionFilter('.js')
11
+ expect(paths.filter(filter)).toStrictEqual(['./src/file.js'])
12
+ })
13
+ it('creates filter that accepts multiple extensions', () => {
14
+ const filter = createFileExtensionFilter('.js', 'md')
15
+ expect(paths.filter(filter)).toStrictEqual(['./src/file.js', './src/file.md'])
16
+ })
17
+ })