Repository: helm/helm (go)

Issue:
helm template inconsistently respects the --namespace option in different environments
## Expected behavior:
When running `helm template` with the `--namespace` argument, it should set the `.Release.Namespace` variable, and any templates using that variable should be set to the value of the `--namespace` argument.

## Actual behavior:
It is inconsistent about setting the `.Release.Namespace` variable. On my and my coworker's laptops, it works as expected. In our CI, it doesn't set it to the value of the `--namespace` argument, but instead just defaults to `default`.

It works on our laptops with or without docker, but in CI it doesn't. The same versions of `helm` and `kubectl` are used on my laptop and in CI. The inconsistency persists even when running locally in the same Docker image used by CI (so the python versions are also the same).

We've looked very hard for differences in our environments, and can find none, which leaves me to suspect helm itself is inconsistent.

## Additional context:
Specifically, we're attempting to template the aws-ebs-csi-driver chart, version 2.19.0, from https://kubernetes-sigs.github.io/aws-ebs-csi-driver .

We're calling `helm template` in a python script pointing at a locally vendored copy of the chart. Values are passed to stdin.
```python3
values = {
    "controller": {
        "serviceAccount": {
            "create": True,
        },
        "nodeSelector": {
            "workload": "mz-system",
        },
    },
    "node": {
        "affinity": {
            "nodeAffinity": {
                "requiredDuringSchedulingIgnoredDuringExecution": {
                    "nodeSelectorTerms": [
                        {
                            "matchExpressions": [
                                {
                                    "key": "eks.amazonaws.com/compute-type",
                                    "operator": "NotIn",
                                    "values": ["fargate"],
                                },
                                {
                                    "key": "workload",
                                    "operator": "NotIn",
                                    "values": ["materialize-egress"],
                                },
                            ],
                        },
                    ],
                },
            },
        },
    },
}

args = [
    "helm",
    "template",
    "aws-ebs-csi-driver",
    "infra/helm/vendor/charts/aws-ebs-csi-driver/2.19.0",
    "-f",
    "-",
    "--namespace",
    "kube-system",
]

rendered_text = subprocess.run(
    args,
    input=yaml.safe_dump(values),
    check=True,
    text=True,
    capture_output=True,
).stdout
```

An example template in the chart which is rendered differently in CI vs locally (the namespace is `kube-system` locally, but in CI is rendered to `default`):
```yaml
{{- if .Values.controller.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ .Values.controller.serviceAccount.name }}
  namespace: {{ .Release.Namespace }}
  labels:
    {{- include "aws-ebs-csi-driver.labels" . | nindent 4 }}
  {{- with .Values.controller.serviceAccount.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
  {{- if eq .Release.Name "kustomize" }}
  #Enable if EKS IAM roles for service accounts (IRSA) is used. See https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html for details.
  #annotations:
  #  eks.amazonaws.com/role-arn: arn:<partition>:iam::<account>:role/ebs-csi-role
  {{- end }}
{{- end -}}
```

### Output of `helm version`:
```
version.BuildInfo{Version:"v3.12.0", GitCommit:"c9f554d75773799f72ceef38c51210f1842a1dea", GitTreeState:"clean", GoVersion:"go1.20.3"}
```

### Output of `kubectl version`:
```
Client Version: version.Info{Major:"1", Minor:"25", GitVersion:"v1.25.9", GitCommit:"a1a87a0a2bcd605820920c6b0e618a8ab7d117d4", GitTreeState:"clean", BuildDate:"2023-04-12T12:16:51Z", GoVersion:"go1.19.8", Compiler:"gc", Platform:"linux/amd64"}
```
Server version is not relevant to `helm template`.

### Cloud Provider/Platform (AKS, GKE, Minikube etc.): 
N/A, but our CI is running in Github Actions and we're running `helm template` in a Docker container.



Pull request description:
12124: Fix namespace on kubeconfig error
<!--  Thanks for sending a pull request!  Here are some tips for you:
1. Make sure to read the Contributing Guide before submitting your PR: https://github.com/helm/helm/blob/main/CONTRIBUTING.md
2. If this PR closes another issue, add 'closes #<issue number>' somewhere in the PR summary. GitHub will automatically close that issue when this PR gets merged. Alternatively, adding 'refs #<issue number>' will not close the issue, but help provide the reviewer more context.-->

**What this PR does / why we need it**:

Closes #12124 

When the kubeconfig is missing or invalid, the namespace defaults to default instead of the correct namespace. Ensure that on error reading the config, the correct namespace is still returned.

**Special notes for your reviewer**:

Copies https://github.com/helm/helm/pull/12126 but adds a unit test.

**If applicable**:
- [ ] this PR contains documentation
- [x] this PR contains unit tests
- [ ] this PR has been tested for backwards compatibility


Patch:
diff --git a/pkg/cli/environment.go b/pkg/cli/environment.go
index 721b840ab..ba103252d 100644
--- a/pkg/cli/environment.go
+++ b/pkg/cli/environment.go
@@ -244,6 +244,9 @@ func (s *EnvSettings) Namespace() string {
 	if ns, _, err := s.config.ToRawKubeConfigLoader().Namespace(); err == nil {
 		return ns
 	}
+	if s.namespace != "" {
+		return s.namespace
+	}
 	return "default"
 }
 


Test patch:
diff --git a/pkg/cli/environment_test.go b/pkg/cli/environment_test.go
index 1692a89d5..f7709045c 100644
--- a/pkg/cli/environment_test.go
+++ b/pkg/cli/environment_test.go
@@ -111,6 +111,14 @@ func TestEnvSettings(t *testing.T) {
 			kubeTLSServer: "example.org",
 			kubeInsecure:  true,
 		},
+		{
+			name:       "invalid kubeconfig",
+			ns:         "testns",
+			args:       "--namespace=testns --kubeconfig=/path/to/fake/file",
+			maxhistory: defaultMaxHistory,
+			burstLimit: defaultBurstLimit,
+			qps:        defaultQPS,
+		},
 	}
 
 	for _, tt := range tests {