/
upload-pack.go
65 lines (56 loc) · 1.88 KB
/
upload-pack.go
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
package pack
import (
"compress/gzip"
"fmt"
"github.com/adlternative/tinygithub/pkg/cmd"
log "github.com/sirupsen/logrus"
"io"
"net/http"
"strings"
"github.com/adlternative/tinygithub/pkg/storage"
"github.com/gin-gonic/gin"
)
func UploadPack(storage *storage.Storage) gin.HandlerFunc {
return func(c *gin.Context) {
serviceName := "upload-pack"
userName := c.Param("username")
repoName := strings.TrimSuffix(c.Param("reponame"), ".git")
repo, err := storage.GetRepository(userName, repoName)
if err != nil {
log.WithError(err).Errorf("GetRepository failed")
c.String(http.StatusNotFound, "GetRepository failed: %v", err)
return
}
var r io.Reader
r = c.Request.Body
encoding := c.GetHeader("Content-Encoding")
switch encoding {
case "gzip":
r, err = gzip.NewReader(r)
if err != nil {
log.WithError(err).Errorf("gzip decode failed")
c.String(http.StatusBadRequest, "gzip decode failed: %v", err)
return
}
default:
}
c.Writer.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", serviceName))
c.Writer.Header().Set("Cache-Control", "no-cache")
var stderrBuf strings.Builder
// git -c <repoPath> upload-pack --stateless-rpc <repoPath>
gitCmd := cmd.NewGitCommand(serviceName).WithGitDir(repo.Path()).
WithOptions("--stateless-rpc").
WithArgs(repo.Path()).WithStderr(&stderrBuf).WithStdout(c.Writer).WithStdin(r)
if protocol := c.GetHeader("Git-Protocol"); protocol != "" {
version := strings.TrimPrefix(protocol, "version=")
if version == "2" || version == "1" {
gitCmd.WithEnv(fmt.Sprintf("GIT_PROTOCOL=version=%s", version))
}
}
if err = gitCmd.Run(c); err != nil {
log.WithError(err).Errorf("git command failed with: err:%v, stderr:%v", err, stderrBuf.String())
c.String(http.StatusInternalServerError, "git command failed with: err:%v, stderr:%v", err, stderrBuf.String())
return
}
}
}