-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
194 lines (172 loc) · 4.34 KB
/
main.go
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"unicode/utf8"
_ "embed"
"github.com/akamensky/argparse"
"github.com/h2non/filetype"
)
const (
pngFileType = "png"
jpgFileType = "jpg"
gifFileType = "gif"
bmpFileType = "bmp"
tiffFileType = "tif"
)
//go:generate bash get_version.sh
//go:embed version.txt
var version string
func exitOnError(err error) {
if err != nil {
log.Fatal(err)
}
}
func getAbsfilename(fileName string) string {
absfileName, err := filepath.Abs(fileName)
exitOnError(err)
return absfileName
}
func validateFile(filePath string) {
_, err := os.Stat(filePath)
exitOnError(err)
}
func cleanup(tempfile *os.File) int {
tempfile.Close()
os.Remove(tempfile.Name())
return 0
}
func getFileClass(fileContent []byte) (string, string) {
kind, _ := filetype.Match(fileContent)
fileExtension := kind.Extension
isImage := filetype.IsImage(fileContent)
var fileClass = ""
if isImage {
switch strings.ToLower(fileExtension) {
case pngFileType:
fileClass = "«class PNGf»"
case jpgFileType:
fileClass = "JPEG picture"
case gifFileType:
fileClass = "GIF picture"
case bmpFileType:
// Extra space here is intentional
fileClass = "«class BMP »"
case tiffFileType:
fileClass = "TIFF picture"
}
} else {
// Check if file is utf8 encoded
if utf8.Valid(fileContent) {
fileClass = "«class utf8»"
}
}
return fileClass, fileExtension
}
func createCommand(absfileName string, fileClass string, rawData bool) (command string) {
if len(fileClass) > 0 {
command = fmt.Sprintf(
"set the clipboard to (read (POSIX file \"%s\") as %s)",
absfileName,
fileClass,
)
} else if rawData {
command = fmt.Sprintf("set the clipboard to (read (POSIX file \"%s\"))", absfileName)
} else {
command = fmt.Sprintf("tell application \"Finder\" to set the clipboard to (POSIX file \"%s\")", absfileName)
}
return
}
func runCommand(command string) {
defer func() {
//lint:ignore SA9003 Unable to copy the data to clipboard, do nothing !
if r := recover(); r != nil {
}
}()
cmd := exec.Command("osascript", "-e", command)
output, err := cmd.CombinedOutput()
if len(output) > 0 {
err = fmt.Errorf("%w; %s", err, string(output))
}
exitOnError(err)
}
func writeTempFile(stdin []byte, fileExtension string) *os.File {
f, err := os.CreateTemp("", fmt.Sprintf("tmpfile-*.%s", fileExtension))
exitOnError(err)
_, err = f.Write(stdin)
exitOnError(err)
return f
}
func readFromStdinUntilSigEOF() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanRunes)
input := ""
for scanner.Scan() {
input += scanner.Text()
runCommand(fmt.Sprintf("set the clipboard to \"%s\"", input))
}
err := scanner.Err()
exitOnError(err)
}
func main() {
parser := argparse.NewParser("gcopy [file] [STDIN]", "gcopy: copy content to the clipboard")
printVersion := parser.Flag("v", "version", &argparse.Options{Help: "Current version"})
pathName := parser.Flag(
"p",
"path",
&argparse.Options{
Help: "Copy (and show) the absolute path of a file or folder to the clipboard",
},
)
var fileName *string = parser.StringPositional(&argparse.Options{Help: "DISABLEDDESCRIPTIONWILLNOTSHOWUP"})
parser.Parse(os.Args)
if *printVersion {
fmt.Printf("build version: %s", version)
os.Exit(0)
}
var fileArg bool
if len(*fileName) > 0 {
fileArg = true
}
if *pathName && fileArg {
absfileName := getAbsfilename(*fileName)
validateFile(absfileName)
command := fmt.Sprintf("set the clipboard to \"%s\"", absfileName)
fmt.Println(absfileName)
runCommand(command)
os.Exit(0)
}
stat, err := os.Stdin.Stat()
exitOnError(err)
if !fileArg && ((stat.Mode() & os.ModeCharDevice) != 0) {
readFromStdinUntilSigEOF()
os.Exit(0)
}
var command = ""
// stdin takes precedence over positional argument
if (stat.Mode() & os.ModeCharDevice) == 0 {
stdin, err := io.ReadAll(os.Stdin)
exitOnError(err)
fileClass, fileExtension := getFileClass(stdin)
tempfile := writeTempFile(stdin, fileExtension)
command = createCommand(tempfile.Name(), fileClass, true)
defer tempfile.Close()
defer os.Remove(tempfile.Name())
runCommand(command)
os.Exit(cleanup(tempfile))
}
// Argument expects file
if fileArg {
absfileName := getAbsfilename(*fileName)
validateFile(absfileName)
command = createCommand(absfileName, "", false)
runCommand(command)
os.Exit(0)
}
}