-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
243 lines (193 loc) · 5.97 KB
/
main.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/signal"
"regexp"
"strings"
"syscall"
"github.com/mrflynn/go-joinederror"
"github.com/mrflynn/upload-to-netlify-action/internal/actions"
"github.com/mrflynn/upload-to-netlify-action/internal/upload"
)
// Program information set during compile.
var version, commit, date string
// Program logger.
var logger = actions.NewLogger()
// Program variables.
var (
siteName string
branchName string
sourceFiles []string
destinationPaths []string
)
// Netlify handler
var handler upload.Handler
func init() {
logger.Debugf(
"upload-to-netlify-action %s (commit: %s, compiled: %s)",
version, commit, date,
)
var (
netlifyToken string
err error
opts = actions.GetInputOptions{
Required: true,
TrimWhitespace: true,
}
)
netlifyToken, err = actions.GetInput("netlify-token", opts)
if err != nil {
logger.Error("Netlify API token is required!")
os.Exit(1)
} else {
logger.SetSecret(netlifyToken)
}
siteName, err = actions.GetInput("site-name", opts)
if err != nil {
logger.Error("Name of Netlify site is required!")
os.Exit(1)
}
branchName, err = actions.GetInput("branch-name", opts)
if err != nil {
branchName = "main"
logger.Warn("Could not get value of branch-name, assuming 'main'")
}
sourceFiles, err = actions.GetMultilineInput("source-file", opts)
if err != nil {
logger.Error("At least one source file must be given.")
os.Exit(1)
}
destinationPaths, err = actions.GetMultilineInput("destination-path", opts)
if err != nil {
logger.Error("At least one destination path must be given.")
os.Exit(1)
}
handler = upload.Handler{Token: netlifyToken}
}
func handleError(ctx context.Context, err error, deployID *string) {
// Log error, but capitalize the first letter.
logger.Error(
regexp.MustCompile(`^\w`).ReplaceAllStringFunc(err.Error(), func(s string) string {
return strings.ToUpper(s)
}),
)
if deployID != nil {
if destroyErr := handler.DestroyDeploy(ctx, *deployID); destroyErr != nil {
logger.Errorf("Error while trying to destroy deploy: %s", destroyErr)
}
}
os.Exit(1)
}
func cleanDestinationPath(path string) (cleaned string, err error) {
if regexp.MustCompile("[#?]").MatchString(path) {
err = fmt.Errorf("path %s contains one of the following illegal characters: #, ?", path)
return
}
cleaned = strings.TrimPrefix(path, "/")
return
}
func getReadersForSourceFiles() (rs map[string]io.ReadSeekCloser, err error) {
rs = make(map[string]io.ReadSeekCloser, len(destinationPaths))
var (
file *os.File
dest string
)
for i, sourceFile := range sourceFiles {
file, err = os.Open(sourceFile)
if err != nil {
err = fmt.Errorf("error opening source file %s: %w", sourceFile, err)
return
}
dest, err = cleanDestinationPath(destinationPaths[i])
if err != nil {
err = fmt.Errorf("error in destination path %s: %w", destinationPaths[i], err)
return
}
rs[dest] = file
}
return
}
func createDeployTitle() (title string) {
gitSha := os.Getenv("GITHUB_SHA")
if len(gitSha) >= 7 {
gitSha = gitSha[:7]
}
title = fmt.Sprintf("%s@%s via upload-to-netlify-action", branchName, gitSha)
return
}
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
// Get site information.
site, err := handler.GetSite(ctx, siteName)
if err != nil {
handleError(ctx, fmt.Errorf("error getting details for site %s: %w", siteName, err), nil)
}
logger.Debugf("Got site ID for %s (ID: %s)", siteName, site.ID)
// Get latest deploy and wait until it has completed.
deploy, err := handler.GetLatestDeploy(ctx, site.ID, branchName)
if err != nil {
handleError(ctx, fmt.Errorf("error getting latest deploy: %w", err), nil)
}
logger.Debugf("Got latest deploy for site ID %s (deployID: %s)", site.ID, deploy.ID)
err = handler.WaitForDeploy(ctx, deploy)
if err != nil {
handleError(ctx, fmt.Errorf("encountered error waiting for deploy to complete: %w", err), nil)
}
// Get site files.
files, err := handler.GetSiteFiles(ctx, site.ID)
if err != nil {
handleError(ctx, fmt.Errorf("error getting files for site: %w", err), nil)
}
logger.Debugf("Got %d preexisting files from site ID %s", len(files), site.ID)
sourceFileReaders, err := getReadersForSourceFiles()
if err != nil {
handleError(ctx, err, nil)
}
deployParams := upload.NewDeployWithExistingFiles(site.ID, branchName, files)
for path, reader := range sourceFileReaders {
err = deployParams.RegisterFile("/"+path, reader)
if err != nil {
handleError(ctx, fmt.Errorf("error preparing file %s for upload: %w", path, err), nil)
}
logger.Debugf("Registered file %s", path)
}
deployParams.Title = createDeployTitle()
logger.Infof(
"Beginning upload of the following files: %s.", strings.Join(sourceFiles, ", "),
)
// Create new deploy with additional files.
deploy, err = handler.CreateDeployWithFiles(ctx, deployParams)
if err != nil {
handleError(ctx, fmt.Errorf("error while initiating new deployment: %w", err), &deploy.ID)
}
logger.Debugf("Started new deploy with ID %s", deploy.ID)
uploadParams := make([]upload.DeployFileUploadParams, 0, len(destinationPaths))
for path, reader := range sourceFileReaders {
uploadParams = append(uploadParams, upload.DeployFileUploadParams{
DeployID: deploy.ID,
Path: path,
File: reader,
})
}
// Upload additional files and wait for deploy to finish.
files, err = handler.UploadFilesToDeploy(ctx, uploadParams...)
if err != nil {
for _, fileError := range joinederror.UnwrapAll(err) {
logger.Error(fileError.Error())
}
handleError(ctx, errors.New("could not upload files due to the above errors"), &deploy.ID)
}
logger.Debugf("Uploaded %d files to deploy with ID %s", len(files), deploy.ID)
err = handler.WaitForDeploy(ctx, deploy)
if err != nil {
handleError(
ctx, fmt.Errorf("encountered error waiting for deploy to complete: %w", err), &deploy.ID,
)
}
logger.Info("Files successfully uploaded to Netlify!")
}