// SPDX-FileCopyrightText: Copyright The Lima Authors1// SPDX-License-Identifier: Apache-2.023package localpathutil45import (6"errors"7"fmt"8"os"9"path/filepath"10"strings"11)1213// IsTildePath returns true if the path is "~" or starts with "~/".14// This means Expand() can expand it with the home directory.15func IsTildePath(path string) bool {16return path == "~" || strings.HasPrefix(path, "~/")17}1819// Expand expands a path like "~", "~/", "~/foo".20// Paths like "~foo/bar" are unsupported.21//22// FIXME: is there an existing library for this?23func Expand(orig string) (string, error) {24s := orig25if s == "" {26return "", errors.New("empty path")27}2829if strings.HasPrefix(s, "~") {30if IsTildePath(s) {31homeDir, err := os.UserHomeDir()32if err != nil {33return "", err34}35s = strings.Replace(s, "~", homeDir, 1)36} else {37// Paths like "~foo/bar" are unsupported.38return "", fmt.Errorf("unexpandable path %q", orig)39}40}41return filepath.Abs(s)42}434445