func()

in tool/preprocess/preprocess.go [142:220]


func (dp *DepProcessor) initMod() (err error) {
	// Find compiling module and package information from the build command
	pkgs, err := findModule(dp.goBuildCmd)
	if err != nil {
		return err
	}
	util.Log("Find Go packages %v", util.Jsonify(pkgs))
	for _, pkg := range pkgs {
		util.Log("Find Go package %v", util.Jsonify(pkg))
		if pkg.GoFiles == nil {
			continue
		}
		if pkg.Module != nil {
			// Best case, we find the module information from the package field
			util.Log("Find Go module %v", util.Jsonify(pkg.Module))
			util.Assert(pkg.Module.Path != "", "pkg.Module.Path is empty")
			util.Assert(pkg.Module.GoMod != "", "pkg.Module.GoMod is empty")
			dp.moduleName = pkg.Module.Path
			dp.modulePath = pkg.Module.GoMod
		} else {
			// If we cannot find the module information from the package field,
			// we try to find it from the go.mod file, where go.mod file is in
			// the same directory as the source file.
			util.Assert(pkg.Name != "", "pkg.Name is empty")
			if pkg.Name == "main" {
				gofile := pkg.GoFiles[0]
				gomod, err := findGoMod(filepath.Dir(gofile))
				if err != nil {
					return err
				}
				util.Assert(gomod != "", "gomod is empty")
				util.Assert(util.PathExists(gomod), "gomod does not exist")
				dp.modulePath = gomod
				// Get module name from go.mod file
				modfile, err := parseGoMod(gomod)
				if err != nil {
					return err
				}
				dp.moduleName = modfile.Module.Mod.Path
				// We generate additional source file(otel_importer.go) in the
				// same directory as the go.mod file, we should append this file
				// into build commands to make sure it is compiled together with
				// the original source files.
				found := false
				for _, cmd := range dp.goBuildCmd {
					if strings.Contains(cmd, OtelImporter) {
						found = true
						break
					}
				}
				if !found {
					dp.goBuildCmd = append(dp.goBuildCmd, OtelImporter)
				}
			}
		}
	}
	if dp.moduleName == "" || dp.modulePath == "" {
		return errc.New(errc.ErrPreprocess, "cannot find compiled module")
	}

	util.Log("Found module %v in %v", dp.moduleName, dp.modulePath)

	// We will import alibaba-otel/pkg module in generated code, which is not
	// published yet, so we also need to add a replace directive to the go.mod file
	// to tell the go tool to use the local module cache instead of the remote
	// module, that's why we do this here.
	// TODO: Once we publish the alibaba-otel/pkg module, we can remove this code
	// along with the replace directive in the go.mod file.
	pkgUrl := "github.com/alibaba/opentelemetry-go-auto-instrumentation/pkg@f55e1e8"
	dp.pkgLocalCache, err = dp.findModCacheDir(pkgUrl)
	if err != nil {
		return err
	}
	if dp.pkgLocalCache == "" {
		return errc.New(errc.ErrPreprocess, "cannot find rule cache dir")
	}
	util.Log("Local module cache: %s", dp.pkgLocalCache)
	return nil
}