golang.org/x/tools@v0.21.1-0.20240520172518-788d39e776b1/go/internal/cgo/cgo_pkgconfig.go (about) 1 // Copyright 2013 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 cgo 6 7 import ( 8 "errors" 9 "fmt" 10 "go/build" 11 "os/exec" 12 "strings" 13 ) 14 15 // pkgConfig runs pkg-config with the specified arguments and returns the flags it prints. 16 func pkgConfig(mode string, pkgs []string) (flags []string, err error) { 17 cmd := exec.Command("pkg-config", append([]string{mode}, pkgs...)...) 18 out, err := cmd.Output() 19 if err != nil { 20 s := fmt.Sprintf("%s failed: %v", strings.Join(cmd.Args, " "), err) 21 if len(out) > 0 { 22 s = fmt.Sprintf("%s: %s", s, out) 23 } 24 if err, ok := err.(*exec.ExitError); ok && len(err.Stderr) > 0 { 25 s = fmt.Sprintf("%s\nstderr:\n%s", s, err.Stderr) 26 } 27 return nil, errors.New(s) 28 } 29 if len(out) > 0 { 30 flags = strings.Fields(string(out)) 31 } 32 return 33 } 34 35 // pkgConfigFlags calls pkg-config if needed and returns the cflags 36 // needed to build the package. 37 func pkgConfigFlags(p *build.Package) (cflags []string, err error) { 38 if len(p.CgoPkgConfig) == 0 { 39 return nil, nil 40 } 41 return pkgConfig("--cflags", p.CgoPkgConfig) 42 }