1
// Copyright 2011 The Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
19
`Adapt os.Open calls to new, easier API and rename O_CREAT O_CREATE.
21
http://codereview.appspot.com/4357052
25
func osopen(f *ast.File) bool {
26
if !imports(f, "os") {
31
walk(f, func(n interface{}) {
32
// Rename O_CREAT to O_CREATE.
33
if expr, ok := n.(ast.Expr); ok && isPkgDot(expr, "os", "O_CREAT") {
34
expr.(*ast.SelectorExpr).Sel.Name = "O_CREATE"
39
// Fix up calls to Open.
40
call, ok := n.(*ast.CallExpr)
41
if !ok || len(call.Args) != 3 {
44
if !isPkgDot(call.Fun, "os", "Open") {
47
sel := call.Fun.(*ast.SelectorExpr)
49
// os.Open(a, os.O_RDONLY, c) -> os.Open(a)
50
if isPkgDot(args[1], "os", "O_RDONLY") || isPkgDot(args[1], "syscall", "O_RDONLY") {
51
call.Args = call.Args[0:1]
55
// os.Open(a, createlike_flags, c) -> os.Create(a, c)
56
if isCreateFlag(args[1]) {
57
sel.Sel.Name = "Create"
58
if !isSimplePerm(args[2]) {
59
warn(sel.Pos(), "rewrote os.Open to os.Create with permission not 0666")
65
// Fallback: os.Open(a, b, c) -> os.OpenFile(a, b, c)
66
sel.Sel.Name = "OpenFile"
72
func isCreateFlag(flag ast.Expr) bool {
75
// OR'ing of flags: is O_CREATE on? + or | would be fine; we just look for os.O_CREATE
76
// and don't worry about the actual operator.
80
expr, isBinary := flag.(*ast.BinaryExpr)
84
sel, ok := lhs.(*ast.SelectorExpr)
85
if !ok || !isTopName(sel.X, "os") {
93
case "O_RDONLY", "O_WRONLY", "O_RDWR":
96
// Unexpected flag, like O_APPEND or O_EXCL.
97
// Be conservative and do not rewrite.
109
warn(p, "rewrote os.Open with O_CREATE but not O_TRUNC to os.Create")
114
func isSimplePerm(perm ast.Expr) bool {
115
basicLit, ok := perm.(*ast.BasicLit)
119
switch basicLit.Value {