vendor/github.com/go-rod/rod/lib/utils/utils.go

379 lines · 7661 bytes

  1// Package utils ...
  2package utils
  3
  4import (
  5	"bytes"
  6	"context"
  7	"crypto/rand"
  8	"encoding/hex"
  9	"encoding/json"
 10	"fmt"
 11	"image"
 12	"image/jpeg"
 13	"image/png"
 14	"io"
 15	"log"
 16	"os"
 17	"os/exec"
 18	"path/filepath"
 19	"reflect"
 20	"regexp"
 21	"strings"
 22	"sync"
 23	"text/template"
 24	"time"
 25
 26	"github.com/ysmood/gson"
 27)
 28
 29// TestEnvs for testing.
 30var TestEnvs = map[string]string{
 31	"GODEBUG": "tracebackancestors=100",
 32}
 33
 34// InContainer will be true if is inside container environment, such as docker.
 35var InContainer = FileExists("/.dockerenv") || FileExists("/.containerenv") ||
 36	os.Getenv("KUBERNETES_SERVICE_HOST") != ""
 37
 38// Noop does nothing.
 39func Noop() {}
 40
 41// Logger interface.
 42type Logger interface {
 43	// Same as fmt.Printf
 44	Println(vs ...interface{})
 45}
 46
 47// Log type for Println.
 48type Log func(msg ...interface{})
 49
 50// Println interface.
 51func (l Log) Println(msg ...interface{}) {
 52	l(msg...)
 53}
 54
 55// LoggerQuiet does nothing.
 56var LoggerQuiet Logger = Log(func(_ ...interface{}) {})
 57
 58// MultiLogger is similar to https://golang.org/pkg/io/#MultiWriter
 59func MultiLogger(list ...Logger) Log {
 60	return Log(func(msg ...interface{}) {
 61		for _, lg := range list {
 62			lg.Println(msg...)
 63		}
 64	})
 65}
 66
 67// Panic is the same as the built-in panic.
 68var Panic = func(v interface{}) { panic(v) }
 69
 70// E if the last arg is error, panic it.
 71func E(args ...interface{}) []interface{} {
 72	err, ok := args[len(args)-1].(error)
 73	if ok {
 74		Panic(err)
 75	}
 76	return args
 77}
 78
 79// S Template render, the params is key-value pairs.
 80func S(tpl string, params ...interface{}) string {
 81	var out bytes.Buffer
 82
 83	dict := map[string]interface{}{}
 84	fnDict := template.FuncMap{}
 85
 86	l := len(params)
 87	for i := 0; i < l-1; i += 2 {
 88		k := params[i].(string) //nolint: forcetypeassert
 89		v := params[i+1]
 90		if reflect.TypeOf(v).Kind() == reflect.Func {
 91			fnDict[k] = v
 92		} else {
 93			dict[k] = v
 94		}
 95	}
 96
 97	t := template.Must(template.New("").Funcs(fnDict).Parse(tpl))
 98	E(t.Execute(&out, dict))
 99
100	return out.String()
101}
102
103// RandString generate random string with specified string length.
104func RandString(l int) string {
105	b := make([]byte, l)
106	_, _ = rand.Read(b)
107	return hex.EncodeToString(b)
108}
109
110// Mkdir makes dir recursively.
111func Mkdir(path string) error {
112	return os.MkdirAll(path, 0o775)
113}
114
115// AbsolutePaths returns absolute paths of files in current working directory.
116func AbsolutePaths(paths []string) []string {
117	absPaths := []string{}
118	for _, p := range paths {
119		absPath, err := filepath.Abs(p)
120		E(err)
121		absPaths = append(absPaths, absPath)
122	}
123	return absPaths
124}
125
126// OutputFile auto creates file if not exists, it will try to detect the data type and
127// auto output binary, string or json.
128func OutputFile(p string, data interface{}) error {
129	dir := filepath.Dir(p)
130	_ = Mkdir(dir)
131
132	var bin []byte
133
134	switch t := data.(type) {
135	case []byte:
136		bin = t
137	case string:
138		bin = []byte(t)
139	case io.Reader:
140		f, _ := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o664)
141		_, err := io.Copy(f, t)
142		return err
143	default:
144		bin = MustToJSONBytes(data)
145	}
146
147	return os.WriteFile(p, bin, 0o664)
148}
149
150// ReadString reads file as string.
151func ReadString(p string) (string, error) {
152	bin, err := os.ReadFile(p)
153	return string(bin), err
154}
155
156// All runs all actions concurrently, returns the wait function for all actions.
157func All(actions ...func()) func() {
158	wg := &sync.WaitGroup{}
159
160	wg.Add(len(actions))
161
162	runner := func(action func()) {
163		defer wg.Done()
164		action()
165	}
166
167	for _, action := range actions {
168		go runner(action)
169	}
170
171	return wg.Wait
172}
173
174// IdleCounter is similar to sync.WaitGroup but it only resolves if no jobs for specified duration.
175type IdleCounter struct {
176	lock     *sync.Mutex
177	job      int
178	duration time.Duration
179	tmr      *time.Timer
180}
181
182// NewIdleCounter ...
183func NewIdleCounter(d time.Duration) *IdleCounter {
184	tmr := time.NewTimer(time.Hour)
185	tmr.Stop()
186
187	return &IdleCounter{
188		lock:     &sync.Mutex{},
189		duration: d,
190		tmr:      tmr,
191	}
192}
193
194// Add ...
195func (de *IdleCounter) Add() {
196	de.lock.Lock()
197	defer de.lock.Unlock()
198
199	de.tmr.Stop()
200	de.job++
201}
202
203// Done ...
204func (de *IdleCounter) Done() {
205	de.lock.Lock()
206	defer de.lock.Unlock()
207
208	de.job--
209	if de.job == 0 {
210		de.reset(de.duration)
211	}
212	if de.job < 0 {
213		panic("all jobs are already done")
214	}
215}
216
217// Wait ...
218func (de *IdleCounter) Wait(ctx context.Context) {
219	de.lock.Lock()
220	if de.job == 0 {
221		de.reset(de.duration)
222	}
223	de.lock.Unlock()
224
225	select {
226	case <-ctx.Done():
227		de.tmr.Stop()
228	case <-de.tmr.C:
229	}
230}
231
232func (de *IdleCounter) reset(d time.Duration) {
233	if !de.tmr.Stop() {
234		select {
235		case <-de.tmr.C:
236		default:
237		}
238	}
239	de.tmr.Reset(d)
240}
241
242var chPause = make(chan struct{})
243
244// Pause the goroutine forever.
245func Pause() {
246	<-chPause
247}
248
249// Dump values for debugging.
250func Dump(list ...interface{}) string {
251	out := []string{}
252	for _, el := range list {
253		out = append(out, gson.New(el).JSON("", "  "))
254	}
255	return strings.Join(out, " ")
256}
257
258// MustToJSONBytes encode data to json bytes.
259func MustToJSONBytes(data interface{}) []byte {
260	buf := bytes.NewBuffer(nil)
261	enc := json.NewEncoder(buf)
262	enc.SetEscapeHTML(false)
263	E(enc.Encode(data))
264	b := buf.Bytes()
265	return b[:len(b)-1]
266}
267
268// MustToJSON encode data to json string.
269func MustToJSON(data interface{}) string {
270	return string(MustToJSONBytes(data))
271}
272
273// FileExists checks if file exists, only for file, not for dir.
274func FileExists(path string) bool {
275	info, err := os.Stat(path)
276	if err != nil {
277		return false
278	}
279
280	if info.IsDir() {
281		return false
282	}
283
284	return true
285}
286
287var regSpace = regexp.MustCompile(`\s`)
288
289// Exec command.
290func Exec(line string, rest ...string) string {
291	return ExecLine(true, line, rest...)
292}
293
294var execLogger = log.New(os.Stdout, "[exec] ", 0)
295
296// ExecLine of command.
297func ExecLine(std bool, line string, rest ...string) string {
298	args := rest
299	if line != "" {
300		args = append(regSpace.Split(line, -1), rest...)
301	}
302
303	execLogger.Println(FormatCLIArgs(args))
304
305	buf := bytes.NewBuffer(nil)
306
307	cmd := exec.Command(args[0], args[1:]...)
308	cmd.Stderr = buf
309	cmd.Stdout = buf
310
311	if std {
312		cmd.Stdin = os.Stdin
313		cmd.Stderr = io.MultiWriter(buf, os.Stderr)
314		cmd.Stdout = io.MultiWriter(buf, os.Stdout)
315	}
316
317	if err := cmd.Run(); err != nil {
318		if std {
319			panic(err)
320		}
321		panic(fmt.Sprintf("%v\n%v", err, buf.String()))
322	}
323
324	return buf.String()
325}
326
327// UseNode installs Node.js and set the bin path to PATH env var.
328func UseNode(std bool) {
329	binPath := strings.TrimSpace(ExecLine(std, "go run github.com/ysmood/use-node@latest -p v20"))
330	E(os.Setenv("PATH", binPath+string(os.PathListSeparator)+os.Getenv("PATH")))
331}
332
333// FormatCLIArgs into one line string.
334func FormatCLIArgs(args []string) string {
335	list := []string{}
336	for _, arg := range args {
337		if regSpace.MatchString(arg) {
338			list = append(list, fmt.Sprintf("%#v", arg))
339		} else {
340			list = append(list, arg)
341		}
342	}
343	return strings.Join(list, " ")
344}
345
346// EscapeGoString not using encoding like base64 or gzip because of they will
347// make git diff every large for small change.
348func EscapeGoString(s string) string {
349	return "`" + strings.ReplaceAll(s, "`", "` + \"`\" + `") + "`"
350}
351
352// CropImage by the specified box, quality is only for jpeg bin.
353func CropImage(bin []byte, quality, x, y, width, height int) ([]byte, error) {
354	img, typ, err := image.Decode(bytes.NewBuffer(bin))
355	if err != nil {
356		return nil, err
357	}
358
359	cropped := bytes.NewBuffer(nil)
360
361	img = img.(interface { //nolint: forcetypeassert
362		SubImage(r image.Rectangle) image.Image
363	}).SubImage(image.Rect(
364		x, y, x+width, y+height,
365	))
366
367	switch typ {
368	case "png":
369		err = png.Encode(cropped, img)
370	case "jpeg":
371		if quality == 0 {
372			quality = 80
373		}
374
375		err = jpeg.Encode(cropped, img, &jpeg.Options{Quality: quality})
376	}
377
378	return cropped.Bytes(), err
379}