Debian Codegraph @

t/cmd/lfstest-realpath.go

raw symbols SCIP
1 //go:build testtools
2 // +build testtools
3
4 package main
5
6 import (
7 "fmt"
8 "os"
9 "path/filepath"
10 )
11
12 func canonicalize(path string) (string, error) {
13 left := path
14 right := ""
15
16 for {
17 canon, err := filepath.EvalSymlinks(left)
18 if err != nil && !os.IsNotExist(err) {
19 return "", err
20 }
21 if err == nil {
22 if right == "" {
23 return canon, nil
24 }
25 return filepath.Join(canon, right), nil
26 }
27 // One component of our path is missing. Let's walk up a level
28 // and canonicalize that and then append the remaining piece.
29 full := filepath.Join(left, right)
30 if right == "" {
31 full = left
32 }
33 newleft := filepath.Clean(fmt.Sprintf("%s%c..", left, os.PathSeparator))
34 newright, err := filepath.Rel(newleft, full)
35 if err != nil {
36 return "", err
37 }
38 left = newleft
39 right = newright
40 }
41 }
42
43 func main() {
44 if len(os.Args) != 2 {
45 fmt.Fprintf(os.Stderr, "Usage: %s PATH\n", os.Args[0])
46 os.Exit(2)
47 }
48
49 path, err := filepath.Abs(os.Args[1])
50 if err != nil {
51 fmt.Fprintf(os.Stderr, "Error creating absolute path: %v", err)
52 os.Exit(3)
53 }
54
55 fullpath, err := canonicalize(path)
56 if err != nil {
57 fmt.Fprintf(os.Stderr, "Error canonicalizing: %v", err)
58 os.Exit(4)
59 }
60
61 fmt.Println(fullpath)
62 }