1
Fork 0
mirror of https://github.com/caddyserver/caddy.git synced 2024-12-16 21:56:40 -05:00

ci: Use gofumpt to format code (#5707)

This commit is contained in:
Jacob Gadikian 2023-08-08 03:40:31 +08:00 committed by GitHub
parent 431adc0980
commit b32f265eca
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
33 changed files with 60 additions and 64 deletions

View file

@ -8,8 +8,7 @@ linters:
enable:
- bodyclose
- errcheck
- gofmt
- goimports
- gofumpt
- gosec
- gosimple
- govet

View file

@ -1346,7 +1346,7 @@ var (
// will get deleted before the process gracefully exits.
func PIDFile(filename string) error {
pid := []byte(strconv.Itoa(os.Getpid()) + "\n")
err := os.WriteFile(filename, pid, 0600)
err := os.WriteFile(filename, pid, 0o600)
if err != nil {
return err
}

View file

@ -356,13 +356,13 @@ func unsyncedDecodeAndRun(cfgJSON []byte, allowPersist bool) error {
newCfg.Admin.Config.Persist == nil ||
*newCfg.Admin.Config.Persist) {
dir := filepath.Dir(ConfigAutosavePath)
err := os.MkdirAll(dir, 0700)
err := os.MkdirAll(dir, 0o700)
if err != nil {
Log().Error("unable to create folder for config autosave",
zap.String("dir", dir),
zap.Error(err))
} else {
err := os.WriteFile(ConfigAutosavePath, cfgJSON, 0600)
err := os.WriteFile(ConfigAutosavePath, cfgJSON, 0o600)
if err == nil {
Log().Info("autosaved config (load with --resume flag)", zap.String("file", ConfigAutosavePath))
} else {
@ -831,7 +831,7 @@ func InstanceID() (uuid.UUID, error) {
if err != nil {
return uuid, err
}
err = os.WriteFile(uuidFilePath, []byte(uuid.String()), 0600)
err = os.WriteFile(uuidFilePath, []byte(uuid.String()), 0o600)
return uuid, err
} else if err != nil {
return [16]byte{}, err

View file

@ -34,6 +34,7 @@ func (i *importGraph) addNode(name string) {
}
i.nodes[name] = true
}
func (i *importGraph) addNodes(names []string) {
for _, name := range names {
i.addNode(name)
@ -43,6 +44,7 @@ func (i *importGraph) addNodes(names []string) {
func (i *importGraph) removeNode(name string) {
delete(i.nodes, name)
}
func (i *importGraph) removeNodes(names []string) {
for _, name := range names {
i.removeNode(name)
@ -73,6 +75,7 @@ func (i *importGraph) addEdge(from, to string) error {
i.edges[from] = append(i.edges[from], to)
return nil
}
func (i *importGraph) addEdges(from string, tos []string) error {
for _, to := range tos {
err := i.addEdge(from, to)

View file

@ -565,7 +565,6 @@ func (p *parser) doSingleImport(importFile string) ([]Token, error) {
// are loaded into the current server block for later use
// by directive setup functions.
func (p *parser) directive() error {
// a segment is a list of tokens associated with this directive
var segment Segment

View file

@ -77,7 +77,8 @@ import (
// multiple addresses to the same lists of server blocks (a many:many mapping).
// (Doing this is essentially a map-reduce technique.)
func (st *ServerType) mapAddressToServerBlocks(originalServerBlocks []serverBlock,
options map[string]any) (map[string][]serverBlock, error) {
options map[string]any,
) (map[string][]serverBlock, error) {
sbmap := make(map[string][]serverBlock)
for i, sblock := range originalServerBlocks {
@ -187,7 +188,8 @@ func (st *ServerType) consolidateAddrMappings(addrToServerBlocks map[string][]se
// listenerAddrsForServerBlockKey essentially converts the Caddyfile
// site addresses to Caddy listener addresses for each server block.
func (st *ServerType) listenerAddrsForServerBlockKey(sblock serverBlock, key string,
options map[string]any) ([]string, error) {
options map[string]any,
) ([]string, error) {
addr, err := ParseAddress(key)
if err != nil {
return nil, fmt.Errorf("parsing key: %v", err)

View file

@ -217,7 +217,8 @@ func (h Helper) ExtractMatcherSet() (caddy.ModuleMap, error) {
// NewRoute returns config values relevant to creating a new HTTP route.
func (h Helper) NewRoute(matcherSet caddy.ModuleMap,
handler caddyhttp.MiddlewareHandler) []ConfigValue {
handler caddyhttp.MiddlewareHandler,
) []ConfigValue {
mod, err := caddy.GetModule(caddy.GetModuleID(handler))
if err != nil {
*h.warnings = append(*h.warnings, caddyconfig.Warning{

View file

@ -49,8 +49,7 @@ type App struct {
}
// ServerType can set up a config from an HTTP Caddyfile.
type ServerType struct {
}
type ServerType struct{}
// Setup makes a config from the tokens.
func (st ServerType) Setup(
@ -1059,8 +1058,8 @@ func appendSubrouteToRouteList(routeList caddyhttp.RouteList,
subroute *caddyhttp.Subroute,
matcherSetsEnc []caddy.ModuleMap,
p sbAddrAssociation,
warnings *[]caddyconfig.Warning) caddyhttp.RouteList {
warnings *[]caddyconfig.Warning,
) caddyhttp.RouteList {
// nothing to do if... there's nothing to do
if len(matcherSetsEnc) == 0 && len(subroute.Routes) == 0 && subroute.Errors == nil {
return routeList
@ -1608,8 +1607,10 @@ type sbAddrAssociation struct {
serverBlocks []serverBlock
}
const matcherPrefix = "@"
const namedRouteKey = "named_route"
const (
matcherPrefix = "@"
namedRouteKey = "named_route"
)
// Interface guard
var _ caddyfile.ServerType = (*ServerType)(nil)

View file

@ -174,7 +174,6 @@ func (st ServerType) buildPKIApp(
options map[string]any,
warnings []caddyconfig.Warning,
) (*caddypki.PKI, []caddyconfig.Warning, error) {
skipInstallTrust := false
if _, ok := options["skip_install_trust"]; ok {
skipInstallTrust = true

View file

@ -36,7 +36,6 @@ func (st ServerType) buildTLSApp(
options map[string]any,
warnings []caddyconfig.Warning,
) (*caddytls.TLS, []caddyconfig.Warning, error) {
tlsApp := &caddytls.TLS{CertificatesRaw: make(caddy.ModuleMap)}
var certLoaders []caddytls.CertificateLoader

View file

@ -63,7 +63,6 @@ type Tester struct {
// NewTester will create a new testing client with an attached cookie jar
func NewTester(t *testing.T) *Tester {
jar, err := cookiejar.New(nil)
if err != nil {
t.Fatalf("failed to create cookiejar: %s", err)
@ -94,7 +93,6 @@ func timeElapsed(start time.Time, name string) {
// InitServer this will configure the server with a configurion of a specific
// type. The configType must be either "json" or the adapter type.
func (tc *Tester) InitServer(rawConfig string, configType string) {
if err := tc.initServer(rawConfig, configType); err != nil {
tc.t.Logf("failed to load config: %s", err)
tc.t.Fail()
@ -108,7 +106,6 @@ func (tc *Tester) InitServer(rawConfig string, configType string) {
// InitServer this will configure the server with a configurion of a specific
// type. The configType must be either "json" or the adapter type.
func (tc *Tester) initServer(rawConfig string, configType string) error {
if testing.Short() {
tc.t.SkipNow()
return nil
@ -232,7 +229,6 @@ const initConfig = `{
// validateTestPrerequisites ensures the certificates are available in the
// designated path and Caddy sub-process is running.
func validateTestPrerequisites(t *testing.T) error {
// check certificates are found
for _, certName := range Default.Certifcates {
if _, err := os.Stat(getIntegrationDir() + certName); os.IsNotExist(err) {
@ -284,7 +280,6 @@ func isCaddyAdminRunning() error {
}
func getIntegrationDir() string {
_, filename, _, ok := runtime.Caller(1)
if !ok {
panic("unable to determine the current file path")
@ -304,7 +299,6 @@ func prependCaddyFilePath(rawConfig string) string {
// CreateTestingTransport creates a testing transport that forces call dialing connections to happen locally
func CreateTestingTransport() *http.Transport {
dialer := net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 5 * time.Second,
@ -332,7 +326,6 @@ func CreateTestingTransport() *http.Transport {
// AssertLoadError will load a config and expect an error
func AssertLoadError(t *testing.T, rawConfig string, configType string, expectedError string) {
tc := NewTester(t)
err := tc.initServer(rawConfig, configType)
@ -343,7 +336,6 @@ func AssertLoadError(t *testing.T, rawConfig string, configType string, expected
// AssertRedirect makes a request and asserts the redirection happens
func (tc *Tester) AssertRedirect(requestURI string, expectedToLocation string, expectedStatusCode int) *http.Response {
redirectPolicyFunc := func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
@ -381,7 +373,6 @@ func (tc *Tester) AssertRedirect(requestURI string, expectedToLocation string, e
// CompareAdapt adapts a config and then compares it against an expected result
func CompareAdapt(t *testing.T, filename, rawConfig string, adapterName string, expectedResponse string) bool {
cfgAdapter := caddyconfig.GetAdapter(adapterName)
if cfgAdapter == nil {
t.Logf("unrecognized config adapter '%s'", adapterName)
@ -469,7 +460,6 @@ func applyHeaders(t *testing.T, req *http.Request, requestHeaders []string) {
// AssertResponseCode will execute the request and verify the status code, returns a response for additional assertions
func (tc *Tester) AssertResponseCode(req *http.Request, expectedStatusCode int) *http.Response {
resp, err := tc.Client.Do(req)
if err != nil {
tc.t.Fatalf("failed to call server %s", err)
@ -484,7 +474,6 @@ func (tc *Tester) AssertResponseCode(req *http.Request, expectedStatusCode int)
// AssertResponse request a URI and assert the status code and the body contains a string
func (tc *Tester) AssertResponse(req *http.Request, expectedStatusCode int, expectedBody string) (*http.Response, string) {
resp := tc.AssertResponseCode(req, expectedStatusCode)
defer resp.Body.Close()
@ -506,7 +495,6 @@ func (tc *Tester) AssertResponse(req *http.Request, expectedStatusCode int, expe
// AssertGetResponse GET a URI and expect a statusCode and body text
func (tc *Tester) AssertGetResponse(requestURI string, expectedStatusCode int, expectedBody string) (*http.Response, string) {
req, err := http.NewRequest("GET", requestURI, nil)
if err != nil {
tc.t.Fatalf("unable to create request %s", err)
@ -517,7 +505,6 @@ func (tc *Tester) AssertGetResponse(requestURI string, expectedStatusCode int, e
// AssertDeleteResponse request a URI and expect a statusCode and body text
func (tc *Tester) AssertDeleteResponse(requestURI string, expectedStatusCode int, expectedBody string) (*http.Response, string) {
req, err := http.NewRequest("DELETE", requestURI, nil)
if err != nil {
tc.t.Fatalf("unable to create request %s", err)
@ -528,7 +515,6 @@ func (tc *Tester) AssertDeleteResponse(requestURI string, expectedStatusCode int
// AssertPostResponseBody POST to a URI and assert the response code and body
func (tc *Tester) AssertPostResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) {
req, err := http.NewRequest("POST", requestURI, requestBody)
if err != nil {
tc.t.Errorf("failed to create request %s", err)
@ -542,7 +528,6 @@ func (tc *Tester) AssertPostResponseBody(requestURI string, requestHeaders []str
// AssertPutResponseBody PUT to a URI and assert the response code and body
func (tc *Tester) AssertPutResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) {
req, err := http.NewRequest("PUT", requestURI, requestBody)
if err != nil {
tc.t.Errorf("failed to create request %s", err)
@ -556,7 +541,6 @@ func (tc *Tester) AssertPutResponseBody(requestURI string, requestHeaders []stri
// AssertPatchResponseBody PATCH to a URI and assert the response code and body
func (tc *Tester) AssertPatchResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) {
req, err := http.NewRequest("PATCH", requestURI, requestBody)
if err != nil {
tc.t.Errorf("failed to create request %s", err)

View file

@ -565,7 +565,7 @@ func cmdFmt(fl Flags) (int, error) {
output := caddyfile.Format(input)
if fl.Bool("overwrite") {
if err := os.WriteFile(formatCmdConfigFile, output, 0600); err != nil {
if err := os.WriteFile(formatCmdConfigFile, output, 0o600); err != nil {
return caddy.ExitCodeFailedStartup, fmt.Errorf("overwriting formatted file: %v", err)
}
return caddy.ExitCodeSuccess, nil

View file

@ -444,7 +444,7 @@ argument of --directory. If the directory does not exist, it will be created.
if dir == "" {
return caddy.ExitCodeFailedQuit, fmt.Errorf("designated output directory and specified section are required")
}
if err := os.MkdirAll(dir, 0755); err != nil {
if err := os.MkdirAll(dir, 0o755); err != nil {
return caddy.ExitCodeFailedQuit, err
}
if err := doc.GenManTree(rootCmd, &doc.GenManHeader{

View file

@ -200,7 +200,7 @@ func cmdExportStorage(fl Flags) (int, error) {
hdr := &tar.Header{
Name: k,
Mode: 0600,
Mode: 0o600,
Size: int64(len(v)),
}

View file

@ -52,5 +52,5 @@ func SplitUnixSocketPermissionsBits(addr string) (path string, fileMode fs.FileM
// default to 0200 (symbolic: `u=w,g=,o=`)
// if no permission bits are specified
return addr, 0200, nil
return addr, 0o200, nil
}

View file

@ -174,7 +174,6 @@ func (na NetworkAddress) listen(ctx context.Context, portOffset uint, config net
if err := os.Chmod(address, unixFileMode); err != nil {
return nil, fmt.Errorf("unable to set permissions (%s) on %s: %v", unixFileMode, address, err)
}
}
return socket, err
}

View file

@ -307,5 +307,7 @@ const (
const separator = string(filepath.Separator)
// Interface guard
var _ caddy.ListenerWrapper = (*tlsPlaceholderWrapper)(nil)
var _ caddyfile.Unmarshaler = (*tlsPlaceholderWrapper)(nil)
var (
_ caddy.ListenerWrapper = (*tlsPlaceholderWrapper)(nil)
_ caddyfile.Unmarshaler = (*tlsPlaceholderWrapper)(nil)
)

View file

@ -234,9 +234,11 @@ func (cr celHTTPRequest) Parent() interpreter.Activation {
func (cr celHTTPRequest) ConvertToNative(typeDesc reflect.Type) (any, error) {
return cr.Request, nil
}
func (celHTTPRequest) ConvertToType(typeVal ref.Type) ref.Val {
panic("not implemented")
}
func (cr celHTTPRequest) Equal(other ref.Val) ref.Val {
if o, ok := other.Value().(celHTTPRequest); ok {
return types.Bool(o.Request == cr.Request)
@ -255,12 +257,14 @@ type celPkixName struct{ *pkix.Name }
func (pn celPkixName) ConvertToNative(typeDesc reflect.Type) (any, error) {
return pn.Name, nil
}
func (pn celPkixName) ConvertToType(typeVal ref.Type) ref.Val {
if typeVal.TypeName() == "string" {
return types.String(pn.Name.String())
}
panic("not implemented")
}
func (pn celPkixName) Equal(other ref.Val) ref.Val {
if o, ok := other.Value().(string); ok {
return types.Bool(pn.Name.String() == o)

View file

@ -113,7 +113,7 @@ func (fsrv *FileServer) serveBrowse(root, dirPath string, w http.ResponseWriter,
fs = http.Dir(repl.ReplaceAll(fsrv.Root, "."))
}
var tplCtx = &templateContext{
tplCtx := &templateContext{
TemplateContext: templates.TemplateContext{
Root: fs,
Req: r,

View file

@ -1392,9 +1392,7 @@ func ParseCaddyfileNestedMatcherSet(d *caddyfile.Dispenser) (caddy.ModuleMap, er
return matcherSet, nil
}
var (
wordRE = regexp.MustCompile(`\w+`)
)
var wordRE = regexp.MustCompile(`\w+`)
const regexpPlaceholderPrefix = "http.regexp"

View file

@ -45,12 +45,15 @@ func (p parsedAddr) dialAddr() string {
}
return net.JoinHostPort(p.host, p.port)
}
func (p parsedAddr) rangedPort() bool {
return strings.Contains(p.port, "-")
}
func (p parsedAddr) replaceablePort() bool {
return strings.Contains(p.port, "{") && strings.Contains(p.port, "}")
}
func (p parsedAddr) isUnix() bool {
return caddy.IsUnixNetwork(p.network)
}

View file

@ -549,7 +549,6 @@ func (h *Handler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
h.RequestBuffers = int64(size)
} else if subdir == "response_buffers" {
h.ResponseBuffers = int64(size)
}
// TODO: These three properties are deprecated; remove them sometime after v2.6.4

View file

@ -284,7 +284,8 @@ func cmdReverseProxy(fs caddycmd.Flags) (int, error) {
var false bool
cfg := &caddy.Config{
Admin: &caddy.AdminConfig{Disabled: true,
Admin: &caddy.AdminConfig{
Disabled: true,
Config: &caddy.ConfigSettings{
Persist: &false,
},

View file

@ -251,7 +251,6 @@ func (c *client) Request(p map[string]string, req io.Reader) (resp *http.Respons
// Get issues a GET request to the fcgi responder.
func (c *client) Get(p map[string]string, body io.Reader, l int64) (resp *http.Response, err error) {
p["REQUEST_METHOD"] = "GET"
p["CONTENT_LENGTH"] = strconv.FormatInt(l, 10)
@ -260,7 +259,6 @@ func (c *client) Get(p map[string]string, body io.Reader, l int64) (resp *http.R
// Head issues a HEAD request to the fcgi responder.
func (c *client) Head(p map[string]string) (resp *http.Response, err error) {
p["REQUEST_METHOD"] = "HEAD"
p["CONTENT_LENGTH"] = "0"
@ -269,7 +267,6 @@ func (c *client) Head(p map[string]string) (resp *http.Response, err error) {
// Options issues an OPTIONS request to the fcgi responder.
func (c *client) Options(p map[string]string) (resp *http.Response, err error) {
p["REQUEST_METHOD"] = "OPTIONS"
p["CONTENT_LENGTH"] = "0"

View file

@ -450,7 +450,8 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyht
// It returns true when the loop is done and should break; false otherwise. The error value returned should
// be assigned to the proxyErr value for the next iteration of the loop (or the error handled after break).
func (h *Handler) proxyLoopIteration(r *http.Request, origReq *http.Request, w http.ResponseWriter, proxyErr error, start time.Time, retries int,
repl *caddy.Replacer, reqHeader http.Header, reqHost string, next caddyhttp.Handler) (bool, error) {
repl *caddy.Replacer, reqHeader http.Header, reqHost string, next caddyhttp.Handler,
) (bool, error) {
// get the updated list of upstreams
upstreams := h.Upstreams
if h.DynamicUpstreams != nil {

View file

@ -522,5 +522,7 @@ var streamingBufPool = sync.Pool{
},
}
const defaultBufferSize = 32 * 1024
const wordSize = int(unsafe.Sizeof(uintptr(0)))
const (
defaultBufferSize = 32 * 1024
wordSize = int(unsafe.Sizeof(uintptr(0)))
)

View file

@ -103,13 +103,11 @@ func (c TemplateContext) OriginalReq() http.Request {
// trusted files. If it is not trusted, be sure to use escaping functions
// in your template.
func (c TemplateContext) funcInclude(filename string, args ...any) (string, error) {
bodyBuf := bufPool.Get().(*bytes.Buffer)
bodyBuf.Reset()
defer bufPool.Put(bodyBuf)
err := c.readFileToBuffer(filename, bodyBuf)
if err != nil {
return "", err
}
@ -215,7 +213,6 @@ func (c TemplateContext) funcHTTPInclude(uri string) (string, error) {
// {{ template }} from the standard template library. If the imported file has
// no {{ define }} blocks, the name of the import will be the path
func (c *TemplateContext) funcImport(filename string) (string, error) {
bodyBuf := bufPool.Get().(*bytes.Buffer)
bodyBuf.Reset()
defer bufPool.Put(bodyBuf)

View file

@ -239,7 +239,7 @@ func (ash Handler) openDatabase() (*db.AuthDB, error) {
dbFolder := filepath.Join(caddy.AppDataDir(), "acme_server", key)
dbPath := filepath.Join(dbFolder, "db")
err := os.MkdirAll(dbFolder, 0755)
err := os.MkdirAll(dbFolder, 0o755)
if err != nil {
return nil, fmt.Errorf("making folder for CA database: %v", err)
}
@ -310,8 +310,10 @@ func (c resolverClient) LookupTxt(name string) ([]string, error) {
const defaultPathPrefix = "/acme/"
var keyCleaner = regexp.MustCompile(`[^\w.-_]`)
var databasePool = caddy.NewUsagePool()
var (
keyCleaner = regexp.MustCompile(`[^\w.-_]`)
databasePool = caddy.NewUsagePool()
)
type databaseCloser struct {
DB *db.AuthDB

View file

@ -376,15 +376,19 @@ func (ca CA) genIntermediate(rootCert *x509.Certificate, rootKey crypto.Signer)
func (ca CA) storageKeyCAPrefix() string {
return path.Join("pki", "authorities", certmagic.StorageKeys.Safe(ca.ID))
}
func (ca CA) storageKeyRootCert() string {
return path.Join(ca.storageKeyCAPrefix(), "root.crt")
}
func (ca CA) storageKeyRootKey() string {
return path.Join(ca.storageKeyCAPrefix(), "root.key")
}
func (ca CA) storageKeyIntermediateCert() string {
return path.Join(ca.storageKeyCAPrefix(), "intermediate.crt")
}
func (ca CA) storageKeyIntermediateKey() string {
return path.Join(ca.storageKeyCAPrefix(), "intermediate.key")
}

View file

@ -316,7 +316,7 @@ func (p *ConnectionPolicy) buildStandardTLSConfig(ctx caddy.Context) error {
return err
}
logFile, _, err := secretsLogPool.LoadOrNew(filename, func() (caddy.Destructor, error) {
w, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
w, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600)
return destructableWriter{w}, err
})
if err != nil {

View file

@ -126,7 +126,7 @@ func (fw FileWriter) OpenWriter() (io.WriteCloser, error) {
}
// otherwise just open a regular file
return os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
return os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666)
}
// UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax:

View file

@ -81,8 +81,7 @@ func hash(s string) string {
// of the SHA-256 hash of the content. Operates
// on string fields, or on arrays of strings
// where each string is hashed.
type HashFilter struct {
}
type HashFilter struct{}
// CaddyModule returns the Caddy module information.
func (HashFilter) CaddyModule() caddy.ModuleInfo {

View file

@ -131,7 +131,8 @@ func (r *Replacer) ReplaceFunc(input string, f ReplacementFunc) (string, error)
func (r *Replacer) replace(input, empty string,
treatUnknownAsEmpty, errOnEmpty, errOnUnknown bool,
f ReplacementFunc) (string, error) {
f ReplacementFunc,
) (string, error) {
if !strings.Contains(input, string(phOpen)) {
return input, nil
}