|
| 1 | +package problems |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + "regexp" |
| 8 | + "strings" |
| 9 | +) |
| 10 | + |
| 11 | +type rehearsalEntry struct { |
| 12 | + Name string |
| 13 | + TestFileName string |
| 14 | + SolutionFileName string |
| 15 | +} |
| 16 | + |
| 17 | +func (r *rehearsalEntry) String() string { |
| 18 | + return fmt.Sprintf("### %s\n", r.Name) |
| 19 | +} |
| 20 | + |
| 21 | +/* |
| 22 | +newRehearsalEntry parses the rehearsal section of the README.md file that looks like: |
| 23 | +
|
| 24 | +## Rehearsal |
| 25 | +
|
| 26 | +* [Some Name 1](./problem_test1.go), [Solution](./solution1.go) |
| 27 | +* [Some Name 2](./problem_test2.go), [Solution](./solution2.go). |
| 28 | +*/ |
| 29 | +func newRehearsalEntry(input string) ([]rehearsalEntry, error) { |
| 30 | + lines := strings.Split(input, "\n") |
| 31 | + entries := []rehearsalEntry{} |
| 32 | + re := regexp.MustCompile(`\* \[([^\]]+)\]\(\.\/([^\)]+)\), \[Solution\]\(\.\/([^\)]+)\)`) |
| 33 | + |
| 34 | + for _, line := range lines { |
| 35 | + line = strings.TrimSpace(line) |
| 36 | + if line == "" || strings.HasPrefix(line, "##") { |
| 37 | + continue // Skip empty lines and heading lines |
| 38 | + } |
| 39 | + matches := re.FindStringSubmatch(line) |
| 40 | + if len(matches) != 4 { |
| 41 | + return nil, fmt.Errorf("invalid line format: %s, %d", line, len(matches)) |
| 42 | + } |
| 43 | + |
| 44 | + entry := rehearsalEntry{ |
| 45 | + Name: matches[1], |
| 46 | + TestFileName: matches[2], |
| 47 | + SolutionFileName: matches[3], |
| 48 | + } |
| 49 | + entries = append(entries, entry) |
| 50 | + } |
| 51 | + |
| 52 | + return entries, nil |
| 53 | +} |
| 54 | + |
| 55 | +func stringRehearsalEntries(dir, section string, entries []rehearsalEntry) string { |
| 56 | + output := "" |
| 57 | + for _, entry := range entries { |
| 58 | + output += fmt.Sprintf("\n### %s\n", entry.Name) |
| 59 | + |
| 60 | + testFileContent, err := os.ReadFile(filepath.Join(dir, section, entry.TestFileName)) |
| 61 | + if err != nil { |
| 62 | + output += fmt.Sprintf("Error reading test file: %s\n", err) |
| 63 | + continue |
| 64 | + } |
| 65 | + output += "```GO\n" + string(testFileContent) + "\n```\n" |
| 66 | + } |
| 67 | + |
| 68 | + output += "\n## Rehearsal Solutions\n" |
| 69 | + |
| 70 | + for _, entry := range entries { |
| 71 | + output += fmt.Sprintf("\n### %s\n", entry.Name) |
| 72 | + |
| 73 | + testFileContent, err := os.ReadFile(filepath.Join(dir, section, entry.SolutionFileName)) |
| 74 | + if err != nil { |
| 75 | + output += fmt.Sprintf("Error reading test file: %s\n", err) |
| 76 | + continue |
| 77 | + } |
| 78 | + output += "```GO\n" + string(testFileContent) + "\n```\n" |
| 79 | + } |
| 80 | + |
| 81 | + return output |
| 82 | +} |
0 commit comments