...

Source file src/github.com/containerd/continuity/driver/utils.go

Documentation: github.com/containerd/continuity/driver

     1  /*
     2     Copyright The containerd Authors.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package driver
    18  
    19  import (
    20  	"io"
    21  	"os"
    22  	"sort"
    23  )
    24  
    25  // ReadFile works the same as os.ReadFile with the Driver abstraction
    26  func ReadFile(r Driver, filename string) ([]byte, error) {
    27  	f, err := r.Open(filename)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  	defer f.Close()
    32  
    33  	data, err := io.ReadAll(f)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  
    38  	return data, nil
    39  }
    40  
    41  // WriteFile works the same as os.WriteFile with the Driver abstraction
    42  func WriteFile(r Driver, filename string, data []byte, perm os.FileMode) error {
    43  	f, err := r.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
    44  	if err != nil {
    45  		return err
    46  	}
    47  	defer f.Close()
    48  
    49  	n, err := f.Write(data)
    50  	if err != nil {
    51  		return err
    52  	} else if n != len(data) {
    53  		return io.ErrShortWrite
    54  	}
    55  
    56  	return nil
    57  }
    58  
    59  // ReadDir works the same as os.ReadDir with the Driver abstraction
    60  func ReadDir(r Driver, dirname string) ([]os.FileInfo, error) {
    61  	f, err := r.Open(dirname)
    62  	if err != nil {
    63  		return nil, err
    64  	}
    65  	defer f.Close()
    66  
    67  	dirs, err := f.Readdir(-1)
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  
    72  	sort.Sort(fileInfos(dirs))
    73  	return dirs, nil
    74  }
    75  
    76  // Simple implementation of the sort.Interface for os.FileInfo
    77  type fileInfos []os.FileInfo
    78  
    79  func (fis fileInfos) Len() int {
    80  	return len(fis)
    81  }
    82  
    83  func (fis fileInfos) Less(i, j int) bool {
    84  	return fis[i].Name() < fis[j].Name()
    85  }
    86  
    87  func (fis fileInfos) Swap(i, j int) {
    88  	fis[i], fis[j] = fis[j], fis[i]
    89  }
    90  

View as plain text