github.com/blend/go-sdk@v1.20220411.3/codeowners/parse_source.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package codeowners
     9  
    10  import (
    11  	"bufio"
    12  	"fmt"
    13  	"os"
    14  	"path/filepath"
    15  	"strings"
    16  )
    17  
    18  // ParseSource parses a source from a given path.
    19  func ParseSource(repoRoot, sourcePath string) (*Source, error) {
    20  	f, err := os.Open(sourcePath)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  	defer f.Close()
    25  	scanner := bufio.NewScanner(f)
    26  
    27  	repoSourcePath, err := MakeRepositoryAbsolute(repoRoot, sourcePath)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  	output := Source{
    32  		Source: repoSourcePath,
    33  	}
    34  
    35  	var line string
    36  	for scanner.Scan() {
    37  		line = strings.TrimSpace(scanner.Text())
    38  		if strings.HasPrefix(strings.TrimSpace(line), "#") { // ignore comments
    39  			continue
    40  		}
    41  		if strings.Contains(line, "#") {
    42  			return nil, fmt.Errorf("invalid codeowners file; must not contain inline comments")
    43  		}
    44  		if strings.TrimSpace(line) == "" {
    45  			continue
    46  		}
    47  		pieces := strings.Fields(line)
    48  		if len(pieces) < 2 {
    49  			return nil, fmt.Errorf("invalid codeowners file; must contain a path glob and an owner on a single line")
    50  		}
    51  		pathGlob, err := MakeRepositoryAbsolute(repoRoot, filepath.Join(filepath.Dir(sourcePath), pieces[0]))
    52  		if err != nil {
    53  			return nil, err
    54  		}
    55  		output.Paths = append(output.Paths, Path{
    56  			PathGlob: pathGlob,
    57  			Owners:   pieces[1:],
    58  		})
    59  	}
    60  	return &output, nil
    61  }