func GenerateYarnConfig()

in pkg/ar/ar.go [304:380]


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

	projectConfig := filepath.Join(ctx.ApplicationRoot(), yarnConfigName)
	projConfigExists, err := ctx.FileExists(projectConfig)
	if err != nil {
		return nil
	}
	if !projConfigExists {
		// If the developer has not included a project-level .yarnrc.yml,
		// there are no AR repos to set credentials for.
		ctx.Warnf("Skipping adding auth token to %s since %s not found.", userConfig, projectConfig)
		return nil
	}

	content, err := ctx.ReadFile(projectConfig)
	if err != nil {
		return err
	}

	var npmScopes NpmScopes
	err = yaml.Unmarshal(content, &npmScopes)
	if err != nil {
		ctx.Warnf("Skipping adding auth token to %s. Unable to read %s with error %v.", userConfig, projectConfig, err)
		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 yarn install to succeed so we should not fail the build here.
		ctx.Warnf("Skipping adding auth token to %s. Unable to find Application Default Credentials: %v", userConfig, err)
		return nil
	}

	npmRegistriesWithToken := NpmRegistries{
		NpmRegistries: make(map[string]NpmRegistryConfig),
	}

	for _, npmScopeConfig := range npmScopes.NpmScopes {
		if match, err := regexp.MatchString(npmRegistryURLRegexp, npmScopeConfig.NpmRegistryServer); err == nil && match {
			npmRegistriesWithToken.NpmRegistries[npmScopeConfig.NpmRegistryServer] = NpmRegistryConfig{
				NpmAlwaysAuth: npmScopeConfig.NpmAlwaysAuth,
				NpmAuthToken:  tok,
			}
		} else if err != nil {
			return fmt.Errorf("parsing npm registry: %w", err)
		}
	}

	if len(npmRegistriesWithToken.NpmRegistries) < 1 {
		ctx.Warnf("Skipping adding auth token to %s. Unable to find Artifact Registry in %s.", userConfig, projectConfig)
		return nil
	}

	out, err := yaml.Marshal(npmRegistriesWithToken)
	if err != nil {
		return err
	}

	err = ctx.WriteFile(userConfig, []byte(out), 0664)
	if err != nil {
		return err
	}
	// Google Cloud Build service account creds are used to access AR during npm install/yarn add for private packages so reusing metric.
	buildermetrics.GlobalBuilderMetrics().GetCounter(buildermetrics.ArNpmCredsGenCounterID).Increment(1)
	return nil
}