| 1 |
// Copyright 2025 Google LLC |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package generate |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"io/fs" |
| 22 |
"log/slog" |
| 23 |
"os" |
| 24 |
"path/filepath" |
| 25 |
"strings" |
| 26 |
|
| 27 |
"cloud.google.com/go/internal/postprocessor/librarian/librariangen/bazel" |
| 28 |
"cloud.google.com/go/internal/postprocessor/librarian/librariangen/config" |
| 29 |
"cloud.google.com/go/internal/postprocessor/librarian/librariangen/execv" |
| 30 |
"cloud.google.com/go/internal/postprocessor/librarian/librariangen/postprocessor" |
| 31 |
"cloud.google.com/go/internal/postprocessor/librarian/librariangen/protoc" |
| 32 |
"cloud.google.com/go/internal/postprocessor/librarian/librariangen/request" |
| 33 |
) |
| 34 |
|
| 35 |
// Test substitution vars. |
| 36 |
var ( |
| 37 |
postProcess = postprocessor.PostProcess |
| 38 |
bazelParse = bazel.Parse |
| 39 |
execvRun = execv.Run |
| 40 |
requestParse = request.ParseLibrary |
| 41 |
) |
| 42 |
|
| 43 |
// Config holds the internal librariangen configuration for the generate command. |
| 44 |
type Config struct { |
| 45 |
// LibrarianDir is the path to the librarian-tool input directory. |
| 46 |
// It is expected to contain the generate-request.json file. |
| 47 |
LibrarianDir string |
| 48 |
// InputDir is the path to the .librarian/generator-input directory from the |
| 49 |
// language repository. |
| 50 |
InputDir string |
| 51 |
// OutputDir is the path to the empty directory where librariangen writes |
| 52 |
// its output. |
| 53 |
OutputDir string |
| 54 |
// SourceDir is the path to a complete checkout of the googleapis repository. |
| 55 |
SourceDir string |
| 56 |
// DisablePostProcessor controls whether the post-processor is run. |
| 57 |
// This should always be false in production. |
| 58 |
DisablePostProcessor bool |
| 59 |
} |
| 60 |
|
| 61 |
// Validate ensures that the configuration is valid. |
| 62 |
func (c *Config) Validate() error { |
| 63 |
if c.LibrarianDir == "" { |
| 64 |
return errors.New("librariangen: librarian directory must be set") |
| 65 |
} |
| 66 |
if c.InputDir == "" { |
| 67 |
return errors.New("librariangen: input directory must be set") |
| 68 |
} |
| 69 |
if c.OutputDir == "" { |
| 70 |
return errors.New("librariangen: output directory must be set") |
| 71 |
} |
| 72 |
if c.SourceDir == "" { |
| 73 |
return errors.New("librariangen: source directory must be set") |
| 74 |
} |
| 75 |
return nil |
| 76 |
} |
| 77 |
|
| 78 |
// Generate is the main entrypoint for the `generate` command. It orchestrates |
| 79 |
// the entire generation process. The high-level steps are: |
| 80 |
// |
| 81 |
// 1. Validate the configuration. |
| 82 |
// 2. Invoke `protoc` for each API specified in the request, generating Go |
| 83 |
// files into a nested directory structure (e.g., |
| 84 |
// `/output/cloud.google.com/go/...`). |
| 85 |
// 3. Fix the permissions of all generated `.go` files to `0644`. |
| 86 |
// 4. Flatten the output directory, moving the generated module(s) to the top |
| 87 |
// level of the output directory (e.g., `/output/chronicle`). |
| 88 |
// 5. If the `DisablePostProcessor` flag is false, run the post-processor on the |
| 89 |
// generated module(s), updating versions for snippet metadata, |
| 90 |
// running go mod tidy etc. |
| 91 |
// |
| 92 |
// The `DisablePostProcessor` flag should always be false in production. It can be |
| 93 |
// true during development to inspect the "raw" protoc output before any |
| 94 |
// post-processing is applied. |
| 95 |
func Generate(ctx context.Context, cfg *Config) error { |
| 96 |
if err := cfg.Validate(); err != nil { |
| 97 |
return fmt.Errorf("librariangen: invalid configuration: %w", err) |
| 98 |
} |
| 99 |
slog.Debug("librariangen: generate command started") |
| 100 |
|
| 101 |
generateReq, err := readGenerateReq(cfg.LibrarianDir) |
| 102 |
if err != nil { |
| 103 |
return fmt.Errorf("librariangen: failed to read request: %w", err) |
| 104 |
} |
| 105 |
repoConfig, err := config.LoadRepoConfig(cfg.LibrarianDir) |
| 106 |
if err != nil { |
| 107 |
return fmt.Errorf("librariangen: failed to load repo config: %w", err) |
| 108 |
} |
| 109 |
moduleConfig := repoConfig.GetModuleConfig(generateReq.ID) |
| 110 |
|
| 111 |
if err := invokeProtoc(ctx, cfg, generateReq, moduleConfig); err != nil { |
| 112 |
return fmt.Errorf("librariangen: gapic generation failed: %w", err) |
| 113 |
} |
| 114 |
if err := fixPermissions(cfg.OutputDir); err != nil { |
| 115 |
return fmt.Errorf("librariangen: failed to fix permissions: %w", err) |
| 116 |
} |
| 117 |
if err := flattenOutput(cfg.OutputDir); err != nil { |
| 118 |
return fmt.Errorf("librariangen: failed to flatten output: %w", err) |
| 119 |
} |
| 120 |
|
| 121 |
if err := applyModuleVersion(cfg.OutputDir, moduleConfig.GetModulePath()); err != nil { |
| 122 |
return fmt.Errorf("librariangen: failed to apply module version to output directories: %w", err) |
| 123 |
} |
| 124 |
|
| 125 |
if !cfg.DisablePostProcessor { |
| 126 |
slog.Debug("librariangen: post-processor enabled") |
| 127 |
if len(generateReq.APIs) == 0 { |
| 128 |
return errors.New("librariangen: no APIs in request") |
| 129 |
} |
| 130 |
moduleDir := filepath.Join(cfg.OutputDir, generateReq.ID) |
| 131 |
if err := postProcess(ctx, generateReq, cfg.OutputDir, moduleDir, moduleConfig); err != nil { |
| 132 |
return fmt.Errorf("librariangen: post-processing failed: %w", err) |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
slog.Debug("librariangen: generate command finished") |
| 137 |
return nil |
| 138 |
} |
| 139 |
|
| 140 |
// invokeProtoc handles the protoc GAPIC generation logic for the 'generate' CLI command. |
| 141 |
// It reads a request file, and for each API specified, it invokes protoc |
| 142 |
// to generate the client library. It returns the module path and the path to the service YAML. |
| 143 |
func invokeProtoc(ctx context.Context, cfg *Config, generateReq *request.Library, moduleConfig *config.ModuleConfig) error { |
| 144 |
for _, api := range generateReq.APIs { |
| 145 |
apiServiceDir := filepath.Join(cfg.SourceDir, api.Path) |
| 146 |
slog.Info("processing api", "service_dir", apiServiceDir) |
| 147 |
bazelConfig, err := bazelParse(apiServiceDir) |
| 148 |
apiConfig := moduleConfig.GetAPIConfig(api.Path) |
| 149 |
if apiConfig.HasDisableGAPIC() { |
| 150 |
bazelConfig.DisableGAPIC() |
| 151 |
} |
| 152 |
if err != nil { |
| 153 |
return fmt.Errorf("librariangen: failed to parse BUILD.bazel for %s: %w", apiServiceDir, err) |
| 154 |
} |
| 155 |
args, err := protoc.Build(generateReq, &api, apiServiceDir, bazelConfig, cfg.SourceDir, cfg.OutputDir) |
| 156 |
if err != nil { |
| 157 |
return fmt.Errorf("librariangen: failed to build protoc command for api %q in library %q: %w", api.Path, generateReq.ID, err) |
| 158 |
} |
| 159 |
if err := execvRun(ctx, args, cfg.OutputDir); err != nil { |
| 160 |
return fmt.Errorf("librariangen: protoc failed for api %q in library %q: %w", api.Path, generateReq.ID, err) |
| 161 |
} |
| 162 |
} |
| 163 |
return nil |
| 164 |
} |
| 165 |
|
| 166 |
// readGenerateReq reads generate-request.json from the librarian-tool input directory. |
| 167 |
// The request file tells librariangen which library and APIs to generate. |
| 168 |
// It is prepared by the Librarian tool and mounted at /librarian. |
| 169 |
func readGenerateReq(librarianDir string) (*request.Library, error) { |
| 170 |
reqPath := filepath.Join(librarianDir, "generate-request.json") |
| 171 |
slog.Debug("librariangen: reading generate request", "path", reqPath) |
| 172 |
|
| 173 |
generateReq, err := requestParse(reqPath) |
| 174 |
if err != nil { |
| 175 |
return nil, err |
| 176 |
} |
| 177 |
slog.Debug("librariangen: successfully unmarshalled request", "library_id", generateReq.ID) |
| 178 |
return generateReq, nil |
| 179 |
} |
| 180 |
|
| 181 |
// fixPermissions recursively finds all .go files in the given directory and sets |
| 182 |
// their permissions to 0644. |
| 183 |
func fixPermissions(dir string) error { |
| 184 |
slog.Debug("librariangen: changing file permissions to 644", "dir", dir) |
| 185 |
return filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { |
| 186 |
if err != nil { |
| 187 |
return err |
| 188 |
} |
| 189 |
if !d.IsDir() && strings.HasSuffix(path, ".go") { |
| 190 |
if err := os.Chmod(path, 0644); err != nil { |
| 191 |
return fmt.Errorf("librariangen: failed to chmod %s: %w", path, err) |
| 192 |
} |
| 193 |
} |
| 194 |
return nil |
| 195 |
}) |
| 196 |
} |
| 197 |
|
| 198 |
// flattenOutput moves the contents of /output/cloud.google.com/go/ to the top |
| 199 |
// level of /output. |
| 200 |
func flattenOutput(outputDir string) error { |
| 201 |
slog.Debug("librariangen: flattening output directory", "dir", outputDir) |
| 202 |
goDir := filepath.Join(outputDir, "cloud.google.com", "go") |
| 203 |
if _, err := os.Stat(goDir); os.IsNotExist(err) { |
| 204 |
return fmt.Errorf("librariangen: go directory does not exist in path: %s", goDir) |
| 205 |
} |
| 206 |
if err := moveFiles(goDir, outputDir); err != nil { |
| 207 |
return err |
| 208 |
} |
| 209 |
// Remove the now-empty cloud.google.com directory. |
| 210 |
if err := os.RemoveAll(filepath.Join(outputDir, "cloud.google.com")); err != nil { |
| 211 |
return fmt.Errorf("librariangen: failed to remove cloud.google.com: %w", err) |
| 212 |
} |
| 213 |
return nil |
| 214 |
} |
| 215 |
|
| 216 |
// applyModuleVersion reorganizes the (already flattened) output directory |
| 217 |
// appropriately for versioned modules. For a module path of the form cloud.google.com/go/{id}/{version}, |
| 218 |
// we expect to find /output/{id}/{version} and /output/internal/generated/snippets/{id}/{version}. |
| 219 |
// The content of these directories are be moved into /output/{id} and |
| 220 |
// /output/internal/generated/snippets/{id} |
| 221 |
func applyModuleVersion(outputDir, modulePath string) error { |
| 222 |
parts := strings.Split(modulePath, "/") |
| 223 |
// Just cloud.google.com/go/xyz |
| 224 |
if len(parts) == 3 { |
| 225 |
return nil |
| 226 |
} |
| 227 |
if len(parts) != 4 { |
| 228 |
return fmt.Errorf("librariangen: unexpected module path format: %s", modulePath) |
| 229 |
} |
| 230 |
// e.g. dataproc |
| 231 |
id := parts[2] |
| 232 |
// e.g. v2 |
| 233 |
version := parts[3] |
| 234 |
|
| 235 |
srcDir := filepath.Join(outputDir, id) |
| 236 |
srcVersionDir := filepath.Join(srcDir, version) |
| 237 |
snippetsDir := filepath.Join(outputDir, "internal", "generated", "snippets", id) |
| 238 |
snippetsVersionDir := filepath.Join(snippetsDir, version) |
| 239 |
|
| 240 |
if err := moveFiles(srcVersionDir, srcDir); err != nil { |
| 241 |
return err |
| 242 |
} |
| 243 |
if err := os.RemoveAll(srcVersionDir); err != nil { |
| 244 |
return fmt.Errorf("librariangen: failed to remove %s: %w", srcVersionDir, err) |
| 245 |
} |
| 246 |
|
| 247 |
if err := moveFiles(snippetsVersionDir, snippetsDir); err != nil { |
| 248 |
return err |
| 249 |
} |
| 250 |
if err := os.RemoveAll(snippetsVersionDir); err != nil { |
| 251 |
return fmt.Errorf("librariangen: failed to remove %s: %w", snippetsVersionDir, err) |
| 252 |
} |
| 253 |
return nil |
| 254 |
} |
| 255 |
|
| 256 |
// moveFiles moves all files (and directories) from sourceDir to targetDir. |
| 257 |
func moveFiles(sourceDir, targetDir string) error { |
| 258 |
files, err := os.ReadDir(sourceDir) |
| 259 |
if err != nil { |
| 260 |
return fmt.Errorf("librariangen: failed to read dir %s: %w", sourceDir, err) |
| 261 |
} |
| 262 |
for _, f := range files { |
| 263 |
oldPath := filepath.Join(sourceDir, f.Name()) |
| 264 |
newPath := filepath.Join(targetDir, f.Name()) |
| 265 |
slog.Debug("librariangen: moving file", "from", oldPath, "to", newPath) |
| 266 |
if err := os.Rename(oldPath, newPath); err != nil { |
| 267 |
return fmt.Errorf("librariangen: failed to move %s to %s: %w", oldPath, newPath, err) |
| 268 |
} |
| 269 |
} |
| 270 |
return nil |
| 271 |
} |