mirror of
https://github.com/ceph/ceph-csi.git
synced 2025-05-22 07:16:41 +00:00
Many reports are about closing or removing files. In some cases it is possible to report an error in the logs, in other cases the error can be ignored without potential issues. Test cases have been modified to not remove the temporary files. The temporary directory that is provided by the testing package, is removed once the tests are done. Signed-off-by: Niels de Vos <ndevos@ibm.com>
73 lines
2.0 KiB
Go
73 lines
2.0 KiB
Go
/*
|
|
Copyright 2024 The Ceph-CSI Authors.
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
you may not use this file except in compliance with the License.
|
|
You may obtain a copy of the License at
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
See the License for the specific language governing permissions and
|
|
limitations under the License.
|
|
*/
|
|
|
|
package file
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
)
|
|
|
|
// CreateTempFile create a temporary file with the given string
|
|
// content and returns the reference to the file.
|
|
// The caller is responsible for disposing the file.
|
|
func CreateTempFile(prefix, contents string) (*os.File, error) {
|
|
// Create a temp file
|
|
file, err := os.CreateTemp("", prefix)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create temporary file: %w", err)
|
|
}
|
|
|
|
// In case of error, remove the file if it was created
|
|
defer func() {
|
|
if err != nil {
|
|
//nolint:errcheck // temporary file failed to remove, shrug
|
|
_ = os.Remove(file.Name())
|
|
}
|
|
}()
|
|
|
|
// Write the contents
|
|
var c int
|
|
c, err = file.WriteString(contents)
|
|
if err != nil || c != len(contents) {
|
|
return nil, fmt.Errorf("failed to write temporary file: %w", err)
|
|
}
|
|
|
|
// Close the handle
|
|
if err = file.Close(); err != nil {
|
|
return nil, fmt.Errorf("failed to close temporary file: %w", err)
|
|
}
|
|
|
|
return file, nil
|
|
}
|
|
|
|
// CreateSpareFile makes `file` a sparse file of size `sizeMB`.
|
|
func CreateSparseFile(file *os.File, sizeMB int64) error {
|
|
sizeBytes := sizeMB * 1024 * 1024
|
|
|
|
// seek to the end of the file.
|
|
if _, err := file.Seek(sizeBytes-1, 0); err != nil {
|
|
return fmt.Errorf("failed to seek to the end of the file: %w", err)
|
|
}
|
|
|
|
// write a single byte, effectively making it a sparse file.
|
|
if _, err := file.Write([]byte{0}); err != nil {
|
|
return fmt.Errorf("failed to write to the end of the file: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|