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