Debian Codegraph @

internal/librariangen/release/release.go

raw
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 release implements the release-init command for librariangen.
16 package release
17
18 import (
19 "bytes"
20 "context"
21 "encoding/json"
22 "fmt"
23 "log/slog"
24 "os"
25 "path/filepath"
26 "sort"
27 "strings"
28 "time"
29
30 "cloud.google.com/go/internal/postprocessor/librarian/librariangen/config"
31 "cloud.google.com/go/internal/postprocessor/librarian/librariangen/module"
32 "cloud.google.com/go/internal/postprocessor/librarian/librariangen/request"
33 )
34
35 var now = time.Now
36
37 // Config holds the configuration for the release-init command.
38 type Config struct {
39 LibrarianDir string
40 RepoDir string
41 OutputDir string
42 }
43
44 // Init is the entrypoint for the release-init command.
45 func Init(ctx context.Context, cfg *Config) error {
46 slog.Info("librariangen: release.Init: starting", "config", cfg)
47 reqPath := filepath.Join(cfg.LibrarianDir, "release-init-request.json")
48 b, err := os.ReadFile(reqPath)
49 if err != nil {
50 return writeErrorResponse(cfg.LibrarianDir, fmt.Errorf("librariangen: failed to read request: %w", err))
51 }
52
53 var req Request
54 if err := json.Unmarshal(b, &req); err != nil {
55 return writeErrorResponse(cfg.LibrarianDir, fmt.Errorf("librariangen: failed to unmarshal request: %w", err))
56 }
57
58 repoConfig, err := config.LoadRepoConfig(cfg.LibrarianDir)
59 if err != nil {
60 return fmt.Errorf("librariangen: failed to load repo config: %w", err)
61 }
62
63 for _, lib := range req.Libraries {
64 if !lib.ReleaseTriggered {
65 continue
66 }
67 moduleConfig := repoConfig.GetModuleConfig(lib.ID)
68
69 moduleDir := filepath.Join(cfg.OutputDir, lib.ID)
70 slog.Info("librariangen: processing library for release", "id", lib.ID, "version", lib.Version)
71 if err := updateChangelog(cfg, lib, now().UTC()); err != nil {
72 return writeErrorResponse(cfg.LibrarianDir, fmt.Errorf("librariangen: failed to update changelog for %s: %w", lib.ID, err))
73 }
74 if err := module.GenerateInternalVersionFile(moduleDir, lib.Version); err != nil {
75 return writeErrorResponse(cfg.LibrarianDir, fmt.Errorf("librariangen: failed to update version for %s: %w", lib.ID, err))
76 }
77 if err := module.UpdateSnippetsMetadata(lib, cfg.RepoDir, cfg.OutputDir, moduleConfig); err != nil {
78 return writeErrorResponse(cfg.LibrarianDir, fmt.Errorf("librariangen: failed to update snippet version for %s: %w", lib.ID, err))
79 }
80 }
81 slog.Info("librariangen: release.Init: finished successfully")
82 return nil
83 }
84
85 var changelogSections = []struct {
86 Type string
87 Section string
88 }{
89 {Type: "feat", Section: "Features"},
90 {Type: "fix", Section: "Bug Fixes"},
91 {Type: "perf", Section: "Performance Improvements"},
92 {Type: "revert", Section: "Reverts"},
93 {Type: "docs", Section: "Documentation"},
94 }
95
96 func updateChangelog(cfg *Config, lib *request.Library, t time.Time) error {
97 relativeChangelogPath := filepath.Join(lib.ID, "CHANGES.md")
98 slog.Info("librariangen: updating changelog", "path", relativeChangelogPath)
99
100 srcPath := filepath.Join(cfg.RepoDir, relativeChangelogPath)
101 oldContent, err := os.ReadFile(srcPath)
102 if err != nil && !os.IsNotExist(err) {
103 return fmt.Errorf("librariangen: reading changelog: %w", err)
104 }
105
106 versionString := fmt.Sprintf("## [%s]", lib.Version)
107 if bytes.Contains(oldContent, []byte(versionString)) {
108 slog.Info("librariangen: changelog already up-to-date", "path", relativeChangelogPath, "version", lib.Version)
109 return nil
110 }
111
112 var newEntry bytes.Buffer
113
114 tag := fmt.Sprintf("%s/v%s", lib.ID, lib.Version)
115 encodedTag := strings.ReplaceAll(tag, "/", "%2F")
116 releaseURL := "https://github.com/googleapis/google-cloud-go/releases/tag/" + encodedTag
117 date := t.Format("2006-01-02")
118 fmt.Fprintf(&newEntry, "## [%s](%s) (%s)\n\n", lib.Version, releaseURL, date)
119
120 changesByType := make(map[string]map[string]*request.Change)
121 for _, change := range lib.Changes {
122 if changesByType[change.Type] == nil {
123 changesByType[change.Type] = make(map[string]*request.Change)
124 }
125 changesByType[change.Type][change.Subject] = change
126 }
127
128 for _, section := range changelogSections {
129 subjectsMap := changesByType[section.Type]
130 if len(subjectsMap) == 0 {
131 continue
132 }
133 fmt.Fprintf(&newEntry, "### %s\n\n", section.Section)
134
135 var subjects []string
136 for subj := range subjectsMap {
137 subjects = append(subjects, subj)
138 }
139 sort.Strings(subjects)
140
141 for _, subj := range subjects {
142 change := subjectsMap[subj]
143 var commitLink string
144 if change.SourceCommitHash != "" {
145 shortHash := change.SourceCommitHash
146 if len(shortHash) > 7 {
147 shortHash = shortHash[:7]
148 }
149 commitURL := fmt.Sprintf("https://github.com/googleapis/google-cloud-go/commit/%s", change.SourceCommitHash)
150 commitLink = fmt.Sprintf("([%s](%s))", shortHash, commitURL)
151 }
152
153 fmt.Fprintf(&newEntry, "* %s %s\n", change.Subject, commitLink)
154
155 }
156 newEntry.WriteString("\n")
157 }
158
159 // Find the insertion point after the "# Changes" title and any blank lines.
160 insertionPoint := 0
161 titleMarker := []byte("# Changes")
162 if i := bytes.Index(oldContent, titleMarker); i != -1 {
163 // Start searching after the title.
164 searchStart := i + len(titleMarker)
165 // Find the first non-whitespace character after the title.
166 nonWhitespaceIdx := bytes.IndexFunc(oldContent[searchStart:], func(r rune) bool {
167 return !bytes.ContainsRune([]byte{' ', '\t', '\n', '\r'}, r)
168 })
169 if nonWhitespaceIdx != -1 {
170 insertionPoint = searchStart + nonWhitespaceIdx
171 } else {
172 // The file only contains the title and whitespace, so append.
173 insertionPoint = len(oldContent)
174 }
175 } else if len(oldContent) > 0 {
176 // The file has content but no title, so prepend.
177 insertionPoint = 0
178 }
179
180 // Ensure there's a blank line between the new entry and the old content.
181 if insertionPoint > 0 && insertionPoint < len(oldContent) && oldContent[insertionPoint-1] != '\n' {
182 newEntry.WriteByte('\n')
183 }
184 if insertionPoint == len(oldContent) && len(oldContent) > 0 && oldContent[len(oldContent)-1] != '\n' {
185 // Add a newline before appending if the file doesn't end with one.
186 oldContent = append(oldContent, '\n')
187 insertionPoint = len(oldContent)
188 }
189 if insertionPoint == len(oldContent) && len(oldContent) > 0 && oldContent[len(oldContent)-1] == '\n' && (len(oldContent) < 2 || oldContent[len(oldContent)-2] != '\n') {
190 // Add a blank line if there isn't one already.
191 oldContent = append(oldContent, '\n')
192 insertionPoint = len(oldContent)
193 }
194
195 var newContent []byte
196 newContent = append(newContent, oldContent[:insertionPoint]...)
197 newContent = append(newContent, newEntry.Bytes()...)
198 newContent = append(newContent, oldContent[insertionPoint:]...)
199
200 destPath := filepath.Join(cfg.OutputDir, relativeChangelogPath)
201 if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
202 return fmt.Errorf("librariangen: creating directory for changelog: %w", err)
203 }
204 return os.WriteFile(destPath, newContent, 0644)
205 }
206
207 func writeErrorResponse(dir string, err error) error {
208 slog.Error("release.Init: failed", "error", err)
209 resp := Response{Error: err.Error()}
210 b, marshErr := json.MarshalIndent(resp, "", " ")
211 if marshErr != nil {
212 slog.Error("failed to marshal error response", "error", marshErr)
213 return err
214 }
215 respPath := filepath.Join(dir, "release-init-response.json")
216 if writeErr := os.WriteFile(respPath, b, 0644); writeErr != nil {
217 slog.Error("failed to write error response", "error", writeErr)
218 }
219 return err
220 }
221
222 // Request is the structure of the release-init-request.json file.
223 type Request struct {
224 Libraries []*request.Library `json:"libraries"`
225 }
226
227 // Response is the structure of the release-init-response.json file.
228 type Response struct {
229 Error string `json:"error,omitempty"`
230 }