goda icon indicating copy to clipboard operation
goda copied to clipboard

Allow to use the package as library

Open dcu opened this issue 2 years ago • 3 comments

there are some cases where using as library would be preferable than using as cli

is there a reason to not allow it? thanks

dcu avatar Jun 29 '23 21:06 dcu

Mostly, I don't want to put the effort into a stable API. I could provide an unstable one.

Is there a concrete problem you are finding difficult to solve? I'm mostly interested in which parts of the system you are interested in being exposed.

Sometimes using golang.org/x/tools/go/packages directly might be more easier.

egonelbre avatar Jul 03 '23 08:07 egonelbre

I would use pkgset.Calc to find all dependencies of a package

dcu avatar Jul 03 '23 19:07 dcu

If you just want all the packages, then this would be sufficient:

package main

import (
	"golang.org/x/tools/go/packages"
)

func Dependencies(pkgs ...string) (map[string]*packages.Package, error) {
	roots, err := packages.Load(&packages.Config{
		Mode: packages.NeedName | packages.NeedImports,
		// Tests: true, // if you need tests
	}, pkgs...)
	if err != nil {
		return nil, fmt.Errorf("failed to load packages %v: %w", pkgs, err)
	}

	r := map[string]*packages.Package{}
	include(r, roots)
	return r, nil
}

func include(r map[string]*packages.Package, pkgs []*packages.Package) {
	for _, pkg := range pkgs {
		if _, added := r[pkg.ID]; added {
			continue
		}
		r[pkg.ID] = pkg
		include(r, pkg.Imports)
	}
}

egonelbre avatar Jul 03 '23 19:07 egonelbre