File: lfshttp.go

package info (click to toggle)
git-lfs 3.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,880 kB
  • sloc: sh: 23,157; makefile: 519; ruby: 404
file content (91 lines) | stat: -rw-r--r-- 1,936 bytes parent folder | download
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
package lfshttp

import (
	"encoding/json"
	"net/http"
	"regexp"

	"github.com/git-lfs/git-lfs/v3/config"
	"github.com/git-lfs/git-lfs/v3/errors"
	"github.com/git-lfs/git-lfs/v3/git"
	"github.com/git-lfs/git-lfs/v3/tr"
)

var (
	lfsMediaTypeRE  = regexp.MustCompile(`\Aapplication/vnd\.git\-lfs\+json(;|\z)`)
	jsonMediaTypeRE = regexp.MustCompile(`\Aapplication/json(;|\z)`)
)

type Context interface {
	GitConfig() *git.Configuration
	OSEnv() config.Environment
	GitEnv() config.Environment
}

func NewContext(gitConf *git.Configuration, osEnv, gitEnv map[string]string) Context {
	c := &testContext{gitConfig: gitConf}
	if c.gitConfig == nil {
		c.gitConfig = git.NewConfig("", "")
	}
	if osEnv != nil {
		c.osEnv = testEnv(osEnv)
	} else {
		c.osEnv = make(testEnv)
	}

	if gitEnv != nil {
		c.gitEnv = testEnv(gitEnv)
	} else {
		c.gitEnv = make(testEnv)
	}
	return c
}

type testContext struct {
	gitConfig *git.Configuration
	osEnv     config.Environment
	gitEnv    config.Environment
}

func (c *testContext) GitConfig() *git.Configuration {
	return c.gitConfig
}

func (c *testContext) OSEnv() config.Environment {
	return c.osEnv
}

func (c *testContext) GitEnv() config.Environment {
	return c.gitEnv
}

func IsDecodeTypeError(err error) bool {
	_, ok := err.(*decodeTypeError)
	return ok
}

type decodeTypeError struct {
	Type string
}

func (e *decodeTypeError) TypeError() {}

func (e *decodeTypeError) Error() string {
	return tr.Tr.Get("Expected JSON type, got: %q", e.Type)
}

func DecodeJSON(res *http.Response, obj interface{}) error {
	ctype := res.Header.Get("Content-Type")
	if !(lfsMediaTypeRE.MatchString(ctype) || jsonMediaTypeRE.MatchString(ctype)) {
		return &decodeTypeError{Type: ctype}
	}

	err := json.NewDecoder(res.Body).Decode(obj)
	res.Body.Close()

	if err != nil {
		return errors.Wrap(err, tr.Tr.Get("Unable to parse HTTP response for %s %s", res.Request.Method, res.Request.URL))
	}

	return nil
}