github.com/adevinta/lava@v0.7.2/internal/assettypes/assettypes.go (about) 1 // Copyright 2023 Adevinta 2 3 // Package assettypes defines a set of asset types that are valid in 4 // the context of Lava. 5 package assettypes 6 7 import ( 8 "errors" 9 "fmt" 10 "io/fs" 11 "os" 12 "slices" 13 14 types "github.com/adevinta/vulcan-types" 15 ) 16 17 // ErrUnsupported is returned when the requested operation does not 18 // support the specified asset type. 19 var ErrUnsupported = errors.New("unsupported asset type") 20 21 // Lava asset types. 22 const ( 23 Path = types.AssetType("Path") 24 ) 25 26 // vulcanMap is the mapping between Lava and Vulcan asset types. 27 var vulcanMap = map[types.AssetType]types.AssetType{ 28 Path: types.GitRepository, 29 } 30 31 // lavaTypes is the list of all Lava asset types. 32 var lavaTypes = []types.AssetType{Path} 33 34 // IsValid reports whether the provided asset type is valid in the 35 // context of Lava. 36 func IsValid(at types.AssetType) bool { 37 return slices.Contains(lavaTypes, at) 38 } 39 40 // ToVulcan maps a Lava asset type to a Vulcan asset type. If there is 41 // no such mapping, the provided asset type is returned. 42 func ToVulcan(at types.AssetType) types.AssetType { 43 if vt, ok := vulcanMap[at]; ok { 44 return vt 45 } 46 return at 47 } 48 49 // CheckReachable checks if the asset with the specified type and 50 // identifier is reachable. CheckReachable does not check if the asset 51 // is functional. If the asset is reachable, it returns a nil 52 // error. If the asset is unreachable, it returns an error explaining 53 // the cause. If the asset type is not supported, it returns an 54 // [ErrUnsupported] error. If the reachability test fails, it returns 55 // the error that caused the failure. 56 func CheckReachable(typ types.AssetType, ident string) error { 57 switch typ { 58 case types.GitRepository: 59 info, err := os.Stat(ident) 60 if err != nil { 61 if errors.Is(err, fs.ErrNotExist) { 62 // If the path does not exist, assume 63 // it is a remote Git repository and, 64 // thus, reachability test is not 65 // supported. 66 return ErrUnsupported 67 } 68 return err 69 } 70 if !info.IsDir() { 71 return fmt.Errorf("not a directory") 72 } 73 case Path: 74 if _, err := os.Stat(ident); err != nil { 75 return err 76 } 77 default: 78 return ErrUnsupported 79 } 80 return nil 81 }