Buckets:

download
raw
15 kB
"""Config CLI."""
from __future__ import annotations
import glob
import os
import platform
import re
import subprocess
import typer
from typing_extensions import Annotated
import calkit
from calkit.cli.core import raise_error
config_app = typer.Typer(no_args_is_help=True)
# Registered under the hub CLI group as 'calkit hub config', and below
# as 'calkit config hub' so both spellings work
hub_config_app = typer.Typer(no_args_is_help=True)
config_app.add_typer(
hub_config_app,
name="hub",
help="Work with per-hub credentials (alias for 'calkit hub config').",
)
_HUB_OPTION = typer.Option(
"--hub",
help=(
"URL of the hub, e.g., https://staging.calkit.io. Defaults to "
"the active hub."
),
)
def _select_hub(hub: str | None) -> None:
if hub is None:
return
if hub in ["test", "local", "staging", "production"]:
raise_error("--hub takes a hub URL, e.g., https://staging.calkit.io")
os.environ["CALKIT_HUB"] = hub
def _check_shared_key(key: str) -> None:
from calkit import config
keys = [
k
for k in config.Settings.model_fields
if k not in config.HUB_SCOPED_FIELDS
]
if key in config.HUB_SCOPED_FIELDS:
raise_error(
f"'{key}' is stored per hub; use 'calkit hub config' commands"
)
if key not in keys:
raise_error(f"Invalid config key: '{key}'; Valid keys are: {keys}")
def _check_hub_key(key: str) -> None:
from calkit import config
if key not in config.HUB_SCOPED_FIELDS:
raise_error(
f"'{key}' is not a per-hub credential; valid keys are: "
f"{config.HUB_SCOPED_FIELDS}"
)
def _set_config_value(key: str, value: str) -> None:
from calkit import config
try:
cfg = config.read()
cfg = config.Settings.model_validate(cfg.model_dump() | {key: value})
except Exception as e:
raise_error(f"Failed to set {key} in config: {e}")
cfg.write()
def _get_config_value(key: str) -> None:
from calkit import config
# Attribute access rather than a full dump, so reading one credential
# doesn't ask the keyring for every other one too
val = getattr(config.read(), key)
if val is not None:
print(val)
else:
print()
def _unset_config_value(key: str) -> None:
from calkit import config
try:
cfg = config.read()
setattr(cfg, key, config.Settings.model_fields[key].default)
except Exception as e:
raise_error(f"Failed to unset {key} in config: {e}")
cfg.write()
@config_app.command(name="set")
def set_config_value(key: str, value: str) -> None:
"""Set a value in the config."""
_check_shared_key(key)
_set_config_value(key, value)
@config_app.command(name="get")
def get_config_value(key: str) -> None:
"""Get and print a value from the config."""
_check_shared_key(key)
_get_config_value(key)
@config_app.command(name="unset")
def unset_config_value(key: str) -> None:
"""Unset a value in the config, returning it to default."""
_check_shared_key(key)
_unset_config_value(key)
@hub_config_app.command(name="list")
def list_hub_config_keys() -> None:
"""List per-hub credential keys."""
from calkit import config
for key in config.HUB_SCOPED_FIELDS:
typer.echo(key)
@hub_config_app.command(name="set")
def set_hub_config_value(
key: str,
value: str,
hub: Annotated[str | None, _HUB_OPTION] = None,
) -> None:
"""Set a credential for the active or given hub."""
_select_hub(hub)
_check_hub_key(key)
_set_config_value(key, value)
@hub_config_app.command(name="get")
def get_hub_config_value(
key: str,
hub: Annotated[str | None, _HUB_OPTION] = None,
) -> None:
"""Get and print a credential for the active or given hub."""
_select_hub(hub)
_check_hub_key(key)
_get_config_value(key)
@hub_config_app.command(name="unset")
def unset_hub_config_value(
key: str,
hub: Annotated[str | None, _HUB_OPTION] = None,
) -> None:
"""Unset a credential for the active or given hub."""
_select_hub(hub)
_check_hub_key(key)
_unset_config_value(key)
@config_app.command(name="setup-remote", help="Alias for 'remote'.")
@config_app.command(name="remote")
def setup_remote(
http: Annotated[
bool,
typer.Option(
"--http",
help=(
"Use the legacy HTTP URL for the Calkit DVC remote instead "
"of ck://."
),
),
] = False,
no_commit: Annotated[
bool,
typer.Option(
"--no-commit", help="Do not commit changes to DVC config."
),
] = False,
):
"""Set up the Calkit hub as the default DVC remote and store a token
in the local config.
"""
from git.exc import InvalidGitRepositoryError
from calkit.dvc import configure_remote, set_remote_auth
try:
remote_name = configure_remote(use_ck=not http)
set_remote_auth(remote_name=remote_name)
except subprocess.CalledProcessError:
if not os.path.isfile(".dvc/config"):
raise_error(
"DVC remote config failed; have you run `calkit init`?"
)
raise_error(
"Failed to configure DVC remote; check DVC config for errors"
)
except InvalidGitRepositoryError:
raise_error("Current directory is not a Git repository")
except (ValueError, RuntimeError) as e:
raise_error(f"Failed to set up DVC remote: {e}")
if not no_commit:
repo = calkit.git.get_repo()
repo.git.add(".dvc/config")
if ".dvc/config" in calkit.git.get_staged_files():
typer.echo("Committing changes to DVC config")
repo.git.commit([".dvc/config", "-m", "Set DVC remote"])
@config_app.command(name="setup-remote-auth", help="Alias for 'remote-auth'.")
@config_app.command(name="remote-auth")
def setup_remote_auth():
"""Store a Calkit hub token in the local DVC config for all Calkit
remotes.
"""
from calkit.dvc import get_remotes, set_remote_auth
try:
remotes = get_remotes()
except Exception:
raise_error("Cannot list DVC remotes; check DVC config for errors")
for name, url in remotes.items():
if calkit.dvc.detect_calkit_remote_type(name, url) is not None:
typer.echo(f"Setting up authentication for DVC remote: {name}")
set_remote_auth(remote_name=name)
@config_app.command(name="list")
def list_config_keys():
"""List keys in the config."""
from calkit import config
cfg = config.read()
for key in cfg.model_dump():
if key in config.HUB_SCOPED_FIELDS:
typer.echo(f"{key} (per hub; see 'calkit hub config')")
else:
typer.echo(key)
@config_app.command(name="github-ssh")
def config_github_ssh():
"""Walk through the process of adding an SSH key to GitHub."""
import git
typer.echo("Checking if you can already connect to GitHub via SSH")
# First check if we can already connect to GitHub
ssh_test_cmd = ["ssh", "-T", "git@github.com"]
p = subprocess.run(ssh_test_cmd, capture_output=True, text=True)
if (
"successfully authenticated" in p.stdout
or "successfully authenticated" in p.stderr
):
typer.echo("You can already connect to GitHub via SSH")
go_on = typer.confirm("Do you want to add a new SSH key anyway?")
if not go_on:
raise typer.Exit()
# If we can, ask the user if they still want to add a new key
# First check if the user has any SSH keys
ssh_dir = os.path.expanduser("~/.ssh")
existing_pub_keys = glob.glob(os.path.join(ssh_dir, "*.pub"))
# If not run ssh-keygen
if existing_pub_keys:
# Ask the user if they want to use an existing key or create a new one
typer.echo("Existing SSH public keys found:")
for i, key in enumerate(existing_pub_keys):
typer.echo(f"{i + 1}: {key}")
use_existing = typer.confirm("Do you want to use one of these keys?")
if use_existing:
key_choice = typer.prompt(
"Enter the number of the key to use", type=int
)
if 1 <= key_choice <= len(existing_pub_keys):
key_path = existing_pub_keys[key_choice - 1][:-4]
else:
typer.echo("Invalid choice")
# Keep asking until they give a valid choice
while True:
key_choice = typer.prompt(
"Enter the number of the key to use", type=int
)
if 1 <= key_choice <= len(existing_pub_keys):
key_path = existing_pub_keys[key_choice - 1][:-4]
break
else:
typer.echo("Invalid choice, please try again.")
else:
key_path = typer.prompt(
"Enter the path to save the new SSH key",
default=os.path.join(ssh_dir, "id_ed25519"),
)
else:
typer.echo("No existing SSH keys found")
key_path = typer.prompt(
"Enter the path to save the new SSH key",
default=os.path.join(ssh_dir, "id_ed25519"),
)
# Get the user's email from their Git config, and ask them if they want to
# use that or a different one
try:
user_git_email = git.Git().config("--get", "user.email").strip()
except Exception:
user_git_email = typer.prompt(
"No email found in Git config; enter email for SSH key"
)
git.Git().config("--global", "user.email", user_git_email)
# Do the same for user name even though we don't need it
try:
user_git_name = git.Git().config("--get", "user.name").strip()
except Exception:
user_git_name = typer.prompt(
"No name found in Git config; enter name for SSH key"
)
git.Git().config("--global", "user.name", user_git_name)
keygen_cmd = [
"ssh-keygen",
"-t",
"ed25519",
"-C",
user_git_email,
"-f",
key_path,
]
subprocess.run(keygen_cmd)
# Start the SSH agent in the background
typer.echo("Checking that the SSH agent is running")
# Note that under git bash / MSYS (MSYSTEM is set) we get a POSIX
# ssh-agent on PATH, so we use the POSIX path even on Windows there.
native_windows = platform.system() == "Windows" and not os.environ.get(
"MSYSTEM"
)
if native_windows:
# On native Windows, OpenSSH's ssh-agent runs as a Windows service
# rather than exporting environment variables to the current shell.
# The service ships disabled by default, so ensure it's enabled
# before starting it (enabling requires administrator privileges).
p = subprocess.run(
[
"powershell",
"-NoProfile",
"-Command",
(
"if ((Get-Service ssh-agent).StartType -eq 'Disabled') "
"{ Set-Service ssh-agent -StartupType Manual }; "
"Start-Service ssh-agent"
),
],
capture_output=True,
text=True,
)
if p.returncode != 0:
err = (p.stderr.strip() or p.stdout.strip()).lower()
if "access" in err and "denied" in err:
raise_error(
"Failed to start ssh-agent service: access denied.\n"
"The ssh-agent service is disabled and enabling it "
"requires administrator privileges. Please run the "
"following in an elevated (Run as administrator) "
"PowerShell, then try again:\n\n"
" Set-Service ssh-agent -StartupType Manual; "
"Start-Service ssh-agent"
)
raise_error(
"Failed to start ssh-agent service: "
f"{p.stderr.strip() or p.stdout.strip()}"
)
else:
# On POSIX systems, ssh-agent -s prints shell commands that export
# SSH_AUTH_SOCK and SSH_AGENT_PID; parse them into our environment so
# the subsequent ssh-add call can find the agent
p = subprocess.run(["ssh-agent", "-s"], capture_output=True, text=True)
if p.returncode != 0:
raise_error("Failed to start ssh-agent")
for match in re.finditer(
r"(SSH_AUTH_SOCK|SSH_AGENT_PID)=([^;\n]+);", p.stdout
):
os.environ[match.group(1)] = match.group(2)
# Add the SSH key to the ssh-agent
typer.echo(f"Adding SSH key to ssh-agent: {key_path}")
cmd = ["ssh-add", key_path]
p = subprocess.run(cmd)
if p.returncode != 0:
raise_error("Failed to add SSH key to ssh-agent; please try again")
# Now add to GitHub
gh_ssh_url = "https://github.com/settings/ssh/new"
typer.echo(
"Add the new SSH key to your GitHub account by visiting:\n"
f"{gh_ssh_url}"
)
with open(key_path + ".pub", "r") as f:
pub_key = f.read()
typer.echo(f"Paste this into the public key field:\n\n{pub_key}\n")
typer.confirm("Press Enter when done", default=True)
typer.echo("Testing SSH connection to GitHub")
p = subprocess.run(ssh_test_cmd, capture_output=True, text=True)
if "successfully authenticated" in p.stderr:
typer.echo("Successfully connected to GitHub via SSH!")
else:
raise_error(
"Failed to connect to GitHub via SSH; please check your setup"
)
@config_app.command(name="github-codespace")
def config_github_codespace():
"""Configure a GitHub Codespace.
Typically this will simply mean we exchange a GitHub token for a Calkit
token to use for pushing with DVC.
If this is run outside a Codespace, typically nothing will happen.
"""
is_codespace = os.getenv("GITHUB_CODESPACE_TOKEN")
if not is_codespace:
typer.echo("Not running in compatible Codespace; exiting")
raise typer.Exit()
github_token = os.getenv("GITHUB_TOKEN")
if not github_token:
typer.echo("No GitHub token found; exiting")
raise typer.Exit()
try:
resp = calkit.hub.post(
"/login/github-token",
headers={"Authorization": f"Bearer {github_token}"},
auth=False,
)
calkit_token = resp["access_token"]
typer.echo("Successfully authenticated with the Calkit API")
set_config_value("token", calkit_token)
# TODO: We should just fetch short-lived DVC tokens with the main
# Calkit API token if necessary, instead of creating long-lived ones
set_config_value("dvc_token", calkit_token)
except Exception as e:
raise_error(f"Failed to authenticate with GitHub token: {e}")

Xet Storage Details

Size:
15 kB
·
Xet hash:
1e5fee5e4b5f3c5f2e96f9073f46a15579cd8c79d4de4a51d4419eb4325dac26

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.