oras.land/oras-go/v2@v2.5.1-0.20240520045656-aef90e4d04c4/registry/remote/credentials/internal/ioutil/ioutil.go (about) 1 /* 2 Copyright The ORAS Authors. 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 */ 15 16 package ioutil 17 18 import ( 19 "fmt" 20 "io" 21 "os" 22 ) 23 24 // Ingest writes content into a temporary ingest file with the file name format 25 // "oras_credstore_temp_{randomString}". 26 func Ingest(dir string, content io.Reader) (path string, ingestErr error) { 27 tempFile, err := os.CreateTemp(dir, "oras_credstore_temp_*") 28 if err != nil { 29 return "", fmt.Errorf("failed to create ingest file: %w", err) 30 } 31 path = tempFile.Name() 32 defer func() { 33 if err := tempFile.Close(); err != nil && ingestErr == nil { 34 ingestErr = fmt.Errorf("failed to close ingest file: %w", err) 35 } 36 // remove the temp file in case of error. 37 if ingestErr != nil { 38 os.Remove(path) 39 } 40 }() 41 42 if err := tempFile.Chmod(0600); err != nil { 43 return "", fmt.Errorf("failed to ensure permission: %w", err) 44 } 45 if _, err := io.Copy(tempFile, content); err != nil { 46 return "", fmt.Errorf("failed to ingest: %w", err) 47 } 48 return 49 }