-
Notifications
You must be signed in to change notification settings - Fork 143
/
migratefromdeployconfig.go
186 lines (159 loc) · 4.7 KB
/
migratefromdeployconfig.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// Copyright 2022 The PipeCD Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package appconfig
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/pipe-cd/pipecd/pkg/app/server/service/apiservice"
"github.com/pipe-cd/pipecd/pkg/cli"
)
type migrateFromDeployConfig struct {
root *command
repoRootPath string
repoID string
envName string
stdout io.Writer
}
func newMigrateCommand(root *command) *cobra.Command {
m := &migrateFromDeployConfig{
root: root,
stdout: os.Stdout,
}
cmd := &cobra.Command{
Use: "migrate-from-deploy-config",
Short: "Migrate local deployment configuration files to application configuration files. Basically this finds all deployment configuration files to add name field and env label to them.",
RunE: cli.WithContext(m.run),
}
cmd.Flags().StringVar(&m.repoRootPath, "repo-root-path", m.repoRootPath, "The absolute path to the root directory of the Git repository.")
cmd.Flags().StringVar(&m.repoID, "repo-id", m.repoID, "The repository ID that is being registered in Piped config.")
cmd.Flags().StringVar(&m.envName, "env-name", m.envName, "The environment name.")
cmd.MarkFlagRequired("repo-root-path")
cmd.MarkFlagRequired("repo-id")
cmd.MarkFlagRequired("env-name")
return cmd
}
func (m *migrateFromDeployConfig) run(ctx context.Context, _ cli.Input) error {
cli, err := m.root.clientOptions.NewClient(ctx)
if err != nil {
return fmt.Errorf("failed to initialize client: %w", err)
}
defer cli.Close()
fmt.Fprintln(m.stdout, "Start finding and migrating deployment configuration files to application configuration files...")
var cursor string
var appConfigs = make(map[string][]byte, 0)
for {
req := &apiservice.ListApplicationsRequest{
EnvName: m.envName,
Cursor: cursor,
}
resp, err := cli.ListApplications(ctx, req)
if err != nil {
return fmt.Errorf("failed to list application: %w", err)
}
for _, app := range resp.Applications {
if app.GitPath.Repo.Id != m.repoID {
continue
}
path := filepath.Join(m.repoRootPath, app.GitPath.GetApplicationConfigFilePath())
oriData, err := os.ReadFile(path)
if err != nil {
return err
}
newData, err := convert(oriData, app.Name, m.envName, app.Description)
if err != nil {
return err
}
appConfigs[path] = newData
}
if resp.Cursor == "" {
break
}
cursor = resp.Cursor
}
if len(appConfigs) == 0 {
fmt.Println("There is no applications to migrate")
return nil
}
for p, data := range appConfigs {
info, err := os.Stat(p)
if err != nil {
return err
}
if err := os.WriteFile(p, data, info.Mode()); err != nil {
return err
}
}
fmt.Fprintf(m.stdout, "Successfully migrated %d applications\n", len(appConfigs))
return nil
}
func convert(data []byte, name, env, description string) ([]byte, error) {
var out strings.Builder
var shouldWrite, done bool
scanner := bufio.NewScanner(bytes.NewReader(data))
for scanner.Scan() {
line := scanner.Text()
if shouldWrite {
indent, ok := determineIndent(line)
if !ok {
fmt.Fprintf(&out, "%s\n", line)
continue
}
writeNewFields(&out, name, env, description, indent)
shouldWrite = false
done = true
}
fmt.Fprintf(&out, "%s\n", line)
if done {
continue
}
if strings.HasPrefix(line, "spec:") {
shouldWrite = true
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return []byte(out.String()), nil
}
func determineIndent(line string) (string, bool) {
noIndentLine := strings.TrimLeft(line, " \t")
// In case of just an empty line.
if noIndentLine == "" {
return "", false
}
// In case of just a comment.
if strings.HasPrefix(noIndentLine, "#") {
return "", false
}
return line[:len(line)-len(noIndentLine)], true
}
func writeNewFields(out io.Writer, name, env, description, indent string) {
doubleIndent := strings.Repeat(indent, 2)
fmt.Fprintf(out, "%sname: %s\n", indent, name)
fmt.Fprintf(out, "%slabels:\n", indent)
fmt.Fprintf(out, "%senv: %s\n", doubleIndent, env)
if description != "" {
fmt.Fprintf(out, "%sdescription: |\n", indent)
for _, s := range strings.Split(description, "\n") {
fmt.Fprintf(out, "%s%s\n", doubleIndent, s)
}
}
}