Debian Codegraph @

main.go

raw
1 package main
2
3 import (
4 "flag"
5 "fmt"
6 "log"
7 "net"
8 "os"
9 "path/filepath"
10 "reflect"
11 "runtime"
12 "runtime/debug"
13 "runtime/pprof"
14 "strconv"
15 "strings"
16
17 _ "embed"
18
19 "golang.org/x/term"
20 )
21
22 //go:embed doc.txt
23 var genDocString string
24
25 var (
26 envPath = os.Getenv("PATH")
27 envLevel = os.Getenv("LF_LEVEL")
28 )
29
30 type arrayFlag []string
31
32 var (
33 gSingleMode bool
34 gPrintLastDir bool
35 gPrintSelection bool
36 gClientID int
37 gHostname string
38 gLastDirPath string
39 gSelectionPath string
40 gSocketPath string
41 gLogPath string
42 gSelect string
43 gConfigPath string
44 gCommands arrayFlag
45 gVersion string
46 )
47
48 func (a *arrayFlag) Set(v string) error {
49 *a = append(*a, v)
50 return nil
51 }
52
53 func (a *arrayFlag) String() string {
54 return strings.Join(*a, ", ")
55 }
56
57 func init() {
58 h, err := os.Hostname()
59 if err != nil {
60 log.Printf("hostname: %s", err)
61 }
62 gHostname = h
63
64 if envLevel == "" {
65 envLevel = "0"
66 }
67 }
68
69 func exportEnvVars() {
70 os.Setenv("id", strconv.Itoa(gClientID))
71
72 os.Setenv("OPENER", envOpener)
73 os.Setenv("EDITOR", envEditor)
74 os.Setenv("PAGER", envPager)
75 os.Setenv("SHELL", envShell)
76
77 dir, err := os.Getwd()
78 if err != nil {
79 fmt.Fprintf(os.Stderr, "getting current directory: %s\n", err)
80 }
81 os.Setenv("OLDPWD", dir)
82
83 level, err := strconv.Atoi(envLevel)
84 if err != nil {
85 log.Printf("reading lf level: %s", err)
86 }
87
88 level++
89
90 os.Setenv("LF_LEVEL", strconv.Itoa(level))
91 }
92
93 func exportFlags() {
94 os.Setenv("lf_flag_config", gConfigPath)
95 os.Setenv("lf_flag_last_dir_path", gLastDirPath)
96 os.Setenv("lf_flag_log", gLogPath)
97 os.Setenv("lf_flag_print_last_dir", strconv.FormatBool(gPrintLastDir))
98 os.Setenv("lf_flag_print_selection", strconv.FormatBool(gPrintSelection))
99 os.Setenv("lf_flag_selection_path", gSelectionPath)
100 os.Setenv("lf_flag_single", strconv.FormatBool(gSingleMode))
101 }
102
103 // used by exportOpts below
104 func fieldToString(field reflect.Value) string {
105 // prevent returning <main.borderStyle Value>
106 if field.Type() == reflect.TypeFor[borderStyle]() {
107 return borderStyle(field.Uint()).String()
108 }
109
110 var value string
111 switch field.Kind() {
112 case reflect.Int:
113 value = strconv.Itoa(int(field.Int()))
114 case reflect.Bool:
115 value = strconv.FormatBool(field.Bool())
116 case reflect.Slice:
117 for i := range field.Len() {
118 element := field.Index(i)
119
120 if i == 0 {
121 value = fieldToString(element)
122 } else {
123 value += ":" + fieldToString(element)
124 }
125 }
126 default:
127 value = field.String()
128 }
129
130 return value
131 }
132
133 func getOptsMap() map[string]string {
134 opts := make(map[string]string)
135 v := reflect.ValueOf(gOpts)
136 t := v.Type()
137
138 for i := range v.NumField() {
139 // Get field name and prefix it with lf_
140 name := "lf_" + t.Field(i).Name
141
142 switch name {
143 case "lf_nkeys", "lf_vkeys", "lf_cmdkeys", "lf_cmds":
144 // Skip maps
145 continue
146 case "lf_user":
147 // set each user option
148 for key, value := range gOpts.user {
149 opts[name+"_"+key] = value
150 }
151 default:
152 opts[name] = fieldToString(v.Field(i))
153 }
154 }
155
156 return opts
157 }
158
159 func exportLfPath() {
160 lfPath, err := os.Executable()
161 if err != nil {
162 log.Printf("getting path to lf binary: %s", err)
163 lfPath = "lf"
164 }
165 os.Setenv("lf", quoteString(lfPath))
166 }
167
168 func exportOpts() {
169 for key, value := range getOptsMap() {
170 os.Setenv(key, value)
171 }
172 }
173
174 func startServer() {
175 cmd := detachedCommand(os.Args[0], "-server")
176 if err := cmd.Start(); err != nil {
177 log.Printf("starting server: %s", err)
178 }
179 }
180
181 func checkServer() {
182 if _, err := os.Stat(gSocketPath); os.IsNotExist(err) {
183 startServer()
184 } else if _, err := net.Dial("unix", gSocketPath); err != nil {
185 if err := os.Remove(gSocketPath); err != nil {
186 log.Print(err)
187 }
188 startServer()
189 }
190 }
191
192 func printVersion() {
193 if gVersion != "" {
194 fmt.Println(gVersion)
195 return
196 }
197
198 buildInfo, ok := debug.ReadBuildInfo()
199 if !ok {
200 return
201 }
202
203 var vcsRevision, vcsTime, vcsModified string
204 for _, setting := range buildInfo.Settings {
205 switch setting.Key {
206 case "vcs.revision":
207 vcsRevision = setting.Value
208 case "vcs.time":
209 vcsTime = setting.Value
210 case "vcs.modified":
211 if setting.Value == "true" {
212 vcsModified = " (dirty)"
213 }
214 }
215 }
216
217 if vcsRevision != "" {
218 fmt.Printf("Built at commit: %s%s %s\n", vcsRevision, vcsModified, vcsTime)
219 }
220 fmt.Printf("Go version: %s\n", buildInfo.GoVersion)
221 }
222
223 func main() {
224 flag.Usage = func() {
225 f := flag.CommandLine.Output()
226 fmt.Fprintf(f, `lf - Terminal file manager
227
228 Usage: %s [options] [cd-or-select-path]
229
230 cd-or-select-path
231 set the initial dir or file selection to the given argument
232
233 Options:
234 `, os.Args[0])
235 flag.PrintDefaults()
236 }
237
238 showDoc := flag.Bool(
239 "doc",
240 false,
241 "show documentation")
242
243 showHelp := flag.Bool(
244 "help",
245 false,
246 "show help")
247
248 showVersion := flag.Bool(
249 "version",
250 false,
251 "show version")
252
253 serverMode := flag.Bool(
254 "server",
255 false,
256 "start server (automatic)")
257
258 singleMode := flag.Bool(
259 "single",
260 false,
261 "start a client without server")
262
263 printLastDir := flag.Bool(
264 "print-last-dir",
265 false,
266 "print the last dir to stdout on exit (to use for cd)")
267
268 printSelection := flag.Bool(
269 "print-selection",
270 false,
271 "print the selected files to stdout on open (to use as open file dialog)")
272
273 remoteCmd := flag.String(
274 "remote",
275 "",
276 "send remote `command` to server")
277
278 cpuprofile := flag.String(
279 "cpuprofile",
280 "",
281 "`path` to the file to write the CPU profile")
282
283 memprofile := flag.String(
284 "memprofile",
285 "",
286 "`path` to the file to write the memory profile")
287
288 flag.StringVar(&gLastDirPath,
289 "last-dir-path",
290 "",
291 "`path` to the file to write the last dir on exit (to use for cd)")
292
293 flag.StringVar(&gSelectionPath,
294 "selection-path",
295 "",
296 "`path` to the file to write selected files on open (to use as open file dialog)")
297
298 flag.StringVar(&gConfigPath,
299 "config",
300 "",
301 "`path` to the config file (instead of the usual paths)")
302
303 flag.Var(&gCommands,
304 "command",
305 "`command` to execute on client initialization")
306
307 flag.StringVar(&gLogPath,
308 "log",
309 "",
310 "`path` to the log file to write messages")
311
312 flag.Parse()
313
314 gSocketPath = gDefaultSocketPath
315
316 if gLogPath != "" {
317 path, err := filepath.Abs(gLogPath)
318 if err != nil {
319 log.Fatalf("getting log path: %s", err)
320 }
321 gLogPath = path
322 }
323
324 if *cpuprofile != "" {
325 f, err := os.Create(*cpuprofile)
326 if err != nil {
327 log.Fatalf("could not create CPU profile: %s", err)
328 }
329 if err := pprof.StartCPUProfile(f); err != nil {
330 log.Fatalf("could not start CPU profile: %s", err)
331 }
332 defer pprof.StopCPUProfile()
333 }
334
335 switch {
336 case *showDoc:
337 fmt.Print(genDocString)
338 case *showHelp:
339 flag.Usage()
340 case *showVersion:
341 printVersion()
342 case *remoteCmd != "":
343 resp, err := remote(*remoteCmd)
344 if err != nil {
345 log.Fatalf("remote command: %s", err)
346 return
347 }
348 // sanitize untrusted names when writing to a terminal
349 if term.IsTerminal(int(os.Stdout.Fd())) {
350 lines := strings.Split(resp, "\n")
351 for i := range lines {
352 lines[i] = sanitizeName(lines[i])
353 }
354 resp = strings.Join(lines, "\n")
355 }
356 fmt.Print(resp)
357 case *serverMode:
358 if err := os.Chdir(gUser.HomeDir); err != nil {
359 log.Print(err)
360 }
361 serve()
362 default:
363 gSingleMode = *singleMode
364 gPrintLastDir = *printLastDir
365 gPrintSelection = *printSelection
366
367 if !gSingleMode {
368 checkServer()
369 }
370
371 gClientID = os.Getpid()
372
373 switch flag.NArg() {
374 case 0:
375 _, err := os.Getwd()
376 if err != nil {
377 fmt.Fprintf(os.Stderr, "getting current directory: %s\n", err)
378 os.Exit(2)
379 }
380 case 1:
381 gSelect = flag.Arg(0)
382 default:
383 fmt.Fprintln(os.Stderr, "only single file or directory is allowed")
384 os.Exit(2)
385 }
386
387 exportEnvVars()
388 exportFlags()
389
390 run()
391 }
392
393 if *memprofile != "" {
394 f, err := os.Create(*memprofile)
395 if err != nil {
396 log.Fatal("could not create memory profile: ", err)
397 }
398 runtime.GC()
399 if err := pprof.WriteHeapProfile(f); err != nil {
400 log.Fatal("could not write memory profile: ", err)
401 }
402 f.Close()
403 }
404 }