github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/builder/dockerignore/dockerignore.go (about)

     1  package 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  		pattern = filepath.Clean(pattern)
    42  		pattern = filepath.ToSlash(pattern)
    43  		excludes = append(excludes, pattern)
    44  	}
    45  	if err := scanner.Err(); err != nil {
    46  		return nil, fmt.Errorf("Error reading .dockerignore: %v", err)
    47  	}
    48  	return excludes, nil
    49  }