@bemoje/fs 0.0.12 → 0.0.13

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 (113) hide show
  1. package/dist/index.cjs.js +6 -0
  2. package/dist/index.cjs.js.map +1 -0
  3. package/dist/index.esm.js +6 -0
  4. package/dist/index.esm.js.map +1 -0
  5. package/dist/types/index.d.ts +36 -0
  6. package/dist/types/index.d.ts.map +1 -0
  7. package/dist/types/lib/AppData.d.ts +11 -0
  8. package/dist/types/lib/AppData.d.ts.map +1 -0
  9. package/dist/types/lib/JsonFile.d.ts +79 -0
  10. package/dist/types/lib/JsonFile.d.ts.map +1 -0
  11. package/dist/types/lib/LogFile.d.ts +51 -0
  12. package/dist/types/lib/LogFile.d.ts.map +1 -0
  13. package/{src/lib/absoluteToRelativePath.ts → dist/types/lib/absoluteToRelativePath.d.ts} +14 -20
  14. package/dist/types/lib/absoluteToRelativePath.d.ts.map +1 -0
  15. package/dist/types/lib/appendLineToFile.d.ts +12 -0
  16. package/dist/types/lib/appendLineToFile.d.ts.map +1 -0
  17. package/{src/lib/cleanDirectorySync.ts → dist/types/lib/cleanDirectorySync.d.ts} +17 -24
  18. package/dist/types/lib/cleanDirectorySync.d.ts.map +1 -0
  19. package/{src/lib/createDirectory.ts → dist/types/lib/createDirectory.d.ts} +2 -5
  20. package/dist/types/lib/createDirectory.d.ts.map +1 -0
  21. package/{src/lib/createDirectorySync.ts → dist/types/lib/createDirectorySync.d.ts} +2 -6
  22. package/dist/types/lib/createDirectorySync.d.ts.map +1 -0
  23. package/{src/lib/createFileExtensionFilter.ts → dist/types/lib/createFileExtensionFilter.d.ts} +2 -14
  24. package/dist/types/lib/createFileExtensionFilter.d.ts.map +1 -0
  25. package/{src/lib/cwdpath.ts → dist/types/lib/cwdpath.d.ts} +13 -16
  26. package/dist/types/lib/cwdpath.d.ts.map +1 -0
  27. package/{src/lib/deleteDirectory.ts → dist/types/lib/deleteDirectory.d.ts} +2 -5
  28. package/dist/types/lib/deleteDirectory.d.ts.map +1 -0
  29. package/{src/lib/deleteDirectorySafe.ts → dist/types/lib/deleteDirectorySafe.d.ts} +2 -5
  30. package/dist/types/lib/deleteDirectorySafe.d.ts.map +1 -0
  31. package/{src/lib/deleteDirectorySafeSync.ts → dist/types/lib/deleteDirectorySafeSync.d.ts} +2 -7
  32. package/dist/types/lib/deleteDirectorySafeSync.d.ts.map +1 -0
  33. package/{src/lib/deleteDirectorySync.ts → dist/types/lib/deleteDirectorySync.d.ts} +2 -6
  34. package/dist/types/lib/deleteDirectorySync.d.ts.map +1 -0
  35. package/{src/lib/ensureValidWindowsPath.ts → dist/types/lib/ensureValidWindowsPath.d.ts} +23 -57
  36. package/dist/types/lib/ensureValidWindowsPath.d.ts.map +1 -0
  37. package/dist/types/lib/getDiskDrivesWindows.d.ts +2 -0
  38. package/dist/types/lib/getDiskDrivesWindows.d.ts.map +1 -0
  39. package/dist/types/lib/getDownloadsDirectory.d.ts +2 -0
  40. package/dist/types/lib/getDownloadsDirectory.d.ts.map +1 -0
  41. package/dist/types/lib/getHomeDirectory.d.ts +2 -0
  42. package/dist/types/lib/getHomeDirectory.d.ts.map +1 -0
  43. package/dist/types/lib/getLastMofifiedFileIn.d.ts +2 -0
  44. package/dist/types/lib/getLastMofifiedFileIn.d.ts.map +1 -0
  45. package/dist/types/lib/getRootDir.d.ts +2 -0
  46. package/dist/types/lib/getRootDir.d.ts.map +1 -0
  47. package/dist/types/lib/isWindows.d.ts +2 -0
  48. package/dist/types/lib/isWindows.d.ts.map +1 -0
  49. package/{src/lib/normalizeFileExtension.ts → dist/types/lib/normalizeFileExtension.d.ts} +23 -29
  50. package/dist/types/lib/normalizeFileExtension.d.ts.map +1 -0
  51. package/{src/lib/readFileLastLines.ts → dist/types/lib/readFileLastLines.d.ts} +3 -5
  52. package/dist/types/lib/readFileLastLines.d.ts.map +1 -0
  53. package/{src/lib/readJsonFile.ts → dist/types/lib/readJsonFile.d.ts} +13 -16
  54. package/dist/types/lib/readJsonFile.d.ts.map +1 -0
  55. package/{src/lib/readJsonFileSync.ts → dist/types/lib/readJsonFileSync.d.ts} +13 -16
  56. package/dist/types/lib/readJsonFileSync.d.ts.map +1 -0
  57. package/dist/types/lib/readPackageJson.d.ts +2 -0
  58. package/dist/types/lib/readPackageJson.d.ts.map +1 -0
  59. package/dist/types/lib/removeIllegalFilenameCharacters.d.ts +2 -0
  60. package/dist/types/lib/removeIllegalFilenameCharacters.d.ts.map +1 -0
  61. package/dist/types/lib/tempFile.d.ts +7 -0
  62. package/dist/types/lib/tempFile.d.ts.map +1 -0
  63. package/dist/types/lib/types/IEnsureValidWindowsPathOptions.d.ts +11 -0
  64. package/dist/types/lib/types/IEnsureValidWindowsPathOptions.d.ts.map +1 -0
  65. package/dist/types/lib/types/ILogFileData.d.ts +6 -0
  66. package/dist/types/lib/types/ILogFileData.d.ts.map +1 -0
  67. package/dist/types/lib/unzipFile.d.ts +2 -0
  68. package/dist/types/lib/unzipFile.d.ts.map +1 -0
  69. package/dist/types/lib/unzipMergeFiles.d.ts +5 -0
  70. package/dist/types/lib/unzipMergeFiles.d.ts.map +1 -0
  71. package/dist/types/lib/wipeDirectorySafe.d.ts +2 -0
  72. package/dist/types/lib/wipeDirectorySafe.d.ts.map +1 -0
  73. package/{src/lib/writeJsonFile.ts → dist/types/lib/writeJsonFile.d.ts} +2 -5
  74. package/dist/types/lib/writeJsonFile.d.ts.map +1 -0
  75. package/{src/lib/writeJsonFileSync.ts → dist/types/lib/writeJsonFileSync.d.ts} +2 -5
  76. package/dist/types/lib/writeJsonFileSync.d.ts.map +1 -0
  77. package/package.json +3 -3
  78. package/src/index.ts +0 -35
  79. package/src/lib/AppData.ts +0 -25
  80. package/src/lib/JsonFile.ts +0 -158
  81. package/src/lib/LogFile.ts +0 -117
  82. package/src/lib/absoluteToRelativePath.test.ts +0 -11
  83. package/src/lib/appendLineToFile.test.ts +0 -49
  84. package/src/lib/appendLineToFile.ts +0 -21
  85. package/src/lib/cleanDirectorySync.test.ts +0 -57
  86. package/src/lib/createDirectory.test.ts +0 -14
  87. package/src/lib/createDirectorySync.test.ts +0 -14
  88. package/src/lib/createFileExtensionFilter.test.ts +0 -17
  89. package/src/lib/cwdpath.test.ts +0 -48
  90. package/src/lib/deleteDirectory.test.ts +0 -24
  91. package/src/lib/deleteDirectorySafe.test.ts +0 -40
  92. package/src/lib/deleteDirectorySafeSync.test.ts +0 -30
  93. package/src/lib/deleteDirectorySync.test.ts +0 -23
  94. package/src/lib/ensureValidWindowsPath.test.ts +0 -80
  95. package/src/lib/getDiskDrivesWindows.ts +0 -13
  96. package/src/lib/getDownloadsDirectory.ts +0 -6
  97. package/src/lib/getHomeDirectory.ts +0 -7
  98. package/src/lib/getLastMofifiedFileIn.ts +0 -15
  99. package/src/lib/getRootDir.ts +0 -5
  100. package/src/lib/isWindows.ts +0 -3
  101. package/src/lib/normalizeFileExtension.test.ts +0 -15
  102. package/src/lib/readJsonFile.test.ts +0 -34
  103. package/src/lib/readJsonFileSync.test.ts +0 -36
  104. package/src/lib/readPackageJson.ts +0 -9
  105. package/src/lib/removeIllegalFilenameCharacters.ts +0 -3
  106. package/src/lib/tempFile.ts +0 -20
  107. package/src/lib/types/IEnsureValidWindowsPathOptions.ts +0 -10
  108. package/src/lib/types/ILogFileData.ts +0 -5
  109. package/src/lib/unzipFile.ts +0 -5
  110. package/src/lib/unzipMergeFiles.ts +0 -20
  111. package/src/lib/wipeDirectorySafe.ts +0 -7
  112. package/src/lib/writeJsonFile.test.ts +0 -26
  113. package/src/lib/writeJsonFileSync.test.ts +0 -28
@@ -1,5 +1,3 @@
1
- import fs from 'fs'
2
-
3
1
  /**
4
2
  * Writes a JSON file to the specified filepath. The data to be written is passed as an argument.
5
3
  * If the 'pretty' argument is set to true, the JSON data will be formatted in a more human-readable way.
@@ -13,6 +11,5 @@ import fs from 'fs'
13
11
  * await writeJsonFile('./data.json', data, true);
14
12
  * ```
15
13
  */
16
- export async function writeJsonFile<T>(filepath: string, data: T, pretty = false): Promise<void> {
17
- await fs.promises.writeFile(filepath, JSON.stringify(data, null, pretty ? 2 : undefined))
18
- }
14
+ export declare function writeJsonFile<T>(filepath: string, data: T, pretty?: boolean): Promise<void>;
15
+ //# sourceMappingURL=writeJsonFile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"writeJsonFile.d.ts","sourceRoot":"","sources":["../../../src/lib/writeJsonFile.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;GAYG;AACH,wBAAsB,aAAa,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,UAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAE/F"}
@@ -1,5 +1,3 @@
1
- import fs from 'fs'
2
-
3
1
  /**
4
2
  * Writes a JSON object to a file synchronously.
5
3
  * @typeParam T - The type of the JSON object.
@@ -12,6 +10,5 @@ import fs from 'fs'
12
10
  * writeJsonFileSync('./data.json', data, true);
13
11
  * ```
14
12
  */
15
- export function writeJsonFileSync<T>(filepath: string, data: T, pretty = false): void {
16
- fs.writeFileSync(filepath, JSON.stringify(data, null, pretty ? 2 : undefined))
17
- }
13
+ export declare function writeJsonFileSync<T>(filepath: string, data: T, pretty?: boolean): void;
14
+ //# sourceMappingURL=writeJsonFileSync.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"writeJsonFileSync.d.ts","sourceRoot":"","sources":["../../../src/lib/writeJsonFileSync.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,UAAQ,GAAG,IAAI,CAEpF"}
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@bemoje/fs",
3
- "version": "0.0.12",
3
+ "version": "0.0.13",
4
4
  "description": "Tools for working with the local filesystem in nodejs.",
5
- "main": "src/index.ts",
5
+ "main": "dist/index.cjs.js",
6
6
  "module": "dist/index.esm.js",
7
7
  "types": "dist/types/index.d.ts",
8
8
  "scripts": {
@@ -36,4 +36,4 @@
36
36
  "devDependencies": {
37
37
  "@types/extract-zip": "^2.0.1"
38
38
  }
39
- }
39
+ }
package/src/index.ts DELETED
@@ -1,35 +0,0 @@
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'
@@ -1,25 +0,0 @@
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
- }
@@ -1,158 +0,0 @@
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
- }
@@ -1,117 +0,0 @@
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
- }
@@ -1,11 +0,0 @@
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,49 +0,0 @@
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
- })
@@ -1,21 +0,0 @@
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
- }
@@ -1,57 +0,0 @@
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,14 +0,0 @@
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,14 +0,0 @@
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,17 +0,0 @@
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
- })
@@ -1,48 +0,0 @@
1
- import path from 'path'
2
- import { cwdpath } from './cwdpath'
3
-
4
- describe(cwdpath.name, () => {
5
- const sep = path.sep
6
-
7
- describe('when the current working directory is "/home/user"', () => {
8
- beforeEach(() => {
9
- jest.spyOn(process, 'cwd').mockReturnValue('/home/user')
10
- })
11
- afterEach(() => {
12
- jest.restoreAllMocks()
13
- })
14
-
15
- it('should join the paths correctly', () => {
16
- const result = cwdpath('dir1', 'dir2', 'file.txt')
17
- expect(result).toBe(`${sep}home${sep}user${sep}dir1${sep}dir2${sep}file.txt`)
18
- })
19
- })
20
-
21
- describe('when the current working directory is "/home/user" and no paths are given', () => {
22
- beforeEach(() => {
23
- jest.spyOn(process, 'cwd').mockReturnValue('/home/user')
24
- })
25
- afterEach(() => {
26
- jest.restoreAllMocks()
27
- })
28
-
29
- it('should return the current working directory', () => {
30
- const result = cwdpath()
31
- expect(result).toBe(`${sep}home${sep}user`)
32
- })
33
- })
34
-
35
- describe('when the current working directory is "/" and the given paths are ["dir1", "dir2"]', () => {
36
- beforeEach(() => {
37
- jest.spyOn(process, 'cwd').mockReturnValue('/')
38
- })
39
- afterEach(() => {
40
- jest.restoreAllMocks()
41
- })
42
-
43
- it('should join the paths correctly', () => {
44
- const result = cwdpath('dir1', 'dir2')
45
- expect(result).toBe(`${sep}dir1${sep}dir2`)
46
- })
47
- })
48
- })
@@ -1,24 +0,0 @@
1
- import fs from 'fs'
2
- import { deleteDirectory } from './deleteDirectory'
3
-
4
- describe(deleteDirectory.name, () => {
5
- afterEach(() => {
6
- jest.restoreAllMocks()
7
- })
8
-
9
- it('should delete directory successfully', async () => {
10
- const dirpath = 'test'
11
- const rmMock = jest.spyOn(fs.promises, 'rm')
12
- await deleteDirectory(dirpath)
13
- expect(rmMock).toHaveBeenCalledWith(dirpath, { recursive: true, force: true })
14
- })
15
-
16
- it('should throw an error if the directory cannot be deleted', async () => {
17
- const dirpath = 'test'
18
- const rmMock = jest.spyOn(fs.promises, 'rm')
19
- const error = new Error('Failed to delete directory')
20
- rmMock.mockRejectedValue(error)
21
- await expect(deleteDirectory(dirpath)).rejects.toThrow(error)
22
- expect(rmMock).toHaveBeenCalledWith(dirpath, { recursive: true, force: true })
23
- })
24
- })