← back to keywaysh__cli

Function bodies 191 total

All specs Real LLM only Function bodies
api.Client.PushSecrets method · go · L25-L37 (13 LOC)
internal/api/secrets.go
func (c *Client) PushSecrets(ctx context.Context, repo, env string, secrets map[string]string) (*PushSecretsResponse, error) {
	body := map[string]interface{}{
		"repoFullName": repo,
		"environment":  env,
		"secrets":      secrets,
	}

	var wrapper struct {
		Data PushSecretsResponse `json:"data"`
	}
	err := c.do(ctx, "POST", "/v1/secrets/push", body, &wrapper)
	return &wrapper.Data, err
}
api.Client.PullSecrets method · go · L40-L50 (11 LOC)
internal/api/secrets.go
func (c *Client) PullSecrets(ctx context.Context, repo, env string) (*PullSecretsResponse, error) {
	params := url.Values{}
	params.Set("repo", repo)
	params.Set("environment", env)

	var wrapper struct {
		Data PullSecretsResponse `json:"data"`
	}
	err := c.do(ctx, "GET", "/v1/secrets/pull?"+params.Encode(), nil, &wrapper)
	return &wrapper.Data, err
}
api.Client.InitVault method · go · L30-L40 (11 LOC)
internal/api/vaults.go
func (c *Client) InitVault(ctx context.Context, repoFullName string) (*InitVaultResponse, error) {
	body := map[string]string{
		"repoFullName": repoFullName,
	}

	var wrapper struct {
		Data InitVaultResponse `json:"data"`
	}
	err := c.do(ctx, "POST", "/v1/vaults", body, &wrapper)
	return &wrapper.Data, err
}
api.Client.GetVaultDetails method · go · L43-L60 (18 LOC)
internal/api/vaults.go
func (c *Client) GetVaultDetails(ctx context.Context, repoFullName string) (*VaultDetails, error) {
	owner, repo := splitRepo(repoFullName)
	if owner == "" || repo == "" {
		return nil, fmt.Errorf("invalid repository format: %s", repoFullName)
	}

	path := fmt.Sprintf("/v1/vaults/%s/%s", owner, repo)
	var wrapper struct {
		Data VaultDetails `json:"data"`
	}

	err := c.do(ctx, "GET", path, nil, &wrapper)
	if err != nil {
		return nil, err
	}

	return &wrapper.Data, nil
}
api.Client.CheckVaultExists method · go · L63-L78 (16 LOC)
internal/api/vaults.go
func (c *Client) CheckVaultExists(ctx context.Context, repoFullName string) (bool, error) {
	owner, repo := splitRepo(repoFullName)
	if owner == "" || repo == "" {
		return false, fmt.Errorf("invalid repository format: %s", repoFullName)
	}

	path := fmt.Sprintf("/v1/vaults/%s/%s", owner, repo)
	err := c.do(ctx, "GET", path, nil, nil)
	if err != nil {
		if apiErr, ok := err.(*APIError); ok && apiErr.StatusCode == 404 {
			return false, nil
		}
		return false, err
	}
	return true, nil
}
api.Client.GetVaultEnvironments method · go · L81-L103 (23 LOC)
internal/api/vaults.go
func (c *Client) GetVaultEnvironments(ctx context.Context, repoFullName string) ([]string, error) {
	owner, repo := splitRepo(repoFullName)
	if owner == "" || repo == "" {
		return []string{"production"}, nil
	}

	path := fmt.Sprintf("/v1/vaults/%s/%s", owner, repo)
	var wrapper struct {
		Data struct {
			Environments []string `json:"environments"`
		} `json:"data"`
	}

	err := c.do(ctx, "GET", path, nil, &wrapper)
	if err != nil {
		return []string{"production"}, nil
	}

	if len(wrapper.Data.Environments) == 0 {
		return []string{"production"}, nil
	}
	return wrapper.Data.Environments, nil
}
api.splitRepo function · go · L106-L113 (8 LOC)
internal/api/vaults.go
func splitRepo(repoFullName string) (string, string) {
	for i, c := range repoFullName {
		if c == '/' {
			return repoFullName[:i], repoFullName[i+1:]
		}
	}
	return "", ""
}
Repobility — same analyzer, your code, free for public repos · /scan/
auth.NewStore function · go · L33-L51 (19 LOC)
internal/auth/store.go
func NewStore() *Store {
	homeDir, _ := os.UserHomeDir()

	// Match Node.js conf package paths for compatibility
	var configDir string
	switch runtime.GOOS {
	case "darwin":
		configDir = filepath.Join(homeDir, "Library", "Preferences", "keyway-nodejs")
	case "windows":
		configDir = filepath.Join(os.Getenv("APPDATA"), "keyway-nodejs", "Config")
	default: // linux and others
		configDir = filepath.Join(homeDir, ".config", "keyway-nodejs")
	}

	return &Store{
		configPath: filepath.Join(configDir, "config.json"),
		keyPath:    filepath.Join(homeDir, ".keyway", ".key"),
	}
}
auth.Store.GetAuth method · go · L54-L97 (44 LOC)
internal/auth/store.go
func (s *Store) GetAuth() (*StoredAuth, error) {
	// Read config file
	data, err := os.ReadFile(s.configPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		}
		return nil, err
	}

	var config map[string]string
	if err := json.Unmarshal(data, &config); err != nil {
		return nil, err
	}

	encryptedAuth, ok := config["auth"]
	if !ok || encryptedAuth == "" {
		return nil, nil
	}

	// Decrypt
	decrypted, err := s.decrypt(encryptedAuth)
	if err != nil {
		// Corrupted data, clear it
		_ = s.ClearAuth()
		return nil, nil
	}

	var auth StoredAuth
	if err := json.Unmarshal([]byte(decrypted), &auth); err != nil {
		return nil, err
	}

	// Check expiration
	if auth.ExpiresAt != "" {
		expires, err := time.Parse(time.RFC3339, auth.ExpiresAt)
		if err == nil && time.Now().After(expires) {
			_ = s.ClearAuth()
			return nil, nil
		}
	}

	return &auth, nil
}
auth.Store.SaveAuth method · go · L100-L130 (31 LOC)
internal/auth/store.go
func (s *Store) SaveAuth(token, githubLogin, expiresAt string) error {
	auth := StoredAuth{
		KeywayToken: token,
		GitHubLogin: githubLogin,
		ExpiresAt:   expiresAt,
		CreatedAt:   time.Now().UTC().Format(time.RFC3339),
	}

	authJSON, err := json.Marshal(auth)
	if err != nil {
		return err
	}

	encrypted, err := s.encrypt(string(authJSON))
	if err != nil {
		return err
	}

	// Ensure directory exists
	if err := os.MkdirAll(filepath.Dir(s.configPath), 0700); err != nil {
		return err
	}

	config := map[string]string{"auth": encrypted}
	data, err := json.MarshalIndent(config, "", "  ")
	if err != nil {
		return err
	}

	return os.WriteFile(s.configPath, data, 0600)
}
auth.Store.ClearAuth method · go · L133-L141 (9 LOC)
internal/auth/store.go
func (s *Store) ClearAuth() error {
	if _, err := os.Stat(s.configPath); os.IsNotExist(err) {
		return nil
	}

	config := map[string]string{}
	data, _ := json.MarshalIndent(config, "", "  ")
	return os.WriteFile(s.configPath, data, 0600)
}
auth.Store.getOrCreateKey method · go · L149-L173 (25 LOC)
internal/auth/store.go
func (s *Store) getOrCreateKey() ([]byte, error) {
	// Try to read existing key
	keyHex, err := os.ReadFile(s.keyPath)
	if err == nil && len(strings.TrimSpace(string(keyHex))) == 64 {
		return hex.DecodeString(strings.TrimSpace(string(keyHex)))
	}

	// Generate new key (32 bytes = 256 bits)
	key := make([]byte, 32)
	if _, err := rand.Read(key); err != nil {
		return nil, fmt.Errorf("failed to generate key: %w", err)
	}

	// Ensure directory exists
	if err := os.MkdirAll(filepath.Dir(s.keyPath), 0700); err != nil {
		return nil, err
	}

	// Save key
	if err := os.WriteFile(s.keyPath, []byte(hex.EncodeToString(key)), 0600); err != nil {
		return nil, err
	}

	return key, nil
}
auth.Store.encrypt method · go · L177-L213 (37 LOC)
internal/auth/store.go
func (s *Store) encrypt(plaintext string) (string, error) {
	key, err := s.getOrCreateKey()
	if err != nil {
		return "", err
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return "", err
	}

	// Generate random IV
	iv := make([]byte, gcm.NonceSize())
	if _, err := rand.Read(iv); err != nil {
		return "", err
	}

	// Encrypt
	ciphertext := gcm.Seal(nil, iv, []byte(plaintext), nil)

	// GCM appends auth tag to ciphertext, we need to split it
	// for compatibility with Node.js format
	tagSize := gcm.Overhead()
	authTag := ciphertext[len(ciphertext)-tagSize:]
	encrypted := ciphertext[:len(ciphertext)-tagSize]

	return fmt.Sprintf("%s:%s:%s",
		hex.EncodeToString(iv),
		hex.EncodeToString(authTag),
		hex.EncodeToString(encrypted),
	), nil
}
auth.Store.decrypt method · go · L217-L267 (51 LOC)
internal/auth/store.go
func (s *Store) decrypt(data string) (string, error) {
	parts := strings.Split(data, ":")
	if len(parts) != 3 {
		return "", fmt.Errorf("invalid encrypted data format")
	}

	iv, err := hex.DecodeString(parts[0])
	if err != nil {
		return "", fmt.Errorf("invalid IV: %w", err)
	}

	authTag, err := hex.DecodeString(parts[1])
	if err != nil {
		return "", fmt.Errorf("invalid auth tag: %w", err)
	}

	encrypted, err := hex.DecodeString(parts[2])
	if err != nil {
		return "", fmt.Errorf("invalid ciphertext: %w", err)
	}

	key, err := s.getOrCreateKey()
	if err != nil {
		return "", err
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return "", err
	}

	// Validate IV length to prevent panic
	if len(iv) != gcm.NonceSize() {
		return "", fmt.Errorf("invalid IV length: got %d, expected %d", len(iv), gcm.NonceSize())
	}

	// Reconstruct ciphertext with auth tag (GCM expects tag at end)
	ciphertext := append(encrypted
cmd.handleAuthError function · go · L12-L40 (29 LOC)
internal/cmd/auth_error.go
func handleAuthError(err error, deps *Dependencies) (string, error) {
	apiErr, ok := err.(*api.APIError)
	if !ok || apiErr.StatusCode != 401 {
		return "", err
	}

	// Clear the expired/invalid token
	store := auth.NewStore()
	_ = store.ClearAuth()

	if deps.UI.IsInteractive() {
		deps.UI.Warn("Session expired or invalid")
		relogin, _ := deps.UI.Confirm("Open browser to sign in again?", true)
		if relogin {
			token, loginErr := RunDeviceLogin()
			if loginErr != nil {
				return "", loginErr
			}
			return token, nil
		}
		deps.UI.Message(deps.UI.Dim("Run: keyway login"))
		return "", err
	}

	// Non-interactive mode
	deps.UI.Error("Session expired or invalid")
	deps.UI.Message(deps.UI.Dim("Run: keyway logout && keyway login"))
	return "", err
}
Methodology: Repobility · https://repobility.com/research/state-of-ai-code-2026/
cmd.isTokenAuthProvider function · go · L44-L51 (8 LOC)
internal/cmd/connect.go
func isTokenAuthProvider(provider string) bool {
	for _, p := range tokenAuthProviders {
		if strings.EqualFold(p, provider) {
			return true
		}
	}
	return false
}
cmd.getTokenCreationURL function · go · L53-L205 (153 LOC)
internal/cmd/connect.go
func getTokenCreationURL(provider string) string {
	switch strings.ToLower(provider) {
	case "railway":
		return "https://railway.com/account/tokens"
	default:
		return ""
	}
}

func runConnect(cmd *cobra.Command, args []string) error {
	provider := strings.ToLower(args[0])

	token, err := EnsureLogin()
	if err != nil {
		return err
	}

	client := api.NewClient(token)
	ctx := context.Background()

	// Validate provider exists
	providers, err := client.GetProviders(ctx)
	if err != nil {
		ui.Error("Failed to fetch providers")
		return err
	}

	var providerInfo *api.Provider
	for _, p := range providers {
		if strings.EqualFold(p.Name, provider) {
			providerInfo = &p
			break
		}
	}

	if providerInfo == nil {
		available := make([]string, len(providers))
		for i, p := range providers {
			available[i] = p.Name
		}
		ui.Error(fmt.Sprintf("Unknown provider: %s", provider))
		ui.Message(ui.Dim(fmt.Sprintf("Available providers: %s", strings.Join(available, ", "))))
		return fmt.Errorf("unkn
cmd.runConnect function · go · L62-L164 (103 LOC)
internal/cmd/connect.go
func runConnect(cmd *cobra.Command, args []string) error {
	provider := strings.ToLower(args[0])

	token, err := EnsureLogin()
	if err != nil {
		return err
	}

	client := api.NewClient(token)
	ctx := context.Background()

	// Validate provider exists
	providers, err := client.GetProviders(ctx)
	if err != nil {
		ui.Error("Failed to fetch providers")
		return err
	}

	var providerInfo *api.Provider
	for _, p := range providers {
		if strings.EqualFold(p.Name, provider) {
			providerInfo = &p
			break
		}
	}

	if providerInfo == nil {
		available := make([]string, len(providers))
		for i, p := range providers {
			available[i] = p.Name
		}
		ui.Error(fmt.Sprintf("Unknown provider: %s", provider))
		ui.Message(ui.Dim(fmt.Sprintf("Available providers: %s", strings.Join(available, ", "))))
		return fmt.Errorf("unknown provider")
	}

	if !providerInfo.Configured {
		ui.Error(fmt.Sprintf("Provider %s is not configured on the server", providerInfo.DisplayName))
		ui.Message(ui.Dim("Contact yo
cmd.connectWithTokenFlow function · go · L166-L205 (40 LOC)
internal/cmd/connect.go
func connectWithTokenFlow(client *api.Client, ctx context.Context, provider, displayName string) (bool, error) {
	tokenURL := getTokenCreationURL(provider)

	if provider == "railway" {
		ui.Warn("Tip: Select the workspace containing your projects.")
		ui.Message(ui.Dim("Do NOT use \"No workspace\" - it won't have access to your projects."))
	}

	_ = browser.OpenURL(tokenURL)

	token, err := ui.Password(fmt.Sprintf("%s API Token:", displayName))
	if err != nil || token == "" {
		ui.Message(ui.Dim("Cancelled."))
		return false, nil
	}

	var resp *api.ConnectTokenResponse
	err = ui.Spin("Validating token...", func() error {
		var err error
		resp, err = client.ConnectWithToken(ctx, provider, token)
		return err
	})

	if err != nil {
		ui.Error(err.Error())
		return false, nil
	}

	if resp.Success {
		ui.Success(fmt.Sprintf("Connected to %s!", displayName))
		ui.Message(ui.Dim(fmt.Sprintf("Account: %s", resp.User.Username)))
		if resp.User.TeamName != nil {
			ui.Message(ui.Dim(fmt.Sprintf
cmd.connectWithOAuthFlow function · go · L207-L250 (44 LOC)
internal/cmd/connect.go
func connectWithOAuthFlow(client *api.Client, ctx context.Context, provider, displayName string) (bool, error) {
	authURL := client.GetProviderAuthURL(provider)
	startTime := time.Now()

	_ = browser.OpenURL(authURL)

	var connected bool
	err := ui.Spin("Waiting for authorization...", func() error {
		maxAttempts := 60 // 5 minutes max
		for i := 0; i < maxAttempts; i++ {
			time.Sleep(5 * time.Second)

			connections, err := client.GetConnections(ctx)
			if err != nil {
				continue
			}

			for _, c := range connections {
				if strings.EqualFold(c.Provider, provider) {
					// Check if this is a new connection (created after we started)
					createdAt, err := time.Parse(time.RFC3339, c.CreatedAt)
					if err == nil && createdAt.After(startTime) {
						connected = true
						return nil
					}
				}
			}
		}
		return fmt.Errorf("authorization timeout")
	})

	if err != nil {
		ui.Error("Authorization timeout.")
		ui.Message(ui.Dim("Run `keyway connections` to check if the connection w
cmd.runConnections function · go · L252-L294 (43 LOC)
internal/cmd/connect.go
func runConnections(cmd *cobra.Command, args []string) error {
	token, err := EnsureLogin()
	if err != nil {
		return err
	}

	client := api.NewClient(token)
	ctx := context.Background()

	connections, err := client.GetConnections(ctx)
	if err != nil {
		ui.Error("Failed to fetch connections")
		return err
	}

	if len(connections) == 0 {
		ui.Info("No provider connections found.")
		ui.Message(ui.Dim("Connect to a provider with: keyway connect <provider>"))
		ui.Message(ui.Dim("Available providers: vercel, railway"))
		return nil
	}

	ui.Intro("connections")

	for _, conn := range connections {
		providerName := cases.Title(language.English).String(conn.Provider)
		teamInfo := ""
		if conn.ProviderTeamID != nil {
			teamInfo = ui.Dim(fmt.Sprintf(" (Team: %s)", *conn.ProviderTeamID))
		}

		// Parse and format date
		createdAt, _ := time.Parse(time.RFC3339, conn.CreatedAt)
		dateStr := createdAt.Format("2006-01-02")

		ui.Success(fmt.Sprintf("%s%s", ui.Bold(providerName), teamInfo))
		u
cmd.runDisconnect function · go · L296-L353 (58 LOC)
internal/cmd/connect.go
func runDisconnect(cmd *cobra.Command, args []string) error {
	provider := strings.ToLower(args[0])

	token, err := EnsureLogin()
	if err != nil {
		return err
	}

	client := api.NewClient(token)
	ctx := context.Background()

	connections, err := client.GetConnections(ctx)
	if err != nil {
		ui.Error("Failed to fetch connections")
		return err
	}

	var connection *api.Connection
	for _, c := range connections {
		if strings.EqualFold(c.Provider, provider) {
			connection = &c
			break
		}
	}

	if connection == nil {
		ui.Info(fmt.Sprintf("No connection found for provider: %s", provider))
		return nil
	}

	providerName := cases.Title(language.English).String(provider)

	if ui.IsInteractive() {
		confirm, _ := ui.Confirm(fmt.Sprintf("Disconnect from %s?", providerName), false)
		if !confirm {
			ui.Message(ui.Dim("Cancelled."))
			return nil
		}
	}

	err = client.DeleteConnection(ctx, connection.ID)
	if err != nil {
		analytics.Track(analytics.EventError, map[string]interface{}{
			"comm
cmd.realEnvHelper.Discover method · go · L100-L107 (8 LOC)
internal/cmd/deps_real.go
func (r *realEnvHelper) Discover() []EnvCandidate {
	candidates := env.Discover()
	result := make([]EnvCandidate, len(candidates))
	for i, c := range candidates {
		result[i] = EnvCandidate{File: c.File, Env: c.Env}
	}
	return result
}
Source: Repobility analyzer · https://repobility.com
cmd.realFileWalker.Walk method · go · L130-L137 (8 LOC)
internal/cmd/deps_real.go
func (r *realFileWalker) Walk(root string, fn func(path string, info FileInfo, err error) error) error {
	return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if info == nil {
			return fn(path, nil, err)
		}
		return fn(path, &realFileInfo{info}, err)
	})
}
cmd.realFileStat.Stat method · go · L151-L157 (7 LOC)
internal/cmd/deps_real.go
func (r *realFileStat) Stat(name string) (FileInfo, error) {
	info, err := os.Stat(name)
	if err != nil {
		return nil, err
	}
	return &realFileInfo{info}, nil
}
cmd.realAuthStore.GetAuth method · go · L162-L175 (14 LOC)
internal/cmd/deps_real.go
func (r *realAuthStore) GetAuth() (*StoredAuthInfo, error) {
	store := auth.NewStore()
	storedAuth, err := store.GetAuth()
	if err != nil {
		return nil, err
	}
	if storedAuth == nil {
		return nil, nil
	}
	return &StoredAuthInfo{
		KeywayToken: storedAuth.KeywayToken,
		GitHubLogin: storedAuth.GitHubLogin,
	}, nil
}
cmd.realHTTPClient.Head method · go · L180-L188 (9 LOC)
internal/cmd/deps_real.go
func (r *realHTTPClient) Head(url string) (int, error) {
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Head(url)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()
	return resp.StatusCode, nil
}
cmd.DefaultDeps function · go · L191-L206 (16 LOC)
internal/cmd/deps_real.go
func DefaultDeps() *Dependencies {
	return &Dependencies{
		Git:        &realGitClient{},
		Auth:       &realAuthProvider{},
		UI:         &realUIProvider{},
		FS:         &realFileSystem{},
		Env:        &realEnvHelper{},
		APIFactory: &realAPIFactory{},
		CmdRunner:  &realCommandRunner{},
		Browser:    &realBrowserOpener{},
		Walker:     &realFileWalker{},
		Stat:       &realFileStat{},
		AuthStore:  &realAuthStore{},
		HTTP:       &realHTTPClient{},
	}
}
cmd.runDiff function · go · L78-L92 (15 LOC)
internal/cmd/diff.go
func runDiff(cmd *cobra.Command, args []string) error {
	opts := DiffOptions{}
	opts.ShowValues, _ = cmd.Flags().GetBool("show-values")
	opts.KeysOnly, _ = cmd.Flags().GetBool("keys-only")
	opts.JSONOutput, _ = cmd.Flags().GetBool("json")

	if len(args) >= 1 {
		opts.Env1 = args[0]
	}
	if len(args) >= 2 {
		opts.Env2 = args[1]
	}

	return runDiffWithDeps(opts, defaultDeps)
}
cmd.runDiffWithDeps function · go · L95-L242 (148 LOC)
internal/cmd/diff.go
func runDiffWithDeps(opts DiffOptions, deps *Dependencies) error {
	deps.UI.Intro("diff")

	repo, err := deps.Git.DetectRepo()
	if err != nil {
		deps.UI.Error("Not in a git repository with GitHub remote")
		return err
	}
	deps.UI.Step(fmt.Sprintf("Repository: %s", deps.UI.Value(repo)))

	token, err := deps.Auth.EnsureLogin()
	if err != nil {
		return err
	}

	client := deps.APIFactory.NewClient(token)
	ctx := context.Background()

	env1 := opts.Env1
	env2 := opts.Env2

	// If arguments not provided, prompt interactively
	if env1 == "" || env2 == "" {
		if !deps.UI.IsInteractive() {
			deps.UI.Error("Two environment arguments required in non-interactive mode")
			return fmt.Errorf("missing arguments")
		}

		// Fetch available environments
		var environments []string
		err = deps.UI.Spin("Fetching environments...", func() error {
			var fetchErr error
			environments, fetchErr = client.GetVaultEnvironments(ctx, repo)
			return fetchErr
		})
		if err != nil {
			deps.UI.Error(fmt.Sprint
cmd.normalizeEnvName function · go · L244-L256 (13 LOC)
internal/cmd/diff.go
func normalizeEnvName(env string) string {
	env = strings.ToLower(strings.TrimSpace(env))
	switch env {
	case "prod":
		return "production"
	case "dev":
		return "development"
	case "stg":
		return "staging"
	default:
		return env
	}
}
Repobility · severity-and-effort ranking · https://repobility.com
cmd.compareSecrets function · go · L258-L320 (63 LOC)
internal/cmd/diff.go
func compareSecrets(env1, env2 string, secrets1, secrets2 map[string]string, includeValues bool) *DiffResult {
	result := &DiffResult{
		Env1:       env1,
		Env2:       env2,
		OnlyInEnv1: []string{},
		OnlyInEnv2: []string{},
		Different:  []DiffEntry{},
		Same:       []string{},
	}

	// Get all keys
	allKeys := make(map[string]bool)
	for k := range secrets1 {
		allKeys[k] = true
	}
	for k := range secrets2 {
		allKeys[k] = true
	}

	// Sort keys for consistent output
	sortedKeys := make([]string, 0, len(allKeys))
	for k := range allKeys {
		sortedKeys = append(sortedKeys, k)
	}
	sort.Strings(sortedKeys)

	// Compare
	for _, key := range sortedKeys {
		val1, in1 := secrets1[key]
		val2, in2 := secrets2[key]

		if in1 && !in2 {
			result.OnlyInEnv1 = append(result.OnlyInEnv1, key)
		} else if !in1 && in2 {
			result.OnlyInEnv2 = append(result.OnlyInEnv2, key)
		} else if val1 != val2 {
			entry := DiffEntry{
				Key:      key,
				Preview1: previewValue(val1),
				Preview2: previewValu
cmd.previewValue function · go · L325-L334 (10 LOC)
internal/cmd/diff.go
func previewValue(value string) string {
	length := len(value)
	if length == 0 {
		return "(empty)"
	}
	if length <= 2 {
		return fmt.Sprintf("**%s (%d chars)", value, length)
	}
	return fmt.Sprintf("**%s (%d chars)", value[length-2:], length)
}
cmd.maskValue function · go · L336-L341 (6 LOC)
internal/cmd/diff.go
func maskValue(value string) string {
	if len(value) <= 4 {
		return "****"
	}
	return value[:2] + strings.Repeat("*", len(value)-4) + value[len(value)-2:]
}
cmd.printDiffResults function · go · L343-L412 (70 LOC)
internal/cmd/diff.go
func printDiffResults(result *DiffResult, env1, env2 string, showValues, keysOnly bool) {
	// Summary
	if result.Stats.OnlyInEnv1 == 0 && result.Stats.OnlyInEnv2 == 0 && result.Stats.Different == 0 {
		ui.Success("Environments are identical!")
		ui.Message(ui.Dim(fmt.Sprintf("%d secrets in both environments", result.Stats.Same)))
		return
	}

	// Only in env1
	if len(result.OnlyInEnv1) > 0 {
		fmt.Println()
		ui.Message(fmt.Sprintf("Only in %s (%d):", ui.Bold(env1), len(result.OnlyInEnv1)))
		for _, key := range result.OnlyInEnv1 {
			if keysOnly {
				fmt.Printf("  %s\n", key)
			} else {
				fmt.Printf("  %s %s\n", ui.Value("-"), key)
			}
		}
	}

	// Only in env2
	if len(result.OnlyInEnv2) > 0 {
		fmt.Println()
		ui.Message(fmt.Sprintf("Only in %s (%d):", ui.Bold(env2), len(result.OnlyInEnv2)))
		for _, key := range result.OnlyInEnv2 {
			if keysOnly {
				fmt.Printf("  %s\n", key)
			} else {
				fmt.Printf("  %s %s\n", ui.Value("+"), key)
			}
		}
	}

	// Different values
	if len(
cmd.printDiffJSON function · go · L414-L472 (59 LOC)
internal/cmd/diff.go
func printDiffJSON(result *DiffResult) error {
	// Simple JSON output without external dependency
	fmt.Println("{")
	fmt.Printf("  \"env1\": %q,\n", result.Env1)
	fmt.Printf("  \"env2\": %q,\n", result.Env2)

	// OnlyInEnv1
	fmt.Print("  \"onlyInEnv1\": [")
	for i, k := range result.OnlyInEnv1 {
		if i > 0 {
			fmt.Print(", ")
		}
		fmt.Printf("%q", k)
	}
	fmt.Println("],")

	// OnlyInEnv2
	fmt.Print("  \"onlyInEnv2\": [")
	for i, k := range result.OnlyInEnv2 {
		if i > 0 {
			fmt.Print(", ")
		}
		fmt.Printf("%q", k)
	}
	fmt.Println("],")

	// Different
	fmt.Print("  \"different\": [")
	for i, d := range result.Different {
		if i > 0 {
			fmt.Print(", ")
		}
		fmt.Printf("{\"key\": %q, \"preview1\": %q, \"preview2\": %q}", d.Key, d.Preview1, d.Preview2)
	}
	fmt.Println("],")

	// Same
	fmt.Print("  \"same\": [")
	for i, k := range result.Same {
		if i > 0 {
			fmt.Print(", ")
		}
		fmt.Printf("%q", k)
	}
	fmt.Println("],")

	// Stats
	fmt.Println("  \"stats\": {")
	fmt.Printf("    \"t
cmd.runDoctor function · go · L52-L59 (8 LOC)
internal/cmd/doctor.go
func runDoctor(cmd *cobra.Command, args []string) error {
	opts := DoctorOptions{}
	opts.JSONOutput, _ = cmd.Flags().GetBool("json")
	opts.Strict, _ = cmd.Flags().GetBool("strict")
	opts.Version = rootCmd.Version

	return runDoctorWithDeps(opts, defaultDeps)
}
cmd.runDoctorWithDeps function · go · L62-L152 (91 LOC)
internal/cmd/doctor.go
func runDoctorWithDeps(opts DoctorOptions, deps *Dependencies) error {
	if !opts.JSONOutput {
		deps.UI.Intro("doctor")
	}

	checks := []checkResult{}

	// 1. Version check
	versionCheck := checkVersion(opts.Version)
	checks = append(checks, versionCheck)

	// 2. Authentication check
	authCheck := checkAuthWithDeps(deps)
	checks = append(checks, authCheck)

	// 3. GitHub repository check
	githubCheck := checkGitHubWithDeps(deps)
	checks = append(checks, githubCheck)

	// 4. Network/API check
	networkCheck := checkNetworkWithDeps(deps)
	checks = append(checks, networkCheck)

	// 5. Env file check
	envCheck := checkEnvFileWithDeps(deps)
	checks = append(checks, envCheck)

	// 6. Gitignore check
	gitignoreCheck := checkGitignoreWithDeps(deps)
	checks = append(checks, gitignoreCheck)

	// Apply strict mode
	if opts.Strict {
		for i := range checks {
			if checks[i].Status == "warn" {
				checks[i].Status = "fail"
			}
		}
	}

	// Calculate summary
	summary := doctorSummary{Checks: checks}
cmd.checkAuthWithDeps function · go · L154-L195 (42 LOC)
internal/cmd/doctor.go
func checkAuthWithDeps(deps *Dependencies) checkResult {
	storedAuth, err := deps.AuthStore.GetAuth()

	if err != nil || storedAuth == nil {
		return checkResult{
			ID:     "auth",
			Name:   "Authentication",
			Status: "warn",
			Detail: "Not logged in. Run: keyway login",
		}
	}

	// Validate token
	client := deps.APIFactory.NewClient(storedAuth.KeywayToken)
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	validation, err := client.ValidateToken(ctx)
	if err != nil {
		return checkResult{
			ID:     "auth",
			Name:   "Authentication",
			Status: "warn",
			Detail: fmt.Sprintf("Token expired or invalid (%v). Run: keyway login", err),
		}
	}

	username := validation.Username
	if username == "" {
		username = storedAuth.GitHubLogin
	}
	if username == "" {
		username = "user"
	}

	return checkResult{
		ID:     "auth",
		Name:   "Authentication",
		Status: "pass",
		Detail: fmt.Sprintf("Logged in as %s", username),
	}
}
Repobility — same analyzer, your code, free for public repos · /scan/
cmd.checkGitHubWithDeps function · go · L197-L223 (27 LOC)
internal/cmd/doctor.go
func checkGitHubWithDeps(deps *Dependencies) checkResult {
	if !deps.Git.IsGitRepository() {
		return checkResult{
			ID:     "github",
			Name:   "GitHub repository",
			Status: "warn",
			Detail: "Not in a git repository",
		}
	}

	repo, err := deps.Git.DetectRepo()
	if err != nil {
		return checkResult{
			ID:     "github",
			Name:   "GitHub repository",
			Status: "warn",
			Detail: "No GitHub remote configured",
		}
	}

	return checkResult{
		ID:     "github",
		Name:   "GitHub repository",
		Status: "pass",
		Detail: repo,
	}
}
cmd.checkNetworkWithDeps function · go · L225-L254 (30 LOC)
internal/cmd/doctor.go
func checkNetworkWithDeps(deps *Dependencies) checkResult {
	healthURL := config.GetAPIURL() + "/v1/health"

	statusCode, err := deps.HTTP.Head(healthURL)

	if err != nil {
		return checkResult{
			ID:     "network",
			Name:   "API connectivity",
			Status: "warn",
			Detail: "Cannot connect to API server",
		}
	}

	if statusCode >= 500 {
		return checkResult{
			ID:     "network",
			Name:   "API connectivity",
			Status: "warn",
			Detail: fmt.Sprintf("Server returned %d", statusCode),
		}
	}

	return checkResult{
		ID:     "network",
		Name:   "API connectivity",
		Status: "pass",
		Detail: fmt.Sprintf("Connected to %s", config.GetAPIURL()),
	}
}
cmd.checkEnvFileWithDeps function · go · L256-L281 (26 LOC)
internal/cmd/doctor.go
func checkEnvFileWithDeps(deps *Dependencies) checkResult {
	envFiles := []string{".env", ".env.local", ".env.development", ".env.production"}
	found := []string{}

	for _, f := range envFiles {
		if _, err := deps.Stat.Stat(f); err == nil {
			found = append(found, f)
		}
	}

	if len(found) == 0 {
		return checkResult{
			ID:     "envfile",
			Name:   "Environment file",
			Status: "warn",
			Detail: "No .env file found. Run: keyway pull",
		}
	}

	return checkResult{
		ID:     "envfile",
		Name:   "Environment file",
		Status: "pass",
		Detail: fmt.Sprintf("Found: %s", found[0]),
	}
}
cmd.checkGitignoreWithDeps function · go · L283-L308 (26 LOC)
internal/cmd/doctor.go
func checkGitignoreWithDeps(deps *Dependencies) checkResult {
	if !deps.Git.IsGitRepository() {
		return checkResult{
			ID:     "gitignore",
			Name:   ".gitignore",
			Status: "pass",
			Detail: "Not in a git repository",
		}
	}

	if deps.Git.CheckEnvGitignore() {
		return checkResult{
			ID:     "gitignore",
			Name:   ".gitignore",
			Status: "pass",
			Detail: "Environment files are ignored",
		}
	}

	return checkResult{
		ID:     "gitignore",
		Name:   ".gitignore",
		Status: "warn",
		Detail: "Missing .env patterns in .gitignore",
	}
}
cmd.checkVersion function · go · L310-L330 (21 LOC)
internal/cmd/doctor.go
func checkVersion(currentVersion string) checkResult {
	ctx, cancel := context.WithTimeout(context.Background(), version.CheckTimeout)
	defer cancel()

	info := version.CheckForUpdate(ctx, currentVersion)
	if info != nil && info.Available {
		return checkResult{
			ID:     "version",
			Name:   "CLI version",
			Status: "warn",
			Detail: fmt.Sprintf("%s available (current: %s). Run: %s", info.LatestVersion, info.CurrentVersion, info.UpdateCommand),
		}
	}

	return checkResult{
		ID:     "version",
		Name:   "CLI version",
		Status: "pass",
		Detail: fmt.Sprintf("%s (latest)", currentVersion),
	}
}
cmd.formatEnvCandidates function · go · L289-L295 (7 LOC)
internal/cmd/init.go
func formatEnvCandidates(candidates []EnvCandidate) string {
	names := make([]string, len(candidates))
	for i, c := range candidates {
		names[i] = c.File
	}
	return strings.Join(names, ", ")
}
cmd.buildDeepLinkInstallURL function · go · L298-L305 (8 LOC)
internal/cmd/init.go
func buildDeepLinkInstallURL(baseURL string, repoIds *api.RepoIds) string {
	if repoIds == nil {
		return baseURL
	}
	// Format: baseURL/permissions?suggested_target_id=OWNER_ID&repository_ids[]=REPO_ID
	return fmt.Sprintf("%s/permissions?suggested_target_id=%d&repository_ids[]=%d",
		strings.TrimSuffix(baseURL, "/"), repoIds.OwnerID, repoIds.RepoID)
}
cmd.ensureLoginAndGitHubAppWithDeps function · go · L307-L397 (91 LOC)
internal/cmd/init.go
func ensureLoginAndGitHubAppWithDeps(repo string, deps *Dependencies) (string, error) {
	// First ensure login
	token, err := deps.Auth.EnsureLogin()
	if err != nil {
		return "", err
	}

	// Check GitHub App installation
	parts := strings.Split(repo, "/")
	if len(parts) != 2 {
		return "", fmt.Errorf("invalid repository format: %s", repo)
	}

	client := deps.APIFactory.NewClient(token)
	ctx := context.Background()

	status, err := client.CheckGitHubAppInstallation(ctx, parts[0], parts[1])
	if err != nil {
		// If we can't check, continue anyway
		return token, nil
	}

	if status.Installed {
		return token, nil
	}

	// GitHub App not installed
	deps.UI.Warn("GitHub App not installed for this repository")
	deps.UI.Message(deps.UI.Dim("The Keyway GitHub App is required for secure access."))

	// Get repo IDs for deep linking
	repoIds := getRepoIdsWithFallbackAndDeps(ctx, repo, deps)
	installURL := buildDeepLinkInstallURL(status.InstallURL, repoIds)

	if !deps.UI.IsInteractive() {
		deps.
Methodology: Repobility · https://repobility.com/research/state-of-ai-code-2026/
cmd.formatCandidates function · go · L399-L405 (7 LOC)
internal/cmd/init.go
func formatCandidates(candidates []env.Candidate) string {
	names := make([]string, len(candidates))
	for i, c := range candidates {
		names[i] = c.File
	}
	return strings.Join(names, ", ")
}
cmd.runLogin function · go · L36-L55 (20 LOC)
internal/cmd/login.go
func runLogin(cmd *cobra.Command, args []string) error {
	ui.Intro("login")

	useToken, _ := cmd.Flags().GetBool("token")

	var err error
	if useToken {
		err = runTokenLogin()
	} else {
		_, err = RunDeviceLogin()
	}

	if err != nil {
		ui.Error(err.Error())
		return err
	}

	ui.Outro("Ready to sync secrets!")
	return nil
}
cmd.getRepoIdsWithFallbackAndDeps function · go · L62-L83 (22 LOC)
internal/cmd/login.go
func getRepoIdsWithFallbackAndDeps(ctx context.Context, repoFullName string, deps *Dependencies) *api.RepoIds {
	if repoFullName == "" {
		return nil
	}

	parts := strings.Split(repoFullName, "/")
	if len(parts) != 2 {
		return nil
	}
	owner, repo := parts[0], parts[1]

	// 1. Try backend (works for private repos if app installed with "all repos")
	client := deps.APIFactory.NewClient("")
	ids, _ := client.GetRepoIdsFromBackend(ctx, repoFullName)
	if ids != nil {
		return ids
	}

	// 2. Fallback: GitHub public API (public repos only)
	ids, _ = api.GetRepoIdsFromGitHub(ctx, owner, repo)
	return ids
}
‹ prevpage 2 / 4next ›