File: path.go

package info (click to toggle)
tea-cli 0.9.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,364 kB
  • sloc: makefile: 120; sh: 17
file content (71 lines) | stat: -rw-r--r-- 1,779 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package utils

import (
	"errors"
	"os"
	"os/user"
	"path/filepath"
	"strings"
)

// PathExists returns whether the given file or directory exists or not
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return true, err
}

// FileExist returns whether the given file exists or not
func FileExist(fileName string) (bool, error) {
	return exists(fileName, false)
}

// DirExists returns whether the given file exists or not
func DirExists(path string) (bool, error) {
	return exists(path, true)
}

func exists(path string, expectDir bool) (bool, error) {
	f, err := os.Stat(path)
	if err != nil {
		if errors.Is(err, os.ErrNotExist) {
			return false, nil
		} else if err.(*os.PathError).Err.Error() == "not a directory" {
			// some middle segment of path is a file, cannot traverse
			// FIXME: catches error on linux; go does not provide a way to catch this properly..
			return false, nil
		}
		return false, err
	}
	isDir := f.IsDir()
	if isDir && !expectDir {
		return false, errors.New("A directory with the same name exists")
	} else if !isDir && expectDir {
		return false, errors.New("A file with the same name exists")
	}
	return true, nil
}

// AbsPathWithExpansion expand path beginning with "~/" to absolute path
func AbsPathWithExpansion(p string) (string, error) {
	u, err := user.Current()
	if err != nil {
		return "", err
	}
	if p == "~" {
		return u.HomeDir, nil
	} else if strings.HasPrefix(p, "~/") {
		return filepath.Join(u.HomeDir, p[2:]), nil
	} else {
		return filepath.Abs(p)
	}
}