summaryrefslogtreecommitdiff
path: root/predict_files.go
diff options
context:
space:
mode:
authorEyal Posener <[email protected]>2019-07-05 15:10:58 +0300
committerEyal Posener <[email protected]>2019-07-05 17:29:25 +0300
commit72c5c945f0d5861ba1d4e51a0a5ac36a4bef3868 (patch)
tree0dbc83883d33ac239db651f19be3fe67fd3dc361 /predict_files.go
parent29f43e246ec41ee311a0a9bc24b15cb4ece4e513 (diff)
Deprecate Args.Directory()
Diffstat (limited to 'predict_files.go')
-rw-r--r--predict_files.go54
1 files changed, 53 insertions, 1 deletions
diff --git a/predict_files.go b/predict_files.go
index c8baec1..25ae2d5 100644
--- a/predict_files.go
+++ b/predict_files.go
@@ -51,7 +51,7 @@ func predictFiles(a Args, pattern string, allowFiles bool) []string {
return nil
}
- dir := a.Directory()
+ dir := directory(a.Last)
files := listFiles(dir, pattern, allowFiles)
// add dir if match
@@ -60,6 +60,19 @@ func predictFiles(a Args, pattern string, allowFiles bool) []string {
return PredictFilesSet(files).Predict(a)
}
+// directory gives the directory of the given partial path
+// in case that it is not, we fall back to the current directory.
+func directory(path string) string {
+ if info, err := os.Stat(path); err == nil && info.IsDir() {
+ return fixPathForm(path, path)
+ }
+ dir := filepath.Dir(path)
+ if info, err := os.Stat(dir); err == nil && info.IsDir() {
+ return fixPathForm(path, dir)
+ }
+ return "./"
+}
+
// PredictFilesSet predict according to file rules to a given set of file names
func PredictFilesSet(files []string) PredictFunc {
return func(a Args) (prediction []string) {
@@ -120,3 +133,42 @@ func matchFile(file, prefix string) bool {
return strings.HasPrefix(file, prefix)
}
+
+// fixPathForm changes a file name to a relative name
+func fixPathForm(last string, file string) string {
+ // get wording directory for relative name
+ workDir, err := os.Getwd()
+ if err != nil {
+ return file
+ }
+
+ abs, err := filepath.Abs(file)
+ if err != nil {
+ return file
+ }
+
+ // if last is absolute, return path as absolute
+ if filepath.IsAbs(last) {
+ return fixDirPath(abs)
+ }
+
+ rel, err := filepath.Rel(workDir, abs)
+ if err != nil {
+ return file
+ }
+
+ // fix ./ prefix of path
+ if rel != "." && strings.HasPrefix(last, ".") {
+ rel = "./" + rel
+ }
+
+ return fixDirPath(rel)
+}
+
+func fixDirPath(path string) string {
+ info, err := os.Stat(path)
+ if err == nil && info.IsDir() && !strings.HasSuffix(path, "/") {
+ path += "/"
+ }
+ return path
+}