summaryrefslogtreecommitdiff
path: root/xdelta3/go/src/xdelta/test.go
blob: 292f1337cb69fd1d366c3538a5c35154c10b8678 (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
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
package xdelta

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"sync/atomic"

	"golang.org/x/sys/unix"
)

var (
	tmpDir = "/tmp"
	srcSeq int64
)

type Program struct {
	Path string
}

type Runner struct {
	Testdir string
}

type Run struct {
	Cmd exec.Cmd
	Srcfile string
	Stdin io.WriteCloser
	Srcin io.WriteCloser
	Stdout io.ReadCloser
	Stderr io.ReadCloser
}

func NewRunner() (*Runner, error) {
	if dir, err := ioutil.TempDir(tmpDir, "xrt"); err != nil {
		return nil, err
	} else {
		return &Runner{dir}, nil
	}
}

func (r *Runner) Cleanup() {
	os.RemoveAll(r.Testdir)
}

func (r *Runner) Exec(p *Program, srcfifo bool, flags []string) (*Run, error) {
	var err error
	run := &Run{}
	args := []string{p.Path}
	if srcfifo {
		num := atomic.AddInt64(&srcSeq, 1)
		run.Srcfile = path.Join(r.Testdir, fmt.Sprint("source", num))
		if err = unix.Mkfifo(run.Srcfile, 0600); err != nil {
			return nil, err
		}
		// Because OpenFile blocks on the Fifo until the reader
		// arrives, a pipe to defer open
		read, write := io.Pipe()
		run.Srcin = write

		go writeFifo(run.Srcfile, read)
		args = append(args, "-s")
		args = append(args, run.Srcfile)
	}
	if run.Stdin, err = run.Cmd.StdinPipe(); err != nil {
		return nil, err
	}
	if run.Stdout, err = run.Cmd.StdoutPipe(); err != nil {
		return nil, err
	}
	if run.Stderr, err = run.Cmd.StderrPipe(); err != nil {
		return nil, err
	}

	run.Cmd.Path = p.Path
	run.Cmd.Args = append(args, flags...)
	run.Cmd.Dir = r.Testdir
	run.Cmd.Start()

	return run, nil
}

func writeFifo(srcfile string, read io.Reader) {
	fifo, err := os.OpenFile(srcfile, os.O_WRONLY, 0600)
	if err != nil {
		panic(err)
	}
	if _, err := io.Copy(fifo, read); err != nil {
		panic(err)
	}
	if err := fifo.Close(); err != nil {
		panic(err)
	}
}