Skip to content

Commit ed358cb

Browse files
fix: allow the api key to be re-inserted after logout clear to credentials.ini file
1 parent 8eb838b commit ed358cb

2 files changed

Lines changed: 36 additions & 3 deletions

File tree

cloudsmith_cli/cli/config.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -222,19 +222,30 @@ def find_existing_files(cls):
222222
return paths
223223

224224
@classmethod
225-
def clear_api_key(cls, path):
226-
"""Clear api_key values in a credentials file, preserving structure."""
225+
def _set_api_key(cls, path, api_key=""):
226+
"""Write api_key value in a credentials file, preserving structure."""
227227
with open(path) as f:
228228
content = f.read()
229+
replacement = rf"\1 = {api_key}" if api_key else r"\1 ="
229230
content = re.sub(
230231
r"^(api_key)\s*=\s*.*$",
231-
r"\1 =",
232+
replacement,
232233
content,
233234
flags=re.MULTILINE,
234235
)
235236
with open(path, "w") as f:
236237
f.write(content)
237238

239+
@classmethod
240+
def clear_api_key(cls, path):
241+
"""Clear api_key values in a credentials file, preserving structure."""
242+
cls._set_api_key(path)
243+
244+
@classmethod
245+
def update_api_key(cls, path, api_key):
246+
"""Update api_key value in an existing credentials file, preserving structure."""
247+
cls._set_api_key(path, api_key)
248+
238249

239250
class Options:
240251
"""Options object that holds config for the application."""

cloudsmith_cli/core/config.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,28 @@ def create_config_files(ctx, opts, api_key, force=False):
8383
)
8484
continue
8585

86+
# Update existing credentials file with new API key if provided
87+
if (
88+
config.present
89+
and config.data.get("api_key")
90+
and hasattr(config.reader, "update_api_key")
91+
):
92+
try:
93+
config.reader.update_api_key(
94+
config.reader.get_default_filepath(),
95+
config.data["api_key"],
96+
)
97+
click.secho("UPDATED", fg="green")
98+
except OSError as exc:
99+
has_errors = True
100+
click.secho("ERROR", fg="red")
101+
click.secho(
102+
"The following error occurred while trying to "
103+
"update the file: %(message)s"
104+
% {"message": click.style(exc.strerror, fg="red")}
105+
)
106+
continue
107+
86108
click.secho("EXISTS" if config.present else "NOT CREATED", fg="yellow")
87109

88110
return create, has_errors

0 commit comments

Comments
 (0)