File: misc.go

package info (click to toggle)
golang-github-evilsocket-islazy 1.11.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 292 kB
  • sloc: javascript: 8; makefile: 3
file content (62 lines) | stat: -rw-r--r-- 1,227 bytes parent folder | download | duplicates (3)
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
package fs

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

var (
	cwdLock = sync.Mutex{}
)

// Expand will expand a path with ~ to the $HOME of the current user.
func Expand(path string) (string, error) {
	if path == "" {
		return path, nil
	}
	home := os.Getenv("HOME")
	if home == "" {
		usr, err := user.Current()
		if err != nil {
			return "", err
		}
		home = usr.HomeDir
	}
	return filepath.Abs(strings.Replace(path, "~", home, 1))
}

// Exists returns true if the path exists.
func Exists(path string) bool {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		return false
	}
	return true
}

// Chdir changes the process current working directory to the specified
// one, executes the callback and then restores the original working directory.
func Chdir(path string, cb func() error) error {
	cwdLock.Lock()
	defer cwdLock.Unlock()

	cwd, err := os.Getwd()
	if err != nil {
		return err
	}
	// make sure that whatever happens we restore the original
	// working directory of the process
	defer func() {
		if err := os.Chdir(cwd); err != nil {
			panic(err)
		}
	}()
	// change folder
	if err := os.Chdir(path); err != nil {
		return err
	}
	// run the callback once inside the folder
	return cb()
}