本文整理汇总了Golang中path/filepath.Abs函数的典型用法代码示例。如果您正苦于以下问题:Golang Abs函数的具体用法?Golang Abs怎么用?Golang Abs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Abs函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestCompileBinary
func TestCompileBinary(t *testing.T) {
scriptFilename := "output.go"
binaryFilename := "TestCompileBinary_output"
if Exist(binaryFilename) {
removeFile(t, binaryFilename)
}
scriptPath, err := filepath.Abs(scriptFilename)
if err != nil {
t.Fatal(err)
}
binaryPath, err := filepath.Abs(binaryFilename)
if err != nil {
t.Fatal(err)
}
CompileBinary(scriptPath, binaryPath, false)
if !Exist(binaryFilename) {
t.Fatalf("Compiled binary does not exist: [%s]", binaryFilename)
}
defer removeFile(t, binaryFilename)
out, err := exec.Command("./" + binaryFilename).Output()
if err != nil {
t.Fatal(err)
}
expected(t, binaryFilename, string(out), "The night is all magic\n")
}
示例2: doCmd
// doCmd executes the given command line string in either the out/Debug
// directory or the inout directory. Returns the stdout and stderr.
func doCmd(commandLine string, moveToDebug bool) (string, error) {
log.Printf("Command: %q\n", commandLine)
programAndArgs := strings.SplitN(commandLine, " ", 2)
program := programAndArgs[0]
args := []string{}
if len(programAndArgs) > 1 {
args = strings.Split(programAndArgs[1], " ")
}
cmd := exec.Command(program, args...)
abs, err := filepath.Abs("../../out/Debug")
if err != nil {
return "", fmt.Errorf("Failed to find absolute path to Debug directory.")
}
if moveToDebug {
cmd.Dir = abs
} else if !*useChroot { // Don't set cmd.Dir when using chroot.
abs, err := filepath.Abs("../../../inout")
if err != nil {
return "", fmt.Errorf("Failed to find absolute path to inout directory.")
}
cmd.Dir = abs
}
log.Printf("Run in directory: %q\n", cmd.Dir)
message, err := cmd.CombinedOutput()
log.Printf("StdOut + StdErr: %s\n", string(message))
if err != nil {
log.Printf("Exit status: %s\n", err.Error())
return string(message), fmt.Errorf("Failed to run command.")
}
return string(message), nil
}
示例3: checkRequiredFilesExist
func (this *fileWriterTester) checkRequiredFilesExist(testCase *fileWriterTestCase, files []string) {
var found bool
for _, expected := range testCase.resFiles {
found = false
exAbs, err := filepath.Abs(expected)
if err != nil {
this.t.Errorf("filepath.Abs failed for %s", expected)
continue
}
for _, f := range files {
if af, e := filepath.Abs(f); e == nil {
this.t.Log(af)
if exAbs == af {
found = true
break
}
} else {
this.t.Errorf("filepath.Abs failed for %s", f)
}
}
if !found {
this.t.Errorf("Expected file: %s doesn't exist. Got %v\n", exAbs, files)
}
}
}
示例4: NewPod
func NewPod(path string, args BuildArgs) (*Pod, error) {
fullPath, err := filepath.Abs(path)
if err != nil {
logs.WithE(err).WithField("path", path).Fatal("Cannot get fullpath")
}
manifest, err := readPodManifest(fullPath + POD_MANIFEST)
if err != nil {
return nil, errors.Annotate(err, "Failed to read pod manifest")
}
fields := data.WithField("pod", manifest.Name.String())
target := path + PATH_TARGET
if cnt.Home.Config.TargetWorkDir != "" {
currentAbsDir, err := filepath.Abs(cnt.Home.Config.TargetWorkDir + "/" + manifest.Name.ShortName())
if err != nil {
logs.WithEF(err, fields).Panic("invalid target path")
}
target = currentAbsDir
}
pod := &Pod{
fields: fields,
path: fullPath,
args: args,
target: target,
manifest: *manifest,
}
return pod, nil
}
示例5: filterPath
func (f *Fs) filterPath(s string) string {
s = filepath.Clean(s)
if runtime.GOOS == "windows" {
s = strings.Replace(s, `/`, `\`, -1)
if !filepath.IsAbs(s) && !strings.HasPrefix(s, "\\") {
s2, err := filepath.Abs(s)
if err == nil {
s = s2
}
}
if f.nounc {
return s
}
// Convert to UNC
return uncPath(s)
}
if !filepath.IsAbs(s) {
s2, err := filepath.Abs(s)
if err == nil {
s = s2
}
}
return s
}
示例6: LoadConfigure
func LoadConfigure() *Configure {
dir := "conf"
absDir := "."
if _, err := os.Stat("../" + dir + "/"); err == nil {
absDir, _ = filepath.Abs("../" + dir + "/")
} else if _, err := os.Stat("../../" + dir + "/"); err == nil {
absDir, _ = filepath.Abs("../../" + dir + "/")
} else {
absDir = binDir() + "/../" + dir
}
var file = absDir + "/../conf/server.cfg"
var default_file = absDir + "/../conf/server_default.cfg"
if _, err := os.Stat(file); err != nil {
file = default_file
}
var config = Configure{}
if _, err := toml.DecodeFile(file, &config); err != nil {
panic(err)
}
fmt.Print(config)
return &config
}
示例7: pkgFromDir
// pkgFromDir extracts package import path from dir. dir can be a path on file system
// or go get path.
func pkgFromDir(dir string) string {
gopaths := strings.Split(os.Getenv("GOPATH"), string(filepath.ListSeparator))
// if directory exits, infer import path from dir relative to GOPATH.
if stat, err := os.Stat(dir); err == nil && stat.IsDir() {
for _, gopath := range gopaths {
absgopath, _ := filepath.Abs(gopath)
gosrc := filepath.Join(absgopath, "src") + string(filepath.Separator)
absdir, _ := filepath.Abs(dir)
if strings.HasPrefix(absdir, gosrc) {
return strings.TrimPrefix(absdir, gosrc)
}
}
// not in GOPATH, create symlink to fake GOPATH.
if newpath, err := symlinkGOPATH(dir); err == nil {
return filepath.Base(newpath)
}
}
if isLocalPkg(dir) {
return dir
}
return ""
}
示例8: testFile
func testFile(t *testing.T, filename string) {
path, _ := filepath.Abs("./tests/" + filename + ".json")
jsonBytes, err := ioutil.ReadFile(path)
if err != nil {
t.Error("Could not load "+filename+".json", err)
}
// Create a new container
vi := &VersionInfo{}
// Parse the config
if err := vi.ParseJSON(jsonBytes); err != nil {
t.Error("Could not parse "+filename+".json", err)
}
// Fill the structures with config data
vi.Build()
// Write the data to a buffer
vi.Walk()
path2, _ := filepath.Abs("./tests/" + filename + ".hex")
expected, err := ioutil.ReadFile(path2)
if err != nil {
t.Error("Could not load "+filename+".hex", err)
}
if !bytes.Equal(vi.Buffer.Bytes(), expected) {
t.Error("Data does not match " + filename + ".hex")
}
}
示例9: guessImportPath
// guessImportPath finds the package containing filename, and returns
// its source directory (an element of $GOPATH) and its import path
// relative to it.
//
// TODO(adonovan): what about _test.go files that are not part of the
// package?
//
func guessImportPath(filename string, buildContext *build.Context) (srcdir, importPath string, err error) {
absFile, err := filepath.Abs(filename)
if err != nil {
err = fmt.Errorf("can't form absolute path of %s", filename)
return
}
absFileDir := segments(filepath.Dir(absFile))
// Find the innermost directory in $GOPATH that encloses filename.
minD := 1024
for _, gopathDir := range buildContext.SrcDirs() {
absDir, err := filepath.Abs(gopathDir)
if err != nil {
continue // e.g. non-existent dir on $GOPATH
}
d := prefixLen(segments(absDir), absFileDir)
// If there are multiple matches,
// prefer the innermost enclosing directory
// (smallest d).
if d >= 0 && d < minD {
minD = d
srcdir = gopathDir
importPath = strings.Join(absFileDir[len(absFileDir)-minD:], string(os.PathSeparator))
}
}
if srcdir == "" {
err = fmt.Errorf("can't find package for file %s", filename)
}
return
}
示例10: cleanAssetName
// cleanAssetName returns an asset name from the parent dirname and
// the file name without extension.
// The combination
// path=/tmp/css/default.css
// basePath=/tmp/
// prependPath=new/
// will return
// new/css/default
func cleanAssetName(path, basePath, prependPath string) string {
var name string
path, basePath, prependPath = strings.TrimSpace(path), strings.TrimSpace(basePath), strings.TrimSpace(prependPath)
basePath, err := filepath.Abs(basePath)
if err != nil {
basePath = ""
}
apath, err := filepath.Abs(path)
if err == nil {
path = apath
}
if basePath == "" {
idx := strings.LastIndex(path, string(os.PathSeparator))
if idx != -1 {
idx = strings.LastIndex(path[:idx], string(os.PathSeparator))
}
name = path[idx+1:]
} else {
// Directory
name = strings.Replace(path, basePath, "", 1)
if name[0] == os.PathSeparator {
name = name[1:]
}
}
if prependPath != "" {
if prependPath[0] == os.PathSeparator {
prependPath = prependPath[1:]
}
prependPath = EnsureTrailingSlash(prependPath)
}
return prependPath + name[:len(name)-len(filepath.Ext(name))]
}
示例11: main
func main() {
if flag.NArg() == 0 {
fmt.Printf("[Error] path or file must provide one.\n\n")
flag.Usage()
os.Exit(retFail)
}
for i := 0; i < flag.NArg(); i++ {
path := strings.TrimSpace(flag.Arg(i))
switch dir, err := os.Stat(path); {
case err != nil:
//fmt.Printf("[Error] error in Stat(): %s.\n", err)
panic(err)
case dir.IsDir():
if path, err = filepath.Abs(path); err != nil {
panic(err)
}
dealDirWithWhiteList(path, cmd, suffixArray)
default:
if path, err = filepath.Abs(path); err != nil {
panic(err)
}
dealFileWithWhiteList(path, cmd, suffixArray)
}
}
}
示例12: LoadSync
// LoadSync loads the sync based on the settings found in localPath
func LoadSync(localPath string) (*SyncInfo, error) {
// Only open pre-existing syncs. sql.Open would indiscrimately create an
// empty database if we didn't check this in advance
dbPath := filepath.Join(localPath, settingsDir, dbFileName)
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
return nil, &ErrSync{fmt.Sprintf("'%v' does not appear to be a valid sync: no settings directory found", localPath), err}
}
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
return nil, err
}
// Load remainder of settings
sync := new(SyncInfo)
sync.db = db
sync.changesReady = make(chan bool)
if sync.localBase, err = filepath.Abs(localPath); err != nil {
return nil, &ErrSync{"Unable to get absolute local path", err}
}
if sync.remoteBase, err = sync.Get(remotePathKey); err != nil {
return nil, &ErrSync{"Remote path not set", err}
}
if sync.remoteBase, err = filepath.Abs(filepath.FromSlash(sync.remoteBase)); err != nil {
return nil, &ErrSync{"Unable to get absolute remote path", err}
}
cKeyStr, err := sync.Get(cryptoKeyKey)
if err != nil {
return nil, &ErrSync{"Encryption key not set", err}
}
aKeyStr, err := sync.Get(authKeyKey)
if err != nil {
return nil, &ErrSync{"Authentication key not set", err}
}
cKey, err := gocrypt.KeyFromString(cKeyStr)
if err != nil {
return nil, &ErrSync{"Failed to convert encryption key", err}
}
aKey, err := gocrypt.KeyFromString(aKeyStr)
if err != nil {
return nil, &ErrSync{"Failed to convert authentication key", err}
}
sync.keys = &gocrypt.KeyCombo{CryptoKey: cKey, AuthKey: aKey}
// Make sure everything loaded correctly
if err = sync.sanityCheckConfig(); err != nil {
return nil, err
}
log.Println("Cleaning sync")
sync.Clean()
return sync, nil
}
示例13: TestCompleteBuild
func TestCompleteBuild(t *testing.T) {
scriptFilename := "build/builder.go"
binaryFilename := "build/TestCompleteBuildBinary_builder"
if Exist(binaryFilename) {
removeFile(t, binaryFilename)
}
out, err := exec.Command("./" + scriptFilename).Output()
if err != nil {
t.Fatal(err)
}
expected(t, "build/builder.go", string(out), "Build!\n")
scriptPath, err := filepath.Abs(scriptFilename)
if err != nil {
t.Fatal(err)
}
binaryPath, err := filepath.Abs(binaryFilename)
if err != nil {
t.Fatal(err)
}
CompileBinary(scriptPath, binaryPath, true)
if !Exist(binaryFilename) {
t.Fatalf("Compiled binary does not exist: [%s]", binaryFilename)
}
defer removeFile(t, binaryFilename)
out, err = exec.Command("./" + binaryFilename).Output()
if err != nil {
t.Fatal(err)
}
expected(t, "build/builder.go", string(out), "Build!\n")
}
示例14: TestNewStaticPageHandler
func TestNewStaticPageHandler(t *testing.T) {
defPagePath, _ := filepath.Abs("haproxy.cfg")
defErrorPath, _ := filepath.Abs("template.cfg")
defErrURL := "http://www.k8s.io"
testDefPage := "file://" + defPagePath
testErrorPage := "file://" + defErrorPath
handler := newStaticPageHandler("", testDefPage)
if handler == nil {
t.Fatalf("Expected page handler")
}
handler = newStaticPageHandler(testErrorPage, testDefPage)
if handler.pagePath != testErrorPage {
t.Fatalf("Expected local file content but got default page")
}
handler = newStaticPageHandler(defErrURL, testDefPage)
if handler.pagePath != defErrURL {
t.Fatalf("Expected remote error page content but got default page")
}
handler = newStaticPageHandler(defErrURL+"s", testDefPage)
if handler.pagePath != testDefPage {
t.Fatalf("Expected local file content with not valid URL")
}
}
示例15: GitAndRootDirs
func GitAndRootDirs() (string, string, error) {
cmd := execCommand("git", "rev-parse", "--git-dir", "--show-toplevel")
buf := &bytes.Buffer{}
cmd.Stderr = buf
out, err := cmd.Output()
output := string(out)
if err != nil {
return "", "", fmt.Errorf("Failed to call git rev-parse --git-dir --show-toplevel: %q", buf.String())
}
paths := strings.Split(output, "\n")
pathLen := len(paths)
if pathLen == 0 {
return "", "", fmt.Errorf("Bad git rev-parse output: %q", output)
}
absGitDir, err := filepath.Abs(paths[0])
if err != nil {
return "", "", fmt.Errorf("Error converting %q to absolute: %s", paths[0], err)
}
if pathLen == 1 || len(paths[1]) == 0 {
return absGitDir, "", nil
}
absRootDir, err := filepath.Abs(paths[1])
if err != nil {
return "", "", fmt.Errorf("Error converting %q to absolute: %s", paths[1], err)
}
return absGitDir, absRootDir, nil
}