func GenerateNPMConfig()

in pkg/ar/ar.go [196:252]


func GenerateNPMConfig(ctx *gcp.Context) error {
	userConfig := filepath.Join(ctx.HomeDir(), npmConfigName)
	userConfigExists, err := ctx.FileExists(userConfig)
	if err != nil {
		return err
	}
	if userConfigExists {
		ctx.Debugf("Found an existing user-level .npmrc file. Skipping .npmrc creation.")
		return nil
	}

	projectConfig := filepath.Join(ctx.ApplicationRoot(), npmConfigName)
	projConfigExists, err := ctx.FileExists(projectConfig)
	if err != nil {
		return nil
	}
	if !projConfigExists {
		// Unlike Python, NPM credentials must be configured per repo. If the devoloper has not included
		// a project-level npmrc, there are no AR repos to set credentials for, so there is nothing
		// more to do.
		return nil
	}
	content, err := ctx.ReadFile(projectConfig)
	if err != nil {
		return err
	}

	matches := npmRegistryRegexp.FindAllStringSubmatch(string(content), -1)
	var repos []string

	for _, m := range matches {
		repos = append(repos, m[2])
	}

	if len(repos) < 1 {
		return nil
	}

	tok, err := findDefaultCredentials()
	if err != nil {
		// findDefaultCredentials will return an error any time Application Default Credentials are
		// missing (e.g. running the buildpacks locally outside of GCB). Credentials might not
		// be required for the npm install to succeed so we should not fail the build here.
		ctx.Warnf("Skipping .npmrc creation. Unable to find Application Default Credentials: %v", err)
		return nil
	}

	ctx.Debugf("Configuring NPM credentials for: %s", strings.Join(repos, ", "))

	f, err := ctx.CreateFile(userConfig)
	if err != nil {
		return err
	}
	defer f.Close()

	return writeNpmConfig(f, repos, tok)
}