...

Source file src/cmd/go/internal/gover/gomod.go

Documentation: cmd/go/internal/gover

     1  // Copyright 2023 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package gover
     6  
     7  import (
     8  	"bytes"
     9  	"strings"
    10  )
    11  
    12  var nl = []byte("\n")
    13  
    14  // GoModLookup takes go.mod or go.work content,
    15  // finds the first line in the file starting with the given key,
    16  // and returns the value associated with that key.
    17  //
    18  // Lookup should only be used with non-factored verbs
    19  // such as "go" and "toolchain", usually to find versions
    20  // or version-like strings.
    21  func GoModLookup(gomod []byte, key string) string {
    22  	for len(gomod) > 0 {
    23  		var line []byte
    24  		line, gomod, _ = bytes.Cut(gomod, nl)
    25  		line = bytes.TrimSpace(line)
    26  		if v, ok := parseKey(line, key); ok {
    27  			return v
    28  		}
    29  	}
    30  	return ""
    31  }
    32  
    33  func parseKey(line []byte, key string) (string, bool) {
    34  	if !strings.HasPrefix(string(line), key) {
    35  		return "", false
    36  	}
    37  	s := strings.TrimPrefix(string(line), key)
    38  	if len(s) == 0 || (s[0] != ' ' && s[0] != '\t') {
    39  		return "", false
    40  	}
    41  	s, _, _ = strings.Cut(s, "//") // strip comments
    42  	return strings.TrimSpace(s), true
    43  }
    44  

View as plain text