summaryrefslogtreecommitdiff
path: root/src/cmd/fix/hmacnew.go
blob: c0c44ef3e6a8567441559a99fdf134322ea1efd3 (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
// 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"

func init() {
	register(hmacNewFix)
}

var hmacNewFix = fix{
	"hmacnew",
	"2012-01-19",
	hmacnew,
	`Deprecate hmac.NewMD5, hmac.NewSHA1 and hmac.NewSHA256.

This fix rewrites code using hmac.NewMD5, hmac.NewSHA1 and hmac.NewSHA256 to
use hmac.New:

	hmac.NewMD5(key) -> hmac.New(md5.New, key)
	hmac.NewSHA1(key) -> hmac.New(sha1.New, key)
	hmac.NewSHA256(key) -> hmac.New(sha256.New, key)

`,
}

func hmacnew(f *ast.File) (fixed bool) {
	if !imports(f, "crypto/hmac") {
		return
	}

	walk(f, func(n interface{}) {
		ce, ok := n.(*ast.CallExpr)
		if !ok {
			return
		}

		var pkg string
		switch {
		case isPkgDot(ce.Fun, "hmac", "NewMD5"):
			pkg = "md5"
		case isPkgDot(ce.Fun, "hmac", "NewSHA1"):
			pkg = "sha1"
		case isPkgDot(ce.Fun, "hmac", "NewSHA256"):
			pkg = "sha256"
		default:
			return
		}

		addImport(f, "crypto/"+pkg)

		ce.Fun = ast.NewIdent("hmac.New")
		ce.Args = append([]ast.Expr{ast.NewIdent(pkg + ".New")}, ce.Args...)

		fixed = true
	})

	return
}