summaryrefslogtreecommitdiff
path: root/cmd/internal/hexai-action/main.go
blob: 8bcc3cdb3a2de0aede00ebc0c0e9443c5a5346fd (plain)
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
package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"os"

	"codeberg.org/snonux/hexai/internal/hexaiaction"
)

func main() {
	infile := flag.String("infile", "", "Read input from this file instead of stdin")
	outfile := flag.String("outfile", "", "Write output to this file instead of stdout")
	flag.Parse()

	in, out, closeIn, closeOut, err := openIO(*infile, *outfile)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer closeIn()
	defer closeOut()

	if err := hexaiaction.Run(context.Background(), in, out, os.Stderr); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

// openIO returns readers/writers for infile/outfile flags with deferred closers.
func openIO(infile, outfile string) (io.Reader, io.Writer, func(), func(), error) {
	in := io.Reader(os.Stdin)
	out := io.Writer(os.Stdout)
	closeIn := func() {}
	closeOut := func() {}

	if path := infile; path != "" {
		f, err := os.Open(path)
		if err != nil {
			return nil, nil, func() {}, func() {}, fmt.Errorf("hexai-action: cannot open infile: %w", err)
		}
		in = f
		closeIn = func() { _ = f.Close() }
	}
	if path := outfile; path != "" {
		f, err := os.Create(path)
		if err != nil {
			return nil, nil, func() {}, func() {}, fmt.Errorf("hexai-action: cannot open outfile: %w", err)
		}
		out = f
		closeOut = func() { _ = f.Close() }
	}
	return in, out, closeIn, closeOut, nil
}