Created
April 30, 2025 01:04
-
-
Save akhenakh/7e77d319352ee7de19c53cd959f544d3 to your computer and use it in GitHub Desktop.
Gemini is often producing code with the pattern **`path/to/file.go`**, this is creating the files from the outputed markdown
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" | |
"log" | |
"os" | |
"path/filepath" | |
"regexp" | |
"strings" | |
) | |
// Regex to find the filename marker like **`path/to/file.go`** | |
// It captures the filename *between* the backticks. | |
// Allows letters, numbers, underscore, hyphen, dot, and forward slash in the filename. | |
var fileNameRegex = regexp.MustCompile("^\\s*\\*\\*`([a-zA-Z0-9_./-]+)`\\*\\*\\s*$") // <-- UPDATED REGEX | |
// Constants for code block markers | |
const codeBlockMarker = "```" | |
func main() { | |
// 1. Get input filename from command-line arguments | |
if len(os.Args) != 2 { | |
log.Fatalf("Usage: %s <input.md>", os.Args[0]) | |
} | |
inputFile := os.Args[1] | |
// 2. Open the markdown file | |
file, err := os.Open(inputFile) | |
if err != nil { | |
log.Fatalf("Error opening file %s: %v", inputFile, err) | |
} | |
defer file.Close() // Ensure file is closed when function exits | |
// 3. Process the file line by line | |
scanner := bufio.NewScanner(file) | |
var currentFileName string | |
var codeBlockContent strings.Builder | |
inCodeBlock := false | |
expectingCodeBlock := false | |
lineNumber := 0 | |
fmt.Printf("Processing markdown file: %s\n", inputFile) | |
for scanner.Scan() { | |
lineNumber++ | |
line := scanner.Text() | |
if inCodeBlock { | |
// Check if the current line is the closing code block marker | |
if strings.HasPrefix(strings.TrimSpace(line), codeBlockMarker) { | |
inCodeBlock = false // Exit code block state | |
// We have the filename and the code, write the file | |
err := writeFile(currentFileName, codeBlockContent.String()) | |
if err != nil { | |
log.Printf("Error writing file %s (defined near line %d): %v", currentFileName, lineNumber, err) | |
} else { | |
fmt.Printf("Successfully created file: %s\n", currentFileName) | |
} | |
// Reset state for the next potential block | |
currentFileName = "" | |
codeBlockContent.Reset() | |
} else { | |
// Add the line (plus a newline) to the content builder | |
// We add the newline because scanner.Text() strips it | |
codeBlockContent.WriteString(line) | |
codeBlockContent.WriteString("\n") | |
} | |
} else if expectingCodeBlock { | |
// We previously found a filename marker, now expect the start of a code block | |
if strings.HasPrefix(strings.TrimSpace(line), codeBlockMarker) { | |
inCodeBlock = true // Enter code block state | |
expectingCodeBlock = false // Stop expecting, we found it | |
codeBlockContent.Reset() // Ensure builder is empty | |
} else if strings.TrimSpace(line) != "" { | |
// Found something else that isn't blank after the filename marker. | |
// Assume the marker wasn't for a code block or format is unexpected. | |
// log.Printf("Warning: Found filename marker for '%s' near line %d, but the next non-blank line was not '```'. Resetting.", currentFileName, lineNumber-1) // Adjust line number | |
expectingCodeBlock = false | |
currentFileName = "" | |
// Re-evaluate this line *now* to see if it's a *new* filename marker | |
match := fileNameRegex.FindStringSubmatch(line) | |
if len(match) == 2 { | |
currentFileName = match[1] | |
expectingCodeBlock = true // Expect a code block *after this* line | |
// fmt.Printf("Found filename marker: %s (Line %d)\n", currentFileName, lineNumber) // Debug | |
} | |
} | |
// Ignore blank lines between filename marker and code block start | |
} else { | |
// Not in a code block, not expecting one. Look for a filename marker. | |
match := fileNameRegex.FindStringSubmatch(line) | |
if len(match) == 2 { // match[0] is the full string, match[1] is the first capture group | |
currentFileName = match[1] | |
expectingCodeBlock = true // Expect a code block *after this* line | |
// fmt.Printf("Found filename marker: %s (Line %d)\n", currentFileName, lineNumber) // Debug | |
} | |
// Otherwise, ignore lines that are not filename markers or part of expected blocks | |
} | |
} | |
// Check for errors during scanning | |
if err := scanner.Err(); err != nil { | |
log.Fatalf("Error reading file %s: %v", inputFile, err) | |
} | |
// Check if the file ended unexpectedly | |
if inCodeBlock { | |
log.Printf("Warning: Markdown file ended while still inside a code block for file: %s", currentFileName) | |
} | |
if expectingCodeBlock { | |
log.Printf("Warning: Found filename marker for '%s' but reached end of file before finding its code block.", currentFileName) | |
} | |
fmt.Println("Processing complete.") | |
} | |
// writeFile creates necessary directories and writes the content to the specified file. | |
// The filename is relative to the current working directory. | |
func writeFile(filename string, content string) error { | |
// Ensure filename is clean and valid for the OS | |
cleanFilename := filepath.Clean(filename) | |
// Prevent writing outside the current directory structure (basic security) | |
// Check if the cleaned path tries to go "up" directories excessively | |
// Or check if it becomes absolute | |
absPath, err := filepath.Abs(cleanFilename) | |
if err != nil { | |
return fmt.Errorf("could not determine absolute path for '%s': %w", filename, err) | |
} | |
cwd, err := os.Getwd() | |
if err != nil { | |
return fmt.Errorf("could not get current working directory: %w", err) | |
} | |
if !strings.HasPrefix(absPath, cwd) { | |
return fmt.Errorf("invalid path '%s': attempted write outside current directory tree", filename) | |
} | |
// Ensure the directory for the file exists | |
dir := filepath.Dir(cleanFilename) | |
if dir != "." && dir != "" { | |
// 0755 permissions: drwxr-xr-x (owner: rwx, group: rx, others: rx) | |
err := os.MkdirAll(dir, 0755) | |
if err != nil { | |
return fmt.Errorf("failed to create directory %s: %w", dir, err) | |
} | |
fmt.Printf("Ensured directory exists: %s\n", dir) | |
} | |
// Write the file content | |
// 0644 permissions: -rw-r--r-- (owner: rw, group: r, others: r) | |
err = os.WriteFile(cleanFilename, []byte(content), 0644) | |
if err != nil { | |
return fmt.Errorf("failed to write file %s: %w", cleanFilename, err) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment