summaryrefslogtreecommitdiff
path: root/src/cmd/fix/httpfs.go
blob: d87b30f9ded8ed87c04de50a59b7377fbfc0d0a3 (plain)
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
// Copyright 2011 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"go/ast"
	"go/token"
)

func init() {
	register(httpFileSystemFix)
}

var httpFileSystemFix = fix{
	"httpfs",
	"2011-06-27",
	httpfs,
	`Adapt http FileServer to take a FileSystem.

http://codereview.appspot.com/4629047  http FileSystem interface
`,
}

func httpfs(f *ast.File) bool {
	if !imports(f, "http") {
		return false
	}

	fixed := false
	walk(f, func(n interface{}) {
		call, ok := n.(*ast.CallExpr)
		if !ok || !isPkgDot(call.Fun, "http", "FileServer") {
			return
		}
		if len(call.Args) != 2 {
			return
		}
		dir, prefix := call.Args[0], call.Args[1]
		call.Args = []ast.Expr{&ast.CallExpr{
			Fun: &ast.SelectorExpr{
				X:   ast.NewIdent("http"),
				Sel: ast.NewIdent("Dir"),
			},
			Args: []ast.Expr{dir},
		}}
		wrapInStripHandler := true
		if prefixLit, ok := prefix.(*ast.BasicLit); ok {
			if prefixLit.Kind == token.STRING && (prefixLit.Value == `"/"` || prefixLit.Value == `""`) {
				wrapInStripHandler = false
			}
		}
		if wrapInStripHandler {
			call.Fun.(*ast.SelectorExpr).Sel = ast.NewIdent("StripPrefix")
			call.Args = []ast.Expr{
				prefix,
				&ast.CallExpr{
					Fun: &ast.SelectorExpr{
						X:   ast.NewIdent("http"),
						Sel: ast.NewIdent("FileServer"),
					},
					Args: call.Args,
				},
			}
		}
		fixed = true
	})
	return fixed
}