github.com/operandinc/gqlgen@v0.16.1/codegen/config/package.go (about)

     1  package config
     2  
     3  import (
     4  	"fmt"
     5  	"go/types"
     6  	"path/filepath"
     7  	"strings"
     8  
     9  	"github.com/operandinc/gqlgen/internal/code"
    10  )
    11  
    12  type PackageConfig struct {
    13  	Filename string `yaml:"filename,omitempty"`
    14  	Package  string `yaml:"package,omitempty"`
    15  }
    16  
    17  func (c *PackageConfig) ImportPath() string {
    18  	if !c.IsDefined() {
    19  		return ""
    20  	}
    21  	return code.ImportPathForDir(c.Dir())
    22  }
    23  
    24  func (c *PackageConfig) Dir() string {
    25  	if !c.IsDefined() {
    26  		return ""
    27  	}
    28  	return filepath.Dir(c.Filename)
    29  }
    30  
    31  func (c *PackageConfig) Pkg() *types.Package {
    32  	if !c.IsDefined() {
    33  		return nil
    34  	}
    35  	return types.NewPackage(c.ImportPath(), c.Package)
    36  }
    37  
    38  func (c *PackageConfig) IsDefined() bool {
    39  	return c.Filename != ""
    40  }
    41  
    42  func (c *PackageConfig) Check() error {
    43  	if strings.ContainsAny(c.Package, "./\\") {
    44  		return fmt.Errorf("package should be the output package name only, do not include the output filename")
    45  	}
    46  	if c.Filename == "" {
    47  		return fmt.Errorf("filename must be specified")
    48  	}
    49  	if !strings.HasSuffix(c.Filename, ".go") {
    50  		return fmt.Errorf("filename should be path to a go source file")
    51  	}
    52  
    53  	c.Filename = abs(c.Filename)
    54  
    55  	// If Package is not set, first attempt to load the package at the output dir. If that fails
    56  	// fallback to just the base dir name of the output filename.
    57  	if c.Package == "" {
    58  		c.Package = code.NameForDir(c.Dir())
    59  	}
    60  
    61  	return nil
    62  }