diff options
| author | Russ Cox <rsc@golang.org> | 2011-11-01 22:04:37 -0400 |
|---|---|---|
| committer | Russ Cox <rsc@golang.org> | 2011-11-01 22:04:37 -0400 |
| commit | c2049d2dfeeea3d41fafa91e3e3f0e47c285355b (patch) | |
| tree | 090fd29206a707cf5a1f63eacaa414203d2b1ccb /src/pkg/exp | |
| parent | 68050ac76b94b58d962cf8265a8d4eb31ff35658 (diff) | |
| download | go-c2049d2dfeeea3d41fafa91e3e3f0e47c285355b.tar.xz | |
src/pkg/[a-m]*: gofix -r error -force=error
R=golang-dev, iant
CC=golang-dev
https://golang.org/cl/5322051
Diffstat (limited to 'src/pkg/exp')
43 files changed, 383 insertions, 392 deletions
diff --git a/src/pkg/exp/ebnf/ebnf.go b/src/pkg/exp/ebnf/ebnf.go index 7070cc79fd..15c199af6c 100644 --- a/src/pkg/exp/ebnf/ebnf.go +++ b/src/pkg/exp/ebnf/ebnf.go @@ -23,8 +23,8 @@ package ebnf import ( + "errors" "fmt" - "os" "scanner" "unicode" "utf8" @@ -33,27 +33,27 @@ import ( // ---------------------------------------------------------------------------- // Error handling -type errorList []os.Error +type errorList []error -func (list errorList) Error() os.Error { +func (list errorList) Err() error { if len(list) == 0 { return nil } return list } -func (list errorList) String() string { +func (list errorList) Error() string { switch len(list) { case 0: return "no errors" case 1: - return list[0].String() + return list[0].Error() } return fmt.Sprintf("%s (and %d more errors)", list[0], len(list)-1) } -func newError(pos scanner.Position, msg string) os.Error { - return os.NewError(fmt.Sprintf("%s: %s", pos, msg)) +func newError(pos scanner.Position, msg string) error { + return errors.New(fmt.Sprintf("%s: %s", pos, msg)) } // ---------------------------------------------------------------------------- @@ -262,8 +262,8 @@ func (v *verifier) verify(grammar Grammar, start string) { // // Position information is interpreted relative to the file set fset. // -func Verify(grammar Grammar, start string) os.Error { +func Verify(grammar Grammar, start string) error { var v verifier v.verify(grammar, start) - return v.errors.Error() + return v.errors.Err() } diff --git a/src/pkg/exp/ebnf/parser.go b/src/pkg/exp/ebnf/parser.go index b550c2b64f..2dad9b4c13 100644 --- a/src/pkg/exp/ebnf/parser.go +++ b/src/pkg/exp/ebnf/parser.go @@ -6,7 +6,6 @@ package ebnf import ( "io" - "os" "scanner" "strconv" ) @@ -184,7 +183,7 @@ func (p *parser) parse(filename string, src io.Reader) Grammar { // more than once; the filename is used only for error // positions. // -func Parse(filename string, src io.Reader) (Grammar, os.Error) { +func Parse(filename string, src io.Reader) (Grammar, error) { var p parser grammar := p.parse(filename, src) return grammar, p.errors.Err() diff --git a/src/pkg/exp/ebnflint/ebnflint.go b/src/pkg/exp/ebnflint/ebnflint.go index c827716c44..6d6f516c90 100644 --- a/src/pkg/exp/ebnflint/ebnflint.go +++ b/src/pkg/exp/ebnflint/ebnflint.go @@ -31,7 +31,7 @@ var ( close = []byte(`</pre>`) ) -func report(err os.Error) { +func report(err error) { scanner.PrintError(os.Stderr, err) os.Exit(1) } @@ -78,7 +78,7 @@ func main() { var ( filename string src []byte - err os.Error + err error ) switch flag.NArg() { case 0: diff --git a/src/pkg/exp/gotype/gotype.go b/src/pkg/exp/gotype/gotype.go index 9199213007..bc4a112c98 100644 --- a/src/pkg/exp/gotype/gotype.go +++ b/src/pkg/exp/gotype/gotype.go @@ -5,6 +5,7 @@ package main import ( + "errors" "exp/types" "flag" "fmt" @@ -38,7 +39,7 @@ func usage() { os.Exit(2) } -func report(err os.Error) { +func report(err error) { scanner.PrintError(os.Stderr, err) exitCode = 2 } @@ -111,7 +112,7 @@ func parseFiles(fset *token.FileSet, filenames []string) (files map[string]*ast. } if file := parse(fset, filename, src); file != nil { if files[filename] != nil { - report(os.NewError(fmt.Sprintf("%q: duplicate file", filename))) + report(errors.New(fmt.Sprintf("%q: duplicate file", filename))) continue } files[filename] = file diff --git a/src/pkg/exp/gui/gui.go b/src/pkg/exp/gui/gui.go index 1714991860..a69f83a1f5 100644 --- a/src/pkg/exp/gui/gui.go +++ b/src/pkg/exp/gui/gui.go @@ -8,7 +8,6 @@ package gui import ( "image" "image/draw" - "os" ) // A Window represents a single graphics window. @@ -21,7 +20,7 @@ type Window interface { // mouse movements and window resizes. EventChan() <-chan interface{} // Close closes the window. - Close() os.Error + Close() error } // A KeyEvent is sent for a key press or release. @@ -54,5 +53,5 @@ type ConfigEvent struct { // An ErrEvent is sent when an error occurs. type ErrEvent struct { - Err os.Error + Err error } diff --git a/src/pkg/exp/gui/x11/auth.go b/src/pkg/exp/gui/x11/auth.go index 732f103d66..24e941cb36 100644 --- a/src/pkg/exp/gui/x11/auth.go +++ b/src/pkg/exp/gui/x11/auth.go @@ -6,12 +6,13 @@ package x11 import ( "bufio" + "errors" "io" "os" ) // readU16BE reads a big-endian uint16 from r, using b as a scratch buffer. -func readU16BE(r io.Reader, b []byte) (uint16, os.Error) { +func readU16BE(r io.Reader, b []byte) (uint16, error) { _, err := io.ReadFull(r, b[0:2]) if err != nil { return 0, err @@ -20,13 +21,13 @@ func readU16BE(r io.Reader, b []byte) (uint16, os.Error) { } // readStr reads a length-prefixed string from r, using b as a scratch buffer. -func readStr(r io.Reader, b []byte) (string, os.Error) { +func readStr(r io.Reader, b []byte) (string, error) { n, err := readU16BE(r, b) if err != nil { return "", err } if int(n) > len(b) { - return "", os.NewError("Xauthority entry too long for buffer") + return "", errors.New("Xauthority entry too long for buffer") } _, err = io.ReadFull(r, b[0:n]) if err != nil { @@ -37,7 +38,7 @@ func readStr(r io.Reader, b []byte) (string, os.Error) { // readAuth reads the X authority file and returns the name/data pair for the display. // displayStr is the "12" out of a $DISPLAY like ":12.0". -func readAuth(displayStr string) (name, data string, err os.Error) { +func readAuth(displayStr string) (name, data string, err error) { // b is a scratch buffer to use and should be at least 256 bytes long // (i.e. it should be able to hold a hostname). var b [256]byte @@ -48,7 +49,7 @@ func readAuth(displayStr string) (name, data string, err os.Error) { if fn == "" { home := os.Getenv("HOME") if home == "" { - err = os.NewError("Xauthority not found: $XAUTHORITY, $HOME not set") + err = errors.New("Xauthority not found: $XAUTHORITY, $HOME not set") return } fn = home + "/.Xauthority" diff --git a/src/pkg/exp/gui/x11/conn.go b/src/pkg/exp/gui/x11/conn.go index f4a453ede4..15afc657ec 100644 --- a/src/pkg/exp/gui/x11/conn.go +++ b/src/pkg/exp/gui/x11/conn.go @@ -10,6 +10,7 @@ package x11 import ( "bufio" + "errors" "exp/gui" "image" "image/draw" @@ -86,7 +87,7 @@ func (c *conn) writeSocket() { for y := b.Min.Y; y < b.Max.Y; y++ { setU32LE(c.flushBuf0[16:20], uint32(y<<16)) if _, err := c.w.Write(c.flushBuf0[:24]); err != nil { - if err != os.EOF { + if err != io.EOF { log.Println("x11:", err) } return @@ -105,7 +106,7 @@ func (c *conn) writeSocket() { } x += nx if _, err := c.w.Write(c.flushBuf1[:nx]); err != nil { - if err != os.EOF { + if err != io.EOF { log.Println("x11:", err) } return @@ -113,7 +114,7 @@ func (c *conn) writeSocket() { } } if err := c.w.Flush(); err != nil { - if err != os.EOF { + if err != io.EOF { log.Println("x11:", err) } return @@ -133,7 +134,7 @@ func (c *conn) FlushImage() { } } -func (c *conn) Close() os.Error { +func (c *conn) Close() error { // Shut down the writeSocket goroutine. This will close the socket to the // X11 server, which will cause c.eventc to close. close(c.flush) @@ -156,7 +157,7 @@ func (c *conn) readSocket() { for { // X events are always 32 bytes long. if _, err := io.ReadFull(c.r, c.buf[:32]); err != nil { - if err != os.EOF { + if err != io.EOF { c.eventc <- gui.ErrEvent{err} } return @@ -167,7 +168,7 @@ func (c *conn) readSocket() { if cookie != 1 { // We issued only one request (GetKeyboardMapping) with a cookie of 1, // so we shouldn't get any other reply from the X server. - c.eventc <- gui.ErrEvent{os.NewError("x11: unexpected cookie")} + c.eventc <- gui.ErrEvent{errors.New("x11: unexpected cookie")} return } keysymsPerKeycode = int(c.buf[1]) @@ -180,7 +181,7 @@ func (c *conn) readSocket() { for j := range m { u, err := readU32LE(c.r, c.buf[:4]) if err != nil { - if err != os.EOF { + if err != io.EOF { c.eventc <- gui.ErrEvent{err} } return @@ -253,10 +254,10 @@ func (c *conn) readSocket() { // connect("/tmp/launch-123/:0") // calls net.Dial("unix", "", "/tmp/launch-123/:0"), displayStr="0" // connect("hostname:2.1") // calls net.Dial("tcp", "", "hostname:6002"), displayStr="2" // connect("tcp/hostname:1.0") // calls net.Dial("tcp", "", "hostname:6001"), displayStr="1" -func connect(display string) (conn net.Conn, displayStr string, err os.Error) { +func connect(display string) (conn net.Conn, displayStr string, err error) { colonIdx := strings.LastIndex(display, ":") if colonIdx < 0 { - return nil, "", os.NewError("bad display: " + display) + return nil, "", errors.New("bad display: " + display) } // Parse the section before the colon. var protocol, host, socket string @@ -275,7 +276,7 @@ func connect(display string) (conn net.Conn, displayStr string, err os.Error) { // Parse the section after the colon. after := display[colonIdx+1:] if after == "" { - return nil, "", os.NewError("bad display: " + display) + return nil, "", errors.New("bad display: " + display) } if i := strings.LastIndex(after, "."); i < 0 { displayStr = after @@ -284,7 +285,7 @@ func connect(display string) (conn net.Conn, displayStr string, err os.Error) { } displayInt, err := strconv.Atoi(displayStr) if err != nil || displayInt < 0 { - return nil, "", os.NewError("bad display: " + display) + return nil, "", errors.New("bad display: " + display) } // Make the connection. if socket != "" { @@ -295,21 +296,21 @@ func connect(display string) (conn net.Conn, displayStr string, err os.Error) { conn, err = net.Dial("unix", "/tmp/.X11-unix/X"+displayStr) } if err != nil { - return nil, "", os.NewError("cannot connect to " + display + ": " + err.String()) + return nil, "", errors.New("cannot connect to " + display + ": " + err.Error()) } return } // authenticate authenticates ourselves with the X server. // displayStr is the "12" out of ":12.0". -func authenticate(w *bufio.Writer, displayStr string) os.Error { +func authenticate(w *bufio.Writer, displayStr string) error { key, value, err := readAuth(displayStr) if err != nil { return err } // Assume that the authentication protocol is "MIT-MAGIC-COOKIE-1". if len(key) != 18 || len(value) != 16 { - return os.NewError("unsupported Xauth") + return errors.New("unsupported Xauth") } // 0x006c means little-endian. 0x000b, 0x0000 means X major version 11, minor version 0. // 0x0012 and 0x0010 means the auth key and value have lengths 18 and 16. @@ -339,7 +340,7 @@ func authenticate(w *bufio.Writer, displayStr string) os.Error { } // readU8 reads a uint8 from r, using b as a scratch buffer. -func readU8(r io.Reader, b []byte) (uint8, os.Error) { +func readU8(r io.Reader, b []byte) (uint8, error) { _, err := io.ReadFull(r, b[:1]) if err != nil { return 0, err @@ -348,7 +349,7 @@ func readU8(r io.Reader, b []byte) (uint8, os.Error) { } // readU16LE reads a little-endian uint16 from r, using b as a scratch buffer. -func readU16LE(r io.Reader, b []byte) (uint16, os.Error) { +func readU16LE(r io.Reader, b []byte) (uint16, error) { _, err := io.ReadFull(r, b[:2]) if err != nil { return 0, err @@ -357,7 +358,7 @@ func readU16LE(r io.Reader, b []byte) (uint16, os.Error) { } // readU32LE reads a little-endian uint32 from r, using b as a scratch buffer. -func readU32LE(r io.Reader, b []byte) (uint32, os.Error) { +func readU32LE(r io.Reader, b []byte) (uint32, error) { _, err := io.ReadFull(r, b[:4]) if err != nil { return 0, err @@ -374,7 +375,7 @@ func setU32LE(b []byte, u uint32) { } // checkPixmapFormats checks that we have an agreeable X pixmap Format. -func checkPixmapFormats(r io.Reader, b []byte, n int) (agree bool, err os.Error) { +func checkPixmapFormats(r io.Reader, b []byte, n int) (agree bool, err error) { for i := 0; i < n; i++ { _, err = io.ReadFull(r, b[:8]) if err != nil { @@ -389,7 +390,7 @@ func checkPixmapFormats(r io.Reader, b []byte, n int) (agree bool, err os.Error) } // checkDepths checks that we have an agreeable X Depth (i.e. one that has an agreeable X VisualType). -func checkDepths(r io.Reader, b []byte, n int, visual uint32) (agree bool, err os.Error) { +func checkDepths(r io.Reader, b []byte, n int, visual uint32) (agree bool, err error) { for i := 0; i < n; i++ { var depth, visualsLen uint16 depth, err = readU16LE(r, b) @@ -427,7 +428,7 @@ func checkDepths(r io.Reader, b []byte, n int, visual uint32) (agree bool, err o } // checkScreens checks that we have an agreeable X Screen. -func checkScreens(r io.Reader, b []byte, n int) (root, visual uint32, err os.Error) { +func checkScreens(r io.Reader, b []byte, n int) (root, visual uint32, err error) { for i := 0; i < n; i++ { var root0, visual0, x uint32 root0, err = readU32LE(r, b) @@ -465,14 +466,14 @@ func checkScreens(r io.Reader, b []byte, n int) (root, visual uint32, err os.Err // handshake performs the protocol handshake with the X server, and ensures // that the server provides a compatible Screen, Depth, etc. -func (c *conn) handshake() os.Error { +func (c *conn) handshake() error { _, err := io.ReadFull(c.r, c.buf[:8]) if err != nil { return err } // Byte 0 should be 1 (success), bytes 2:6 should be 0xb0000000 (major/minor version 11.0). if c.buf[0] != 1 || c.buf[2] != 11 || c.buf[3] != 0 || c.buf[4] != 0 || c.buf[5] != 0 { - return os.NewError("unsupported X version") + return errors.New("unsupported X version") } // Ignore the release number. _, err = io.ReadFull(c.r, c.buf[:4]) @@ -490,7 +491,7 @@ func (c *conn) handshake() os.Error { return err } if resourceIdMask < 256 { - return os.NewError("X resource ID mask is too small") + return errors.New("X resource ID mask is too small") } // Ignore the motion buffer size. _, err = io.ReadFull(c.r, c.buf[:4]) @@ -510,7 +511,7 @@ func (c *conn) handshake() os.Error { return err } if maxReqLen != 0xffff { - return os.NewError("unsupported X maximum request length") + return errors.New("unsupported X maximum request length") } // Read the roots length. rootsLen, err := readU8(c.r, c.buf[:1]) @@ -526,7 +527,7 @@ func (c *conn) handshake() os.Error { // imageByteOrder(1), bitmapFormatBitOrder(1), bitmapFormatScanlineUnit(1) bitmapFormatScanlinePad(1), // minKeycode(1), maxKeycode(1), padding(4), vendor (vendorLen). if 10+int(vendorLen) > cap(c.buf) { - return os.NewError("unsupported X vendor") + return errors.New("unsupported X vendor") } _, err = io.ReadFull(c.r, c.buf[:10+int(vendorLen)]) if err != nil { @@ -538,7 +539,7 @@ func (c *conn) handshake() os.Error { return err } if !agree { - return os.NewError("unsupported X pixmap formats") + return errors.New("unsupported X pixmap formats") } // Check that we have an agreeable screen. root, visual, err := checkScreens(c.r, c.buf[:24], int(rootsLen)) @@ -546,7 +547,7 @@ func (c *conn) handshake() os.Error { return err } if root == 0 || visual == 0 { - return os.NewError("unsupported X screen") + return errors.New("unsupported X screen") } c.gc = resID(resourceIdBase) c.window = resID(resourceIdBase + 1) @@ -556,10 +557,10 @@ func (c *conn) handshake() os.Error { } // NewWindow calls NewWindowDisplay with $DISPLAY. -func NewWindow() (gui.Window, os.Error) { +func NewWindow() (gui.Window, error) { display := os.Getenv("DISPLAY") if len(display) == 0 { - return nil, os.NewError("$DISPLAY not set") + return nil, errors.New("$DISPLAY not set") } return NewWindowDisplay(display) } @@ -567,7 +568,7 @@ func NewWindow() (gui.Window, os.Error) { // NewWindowDisplay returns a new gui.Window, backed by a newly created and // mapped X11 window. The X server to connect to is specified by the display // string, such as ":1". -func NewWindowDisplay(display string) (gui.Window, os.Error) { +func NewWindowDisplay(display string) (gui.Window, error) { socket, displayStr, err := connect(display) if err != nil { return nil, err diff --git a/src/pkg/exp/inotify/inotify_linux.go b/src/pkg/exp/inotify/inotify_linux.go index ee3c75f63b..d6b7e8514e 100644 --- a/src/pkg/exp/inotify/inotify_linux.go +++ b/src/pkg/exp/inotify/inotify_linux.go @@ -27,6 +27,7 @@ Example: package inotify import ( + "errors" "fmt" "os" "strings" @@ -49,14 +50,14 @@ type Watcher struct { fd int // File descriptor (as returned by the inotify_init() syscall) watches map[string]*watch // Map of inotify watches (key: path) paths map[int]string // Map of watched paths (key: watch descriptor) - Error chan os.Error // Errors are sent on this channel + Error chan error // Errors are sent on this channel Event chan *Event // Events are returned on this channel done chan bool // Channel for sending a "quit message" to the reader goroutine isClosed bool // Set to true when Close() is first called } // NewWatcher creates and returns a new inotify instance using inotify_init(2) -func NewWatcher() (*Watcher, os.Error) { +func NewWatcher() (*Watcher, error) { fd, errno := syscall.InotifyInit() if fd == -1 { return nil, os.NewSyscallError("inotify_init", errno) @@ -66,7 +67,7 @@ func NewWatcher() (*Watcher, os.Error) { watches: make(map[string]*watch), paths: make(map[int]string), Event: make(chan *Event), - Error: make(chan os.Error), + Error: make(chan error), done: make(chan bool, 1), } @@ -77,7 +78,7 @@ func NewWatcher() (*Watcher, os.Error) { // Close closes an inotify watcher instance // It sends a message to the reader goroutine to quit and removes all watches // associated with the inotify instance -func (w *Watcher) Close() os.Error { +func (w *Watcher) Close() error { if w.isClosed { return nil } @@ -94,9 +95,9 @@ func (w *Watcher) Close() os.Error { // AddWatch adds path to the watched file set. // The flags are interpreted as described in inotify_add_watch(2). -func (w *Watcher) AddWatch(path string, flags uint32) os.Error { +func (w *Watcher) AddWatch(path string, flags uint32) error { if w.isClosed { - return os.NewError("inotify instance already closed") + return errors.New("inotify instance already closed") } watchEntry, found := w.watches[path] @@ -117,15 +118,15 @@ func (w *Watcher) AddWatch(path string, flags uint32) os.Error { } // Watch adds path to the watched file set, watching all events. -func (w *Watcher) Watch(path string) os.Error { +func (w *Watcher) Watch(path string) error { return w.AddWatch(path, IN_ALL_EVENTS) } // RemoveWatch removes path from the watched file set. -func (w *Watcher) RemoveWatch(path string) os.Error { +func (w *Watcher) RemoveWatch(path string) error { watch, ok := w.watches[path] if !ok { - return os.NewError(fmt.Sprintf("can't remove non-existent inotify watch for: %s", path)) + return errors.New(fmt.Sprintf("can't remove non-existent inotify watch for: %s", path)) } success, errno := syscall.InotifyRmWatch(w.fd, watch.wd) if success == -1 { @@ -168,7 +169,7 @@ func (w *Watcher) readEvents() { continue } if n < syscall.SizeofInotifyEvent { - w.Error <- os.NewError("inotify: short read in readEvents()") + w.Error <- errors.New("inotify: short read in readEvents()") continue } diff --git a/src/pkg/exp/norm/maketables.go b/src/pkg/exp/norm/maketables.go index 93edf221ef..c7a3762bde 100644 --- a/src/pkg/exp/norm/maketables.go +++ b/src/pkg/exp/norm/maketables.go @@ -220,7 +220,7 @@ func openReader(file string) (input io.ReadCloser) { return } -func parseDecomposition(s string, skipfirst bool) (a []rune, e os.Error) { +func parseDecomposition(s string, skipfirst bool) (a []rune, e error) { decomp := strings.Split(s, " ") if len(decomp) > 0 && skipfirst { decomp = decomp[1:] @@ -310,7 +310,7 @@ func loadUnicodeData() { for { line, err := input.ReadString('\n') if err != nil { - if err == os.EOF { + if err == io.EOF { break } logger.Fatal(err) @@ -350,7 +350,7 @@ func loadCompositionExclusions() { for { line, err := input.ReadString('\n') if err != nil { - if err == os.EOF { + if err == io.EOF { break } logger.Fatal(err) @@ -782,7 +782,7 @@ func testDerived() { for { line, err := input.ReadString('\n') if err != nil { - if err == os.EOF { + if err == io.EOF { break } logger.Fatal(err) diff --git a/src/pkg/exp/norm/normregtest.go b/src/pkg/exp/norm/normregtest.go index cf3b34023b..6e27f638aa 100644 --- a/src/pkg/exp/norm/normregtest.go +++ b/src/pkg/exp/norm/normregtest.go @@ -11,6 +11,7 @@ import ( "flag" "fmt" "http" + "io" "log" "os" "path" @@ -141,7 +142,7 @@ func loadTestData() { for { line, err := input.ReadString('\n') if err != nil { - if err == os.EOF { + if err == io.EOF { break } logger.Fatal(err) diff --git a/src/pkg/exp/norm/readwriter.go b/src/pkg/exp/norm/readwriter.go index 48ae135620..ee58abd22d 100644 --- a/src/pkg/exp/norm/readwriter.go +++ b/src/pkg/exp/norm/readwriter.go @@ -4,10 +4,7 @@ package norm -import ( - "io" - "os" -) +import "io" type normWriter struct { rb reorderBuffer @@ -18,7 +15,7 @@ type normWriter struct { // Write implements the standard write interface. If the last characters are // not at a normalization boundary, the bytes will be buffered for the next // write. The remaining bytes will be written on close. -func (w *normWriter) Write(data []byte) (n int, err os.Error) { +func (w *normWriter) Write(data []byte) (n int, err error) { // Process data in pieces to keep w.buf size bounded. const chunk = 4000 @@ -52,7 +49,7 @@ func (w *normWriter) Write(data []byte) (n int, err os.Error) { } // Close forces data that remains in the buffer to be written. -func (w *normWriter) Close() os.Error { +func (w *normWriter) Close() error { if len(w.buf) > 0 { _, err := w.w.Write(w.buf) if err != nil { @@ -79,11 +76,11 @@ type normReader struct { outbuf []byte bufStart int lastBoundary int - err os.Error + err error } // Read implements the standard read interface. -func (r *normReader) Read(p []byte) (int, os.Error) { +func (r *normReader) Read(p []byte) (int, error) { for { if r.lastBoundary-r.bufStart > 0 { n := copy(p, r.outbuf[r.bufStart:r.lastBoundary]) @@ -106,7 +103,7 @@ func (r *normReader) Read(p []byte) (int, os.Error) { if n > 0 { r.outbuf = doAppend(&r.rb, r.outbuf) } - if err == os.EOF { + if err == io.EOF { r.lastBoundary = len(r.outbuf) } else { r.lastBoundary = lastBoundary(&r.rb.f, r.outbuf) diff --git a/src/pkg/exp/norm/readwriter_test.go b/src/pkg/exp/norm/readwriter_test.go index 68652efa65..3b49eb0a2f 100644 --- a/src/pkg/exp/norm/readwriter_test.go +++ b/src/pkg/exp/norm/readwriter_test.go @@ -7,7 +7,6 @@ package norm import ( "bytes" "fmt" - "os" "strings" "testing" ) @@ -27,7 +26,7 @@ func readFunc(size int) appendFunc { r := f.Reader(bytes.NewBuffer(out)) buf := make([]byte, size) result := []byte{} - for n, err := 0, os.Error(nil); err == nil; { + for n, err := 0, error(nil); err == nil; { n, err = r.Read(buf) result = append(result, buf[:n]...) } diff --git a/src/pkg/exp/spdy/read.go b/src/pkg/exp/spdy/read.go index 2b1fd3d0d4..3de80c04d7 100644 --- a/src/pkg/exp/spdy/read.go +++ b/src/pkg/exp/spdy/read.go @@ -9,19 +9,18 @@ import ( "encoding/binary" "http" "io" - "os" "strings" ) -func (frame *SynStreamFrame) read(h ControlFrameHeader, f *Framer) os.Error { +func (frame *SynStreamFrame) read(h ControlFrameHeader, f *Framer) error { return f.readSynStreamFrame(h, frame) } -func (frame *SynReplyFrame) read(h ControlFrameHeader, f *Framer) os.Error { +func (frame *SynReplyFrame) read(h ControlFrameHeader, f *Framer) error { return f.readSynReplyFrame(h, frame) } -func (frame *RstStreamFrame) read(h ControlFrameHeader, f *Framer) os.Error { +func (frame *RstStreamFrame) read(h ControlFrameHeader, f *Framer) error { frame.CFHeader = h if err := binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { return err @@ -32,7 +31,7 @@ func (frame *RstStreamFrame) read(h ControlFrameHeader, f *Framer) os.Error { return nil } -func (frame *SettingsFrame) read(h ControlFrameHeader, f *Framer) os.Error { +func (frame *SettingsFrame) read(h ControlFrameHeader, f *Framer) error { frame.CFHeader = h var numSettings uint32 if err := binary.Read(f.r, binary.BigEndian, &numSettings); err != nil { @@ -52,12 +51,12 @@ func (frame *SettingsFrame) read(h ControlFrameHeader, f *Framer) os.Error { return nil } -func (frame *NoopFrame) read(h ControlFrameHeader, f *Framer) os.Error { +func (frame *NoopFrame) read(h ControlFrameHeader, f *Framer) error { frame.CFHeader = h return nil } -func (frame *PingFrame) read(h ControlFrameHeader, f *Framer) os.Error { +func (frame *PingFrame) read(h ControlFrameHeader, f *Framer) error { frame.CFHeader = h if err := binary.Read(f.r, binary.BigEndian, &frame.Id); err != nil { return err @@ -65,7 +64,7 @@ func (frame *PingFrame) read(h ControlFrameHeader, f *Framer) os.Error { return nil } -func (frame *GoAwayFrame) read(h ControlFrameHeader, f *Framer) os.Error { +func (frame *GoAwayFrame) read(h ControlFrameHeader, f *Framer) error { frame.CFHeader = h if err := binary.Read(f.r, binary.BigEndian, &frame.LastGoodStreamId); err != nil { return err @@ -73,11 +72,11 @@ func (frame *GoAwayFrame) read(h ControlFrameHeader, f *Framer) os.Error { return nil } -func (frame *HeadersFrame) read(h ControlFrameHeader, f *Framer) os.Error { +func (frame *HeadersFrame) read(h ControlFrameHeader, f *Framer) error { return f.readHeadersFrame(h, frame) } -func newControlFrame(frameType ControlFrameType) (controlFrame, os.Error) { +func newControlFrame(frameType ControlFrameType) (controlFrame, error) { ctor, ok := cframeCtor[frameType] if !ok { return nil, &Error{Err: InvalidControlFrame} @@ -97,7 +96,7 @@ var cframeCtor = map[ControlFrameType]func() controlFrame{ // TODO(willchan): Add TypeWindowUpdate } -func (f *Framer) uncorkHeaderDecompressor(payloadSize int64) os.Error { +func (f *Framer) uncorkHeaderDecompressor(payloadSize int64) error { if f.headerDecompressor != nil { f.headerReader.N = payloadSize return nil @@ -112,7 +111,7 @@ func (f *Framer) uncorkHeaderDecompressor(payloadSize int64) os.Error { } // ReadFrame reads SPDY encoded data and returns a decompressed Frame. -func (f *Framer) ReadFrame() (Frame, os.Error) { +func (f *Framer) ReadFrame() (Frame, error) { var firstWord uint32 if err := binary.Read(f.r, binary.BigEndian, &firstWord); err != nil { return nil, err @@ -125,7 +124,7 @@ func (f *Framer) ReadFrame() (Frame, os.Error) { return f.parseDataFrame(firstWord & 0x7fffffff) } -func (f *Framer) parseControlFrame(version uint16, frameType ControlFrameType) (Frame, os.Error) { +func (f *Framer) parseControlFrame(version uint16, frameType ControlFrameType) (Frame, error) { var length uint32 if err := binary.Read(f.r, binary.BigEndian, &length); err != nil { return nil, err @@ -143,12 +142,12 @@ func (f *Framer) parseControlFrame(version uint16, frameType ControlFrameType) ( return cframe, nil } -func parseHeaderValueBlock(r io.Reader, streamId uint32) (http.Header, os.Error) { +func parseHeaderValueBlock(r io.Reader, streamId uint32) (http.Header, error) { var numHeaders uint16 if err := binary.Read(r, binary.BigEndian, &numHeaders); err != nil { return nil, err } - var e os.Error + var e error h := make(http.Header, int(numHeaders)) for i := 0; i < int(numHeaders); i++ { var length uint16 @@ -185,9 +184,9 @@ func parseHeaderValueBlock(r io.Reader, streamId uint32) (http.Header, os.Error) return h, nil } -func (f *Framer) readSynStreamFrame(h ControlFrameHeader, frame *SynStreamFrame) os.Error { +func (f *Framer) readSynStreamFrame(h ControlFrameHeader, frame *SynStreamFrame) error { frame.CFHeader = h - var err os.Error + var err error if err = binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { return err } @@ -206,7 +205,7 @@ func (f *Framer) readSynStreamFrame(h ControlFrameHeader, frame *SynStreamFrame) } frame.Headers, err = parseHeaderValueBlock(reader, frame.StreamId) - if !f.headerCompressionDisabled && ((err == os.EOF && f.headerReader.N == 0) || f.headerReader.N != 0) { + if !f.headerCompressionDisabled && ((err == io.EOF && f.headerReader.N == 0) || f.headerReader.N != 0) { err = &Error{WrongCompressedPayloadSize, 0} } if err != nil { @@ -223,9 +222,9 @@ func (f *Framer) readSynStreamFrame(h ControlFrameHeader, frame *SynStreamFrame) return nil } -func (f *Framer) readSynReplyFrame(h ControlFrameHeader, frame *SynReplyFrame) os.Error { +func (f *Framer) readSynReplyFrame(h ControlFrameHeader, frame *SynReplyFrame) error { frame.CFHeader = h - var err os.Error + var err error if err = binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { return err } @@ -239,7 +238,7 @@ func (f *Framer) readSynReplyFrame(h ControlFrameHeader, frame *SynReplyFrame) o reader = f.headerDecompressor } frame.Headers, err = parseHeaderValueBlock(reader, frame.StreamId) - if !f.headerCompressionDisabled && ((err == os.EOF && f.headerReader.N == 0) || f.headerReader.N != 0) { + if !f.headerCompressionDisabled && ((err == io.EOF && f.headerReader.N == 0) || f.headerReader.N != 0) { err = &Error{WrongCompressedPayloadSize, 0} } if err != nil { @@ -256,9 +255,9 @@ func (f *Framer) readSynReplyFrame(h ControlFrameHeader, frame *SynReplyFrame) o return nil } -func (f *Framer) readHeadersFrame(h ControlFrameHeader, frame *HeadersFrame) os.Error { +func (f *Framer) readHeadersFrame(h ControlFrameHeader, frame *HeadersFrame) error { frame.CFHeader = h - var err os.Error + var err error if err = binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil { return err } @@ -272,7 +271,7 @@ func (f *Framer) readHeadersFrame(h ControlFrameHeader, frame *HeadersFrame) os. reader = f.headerDecompressor } frame.Headers, err = parseHeaderValueBlock(reader, frame.StreamId) - if !f.headerCompressionDisabled && ((err == os.EOF && f.headerReader.N == 0) || f.headerReader.N != 0) { + if !f.headerCompressionDisabled && ((err == io.EOF && f.headerReader.N == 0) || f.headerReader.N != 0) { err = &Error{WrongCompressedPayloadSize, 0} } if err != nil { @@ -296,7 +295,7 @@ func (f *Framer) readHeadersFrame(h ControlFrameHeader, frame *HeadersFrame) os. return nil } -func (f *Framer) parseDataFrame(streamId uint32) (*DataFrame, os.Error) { +func (f *Framer) parseDataFrame(streamId uint32) (*DataFrame, error) { var length uint32 if err := binary.Read(f.r, binary.BigEndian, &length); err != nil { return nil, err diff --git a/src/pkg/exp/spdy/types.go b/src/pkg/exp/spdy/types.go index 41cafb1741..87d6edbd56 100644 --- a/src/pkg/exp/spdy/types.go +++ b/src/pkg/exp/spdy/types.go @@ -9,7 +9,6 @@ import ( "compress/zlib" "http" "io" - "os" ) // Data Frame Format @@ -161,7 +160,7 @@ const MaxDataLength = 1<<24 - 1 // Frame is a single SPDY frame in its unpacked in-memory representation. Use // Framer to read and write it. type Frame interface { - write(f *Framer) os.Error + write(f *Framer) error } // ControlFrameHeader contains all the fields in a control frame header, @@ -176,7 +175,7 @@ type ControlFrameHeader struct { type controlFrame interface { Frame - read(h ControlFrameHeader, f *Framer) os.Error + read(h ControlFrameHeader, f *Framer) error } // SynStreamFrame is the unpacked, in-memory representation of a SYN_STREAM @@ -321,7 +320,7 @@ type Error struct { StreamId uint32 } -func (e *Error) String() string { +func (e *Error) Error() string { return string(e.Err) } @@ -354,7 +353,7 @@ type Framer struct { // a io.Writer and io.Reader. Note that Framer will read and write individual fields // from/to the Reader and Writer, so the caller should pass in an appropriately // buffered implementation to optimize performance. -func NewFramer(w io.Writer, r io.Reader) (*Framer, os.Error) { +func NewFramer(w io.Writer, r io.Reader) (*Framer, error) { compressBuf := new(bytes.Buffer) compressor, err := zlib.NewWriterDict(compressBuf, zlib.BestCompression, []byte(HeaderDictionary)) if err != nil { diff --git a/src/pkg/exp/spdy/write.go b/src/pkg/exp/spdy/write.go index 7d40bbe9fe..537154fbd3 100644 --- a/src/pkg/exp/spdy/write.go +++ b/src/pkg/exp/spdy/write.go @@ -8,19 +8,18 @@ import ( "encoding/binary" "http" "io" - "os" "strings" ) -func (frame *SynStreamFrame) write(f *Framer) os.Error { +func (frame *SynStreamFrame) write(f *Framer) error { return f.writeSynStreamFrame(frame) } -func (frame *SynReplyFrame) write(f *Framer) os.Error { +func (frame *SynReplyFrame) write(f *Framer) error { return f.writeSynReplyFrame(frame) } -func (frame *RstStreamFrame) write(f *Framer) (err os.Error) { +func (frame *RstStreamFrame) write(f *Framer) (err error) { frame.CFHeader.version = Version frame.CFHeader.frameType = TypeRstStream frame.CFHeader.length = 8 @@ -38,7 +37,7 @@ func (frame *RstStreamFrame) write(f *Framer) (err os.Error) { return } -func (frame *SettingsFrame) write(f *Framer) (err os.Error) { +func (frame *SettingsFrame) write(f *Framer) (err error) { frame.CFHeader.version = Version frame.CFHeader.frameType = TypeSettings frame.CFHeader.length = uint32(len(frame.FlagIdValues)*8 + 4) @@ -62,7 +61,7 @@ func (frame *SettingsFrame) write(f *Framer) (err os.Error) { return } -func (frame *NoopFrame) write(f *Framer) os.Error { +func (frame *NoopFrame) write(f *Framer) error { frame.CFHeader.version = Version frame.CFHeader.frameType = TypeNoop @@ -70,7 +69,7 @@ func (frame *NoopFrame) write(f *Framer) os.Error { return writeControlFrameHeader(f.w, frame.CFHeader) } -func (frame *PingFrame) write(f *Framer) (err os.Error) { +func (frame *PingFrame) write(f *Framer) (err error) { frame.CFHeader.version = Version frame.CFHeader.frameType = TypePing frame.CFHeader.length = 4 @@ -85,7 +84,7 @@ func (frame *PingFrame) write(f *Framer) (err os.Error) { return } -func (frame *GoAwayFrame) write(f *Framer) (err os.Error) { +func (frame *GoAwayFrame) write(f *Framer) (err error) { frame.CFHeader.version = Version frame.CFHeader.frameType = TypeGoAway frame.CFHeader.length = 4 @@ -100,20 +99,20 @@ func (frame *GoAwayFrame) write(f *Framer) (err os.Error) { return nil } -func (frame *HeadersFrame) write(f *Framer) os.Error { +func (frame *HeadersFrame) write(f *Framer) error { return f.writeHeadersFrame(frame) } -func (frame *DataFrame) write(f *Framer) os.Error { +func (frame *DataFrame) write(f *Framer) error { return f.writeDataFrame(frame) } // WriteFrame writes a frame. -func (f *Framer) WriteFrame(frame Frame) os.Error { +func (f *Framer) WriteFrame(frame Frame) error { return frame.write(f) } -func writeControlFrameHeader(w io.Writer, h ControlFrameHeader) os.Error { +func writeControlFrameHeader(w io.Writer, h ControlFrameHeader) error { if err := binary.Write(w, binary.BigEndian, 0x8000|h.version); err != nil { return err } @@ -127,7 +126,7 @@ func writeControlFrameHeader(w io.Writer, h ControlFrameHeader) os.Error { return nil } -func writeHeaderValueBlock(w io.Writer, h http.Header) (n int, err os.Error) { +func writeHeaderValueBlock(w io.Writer, h http.Header) (n int, err error) { n = 0 if err = binary.Write(w, binary.BigEndian, uint16(len(h))); err != nil { return @@ -156,7 +155,7 @@ func writeHeaderValueBlock(w io.Writer, h http.Header) (n int, err os.Error) { return } -func (f *Framer) writeSynStreamFrame(frame *SynStreamFrame) (err os.Error) { +func (f *Framer) writeSynStreamFrame(frame *SynStreamFrame) (err error) { // Marshal the headers. var writer io.Writer = f.headerBuf if !f.headerCompressionDisabled { @@ -194,7 +193,7 @@ func (f *Framer) writeSynStreamFrame(frame *SynStreamFrame) (err os.Error) { return nil } -func (f *Framer) writeSynReplyFrame(frame *SynReplyFrame) (err os.Error) { +func (f *Framer) writeSynReplyFrame(frame *SynReplyFrame) (err error) { // Marshal the headers. var writer io.Writer = f.headerBuf if !f.headerCompressionDisabled { @@ -229,7 +228,7 @@ func (f *Framer) writeSynReplyFrame(frame *SynReplyFrame) (err os.Error) { return } -func (f *Framer) writeHeadersFrame(frame *HeadersFrame) (err os.Error) { +func (f *Framer) writeHeadersFrame(frame *HeadersFrame) (err error) { // Marshal the headers. var writer io.Writer = f.headerBuf if !f.headerCompressionDisabled { @@ -264,7 +263,7 @@ func (f *Framer) writeHeadersFrame(frame *HeadersFrame) (err os.Error) { return } -func (f *Framer) writeDataFrame(frame *DataFrame) (err os.Error) { +func (f *Framer) writeDataFrame(frame *DataFrame) (err error) { // Validate DataFrame if frame.StreamId&0x80000000 != 0 || len(frame.Data) >= 0x0f000000 { return &Error{InvalidDataFrame, frame.StreamId} diff --git a/src/pkg/exp/sql/convert.go b/src/pkg/exp/sql/convert.go index a35e0be9cb..b1feef0eb8 100644 --- a/src/pkg/exp/sql/convert.go +++ b/src/pkg/exp/sql/convert.go @@ -7,8 +7,8 @@ package sql import ( + "errors" "fmt" - "os" "reflect" "strconv" ) @@ -16,7 +16,7 @@ import ( // convertAssign copies to dest the value in src, converting it if possible. // An error is returned if the copy would result in loss of information. // dest should be a pointer type. -func convertAssign(dest, src interface{}) os.Error { +func convertAssign(dest, src interface{}) error { // Common cases, without reflect. Fall through. switch s := src.(type) { case string: @@ -56,7 +56,7 @@ func convertAssign(dest, src interface{}) os.Error { dpv := reflect.ValueOf(dest) if dpv.Kind() != reflect.Ptr { - return os.NewError("destination not a pointer") + return errors.New("destination not a pointer") } dv := reflect.Indirect(dpv) diff --git a/src/pkg/exp/sql/convert_test.go b/src/pkg/exp/sql/convert_test.go index 849991868e..f85ed99978 100644 --- a/src/pkg/exp/sql/convert_test.go +++ b/src/pkg/exp/sql/convert_test.go @@ -68,7 +68,7 @@ func TestConversions(t *testing.T) { err := convertAssign(ct.d, ct.s) errstr := "" if err != nil { - errstr = err.String() + errstr = err.Error() } errf := func(format string, args ...interface{}) { base := fmt.Sprintf("convertAssign #%d: for %v (%T) -> %T, ", n, ct.s, ct.s, ct.d) diff --git a/src/pkg/exp/sql/driver/driver.go b/src/pkg/exp/sql/driver/driver.go index 7508b19fa1..52714e817a 100644 --- a/src/pkg/exp/sql/driver/driver.go +++ b/src/pkg/exp/sql/driver/driver.go @@ -19,9 +19,7 @@ // package driver -import ( - "os" -) +import "errors" // Driver is the interface that must be implemented by a database // driver. @@ -31,7 +29,7 @@ type Driver interface { // // The returned connection is only used by one goroutine at a // time. - Open(name string) (Conn, os.Error) + Open(name string) (Conn, error) } // Execer is an optional interface that may be implemented by a Driver @@ -48,7 +46,7 @@ type Driver interface { // // All arguments are of a subset type as defined in the package docs. type Execer interface { - Exec(query string, args []interface{}) (Result, os.Error) + Exec(query string, args []interface{}) (Result, error) } // Conn is a connection to a database. It is not used concurrently @@ -57,16 +55,16 @@ type Execer interface { // Conn is assumed to be stateful. type Conn interface { // Prepare returns a prepared statement, bound to this connection. - Prepare(query string) (Stmt, os.Error) + Prepare(query string) (Stmt, error) // Close invalidates and potentially stops any current // prepared statements and transactions, marking this // connection as no longer in use. The driver may cache or // close its underlying connection to its database. - Close() os.Error + Close() error // Begin starts and returns a new transaction. - Begin() (Tx, os.Error) + Begin() (Tx, error) } // Result is the result of a query execution. @@ -74,18 +72,18 @@ type Result interface { // LastInsertId returns the database's auto-generated ID // after, for example, an INSERT into a table with primary // key. - LastInsertId() (int64, os.Error) + LastInsertId() (int64, error) // RowsAffected returns the number of rows affected by the // query. - RowsAffected() (int64, os.Error) + RowsAffected() (int64, error) } // Stmt is a prepared statement. It is bound to a Conn and not // used by multiple goroutines concurrently. type Stmt interface { // Close closes the statement. - Close() os.Error + Close() error // NumInput returns the number of placeholder parameters. NumInput() int @@ -93,11 +91,11 @@ type Stmt interface { // Exec executes a query that doesn't return rows, such // as an INSERT or UPDATE. The args are all of a subset // type as defined above. - Exec(args []interface{}) (Result, os.Error) + Exec(args []interface{}) (Result, error) // Exec executes a query that may return rows, such as a // SELECT. The args of all of a subset type as defined above. - Query(args []interface{}) (Rows, os.Error) + Query(args []interface{}) (Rows, error) } // ColumnConverter may be optionally implemented by Stmt if the @@ -120,7 +118,7 @@ type Rows interface { Columns() []string // Close closes the rows iterator. - Close() os.Error + Close() error // Next is called to populate the next row of data into // the provided slice. The provided slice will be the same @@ -129,13 +127,13 @@ type Rows interface { // The dest slice may be populated with only with values // of subset types defined above, but excluding string. // All string values must be converted to []byte. - Next(dest []interface{}) os.Error + Next(dest []interface{}) error } // Tx is a transaction. type Tx interface { - Commit() os.Error - Rollback() os.Error + Commit() error + Rollback() error } // RowsAffected implements Result for an INSERT or UPDATE operation @@ -144,11 +142,11 @@ type RowsAffected int64 var _ Result = RowsAffected(0) -func (RowsAffected) LastInsertId() (int64, os.Error) { - return 0, os.NewError("no LastInsertId available") +func (RowsAffected) LastInsertId() (int64, error) { + return 0, errors.New("no LastInsertId available") } -func (v RowsAffected) RowsAffected() (int64, os.Error) { +func (v RowsAffected) RowsAffected() (int64, error) { return int64(v), nil } @@ -160,10 +158,10 @@ type ddlSuccess struct{} var _ Result = ddlSuccess{} -func (ddlSuccess) LastInsertId() (int64, os.Error) { - return 0, os.NewError("no LastInsertId available after DDL statement") +func (ddlSuccess) LastInsertId() (int64, error) { + return 0, errors.New("no LastInsertId available after DDL statement") } -func (ddlSuccess) RowsAffected() (int64, os.Error) { - return 0, os.NewError("no RowsAffected available after DDL statement") +func (ddlSuccess) RowsAffected() (int64, error) { + return 0, errors.New("no RowsAffected available after DDL statement") } diff --git a/src/pkg/exp/sql/driver/types.go b/src/pkg/exp/sql/driver/types.go index 5521d5389c..9faf32f671 100644 --- a/src/pkg/exp/sql/driver/types.go +++ b/src/pkg/exp/sql/driver/types.go @@ -6,7 +6,6 @@ package driver import ( "fmt" - "os" "reflect" "strconv" ) @@ -14,7 +13,7 @@ import ( // ValueConverter is the interface providing the ConvertValue method. type ValueConverter interface { // ConvertValue converts a value to a restricted subset type. - ConvertValue(v interface{}) (interface{}, os.Error) + ConvertValue(v interface{}) (interface{}, error) } // Bool is a ValueConverter that converts input values to bools. @@ -27,7 +26,7 @@ type boolType struct{} var _ ValueConverter = boolType{} -func (boolType) ConvertValue(v interface{}) (interface{}, os.Error) { +func (boolType) ConvertValue(v interface{}) (interface{}, error) { return nil, fmt.Errorf("TODO(bradfitz): bool conversions") } @@ -39,7 +38,7 @@ type int32Type struct{} var _ ValueConverter = int32Type{} -func (int32Type) ConvertValue(v interface{}) (interface{}, os.Error) { +func (int32Type) ConvertValue(v interface{}) (interface{}, error) { rv := reflect.ValueOf(v) switch rv.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: @@ -72,7 +71,7 @@ var String stringType type stringType struct{} -func (stringType) ConvertValue(v interface{}) (interface{}, os.Error) { +func (stringType) ConvertValue(v interface{}) (interface{}, error) { switch v.(type) { case string, []byte: return v, nil @@ -137,7 +136,7 @@ type defaultConverter struct{} var _ ValueConverter = defaultConverter{} -func (defaultConverter) ConvertValue(v interface{}) (interface{}, os.Error) { +func (defaultConverter) ConvertValue(v interface{}) (interface{}, error) { if IsParameterSubsetType(v) { return v, nil } diff --git a/src/pkg/exp/sql/fakedb_test.go b/src/pkg/exp/sql/fakedb_test.go index c906185e58..289294bee2 100644 --- a/src/pkg/exp/sql/fakedb_test.go +++ b/src/pkg/exp/sql/fakedb_test.go @@ -5,9 +5,10 @@ package sql import ( + "errors" "fmt" + "io" "log" - "os" "strconv" "strings" "sync" @@ -108,7 +109,7 @@ func init() { // Supports dsn forms: // <dbname> // <dbname>;wipe -func (d *fakeDriver) Open(dsn string) (driver.Conn, os.Error) { +func (d *fakeDriver) Open(dsn string) (driver.Conn, error) { d.mu.Lock() defer d.mu.Unlock() d.openCount++ @@ -117,7 +118,7 @@ func (d *fakeDriver) Open(dsn string) (driver.Conn, os.Error) { } parts := strings.Split(dsn, ";") if len(parts) < 1 { - return nil, os.NewError("fakedb: no database name") + return nil, errors.New("fakedb: no database name") } name := parts[0] db, ok := d.dbs[name] @@ -134,7 +135,7 @@ func (db *fakeDB) wipe() { db.tables = nil } -func (db *fakeDB) createTable(name string, columnNames, columnTypes []string) os.Error { +func (db *fakeDB) createTable(name string, columnNames, columnTypes []string) error { db.mu.Lock() defer db.mu.Unlock() if db.tables == nil { @@ -175,33 +176,33 @@ func (db *fakeDB) columnType(table, column string) (typ string, ok bool) { return "", false } -func (c *fakeConn) Begin() (driver.Tx, os.Error) { +func (c *fakeConn) Begin() (driver.Tx, error) { if c.currTx != nil { - return nil, os.NewError("already in a transaction") + return nil, errors.New("already in a transaction") } c.currTx = &fakeTx{c: c} return c.currTx, nil } -func (c *fakeConn) Close() os.Error { +func (c *fakeConn) Close() error { if c.currTx != nil { - return os.NewError("can't close; in a Transaction") + return errors.New("can't close; in a Transaction") } if c.db == nil { - return os.NewError("can't close; already closed") + return errors.New("can't close; already closed") } c.db = nil return nil } -func errf(msg string, args ...interface{}) os.Error { - return os.NewError("fakedb: " + fmt.Sprintf(msg, args...)) +func errf(msg string, args ...interface{}) error { + return errors.New("fakedb: " + fmt.Sprintf(msg, args...)) } // parts are table|selectCol1,selectCol2|whereCol=?,whereCol2=? // (note that where where columns must always contain ? marks, // just a limitation for fakedb) -func (c *fakeConn) prepareSelect(stmt *fakeStmt, parts []string) (driver.Stmt, os.Error) { +func (c *fakeConn) prepareSelect(stmt *fakeStmt, parts []string) (driver.Stmt, error) { if len(parts) != 3 { return nil, errf("invalid SELECT syntax with %d parts; want 3", len(parts)) } @@ -228,7 +229,7 @@ func (c *fakeConn) prepareSelect(stmt *fakeStmt, parts []string) (driver.Stmt, o } // parts are table|col=type,col2=type2 -func (c *fakeConn) prepareCreate(stmt *fakeStmt, parts []string) (driver.Stmt, os.Error) { +func (c *fakeConn) prepareCreate(stmt *fakeStmt, parts []string) (driver.Stmt, error) { if len(parts) != 2 { return nil, errf("invalid CREATE syntax with %d parts; want 2", len(parts)) } @@ -245,7 +246,7 @@ func (c *fakeConn) prepareCreate(stmt *fakeStmt, parts []string) (driver.Stmt, o } // parts are table|col=?,col2=val -func (c *fakeConn) prepareInsert(stmt *fakeStmt, parts []string) (driver.Stmt, os.Error) { +func (c *fakeConn) prepareInsert(stmt *fakeStmt, parts []string) (driver.Stmt, error) { if len(parts) != 2 { return nil, errf("invalid INSERT syntax with %d parts; want 2", len(parts)) } @@ -287,7 +288,7 @@ func (c *fakeConn) prepareInsert(stmt *fakeStmt, parts []string) (driver.Stmt, o return stmt, nil } -func (c *fakeConn) Prepare(query string) (driver.Stmt, os.Error) { +func (c *fakeConn) Prepare(query string) (driver.Stmt, error) { if c.db == nil { panic("nil c.db; conn = " + fmt.Sprintf("%#v", c)) } @@ -317,11 +318,11 @@ func (s *fakeStmt) ColumnConverter(idx int) driver.ValueConverter { return s.placeholderConverter[idx] } -func (s *fakeStmt) Close() os.Error { +func (s *fakeStmt) Close() error { return nil } -func (s *fakeStmt) Exec(args []interface{}) (driver.Result, os.Error) { +func (s *fakeStmt) Exec(args []interface{}) (driver.Result, error) { db := s.c.db switch s.cmd { case "WIPE": @@ -339,7 +340,7 @@ func (s *fakeStmt) Exec(args []interface{}) (driver.Result, os.Error) { return nil, fmt.Errorf("unimplemented statement Exec command type of %q", s.cmd) } -func (s *fakeStmt) execInsert(args []interface{}) (driver.Result, os.Error) { +func (s *fakeStmt) execInsert(args []interface{}) (driver.Result, error) { db := s.c.db if len(args) != s.placeholders { panic("error in pkg db; should only get here if size is correct") @@ -375,7 +376,7 @@ func (s *fakeStmt) execInsert(args []interface{}) (driver.Result, os.Error) { return driver.RowsAffected(1), nil } -func (s *fakeStmt) Query(args []interface{}) (driver.Rows, os.Error) { +func (s *fakeStmt) Query(args []interface{}) (driver.Rows, error) { db := s.c.db if len(args) != s.placeholders { panic("error in pkg db; should only get here if size is correct") @@ -438,12 +439,12 @@ func (s *fakeStmt) NumInput() int { return s.placeholders } -func (tx *fakeTx) Commit() os.Error { +func (tx *fakeTx) Commit() error { tx.c.currTx = nil return nil } -func (tx *fakeTx) Rollback() os.Error { +func (tx *fakeTx) Rollback() error { tx.c.currTx = nil return nil } @@ -455,7 +456,7 @@ type rowsCursor struct { closed bool } -func (rc *rowsCursor) Close() os.Error { +func (rc *rowsCursor) Close() error { rc.closed = true return nil } @@ -464,13 +465,13 @@ func (rc *rowsCursor) Columns() []string { return rc.cols } -func (rc *rowsCursor) Next(dest []interface{}) os.Error { +func (rc *rowsCursor) Next(dest []interface{}) error { if rc.closed { - return os.NewError("fakedb: cursor is closed") + return errors.New("fakedb: cursor is closed") } rc.pos++ if rc.pos >= len(rc.rows) { - return os.EOF // per interface spec + return io.EOF // per interface spec } for i, v := range rc.rows[rc.pos].cols { // TODO(bradfitz): convert to subset types? naah, I diff --git a/src/pkg/exp/sql/sql.go b/src/pkg/exp/sql/sql.go index 7f0e0b2842..4f1c539127 100644 --- a/src/pkg/exp/sql/sql.go +++ b/src/pkg/exp/sql/sql.go @@ -7,8 +7,9 @@ package sql import ( + "errors" "fmt" - "os" + "io" "runtime" "sync" @@ -50,7 +51,7 @@ type NullableString struct { } // ScanInto implements the ScannerInto interface. -func (ms *NullableString) ScanInto(value interface{}) os.Error { +func (ms *NullableString) ScanInto(value interface{}) error { if value == nil { ms.String, ms.Valid = "", false return nil @@ -74,13 +75,13 @@ type ScannerInto interface { // // An error should be returned if the value can not be stored // without loss of information. - ScanInto(value interface{}) os.Error + ScanInto(value interface{}) error } // ErrNoRows is returned by Scan when QueryRow doesn't return a // row. In such a case, QueryRow returns a placeholder *Row value that // defers this error until a Scan. -var ErrNoRows = os.NewError("db: no rows in result set") +var ErrNoRows = errors.New("db: no rows in result set") // DB is a database handle. It's safe for concurrent use by multiple // goroutines. @@ -98,7 +99,7 @@ type DB struct { // // Most users will open a database via a driver-specific connection // helper function that returns a *DB. -func Open(driverName, dataSourceName string) (*DB, os.Error) { +func Open(driverName, dataSourceName string) (*DB, error) { driver, ok := drivers[driverName] if !ok { return nil, fmt.Errorf("db: unknown driver %q (forgotten import?)", driverName) @@ -114,7 +115,7 @@ func (db *DB) maxIdleConns() int { } // conn returns a newly-opened or cached driver.Conn -func (db *DB) conn() (driver.Conn, os.Error) { +func (db *DB) conn() (driver.Conn, error) { db.mu.Lock() if n := len(db.freeConn); n > 0 { conn := db.freeConn[n-1] @@ -154,7 +155,7 @@ func (db *DB) closeConn(c driver.Conn) { } // Prepare creates a prepared statement for later execution. -func (db *DB) Prepare(query string) (*Stmt, os.Error) { +func (db *DB) Prepare(query string) (*Stmt, error) { // TODO: check if db.driver supports an optional // driver.Preparer interface and call that instead, if so, // otherwise we make a prepared statement that's bound @@ -179,7 +180,7 @@ func (db *DB) Prepare(query string) (*Stmt, os.Error) { } // Exec executes a query without returning any rows. -func (db *DB) Exec(query string, args ...interface{}) (Result, os.Error) { +func (db *DB) Exec(query string, args ...interface{}) (Result, error) { // Optional fast path, if the driver implements driver.Execer. if execer, ok := db.driver.(driver.Execer); ok { resi, err := execer.Exec(query, args) @@ -218,7 +219,7 @@ func (db *DB) Exec(query string, args ...interface{}) (Result, os.Error) { } // Query executes a query that returns rows, typically a SELECT. -func (db *DB) Query(query string, args ...interface{}) (*Rows, os.Error) { +func (db *DB) Query(query string, args ...interface{}) (*Rows, error) { stmt, err := db.Prepare(query) if err != nil { return nil, err @@ -240,7 +241,7 @@ func (db *DB) QueryRow(query string, args ...interface{}) *Row { // Begin starts a transaction. The isolation level is dependent on // the driver. -func (db *DB) Begin() (*Tx, os.Error) { +func (db *DB) Begin() (*Tx, error) { // TODO(bradfitz): add another method for beginning a transaction // at a specific isolation level. panic(todo()) @@ -257,17 +258,17 @@ type Tx struct { } // Commit commits the transaction. -func (tx *Tx) Commit() os.Error { +func (tx *Tx) Commit() error { panic(todo()) } // Rollback aborts the transaction. -func (tx *Tx) Rollback() os.Error { +func (tx *Tx) Rollback() error { panic(todo()) } // Prepare creates a prepared statement. -func (tx *Tx) Prepare(query string) (*Stmt, os.Error) { +func (tx *Tx) Prepare(query string) (*Stmt, error) { panic(todo()) } @@ -278,7 +279,7 @@ func (tx *Tx) Exec(query string, args ...interface{}) { } // Query executes a query that returns rows, typically a SELECT. -func (tx *Tx) Query(query string, args ...interface{}) (*Rows, os.Error) { +func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) { panic(todo()) } @@ -313,7 +314,7 @@ func todo() string { // Exec executes a prepared statement with the given arguments and // returns a Result summarizing the effect of the statement. -func (s *Stmt) Exec(args ...interface{}) (Result, os.Error) { +func (s *Stmt) Exec(args ...interface{}) (Result, error) { ci, si, err := s.connStmt() if err != nil { return nil, err @@ -352,10 +353,10 @@ func (s *Stmt) Exec(args ...interface{}) (Result, os.Error) { return result{resi}, nil } -func (s *Stmt) connStmt(args ...interface{}) (driver.Conn, driver.Stmt, os.Error) { +func (s *Stmt) connStmt(args ...interface{}) (driver.Conn, driver.Stmt, error) { s.mu.Lock() if s.closed { - return nil, nil, os.NewError("db: statement is closed") + return nil, nil, errors.New("db: statement is closed") } var cs connStmt match := false @@ -391,7 +392,7 @@ func (s *Stmt) connStmt(args ...interface{}) (driver.Conn, driver.Stmt, os.Error // Query executes a prepared query statement with the given arguments // and returns the query results as a *Rows. -func (s *Stmt) Query(args ...interface{}) (*Rows, os.Error) { +func (s *Stmt) Query(args ...interface{}) (*Rows, error) { ci, si, err := s.connStmt(args...) if err != nil { return nil, err @@ -433,7 +434,7 @@ func (s *Stmt) QueryRow(args ...interface{}) *Row { } // Close closes the statement. -func (s *Stmt) Close() os.Error { +func (s *Stmt) Close() error { s.mu.Lock() defer s.mu.Unlock() // TODO(bradfitz): move this unlock after 'closed = true'? if s.closed { @@ -473,7 +474,7 @@ type Rows struct { closed bool lastcols []interface{} - lasterr os.Error + lasterr error } // Next prepares the next result row for reading with the Scan method. @@ -495,8 +496,8 @@ func (rs *Rows) Next() bool { } // Error returns the error, if any, that was encountered during iteration. -func (rs *Rows) Error() os.Error { - if rs.lasterr == os.EOF { +func (rs *Rows) Error() error { + if rs.lasterr == io.EOF { return nil } return rs.lasterr @@ -506,15 +507,15 @@ func (rs *Rows) Error() os.Error { // at by dest. If dest contains pointers to []byte, the slices should // not be modified and should only be considered valid until the next // call to Next or Scan. -func (rs *Rows) Scan(dest ...interface{}) os.Error { +func (rs *Rows) Scan(dest ...interface{}) error { if rs.closed { - return os.NewError("db: Rows closed") + return errors.New("db: Rows closed") } if rs.lasterr != nil { return rs.lasterr } if rs.lastcols == nil { - return os.NewError("db: Scan called without calling Next") + return errors.New("db: Scan called without calling Next") } if len(dest) != len(rs.lastcols) { return fmt.Errorf("db: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest)) @@ -531,7 +532,7 @@ func (rs *Rows) Scan(dest ...interface{}) os.Error { // Close closes the Rows, preventing further enumeration. If the // end is encountered, the Rows are closed automatically. Close // is idempotent. -func (rs *Rows) Close() os.Error { +func (rs *Rows) Close() error { if rs.closed { return nil } @@ -544,7 +545,7 @@ func (rs *Rows) Close() os.Error { // Row is the result of calling QueryRow to select a single row. type Row struct { // One of these two will be non-nil: - err os.Error // deferred error for easy chaining + err error // deferred error for easy chaining rows *Rows } @@ -556,7 +557,7 @@ type Row struct { // If dest contains pointers to []byte, the slices should not be // modified and should only be considered valid until the next call to // Next or Scan. -func (r *Row) Scan(dest ...interface{}) os.Error { +func (r *Row) Scan(dest ...interface{}) error { if r.err != nil { return r.err } @@ -569,8 +570,8 @@ func (r *Row) Scan(dest ...interface{}) os.Error { // A Result summarizes an executed SQL command. type Result interface { - LastInsertId() (int64, os.Error) - RowsAffected() (int64, os.Error) + LastInsertId() (int64, error) + RowsAffected() (int64, error) } type result struct { diff --git a/src/pkg/exp/sql/sql_test.go b/src/pkg/exp/sql/sql_test.go index eaa0a90356..eb1bb58966 100644 --- a/src/pkg/exp/sql/sql_test.go +++ b/src/pkg/exp/sql/sql_test.go @@ -40,7 +40,7 @@ func TestQuery(t *testing.T) { var age int err := db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&age) - if err == nil || !strings.Contains(err.String(), "expected 2 destination arguments") { + if err == nil || !strings.Contains(err.Error(), "expected 2 destination arguments") { t.Errorf("expected error from wrong number of arguments; actually got: %v", err) } @@ -99,7 +99,7 @@ func TestBogusPreboundParameters(t *testing.T) { if err == nil { t.Fatalf("expected error") } - if err.String() != `fakedb: invalid conversion to int32 from "bogusconversion"` { + if err.Error() != `fakedb: invalid conversion to int32 from "bogusconversion"` { t.Errorf("unexpected error: %v", err) } } @@ -135,7 +135,7 @@ func TestDb(t *testing.T) { _, err := stmt.Exec(et.args...) errStr := "" if err != nil { - errStr = err.String() + errStr = err.Error() } if errStr != et.wantErr { t.Errorf("stmt.Execute #%d: for %v, got error %q, want error %q", diff --git a/src/pkg/exp/ssh/channel.go b/src/pkg/exp/ssh/channel.go index f69b735fd4..428e71c806 100644 --- a/src/pkg/exp/ssh/channel.go +++ b/src/pkg/exp/ssh/channel.go @@ -5,7 +5,8 @@ package ssh import ( - "os" + "errors" + "io" "sync" ) @@ -13,19 +14,19 @@ import ( // SSH connection. type Channel interface { // Accept accepts the channel creation request. - Accept() os.Error + Accept() error // Reject rejects the channel creation request. After calling this, no // other methods on the Channel may be called. If they are then the // peer is likely to signal a protocol error and drop the connection. - Reject(reason RejectionReason, message string) os.Error + Reject(reason RejectionReason, message string) error // Read may return a ChannelRequest as an os.Error. - Read(data []byte) (int, os.Error) - Write(data []byte) (int, os.Error) - Close() os.Error + Read(data []byte) (int, error) + Write(data []byte) (int, error) + Close() error // AckRequest either sends an ack or nack to the channel request. - AckRequest(ok bool) os.Error + AckRequest(ok bool) error // ChannelType returns the type of the channel, as supplied by the // client. @@ -43,7 +44,7 @@ type ChannelRequest struct { Payload []byte } -func (c ChannelRequest) String() string { +func (c ChannelRequest) Error() string { return "channel request received" } @@ -72,7 +73,7 @@ type channel struct { myId, theirId uint32 myWindow, theirWindow uint32 maxPacketSize uint32 - err os.Error + err error pendingRequests []ChannelRequest pendingData []byte @@ -83,7 +84,7 @@ type channel struct { cond *sync.Cond } -func (c *channel) Accept() os.Error { +func (c *channel) Accept() error { c.serverConn.lock.Lock() defer c.serverConn.lock.Unlock() @@ -100,7 +101,7 @@ func (c *channel) Accept() os.Error { return c.serverConn.writePacket(marshal(msgChannelOpenConfirm, confirm)) } -func (c *channel) Reject(reason RejectionReason, message string) os.Error { +func (c *channel) Reject(reason RejectionReason, message string) error { c.serverConn.lock.Lock() defer c.serverConn.lock.Unlock() @@ -167,7 +168,7 @@ func (c *channel) handleData(data []byte) { c.cond.Signal() } -func (c *channel) Read(data []byte) (n int, err os.Error) { +func (c *channel) Read(data []byte) (n int, err error) { c.lock.Lock() defer c.lock.Unlock() @@ -187,7 +188,7 @@ func (c *channel) Read(data []byte) (n int, err os.Error) { for { if c.theySentEOF || c.theyClosed || c.dead { - return 0, os.EOF + return 0, io.EOF } if len(c.pendingRequests) > 0 { @@ -223,11 +224,11 @@ func (c *channel) Read(data []byte) (n int, err os.Error) { panic("unreachable") } -func (c *channel) Write(data []byte) (n int, err os.Error) { +func (c *channel) Write(data []byte) (n int, err error) { for len(data) > 0 { c.lock.Lock() if c.dead || c.weClosed { - return 0, os.EOF + return 0, io.EOF } if c.theirWindow == 0 { @@ -267,7 +268,7 @@ func (c *channel) Write(data []byte) (n int, err os.Error) { return } -func (c *channel) Close() os.Error { +func (c *channel) Close() error { c.serverConn.lock.Lock() defer c.serverConn.lock.Unlock() @@ -276,7 +277,7 @@ func (c *channel) Close() os.Error { } if c.weClosed { - return os.NewError("ssh: channel already closed") + return errors.New("ssh: channel already closed") } c.weClosed = true @@ -286,7 +287,7 @@ func (c *channel) Close() os.Error { return c.serverConn.writePacket(marshal(msgChannelClose, closeMsg)) } -func (c *channel) AckRequest(ok bool) os.Error { +func (c *channel) AckRequest(ok bool) error { c.serverConn.lock.Lock() defer c.serverConn.lock.Unlock() diff --git a/src/pkg/exp/ssh/client.go b/src/pkg/exp/ssh/client.go index fe76db16c4..345e707b33 100644 --- a/src/pkg/exp/ssh/client.go +++ b/src/pkg/exp/ssh/client.go @@ -8,9 +8,9 @@ import ( "big" "crypto" "crypto/rand" + "errors" "fmt" "io" - "os" "net" "sync" ) @@ -26,7 +26,7 @@ type ClientConn struct { } // Client returns a new SSH client connection using c as the underlying transport. -func Client(c net.Conn, config *ClientConfig) (*ClientConn, os.Error) { +func Client(c net.Conn, config *ClientConfig) (*ClientConn, error) { conn := &ClientConn{ transport: newTransport(c, config.rand()), config: config, @@ -44,7 +44,7 @@ func Client(c net.Conn, config *ClientConfig) (*ClientConn, os.Error) { } // handshake performs the client side key exchange. See RFC 4253 Section 7. -func (c *ClientConn) handshake() os.Error { +func (c *ClientConn) handshake() error { var magics handshakeMagics if _, err := c.Write(clientVersion); err != nil { @@ -91,7 +91,7 @@ func (c *ClientConn) handshake() os.Error { kexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(c.transport, &clientKexInit, &serverKexInit) if !ok { - return os.NewError("ssh: no common algorithms") + return errors.New("ssh: no common algorithms") } if serverKexInit.FirstKexFollows && kexAlgo != serverKexInit.KexAlgos[0] { @@ -133,7 +133,7 @@ func (c *ClientConn) handshake() os.Error { // authenticate authenticates with the remote server. See RFC 4252. // Only "password" authentication is supported. -func (c *ClientConn) authenticate() os.Error { +func (c *ClientConn) authenticate() error { if err := c.writePacket(marshal(msgServiceRequest, serviceRequestMsg{serviceUserAuth})); err != nil { return err } @@ -166,7 +166,7 @@ func (c *ClientConn) authenticate() os.Error { return nil } -func (c *ClientConn) sendUserAuthReq(method string) os.Error { +func (c *ClientConn) sendUserAuthReq(method string) error { length := stringLength([]byte(c.config.Password)) + 1 payload := make([]byte, length) // always false for password auth, see RFC 4252 Section 8. @@ -183,7 +183,7 @@ func (c *ClientConn) sendUserAuthReq(method string) os.Error { // kexDH performs Diffie-Hellman key agreement on a ClientConn. The // returned values are given the same names as in RFC 4253, section 8. -func (c *ClientConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) ([]byte, []byte, os.Error) { +func (c *ClientConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) ([]byte, []byte, error) { x, err := rand.Int(c.config.rand(), group.p) if err != nil { return nil, nil, err @@ -207,7 +207,7 @@ func (c *ClientConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handsha } if kexDHReply.Y.Sign() == 0 || kexDHReply.Y.Cmp(group.p) >= 0 { - return nil, nil, os.NewError("server DH parameter out of bounds") + return nil, nil, errors.New("server DH parameter out of bounds") } kInt := new(big.Int).Exp(kexDHReply.Y, x, group.p) @@ -230,7 +230,7 @@ func (c *ClientConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handsha // openChan opens a new client channel. The most common session type is "session". // The full set of valid session types are listed in RFC 4250 4.9.1. -func (c *ClientConn) openChan(typ string) (*clientChan, os.Error) { +func (c *ClientConn) openChan(typ string) (*clientChan, error) { ch := c.newChan(c.transport) if err := c.writePacket(marshal(msgChannelOpen, channelOpenMsg{ ChanType: typ, @@ -247,10 +247,10 @@ func (c *ClientConn) openChan(typ string) (*clientChan, os.Error) { ch.peersId = msg.MyId case *channelOpenFailureMsg: c.chanlist.remove(ch.id) - return nil, os.NewError(msg.Message) + return nil, errors.New(msg.Message) default: c.chanlist.remove(ch.id) - return nil, os.NewError("Unexpected packet") + return nil, errors.New("Unexpected packet") } return ch, nil } @@ -329,7 +329,7 @@ func (c *ClientConn) mainLoop() { // Dial connects to the given network address using net.Dial and // then initiates a SSH handshake, returning the resulting client connection. -func Dial(network, addr string, config *ClientConfig) (*ClientConn, os.Error) { +func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) { conn, err := net.Dial(network, addr) if err != nil { return nil, err @@ -382,13 +382,13 @@ func newClientChan(t *transport, id uint32) *clientChan { } // Close closes the channel. This does not close the underlying connection. -func (c *clientChan) Close() os.Error { +func (c *clientChan) Close() error { return c.writePacket(marshal(msgChannelClose, channelCloseMsg{ PeersId: c.id, })) } -func (c *clientChan) sendChanReq(req channelRequestMsg) os.Error { +func (c *clientChan) sendChanReq(req channelRequestMsg) error { if err := c.writePacket(marshal(msgChannelRequest, req)); err != nil { return err } @@ -447,12 +447,12 @@ type chanWriter struct { } // Write writes data to the remote process's standard input. -func (w *chanWriter) Write(data []byte) (n int, err os.Error) { +func (w *chanWriter) Write(data []byte) (n int, err error) { for { if w.rwin == 0 { win, ok := <-w.win if !ok { - return 0, os.EOF + return 0, io.EOF } w.rwin += win continue @@ -469,7 +469,7 @@ func (w *chanWriter) Write(data []byte) (n int, err os.Error) { panic("unreachable") } -func (w *chanWriter) Close() os.Error { +func (w *chanWriter) Close() error { return w.writePacket(marshal(msgChannelEOF, channelEOFMsg{w.id})) } @@ -485,7 +485,7 @@ type chanReader struct { } // Read reads data from the remote process's stdout or stderr. -func (r *chanReader) Read(data []byte) (int, os.Error) { +func (r *chanReader) Read(data []byte) (int, error) { var ok bool for { if len(r.buf) > 0 { @@ -499,12 +499,12 @@ func (r *chanReader) Read(data []byte) (int, os.Error) { } r.buf, ok = <-r.data if !ok { - return 0, os.EOF + return 0, io.EOF } } panic("unreachable") } -func (r *chanReader) Close() os.Error { +func (r *chanReader) Close() error { return r.writePacket(marshal(msgChannelEOF, channelEOFMsg{r.id})) } diff --git a/src/pkg/exp/ssh/common.go b/src/pkg/exp/ssh/common.go index 739bd2f9c5..f68c353a39 100644 --- a/src/pkg/exp/ssh/common.go +++ b/src/pkg/exp/ssh/common.go @@ -53,7 +53,7 @@ type UnexpectedMessageError struct { expected, got uint8 } -func (u UnexpectedMessageError) String() string { +func (u UnexpectedMessageError) Error() string { return "ssh: unexpected message type " + strconv.Itoa(int(u.got)) + " (expected " + strconv.Itoa(int(u.expected)) + ")" } @@ -62,7 +62,7 @@ type ParseError struct { msgType uint8 } -func (p ParseError) String() string { +func (p ParseError) Error() string { return "ssh: parse error in message type " + strconv.Itoa(int(p.msgType)) } diff --git a/src/pkg/exp/ssh/messages.go b/src/pkg/exp/ssh/messages.go index 5f2c447142..5eae181872 100644 --- a/src/pkg/exp/ssh/messages.go +++ b/src/pkg/exp/ssh/messages.go @@ -8,7 +8,6 @@ import ( "big" "bytes" "io" - "os" "reflect" ) @@ -192,7 +191,7 @@ type userAuthPubKeyOkMsg struct { // unmarshal parses the SSH wire data in packet into out using reflection. // expectedType is the expected SSH message type. It either returns nil on // success, or a ParseError or UnexpectedMessageError on error. -func unmarshal(out interface{}, packet []byte, expectedType uint8) os.Error { +func unmarshal(out interface{}, packet []byte, expectedType uint8) error { if len(packet) == 0 { return ParseError{expectedType} } diff --git a/src/pkg/exp/ssh/server.go b/src/pkg/exp/ssh/server.go index 0dd24ecd6e..2ae8079d2d 100644 --- a/src/pkg/exp/ssh/server.go +++ b/src/pkg/exp/ssh/server.go @@ -12,9 +12,9 @@ import ( "crypto/rsa" "crypto/x509" "encoding/pem" + "errors" "io" "net" - "os" "sync" ) @@ -53,12 +53,12 @@ func (c *ServerConfig) rand() io.Reader { // private key configured in order to accept connections. The private key must // be in the form of a PEM encoded, PKCS#1, RSA private key. The file "id_rsa" // typically contains such a key. -func (s *ServerConfig) SetRSAPrivateKey(pemBytes []byte) os.Error { +func (s *ServerConfig) SetRSAPrivateKey(pemBytes []byte) error { block, _ := pem.Decode(pemBytes) if block == nil { - return os.NewError("ssh: no key found") + return errors.New("ssh: no key found") } - var err os.Error + var err error s.rsa, err = x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return err @@ -140,7 +140,7 @@ type ServerConn struct { // lock protects err and also allows Channels to serialise their writes // to out. lock sync.RWMutex - err os.Error + err error // cachedPubKeys contains the cache results of tests for public keys. // Since SSH clients will query whether a public key is acceptable @@ -162,7 +162,7 @@ func Server(c net.Conn, config *ServerConfig) *ServerConn { // kexDH performs Diffie-Hellman key agreement on a ServerConnection. The // returned values are given the same names as in RFC 4253, section 8. -func (s *ServerConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) (H, K []byte, err os.Error) { +func (s *ServerConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) (H, K []byte, err error) { packet, err := s.readPacket() if err != nil { return @@ -173,7 +173,7 @@ func (s *ServerConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handsha } if kexDHInit.X.Sign() == 0 || kexDHInit.X.Cmp(group.p) >= 0 { - return nil, nil, os.NewError("client DH parameter out of bounds") + return nil, nil, errors.New("client DH parameter out of bounds") } y, err := rand.Int(s.config.rand(), group.p) @@ -189,7 +189,7 @@ func (s *ServerConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handsha case hostAlgoRSA: serializedHostKey = s.config.rsaSerialized default: - return nil, nil, os.NewError("internal error") + return nil, nil, errors.New("internal error") } h := hashFunc.New() @@ -218,7 +218,7 @@ func (s *ServerConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handsha return } default: - return nil, nil, os.NewError("internal error") + return nil, nil, errors.New("internal error") } serializedSig := serializeRSASignature(sig) @@ -279,7 +279,7 @@ func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubK } // Handshake performs an SSH transport and client authentication on the given ServerConn. -func (s *ServerConn) Handshake() os.Error { +func (s *ServerConn) Handshake() error { var magics handshakeMagics if _, err := s.Write(serverVersion); err != nil { return err @@ -326,7 +326,7 @@ func (s *ServerConn) Handshake() os.Error { kexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(s.transport, &clientKexInit, &serverKexInit) if !ok { - return os.NewError("ssh: no common algorithms") + return errors.New("ssh: no common algorithms") } if clientKexInit.FirstKexFollows && kexAlgo != clientKexInit.KexAlgos[0] { @@ -345,7 +345,7 @@ func (s *ServerConn) Handshake() os.Error { dhGroup14Once.Do(initDHGroup14) H, K, err = s.kexDH(dhGroup14, hashFunc, &magics, hostKeyAlgo) default: - err = os.NewError("ssh: unexpected key exchange algorithm " + kexAlgo) + err = errors.New("ssh: unexpected key exchange algorithm " + kexAlgo) } if err != nil { return err @@ -374,7 +374,7 @@ func (s *ServerConn) Handshake() os.Error { return err } if serviceRequest.Service != serviceUserAuth { - return os.NewError("ssh: requested service '" + serviceRequest.Service + "' before authenticating") + return errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating") } serviceAccept := serviceAcceptMsg{ Service: serviceUserAuth, @@ -420,9 +420,9 @@ func (s *ServerConn) testPubKey(user, algo string, pubKey []byte) bool { return result } -func (s *ServerConn) authenticate(H []byte) os.Error { +func (s *ServerConn) authenticate(H []byte) error { var userAuthReq userAuthRequestMsg - var err os.Error + var err error var packet []byte userAuthLoop: @@ -435,7 +435,7 @@ userAuthLoop: } if userAuthReq.Service != serviceSSH { - return os.NewError("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service) + return errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service) } switch userAuthReq.Method { @@ -523,7 +523,7 @@ userAuthLoop: return ParseError{msgUserAuthRequest} } default: - return os.NewError("ssh: isAcceptableAlgo incorrect") + return errors.New("ssh: isAcceptableAlgo incorrect") } if s.testPubKey(userAuthReq.User, algo, pubKey) { break userAuthLoop @@ -540,7 +540,7 @@ userAuthLoop: } if len(failureMsg.Methods) == 0 { - return os.NewError("ssh: no authentication methods configured but NoClientAuth is also false") + return errors.New("ssh: no authentication methods configured but NoClientAuth is also false") } if err = s.writePacket(marshal(msgUserAuthFailure, failureMsg)); err != nil { @@ -560,7 +560,7 @@ const defaultWindowSize = 32768 // Accept reads and processes messages on a ServerConn. It must be called // in order to demultiplex messages to any resulting Channels. -func (s *ServerConn) Accept() (Channel, os.Error) { +func (s *ServerConn) Accept() (Channel, error) { if s.err != nil { return nil, s.err } @@ -660,7 +660,7 @@ func (s *ServerConn) Accept() (Channel, os.Error) { case UnexpectedMessageError: return nil, msg case *disconnectMsg: - return nil, os.EOF + return nil, io.EOF default: // Unknown message. Ignore. } @@ -679,7 +679,7 @@ type Listener struct { // Accept waits for and returns the next incoming SSH connection. // The receiver should call Handshake() in another goroutine // to avoid blocking the accepter. -func (l *Listener) Accept() (*ServerConn, os.Error) { +func (l *Listener) Accept() (*ServerConn, error) { c, err := l.listener.Accept() if err != nil { return nil, err @@ -694,13 +694,13 @@ func (l *Listener) Addr() net.Addr { } // Close closes the listener. -func (l *Listener) Close() os.Error { +func (l *Listener) Close() error { return l.listener.Close() } // Listen creates an SSH listener accepting connections on // the given network address using net.Listen. -func Listen(network, addr string, config *ServerConfig) (*Listener, os.Error) { +func Listen(network, addr string, config *ServerConfig) (*Listener, error) { l, err := net.Listen(network, addr) if err != nil { return nil, err diff --git a/src/pkg/exp/ssh/server_shell.go b/src/pkg/exp/ssh/server_shell.go index 0e9967a909..5243d0ee7f 100644 --- a/src/pkg/exp/ssh/server_shell.go +++ b/src/pkg/exp/ssh/server_shell.go @@ -4,9 +4,7 @@ package ssh -import ( - "os" -) +import "io" // ServerShell contains the state for running a VT100 terminal that is capable // of reading lines of input. @@ -326,12 +324,12 @@ func parsePtyRequest(s []byte) (width, height int, ok bool) { return } -func (ss *ServerShell) Write(buf []byte) (n int, err os.Error) { +func (ss *ServerShell) Write(buf []byte) (n int, err error) { return ss.c.Write(buf) } // ReadLine returns a line of input from the terminal. -func (ss *ServerShell) ReadLine() (line string, err os.Error) { +func (ss *ServerShell) ReadLine() (line string, err error) { ss.writeLine([]byte(ss.prompt)) ss.c.Write(ss.outBuf) ss.outBuf = ss.outBuf[:0] @@ -353,7 +351,7 @@ func (ss *ServerShell) ReadLine() (line string, err os.Error) { break } if key == keyCtrlD { - return "", os.EOF + return "", io.EOF } line, lineOk = ss.handleKey(key) } diff --git a/src/pkg/exp/ssh/server_shell_test.go b/src/pkg/exp/ssh/server_shell_test.go index 622cf7cfad..aa69ef7fed 100644 --- a/src/pkg/exp/ssh/server_shell_test.go +++ b/src/pkg/exp/ssh/server_shell_test.go @@ -5,8 +5,8 @@ package ssh import ( + "io" "testing" - "os" ) type MockChannel struct { @@ -15,15 +15,15 @@ type MockChannel struct { received []byte } -func (c *MockChannel) Accept() os.Error { +func (c *MockChannel) Accept() error { return nil } -func (c *MockChannel) Reject(RejectionReason, string) os.Error { +func (c *MockChannel) Reject(RejectionReason, string) error { return nil } -func (c *MockChannel) Read(data []byte) (n int, err os.Error) { +func (c *MockChannel) Read(data []byte) (n int, err error) { n = len(data) if n == 0 { return @@ -32,7 +32,7 @@ func (c *MockChannel) Read(data []byte) (n int, err os.Error) { n = len(c.toSend) } if n == 0 { - return 0, os.EOF + return 0, io.EOF } if c.bytesPerRead > 0 && n > c.bytesPerRead { n = c.bytesPerRead @@ -42,16 +42,16 @@ func (c *MockChannel) Read(data []byte) (n int, err os.Error) { return } -func (c *MockChannel) Write(data []byte) (n int, err os.Error) { +func (c *MockChannel) Write(data []byte) (n int, err error) { c.received = append(c.received, data...) return len(data), nil } -func (c *MockChannel) Close() os.Error { +func (c *MockChannel) Close() error { return nil } -func (c *MockChannel) AckRequest(ok bool) os.Error { +func (c *MockChannel) AckRequest(ok bool) error { return nil } @@ -70,7 +70,7 @@ func TestClose(t *testing.T) { if line != "" { t.Errorf("Expected empty line but got: %s", line) } - if err != os.EOF { + if err != io.EOF { t.Errorf("Error should have been EOF but got: %s", err) } } @@ -78,12 +78,12 @@ func TestClose(t *testing.T) { var keyPressTests = []struct { in string line string - err os.Error + err error }{ { "", "", - os.EOF, + io.EOF, }, { "\r", diff --git a/src/pkg/exp/ssh/session.go b/src/pkg/exp/ssh/session.go index 13df2f0dda..77154f2c3c 100644 --- a/src/pkg/exp/ssh/session.go +++ b/src/pkg/exp/ssh/session.go @@ -9,8 +9,8 @@ package ssh import ( "encoding/binary" + "errors" "io" - "os" ) // A Session represents a connection to a remote command or shell. @@ -34,7 +34,7 @@ type Session struct { // Setenv sets an environment variable that will be applied to any // command executed by Shell or Exec. -func (s *Session) Setenv(name, value string) os.Error { +func (s *Session) Setenv(name, value string) error { n, v := []byte(name), []byte(value) nlen, vlen := stringLength(n), stringLength(v) payload := make([]byte, nlen+vlen) @@ -53,7 +53,7 @@ func (s *Session) Setenv(name, value string) os.Error { var emptyModeList = []byte{0, 0, 0, 1, 0} // RequestPty requests the association of a pty with the session on the remote host. -func (s *Session) RequestPty(term string, h, w int) os.Error { +func (s *Session) RequestPty(term string, h, w int) error { buf := make([]byte, 4+len(term)+16+len(emptyModeList)) b := marshalString(buf, []byte(term)) binary.BigEndian.PutUint32(b, uint32(h)) @@ -73,9 +73,9 @@ func (s *Session) RequestPty(term string, h, w int) os.Error { // Exec runs cmd on the remote host. Typically, the remote // server passes cmd to the shell for interpretation. // A Session only accepts one call to Exec or Shell. -func (s *Session) Exec(cmd string) os.Error { +func (s *Session) Exec(cmd string) error { if s.started { - return os.NewError("session already started") + return errors.New("session already started") } cmdLen := stringLength([]byte(cmd)) payload := make([]byte, cmdLen) @@ -92,9 +92,9 @@ func (s *Session) Exec(cmd string) os.Error { // Shell starts a login shell on the remote host. A Session only // accepts one call to Exec or Shell. -func (s *Session) Shell() os.Error { +func (s *Session) Shell() error { if s.started { - return os.NewError("session already started") + return errors.New("session already started") } s.started = true @@ -106,7 +106,7 @@ func (s *Session) Shell() os.Error { } // NewSession returns a new interactive session on the remote host. -func (c *ClientConn) NewSession() (*Session, os.Error) { +func (c *ClientConn) NewSession() (*Session, error) { ch, err := c.openChan("session") if err != nil { return nil, err diff --git a/src/pkg/exp/ssh/transport.go b/src/pkg/exp/ssh/transport.go index 97eaf975d1..579a9d82de 100644 --- a/src/pkg/exp/ssh/transport.go +++ b/src/pkg/exp/ssh/transport.go @@ -11,10 +11,10 @@ import ( "crypto/cipher" "crypto/hmac" "crypto/subtle" + "errors" "hash" "io" "net" - "os" "sync" ) @@ -27,7 +27,7 @@ const ( // TODO(dfc) suggestions for a better name will be warmly received. type filteredConn interface { // Close closes the connection. - Close() os.Error + Close() error // LocalAddr returns the local network address. LocalAddr() net.Addr @@ -40,7 +40,7 @@ type filteredConn interface { // an SSH peer. type packetWriter interface { // Encrypt and send a packet of data to the remote peer. - writePacket(packet []byte) os.Error + writePacket(packet []byte) error } // transport represents the SSH connection to the remote peer. @@ -79,7 +79,7 @@ type common struct { } // Read and decrypt a single packet from the remote peer. -func (r *reader) readOnePacket() ([]byte, os.Error) { +func (r *reader) readOnePacket() ([]byte, error) { var lengthBytes = make([]byte, 5) var macSize uint32 @@ -108,10 +108,10 @@ func (r *reader) readOnePacket() ([]byte, os.Error) { paddingLength := uint32(lengthBytes[4]) if length <= paddingLength+1 { - return nil, os.NewError("invalid packet length") + return nil, errors.New("invalid packet length") } if length > maxPacketSize { - return nil, os.NewError("packet too large") + return nil, errors.New("packet too large") } packet := make([]byte, length-1+macSize) @@ -126,7 +126,7 @@ func (r *reader) readOnePacket() ([]byte, os.Error) { if r.mac != nil { r.mac.Write(packet[:length-1]) if subtle.ConstantTimeCompare(r.mac.Sum(), mac) != 1 { - return nil, os.NewError("ssh: MAC failure") + return nil, errors.New("ssh: MAC failure") } } @@ -135,7 +135,7 @@ func (r *reader) readOnePacket() ([]byte, os.Error) { } // Read and decrypt next packet discarding debug and noop messages. -func (t *transport) readPacket() ([]byte, os.Error) { +func (t *transport) readPacket() ([]byte, error) { for { packet, err := t.readOnePacket() if err != nil { @@ -149,7 +149,7 @@ func (t *transport) readPacket() ([]byte, os.Error) { } // Encrypt and send a packet of data to the remote peer. -func (w *writer) writePacket(packet []byte) os.Error { +func (w *writer) writePacket(packet []byte) error { w.Mutex.Lock() defer w.Mutex.Unlock() @@ -218,7 +218,7 @@ func (w *writer) writePacket(packet []byte) os.Error { } // Send a message to the remote peer -func (t *transport) sendMessage(typ uint8, msg interface{}) os.Error { +func (t *transport) sendMessage(typ uint8, msg interface{}) error { packet := marshal(typ, msg) return t.writePacket(packet) } @@ -252,7 +252,7 @@ var ( // setupKeys sets the cipher and MAC keys from K, H and sessionId, as // described in RFC 4253, section 6.4. direction should either be serverKeys // (to setup server->client keys) or clientKeys (for client->server keys). -func (c *common) setupKeys(d direction, K, H, sessionId []byte, hashFunc crypto.Hash) os.Error { +func (c *common) setupKeys(d direction, K, H, sessionId []byte, hashFunc crypto.Hash) error { h := hashFunc.New() blockSize := 16 @@ -308,7 +308,7 @@ type truncatingMAC struct { hmac hash.Hash } -func (t truncatingMAC) Write(data []byte) (int, os.Error) { +func (t truncatingMAC) Write(data []byte) (int, error) { return t.hmac.Write(data) } @@ -332,7 +332,7 @@ func (t truncatingMAC) Size() int { const maxVersionStringBytes = 1024 // Read version string as specified by RFC 4253, section 4.2. -func readVersion(r io.Reader) ([]byte, os.Error) { +func readVersion(r io.Reader) ([]byte, error) { versionString := make([]byte, 0, 64) var ok, seenCR bool var buf [1]byte @@ -360,7 +360,7 @@ forEachByte: } if !ok { - return nil, os.NewError("failed to read version string") + return nil, errors.New("failed to read version string") } // We need to remove the CR from versionString diff --git a/src/pkg/exp/template/html/error.go b/src/pkg/exp/template/html/error.go index 5515bfe68d..22fca9e060 100644 --- a/src/pkg/exp/template/html/error.go +++ b/src/pkg/exp/template/html/error.go @@ -197,7 +197,7 @@ const ( ErrSlashAmbig ) -func (e *Error) String() string { +func (e *Error) Error() string { if e.Line != 0 { return fmt.Sprintf("exp/template/html:%s:%d: %s", e.Name, e.Line, e.Description) } else if e.Name != "" { diff --git a/src/pkg/exp/template/html/escape.go b/src/pkg/exp/template/html/escape.go index 74abccecdd..28615a9318 100644 --- a/src/pkg/exp/template/html/escape.go +++ b/src/pkg/exp/template/html/escape.go @@ -8,14 +8,13 @@ import ( "bytes" "fmt" "html" - "os" "template" "template/parse" ) // Escape rewrites each action in the template to guarantee that the output is // properly escaped. -func Escape(t *template.Template) (*template.Template, os.Error) { +func Escape(t *template.Template) (*template.Template, error) { var s template.Set s.Add(t) if _, err := EscapeSet(&s, t.Name()); err != nil { @@ -32,7 +31,7 @@ func Escape(t *template.Template) (*template.Template, os.Error) { // need not include helper templates. // If no error is returned, then the named templates have been modified. // Otherwise the named templates have been rendered unusable. -func EscapeSet(s *template.Set, names ...string) (*template.Set, os.Error) { +func EscapeSet(s *template.Set, names ...string) (*template.Set, error) { if len(names) == 0 { // TODO: Maybe add a method to Set to enumerate template names // and use those instead. @@ -41,7 +40,7 @@ func EscapeSet(s *template.Set, names ...string) (*template.Set, os.Error) { e := newEscaper(s) for _, name := range names { c, _ := e.escapeTree(context{}, name, 0) - var err os.Error + var err error if c.err != nil { err, c.err.Name = c.err, name } else if c.state != stateText { diff --git a/src/pkg/exp/template/html/escape_test.go b/src/pkg/exp/template/html/escape_test.go index 1b3b256733..20599bce15 100644 --- a/src/pkg/exp/template/html/escape_test.go +++ b/src/pkg/exp/template/html/escape_test.go @@ -8,7 +8,6 @@ import ( "bytes" "fmt" "json" - "os" "strings" "template" "template/parse" @@ -17,14 +16,14 @@ import ( type badMarshaler struct{} -func (x *badMarshaler) MarshalJSON() ([]byte, os.Error) { +func (x *badMarshaler) MarshalJSON() ([]byte, error) { // Keys in valid JSON must be double quoted as must all strings. return []byte("{ foo: 'not quite valid JSON' }"), nil } type goodMarshaler struct{} -func (x *goodMarshaler) MarshalJSON() ([]byte, os.Error) { +func (x *goodMarshaler) MarshalJSON() ([]byte, error) { return []byte(`{ "<foo>": "O'Reilly" }`), nil } @@ -783,7 +782,7 @@ func TestEscapeSet(t *testing.T) { // pred is a template function that returns the predecessor of a // natural number for testing recursive templates. - fns := template.FuncMap{"pred": func(a ...interface{}) (interface{}, os.Error) { + fns := template.FuncMap{"pred": func(a ...interface{}) (interface{}, error) { if len(a) == 1 { if i, _ := a[0].(int); i > 0 { return i - 1, nil @@ -807,7 +806,7 @@ func TestEscapeSet(t *testing.T) { var b bytes.Buffer if err := s.Execute(&b, "main", data); err != nil { - t.Errorf("%q executing %v", err.String(), s.Template("main")) + t.Errorf("%q executing %v", err.Error(), s.Template("main")) continue } if got := b.String(); test.want != got { @@ -962,7 +961,7 @@ func TestErrors(t *testing.T) { } for _, test := range tests { - var err os.Error + var err error if strings.HasPrefix(test.input, "{{define") { var s template.Set _, err = s.Parse(test.input) @@ -977,7 +976,7 @@ func TestErrors(t *testing.T) { } var got string if err != nil { - got = err.String() + got = err.Error() } if test.err == "" { if got != "" { @@ -1549,7 +1548,7 @@ func TestEnsurePipelineContains(t *testing.T) { } } -func expectExecuteFailure(t *testing.T, b *bytes.Buffer, err os.Error) { +func expectExecuteFailure(t *testing.T, b *bytes.Buffer, err error) { if err != nil { if b.Len() != 0 { t.Errorf("output on buffer: %q", b.String()) diff --git a/src/pkg/exp/template/html/js.go b/src/pkg/exp/template/html/js.go index 5646f8a4fd..22be4183d7 100644 --- a/src/pkg/exp/template/html/js.go +++ b/src/pkg/exp/template/html/js.go @@ -148,7 +148,7 @@ func jsValEscaper(args ...interface{}) string { // turning into // x//* error marshalling y: // second line of error message */null - return fmt.Sprintf(" /* %s */null ", strings.Replace(err.String(), "*/", "* /", -1)) + return fmt.Sprintf(" /* %s */null ", strings.Replace(err.Error(), "*/", "* /", -1)) } // TODO: maybe post-process output to prevent it from containing diff --git a/src/pkg/exp/terminal/shell.go b/src/pkg/exp/terminal/shell.go index e3f584774e..5c5916755d 100644 --- a/src/pkg/exp/terminal/shell.go +++ b/src/pkg/exp/terminal/shell.go @@ -4,10 +4,7 @@ package terminal -import ( - "os" - "io" -) +import "io" // Shell contains the state for running a VT100 terminal that is capable of // reading lines of input. @@ -306,12 +303,12 @@ func (ss *Shell) writeLine(line []byte) { } } -func (ss *Shell) Write(buf []byte) (n int, err os.Error) { +func (ss *Shell) Write(buf []byte) (n int, err error) { return ss.c.Write(buf) } // ReadLine returns a line of input from the terminal. -func (ss *Shell) ReadLine() (line string, err os.Error) { +func (ss *Shell) ReadLine() (line string, err error) { ss.writeLine([]byte(ss.prompt)) ss.c.Write(ss.outBuf) ss.outBuf = ss.outBuf[:0] @@ -337,7 +334,7 @@ func (ss *Shell) ReadLine() (line string, err os.Error) { break } if key == keyCtrlD { - return "", os.EOF + return "", io.EOF } line, lineOk = ss.handleKey(key) } diff --git a/src/pkg/exp/terminal/shell_test.go b/src/pkg/exp/terminal/shell_test.go index 2bbe4a4f8f..8a76a85d5d 100644 --- a/src/pkg/exp/terminal/shell_test.go +++ b/src/pkg/exp/terminal/shell_test.go @@ -5,8 +5,8 @@ package terminal import ( + "io" "testing" - "os" ) type MockTerminal struct { @@ -15,7 +15,7 @@ type MockTerminal struct { received []byte } -func (c *MockTerminal) Read(data []byte) (n int, err os.Error) { +func (c *MockTerminal) Read(data []byte) (n int, err error) { n = len(data) if n == 0 { return @@ -24,7 +24,7 @@ func (c *MockTerminal) Read(data []byte) (n int, err os.Error) { n = len(c.toSend) } if n == 0 { - return 0, os.EOF + return 0, io.EOF } if c.bytesPerRead > 0 && n > c.bytesPerRead { n = c.bytesPerRead @@ -34,7 +34,7 @@ func (c *MockTerminal) Read(data []byte) (n int, err os.Error) { return } -func (c *MockTerminal) Write(data []byte) (n int, err os.Error) { +func (c *MockTerminal) Write(data []byte) (n int, err error) { c.received = append(c.received, data...) return len(data), nil } @@ -46,7 +46,7 @@ func TestClose(t *testing.T) { if line != "" { t.Errorf("Expected empty line but got: %s", line) } - if err != os.EOF { + if err != io.EOF { t.Errorf("Error should have been EOF but got: %s", err) } } @@ -54,12 +54,12 @@ func TestClose(t *testing.T) { var keyPressTests = []struct { in string line string - err os.Error + err error }{ { "", "", - os.EOF, + io.EOF, }, { "\r", diff --git a/src/pkg/exp/terminal/terminal.go b/src/pkg/exp/terminal/terminal.go index aacd90905f..d711493819 100644 --- a/src/pkg/exp/terminal/terminal.go +++ b/src/pkg/exp/terminal/terminal.go @@ -15,6 +15,7 @@ package terminal import ( + "io" "os" "syscall" "unsafe" @@ -35,7 +36,7 @@ func IsTerminal(fd int) bool { // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. -func MakeRaw(fd int) (*State, os.Error) { +func MakeRaw(fd int) (*State, error) { var oldState State if _, _, e := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCGETS), uintptr(unsafe.Pointer(&oldState.termios)), 0, 0, 0); e != 0 { return nil, os.Errno(e) @@ -53,7 +54,7 @@ func MakeRaw(fd int) (*State, os.Error) { // Restore restores the terminal connected to the given file descriptor to a // previous state. -func Restore(fd int, state *State) os.Error { +func Restore(fd int, state *State) error { _, _, e := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCSETS), uintptr(unsafe.Pointer(&state.termios)), 0, 0, 0) return os.Errno(e) } @@ -61,7 +62,7 @@ func Restore(fd int, state *State) os.Error { // ReadPassword reads a line of input from a terminal without local echo. This // is commonly used for inputting passwords and other sensitive data. The slice // returned does not include the \n. -func ReadPassword(fd int) ([]byte, os.Error) { +func ReadPassword(fd int) ([]byte, error) { var oldState syscall.Termios if _, _, e := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TCGETS), uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); e != 0 { return nil, os.Errno(e) @@ -86,7 +87,7 @@ func ReadPassword(fd int) ([]byte, os.Error) { } if n == 0 { if len(ret) == 0 { - return nil, os.EOF + return nil, io.EOF } break } diff --git a/src/pkg/exp/types/check.go b/src/pkg/exp/types/check.go index 87e3e93da7..09e29d1261 100644 --- a/src/pkg/exp/types/check.go +++ b/src/pkg/exp/types/check.go @@ -11,7 +11,6 @@ import ( "go/ast" "go/scanner" "go/token" - "os" "strconv" ) @@ -213,7 +212,7 @@ func (c *checker) checkObj(obj *ast.Object, ref bool) { // of types for all expression nodes in statements, and a scanner.ErrorList if // there are errors. // -func Check(fset *token.FileSet, pkg *ast.Package) (types map[ast.Expr]Type, err os.Error) { +func Check(fset *token.FileSet, pkg *ast.Package) (types map[ast.Expr]Type, err error) { var c checker c.fset = fset c.types = make(map[ast.Expr]Type) diff --git a/src/pkg/exp/types/check_test.go b/src/pkg/exp/types/check_test.go index 034acd00de..4a30acf231 100644 --- a/src/pkg/exp/types/check_test.go +++ b/src/pkg/exp/types/check_test.go @@ -67,7 +67,7 @@ func getPos(filename string, offset int) token.Pos { // TODO(gri) Need to revisit parser interface. We should be able to use parser.ParseFiles // or a similar function instead. -func parseFiles(t *testing.T, testname string, filenames []string) (map[string]*ast.File, os.Error) { +func parseFiles(t *testing.T, testname string, filenames []string) (map[string]*ast.File, error) { files := make(map[string]*ast.File) var errors scanner.ErrorList for _, filename := range filenames { @@ -132,7 +132,7 @@ func expectedErrors(t *testing.T, testname string, files map[string]*ast.File) m return errors } -func eliminate(t *testing.T, expected map[token.Pos]string, errors os.Error) { +func eliminate(t *testing.T, expected map[token.Pos]string, errors error) { if errors == nil { return } diff --git a/src/pkg/exp/types/exportdata.go b/src/pkg/exp/types/exportdata.go index 784ffff01a..fa5b6a37fe 100644 --- a/src/pkg/exp/types/exportdata.go +++ b/src/pkg/exp/types/exportdata.go @@ -8,6 +8,7 @@ package types import ( "bufio" + "errors" "fmt" "io" "os" @@ -15,7 +16,7 @@ import ( "strings" ) -func readGopackHeader(buf *bufio.Reader) (name string, size int, err os.Error) { +func readGopackHeader(buf *bufio.Reader) (name string, size int, err error) { // See $GOROOT/include/ar.h. hdr := make([]byte, 16+12+6+6+8+10+2) _, err = io.ReadFull(buf, hdr) @@ -28,7 +29,7 @@ func readGopackHeader(buf *bufio.Reader) (name string, size int, err os.Error) { s := strings.TrimSpace(string(hdr[16+12+6+6+8:][:10])) size, err = strconv.Atoi(s) if err != nil || hdr[len(hdr)-2] != '`' || hdr[len(hdr)-1] != '\n' { - err = os.NewError("invalid archive header") + err = errors.New("invalid archive header") return } name = strings.TrimSpace(string(hdr[:16])) @@ -44,7 +45,7 @@ type dataReader struct { // export data section of the given object/archive file, or an error. // It is the caller's responsibility to close the readCloser. // -func ExportData(filename string) (rc io.ReadCloser, err os.Error) { +func ExportData(filename string) (rc io.ReadCloser, err error) { file, err := os.Open(filename) if err != nil { return @@ -77,7 +78,7 @@ func ExportData(filename string) (rc io.ReadCloser, err os.Error) { return } if name != "__.SYMDEF" { - err = os.NewError("go archive does not begin with __.SYMDEF") + err = errors.New("go archive does not begin with __.SYMDEF") return } const block = 4096 @@ -99,7 +100,7 @@ func ExportData(filename string) (rc io.ReadCloser, err os.Error) { return } if name != "__.PKGDEF" { - err = os.NewError("go archive is missing __.PKGDEF") + err = errors.New("go archive is missing __.PKGDEF") return } @@ -114,7 +115,7 @@ func ExportData(filename string) (rc io.ReadCloser, err os.Error) { // Now at __.PKGDEF in archive or still at beginning of file. // Either way, line should begin with "go object ". if !strings.HasPrefix(string(line), "go object ") { - err = os.NewError("not a go object file") + err = errors.New("not a go object file") return } diff --git a/src/pkg/exp/types/gcimporter.go b/src/pkg/exp/types/gcimporter.go index 4e5172a3d2..d88af95031 100644 --- a/src/pkg/exp/types/gcimporter.go +++ b/src/pkg/exp/types/gcimporter.go @@ -9,6 +9,7 @@ package types import ( "big" + "errors" "fmt" "go/ast" "go/token" @@ -102,7 +103,7 @@ func (p *gcParser) next() { } // GcImporter implements the ast.Importer signature. -func GcImporter(imports map[string]*ast.Object, path string) (pkg *ast.Object, err os.Error) { +func GcImporter(imports map[string]*ast.Object, path string) (pkg *ast.Object, err error) { if path == "unsafe" { return Unsafe, nil } @@ -118,7 +119,7 @@ func GcImporter(imports map[string]*ast.Object, path string) (pkg *ast.Object, e filename, id := findPkg(path) if filename == "" { - err = os.NewError("can't find import: " + id) + err = errors.New("can't find import: " + id) return } @@ -176,19 +177,19 @@ func (p *gcParser) declare(scope *ast.Scope, kind ast.ObjKind, name string) *ast // Internal errors are boxed as importErrors. type importError struct { pos scanner.Position - err os.Error + err error } -func (e importError) String() string { +func (e importError) Error() string { return fmt.Sprintf("import error %s (byte offset = %d): %s", e.pos, e.pos.Offset, e.err) } func (p *gcParser) error(err interface{}) { if s, ok := err.(string); ok { - err = os.NewError(s) + err = errors.New(s) } // panic with a runtime.Error if err is not an os.Error - panic(importError{p.scanner.Pos(), err.(os.Error)}) + panic(importError{p.scanner.Pos(), err.(error)}) } func (p *gcParser) errorf(format string, args ...interface{}) { diff --git a/src/pkg/exp/winfsnotify/winfsnotify.go b/src/pkg/exp/winfsnotify/winfsnotify.go index c5dfe99ad7..d133740304 100644 --- a/src/pkg/exp/winfsnotify/winfsnotify.go +++ b/src/pkg/exp/winfsnotify/winfsnotify.go @@ -7,6 +7,7 @@ package winfsnotify import ( + "errors" "fmt" "os" "path/filepath" @@ -36,7 +37,7 @@ type input struct { op int path string flags uint32 - reply chan os.Error + reply chan error } type inode struct { @@ -65,14 +66,14 @@ type Watcher struct { watches watchMap // Map of watches (key: i-number) input chan *input // Inputs to the reader are sent on this channel Event chan *Event // Events are returned on this channel - Error chan os.Error // Errors are sent on this channel + Error chan error // Errors are sent on this channel isClosed bool // Set to true when Close() is first called - quit chan chan<- os.Error + quit chan chan<- error cookie uint32 } // NewWatcher creates and returns a Watcher. -func NewWatcher() (*Watcher, os.Error) { +func NewWatcher() (*Watcher, error) { port, e := syscall.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0) if e != 0 { return nil, os.NewSyscallError("CreateIoCompletionPort", e) @@ -82,8 +83,8 @@ func NewWatcher() (*Watcher, os.Error) { watches: make(watchMap), input: make(chan *input, 1), Event: make(chan *Event, 50), - Error: make(chan os.Error), - quit: make(chan chan<- os.Error, 1), + Error: make(chan error), + quit: make(chan chan<- error, 1), } go w.readEvents() return w, nil @@ -92,14 +93,14 @@ func NewWatcher() (*Watcher, os.Error) { // Close closes a Watcher. // It sends a message to the reader goroutine to quit and removes all watches // associated with the watcher. -func (w *Watcher) Close() os.Error { +func (w *Watcher) Close() error { if w.isClosed { return nil } w.isClosed = true // Send "quit" message to the reader goroutine - ch := make(chan os.Error) + ch := make(chan error) w.quit <- ch if err := w.wakeupReader(); err != nil { return err @@ -108,15 +109,15 @@ func (w *Watcher) Close() os.Error { } // AddWatch adds path to the watched file set. -func (w *Watcher) AddWatch(path string, flags uint32) os.Error { +func (w *Watcher) AddWatch(path string, flags uint32) error { if w.isClosed { - return os.NewError("watcher already closed") + return errors.New("watcher already closed") } in := &input{ op: opAddWatch, path: filepath.Clean(path), flags: flags, - reply: make(chan os.Error), + reply: make(chan error), } w.input <- in if err := w.wakeupReader(); err != nil { @@ -126,16 +127,16 @@ func (w *Watcher) AddWatch(path string, flags uint32) os.Error { } // Watch adds path to the watched file set, watching all events. -func (w *Watcher) Watch(path string) os.Error { +func (w *Watcher) Watch(path string) error { return w.AddWatch(path, FS_ALL_EVENTS) } // RemoveWatch removes path from the watched file set. -func (w *Watcher) RemoveWatch(path string) os.Error { +func (w *Watcher) RemoveWatch(path string) error { in := &input{ op: opRemoveWatch, path: filepath.Clean(path), - reply: make(chan os.Error), + reply: make(chan error), } w.input <- in if err := w.wakeupReader(); err != nil { @@ -144,7 +145,7 @@ func (w *Watcher) RemoveWatch(path string) os.Error { return <-in.reply } -func (w *Watcher) wakeupReader() os.Error { +func (w *Watcher) wakeupReader() error { e := syscall.PostQueuedCompletionStatus(w.port, 0, 0, nil) if e != 0 { return os.NewSyscallError("PostQueuedCompletionStatus", e) @@ -152,7 +153,7 @@ func (w *Watcher) wakeupReader() os.Error { return nil } -func getDir(pathname string) (dir string, err os.Error) { +func getDir(pathname string) (dir string, err error) { attr, e := syscall.GetFileAttributes(syscall.StringToUTF16Ptr(pathname)) if e != 0 { return "", os.NewSyscallError("GetFileAttributes", e) @@ -166,7 +167,7 @@ func getDir(pathname string) (dir string, err os.Error) { return } -func getIno(path string) (ino *inode, err os.Error) { +func getIno(path string) (ino *inode, err error) { h, e := syscall.CreateFile(syscall.StringToUTF16Ptr(path), syscall.FILE_LIST_DIRECTORY, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, @@ -207,7 +208,7 @@ func (m watchMap) set(ino *inode, watch *watch) { } // Must run within the I/O thread. -func (w *Watcher) addWatch(pathname string, flags uint64) os.Error { +func (w *Watcher) addWatch(pathname string, flags uint64) error { dir, err := getDir(pathname) if err != nil { return err @@ -252,7 +253,7 @@ func (w *Watcher) addWatch(pathname string, flags uint64) os.Error { } // Must run within the I/O thread. -func (w *Watcher) removeWatch(pathname string) os.Error { +func (w *Watcher) removeWatch(pathname string) error { dir, err := getDir(pathname) if err != nil { return err @@ -293,7 +294,7 @@ func (w *Watcher) deleteWatch(watch *watch) { } // Must run within the I/O thread. -func (w *Watcher) startRead(watch *watch) os.Error { +func (w *Watcher) startRead(watch *watch) error { if e := syscall.CancelIo(watch.ino.handle); e != 0 { w.Error <- os.NewSyscallError("CancelIo", e) w.deleteWatch(watch) @@ -352,7 +353,7 @@ func (w *Watcher) readEvents() { w.startRead(watch) } } - var err os.Error + var err error if e := syscall.CloseHandle(w.port); e != 0 { err = os.NewSyscallError("CloseHandle", e) } @@ -392,7 +393,7 @@ func (w *Watcher) readEvents() { for { if n == 0 { w.Event <- &Event{Mask: FS_Q_OVERFLOW} - w.Error <- os.NewError("short read in readEvents()") + w.Error <- errors.New("short read in readEvents()") break } |
