Skip to content

Commit d7ea2ac

Browse files
authored
feat(librarian/swift): format after generation (#5094)
Use `swift-format` to format each library after it is generated. This is safe to run in parallel, so let's do so. AFAICT, `swift-format` is installed with the rest of the Swift toolchain, so there is no need to call `swiftly install blah...` for it.
1 parent ff29dd7 commit d7ea2ac

3 files changed

Lines changed: 32 additions & 0 deletions

File tree

internal/librarian/generate.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,9 @@ func generateLibraries(ctx context.Context, cfg *config.Config, libraries []*con
247247
if err := swift.Generate(gctx, cfg, library, src); err != nil {
248248
return fmt.Errorf("generate library %q (%s): %w", library.Name, cfg.Language, err)
249249
}
250+
if err := swift.Format(gctx, library); err != nil {
251+
return fmt.Errorf("format library %q (%s): %w", library.Name, cfg.Language, err)
252+
}
250253
return nil
251254
})
252255
}

internal/librarian/swift/generate.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"fmt"
2121
"strings"
2222

23+
"github.com/googleapis/librarian/internal/command"
2324
"github.com/googleapis/librarian/internal/config"
2425
"github.com/googleapis/librarian/internal/serviceconfig"
2526
"github.com/googleapis/librarian/internal/sidekick/parser"
@@ -44,6 +45,11 @@ func Generate(ctx context.Context, cfg *config.Config, library *config.Library,
4445
return sidekickswift.Generate(ctx, model, library.Output, modelConfig)
4546
}
4647

48+
// Format formats a generated Swift library.
49+
func Format(ctx context.Context, library *config.Library) error {
50+
return command.Run(ctx, "swift-format", "format", "--in-place", "--recursive", library.Output)
51+
}
52+
4753
// DefaultLibraryName derives a library name from an API path.
4854
// For example: google/cloud/secretmanager/v1 -> GoogleCloudSecretmanagerV1.
4955
func DefaultLibraryName(api string) string {

internal/librarian/swift/generate_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,26 @@ func TestGenerate(t *testing.T) {
7979
}
8080
}
8181
}
82+
83+
func TestFormat(t *testing.T) {
84+
testhelper.RequireCommand(t, "swift-format")
85+
86+
outDir := t.TempDir()
87+
sourcesDir := filepath.Join(outDir, "Sources")
88+
if err := os.MkdirAll(sourcesDir, 0755); err != nil {
89+
t.Fatal(err)
90+
}
91+
filePath := filepath.Join(sourcesDir, "test.swift")
92+
// Write a file that needs formatting.
93+
if err := os.WriteFile(filePath, []byte("func foo(){\n print(\"hello\")\n}\n"), 0644); err != nil {
94+
t.Fatal(err)
95+
}
96+
97+
library := &config.Library{
98+
Output: outDir,
99+
}
100+
101+
if err := Format(t.Context(), library); err != nil {
102+
t.Fatal(err)
103+
}
104+
}

0 commit comments

Comments
 (0)