Debian Codegraph @

internal/gapicgen/cmd/genbot/local.go

raw
1 // Copyright 2021 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 //go:build !windows
16 // +build !windows
17
18 package main
19
20 import (
21 "context"
22 "log"
23 "os"
24 "path/filepath"
25
26 "cloud.google.com/go/internal/gapicgen/generator"
27 "github.com/go-git/go-git/v5"
28 "golang.org/x/sync/errgroup"
29 )
30
31 type localConfig struct {
32 googleapisDir string
33 genprotoDir string
34 protoDir string
35 regenOnly bool
36 forceAll bool
37 genAlias bool
38 }
39
40 func genLocal(ctx context.Context, c localConfig) error {
41 log.Println("creating temp dir")
42 tmpDir, err := os.MkdirTemp("", "update-genproto")
43 if err != nil {
44 log.Fatal(err)
45 }
46 log.Printf("temp dir created at %s\n", tmpDir)
47 tmpGoogleapisDir := filepath.Join(tmpDir, "googleapis")
48 tmpGenprotoDir := filepath.Join(tmpDir, "genproto")
49 tmpProtoDir := filepath.Join(tmpDir, "proto")
50
51 // Clone repositories if needed.
52 grp, _ := errgroup.WithContext(ctx)
53 gitShallowClone(grp, "https://github.com/googleapis/googleapis.git", c.googleapisDir, tmpGoogleapisDir)
54 gitShallowClone(grp, "https://github.com/googleapis/go-genproto", c.genprotoDir, tmpGenprotoDir)
55 gitShallowClone(grp, "https://github.com/protocolbuffers/protobuf", c.protoDir, tmpProtoDir)
56 if err := grp.Wait(); err != nil {
57 log.Println(err)
58 }
59
60 // Regen.
61 conf := &generator.Config{
62 GoogleapisDir: defaultDir(tmpGoogleapisDir, c.googleapisDir),
63 GenprotoDir: defaultDir(tmpGenprotoDir, c.genprotoDir),
64 ProtoDir: defaultDir(tmpProtoDir, c.protoDir),
65 LocalMode: true,
66 RegenOnly: c.regenOnly,
67 ForceAll: c.forceAll,
68 GenAlias: c.genAlias,
69 }
70 if _, err := generator.Generate(ctx, conf); err != nil {
71 return err
72 }
73 return nil
74 }
75
76 // gitShallowClone clones a repository into the provided tmpDir if a dir has not
77 // been specified.
78 func gitShallowClone(eg *errgroup.Group, repo, dir, tmpDir string) {
79 if dir != "" {
80 return
81 }
82 eg.Go(func() error {
83 log.Printf("cloning %s\n", repo)
84
85 _, err := git.PlainClone(tmpDir, false, &git.CloneOptions{
86 URL: repo,
87 Progress: os.Stdout,
88 Depth: 1,
89 Tags: git.NoTags,
90 })
91 return err
92 })
93 }
94
95 // defaultDir returns the default option if dir is not set.
96 func defaultDir(def, dir string) string {
97 if dir == "" {
98 return def
99 }
100 return dir
101 }