github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/fsutil/builder.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package fsutil 19 20 import ( 21 "errors" 22 "fmt" 23 "io/fs" 24 "os" 25 "path/filepath" 26 "strings" 27 28 "github.com/zntrio/harp/v2/pkg/sdk/fsutil/targzfs" 29 ) 30 31 var ErrNotSupported = errors.New("not supported filesystem path") 32 33 func From(rootPath string) (fs.FS, error) { 34 // Get absolute path 35 absPath, errPath := filepath.Abs(filepath.Clean(rootPath)) 36 if errPath != nil { 37 return nil, fmt.Errorf("unable to get absolute path: %w", errPath) 38 } 39 40 // Check existence 41 fi, errFileInfo := os.Stat(absPath) 42 if errFileInfo != nil { 43 return nil, fmt.Errorf("unabe to retrieve file information: %w", errFileInfo) 44 } 45 46 var ( 47 errRootFS error 48 fileRootFS fs.FS 49 ) 50 switch { 51 case !fi.IsDir() && strings.HasSuffix(absPath, ".tar.gz"): 52 // Create in-memory filesystem. 53 fileRootFS, errRootFS = targzfs.FromFile(os.DirFS(filepath.Dir(absPath)), filepath.Base(absPath)) 54 case fi.IsDir(): 55 fileRootFS = os.DirFS(absPath) 56 default: 57 errRootFS = ErrNotSupported 58 } 59 if errRootFS != nil { 60 return nil, fmt.Errorf("unable to prepare filesystem: %w", errRootFS) 61 } 62 63 // No error 64 return fileRootFS, nil 65 }