Debian Codegraph @

plumbing/transport/git/common.go

raw
1 // Package git implements the git transport protocol.
2 package git
3
4 import (
5 "io"
6 "net"
7 "strconv"
8
9 "github.com/go-git/go-git/v5/plumbing/protocol/packp"
10 "github.com/go-git/go-git/v5/plumbing/transport"
11 "github.com/go-git/go-git/v5/plumbing/transport/internal/common"
12 "github.com/go-git/go-git/v5/utils/ioutil"
13 )
14
15 // DefaultClient is the default git client.
16 var DefaultClient = common.NewClient(&runner{})
17
18 const DefaultPort = 9418
19
20 type runner struct{}
21
22 // Command returns a new Command for the given cmd in the given Endpoint
23 func (r *runner) Command(cmd string, ep *transport.Endpoint, auth transport.AuthMethod) (common.Command, error) {
24 // auth not allowed since git protocol doesn't support authentication
25 if auth != nil {
26 return nil, transport.ErrInvalidAuthMethod
27 }
28 c := &command{command: cmd, endpoint: ep}
29 if err := c.connect(); err != nil {
30 return nil, err
31 }
32 return c, nil
33 }
34
35 type command struct {
36 conn net.Conn
37 connected bool
38 command string
39 endpoint *transport.Endpoint
40 }
41
42 // Start executes the command sending the required message to the TCP connection
43 func (c *command) Start() error {
44 req := packp.GitProtoRequest{
45 RequestCommand: c.command,
46 Pathname: c.endpoint.Path,
47 }
48 host := c.endpoint.Host
49 if c.endpoint.Port != DefaultPort {
50 host = net.JoinHostPort(c.endpoint.Host, strconv.Itoa(c.endpoint.Port))
51 }
52
53 req.Host = host
54
55 return req.Encode(c.conn)
56 }
57
58 func (c *command) connect() error {
59 if c.connected {
60 return transport.ErrAlreadyConnected
61 }
62
63 var err error
64 c.conn, err = net.Dial("tcp", c.getHostWithPort())
65 if err != nil {
66 return err
67 }
68
69 c.connected = true
70 return nil
71 }
72
73 func (c *command) getHostWithPort() string {
74 host := c.endpoint.Host
75 port := c.endpoint.Port
76 if port <= 0 {
77 port = DefaultPort
78 }
79
80 return net.JoinHostPort(host, strconv.Itoa(port))
81 }
82
83 // StderrPipe git protocol doesn't have any dedicated error channel
84 func (c *command) StderrPipe() (io.Reader, error) {
85 return nil, nil
86 }
87
88 // StdinPipe returns the underlying connection as WriteCloser, wrapped to prevent
89 // call to the Close function from the connection, a command execution in git
90 // protocol can't be closed or killed
91 func (c *command) StdinPipe() (io.WriteCloser, error) {
92 return ioutil.WriteNopCloser(c.conn), nil
93 }
94
95 // StdoutPipe returns the underlying connection as Reader
96 func (c *command) StdoutPipe() (io.Reader, error) {
97 return c.conn, nil
98 }
99
100 // Close closes the TCP connection and connection.
101 func (c *command) Close() error {
102 if !c.connected {
103 return nil
104 }
105
106 c.connected = false
107 return c.conn.Close()
108 }