|
| 1 | +package tapcfg |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "runtime" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +// ensureDirWritable verifies that the provided directory exists, is a directory |
| 11 | +// and is writable by creating a temporary file within it. |
| 12 | +func ensureDirWritable(dir string) error { |
| 13 | + dirInfo, err := os.Stat(dir) |
| 14 | + if err != nil { |
| 15 | + return fmt.Errorf("not accessible (dir=%s): %w", dir, err) |
| 16 | + } |
| 17 | + |
| 18 | + if !dirInfo.IsDir() { |
| 19 | + return fmt.Errorf("not a directory (dir=%s)", dir) |
| 20 | + } |
| 21 | + |
| 22 | + tmpFile, err := os.CreateTemp(dir, "tapd-tmpdir-check-*") |
| 23 | + if err != nil { |
| 24 | + return fmt.Errorf("not writable (dir=%s): %w", dir, err) |
| 25 | + } |
| 26 | + defer func() { _ = os.Remove(tmpFile.Name()) }() |
| 27 | + |
| 28 | + if err := tmpFile.Close(); err != nil { |
| 29 | + return fmt.Errorf("not writable (dir=%s): %w", dir, err) |
| 30 | + } |
| 31 | + |
| 32 | + return nil |
| 33 | +} |
| 34 | + |
| 35 | +// checkSQLiteTempDir checks temp directory locations on Linux/Darwin |
| 36 | +// and verifies the first writable option. SQLite honors SQLITE_TMPDIR first, |
| 37 | +// then TMPDIR, then falls back to /var/tmp, /usr/tmp and /tmp. |
| 38 | +// |
| 39 | +// NOTE: SQLite requires a writable temp directory because several internal |
| 40 | +// operations need temporary files when they cannot be done purely in memory. |
| 41 | +func checkSQLiteTempDir() error { |
| 42 | + // This check only runs for Linux/Darwin. |
| 43 | + if runtime.GOOS != "linux" && runtime.GOOS != "darwin" { |
| 44 | + return nil |
| 45 | + } |
| 46 | + |
| 47 | + // SQLite will use the first available temp directory; we mirror that |
| 48 | + // behavior by trying environment variables and standard fallback |
| 49 | + // directories in order. |
| 50 | + var errs []string |
| 51 | + |
| 52 | + type dirSource struct { |
| 53 | + path string |
| 54 | + source string |
| 55 | + } |
| 56 | + |
| 57 | + sources := []dirSource{ |
| 58 | + {path: os.Getenv("SQLITE_TMPDIR"), source: "env=SQLITE_TMPDIR"}, |
| 59 | + {path: os.Getenv("TMPDIR"), source: "env=TMPDIR"}, |
| 60 | + {path: "/var/tmp", source: "fallback=/var/tmp"}, |
| 61 | + {path: "/usr/tmp", source: "fallback=/usr/tmp"}, |
| 62 | + {path: "/tmp", source: "fallback=/tmp"}, |
| 63 | + } |
| 64 | + |
| 65 | + for _, s := range sources { |
| 66 | + if s.path == "" { |
| 67 | + continue |
| 68 | + } |
| 69 | + |
| 70 | + err := ensureDirWritable(s.path) |
| 71 | + if err != nil { |
| 72 | + err = fmt.Errorf("(%s) %w", s.source, err) |
| 73 | + errs = append(errs, err.Error()) |
| 74 | + continue |
| 75 | + } |
| 76 | + |
| 77 | + // Found a writable temp directory. |
| 78 | + return nil |
| 79 | + } |
| 80 | + |
| 81 | + return fmt.Errorf("no writable temp directory found; attempts=%s", |
| 82 | + strings.Join(errs, "; ")) |
| 83 | +} |
0 commit comments