-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.go
More file actions
89 lines (77 loc) · 2.31 KB
/
util.go
File metadata and controls
89 lines (77 loc) · 2.31 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// This file is part of clipsync (C)2023 by Marco Paganini
// Please see http://github.com/marcopaganini/clipsync for details.
package main
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/fredli74/lockfile"
log "github.com/romana/rlog"
)
// Show at most this number of characters on a redacted string
// (half at the beginning, half at the end.)
const redactDefaultLen = 50
// redact holds the level of redaction.
type redactType struct {
maxlen int
}
// redact returns a shortened and partially redacted string.
func (x redactType) redact(s string) string {
ret := fmt.Sprintf("[%s]", strquote(s))
// Only redact if too long.
if x.maxlen <= 0 {
x.maxlen = redactDefaultLen
}
if len(s) > x.maxlen {
ret = fmt.Sprintf("[%s(...)%s]", strquote(s[:x.maxlen/2]), strquote(s[len(s)-x.maxlen/2:]))
}
ret += fmt.Sprintf(" length=%d", len(s))
return ret
}
// strquote returns a quoted string, but removes the external quotes and
// replaces \" for " inside the string.
func strquote(s string) string {
ret := strings.ReplaceAll(strconv.Quote(s), `\"`, `"`)
return ret[1 : len(ret)-1]
}
// singleInstanceOrDie guarantees that this is the only instance of
// this program using the specified lockfile. Caller must call
// Unlock on the returned lock once it's not needed anymore.
func singleInstanceOrDie(lckfile string) *lockfile.LockFile {
lock, err := lockfile.Lock(lckfile)
if err != nil {
fatal("Another instance is already running.")
}
return lock
}
// tildeExpand expands the tilde at the beginning of a filename to $HOME.
func tildeExpand(path string) string {
if !strings.HasPrefix(path, "~/") {
return path
}
dirname, err := os.UserHomeDir()
if err != nil {
log.Errorf("Unable to locate homedir when expanding: %q", path)
return path
}
return filepath.Join(dirname, path[2:])
}
// fileExists if the given file exists and is a file (not a directory).
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
// instanceID generates a unique instance ID based on the machine name,
// display, and a random number unique for this run.
func instanceID() (string, error) {
host, err := os.Hostname()
if err != nil {
return "", err
}
return fmt.Sprintf("%s%s-%d", host, os.Getenv("DISPLAY"), os.Getpid()), nil
}