switchupcb / copygen

Go generator to copy values from type to type and fields from struct to struct (copier without reflection). Generate any code based on types.
https://switchupcb.com/copygen-license-exception/
GNU General Public License v3.0
349 stars 22 forks source link

Parser: Output File doesn't resolve imports when Setup File Package is an Output File Package Import #23

Closed switchupcb closed 2 years ago

switchupcb commented 2 years ago

Problem

Copygen assumes that the user outputs to a package that does not contain imports in the setup file. As a result, using the following example results in invalid output.

// Package requests contains the setup information for copygen generated code.
package requests

import (
    "github.com/switchupcb/disgo/wrapper/requests" // setup file imports package it will output to
    "github.com/switchupcb/disgo/wrapper/requests/responses"
    "github.com/switchupcb/disgo/wrapper/resources"
)

// Copygen defines the functions that will be generated.
type Copygen interface {
        // setup file uses package for field, but in the output this package isn't necessary
    SendGetGlobalApplicationCommands(*requests.GetGlobalApplicationCommands) ([]*resources.ApplicationCommand, error)
}

Fix

Allow the user to do this (extreme edge case) by modifying the field's package - at some point in the parser - based on the setup file's imports. We already substitute package names with aliases so we only have to modify how the aliasImportMap is handled. Basically this issue is solved by detecting when an import uses a package that the setup file is in, then not assigning packages to the field's of the objects defined in the setup file AND the same package-import.

switchupcb commented 2 years ago

In addition, we can add a method to add imports to files for custom generation.