github.com/uber/kraken@v0.1.4/utils/osutil/osutil.go (about)

     1  // Copyright (c) 2016-2019 Uber Technologies, Inc.
     2  //
     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  package osutil
    15  
    16  import (
    17  	"bufio"
    18  	"fmt"
    19  	"io"
    20  	"os"
    21  	"path"
    22  )
    23  
    24  // IsEmpty returns true if directory dir is empty.
    25  func IsEmpty(dir string) (bool, error) {
    26  	f, err := os.Open(dir)
    27  	if err != nil {
    28  		return false, err
    29  	}
    30  	defer f.Close()
    31  
    32  	_, err = f.Readdirnames(1)
    33  	if err == io.EOF {
    34  		return true, nil
    35  	}
    36  	return false, err
    37  }
    38  
    39  // ReadLines returns a list of lines in filename.
    40  func ReadLines(f *os.File) ([]string, error) {
    41  	var lines []string
    42  	s := bufio.NewScanner(f)
    43  	s.Split(bufio.ScanLines)
    44  	for s.Scan() {
    45  		l := s.Text()
    46  		lines = append(lines, l)
    47  	}
    48  	return lines, nil
    49  }
    50  
    51  // EnsureFilePresent initializes a file and all parent directories for filepath
    52  // if they do not exist. If the file exists, no-ops.
    53  func EnsureFilePresent(filepath string, perm os.FileMode) error {
    54  	if _, err := os.Stat(filepath); os.IsNotExist(err) {
    55  		err := os.MkdirAll(path.Dir(filepath), perm)
    56  		if err != nil {
    57  			return fmt.Errorf("mkdir: %s", err)
    58  		}
    59  		f, err := os.Create(filepath)
    60  		if err != nil {
    61  			return fmt.Errorf("create: %s", err)
    62  		}
    63  		f.Close()
    64  	} else if err != nil {
    65  		return fmt.Errorf("stat: %s", err)
    66  	}
    67  	return nil
    68  }