package main
import (
+ "errors"
"http"
"io/ioutil"
- "os"
"regexp"
"template"
)
Body []byte
}
-func (p *Page) save() os.Error {
+func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
-func loadPage(title string) (*Page, os.Error) {
+func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
p := &Page{Title: title, Body: []byte(body)}
err = p.save()
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/view/"+title, http.StatusFound)
}
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
- t, err := template.ParseFile(tmpl+".html")
+ t, err := template.ParseFile(tmpl + ".html")
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = t.Execute(w, p)
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
var titleValidator = regexp.MustCompile("^[a-zA-Z0-9]+$")
-func getTitle(w http.ResponseWriter, r *http.Request) (title string, err os.Error) {
+func getTitle(w http.ResponseWriter, r *http.Request) (title string, err error) {
title = r.URL.Path[lenPath:]
if !titleValidator.MatchString(title) {
http.NotFound(w, r)
- err = os.NewError("Invalid Page Title")
+ err = errors.New("Invalid Page Title")
}
return
}
import (
"http"
"io/ioutil"
- "os"
"template"
)
Body []byte
}
-func (p *Page) save() os.Error {
+func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
-func loadPage(title string) (*Page, os.Error) {
+func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
import (
"http"
"io/ioutil"
- "os"
"regexp"
"template"
)
Body []byte
}
-func (p *Page) save() os.Error {
+func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
-func loadPage(title string) (*Page, os.Error) {
+func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
p := &Page{Title: title, Body: []byte(body)}
err := p.save()
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/view/"+title, http.StatusFound)
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
t, err := template.ParseFile(tmpl+".html", nil)
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = t.Execute(w, p)
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
import (
"http"
"io/ioutil"
- "os"
"template"
)
Body []byte
}
-func (p *Page) save() os.Error {
+func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
-func loadPage(title string) (*Page, os.Error) {
+func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
import (
"http"
"io/ioutil"
- "os"
"regexp"
"template"
)
Body []byte
}
-func (p *Page) save() os.Error {
+func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
-func loadPage(title string) (*Page, os.Error) {
+func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
p := &Page{Title: title, Body: []byte(body)}
err := p.save()
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/view/"+title, http.StatusFound)
func init() {
for _, tmpl := range []string{"edit", "view"} {
- t := template.Must(template.ParseFile(tmpl+".html"))
+ t := template.Must(template.ParseFile(tmpl + ".html"))
templates[tmpl] = t
}
}
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
err := templates[tmpl].Execute(w, p)
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
log.Fatal("no url supplied")
}
var r *http.Response
- var err os.Error
+ var err error
if *post != "" {
b := strings.NewReader(*post)
r, err = http.Post(url, "application/x-www-form-urlencoded", b)
</p>
<pre>
-func (p *Page) save() os.Error {
+func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
</p>
<pre>
-func loadPage(title string) (*Page, os.Error) {
+func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
t, err := template.ParseFile(tmpl+".html", nil)
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = t.Execute(w, p)
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
</pre>
p := &Page{Title: title, Body: []byte(body)}
err = p.save()
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/view/"+title, http.StatusFound)
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
err := templates[tmpl].Execute(w, p)
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
</pre>
</p>
<pre>
-func getTitle(w http.ResponseWriter, r *http.Request) (title string, err os.Error) {
+func getTitle(w http.ResponseWriter, r *http.Request) (title string, err error) {
title = r.URL.Path[lenPath:]
if !titleValidator.MatchString(title) {
http.NotFound(w, r)
- err = os.NewError("Invalid Page Title")
+ err = errors.New("Invalid Page Title")
}
return
}
p := &Page{Title: title, Body: []byte(body)}
err = p.save()
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/view/"+title, http.StatusFound)
p := &Page{Title: title, Body: []byte(body)}
err := p.save()
if err != nil {
- http.Error(w, err.String(), http.StatusInternalServerError)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/view/"+title, http.StatusFound)
"fmt"
"http"
"io/ioutil"
- "os"
)
type Page struct {
Body []byte
}
-func (p *Page) save() os.Error {
+func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
-func loadPage(title string) (*Page, os.Error) {
+func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
import (
"fmt"
"io/ioutil"
- "os"
)
type Page struct {
Body []byte
}
-func (p *Page) save() os.Error {
+func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
import (
"fmt"
"io/ioutil"
- "os"
)
type Page struct {
Body []byte
}
-func (p *Page) save() os.Error {
+func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
-func loadPage(title string) (*Page, os.Error) {
+func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
"fmt"
"http"
"io/ioutil"
- "os"
)
type Page struct {
Body []byte
}
-func (p *Page) save() os.Error {
+func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
-func loadPage(title string) (*Page, os.Error) {
+func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
if err != nil {
log.Println("Error", r.url, err)
r.errCount++
- return err.String()
+ return err.Error()
}
r.errCount = 0
return resp.Status
exported factory to use is <code>OpenFile</code> (we'll explain that name in a moment):
<p>
<pre><!--{{code "progs/file.go" `/func.OpenFile/` `/^}/`}}
--->func OpenFile(name string, mode int, perm uint32) (file *File, err os.Error) {
+-->func OpenFile(name string, mode int, perm uint32) (file *File, err error) {
r, e := syscall.Open(name, mode, perm)
if e != 0 {
err = os.Errno(e)
O_TRUNC = syscall.O_TRUNC
)
-func Open(name string) (file *File, err os.Error) {
+func Open(name string) (file *File, err error) {
return OpenFile(name, O_RDONLY, 0)
}
</pre>
<p>
<pre><!--{{code "progs/file.go" `/func.Create/` `/^}/`}}
--->func Create(name string) (file *File, err os.Error) {
+-->func Create(name string) (file *File, err error) {
return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}
</pre>
each of which declares a receiver variable <code>file</code>.
<p>
<pre><!--{{code "progs/file.go" `/Close/` "$"}}
--->func (file *File) Close() os.Error {
+-->func (file *File) Close() error {
if file == nil {
return os.EINVAL
}
return nil
}
-func (file *File) Read(b []byte) (ret int, err os.Error) {
+func (file *File) Read(b []byte) (ret int, err error) {
if file == nil {
return -1, os.EINVAL
}
return int(r), err
}
-func (file *File) Write(b []byte) (ret int, err os.Error) {
+func (file *File) Write(b []byte) (ret int, err error) {
if file == nil {
return -1, os.EINVAL
}
file.Stdout.Write(hello)
f, err := file.Open("/does/not/exist")
if f == nil {
- fmt.Printf("can't open file; err=%s\n", err.String())
+ fmt.Printf("can't open file; err=%s\n", err.Error())
os.Exit(1)
}
}
<p>
<pre><!--{{code "progs/cat_rot13.go" `/type.reader/` `/^}/`}}
-->type reader interface {
- Read(b []byte) (ret int, err os.Error)
+ Read(b []byte) (ret int, err error)
String() string
}
</pre>
return &rotate13{source}
}
-func (r13 *rotate13) Read(b []byte) (ret int, err os.Error) {
+func (r13 *rotate13) Read(b []byte) (ret int, err error) {
r, e := r13.source.Read(b)
for i := 0; i < r; i++ {
b[i] = rot13(b[i])
}
type reader interface {
- Read(b []byte) (ret int, err os.Error)
+ Read(b []byte) (ret int, err error)
String() string
}
return &rotate13{source}
}
-func (r13 *rotate13) Read(b []byte) (ret int, err os.Error) {
+func (r13 *rotate13) Read(b []byte) (ret int, err error) {
r, e := r13.source.Read(b)
for i := 0; i < r; i++ {
b[i] = rot13(b[i])
Stderr = newFile(syscall.Stderr, "/dev/stderr")
)
-func OpenFile(name string, mode int, perm uint32) (file *File, err os.Error) {
+func OpenFile(name string, mode int, perm uint32) (file *File, err error) {
r, e := syscall.Open(name, mode, perm)
if e != 0 {
err = os.Errno(e)
O_TRUNC = syscall.O_TRUNC
)
-func Open(name string) (file *File, err os.Error) {
+func Open(name string) (file *File, err error) {
return OpenFile(name, O_RDONLY, 0)
}
-func Create(name string) (file *File, err os.Error) {
+func Create(name string) (file *File, err error) {
return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}
-func (file *File) Close() os.Error {
+func (file *File) Close() error {
if file == nil {
return os.EINVAL
}
return nil
}
-func (file *File) Read(b []byte) (ret int, err os.Error) {
+func (file *File) Read(b []byte) (ret int, err error) {
if file == nil {
return -1, os.EINVAL
}
return int(r), err
}
-func (file *File) Write(b []byte) (ret int, err os.Error) {
+func (file *File) Write(b []byte) (ret int, err error) {
if file == nil {
return -1, os.EINVAL
}
Stderr = newFile(syscall.Stderr, "/dev/stderr")
)
-func OpenFile(name string, mode int, perm uint32) (file *File, err os.Error) {
+func OpenFile(name string, mode int, perm uint32) (file *File, err error) {
r, e := syscall.Open(name, mode, perm)
if e != 0 {
err = os.Errno(e)
O_TRUNC = syscall.O_TRUNC
)
-func Open(name string) (file *File, err os.Error) {
+func Open(name string) (file *File, err error) {
return OpenFile(name, O_RDONLY, 0)
}
-func Create(name string) (file *File, err os.Error) {
+func Create(name string) (file *File, err error) {
return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}
-func (file *File) Close() os.Error {
+func (file *File) Close() error {
if file == nil {
return os.EINVAL
}
return nil
}
-func (file *File) Read(b []byte) (ret int, err os.Error) {
+func (file *File) Read(b []byte) (ret int, err error) {
if file == nil {
return -1, os.EINVAL
}
return int(r), err
}
-func (file *File) Write(b []byte) (ret int, err os.Error) {
+func (file *File) Write(b []byte) (ret int, err error) {
if file == nil {
return -1, os.EINVAL
}
file.Stdout.Write(hello)
f, err := file.Open("/does/not/exist")
if f == nil {
- fmt.Printf("can't open file; err=%s\n", err.String())
+ fmt.Printf("can't open file; err=%s\n", err.Error())
os.Exit(1)
}
}
"os"
)
-func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) os.Error {
+func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) error {
r, err := os.Open(srcfile)
if err != nil {
return err
return err
}
-func DecryptAndGunzip(dstfile, srcfile string, key, iv []byte) os.Error {
+func DecryptAndGunzip(dstfile, srcfile string, key, iv []byte) error {
f, err := os.Open(srcfile)
if err != nil {
return err
"os"
)
-func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) os.Error {
+func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) error {
r, err := os.Open(srcfile)
if err != nil {
return err
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-
// The template uses the function "code" to inject program
// source into the output by extracting code from files and
// injecting them as HTML-escaped <pre> blocks.
return ""
}
-func code(file string, arg ...interface{}) (string, os.Error) {
+func code(file string, arg ...interface{}) (string, error) {
text := contents(file)
var command string
switch len(arg) {
// SetString interprets s as a number in the given base
// and sets z to that value. The base must be in the range [2,36].
// SetString returns an error if s cannot be parsed or the base is invalid.
-func (z *Int) SetString(s string, base int) os.Error {
+func (z *Int) SetString(s string, base int) error {
z.doinit()
if base < 2 || base > 36 {
return os.EINVAL
C.uuid_generate(&uuid[0])
}
-func Size(name string) (int64, os.Error) {
+func Size(name string) (int64, error) {
var st C.struct_stat
p := C.CString(name)
_, err := C.stat(p, &st)
return int64(C.ulong(st.st_size)), nil
}
-func Strtol(s string, base int) (int, os.Error) {
+func Strtol(s string, base int) (int, error) {
p := C.CString(s)
n, err := C.strtol(p, nil, C.int(base))
C.free(unsafe.Pointer(p))
)
// run is a simple wrapper for exec.Run/Close
-func run(envv []string, dir string, argv ...string) os.Error {
+func run(envv []string, dir string, argv ...string) error {
if *verbose {
log.Println("run", argv)
}
// process combined stdout and stderr output, exit status and error.
// The error returned is nil, if process is started successfully,
// even if exit status is not 0.
-func runLog(envv []string, logfile, dir string, argv ...string) (string, int, os.Error) {
+func runLog(envv []string, logfile, dir string, argv ...string) (string, int, error) {
if *verbose {
log.Println("runLog", argv)
}
err := cmd.Run()
if err != nil {
- if ws, ok := err.(*os.Waitmsg); ok {
+ if ws, ok := err.(*exec.ExitError); ok {
return b.String(), ws.ExitStatus(), nil
}
}
import (
"bytes"
+ "errors"
"fmt"
"http"
"json"
"log"
- "os"
"strconv"
"url"
)
// dash runs the given method and command on the dashboard.
// If args is not nil, it is the query or post parameters.
// If resp is not nil, dash unmarshals the body as JSON into resp.
-func dash(meth, cmd string, resp interface{}, args param) os.Error {
+func dash(meth, cmd string, resp interface{}, args param) error {
var r *http.Response
- var err os.Error
+ var err error
if *verbose {
log.Println("dash", cmd, args)
}
return nil
}
-func dashStatus(meth, cmd string, args param) os.Error {
+func dashStatus(meth, cmd string, args param) error {
var resp struct {
Status string
Error string
return err
}
if resp.Status != "OK" {
- return os.NewError("/build: " + resp.Error)
+ return errors.New("/build: " + resp.Error)
}
return nil
}
// todo returns the next hash to build.
-func (b *Builder) todo() (rev string, err os.Error) {
+func (b *Builder) todo() (rev string, err error) {
var resp []struct {
Hash string
}
}
// recordResult sends build results to the dashboard
-func (b *Builder) recordResult(buildLog string, hash string) os.Error {
+func (b *Builder) recordResult(buildLog string, hash string) error {
return dash("POST", "build", nil, param{
"builder": b.name,
"key": b.key,
}
// packages fetches a list of package paths from the dashboard
-func packages() (pkgs []string, err os.Error) {
+func packages() (pkgs []string, err error) {
var resp struct {
Packages []struct {
Path string
}
// updatePackage sends package build results and info dashboard
-func (b *Builder) updatePackage(pkg string, ok bool, buildLog, info string) os.Error {
+func (b *Builder) updatePackage(pkg string, ok bool, buildLog, info string) error {
return dash("POST", "package", nil, param{
"builder": b.name,
"key": b.key,
}
// postCommit informs the dashboard of a new commit
-func postCommit(key string, l *HgLog) os.Error {
+func postCommit(key string, l *HgLog) error {
return dashStatus("POST", "commit", param{
"key": key,
"node": l.Hash,
package main
import (
+ "errors"
"flag"
"fmt"
"io/ioutil"
}
}
-func NewBuilder(builder string) (*Builder, os.Error) {
+func NewBuilder(builder string) (*Builder, error) {
b := &Builder{name: builder}
// get goos/goarch from builder string
return true
}
-func (b *Builder) buildHash(hash string) (err os.Error) {
+func (b *Builder) buildHash(hash string) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("%s build: %s: %s", b.name, hash, err)
// if we're in external mode, build all packages and return
if *external {
if status != 0 {
- return os.NewError("go build failed")
+ return errors.New("go build failed")
}
return b.buildPackages(workpath, hash)
}
}
// fullHash returns the full hash for the given Mercurial revision.
-func fullHash(rev string) (hash string, err os.Error) {
+func fullHash(rev string) (hash string, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("fullHash: %s: %s", rev, err)
var revisionRe = regexp.MustCompile(`^([^ ]+) +[0-9]+:([0-9a-f]+)$`)
// firstTag returns the hash and tag of the most recent tag matching re.
-func firstTag(re *regexp.Regexp) (hash string, tag string, err os.Error) {
+func firstTag(re *regexp.Regexp) (hash string, tag string, err error) {
o, _, err := runLog(nil, "", goroot, "hg", "tags")
for _, l := range strings.Split(o, "\n") {
if l == "" {
}
s := revisionRe.FindStringSubmatch(l)
if s == nil {
- err = os.NewError("couldn't find revision number")
+ err = errors.New("couldn't find revision number")
return
}
if !re.MatchString(s[1]) {
hash, err = fullHash(s[2])
return
}
- err = os.NewError("no matching tag found")
+ err = errors.New("no matching tag found")
return
}
package main
import (
+ "errors"
"fmt"
"go/doc"
"go/parser"
const MaxCommentLength = 500 // App Engine won't store more in a StringProperty.
-func (b *Builder) buildPackages(workpath string, hash string) os.Error {
+func (b *Builder) buildPackages(workpath string, hash string) error {
logdir := filepath.Join(*buildroot, "log")
if err := os.Mkdir(logdir, 0755); err != nil {
return err
filepath.Ext(fi.Name) == ".go"
}
-func packageComment(pkg, pkgpath string) (info string, err os.Error) {
+func packageComment(pkg, pkgpath string) (info string, err error) {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, pkgpath, isGoFile, parser.PackageClauseOnly|parser.ParseComments)
if err != nil {
continue
}
if info != "" {
- return "", os.NewError("multiple packages with docs")
+ return "", errors.New("multiple packages with docs")
}
info = pdoc.Doc
}
// write request Body to x.go
f, err := os.Create(src)
if err != nil {
- error(w, nil, err)
+ error_(w, nil, err)
return
}
defer os.Remove(src)
defer f.Close()
_, err = io.Copy(f, req.Body)
if err != nil {
- error(w, nil, err)
+ error_(w, nil, err)
return
}
f.Close()
out, err := run(archChar+"g", "-o", obj, src)
defer os.Remove(obj)
if err != nil {
- error(w, out, err)
+ error_(w, out, err)
return
}
out, err = run(archChar+"l", "-o", bin, obj)
defer os.Remove(bin)
if err != nil {
- error(w, out, err)
+ error_(w, out, err)
return
}
// run x
out, err = run(bin)
if err != nil {
- error(w, out, err)
+ error_(w, out, err)
}
// write the output of x as the http response
// error writes compile, link, or runtime errors to the HTTP connection.
// The JavaScript interface uses the 404 status code to identify the error.
-func error(w http.ResponseWriter, out []byte, err os.Error) {
+func error_(w http.ResponseWriter, out []byte, err error) {
w.WriteHeader(404)
if out != nil {
output.Execute(w, out)
} else {
- output.Execute(w, err.String())
+ output.Execute(w, err.Error())
}
}
// run executes the specified command and returns its output and an error.
-func run(cmd ...string) ([]byte, os.Error) {
+func run(cmd ...string) ([]byte, error) {
return exec.Command(cmd[0], cmd[1:]...).CombinedOutput()
}
}
sawC = true
if s.Name != nil {
- error(s.Path.Pos(), `cannot rename import "C"`)
+ error_(s.Path.Pos(), `cannot rename import "C"`)
}
cg := s.Doc
if cg == nil && len(d.Specs) == 1 {
}
}
if !sawC {
- error(token.NoPos, `cannot find import "C"`)
+ error_(token.NoPos, `cannot find import "C"`)
}
// In ast2, strip the import "C" line.
}
goname := sel.Sel.Name
if goname == "errno" {
- error(sel.Pos(), "cannot refer to errno directly; see documentation")
+ error_(sel.Pos(), "cannot refer to errno directly; see documentation")
return
}
name := f.Name[goname]
name := strings.TrimSpace(string(c.Text[9:]))
if name == "" {
- error(c.Pos(), "export missing name")
+ error_(c.Pos(), "export missing name")
}
if name != n.Name.Name {
- error(c.Pos(), "export comment has wrong name %q, want %q", name, n.Name.Name)
+ error_(c.Pos(), "export comment has wrong name %q, want %q", name, n.Name.Name)
}
f.ExpFunc = append(f.ExpFunc, &ExpFunc{
// everything else just recurs
default:
- error(token.NoPos, "unexpected type %T in walk", x, visit)
+ error_(token.NoPos, "unexpected type %T in walk", x, visit)
panic("unexpected type")
case nil:
"debug/macho"
"debug/pe"
"encoding/binary"
+ "errors"
"flag"
"fmt"
"go/ast"
// pkgConfig runs pkg-config and extracts --libs and --cflags information
// for packages.
-func pkgConfig(packages []string) (cflags, ldflags []string, err os.Error) {
+func pkgConfig(packages []string) (cflags, ldflags []string, err error) {
for _, name := range packages {
if len(name) == 0 || name[0] == '-' {
- return nil, nil, os.NewError(fmt.Sprintf("invalid name: %q", name))
+ return nil, nil, errors.New(fmt.Sprintf("invalid name: %q", name))
}
}
stdout, stderr, ok := run(nil, args)
if !ok {
os.Stderr.Write(stderr)
- return nil, nil, os.NewError("pkg-config failed")
+ return nil, nil, errors.New("pkg-config failed")
}
cflags, err = splitQuoted(string(stdout))
if err != nil {
stdout, stderr, ok = run(nil, args)
if !ok {
os.Stderr.Write(stderr)
- return nil, nil, os.NewError("pkg-config failed")
+ return nil, nil, errors.New("pkg-config failed")
}
ldflags, err = splitQuoted(string(stdout))
return
//
// []string{"a", "b:c d", "ef", `g"`}
//
-func splitQuoted(s string) (r []string, err os.Error) {
+func splitQuoted(s string) (r []string, err error) {
var args []string
arg := make([]rune, len(s))
escaped := false
args = append(args, string(arg[:i]))
}
if quote != 0 {
- err = os.NewError("unclosed quote")
+ err = errors.New("unclosed quote")
} else if escaped {
- err = os.NewError("unfinished escaping")
+ err = errors.New("unfinished escaping")
}
return args, err
}
case strings.Contains(line, ": statement with no effect"):
what = "not-type" // const or func or var
case strings.Contains(line, "undeclared"):
- error(token.NoPos, "%s", strings.TrimSpace(line[colon+1:]))
+ error_(token.NoPos, "%s", strings.TrimSpace(line[colon+1:]))
case strings.Contains(line, "is not an integer constant"):
isConst[i] = false
continue
if n.Kind != "" {
continue
}
- error(token.NoPos, "could not determine kind of name for C.%s", n.Go)
+ error_(token.NoPos, "could not determine kind of name for C.%s", n.Go)
}
if nerrors > 0 {
fatalf("unresolved names")
// functions are only used in calls.
for _, r := range f.Ref {
if r.Name.Kind == "const" && r.Name.Const == "" {
- error(r.Pos(), "unable to find value of constant C.%s", r.Name.Go)
+ error_(r.Pos(), "unable to find value of constant C.%s", r.Name.Go)
}
var expr ast.Expr = ast.NewIdent(r.Name.Mangle) // default
switch r.Context {
expr = r.Name.Type.Go
break
}
- error(r.Pos(), "call of non-function C.%s", r.Name.Go)
+ error_(r.Pos(), "call of non-function C.%s", r.Name.Go)
break
}
if r.Context == "call2" {
if r.Name.FuncType.Result == nil {
- error(r.Pos(), "assignment count mismatch: 2 = 0")
+ error_(r.Pos(), "assignment count mismatch: 2 = 0")
}
// Invent new Name for the two-result function.
n := f.Name["2"+r.Name.Go]
}
case "expr":
if r.Name.Kind == "func" {
- error(r.Pos(), "must call C.%s", r.Name.Go)
+ error_(r.Pos(), "must call C.%s", r.Name.Go)
}
if r.Name.Kind == "type" {
// Okay - might be new(T)
case "type":
if r.Name.Kind != "type" {
- error(r.Pos(), "expression C.%s used as type", r.Name.Go)
+ error_(r.Pos(), "expression C.%s used as type", r.Name.Go)
} else {
expr = r.Name.Type.Go
}
default:
if r.Name.Kind == "func" {
- error(r.Pos(), "must call C.%s", r.Name.Go)
+ error_(r.Pos(), "must call C.%s", r.Name.Go)
}
}
*r.Expr = expr
if p.PackageName == "" {
p.PackageName = f.Package
} else if p.PackageName != f.Package {
- error(token.NoPos, "inconsistent package names: %s, %s", p.PackageName, f.Package)
+ error_(token.NoPos, "inconsistent package names: %s, %s", p.PackageName, f.Package)
}
if p.Name == nil {
if p.Name[k] == nil {
p.Name[k] = v
} else if !reflect.DeepEqual(p.Name[k], v) {
- error(token.NoPos, "inconsistent definitions for C.%s", k)
+ error_(token.NoPos, "inconsistent definitions for C.%s", k)
}
}
}
}
return r
}
- error(e.Pos(), "unrecognized Go type %s", t.Name)
+ error_(e.Pos(), "unrecognized Go type %s", t.Name)
return &Type{Size: 4, Align: 4, C: c("int")}
case *ast.SelectorExpr:
id, ok := t.X.(*ast.Ident)
return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
}
}
- error(e.Pos(), "unrecognized Go type %T", e)
+ error_(e.Pos(), "unrecognized Go type %T", e)
return &Type{Size: 4, Align: 4, C: c("int")}
}
var nerrors int
-func error(pos token.Pos, msg string, args ...interface{}) {
+func error_(pos token.Pos, msg string, args ...interface{}) {
nerrors++
if pos.IsValid() {
fmt.Fprintf(os.Stderr, "%s: ", fset.Position(pos).String())
"archive/zip"
"http"
"log"
- "os"
"path"
)
-func serveError(w http.ResponseWriter, r *http.Request, relpath string, err os.Error) {
+func serveError(w http.ResponseWriter, r *http.Request, relpath string, err error) {
contents := applyTemplate(errorHTML, "errorHTML", err) // err may contain an absolute path!
w.WriteHeader(http.StatusNotFound)
servePage(w, "File "+relpath, "", "", contents)
package main
import (
+ "errors"
"fmt"
"http"
"io"
XML string `xml:"innerxml"`
// Derived from Src; not in XML.
- Err os.Error
+ Err error
File string
Lo int
LoByte int
}
// loadCodewalk reads a codewalk from the named XML file.
-func loadCodewalk(filename string) (*Codewalk, os.Error) {
+func loadCodewalk(filename string) (*Codewalk, error) {
f, err := fs.Open(filename)
if err != nil {
return nil, err
// It returns the lo and hi byte offset of the matched region within data.
// See http://plan9.bell-labs.com/sys/doc/sam/sam.html Table II
// for details on the syntax.
-func addrToByteRange(addr string, start int, data []byte) (lo, hi int, err os.Error) {
+func addrToByteRange(addr string, start int, data []byte) (lo, hi int, err error) {
var (
dir byte
prevc byte
c := addr[0]
switch c {
default:
- err = os.NewError("invalid address syntax near " + string(c))
+ err = errors.New("invalid address syntax near " + string(c))
case ',':
if len(addr) == 1 {
hi = len(data)
// (or characters) after hi. Applying -n (or -#n) means to back up n lines
// (or characters) before lo.
// The return value is the new lo, hi.
-func addrNumber(data []byte, lo, hi int, dir byte, n int, charOffset bool) (int, int, os.Error) {
+func addrNumber(data []byte, lo, hi int, dir byte, n int, charOffset bool) (int, int, error) {
switch dir {
case 0:
lo = 0
}
}
- return 0, 0, os.NewError("address out of range")
+ return 0, 0, errors.New("address out of range")
}
// addrRegexp searches for pattern in the given direction starting at lo, hi.
// The direction dir is '+' (search forward from hi) or '-' (search backward from lo).
// Backward searches are unimplemented.
-func addrRegexp(data []byte, lo, hi int, dir byte, pattern string) (int, int, os.Error) {
+func addrRegexp(data []byte, lo, hi int, dir byte, pattern string) (int, int, error) {
re, err := regexp.Compile(pattern)
if err != nil {
return 0, 0, err
if dir == '-' {
// Could implement reverse search using binary search
// through file, but that seems like overkill.
- return 0, 0, os.NewError("reverse search not implemented")
+ return 0, 0, errors.New("reverse search not implemented")
}
m := re.FindIndex(data[hi:])
if len(m) > 0 {
m = re.FindIndex(data)
}
if len(m) == 0 {
- return 0, 0, os.NewError("no match for " + pattern)
+ return 0, 0, errors.New("no match for " + pattern)
}
return m[0], m[1], nil
}
// The FileSystem interface specifies the methods godoc is using
// to access the file system for which it serves documentation.
type FileSystem interface {
- Open(path string) (io.ReadCloser, os.Error)
- Lstat(path string) (FileInfo, os.Error)
- Stat(path string) (FileInfo, os.Error)
- ReadDir(path string) ([]FileInfo, os.Error)
+ Open(path string) (io.ReadCloser, error)
+ Lstat(path string) (FileInfo, error)
+ Stat(path string) (FileInfo, error)
+ ReadDir(path string) ([]FileInfo, error)
}
// ReadFile reads the file named by path from fs and returns the contents.
-func ReadFile(fs FileSystem, path string) ([]byte, os.Error) {
+func ReadFile(fs FileSystem, path string) ([]byte, error) {
rc, err := fs.Open(path)
if err != nil {
return nil, err
// osFS is the OS-specific implementation of FileSystem
type osFS struct{}
-func (osFS) Open(path string) (io.ReadCloser, os.Error) {
+func (osFS) Open(path string) (io.ReadCloser, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
return f, nil
}
-func (osFS) Lstat(path string) (FileInfo, os.Error) {
+func (osFS) Lstat(path string) (FileInfo, error) {
fi, err := os.Lstat(path)
return osFI{fi}, err
}
-func (osFS) Stat(path string) (FileInfo, os.Error) {
+func (osFS) Stat(path string) (FileInfo, error) {
fi, err := os.Stat(path)
return osFI{fi}, err
}
-func (osFS) ReadDir(path string) ([]FileInfo, os.Error) {
+func (osFS) ReadDir(path string) ([]FileInfo, error) {
l0, err := ioutil.ReadDir(path) // l0 is sorted
if err != nil {
return nil, err
// readDirList reads a file containing a newline-separated list
// of directory paths and returns the list of paths.
-func readDirList(filename string) ([]string, os.Error) {
+func readDirList(filename string) ([]string, error) {
contents, err := ReadFile(fs, filename)
if err != nil {
return nil, err
indent int // valid if state == indenting
}
-func (p *tconv) writeIndent() (err os.Error) {
+func (p *tconv) writeIndent() (err error) {
i := p.indent
for i >= len(spaces) {
i -= len(spaces)
return
}
-func (p *tconv) Write(data []byte) (n int, err os.Error) {
+func (p *tconv) Write(data []byte) (n int, err error) {
if len(data) == 0 {
return
}
Dirs *DirList // nil if no directory information
DirTime int64 // directory time stamp in seconds since epoch
IsPkg bool // false if this is not documenting a real package
- Err os.Error // directory read error or nil
+ Err error // directory read error or nil
}
func (info *PageInfo) IsEmpty() bool {
}
// fsReadDir implements ReadDir for the go/build package.
-func fsReadDir(dir string) ([]*os.FileInfo, os.Error) {
+func fsReadDir(dir string) ([]*os.FileInfo, error) {
fi, err := fs.ReadDir(dir)
if err != nil {
return nil, err
}
// fsReadFile implements ReadFile for the go/build package.
-func fsReadFile(dir, name string) (path string, data []byte, err os.Error) {
+func fsReadFile(dir, name string) (path string, data []byte, err error) {
path = filepath.Join(dir, name)
data, err = ReadFile(fs, path)
return
index := index.(*Index)
// identifier search
- var err os.Error
+ var err error
result.Pak, result.Hit, result.Alt, err = index.Lookup(query)
if err != nil && *maxResults <= 0 {
// ignore the error if full text search is enabled
// since the query may be a valid regular expression
- result.Alert = "Error in query string: " + err.String()
+ result.Alert = "Error in query string: " + err.Error()
return
}
if *maxResults > 0 && query != "" {
rx, err := regexp.Compile(query)
if err != nil {
- result.Alert = "Error in query regular expression: " + err.String()
+ result.Alert = "Error in query regular expression: " + err.Error()
return
}
// If we get maxResults+1 results we know that there are more than
return c
}
-func readIndex(filenames string) os.Error {
+func readIndex(filenames string) error {
matches, err := filepath.Glob(filenames)
if err != nil {
return err
list zipList
}
-func (f *httpZipFile) Close() os.Error {
+func (f *httpZipFile) Close() error {
if f.info.IsRegular() {
return f.ReadCloser.Close()
}
return nil
}
-func (f *httpZipFile) Stat() (*os.FileInfo, os.Error) {
+func (f *httpZipFile) Stat() (*os.FileInfo, error) {
return &f.info, nil
}
-func (f *httpZipFile) Readdir(count int) ([]os.FileInfo, os.Error) {
+func (f *httpZipFile) Readdir(count int) ([]os.FileInfo, error) {
var list []os.FileInfo
dirname := f.path + "/"
prevname := ""
}
if count >= 0 && len(list) == 0 {
- return nil, os.EOF
+ return nil, io.EOF
}
return list, nil
}
-func (f *httpZipFile) Seek(offset int64, whence int) (int64, os.Error) {
+func (f *httpZipFile) Seek(offset int64, whence int) (int64, error) {
return 0, fmt.Errorf("Seek not implemented for zip file entry: %s", f.info.Name)
}
root string
}
-func (fs *httpZipFS) Open(name string) (http.File, os.Error) {
+func (fs *httpZipFS) Open(name string) (http.File, error) {
// fs.root does not start with '/'.
path := path.Join(fs.root, name) // path is clean
index, exact := fs.list.lookup(path)
}, nil
}
-func (fs *httpZipFS) Close() os.Error {
+func (fs *httpZipFS) Close() error {
fs.list = nil
return fs.ReadCloser.Close()
}
import (
"bufio"
"bytes"
+ "errors"
"go/ast"
"go/parser"
"go/token"
"gob"
"index/suffixarray"
"io"
- "os"
"path/filepath"
"regexp"
"sort"
Fulltext bool
}
-func (x *fileIndex) Write(w io.Writer) os.Error {
+func (x *fileIndex) Write(w io.Writer) error {
return gob.NewEncoder(w).Encode(x)
}
-func (x *fileIndex) Read(r io.Reader) os.Error {
+func (x *fileIndex) Read(r io.Reader) error {
return gob.NewDecoder(r).Decode(x)
}
// Write writes the index x to w.
-func (x *Index) Write(w io.Writer) os.Error {
+func (x *Index) Write(w io.Writer) error {
fulltext := false
if x.suffixes != nil {
fulltext = true
// Read reads the index from r into x; x must not be nil.
// If r does not also implement io.ByteReader, it will be wrapped in a bufio.Reader.
-func (x *Index) Read(r io.Reader) os.Error {
+func (x *Index) Read(r io.Reader) error {
// We use the ability to read bytes as a plausible surrogate for buffering.
if _, ok := r.(io.ByteReader); !ok {
r = bufio.NewReader(r)
// identifier, Lookup returns a list of packages, a LookupResult, and a
// list of alternative spellings, if any. Any and all results may be nil.
// If the query syntax is wrong, an error is reported.
-func (x *Index) Lookup(query string) (paks HitList, match *LookupResult, alt *AltWords, err os.Error) {
+func (x *Index) Lookup(query string) (paks HitList, match *LookupResult, alt *AltWords, err error) {
ss := strings.Split(query, ".")
// check query syntax
for _, s := range ss {
if !isIdentifier(s) {
- err = os.NewError("all query parts must be identifiers")
+ err = errors.New("all query parts must be identifiers")
return
}
}
}
default:
- err = os.NewError("query is not a (qualified) identifier")
+ err = errors.New("query is not a (qualified) identifier")
}
return
import (
"archive/zip"
"bytes"
+ "errors"
_ "expvar" // to serve /debug/vars
"flag"
"fmt"
query = flag.Bool("q", false, "arguments are considered search queries")
)
-func serveError(w http.ResponseWriter, r *http.Request, relpath string, err os.Error) {
+func serveError(w http.ResponseWriter, r *http.Request, relpath string, err error) {
contents := applyTemplate(errorHTML, "errorHTML", err) // err may contain an absolute path!
w.WriteHeader(http.StatusNotFound)
servePage(w, "File "+relpath, "", "", contents)
})
}
-func remoteSearch(query string) (res *http.Response, err os.Error) {
+func remoteSearch(query string) (res *http.Response, err error) {
search := "/search?f=text&q=" + url.QueryEscape(query)
// list of addresses to try
}
if err == nil && res.StatusCode != http.StatusOK {
- err = os.NewError(res.Status)
+ err = errors.New(res.Status)
}
return
"go/ast"
"go/parser"
"go/token"
- "os"
"path/filepath"
)
-func parseFile(fset *token.FileSet, filename string, mode uint) (*ast.File, os.Error) {
+func parseFile(fset *token.FileSet, filename string, mode uint) (*ast.File, error) {
src, err := ReadFile(fs, filename)
if err != nil {
return nil, err
return parser.ParseFile(fset, filename, src, mode)
}
-func parseFiles(fset *token.FileSet, filenames []string) (pkgs map[string]*ast.Package, first os.Error) {
+func parseFiles(fset *token.FileSet, filenames []string) (pkgs map[string]*ast.Package, first error) {
pkgs = make(map[string]*ast.Package)
for _, filename := range filenames {
file, err := parseFile(fset, filename, parser.ParseComments)
return
}
-func parseDir(fset *token.FileSet, path string, filter func(FileInfo) bool) (map[string]*ast.Package, os.Error) {
+func parseDir(fset *token.FileSet, path string, filter func(FileInfo) bool) (map[string]*ast.Package, error) {
list, err := fs.ReadDir(path)
if err != nil {
return nil, err
// writeFileAtomically writes data to a temporary file and then
// atomically renames that file to the file named by filename.
//
-func writeFileAtomically(filename string, data []byte) os.Error {
+func writeFileAtomically(filename string, data []byte) error {
// TODO(gri) this won't work on appengine
f, err := ioutil.TempFile(filepath.Split(filename))
if err != nil {
"archive/zip"
"fmt"
"io"
- "os"
"path"
"sort"
"strings"
list zipList
}
-func (fs *zipFS) Close() os.Error {
+func (fs *zipFS) Close() error {
fs.list = nil
return fs.ReadCloser.Close()
}
return name[1:] // strip leading '/'
}
-func (fs *zipFS) stat(abspath string) (int, zipFI, os.Error) {
+func (fs *zipFS) stat(abspath string) (int, zipFI, error) {
i, exact := fs.list.lookup(abspath)
if i < 0 {
// abspath has leading '/' stripped - print it explicitly
return i, zipFI{name, file}, nil
}
-func (fs *zipFS) Open(abspath string) (io.ReadCloser, os.Error) {
+func (fs *zipFS) Open(abspath string) (io.ReadCloser, error) {
_, fi, err := fs.stat(zipPath(abspath))
if err != nil {
return nil, err
return fi.file.Open()
}
-func (fs *zipFS) Lstat(abspath string) (FileInfo, os.Error) {
+func (fs *zipFS) Lstat(abspath string) (FileInfo, error) {
_, fi, err := fs.stat(zipPath(abspath))
return fi, err
}
-func (fs *zipFS) Stat(abspath string) (FileInfo, os.Error) {
+func (fs *zipFS) Stat(abspath string) (FileInfo, error) {
_, fi, err := fs.stat(zipPath(abspath))
return fi, err
}
-func (fs *zipFS) ReadDir(abspath string) ([]FileInfo, os.Error) {
+func (fs *zipFS) ReadDir(abspath string) ([]FileInfo, error) {
path := zipPath(abspath)
i, fi, err := fs.stat(path)
if err != nil {
tabWidth,
}
-func processFile(filename string, useStdin bool) os.Error {
+func processFile(filename string, useStdin bool) error {
var f *os.File
- var err os.Error
+ var err error
var fixlog bytes.Buffer
var buf bytes.Buffer
gofmtBuf.Reset()
_, err := printConfig.Fprint(&gofmtBuf, fset, n)
if err != nil {
- return "<" + err.String() + ">"
+ return "<" + err.Error() + ">"
}
return gofmtBuf.String()
}
-func report(err os.Error) {
+func report(err error) {
scanner.PrintError(os.Stderr, err)
exitCode = 2
}
filepath.Walk(path, visitFile)
}
-func visitFile(path string, f *os.FileInfo, err os.Error) os.Error {
+func visitFile(path string, f *os.FileInfo, err error) error {
if err == nil && isGoFile(f) {
err = processFile(path, false)
}
return f.IsRegular() && !strings.HasPrefix(f.Name, ".") && strings.HasSuffix(f.Name, ".go")
}
-func diff(b1, b2 []byte) (data []byte, err os.Error) {
+func diff(b1, b2 []byte) (data []byte, err error) {
f1, err := ioutil.TempFile("", "gofix")
if err != nil {
return nil, err
printerMode uint
)
-func report(err os.Error) {
+func report(err error) {
scanner.PrintError(os.Stderr, err)
exitCode = 2
}
}
// If in == nil, the source is the contents of the file with the given filename.
-func processFile(filename string, in io.Reader, out io.Writer, stdin bool) os.Error {
+func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error {
if in == nil {
f, err := os.Open(filename)
if err != nil {
return err
}
-func visitFile(path string, f *os.FileInfo, err os.Error) os.Error {
+func visitFile(path string, f *os.FileInfo, err error) error {
if err == nil && isGoFile(f) {
err = processFile(path, nil, os.Stdout, false)
}
}
}
-func diff(b1, b2 []byte) (data []byte, err os.Error) {
+func diff(b1, b2 []byte) (data []byte, err error) {
f1, err := ioutil.TempFile("", "gofmt")
if err != nil {
return
// parse parses src, which was read from filename,
// as a Go source file or statement list.
-func parse(filename string, src []byte, stdin bool) (*ast.File, func(orig, src []byte) []byte, os.Error) {
+func parse(filename string, src []byte, stdin bool) (*ast.File, func(orig, src []byte) []byte, error) {
// Try as whole source file.
file, err := parser.ParseFile(fset, filename, src, parserMode)
if err == nil {
// If the error is that the source file didn't begin with a
// package line and this is standard input, fall through to
// try as a source fragment. Stop and return on any other error.
- if !stdin || !strings.Contains(err.String(), "expected 'package'") {
+ if !stdin || !strings.Contains(err.Error(), "expected 'package'") {
return nil, nil, err
}
// If the error is that the source file didn't begin with a
// declaration, fall through to try as a statement list.
// Stop and return on any other error.
- if !strings.Contains(err.String(), "expected declaration") {
+ if !strings.Contains(err.Error(), "expected declaration") {
return nil, nil, err
}
import (
"bytes"
+ "errors"
"exec"
"fmt"
"http"
type host struct {
pattern *regexp.Regexp
- getVcs func(repo, path string) (*vcsMatch, os.Error)
+ getVcs func(repo, path string) (*vcsMatch, error)
}
var knownHosts = []host{
prefix, repo string
}
-func googleVcs(repo, path string) (*vcsMatch, os.Error) {
+func googleVcs(repo, path string) (*vcsMatch, error) {
parts := strings.SplitN(repo, "/", 2)
url := "https://" + repo
switch parts[1] {
case "hg":
return &vcsMatch{&hg, repo, url}, nil
}
- return nil, os.NewError("unsupported googlecode vcs: " + parts[1])
+ return nil, errors.New("unsupported googlecode vcs: " + parts[1])
}
-func githubVcs(repo, path string) (*vcsMatch, os.Error) {
+func githubVcs(repo, path string) (*vcsMatch, error) {
if strings.HasSuffix(repo, ".git") {
- return nil, os.NewError("path must not include .git suffix")
+ return nil, errors.New("path must not include .git suffix")
}
return &vcsMatch{&git, repo, "http://" + repo + ".git"}, nil
}
-func bitbucketVcs(repo, path string) (*vcsMatch, os.Error) {
+func bitbucketVcs(repo, path string) (*vcsMatch, error) {
const bitbucketApiUrl = "https://api.bitbucket.org/1.0/repositories/"
if strings.HasSuffix(repo, ".git") {
- return nil, os.NewError("path must not include .git suffix")
+ return nil, errors.New("path must not include .git suffix")
}
parts := strings.SplitN(repo, "/", 2)
return &vcsMatch{&hg, repo, "http://" + repo}, nil
}
- return nil, os.NewError("unsupported bitbucket vcs: " + response.Vcs)
+ return nil, errors.New("unsupported bitbucket vcs: " + response.Vcs)
}
-func launchpadVcs(repo, path string) (*vcsMatch, os.Error) {
+func launchpadVcs(repo, path string) (*vcsMatch, error) {
return &vcsMatch{&bzr, repo, "https://" + repo}, nil
}
// findPublicRepo checks whether pkg is located at one of
// the supported code hosting sites and, if so, returns a match.
-func findPublicRepo(pkg string) (*vcsMatch, os.Error) {
+func findPublicRepo(pkg string) (*vcsMatch, error) {
for _, host := range knownHosts {
if hm := host.pattern.FindStringSubmatch(pkg); hm != nil {
return host.getVcs(hm[1], hm[2])
}
// findAnyRepo looks for a vcs suffix in pkg (.git, etc) and returns a match.
-func findAnyRepo(pkg string) (*vcsMatch, os.Error) {
+func findAnyRepo(pkg string) (*vcsMatch, error) {
for _, v := range vcsList {
i := strings.Index(pkg+"/", v.suffix+"/")
if i < 0 {
}
// download checks out or updates pkg from the remote server.
-func download(pkg, srcDir string) (public bool, err os.Error) {
+func download(pkg, srcDir string) (public bool, err error) {
if strings.Contains(pkg, "..") {
- err = os.NewError("invalid path (contains ..)")
+ err = errors.New("invalid path (contains ..)")
return
}
m, err := findPublicRepo(pkg)
}
}
if m == nil {
- err = os.NewError("cannot download: " + pkg)
+ err = errors.New("cannot download: " + pkg)
return
}
err = m.checkoutRepo(srcDir, m.prefix, m.repo)
// updateRepo gets a list of tags in the repository and
// checks out the tag closest to the current runtime.Version.
// If no matching tag is found, it just updates to tip.
-func (v *vcs) updateRepo(dst string) os.Error {
+func (v *vcs) updateRepo(dst string) error {
if v.tagList == "" || v.tagListRe == nil {
// TODO(adg): fix for svn
return run(dst, nil, v.cmd, v.update)
// exists and -u was specified on the command line)
// the repository at tag/branch "release". If there is no
// such tag or branch, it falls back to the repository tip.
-func (vcs *vcs) checkoutRepo(srcDir, pkgprefix, repo string) os.Error {
+func (vcs *vcs) checkoutRepo(srcDir, pkgprefix, repo string) error {
dst := filepath.Join(srcDir, filepath.FromSlash(pkgprefix))
dir, err := os.Stat(filepath.Join(dst, vcs.metadir))
if err == nil && !dir.IsDirectory() {
- return os.NewError("not a directory: " + dst)
+ return errors.New("not a directory: " + dst)
}
if err != nil {
parent, _ := filepath.Split(dst)
import (
"bytes"
+ "errors"
"exec"
"flag"
"fmt"
var (
fset = token.NewFileSet()
argv0 = os.Args[0]
- errors = false
+ errors_ = false
parents = make(map[string]string)
visit = make(map[string]status)
installedPkgs = make(map[string]map[string]bool)
}
func errorf(format string, args ...interface{}) {
- errors = true
+ errors_ = true
logf(format, args...)
}
install(path, "")
}
- if errors {
+ if errors_ {
os.Exit(1)
}
}
install(p, pkg)
}
}
- if errors {
+ if errors_ {
return
}
// run runs the command cmd in directory dir with standard input stdin.
// If the command fails, run prints the command and output on standard error
// in addition to returning a non-nil os.Error.
-func run(dir string, stdin []byte, cmd ...string) os.Error {
+func run(dir string, stdin []byte, cmd ...string) error {
return genRun(dir, stdin, cmd, false)
}
// quietRun is like run but prints nothing on failure unless -v is used.
-func quietRun(dir string, stdin []byte, cmd ...string) os.Error {
+func quietRun(dir string, stdin []byte, cmd ...string) error {
return genRun(dir, stdin, cmd, true)
}
// genRun implements run and quietRun.
-func genRun(dir string, stdin []byte, arg []string, quiet bool) os.Error {
+func genRun(dir string, stdin []byte, arg []string, quiet bool) error {
cmd := exec.Command(arg[0], arg[1:]...)
cmd.Stdin = bytes.NewBuffer(stdin)
cmd.Dir = dir
os.Stderr.Write(out)
fmt.Fprintf(os.Stderr, "--- %s\n", err)
}
- return os.NewError("running " + arg[0] + ": " + err.String())
+ return errors.New("running " + arg[0] + ": " + err.Error())
}
return nil
}
import (
"bytes"
+ "errors"
"go/build"
- "os"
"path" // use for import paths
"strings"
"template"
// domake builds the package in dir.
// domake generates a standard Makefile and passes it
// to make on standard input.
-func domake(dir, pkg string, tree *build.Tree, isCmd bool) (err os.Error) {
+func domake(dir, pkg string, tree *build.Tree, isCmd bool) (err error) {
makefile, err := makeMakefile(dir, pkg, tree, isCmd)
if err != nil {
return err
// makeMakefile computes the standard Makefile for the directory dir
// installing as package pkg. It includes all *.go files in the directory
// except those in package main and those ending in _test.go.
-func makeMakefile(dir, pkg string, tree *build.Tree, isCmd bool) ([]byte, os.Error) {
+func makeMakefile(dir, pkg string, tree *build.Tree, isCmd bool) ([]byte, error) {
if !safeName(pkg) {
- return nil, os.NewError("unsafe name: " + pkg)
+ return nil, errors.New("unsafe name: " + pkg)
}
targ := pkg
targDir := tree.PkgDir()
isCgo := make(map[string]bool, len(cgoFiles))
for _, file := range cgoFiles {
if !safeName(file) {
- return nil, os.NewError("bad name: " + file)
+ return nil, errors.New("bad name: " + file)
}
isCgo[file] = true
}
goFiles := make([]string, 0, len(dirInfo.GoFiles))
for _, file := range dirInfo.GoFiles {
if !safeName(file) {
- return nil, os.NewError("unsafe name: " + file)
+ return nil, errors.New("unsafe name: " + file)
}
if !isCgo[file] {
goFiles = append(goFiles, file)
cgoOFiles := make([]string, 0, len(dirInfo.CFiles))
for _, file := range dirInfo.CFiles {
if !safeName(file) {
- return nil, os.NewError("unsafe name: " + file)
+ return nil, errors.New("unsafe name: " + file)
}
// When cgo is in use, C files are compiled with gcc,
// otherwise they're compiled with gc.
for _, file := range dirInfo.SFiles {
if !safeName(file) {
- return nil, os.NewError("unsafe name: " + file)
+ return nil, errors.New("unsafe name: " + file)
}
oFiles = append(oFiles, file[:len(file)-2]+".$O")
}
command = "bash"
argv = []string{"bash", "-c", cmd}
}
- var err os.Error
+ var err error
argv[0], err = exec.LookPath(argv[0])
if err != nil {
Fatalf("can't find %s: %s", command, err)
}
skip := 0
if colon := strings.LastIndex(name, ":"); colon > 0 {
- var err os.Error
+ var err error
skip, err = strconv.Atoi(name[colon+1:])
if err != nil {
errorf(`illegal format for "Func:N" argument %q; %s`, name, err)
file.checkFile(name, parsedFile)
}
-func visit(path string, f *os.FileInfo, err os.Error) os.Error {
+func visit(path string, f *os.FileInfo, err error) error {
if err != nil {
errorf("walk error: %s", err)
return nil
args := flag.Args()
var data []byte
- var err os.Error
+ var err error
switch len(args) {
case 0:
data, err = ioutil.ReadAll(os.Stdin)
// Copy of os.MkdirAll but adds to undo log after
// creating a directory.
-func mkdirAll(path string, perm uint32) os.Error {
+func mkdirAll(path string, perm uint32) error {
dir, err := os.Lstat(path)
if err == nil {
if dir.IsDirectory() {
}
// If err != nil, process the undo log and exit.
-func chk(err os.Error) {
+func chk(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
runUndo()
}
// Undo log
-type undo func() os.Error
+type undo func() error
var undoLog []undo
func undoRevert(name string) {
- undoLog = append(undoLog, undo(func() os.Error { return hgRevert(name) }))
+ undoLog = append(undoLog, undo(func() error { return hgRevert(name) }))
}
-func undoRm(name string) { undoLog = append(undoLog, undo(func() os.Error { return os.Remove(name) })) }
+func undoRm(name string) { undoLog = append(undoLog, undo(func() error { return os.Remove(name) })) }
func runUndo() {
for i := len(undoLog) - 1; i >= 0; i-- {
}
// hgRoot returns the root directory of the repository.
-func hgRoot() (string, os.Error) {
+func hgRoot() (string, error) {
out, err := run([]string{"hg", "root"}, nil)
if err != nil {
return "", err
// hgModified returns a list of the modified files in the
// repository.
-func hgModified() ([]string, os.Error) {
+func hgModified() ([]string, error) {
out, err := run([]string{"hg", "status", "-n"}, nil)
if err != nil {
return nil, err
}
// hgAdd adds name to the repository.
-func hgAdd(name string) os.Error {
+func hgAdd(name string) error {
_, err := run([]string{"hg", "add", name}, nil)
return err
}
// hgRemove removes name from the repository.
-func hgRemove(name string) os.Error {
+func hgRemove(name string) error {
_, err := run([]string{"hg", "rm", name}, nil)
return err
}
// hgRevert reverts name.
-func hgRevert(name string) os.Error {
+func hgRevert(name string) error {
_, err := run([]string{"hg", "revert", name}, nil)
return err
}
// hgCopy copies src to dst in the repository.
// Note that the argument order matches io.Copy, not "hg cp".
-func hgCopy(dst, src string) os.Error {
+func hgCopy(dst, src string) error {
_, err := run([]string{"hg", "cp", src, dst}, nil)
return err
}
// hgRename renames src to dst in the repository.
// Note that the argument order matches io.Copy, not "hg mv".
-func hgRename(dst, src string) os.Error {
+func hgRename(dst, src string) error {
_, err := run([]string{"hg", "mv", src, dst}, nil)
return err
}
// run runs the command argv, resolving argv[0] if necessary by searching $PATH.
// It provides input on standard input to the command.
-func run(argv []string, input []byte) (out string, err os.Error) {
+func run(argv []string, input []byte) (out string, err error) {
if len(argv) < 1 {
return "", &runError{dup(argv), os.EINVAL}
}
// A runError represents an error that occurred while running a command.
type runError struct {
cmd []string
- err os.Error
+ err error
}
-func (e *runError) String() string { return strings.Join(e.cmd, " ") + ": " + e.err.String() }
+func (e *runError) Error() string { return strings.Join(e.cmd, " ") + ": " + e.err.Error() }
func main() {
var n = 10000
if len(os.Args) > 1 {
- var err os.Error
+ var err error
n, err = strconv.Atoi(os.Args[1])
if err != nil {
print("bad arg\n")
func main() {
ga, e0 := os.Getenverror("GOARCH")
if e0 != nil {
- print("$GOARCH: ", e0.String(), "\n")
+ print("$GOARCH: ", e0.Error(), "\n")
os.Exit(1)
}
if ga != runtime.GOARCH {
}
xxx, e1 := os.Getenverror("DOES_NOT_EXIST")
if e1 != os.ENOENV {
- print("$DOES_NOT_EXIST=", xxx, "; err = ", e1.String(), "\n")
+ print("$DOES_NOT_EXIST=", xxx, "; err = ", e1.Error(), "\n")
os.Exit(1)
}
}
package main
-import "os"
+import "errors"
// Issue 481: closures and var declarations
// with multiple variables assigned from one
}
}()
- var conn, _ = Dial("tcp", "", listen.Addr().String())
+ var conn, _ = Dial("tcp", "", listen.Addr().Error())
_ = conn
}
return global, y
}
-func (t T) Addr() os.Error {
- return os.NewError("stringer")
+func (t T) Addr() error {
+ return errors.New("stringer")
}
func (t T) Accept() (int, string) {
return "abc"
}
-func g() *os.Error {
+func g() *error {
trace += "g"
- var x os.Error
+ var x error
return &x
}
return &i
}
-
func main() {
m := make(map[string]int)
m[f()], *g() = strconv.Atoi(h())
println("BUG", m["abc"], trace)
panic("fail")
}
- mm := make(map[string]os.Error)
+ mm := make(map[string]error)
trace = ""
mm["abc"] = os.EINVAL
*i(), mm[f()] = strconv.Atoi(h())
f()
}
-
var callee string
-var error bool
+var error_ bool
type T int
func (t *T) f() { callee = "f" }
func (i *T) g() { callee = "g" }
-
// test1 and test2 are the same except that in the interface J
// the entries are swapped. test2 and test3 are the same except
// that in test3 the interface J is declared outside the function.
x.(J).f()
if callee != "f" {
println("test1 called", callee)
- error = true
+ error_ = true
}
}
-
func test2(x I) {
type J interface {
g()
x.(J).f()
if callee != "f" {
println("test2 called", callee)
- error = true
+ error_ = true
}
}
-
type J interface {
g()
I
x.(J).f()
if callee != "f" {
println("test3 called", callee)
- error = true
+ error_ = true
}
}
test1(x)
test2(x)
test3(x)
- if error {
+ if error_ {
panic("wrong method called")
}
}
package p
-import "os"
-
-func f() (_ int, err os.Error) {
+func f() (_ int, err error) {
return
}
-func g() (x int, _ os.Error) {
+func g() (x int, _ error) {
return
}
-func h() (_ int, _ os.Error) {
+func h() (_ int, _ error) {
return
}
-func i() (int, os.Error) {
- return // ERROR "not enough arguments to return"
+func i() (int, error) {
+ return // ERROR "not enough arguments to return"
}
-func f1() (_ int, err os.Error) {
+func f1() (_ int, err error) {
return 1, nil
}
-func g1() (x int, _ os.Error) {
+func g1() (x int, _ error) {
return 1, nil
}
-func h1() (_ int, _ os.Error) {
+func h1() (_ int, _ error) {
return 1, nil
}
-func ii() (int, os.Error) {
+func ii() (int, error) {
return 1, nil
}
package main
-import "os"
+import "io"
-func f() (_ string, x float64, err os.Error) {
+func f() (_ string, x float64, err error) {
return
}
-func g() (_ string, x float64, err os.Error) {
- return "hello", 3.14, os.EOF
+func g() (_ string, x float64, err error) {
+ return "hello", 3.14, io.EOF
}
-var _ func() (string, float64, os.Error) = f
-var _ func() (string, float64, os.Error) = g
+var _ func() (string, float64, error) = f
+var _ func() (string, float64, error) = g
func main() {
x, y, z := g()
- if x != "hello" || y != 3.14 || z != os.EOF {
+ if x != "hello" || y != 3.14 || z != io.EOF {
println("wrong", x, len(x), y, z)
}
}
package main
-import (
- "os"
-)
-
type Inner struct {
- F func() os.Error
+ F func() error
}
type Outer struct {
// calls makeclosure twice on same closure
-var Foo = Outer{[]Inner{Inner{func() os.Error{ return nil }}}}
+var Foo = Outer{[]Inner{Inner{func() error { return nil }}}}
// license that can be found in the LICENSE file.
package main
-import os "os"
type t1 int
type t2 int
func f9(os int) int {
return os
}
-func f10(err os.Error) os.Error {
+func f10(err error) error {
return err
}
func f11(t1 string) string {
// get package AST
pkgs, err := parser.ParseDir(token.NewFileSet(), dirpath, filter, parser.ParseComments)
if err != nil {
- println("parse", dirpath, err.String())
+ println("parse", dirpath, err.Error())
panic("fail")
}
return pkgs
package main
-import (
- "os"
- "strings"
-)
+import "strings"
var x = make([]byte, 10)
if v == nil {
panic("expected panic")
}
- if e := v.(os.Error).String(); strings.Index(e, s) < 0 {
+ if e := v.(error).Error(); strings.Index(e, s) < 0 {
panic("want: " + s + "; have: " + e)
}
}
println(name, "panicked but not with runtime.Error")
return
}
- s := runt.String()
+ s := runt.Error()
if strings.Index(s, err) < 0 {
bug()
println(name, "panicked with", s, "not", err)
ErrorTest{"complex128 1/0", func() { use(e128 / d128) }, ""},
}
-func error(fn func()) (error string) {
+func error_(fn func()) (error string) {
defer func() {
if e := recover(); e != nil {
- error = e.(runtime.Error).String()
+ error = e.(runtime.Error).Error()
}
}()
fn()
if t.err != "" {
continue
}
- err := error(t.fn)
+ err := error_(t.fn)
switch {
case t.err == "" && err == "":
// fine