本文整理汇总了Golang中os.Getwd函数的典型用法代码示例。如果您正苦于以下问题:Golang Getwd函数的具体用法?Golang Getwd怎么用?Golang Getwd使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Getwd函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: initOSVars
func initOSVars() {
var err error
switch runtime.GOOS {
case "darwin":
if dbg {
workingDir, err = os.Getwd()
} else {
workingDir = "/Applications/5DPrint.app/Contents/MacOS"
}
launchBrowserArgs = []string{"open"}
case "windows":
workingDir, err = os.Getwd()
launchBrowserArgs = []string{"cmd", "/c", "start"}
default:
workingDir, err = os.Getwd()
launchBrowserArgs = []string{"xdg-open"}
}
if err != nil {
log.Println("initOSVars: ", err)
os.Exit(1)
}
}
示例2: ConstructFileLocations
// Construct file locations of of scanner resources based on the operating system.
//
// Example:
//
// fileLocations := goNessus.ConstructFileLocations()
func ConstructFileLocations() FileLocations {
if runtime.GOOS == "linux" {
fileLocations := FileLocations{Base_directory: "/opt/scanner"}
fileLocations.Temp_directory = fmt.Sprintf("%s/temp%d", fileLocations.Base_directory, os.Getpid())
fileLocations.Archive_directory = fmt.Sprintf("%s/targets/archive", fileLocations.Base_directory)
fileLocations.Incoming_directory = fmt.Sprintf("%s/targets/incoming", fileLocations.Base_directory)
fileLocations.Results_directory = fmt.Sprintf("%s/results", fileLocations.Base_directory)
return fileLocations
} else if runtime.GOOS == "darwin" {
// Use PWD since don't really know where to put this type of thing
pwd, err := os.Getwd()
CheckErr(err)
fileLocations := FileLocations{Base_directory: pwd}
fileLocations.Temp_directory = fmt.Sprintf("%s/temp%d", fileLocations.Base_directory, os.Getpid())
fileLocations.Archive_directory = fmt.Sprintf("%s/targets/archive", fileLocations.Base_directory)
fileLocations.Incoming_directory = fmt.Sprintf("%s/targets/incoming", fileLocations.Base_directory)
fileLocations.Results_directory = fmt.Sprintf("%s/results", fileLocations.Base_directory)
return fileLocations
} else {
// Use PWD since don't really know where to put this type of thing
pwd, err := os.Getwd()
CheckErr(err)
fileLocations := FileLocations{Base_directory: pwd}
fileLocations.Temp_directory = fmt.Sprintf("%s/temp%d", fileLocations.Base_directory, os.Getpid())
fileLocations.Archive_directory = fmt.Sprintf("%s/targets/archive", fileLocations.Base_directory)
fileLocations.Incoming_directory = fmt.Sprintf("%s/targets/incoming", fileLocations.Base_directory)
fileLocations.Results_directory = fmt.Sprintf("%s/results", fileLocations.Base_directory)
return fileLocations
}
}
示例3: TestdirectoryContents
func TestdirectoryContents(t *testing.T) {
// setup
save_pwd, _ := os.Getwd()
if err := os.MkdirAll("test/artifacts/.amber", 0700); err != nil {
t.Error("Error creating artifacts: ", err)
}
defer os.RemoveAll("test/artifacts")
defer os.Chdir(save_pwd)
// test
actual, err := directoryContents("test/artifacts")
if err != nil {
t.Error(err)
}
// verify pwd same
if pwd, _ := os.Getwd(); save_pwd != pwd {
t.Errorf("Expected: %v, actual: %v", save_pwd, pwd)
}
// verify
expected := []string{".amber"}
if !stringSlicesEqual(expected, actual) {
t.Errorf("Expected: %v, actual: %v", expected, actual)
}
}
示例4: TestPushdPopd
func TestPushdPopd(t *testing.T) {
sh := gosh.NewShell(t)
defer sh.Cleanup()
startDir, err := os.Getwd()
ok(t, err)
parentDir := filepath.Dir(startDir)
neq(t, startDir, parentDir)
sh.Pushd(parentDir)
cwd, err := os.Getwd()
ok(t, err)
eq(t, cwd, parentDir)
sh.Pushd(startDir)
cwd, err = os.Getwd()
ok(t, err)
eq(t, cwd, startDir)
sh.Popd()
cwd, err = os.Getwd()
ok(t, err)
eq(t, cwd, parentDir)
sh.Popd()
cwd, err = os.Getwd()
ok(t, err)
eq(t, cwd, startDir)
// The next sh.Popd() will fail.
setsErr(t, sh, func() { sh.Popd() })
}
示例5: testGetwd
func testGetwd() {
// 获取程序当前目录,main go文件的目录
dir, err := os.Getwd()
olddir := dir
if err != nil {
fmt.Println("Error : ", err)
return
}
fmt.Println("当前 dir = ", dir)
// 系统的目录分隔符
ps := os.PathSeparator
fmt.Println("PathSeparator : ", string(ps))
// 切换目录
os.Chdir(dir + "/mytest")
dir, err = os.Getwd()
if err != nil {
fmt.Println("Error : ", err)
return
}
fmt.Println("切换后 dir = ", dir)
// 切换目录
os.Chdir(olddir)
}
示例6: main
func main() {
file, _ := os.Getwd()
// log.Println("current path:", file)
// fmt.Println(os.Args[0])
// file, _ = exec.LookPath(os.Args[0])
abs := fmt.Sprintf(`%s/metronic/templates/admin/extra_profile.html`, file)
// fmt.Println(abs)
file, _ = exec.LookPath(fmt.Sprintf(`%smetronic/templates/admin/extra_profile.html`, file))
// fmt.Printf("%T", os.Args[0])
// fmt.Println(file)
log.Println("exec path:", file)
filename := path.Dir(abs)
os.MkdirAll(filename, 0777)
dir, _ := path.Split(file)
log.Println("exec folder relative path:", dir)
os.OpenFile(file, os.O_CREATE, 0777)
os.Chdir(dir)
wd, _ := os.Getwd()
log.Println("exec folder absolute path:", wd)
fmt.Println("\n")
m := map[string]map[string]string{}
m["dasdfsdf"]["dfsadfasf"] = "sdfdsfsfsfddsfww"
if m["dasdfsssdf"] == "" {
fmt.Println(m["dasdfsdf"])
}
}
示例7: TestAbs
func TestAbs(t *testing.T) {
oldwd, err := os.Getwd()
if err != nil {
t.Fatal("Getwd failed: ", err)
}
defer os.Chdir(oldwd)
root, err := ioutil.TempDir("", "TestAbs")
if err != nil {
t.Fatal("TempDir failed: ", err)
}
defer os.RemoveAll(root)
wd, err := os.Getwd()
if err != nil {
t.Fatal("getwd failed: ", err)
}
err = os.Chdir(root)
if err != nil {
t.Fatal("chdir failed: ", err)
}
defer os.Chdir(wd)
for _, dir := range absTestDirs {
err = os.Mkdir(dir, 0777)
if err != nil {
t.Fatal("Mkdir failed: ", err)
}
}
err = os.Chdir(absTestDirs[0])
if err != nil {
t.Fatal("chdir failed: ", err)
}
for _, path := range absTests {
path = strings.Replace(path, "$", root, -1)
info, err := os.Stat(path)
if err != nil {
t.Errorf("%s: %s", path, err)
continue
}
abspath, err := filepath.Abs(path)
if err != nil {
t.Errorf("Abs(%q) error: %v", path, err)
continue
}
absinfo, err := os.Stat(abspath)
if err != nil || !os.SameFile(absinfo, info) {
t.Errorf("Abs(%q)=%q, not the same file", path, abspath)
}
if !filepath.IsAbs(abspath) {
t.Errorf("Abs(%q)=%q, not an absolute path", path, abspath)
}
if filepath.IsAbs(path) && abspath != filepath.Clean(path) {
t.Errorf("Abs(%q)=%q, isn't clean", path, abspath)
}
}
}
示例8: ReadComposeVolumes
// ReadComposeVolumes reads a docker-compose.yml and return a slice of
// directories to sync into the Docker Host
//
// "." and "./." is converted to the current directory parity is running from.
// Any volume starting with "/" will be treated as an absolute path.
// All other volumes (e.g. starting with "./" or without a prefix "/") will be treated as
// relative paths.
func ReadComposeVolumes() []string {
var volumes []string
files := FindDockerComposeFiles()
for i, file := range files {
if _, err := os.Stat(file); err == nil {
project, err := docker.NewProject(&docker.Context{
Context: project.Context{
ComposeFiles: []string{file},
ProjectName: fmt.Sprintf("parity-%d", i),
},
})
if err != nil {
log.Info("Could not parse compose file")
}
for _, c := range project.Configs {
for _, v := range c.Volumes {
v = strings.SplitN(v, ":", 2)[0]
if v == "." || v == "./." {
v, _ = os.Getwd()
} else if strings.Index(v, "/") != 0 {
cwd, _ := os.Getwd()
v = fmt.Sprintf("%s/%s", cwd, v)
}
volumes = append(volumes, mutils.LinuxPath(v))
}
}
}
}
return volumes
}
示例9: loadConfig
func loadConfig() {
var temp Config
if err := decodeConfig(bytes.NewBufferString(defaultConfig), &temp); err != nil {
log.Fatal(err)
}
//Look for a configuration file in the following order:
// Environment: MAPWRAP_CONFIG
// Current Directory: mapwrap.json
configFile := os.Getenv("MAPWRAP_CONFIG")
if configFile == "" {
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
configFile = filepath.Join(cwd, "mapwrap.json")
}
f, err := os.Open(configFile)
defer f.Close()
if err != nil {
log.Printf("Error opening configuration file: %s\n", configFile)
log.Fatal(err)
}
if err := decodeConfig(f, &temp); err != nil {
log.Printf("Error loading configuration file: %s\n", configFile)
log.Fatal(err)
}
//Set the working directory if it's not already set
if temp.Directory == "" {
temp.Directory, err = os.Getwd()
if err != nil {
log.Fatal(err)
}
}
//Make sure the directory exists
_, err = os.Stat(temp.Directory)
if err != nil {
log.Fatal(err)
}
if temp.Mapserv == "" {
out, err := exec.Command("which", "mapserv").Output()
if err != nil {
log.Fatal("Error attempting to find mapserv: ", err)
}
temp.Mapserv = string(out)
}
_, err = exec.Command(temp.Mapserv).Output()
if err != nil {
log.Fatal("Error attempting to run mapserv: ", err)
}
config = &temp
}
示例10: findEntomon
func findEntomon() os.Error {
origd, err := os.Getwd()
if err != nil {
// If we can't read our working directory, let's just fail!
return err
}
oldd := origd
for !isEntomonHere() {
err = os.Chdir("..")
if err != nil {
// If we can't cd .. then we'll just use the original directory.
goto giveup
}
newd, err := os.Getwd()
if err != nil || newd == oldd {
// Either something weird happened or we're at the root
// directory. In either case, we'll just go with the original
// directory.
goto giveup
}
oldd = newd
}
return nil
giveup:
// If nothing else works we'll just use the original directory.
err = os.Chdir(origd)
if err != nil {
return err
}
return os.MkdirAll(".entomon", 0777)
}
示例11: GetExeDir
// TODO(urgent): don't rely on os.Args[0]
func GetExeDir() (string, error) {
// Path with which the exe was ran.
arg := os.Args[0]
// This is the absolute path.
if arg[0] == '/' {
return path.Dir(arg), nil
}
// Running from within directory.
if arg[0] == '.' && arg[1] == '/' {
curDir, err := os.Getwd()
if err != nil {
return "", err
}
return curDir, nil
}
if existsIn('/', arg) {
curDir, err := os.Getwd()
if err != nil {
return "", err
}
return path.Dir(path.Join(curDir, arg)), nil
}
return "", errors.New("Could not find exe path.")
}
示例12: main
func main() {
if len(os.Args) > 1 {
var err error
if port, err = strconv.Atoi(os.Args[1]); err != nil {
printUsage()
return
} else {
if len(os.Args) > 2 {
rootPath = os.Args[2]
if rootStat, err := os.Stat(rootPath); err != nil || !rootStat.IsDir() {
printUsage()
return
}
} else {
rootPath, _ = os.Getwd()
}
}
} else {
port = 80
rootPath, _ = os.Getwd()
}
cacheFile = make(map[string]*FileRecord)
go PeriodUpdate(periodSec)
server := http.NewServeMux()
server.HandleFunc("/", service)
if err := http.ListenAndServe(":"+strconv.Itoa(port), server); err != nil {
fmt.Println(err)
}
}
示例13: TestDirUnix
func TestDirUnix(t *testing.T) {
check(t)
if runtime.GOOS == "windows" {
t.Skipf("skipping test on %q", runtime.GOOS)
}
cwd, _ := os.Getwd()
h := &Handler{
Path: "testdata/test.cgi",
Root: "/test.cgi",
Dir: cwd,
}
expectedMap := map[string]string{
"cwd": cwd,
}
runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
cwd, _ = os.Getwd()
cwd = filepath.Join(cwd, "testdata")
h = &Handler{
Path: "testdata/test.cgi",
Root: "/test.cgi",
}
expectedMap = map[string]string{
"cwd": cwd,
}
runCgiTest(t, h, "GET /test.cgi HTTP/1.0\nHost: example.com\n\n", expectedMap)
}
示例14: main
func main() {
mypath, _ := os.Getwd()
println(mypath + ":" + os.Args[0])
d, _ := path.Split(os.Args[0])
os.Chdir(d)
fmt.Println(os.Getwd())
mypath, _ = os.Getwd()
println(mypath + ":" + os.Args[0])
mybytes := make(TestBytes, 100)
println(mybytes)
processMap["server"] = &Command{name: "server", command: "mhive", dir: mypath, args: []string{"mhive", "-r"}}
processMap["client"] = &Command{name: "client", command: "mhive", dir: mypath, args: []string{"mhive", "-i"}}
processMap["web"] = &Command{name: "web", command: "mhive", dir: mypath, args: []string{"mhive", "-w"}}
flag.Parse()
if flag.Arg(0) == "s" {
fmt.Println("starting server")
//go processListener(processMap)
server()
<-make(chan int)
} else if flag.Arg(0) == "stop" {
fmt.Println("stopping client")
stopclient("localhost", 1234)
} else {
fmt.Println("starting client")
client(flag.Arg(0), 1234)
}
}
示例15: LoadConfig
func LoadConfig(cfgfile string) (*Config, error) {
var (
cfg *Config
err error
wd string
)
if cfg, err = loadJsonConfig(cfgfile); err != nil {
return cfg, err
}
if cfg.Http.Webroot != "" && !strings.HasPrefix(cfg.Http.Webroot, "/") {
if wd, err = os.Getwd(); err == nil {
cfg.Http.Webroot = wd + "/" + cfg.Http.Webroot
} else {
return cfg, err
}
}
if !strings.HasPrefix(cfg.Http.ClientConf, "/") {
if wd, err = os.Getwd(); err == nil {
cfg.Http.ClientConf = wd + "/" + cfg.Http.ClientConf
} else {
return cfg, err
}
}
return cfg, nil
}