cloving 0.3.19 → 0.3.20

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 (95) hide show
  1. package/dist/index.js +2 -0
  2. package/dist/managers/CommitManager.js +30 -16
  3. package/dist/package.json +1 -1
  4. package/package.json +1 -1
  5. package/.DS_Store +0 -0
  6. package/.aider.chat.history.md +0 -16978
  7. package/.aider.input.history +0 -15
  8. package/.aider.tags.cache.v3/cache.db +0 -0
  9. package/.aider.tags.cache.v3/cache.db-shm +0 -0
  10. package/.aider.tags.cache.v3/cache.db-wal +0 -0
  11. package/.cursorrules +0 -77
  12. package/.github/workflows/auto-release.yml +0 -83
  13. package/.github/workflows/ci.yml +0 -32
  14. package/.github/workflows/npm-publish.yml +0 -34
  15. package/.gitignore +0 -67
  16. package/.husky/_/.gitignore +0 -1
  17. package/.husky/_/applypatch-msg +0 -2
  18. package/.husky/_/commit-msg +0 -2
  19. package/.husky/_/h +0 -22
  20. package/.husky/_/husky.sh +0 -9
  21. package/.husky/_/post-applypatch +0 -2
  22. package/.husky/_/post-checkout +0 -2
  23. package/.husky/_/post-commit +0 -2
  24. package/.husky/_/post-merge +0 -2
  25. package/.husky/_/post-rewrite +0 -2
  26. package/.husky/_/pre-applypatch +0 -2
  27. package/.husky/_/pre-auto-gc +0 -2
  28. package/.husky/_/pre-commit +0 -2
  29. package/.husky/_/pre-merge-commit +0 -2
  30. package/.husky/_/pre-push +0 -2
  31. package/.husky/_/pre-rebase +0 -2
  32. package/.husky/_/prepare-commit-msg +0 -2
  33. package/.husky/pre-commit +0 -1
  34. package/.husky/pre-push +0 -1
  35. package/.prettierrc.json +0 -7
  36. package/.tool-versions +0 -2
  37. package/SECURITY.md +0 -15
  38. package/cloving.json +0 -67
  39. package/jest.config.js +0 -11
  40. package/src/cloving_gpt/adapters/azureopenai.ts +0 -83
  41. package/src/cloving_gpt/adapters/claude.ts +0 -140
  42. package/src/cloving_gpt/adapters/gemini.ts +0 -146
  43. package/src/cloving_gpt/adapters/index.ts +0 -43
  44. package/src/cloving_gpt/adapters/mistral.ts +0 -142
  45. package/src/cloving_gpt/adapters/ollama.ts +0 -136
  46. package/src/cloving_gpt/adapters/openai.ts +0 -113
  47. package/src/cloving_gpt/index.ts +0 -229
  48. package/src/commands/chat.ts +0 -12
  49. package/src/commands/config.ts +0 -192
  50. package/src/commands/generate/code.ts +0 -18
  51. package/src/commands/generate/commit.ts +0 -9
  52. package/src/commands/generate/context.ts +0 -93
  53. package/src/commands/generate/docs.ts +0 -9
  54. package/src/commands/generate/review.ts +0 -9
  55. package/src/commands/generate/shell.ts +0 -9
  56. package/src/commands/generate/unit_tests.ts +0 -9
  57. package/src/commands/init.ts +0 -9
  58. package/src/commands/models.ts +0 -21
  59. package/src/commands/proxy.ts +0 -9
  60. package/src/commands/tokens.ts +0 -82
  61. package/src/index.ts +0 -197
  62. package/src/managers/BlockManager.ts +0 -126
  63. package/src/managers/ChatManager.ts +0 -755
  64. package/src/managers/ChunkManager.ts +0 -31
  65. package/src/managers/CodeManager.ts +0 -226
  66. package/src/managers/CommitManager.ts +0 -71
  67. package/src/managers/DocsManager.ts +0 -101
  68. package/src/managers/InitManager.ts +0 -263
  69. package/src/managers/ProxyManager.ts +0 -240
  70. package/src/managers/ReviewManager.ts +0 -154
  71. package/src/managers/ShellManager.ts +0 -172
  72. package/src/managers/StreamManager.ts +0 -353
  73. package/src/managers/UnitTestManager.ts +0 -293
  74. package/src/utils/config_utils.ts +0 -271
  75. package/src/utils/git_utils.ts +0 -230
  76. package/src/utils/model_utils.ts +0 -3
  77. package/src/utils/prompt_utils.ts +0 -375
  78. package/src/utils/prompts/CODEGEN_COULDNT_APPLY.md +0 -5
  79. package/src/utils/prompts/CODEGEN_EXAMPLES.md +0 -82
  80. package/src/utils/prompts/CODEGEN_INSTRUCTIONS.md +0 -43
  81. package/src/utils/prompts/DOCS_INSTRUCTIONS.md +0 -9
  82. package/src/utils/prompts/INIT_INSTRUCTIONS.md +0 -132
  83. package/src/utils/prompts/REVIEW_INSTRUCTIONS.md +0 -49
  84. package/src/utils/prompts/SHELL_INSTRUCTIONS.md +0 -15
  85. package/src/utils/prompts/SPECIAL_FILES.md +0 -66
  86. package/src/utils/prompts/index.ts +0 -37
  87. package/src/utils/string_utils.ts +0 -552
  88. package/src/utils/types.ts +0 -127
  89. package/tests/commands/generate/unit_tests.test.ts +0 -27
  90. package/tests/utils/git_utils.test.ts +0 -116
  91. package/tests/utils/model_utils.test.ts +0 -27
  92. package/tests/utils/prompt_utils.test.ts +0 -33
  93. package/tests/utils/string_utils.test.ts +0 -560
  94. package/tsconfig.json +0 -14
  95. package/yarn.lock +0 -5823
@@ -1,15 +0,0 @@
1
- # Shell Script Instructions
2
-
3
- Generate an executable script that works on the current operating system. Try to make it a single line if possible and as simple and straightforward as possible.
4
-
5
- Do not add any commentary or context to the message other than the commit message itself.
6
-
7
- ## Example
8
-
9
- An example of the output for this should look like the following:
10
-
11
- ```sh
12
- find . -type f -name "*.ts" -exec sed -i '' 's/old/new/g' {} +
13
- ```
14
-
15
- Don't use that script, it is only an example.
@@ -1,66 +0,0 @@
1
- # Special Files
2
-
3
- The following is a list of special files recognized by the system:
4
-
5
- - package.json
6
- - Gemfile
7
- - requirements.txt
8
- - Pipfile
9
- - pyproject.toml
10
- - pom.xml
11
- - build.gradle
12
- - .csproj
13
- - packages.config
14
- - composer.json
15
- - CMakeLists.txt
16
- - conanfile.txt
17
- - conanfile.py
18
- - go.mod
19
- - Cargo.toml
20
- - Package.swift
21
- - build.gradle.kts
22
- - Podfile
23
- - Cartfile
24
- - cpanfile
25
- - DESCRIPTION
26
- - mix.exs
27
- - build.sbt
28
- - pubspec.yaml
29
- - stack.yaml
30
- - top.sls
31
- - requirements.yml
32
- - terraform.tf
33
- - versions.tf
34
- - main.yml
35
- - cabal.project
36
- - Project.toml
37
- - rockspec
38
- - rebar.config
39
- - project.clj
40
- - tsconfig.json
41
- - .eslintrc.js
42
- - .eslintrc.json
43
- - .eslintrc.yaml
44
- - .eslintrc.yml
45
- - .eslintrc
46
- - .prettierrc
47
- - .prettierrc.js
48
- - .prettierrc.json
49
- - .prettierrc.yaml
50
- - .prettierrc.yml
51
- - .prettierrc
52
- - .stylelintrc
53
- - .stylelintrc.json
54
- - .stylelintrc.yaml
55
- - .stylelintrc.yml
56
- - .stylelintrc
57
- - jest.config.js
58
- - jest.config.json
59
- - jest.config.ts
60
- - jest.config.cjs
61
- - jest.config.mjs
62
- - webpack.config.js
63
- - webpack.config.ts
64
- - webpack.config.cjs
65
- - webpack.config.mjs
66
- - webpack.config.common.js
@@ -1,37 +0,0 @@
1
- import fs from 'fs'
2
- import path from 'path'
3
-
4
- const CODEGEN_COULDNT_APPLY = fs.readFileSync(
5
- path.resolve(__dirname, 'CODEGEN_COULDNT_APPLY.md'),
6
- 'utf-8',
7
- )
8
- const CODEGEN_INSTRUCTIONS = fs.readFileSync(
9
- path.resolve(__dirname, 'CODEGEN_INSTRUCTIONS.md'),
10
- 'utf-8',
11
- )
12
- const CODEGEN_EXAMPLES = fs.readFileSync(path.resolve(__dirname, 'CODEGEN_EXAMPLES.md'), 'utf-8')
13
- const SHELL_INSTRUCTIONS = fs.readFileSync(
14
- path.resolve(__dirname, 'SHELL_INSTRUCTIONS.md'),
15
- 'utf-8',
16
- )
17
- const REVIEW_INSTRUCTIONS = fs.readFileSync(
18
- path.resolve(__dirname, 'REVIEW_INSTRUCTIONS.md'),
19
- 'utf-8',
20
- )
21
- const DOCS_INSTRUCTIONS = fs.readFileSync(path.resolve(__dirname, 'DOCS_INSTRUCTIONS.md'), 'utf-8')
22
- const INIT_INSTRUCTIONS = fs.readFileSync(path.resolve(__dirname, 'INIT_INSTRUCTIONS.md'), 'utf-8')
23
- const SPECIAL_FILES_PATH = fs.readFileSync(path.resolve(__dirname, 'SPECIAL_FILES.md'), 'utf-8')
24
- const SPECIAL_FILES = SPECIAL_FILES_PATH.split('\n')
25
- .filter((line) => line.startsWith('- '))
26
- .map((line) => line.slice(2).trim())
27
-
28
- export {
29
- SHELL_INSTRUCTIONS,
30
- CODEGEN_INSTRUCTIONS,
31
- CODEGEN_COULDNT_APPLY,
32
- DOCS_INSTRUCTIONS,
33
- INIT_INSTRUCTIONS,
34
- SPECIAL_FILES,
35
- CODEGEN_EXAMPLES,
36
- REVIEW_INSTRUCTIONS,
37
- }
@@ -1,552 +0,0 @@
1
- import fs from 'fs'
2
- import path from 'path'
3
- import colors from 'colors'
4
-
5
- import type { BlockIndices, CurrentNewBlock } from './types'
6
-
7
- const BLOCK_START = '\n```'
8
- const BLOCK_CURRENT = '\n<<<<<<< CURRENT'
9
- const BLOCK_DIVIDER = '\n======='
10
- const BLOCK_END = '\n>>>>>>> NEW\n```'
11
-
12
- // Function to estimate token count
13
- export const estimateTokens = async (text: string): Promise<number> => {
14
- const charCount = text.length
15
- const tokenCount = Math.ceil(charCount / 4)
16
- return tokenCount
17
- }
18
-
19
- /**
20
- * Extracts JSON metadata from an AI response string.
21
- *
22
- * This function attempts to extract a valid JSON string from the given response.
23
- * It handles responses that may contain the JSON within a code block or as plain text.
24
- *
25
- * The function performs the following steps:
26
- * 1. Looks for a ```json code block and extracts its content if found.
27
- * 2. If no code block is found, it treats the entire response as potential JSON.
28
- * 3. Trims the extracted string to remove leading/trailing whitespace.
29
- * 4. Removes any text before the first '{' and after the last '}'.
30
- *
31
- * @param {string} response - The AI response string that may contain JSON metadata.
32
- * @returns {string} A string containing only the JSON part of the response.
33
- * If no valid JSON structure is found, it may return an empty string
34
- * or a partial JSON string.
35
- *
36
- * @example
37
- * const aiResponse = '```json\n{"key": "value"}\n```\nOther text'
38
- * const jsonMetadata = extractJsonMetadata(aiResponse)
39
- * // jsonMetadata will be '{"key": "value"}'
40
- *
41
- * @example
42
- * const plainResponse = 'Some text {"key": "value"} more text'
43
- * const jsonMetadata = extractJsonMetadata(plainResponse)
44
- * // jsonMetadata will be '{"key": "value"}'
45
- */
46
- export const extractJsonMetadata = (response: string): string => {
47
- let jsonString: string
48
-
49
- // Extract the ```json block from the response
50
- const jsonBlockStart = response.indexOf('```json')
51
- const jsonBlockEnd = response.indexOf('```', jsonBlockStart + 6)
52
-
53
- if (jsonBlockStart !== -1 && jsonBlockEnd !== -1) {
54
- jsonString = response.substring(jsonBlockStart + 6, jsonBlockEnd).trim()
55
- } else {
56
- jsonString = response
57
- }
58
-
59
- // Remove any data before the first '{'
60
- const jsonStartIndex = jsonString.indexOf('{')
61
- if (jsonStartIndex !== -1) {
62
- jsonString = jsonString.substring(jsonStartIndex)
63
- }
64
-
65
- // Remove any data after the last '}'
66
- const jsonEndIndex = jsonString.lastIndexOf('}')
67
- if (jsonEndIndex !== -1) {
68
- jsonString = jsonString.substring(0, jsonEndIndex + 1)
69
- }
70
-
71
- // sanity check that the extracted string is valid JSON
72
- try {
73
- JSON.parse(jsonString)
74
- } catch (error) {
75
- jsonString = ''
76
- }
77
-
78
- return jsonString
79
- }
80
-
81
- /**
82
- * Extracts markdown content from a given response string.
83
- *
84
- * This function attempts to extract markdown content from the input string,
85
- * focusing on content within code blocks and removing any surrounding metadata.
86
- *
87
- * @param {string} response - The input string containing markdown and possibly other content.
88
- * @returns {string} The extracted markdown content.
89
- *
90
- * @example
91
- * const response = '```markdown\n# Title\nContent\n```\nOther text';
92
- * const markdown = extractMarkdown(response);
93
- * console.log(markdown); // Outputs: "# Title\nContent"
94
- */
95
- export const extractMarkdown = (response: string): string => {
96
- let markdownString = response
97
-
98
- // Regular expression to match any ```<word> block
99
- const codeBlockRegex = /```(\w+)\s*([\s\S]*?)\s*```/g
100
-
101
- let match
102
- while ((match = codeBlockRegex.exec(response)) !== null) {
103
- // Extract the content inside the code block
104
- const [, , content] = match
105
- markdownString = content.trim()
106
- }
107
-
108
- // Remove any data before the first '#'
109
- const jsonStartIndex = markdownString.indexOf('#')
110
- if (jsonStartIndex !== -1) {
111
- markdownString = markdownString.substring(jsonStartIndex)
112
- }
113
-
114
- // Remove the last ``` if it exists
115
- if (markdownString.endsWith('```')) {
116
- markdownString = markdownString.substring(0, markdownString.length - 3)
117
- }
118
-
119
- return markdownString
120
- }
121
-
122
- /**
123
- * Parses markdown instructions into separate blocks.
124
- *
125
- * This function takes a string input containing markdown instructions and
126
- * separates it into an array of strings, where each string represents a
127
- * distinct block of content (either a code block or a text block).
128
- *
129
- * @param {string} input - The input string containing markdown instructions.
130
- * @returns {string[]} An array of strings, each representing a distinct block of content.
131
- *
132
- * @example
133
- * const input = "# Title\n```js\nconst x = 1;\n```\nSome text";
134
- * const blocks = parseMarkdownInstructions(input);
135
- * console.log(blocks);
136
- * // Outputs: ["# Title", "```js\nconst x = 1;\n```", "Some text"]
137
- */
138
- export const parseMarkdownInstructions = (input: string): string[] => {
139
- const lines = input.split('\n')
140
- const result: string[] = []
141
- let buffer: string[] = []
142
- let inCodeBlock = false
143
-
144
- lines.forEach((line) => {
145
- if (line.trim().startsWith('```')) {
146
- if (inCodeBlock) {
147
- // End of code block
148
- buffer.push(line)
149
- result.push(buffer.join('\n'))
150
- buffer = []
151
- inCodeBlock = false
152
- } else {
153
- // Start of code block
154
- if (buffer.length > 0) {
155
- result.push(buffer.join('\n'))
156
- buffer = []
157
- }
158
- buffer.push(line)
159
- inCodeBlock = true
160
- }
161
- } else {
162
- buffer.push(line)
163
- }
164
- })
165
-
166
- // If buffer has any remaining lines, add them to the result
167
- if (buffer.length > 0) {
168
- result.push(buffer.join('\n'))
169
- }
170
-
171
- return result
172
- }
173
-
174
- /**
175
- * Finds the indices of a CURRENT/NEW block within the input string.
176
- *
177
- * This function searches for the start, divider, and end markers of a CURRENT/NEW block
178
- * in the input string, starting from the given index. It returns the indices of these
179
- * markers if a complete block is found.
180
- *
181
- * @param {string} input - The input string to search for block indices.
182
- * @param {number} startIndex - The index in the input string to start searching from.
183
- * @returns {BlockIndices | null} An object containing the indices of the block components,
184
- * or null if a complete block is not found.
185
- */
186
- export const findBlockIndices = (input: string, startIndex: number): BlockIndices | null => {
187
- const blockStart = input.indexOf(BLOCK_START, startIndex)
188
- if (blockStart === -1) return null
189
-
190
- const languageStart = blockStart + BLOCK_START.length
191
- const languageEnd = input.indexOf('\n', languageStart)
192
- if (languageEnd === -1) return null
193
-
194
- const currentStart = input.indexOf(BLOCK_CURRENT, startIndex)
195
- const filePathStart = currentStart + BLOCK_CURRENT.length
196
- const filePathEnd = input.indexOf('\n', filePathStart)
197
- const dividerIndex = input.indexOf(BLOCK_DIVIDER, filePathEnd)
198
- if (dividerIndex === -1) return null
199
-
200
- const blockEnd = input.indexOf(BLOCK_END, dividerIndex)
201
- if (blockEnd === -1) return null
202
-
203
- return {
204
- start: languageStart,
205
- current: currentStart,
206
- filePathEnd,
207
- divider: dividerIndex,
208
- end: blockEnd,
209
- }
210
- }
211
-
212
- /**
213
- * Extracts the content of a CURRENT/NEW block using the provided indices.
214
- *
215
- * This function takes the input string and a set of block indices, and extracts
216
- * the file path, current content, and new content from the block.
217
- *
218
- * @param {string} input - The input string containing the CURRENT/NEW block.
219
- * @param {BlockIndices} indices - An object containing the indices of the block components.
220
- * @returns {CurrentNewBlock} An object containing the extracted file path, current content, and new content.
221
- */
222
- export const extractBlock = (input: string, indices: BlockIndices): CurrentNewBlock => {
223
- const language = input.slice(indices.start, indices.current).trim()
224
- const filePath = input.slice(indices.current + BLOCK_CURRENT.length, indices.filePathEnd).trim()
225
- const currentContent = input.slice(indices.filePathEnd + 1, indices.divider).trim()
226
- const newContent = input.slice(indices.divider + BLOCK_DIVIDER.length, indices.end).trim()
227
-
228
- return { language, filePath, currentContent, newContent }
229
- }
230
-
231
- /**
232
- * Extracts CURRENT/NEW blocks from the given input string.
233
- *
234
- * This function parses the input string to find and extract all CURRENT/NEW blocks.
235
- * Each block contains information about file paths, current content, and new content.
236
- *
237
- * The blocks are defined by specific delimiters:
238
- * - Setup: '```lang'
239
- * - Start: '<<<<<<< CURRENT'
240
- * - Divider: '======='
241
- * - End: '>>>>>>> NEW'
242
- * - Finish: '```'
243
- *
244
- * @param {string} [input] - The input string containing CURRENT/NEW blocks.
245
- * @returns {CurrentNewBlock[]} An array of CurrentNewBlock objects, each representing a parsed block.
246
- * If the input is undefined or empty, an empty array is returned.
247
- *
248
- * @example
249
- * const input = "
250
- * ```typescript
251
- * <<<<<<< CURRENT path/to/file.ts
252
- * const oldCode = 'old'
253
- * =======
254
- * const newCode = 'new'
255
- * >>>>>>> NEW
256
- * ```"
257
- * const blocks = extractCurrentNewBlocks(input)
258
- * // blocks will contain one CurrentNewBlock object with the parsed information
259
- */
260
-
261
- export const extractCurrentNewBlocks = (input?: string): CurrentNewBlock[] => {
262
- if (!input) return []
263
-
264
- const blocks: CurrentNewBlock[] = []
265
- let currentIndex = 0
266
-
267
- while (currentIndex < input.length) {
268
- const indices = findBlockIndices(input, currentIndex)
269
- if (!indices) break
270
-
271
- blocks.push(extractBlock(input, indices))
272
- currentIndex = indices.end + BLOCK_END.length
273
- }
274
-
275
- return blocks
276
- }
277
-
278
- const readFileContent = async (filePath: string): Promise<string> => {
279
- try {
280
- return await fs.promises.readFile(filePath, 'utf-8')
281
- } catch (error) {
282
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
283
- return ''
284
- }
285
- throw error
286
- }
287
- }
288
-
289
- export const ensureDirectoryExists = async (filePath: string): Promise<void> => {
290
- await fs.promises.mkdir(path.dirname(filePath), { recursive: true })
291
- }
292
-
293
- export const writeFileContent = async (filePath: string, content: string): Promise<void> => {
294
- await ensureDirectoryExists(filePath)
295
- await fs.promises.writeFile(filePath, content)
296
- }
297
-
298
- /**
299
- * Updates the content of a file by replacing a specified block of current content with new content.
300
- *
301
- * This function searches for the `currentContent` within the `currentContent` of the file.
302
- * If found, it replaces it with the `newContent` from the `block`, preserving the indentation
303
- * level of the original content.
304
- *
305
- * @param {string} currentContent - The existing content of the file.
306
- * @param {CurrentNewBlock} block - An object containing the current and new content to be replaced.
307
- * @returns {string} The updated file content with the specified block replaced.
308
- *
309
- * @example
310
- * const currentContent = `
311
- * function example() {
312
- * console.log('Old content')
313
- * }
314
- * `
315
- * const block = {
316
- * currentContent: "console.log('Old content')",
317
- * newContent: "console.log('New content')"
318
- * }
319
- * const updatedContent = searchReplaceString(currentContent, block)
320
- * // updatedContent will be:
321
- * // function example() {
322
- * // console.log('New content')
323
- * // }
324
- */
325
- export const searchReplaceString = (currentContent: string, block: CurrentNewBlock): string => {
326
- // 1) if block.currentContent.trim() is empty then return block.newContent
327
- if (block.currentContent.trim() === '') {
328
- return block.newContent
329
- }
330
-
331
- // check if you can replace the entire block without changing indentation
332
- if (currentContent.includes(block.currentContent)) {
333
- return currentContent.replace(block.currentContent, block.newContent)
334
- }
335
-
336
- // 2) split currentContent and block.currentContent into new lines and trim() all the lines, then put back the new lines
337
- const currentLines = currentContent.split('\n').map((line) => line.trim())
338
- const blockLines = block.currentContent.split('\n').map((line) => line.trim())
339
-
340
- // 3) see if the trimmed block.currentContent matches a section of code in the trimmed currentContent
341
- const blockContent = blockLines.join('\n')
342
- const currentContentTrimmed = currentLines.join('\n')
343
-
344
- // 4) if so, make a variable named matchingLine with the line number of which line the block.currentContent starts on in currentContent
345
- const matchingLine = currentContentTrimmed.indexOf(blockContent)
346
- if (matchingLine === -1) {
347
- return currentContent // If no match is found, return the original content
348
- }
349
-
350
- // 5) compare the first line of block.currentContent with the startLine line of currentContent, putting any preceeding spaces that are in currentContent but not in block.currentContent into a variable named preceedingSpaces
351
- const startLine = currentContent.split('\n').findIndex((line) => line.includes(blockLines[0]))
352
- if (startLine === -1) {
353
- return currentContent // If no match is found, return the original content
354
- }
355
- const startLineContent = currentContent.split('\n')[startLine]
356
- const blockLineContent = block.currentContent.split('\n')[0]
357
- const precedingSpaces = startLineContent.replace(blockLineContent, '')
358
-
359
- // 6) add preceedingSpaces to the start of each line in both block.currentContent and block.newContent
360
- if (precedingSpaces) {
361
- const indentedCurrentContent = block.currentContent
362
- .split('\n')
363
- .map((line) => precedingSpaces + line)
364
- .join('\n')
365
- const indentedNewContent = block.newContent
366
- .split('\n')
367
- .map((line) => precedingSpaces + line)
368
- .join('\n')
369
- // 7) finally, do a simple currentContent.replace(block.currentContent, block.newContent) with the modified (added preceeding spaces to match) variables
370
- return currentContent.replace(indentedCurrentContent, indentedNewContent)
371
- } else {
372
- return currentContent.replace(block.currentContent, block.newContent)
373
- }
374
- }
375
-
376
- /**
377
- * Analyzes the content of a block against the file content to find matching lines.
378
- *
379
- * This function compares the trimmed content of a block with the trimmed content of a file
380
- * to identify all occurrences of the block content within the file.
381
- *
382
- * @param {CurrentNewBlock} block - The block containing the content to be searched for.
383
- * @param {string} fileContent - The content of the file to be analyzed.
384
- * @returns {Promise<{ matchingLines: number[]; currentContentTrimmed: string }>} A promise that resolves to an object containing:
385
- * - matchingLines: An array of line numbers where the block content matches in the file.
386
- * - currentContentTrimmed: The trimmed content of the file.
387
- */
388
- const analyzeBlockContent = async (
389
- block: CurrentNewBlock,
390
- fileContent: string,
391
- ): Promise<{ matchingLines: number[]; currentContentTrimmed: string }> => {
392
- const currentLines = fileContent.split('\n').map((line) => line.trim())
393
- const blockLines = block.currentContent.split('\n').map((line) => line.trim())
394
-
395
- const blockContent = blockLines.join('\n')
396
- const currentContentTrimmed = currentLines.join('\n')
397
- const matchingLines = []
398
- let matchingLine = -1
399
-
400
- while ((matchingLine = currentContentTrimmed.indexOf(blockContent, matchingLine + 1)) !== -1) {
401
- matchingLines.push(matchingLine)
402
- }
403
-
404
- return { matchingLines, currentContentTrimmed }
405
- }
406
-
407
- /**
408
- * Processes a single block by applying its changes to the corresponding file.
409
- *
410
- * This function handles the following scenarios:
411
- * 1. Creating a new file if it doesn't exist.
412
- * 2. Updating an existing file if the block's current content matches exactly once.
413
- * 3. Logging errors if the current content is not found or matches multiple times.
414
- *
415
- * @param {CurrentNewBlock} block - The block containing the changes to be applied.
416
- * @param {number} index - The index of the block being processed (used for logging).
417
- * @returns {Promise<void>} A promise that resolves when the block has been processed.
418
- */
419
- export const applyAndSaveBlock = async (block: CurrentNewBlock, index: number): Promise<void> => {
420
- const filePath = path.resolve(block.filePath)
421
- let fileContent = await readFileContent(filePath)
422
-
423
- if (fileContent === '') {
424
- await writeFileContent(filePath, block.newContent)
425
- console.log(
426
- `[${index + 1}] ${colors.green.bold(block.filePath)} has been ${colors.green.bold('created')}`,
427
- )
428
- return
429
- }
430
-
431
- const { matchingLines } = await analyzeBlockContent(block, fileContent)
432
-
433
- if (matchingLines.length === 0) {
434
- console.log(
435
- `[${index + 1}] ${colors.red.bold(block.filePath)} ${colors.red.bold('ERROR: Current content not found to replace in the file')}`,
436
- )
437
- return
438
- } else if (matchingLines.length > 1) {
439
- console.log(
440
- `[${index + 1}] ${colors.red.bold(block.filePath)} ${colors.red.bold(`ERROR: Current content matches multiple (${matchingLines.length}) parts in the file`)}`,
441
- )
442
- return
443
- }
444
-
445
- const updatedContent = searchReplaceString(fileContent, block)
446
- await writeFileContent(filePath, updatedContent)
447
- console.log(
448
- `[${index + 1}] ${colors.green.bold(block.filePath)} has been ${colors.yellow.bold('updated')}`,
449
- )
450
- }
451
-
452
- /**
453
- * Applies and saves the changes specified in the CurrentNewBlock array.
454
- *
455
- * This function iterates through an array of CurrentNewBlock objects, each representing
456
- * a change to be made to a file. For each block, it attempts to process the change
457
- * by either creating a new file, updating an existing file, or reporting an error
458
- * if the current content doesn't match.
459
- *
460
- * The function provides console output to inform the user about the status of each
461
- * file operation (created, updated, or error).
462
- *
463
- * @param {CurrentNewBlock[]} blocks - An array of CurrentNewBlock objects representing the changes to be applied.
464
- * @returns {Promise<void>} A promise that resolves when all blocks have been processed.
465
- *
466
- * @throws Will log errors to the console if any block processing fails, but won't stop execution for other blocks.
467
- *
468
- * @example
469
- * const blocks = [
470
- * { filePath: 'path/to/file.ts', currentContent: 'old code', newContent: 'new code' },
471
- * { filePath: 'path/to/newfile.ts', currentContent: '', newContent: 'new file content' }
472
- * ]
473
- * await applyAndSaveCurrentNewBlocks(blocks)
474
- */
475
- export const applyAndSaveCurrentNewBlocks = async (blocks: CurrentNewBlock[]): Promise<void> => {
476
- console.log(`\nApplying and saving current/new blocks...\n`)
477
-
478
- for (const [index, block] of blocks.entries()) {
479
- try {
480
- await applyAndSaveBlock(block, index)
481
- } catch (error) {
482
- console.error(`Error processing ${colors.red(block.filePath)}:`, error)
483
- }
484
- }
485
- }
486
-
487
- /**
488
- * Checks if all the blocks can be applied without making any changes.
489
- *
490
- * This function iterates through an array of CurrentNewBlock objects and checks
491
- * if each block can be applied to its respective file. It returns a tuple where
492
- * the first element is a boolean indicating if all blocks can be applied, and
493
- * the second element is a string summarizing the success or failure of each block.
494
- *
495
- * @param {CurrentNewBlock[]} blocks - An array of CurrentNewBlock objects to be checked.
496
- * @returns {Promise<[boolean, string]>} A promise that resolves to a tuple containing
497
- * a boolean and a summary string.
498
- *
499
- * @example
500
- * const blocks = [
501
- * { filePath: 'path/to/file.ts', currentContent: 'old code', newContent: 'new code' },
502
- * { filePath: 'path/to/newfile.ts', currentContent: '', newContent: 'new file content' }
503
- * ]
504
- * const [canApply, summary] = await checkBlocksApplicability(blocks)
505
- */
506
- export const checkBlocksApplicability = async (
507
- blocks: CurrentNewBlock[],
508
- ): Promise<[boolean, string]> => {
509
- let allApplicable = true
510
- const summary: string[] = []
511
-
512
- for (const [index, block] of blocks.entries()) {
513
- const filePath = path.resolve(block.filePath)
514
- let fileContent = await readFileContent(filePath)
515
-
516
- if (block.newContent.trim() === '') {
517
- allApplicable = false
518
- summary.push(
519
- `[${index + 1}] ${colors.red.bold(block.filePath)} ${colors.red.bold('cannot be applied: New content is empty')}`,
520
- )
521
- } else if (fileContent === '') {
522
- summary.push(
523
- `[${index + 1}] ${colors.green.bold(block.filePath)} can be ${colors.green.bold('created')}`,
524
- )
525
- } else if (block.currentContent.trim() === '') {
526
- allApplicable = false
527
- summary.push(
528
- `[${index + 1}] ${colors.red.bold(block.filePath)} ${colors.red.bold(`cannot be applied: File '${block.filePath}' already exists`)}`,
529
- )
530
- } else {
531
- const { matchingLines } = await analyzeBlockContent(block, fileContent)
532
-
533
- if (matchingLines.length === 0) {
534
- allApplicable = false
535
- summary.push(
536
- `[${index + 1}] ${colors.red.bold(block.filePath)} ${colors.red.bold('cannot be applied: Current content not found')}`,
537
- )
538
- } else if (matchingLines.length > 1) {
539
- allApplicable = false
540
- summary.push(
541
- `[${index + 1}] ${colors.red.bold(block.filePath)} ${colors.red.bold(`cannot be applied: Current content matches multiple (${matchingLines.length}) parts in the file`)}`,
542
- )
543
- } else {
544
- summary.push(
545
- `[${index + 1}] ${colors.green.bold(block.filePath)} can be ${colors.yellow.bold('updated')}`,
546
- )
547
- }
548
- }
549
- }
550
-
551
- return [allApplicable, summary.join('\n')]
552
- }