summaryrefslogtreecommitdiff
path: root/frontend.go
blob: d0c8c10554a3f3f01f57e312ea45274d26300062 (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
package libfastimport

import (
	"bufio"
	"io"
	"os"

	"git.lukeshu.com/go/libfastimport/textproto"
)

type UnsupportedCommand string

func (e UnsupportedCommand) Error() string {
	return "Unsupported command: " + string(e)
}

// A Frontend is something that produces a fast-import stream; the
// Frontend object provides methods for reading from it.
type Frontend struct {
	fastImport   *parser
	catBlobWrite *textproto.CatBlobWriter
	catBlobFlush *bufio.Writer

	onErr func(error) error
}

func NewFrontend(fastImport io.Reader, catBlob io.Writer, onErr func(error) error) *Frontend {
	ret := &Frontend{}

	ret.fastImport = newParser(textproto.NewFIReader(fastImport))

	if catBlob == nil {
		catBlob = os.Stdout
	}
	ret.catBlobFlush = bufio.NewWriter(catBlob)
	ret.catBlobWrite = textproto.NewCatBlobWriter(ret.catBlobFlush)

	if onErr == nil {
		onErr = func(e error) error { return e }
	}
	ret.onErr = onErr

	return ret
}

func (f *Frontend) ReadCmd() (Cmd, error) {
	cmd, err := f.fastImport.ReadCmd()
	if err != nil {
		err = f.onErr(err)
	}
	return cmd, err
}

func (f *Frontend) RespondGetMark(sha1 string) error {
	err := f.catBlobWrite.WriteLine(sha1)
	if err != nil {
		return err
	}
	return f.catBlobFlush.Flush()
}

func (f *Frontend) RespondCatBlob(sha1 string, data string) error {
	err := f.catBlobWrite.WriteBlob(sha1, data)
	if err != nil {
		return err
	}
	return f.catBlobFlush.Flush()
}

func (f *Frontend) RespondLs(mode Mode, dataref string, path Path) error {
	var err error
	if mode == 0 {
		err = f.catBlobWrite.WriteLine("missing", path)
	} else {
		var t string
		switch mode {
		case ModeDir:
			t = "tree"
		case ModeGit:
			t = "commit"
		default:
			t = "blob"
		}
		err = f.catBlobWrite.WriteLine(mode, t, dataref+"\t"+PathEscape(path))
	}
	if err != nil {
		return err
	}
	return f.catBlobFlush.Flush()
}