// Copyright 2009 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package osimport ()vargetwdCachestruct {sync.Mutex dir string}// Getwd returns a rooted path name corresponding to the// current directory. If the current directory can be// reached via multiple paths (due to symbolic links),// Getwd may return any one of them.func () ( string, error) {ifruntime.GOOS == "windows" || runtime.GOOS == "plan9" {returnsyscall.Getwd() }// Clumsy but widespread kludge: // if $PWD is set and matches ".", use it. , := statNolog(".")if != nil {return"", } = Getenv("PWD")iflen() > 0 && [0] == '/' { , := statNolog()if == nil && SameFile(, ) {return , nil } }// If the operating system provides a Getwd call, use it. // Otherwise, we're trying to find our way back to ".".ifsyscall.ImplementsGetwd {var (stringerror )for { , = syscall.Getwd()if != syscall.EINTR {break } }return , NewSyscallError("getwd", ) }// Apply same kludge but to cached dir instead of $PWD.getwdCache.Lock() = getwdCache.dirgetwdCache.Unlock()iflen() > 0 { , := statNolog()if == nil && SameFile(, ) {return , nil } }// Root is a special case because it has no parent // and ends in a slash. , := statNolog("/")if != nil {// Can't stat root - no hope.return"", }ifSameFile(, ) {return"/", nil }// General algorithm: find name in parent // and then find name of parent. Each iteration // adds /name to the beginning of dir. = ""for := ".."; ; = "../" + {iflen() >= 1024 { // Sanity checkreturn"", syscall.ENAMETOOLONG } , := openFileNolog(, O_RDONLY, 0)if != nil {return"", }for { , := .Readdirnames(100)if != nil { .Close()return"", }for , := range { , := lstatNolog( + "/" + )ifSameFile(, ) { = "/" + + goto } } } : , := .Stat() .Close()if != nil {return"", }ifSameFile(, ) {break }// Set up for next round. = }// Save answer as hint to avoid the expensive path next time.getwdCache.Lock()getwdCache.dir = getwdCache.Unlock()return , nil}
The pages are generated with Goldsv0.6.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.