| // Copyright 2020 The Fuchsia 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 codifier |
| |
| import ( |
| "fmt" |
| "os" |
| "path/filepath" |
| "strings" |
| ) |
| |
| // Resolves the current name to a full path, given the current base, home, and |
| // current directories. |
| func resolve(baseDir, homeDir, currentDir, name string) string { |
| if strings.HasPrefix(name, "//") { |
| return filepath.Join(baseDir, name[2:]) |
| } |
| |
| if strings.HasPrefix(name, "/") { |
| return name |
| } |
| |
| if strings.HasPrefix(name, "~") { |
| return filepath.Join(homeDir, name[1:]) |
| } |
| |
| return filepath.Join(currentDir, name) |
| } |
| |
| // resolveGnPath makes the given path absolute by resolving the home directory, |
| // the given baseDir or the current directory depending on the path prefix. The |
| // home directory case handles paths that start with "~". The baseDir may be |
| // absolute or relative to the home directory. Paths that start with "//"" are |
| // made absolute relative to the baseDir. |
| func resolveGnPath(baseDir, filename string) (string, error) { |
| home, err := os.UserHomeDir() |
| if err != nil { |
| return "", fmt.Errorf("can't find user home directory: %w", err) |
| } |
| |
| if strings.HasPrefix(baseDir, "~") { |
| baseDir = filepath.Join(home, baseDir[1:]) |
| } else { |
| if !strings.HasPrefix(baseDir, "/") { |
| baseDir = filepath.Join(home, baseDir) |
| } |
| } |
| |
| cwd, err := os.Getwd() |
| if err != nil { |
| return "", fmt.Errorf("can't obtain working directory: %w", err) |
| } |
| |
| return resolve(baseDir, home, cwd, filename), nil |
| } |
| |
| // SplitGNBuildTarget returns the BUILD absolute filepath and the target given a |
| // gn build target. For example, "//path/to/test:target" would return |
| // "/usr/home/foo/fuchsia/path/to/test/BUILD.gn" and "target". |
| func SplitGNBuildTarget(fuchsiaHome, targetPath string) (string, string, error) { |
| parts := strings.Split(targetPath, ":") |
| if len(parts) != 2 { |
| return "", "", fmt.Errorf("can't find ':' separator in string %q", targetPath) |
| } |
| buildPath, target := parts[0], parts[1] |
| dirPath, err := resolveGnPath(fuchsiaHome, buildPath) |
| if err != nil { |
| return "", "", err |
| } |
| buildFile := filepath.Join(dirPath, "BUILD.gn") |
| return buildFile, target, nil |
| } |