Created
October 20, 2024 01:46
-
-
Save angeloevangelista/5a9c4818876f1123735a5171a9a9ed41 to your computer and use it in GitHub Desktop.
Split GoLang file methods into new files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import fs from 'fs'; | |
| import path from 'path'; | |
| const rootPath = "/Users/angelo/www/my-app" | |
| const contextRelativePath = "pkg/some_package" | |
| const fileName = "file_name.go" | |
| const fileLines = fs | |
| .readFileSync(path.join(rootPath, contextRelativePath, fileName)) | |
| .toString() | |
| .trim() | |
| .split("\n"); | |
| const indexOfFirstOption = fileLines.findIndex(line => line.includes("func ")); | |
| const commonHeader = fileLines.slice(0, indexOfFirstOption).join("\n") | |
| const indexesOfFunctionsDeclarations = fileLines.reduce( | |
| (acc, next, index) => { | |
| if (next.includes("func ")) { | |
| acc.push(index); | |
| } | |
| return acc; | |
| }, | |
| [], | |
| ); | |
| const methods = indexesOfFunctionsDeclarations.reduce( | |
| (acc, declarationStartIndex) => { | |
| let scopeLevel = 0 | |
| let foundAtLeastOneScope = false | |
| const methodPossibleSlice = fileLines.slice(declarationStartIndex); | |
| const methodName = fileLines[declarationStartIndex].match( | |
| /func\s+(\([\w\s\*\d]+\)\s+)?(\w+)\s*\(/, | |
| )[2]; | |
| for (let i = 0; i < methodPossibleSlice.length; i++) { | |
| const sliceLine = methodPossibleSlice[i]; | |
| scopeLevel += (sliceLine.match(/{/g) || []).length; | |
| scopeLevel -= (sliceLine.match(/}/g) || []).length; | |
| if (!foundAtLeastOneScope) { | |
| foundAtLeastOneScope = (sliceLine.match(/{/g) || []).length > 0 | |
| } | |
| if (scopeLevel === 0 && foundAtLeastOneScope) { | |
| acc.push( | |
| { | |
| name: methodName, | |
| file_name: (() => { | |
| let as_snake = methodName | |
| .replace(/([A-Z])/g, " $1") | |
| .split(' ') | |
| .join('_') | |
| .toLowerCase(); | |
| if (as_snake[0] === "_") { | |
| as_snake = as_snake.slice(1); | |
| } | |
| return as_snake | |
| })() + ".go", | |
| content: [ | |
| commonHeader, | |
| fileLines.slice( | |
| declarationStartIndex, | |
| declarationStartIndex + i + 1, | |
| ).join("\n") | |
| ].join("\n"), | |
| } | |
| ); | |
| break | |
| } | |
| } | |
| return acc | |
| }, | |
| [], | |
| ) | |
| methods.forEach(method => { | |
| fs.writeFileSync( | |
| path.join(rootPath, contextRelativePath, method.file_name), | |
| method.content, | |
| ) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment