ytdl-web/pkg/ytdl/cmdbuilder.go

57 lines
914 B
Go
Raw Permalink Normal View History

2023-05-23 18:44:05 -04:00
package ytdl
import (
"bytes"
"encoding/json"
"os/exec"
"go.fifitido.net/ytdl-web/pkg/ytdl/metadata"
2023-05-23 18:44:05 -04:00
)
func Exec(binary, url string, options ...Option) error {
2023-05-23 18:44:05 -04:00
opts := Options{
args: []string{url},
stdin: nil,
stdout: nil,
stderr: nil,
output: nil,
}
for _, opt := range options {
if err := opt(&opts); err != nil {
return err
}
}
cmd := exec.Command(binary, opts.args...)
2023-05-23 18:44:05 -04:00
if opts.stdin != nil {
cmd.Stdin = opts.stdin
}
if opts.stdout != nil {
cmd.Stdout = opts.stdout
}
2024-09-18 20:46:18 -04:00
var stderr = new(bytes.Buffer)
2023-05-23 18:44:05 -04:00
if opts.stderr != nil {
2024-09-18 20:46:18 -04:00
cmd.Stderr = stderr
2023-05-23 18:44:05 -04:00
}
if err := cmd.Run(); err != nil {
2024-09-18 20:46:18 -04:00
return &Error{
stderr: stderr.String(),
child: err,
}
2023-05-23 18:44:05 -04:00
}
buf, bufOk := opts.stdout.(*bytes.Buffer)
meta, metaOk := opts.output.(*metadata.Metadata)
if bufOk && metaOk {
if err := json.Unmarshal(buf.Bytes(), meta); err != nil {
return err
}
}
return nil
}