-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
run.go
393 lines (355 loc) · 10.7 KB
/
run.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package playwright
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
const (
playwrightCliVersion = "1.48.2"
)
var (
logger = log.Default()
playwrightCDNMirrors = []string{
"https://playwright.azureedge.net",
"https://playwright-akamai.azureedge.net",
"https://playwright-verizon.azureedge.net",
}
)
// PlaywrightDriver wraps the Playwright CLI of upstream Playwright.
//
// It's required for playwright-go to work.
type PlaywrightDriver struct {
Version string
options *RunOptions
}
func NewDriver(options ...*RunOptions) (*PlaywrightDriver, error) {
transformed, err := transformRunOptions(options...) // get default values
if err != nil {
return nil, err
}
return &PlaywrightDriver{
options: transformed,
Version: playwrightCliVersion,
}, nil
}
func getDefaultCacheDirectory() (string, error) {
userHomeDir, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("could not get user home directory: %w", err)
}
switch runtime.GOOS {
case "windows":
return filepath.Join(userHomeDir, "AppData", "Local"), nil
case "darwin":
return filepath.Join(userHomeDir, "Library", "Caches"), nil
case "linux":
return filepath.Join(userHomeDir, ".cache"), nil
}
return "", errors.New("could not determine cache directory")
}
func (d *PlaywrightDriver) isUpToDateDriver() (bool, error) {
if _, err := os.Stat(d.options.DriverDirectory); os.IsNotExist(err) {
if err := os.MkdirAll(d.options.DriverDirectory, 0o777); err != nil {
return false, fmt.Errorf("could not create driver directory: %w", err)
}
}
if _, err := os.Stat(getDriverCliJs(d.options.DriverDirectory)); os.IsNotExist(err) {
return false, nil
} else if err != nil {
return false, fmt.Errorf("could not check if driver is up2date: %w", err)
}
cmd := d.Command("--version")
output, err := cmd.Output()
if err != nil {
return false, fmt.Errorf("could not run driver: %w", err)
}
if bytes.Contains(output, []byte(d.Version)) {
return true, nil
}
// avoid triggering downloads and accidentally overwriting files
return false, fmt.Errorf("driver exists but version not %s in : %s", d.Version, d.options.DriverDirectory)
}
// Command returns an exec.Cmd for the driver.
func (d *PlaywrightDriver) Command(arg ...string) *exec.Cmd {
cmd := exec.Command(getNodeExecutable(d.options.DriverDirectory), append([]string{getDriverCliJs(d.options.DriverDirectory)}, arg...)...)
cmd.SysProcAttr = defaultSysProcAttr
return cmd
}
// Install downloads the driver and the browsers depending on [RunOptions].
func (d *PlaywrightDriver) Install() error {
if err := d.DownloadDriver(); err != nil {
return fmt.Errorf("could not install driver: %w", err)
}
if d.options.SkipInstallBrowsers {
return nil
}
d.log("Downloading browsers...")
if err := d.installBrowsers(); err != nil {
return fmt.Errorf("could not install browsers: %w", err)
}
d.log("Downloaded browsers successfully")
return nil
}
// Uninstall removes the driver and the browsers.
func (d *PlaywrightDriver) Uninstall() error {
d.log("Removing browsers...")
if err := d.uninstallBrowsers(); err != nil {
return fmt.Errorf("could not uninstall browsers: %w", err)
}
d.log("Removing driver...")
if err := os.RemoveAll(d.options.DriverDirectory); err != nil {
return fmt.Errorf("could not remove driver directory: %w", err)
}
d.log("Uninstall driver successfully")
return nil
}
// DownloadDriver downloads the driver only
func (d *PlaywrightDriver) DownloadDriver() error {
up2Date, err := d.isUpToDateDriver()
if err != nil {
return err
}
if up2Date {
return nil
}
d.log(fmt.Sprintf("Downloading driver to %s", d.options.DriverDirectory))
body, err := downloadDriver(d.getDriverURLs())
if err != nil {
return err
}
zipReader, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))
if err != nil {
return fmt.Errorf("could not read zip content: %w", err)
}
for _, zipFile := range zipReader.File {
zipFileDiskPath := filepath.Join(d.options.DriverDirectory, zipFile.Name)
if zipFile.FileInfo().IsDir() {
if err := os.MkdirAll(zipFileDiskPath, os.ModePerm); err != nil {
return fmt.Errorf("could not create directory: %w", err)
}
continue
}
outFile, err := os.Create(zipFileDiskPath)
if err != nil {
return fmt.Errorf("could not create driver: %w", err)
}
file, err := zipFile.Open()
if err != nil {
return fmt.Errorf("could not open zip file: %w", err)
}
if _, err = io.Copy(outFile, file); err != nil {
return fmt.Errorf("could not copy response body to file: %w", err)
}
if err := outFile.Close(); err != nil {
return fmt.Errorf("could not close file (driver): %w", err)
}
if err := file.Close(); err != nil {
return fmt.Errorf("could not close file (zip file): %w", err)
}
if zipFile.Mode().Perm()&0o100 != 0 && runtime.GOOS != "windows" {
if err := makeFileExecutable(zipFileDiskPath); err != nil {
return fmt.Errorf("could not make executable: %w", err)
}
}
}
d.log("Downloaded driver successfully")
return nil
}
func (d *PlaywrightDriver) log(s string) {
if d.options.Verbose {
logger.Println(s)
}
}
func (d *PlaywrightDriver) run() (*connection, error) {
transport, err := newPipeTransport(d, d.options.Stderr)
if err != nil {
return nil, err
}
connection := newConnection(transport)
return connection, nil
}
func (d *PlaywrightDriver) installBrowsers() error {
additionalArgs := []string{"install"}
if d.options.Browsers != nil {
additionalArgs = append(additionalArgs, d.options.Browsers...)
}
cmd := d.Command(additionalArgs...)
cmd.Stdout = d.options.Stdout
cmd.Stderr = d.options.Stderr
return cmd.Run()
}
func (d *PlaywrightDriver) uninstallBrowsers() error {
cmd := d.Command("uninstall")
cmd.Stdout = d.options.Stdout
cmd.Stderr = d.options.Stderr
return cmd.Run()
}
// RunOptions are custom options to run the driver
type RunOptions struct {
// DriverDirectory points to the playwright driver directory.
// It should have two subdirectories: node and package.
// You can also specify it using the environment variable PLAYWRIGHT_DRIVER_PATH.
//
// Default is user cache directory + "/ms-playwright-go/x.xx.xx":
// - Windows: %USERPROFILE%\AppData\Local
// - macOS: ~/Library/Caches
// - Linux: ~/.cache
DriverDirectory string
SkipInstallBrowsers bool
// if not set and SkipInstallBrowsers is false, will download all browsers (chromium, firefox, webkit)
Browsers []string
Verbose bool // default true
Stdout io.Writer
Stderr io.Writer
}
// Install does download the driver and the browsers.
//
// Use this before playwright.Run() or use playwright cli to install the driver and browsers
func Install(options ...*RunOptions) error {
driver, err := NewDriver(options...)
if err != nil {
return fmt.Errorf("could not get driver instance: %w", err)
}
if err := driver.Install(); err != nil {
return fmt.Errorf("could not install driver: %w", err)
}
return nil
}
// Run starts a Playwright instance.
//
// Requires the driver and the browsers to be installed before.
// Either use Install() or use playwright cli.
func Run(options ...*RunOptions) (*Playwright, error) {
driver, err := NewDriver(options...)
if err != nil {
return nil, fmt.Errorf("could not get driver instance: %w", err)
}
up2date, err := driver.isUpToDateDriver()
if err != nil || !up2date {
return nil, fmt.Errorf("please install the driver (v%s) first: %w", playwrightCliVersion, err)
}
connection, err := driver.run()
if err != nil {
return nil, err
}
playwright, err := connection.Start()
return playwright, err
}
func transformRunOptions(options ...*RunOptions) (*RunOptions, error) {
option := &RunOptions{
Verbose: true,
}
if len(options) == 1 {
option = options[0]
}
if option.DriverDirectory == "" { // if user did not set it, try to get it from env
option.DriverDirectory = os.Getenv("PLAYWRIGHT_DRIVER_PATH")
}
if option.DriverDirectory == "" {
cacheDirectory, err := getDefaultCacheDirectory()
if err != nil {
return nil, fmt.Errorf("could not get default cache directory: %w", err)
}
option.DriverDirectory = filepath.Join(cacheDirectory, "ms-playwright-go", playwrightCliVersion)
}
if option.Stdout == nil {
option.Stdout = os.Stdout
}
if option.Stderr == nil {
option.Stderr = os.Stderr
} else {
logger.SetOutput(option.Stderr)
}
return option, nil
}
func getNodeExecutable(driverDirectory string) string {
envPath := os.Getenv("PLAYWRIGHT_NODEJS_PATH")
if envPath != "" {
return envPath
}
node := "node"
if runtime.GOOS == "windows" {
node = "node.exe"
}
return filepath.Join(driverDirectory, node)
}
func getDriverCliJs(driverDirectory string) string {
return filepath.Join(driverDirectory, "package", "cli.js")
}
func (d *PlaywrightDriver) getDriverURLs() []string {
platform := ""
switch runtime.GOOS {
case "windows":
platform = "win32_x64"
case "darwin":
if runtime.GOARCH == "arm64" {
platform = "mac-arm64"
} else {
platform = "mac"
}
case "linux":
if runtime.GOARCH == "arm64" {
platform = "linux-arm64"
} else {
platform = "linux"
}
}
baseURLs := []string{}
pattern := "%s/builds/driver/playwright-%s-%s.zip"
if !d.isReleaseVersion() {
pattern = "%s/builds/driver/next/playwright-%s-%s.zip"
}
if hostEnv := os.Getenv("PLAYWRIGHT_DOWNLOAD_HOST"); hostEnv != "" {
baseURLs = append(baseURLs, fmt.Sprintf(pattern, hostEnv, d.Version, platform))
} else {
for _, mirror := range playwrightCDNMirrors {
baseURLs = append(baseURLs, fmt.Sprintf(pattern, mirror, d.Version, platform))
}
}
return baseURLs
}
// isReleaseVersion checks if the version is not a beta or alpha release
// this helps to determine the url from where to download the driver
func (d *PlaywrightDriver) isReleaseVersion() bool {
return !strings.Contains(d.Version, "beta") && !strings.Contains(d.Version, "alpha") && !strings.Contains(d.Version, "next")
}
func makeFileExecutable(path string) error {
stats, err := os.Stat(path)
if err != nil {
return fmt.Errorf("could not stat driver: %w", err)
}
if err := os.Chmod(path, stats.Mode()|0x40); err != nil {
return fmt.Errorf("could not set permissions: %w", err)
}
return nil
}
func downloadDriver(driverURLs []string) (body []byte, e error) {
for _, driverURL := range driverURLs {
resp, err := http.Get(driverURL)
if err != nil {
e = errors.Join(e, fmt.Errorf("could not download driver from %s: %w", driverURL, err))
continue
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
e = errors.Join(e, fmt.Errorf("error: got non 200 status code: %d (%s) from %s", resp.StatusCode, resp.Status, driverURL))
continue
}
body, err = io.ReadAll(resp.Body)
if err != nil {
e = errors.Join(e, fmt.Errorf("could not read response body: %w", err))
continue
}
return body, nil
}
return nil, e
}