Created
December 11, 2024 14:51
-
-
Save foufrix/d1a3425121c1978a5c7de9270e2e67f1 to your computer and use it in GitHub Desktop.
solidity flattener
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
package main | |
import ( | |
"bufio" | |
"fmt" | |
"io/ioutil" | |
"os" | |
"path/filepath" | |
"regexp" | |
"strings" | |
) | |
func main() { | |
if len(os.Args) != 2 { | |
fmt.Println("Usage: go run flattener.go <folder_path>") | |
return | |
} | |
folderPath := os.Args[1] | |
imports := make(map[string]string) | |
// Find all Solidity files | |
var solidityFiles []string | |
err := filepath.Walk(folderPath, func(path string, info os.FileInfo, err error) error { | |
if err != nil { | |
return err | |
} | |
if !info.IsDir() && strings.HasSuffix(path, ".sol") { | |
solidityFiles = append(solidityFiles, path) | |
} | |
return nil | |
}) | |
if err != nil { | |
fmt.Printf("Error walking folder: %v\n", err) | |
return | |
} | |
// Create output file | |
outputFile, err := os.Create("flattened.sol") | |
if err != nil { | |
fmt.Printf("Error creating output file: %v\n", err) | |
return | |
} | |
defer outputFile.Close() | |
writer := bufio.NewWriter(outputFile) | |
pragmaWritten := false | |
// Process each file | |
for _, file := range solidityFiles { | |
content, err := ioutil.ReadFile(file) | |
if err != nil { | |
fmt.Printf("Error reading file %s: %v\n", file, err) | |
continue | |
} | |
lines := strings.Split(string(content), "\n") | |
for _, line := range lines { | |
line = strings.TrimSpace(line) | |
// Handle pragma only once | |
if strings.HasPrefix(line, "pragma") { | |
if !pragmaWritten { | |
writer.WriteString(line + "\n") | |
pragmaWritten = true | |
} | |
continue | |
} | |
// Skip import statements | |
if strings.HasPrefix(line, "import") { | |
importPath := extractImportPath(line) | |
if importPath != "" { | |
imports[importPath] = line | |
} | |
continue | |
} | |
// Write other lines | |
if line != "" { | |
writer.WriteString(line + "\n") | |
} | |
} | |
} | |
writer.Flush() | |
fmt.Println("Flattening complete. Output written to flattened.sol") | |
} | |
func extractImportPath(line string) string { | |
re := regexp.MustCompile(`"([^"]*)"`) | |
matches := re.FindStringSubmatch(line) | |
if len(matches) > 1 { | |
return matches[1] | |
} | |
return "" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment