github.com/docker/docker@v299999999.0.0-20200612211812-aaf470eca7b5+incompatible/builder/dockerignore/dockerignore.go (about)

     1  package dockerignore // import "github.com/docker/docker/builder/dockerignore"
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"fmt"
     7  	"io"
     8  	"path/filepath"
     9  	"strings"
    10  )
    11  
    12  // ReadAll reads a .dockerignore file and returns the list of file patterns
    13  // to ignore. Note this will trim whitespace from each line as well
    14  // as use GO's "clean" func to get the shortest/cleanest path for each.
    15  func ReadAll(reader io.Reader) ([]string, error) {
    16  	if reader == nil {
    17  		return nil, nil
    18  	}
    19  
    20  	scanner := bufio.NewScanner(reader)
    21  	var excludes []string
    22  	currentLine := 0
    23  
    24  	utf8bom := []byte{0xEF, 0xBB, 0xBF}
    25  	for scanner.Scan() {
    26  		scannedBytes := scanner.Bytes()
    27  		// We trim UTF8 BOM
    28  		if currentLine == 0 {
    29  			scannedBytes = bytes.TrimPrefix(scannedBytes, utf8bom)
    30  		}
    31  		pattern := string(scannedBytes)
    32  		currentLine++
    33  		// Lines starting with # (comments) are ignored before processing
    34  		if strings.HasPrefix(pattern, "#") {
    35  			continue
    36  		}
    37  		pattern = strings.TrimSpace(pattern)
    38  		if pattern == "" {
    39  			continue
    40  		}
    41  		// normalize absolute paths to paths relative to the context
    42  		// (taking care of '!' prefix)
    43  		invert := pattern[0] == '!'
    44  		if invert {
    45  			pattern = strings.TrimSpace(pattern[1:])
    46  		}
    47  		if len(pattern) > 0 {
    48  			pattern = filepath.Clean(pattern)
    49  			pattern = filepath.ToSlash(pattern)
    50  			if len(pattern) > 1 && pattern[0] == '/' {
    51  				pattern = pattern[1:]
    52  			}
    53  		}
    54  		if invert {
    55  			pattern = "!" + pattern
    56  		}
    57  
    58  		excludes = append(excludes, pattern)
    59  	}
    60  	if err := scanner.Err(); err != nil {
    61  		return nil, fmt.Errorf("Error reading .dockerignore: %v", err)
    62  	}
    63  	return excludes, nil
    64  }