func addNamespaceToManifests()

in internal/generators/helm.go [35:87]


func addNamespaceToManifests(manifests, namespace string) chan namespaceInjectionResponse {
	respChan := make(chan namespaceInjectionResponse)
	syncGroup := sync.WaitGroup{}
	splitManifest := strings.Split(manifests, "\n---")

	// Wait for all manifests to be iterated over then close the channel
	syncGroup.Add(len(splitManifest))
	go func() {
		syncGroup.Wait()
		close(respChan)
	}()

	// Iterate over all manifests, decrementing the wait group for every channel put
	for index, manifest := range splitManifest {
		go func(index int, manifest string) {
			parsedManifest := make(map[interface{}]interface{})

			// Push a warning if unable to unmarshal
			if err := yaml.Unmarshal([]byte(manifest), &parsedManifest); err != nil {
				warning := emoji.Sprintf(":question: Unable to unmarshal manifest into type '%s', this is most likely a warning message outputted from `helm template`. Skipping namespace injection of '%s' into manifest: '%s'", reflect.TypeOf(parsedManifest), namespace, manifest)
				respChan <- namespaceInjectionResponse{warn: &warning}
				syncGroup.Done()
				return
			}

			// strip any empty entries
			if len(parsedManifest) == 0 {
				syncGroup.Done()
				return
			}

			// Inject the namespace
			if parsedManifest["metadata"] != nil {
				metadataMap := parsedManifest["metadata"].(map[interface{}]interface{})
				if metadataMap["namespace"] == nil {
					metadataMap["namespace"] = namespace
				}
			}

			// Marshal updated manifest and put the response on channel
			updatedManifest, err := yaml.Marshal(&parsedManifest)
			if err != nil {
				respChan <- namespaceInjectionResponse{err: err}
				syncGroup.Done()
				return
			}
			respChan <- namespaceInjectionResponse{index: index, namespacedManifest: &updatedManifest}
			syncGroup.Done()
		}(index, manifest)
	}

	return respChan
}