Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions internal/librarian/java/readme.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,46 @@ func extractTitle(filePath string) (string, error) {
}
return title, nil
}

// minLeadingSpaces finds the minimum number of leading spaces across non-empty lines.
func minLeadingSpaces(lines []string) int {
if len(lines) == 0 {
return 0
}
minSpaces := -1
for _, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
spaces := len(line) - len(strings.TrimLeft(line, " "))
if minSpaces == -1 || spaces < minSpaces {
minSpaces = spaces
}
}
if minSpaces == -1 {
return 0
}
return minSpaces
}

// trimLeadingWhitespace computes minimum leading space indentation and trims it.
func trimLeadingWhitespace(lines []string) string {
if len(lines) == 0 {
return ""
}
minSpaces := minLeadingSpaces(lines)
var sb strings.Builder
for _, line := range lines {
if strings.TrimSpace(line) == "" {
sb.WriteString("\n")
continue
}
if len(line) >= minSpaces {
sb.WriteString(line[minSpaces:])
} else {
sb.WriteString(line)
}
Comment thread
yangyzs marked this conversation as resolved.
Resolved
sb.WriteString("\n")
}
return sb.String()
}
67 changes: 67 additions & 0 deletions internal/librarian/java/readme_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -476,3 +476,70 @@ func TestExtractTitle_Error(t *testing.T) {
})
}
}

func TestMinLeadingSpaces(t *testing.T) {
for _, test := range []struct {
name string
lines []string
want int
}{
{
name: "two lines indented",
lines: []string{" foo", " bar"},
want: 2,
},
{
name: "zero indented line",
lines: []string{"foo", " bar"},
want: 0,
},
{
name: "empty slice",
lines: nil,
want: 0,
},
{
name: "only whitespace lines",
lines: []string{" ", "\t"},
want: 0,
},
} {
t.Run(test.name, func(t *testing.T) {
got := minLeadingSpaces(test.lines)
if diff := cmp.Diff(test.want, got); diff != "" {
t.Errorf("mismatch (-want +got):\n%s", diff)
}
})
}
}

func TestTrimLeadingWhitespace(t *testing.T) {
for _, test := range []struct {
name string
lines []string
want string
}{
{
name: "standard indentation",
lines: []string{" int x = 1;", " int y = 2;"},
want: "int x = 1;\n int y = 2;\n",
},
{
name: "with blank line",
lines: []string{" int x = 1;", "", " int y = 2;"},
want: "int x = 1;\n\nint y = 2;\n",
},
{
name: "empty input",
lines: nil,
want: "",
},
} {
t.Run(test.name, func(t *testing.T) {
got := trimLeadingWhitespace(test.lines)
if diff := cmp.Diff(test.want, got); diff != "" {
t.Errorf("mismatch (-want +got):\n%s", diff)
}
})
}
}
Loading