Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: use gofumpt #5707

Merged
merged 2 commits into from
Aug 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ linters:
enable:
- bodyclose
- errcheck
- gofmt
- goimports
- gofumpt
- gosec
- gosimple
- govet
Expand Down
2 changes: 1 addition & 1 deletion admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
6 changes: 3 additions & 3 deletions caddy.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions caddyconfig/caddyfile/importgraph.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion caddyconfig/caddyfile/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 4 additions & 2 deletions caddyconfig/httpcaddyfile/addresses.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion caddyconfig/httpcaddyfile/directives.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down
13 changes: 7 additions & 6 deletions caddyconfig/httpcaddyfile/httptype.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
1 change: 0 additions & 1 deletion caddyconfig/httpcaddyfile/pkiapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 0 additions & 1 deletion caddyconfig/httpcaddyfile/tlsapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
16 changes: 0 additions & 16 deletions caddytest/caddytest.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand All @@ -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
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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")
Expand All @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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
}
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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()
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion cmd/commandfuncs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion cmd/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down
2 changes: 1 addition & 1 deletion cmd/storagefuncs.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ func cmdExportStorage(fl Flags) (int, error) {

hdr := &tar.Header{
Name: k,
Mode: 0600,
Mode: 0o600,
Size: int64(len(v)),
}

Expand Down
2 changes: 1 addition & 1 deletion internal/sockets.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
1 change: 0 additions & 1 deletion listeners.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
6 changes: 4 additions & 2 deletions modules/caddyhttp/caddyhttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)
4 changes: 4 additions & 0 deletions modules/caddyhttp/celmatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion modules/caddyhttp/fileserver/browse.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 1 addition & 3 deletions modules/caddyhttp/matchers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
3 changes: 3 additions & 0 deletions modules/caddyhttp/reverseproxy/addresses.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
Loading
Loading