Skip to content

FileRestorer Package Alias does not work for std library packages #82

@thesilentg

Description

@thesilentg

I'm trying to use dst with import management, but this doesn't appear to work correctly when aliases are necessary for packages in the standard library. This can be necessary in the case where existing identifiers are already using the default name for a package. Example below:

Example input

package scope

import "fmt"

func myfunc2() {
    context := 5
    fmt.Println(context)
}

Desired output

package scope

import (
    "fmt"
    context1 "context"
)

func myfunc2() {
    context := 5
    fmt.Println(context)
    client{}.DoWithContext(context1.TODO())
}

The exact example shown is a bit contrived, but the core situation can be generalized. Here, the existing context variable means that trying to import the context package without an alias will fail. To get around this, I'm doing this to create an identifier with a non-standard path for the context package import.

	ident := dst.NewIdent("TODO")
	ident.Path = "context1"
	return &dst.CallExpr{
		Fun: ident,
	}

and then using a gopackages FileRestorer like this to map this non-standard path back in the import block.

	pkgs, err := decorator.Load(cfg, packagesToCheck...)
        ...
        restorer := decorator.NewRestorerWithImports(fullPath, gopackages.New(fullPath))
        ...
        fr := restorer.FileRestorer()
	fr.Alias = map[string]string{"context": "context1"}
        ...
        // Eventually
        fr.Fprint(outputBuffer, astNode.(*dst.File))

This should hopefully allow dst to manage the import block. However, it actually returns the following error: package context1 is not in std.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions