feat: show git branch if available

This commit is contained in:
Dallin Romney 2025-09-02 14:58:06 -07:00
parent 4d8088f68a
commit 5fce82dfd2
10 changed files with 508 additions and 23 deletions

View file

@ -0,0 +1,15 @@
# Continue CLI Terminal UI spec
This spec is incomplete.
## Stack
The Continue CLI uses Ink as a react TUI library.
## cwd/git display
The lower left corner of the TUI should display
- the current git branch if in a git repo
- also the current owner/repo if enough columns are available to display and it's a gh repo
- if not in git, the cwd

View file

@ -0,0 +1,226 @@
import { execSync } from "child_process";
import fs from "fs/promises";
import path from "path";
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import {
createTestContext,
cleanupTestContext,
runCLI,
createTestConfig,
type CLITestContext,
} from "../test-helpers/cli-helpers.js";
describe("E2E: Git Branch Display", () => {
let context: CLITestContext;
let originalCwd: string;
const testConfig = `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`;
beforeEach(async () => {
context = await createTestContext();
originalCwd = process.cwd();
});
afterEach(async () => {
await cleanupTestContext(context);
process.chdir(originalCwd);
});
describe("git branch display in status bar", () => {
it("should show branch name when in a git repository", async () => {
// Initialize a git repo in the test directory
process.chdir(context.testDir);
try {
// Initialize git repo
execSync("git init", { stdio: "ignore" });
execSync("git config user.email 'test@example.com'", { stdio: "ignore" });
execSync("git config user.name 'Test User'", { stdio: "ignore" });
// Create a test file and initial commit
await fs.writeFile(path.join(context.testDir, "test.txt"), "test content");
execSync("git add .", { stdio: "ignore" });
execSync("git commit -m 'Initial commit'", { stdio: "ignore" });
// Create and checkout a test branch
const testBranchName = "feature/test-branch";
execSync(`git checkout -b ${testBranchName}`, { stdio: "ignore" });
// Create config file
await createTestConfig(context, testConfig);
// Run CLI in TUI mode - it should fail quickly but show the branch in output
const result = await runCLI(context, {
args: ["--config", context.configPath!, "--help"],
timeout: 3000,
});
// The help command should succeed
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("Continue CLI");
// Now let's test that our git utils work in this context
// We can't easily test the full TUI display, but we can verify the git functions work
const { getGitBranch } = await import("../util/git.js");
const branch = getGitBranch();
expect(branch).toBe(testBranchName);
} catch (error) {
// Skip test if git is not available or fails
console.warn("Skipping git branch test - git not available:", error);
return;
}
});
it("should handle non-git directory gracefully", async () => {
// Don't initialize git in test directory
process.chdir(context.testDir);
await createTestConfig(context, testConfig);
// Test that git functions return null in non-git directory
const { getGitBranch, isGitRepo } = await import("../util/git.js");
expect(isGitRepo()).toBe(false);
expect(getGitBranch()).toBeNull();
// CLI should still work without git
const result = await runCLI(context, {
args: ["--help"],
timeout: 3000,
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("Continue CLI");
});
it("should handle detached HEAD state", async () => {
process.chdir(context.testDir);
try {
// Initialize git repo
execSync("git init", { stdio: "ignore" });
execSync("git config user.email 'test@example.com'", { stdio: "ignore" });
execSync("git config user.name 'Test User'", { stdio: "ignore" });
// Create initial commit
await fs.writeFile(path.join(context.testDir, "test.txt"), "test content");
execSync("git add .", { stdio: "ignore" });
execSync("git commit -m 'Initial commit'", { stdio: "ignore" });
// Create another commit
await fs.writeFile(path.join(context.testDir, "test2.txt"), "test content 2");
execSync("git add .", { stdio: "ignore" });
execSync("git commit -m 'Second commit'", { stdio: "ignore" });
// Get first commit hash and checkout to detached HEAD
const firstCommit = execSync("git rev-list --reverse HEAD | head -1", {
encoding: "utf-8"
}).trim();
execSync(`git checkout ${firstCommit}`, { stdio: "ignore" });
// Test git functions in detached HEAD state
const { getGitBranch, isGitRepo } = await import("../util/git.js");
expect(isGitRepo()).toBe(true);
// In detached HEAD state, git branch --show-current returns empty string
// which our function converts to null
expect(getGitBranch()).toBeNull();
} catch (error) {
// Skip test if git operations fail
console.warn("Skipping detached HEAD test - git operations failed:", error);
return;
}
});
it("should handle branch names with special characters", async () => {
process.chdir(context.testDir);
try {
// Initialize git repo
execSync("git init", { stdio: "ignore" });
execSync("git config user.email 'test@example.com'", { stdio: "ignore" });
execSync("git config user.name 'Test User'", { stdio: "ignore" });
// Create initial commit
await fs.writeFile(path.join(context.testDir, "test.txt"), "test content");
execSync("git add .", { stdio: "ignore" });
execSync("git commit -m 'Initial commit'", { stdio: "ignore" });
// Create branch with special characters
const specialBranchName = "feature/fix-123_with-dashes.and.dots";
execSync(`git checkout -b "${specialBranchName}"`, { stdio: "ignore" });
// Test git functions
const { getGitBranch } = await import("../util/git.js");
const branch = getGitBranch();
expect(branch).toBe(specialBranchName);
} catch (error) {
// Skip test if git operations fail
console.warn("Skipping special characters test - git operations failed:", error);
return;
}
});
});
describe("getRepoUrlText function with branch", () => {
it("should format repo URL with branch correctly", async () => {
process.chdir(context.testDir);
try {
// Initialize git repo with remote
execSync("git init", { stdio: "ignore" });
execSync("git config user.email 'test@example.com'", { stdio: "ignore" });
execSync("git config user.name 'Test User'", { stdio: "ignore" });
// Add a fake remote
execSync("git remote add origin https://github.com/testuser/testrepo.git", { stdio: "ignore" });
// Create initial commit and branch
await fs.writeFile(path.join(context.testDir, "test.txt"), "test content");
execSync("git add .", { stdio: "ignore" });
execSync("git commit -m 'Initial commit'", { stdio: "ignore" });
execSync("git checkout -b test-branch", { stdio: "ignore" });
// Test the formatting function
const { getResponsiveRepoText } = await import("../ui/hooks/useTUIChatHooks.js");
const repoText = getResponsiveRepoText();
// Should include both repo and branch
expect(repoText).toContain("testuser/testrepo");
expect(repoText).toContain("test-branch");
expect(repoText).toContain("⊦"); // Branch separator icon
} catch (error) {
// Skip test if git operations fail
console.warn("Skipping repo URL formatting test - git operations failed:", error);
return;
}
});
it("should handle repo URL without branch when not in git repo", async () => {
process.chdir(context.testDir);
// Test without git repo
const { getRepoUrlText } = await import("../ui/hooks/useTUIChatHooks.js");
const repoText = getRepoUrlText();
// Should not contain branch separator
expect(repoText).not.toContain("⊦");
// Should contain the current directory path
expect(typeof repoText).toBe("string");
expect(repoText.length).toBeGreaterThan(0);
});
});
});

View file

@ -26,7 +26,6 @@ import { useChat } from "./hooks/useChat.js";
import { useContextPercentage } from "./hooks/useContextPercentage.js";
import { useMessageRenderer } from "./hooks/useMessageRenderer.js";
import {
getRepoUrlText,
useCurrentMode,
useIntroMessage,
useLoginHandlers,
@ -147,7 +146,6 @@ const TUIChat: React.FC<TUIChatProps> = ({
const { services, allServicesReady, isRemoteMode } =
useTUIChatServices(remoteUrl);
const repoURlText = useMemo(() => getRepoUrlText(remoteUrl), [remoteUrl]);
// Use navigation context
const {
@ -334,7 +332,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
{/* Free trial status and Continue CLI info - always show */}
<BottomStatusBar
currentMode={currentMode}
repoURLText={repoURlText}
remoteUrl={remoteUrl}
isRemoteMode={isRemoteMode}
services={services}
navState={navState}

View file

@ -66,7 +66,11 @@ const UpdateNotification: React.FC<UpdateNotificationProps> = ({
if (isRemoteMode) {
return <Text color="cyan">◉ Remote Mode</Text>;
}
return <Text color="gray">● Continue CLI</Text>;
return (
<Text wrap="truncate-end" color="gray">
● Continue CLI
</Text>
);
}
return <Text color="dim">{text}</Text>;

View file

@ -8,10 +8,11 @@ import { UpdateNotification } from "../UpdateNotification.js";
import { ContextPercentageDisplay } from "./ContextPercentageDisplay.js";
import { ModeIndicator } from "./ModeIndicator.js";
import { ResponsiveRepoDisplay } from "./ResponsiveRepoDisplay.js";
interface BottomStatusBarProps {
currentMode: PermissionMode;
repoURLText: string;
remoteUrl?: string;
isRemoteMode: boolean;
services: any;
navState: any;
@ -22,7 +23,7 @@ interface BottomStatusBarProps {
export const BottomStatusBar: React.FC<BottomStatusBarProps> = ({
currentMode,
repoURLText,
remoteUrl,
isRemoteMode,
services,
navState,
@ -34,9 +35,7 @@ export const BottomStatusBar: React.FC<BottomStatusBarProps> = ({
<Box marginLeft={2} flexDirection="row" alignItems="center">
{currentMode === "normal" && (
<React.Fragment>
<Text key="repo-url" color="dim" wrap="truncate-start">
{repoURLText}
</Text>
<ResponsiveRepoDisplay remoteUrl={remoteUrl} />
<Text key="repo-separator"> </Text>
</React.Fragment>
)}

View file

@ -0,0 +1,35 @@
import { Text } from "ink";
import React, { useMemo } from "react";
import { getResponsiveRepoText } from "../hooks/useTUIChatHooks.js";
import { useTerminalSize } from "../hooks/useTerminalSize.js";
interface ResponsiveRepoDisplayProps {
remoteUrl?: string;
reservedWidth?: number; // Width reserved for other elements in the same row
}
export const ResponsiveRepoDisplay: React.FC<ResponsiveRepoDisplayProps> = ({
remoteUrl,
}) => {
const { columns } = useTerminalSize();
const repoText = useMemo(() => {
// Calculate available width for repo display
// Reserve space for margins, mode indicator, context percentage, and other UI elements
const availableWidth = Math.floor(columns / 2);
return getResponsiveRepoText(remoteUrl, availableWidth);
}, [remoteUrl, columns]);
// Don't render if no text to show
if (!repoText) {
return null;
}
return (
<Text color="dim" wrap="truncate-start">
{repoText}
</Text>
);
};

View file

@ -0,0 +1,106 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import { getResponsiveRepoText, getRepoInfo } from "./useTUIChatHooks.js";
// Mock the git utilities
vi.mock("../../util/git.js", () => ({
isGitRepo: vi.fn(() => true),
getGitRemoteUrl: vi.fn(() => "https://github.com/testuser/testrepo.git"),
getGitBranch: vi.fn(() => "feature/test-branch"),
}));
describe("Responsive repo text functionality", () => {
beforeEach(async () => {
// Reset mocks before each test
const gitModule = await import("../../util/git.js");
vi.mocked(gitModule.isGitRepo).mockReturnValue(true);
vi.mocked(gitModule.getGitRemoteUrl).mockReturnValue("https://github.com/testuser/testrepo.git");
vi.mocked(gitModule.getGitBranch).mockReturnValue("feature/test-branch");
});
describe("getRepoInfo", () => {
it("should extract repo info correctly", () => {
const info = getRepoInfo();
expect(info.repoName).toBe("testuser/testrepo");
expect(info.branchName).toBe("feature/test-branch");
expect(info.isGitRepo).toBe(true);
});
it("should handle remote URL override", () => {
const info = getRepoInfo("https://github.com/override/repo.git");
expect(info.repoName).toBe("override/repo");
expect(info.branchName).toBe("feature/test-branch");
expect(info.isGitRepo).toBe(true);
});
});
describe("getResponsiveRepoText", () => {
it("should return empty string when no width provided", () => {
const result = getResponsiveRepoText();
expect(result).toBe("");
});
it("should return full text when width allows", () => {
const result = getResponsiveRepoText(undefined, 100);
expect(result).toBe("testuser/testrepo ⊦feature/test-branch");
});
it("should prefer branch when both fit individually", () => {
// Full text: "testuser/testrepo ⊦ feature/test-branch" (38 chars)
// Repo only: "testuser/testrepo" (17 chars)
// Branch only: "feature/test-branch" (18 chars)
// With width 20, both repo and branch fit, but we prefer branch
const result = getResponsiveRepoText(undefined, 20);
expect(result).toBe("feature/test-branch");
});
it("should fallback to repo when branch doesn't fit but repo does", async () => {
// Use a long branch name
const gitModule = await import("../../util/git.js");
vi.mocked(gitModule.getGitBranch).mockReturnValue("very-long-feature-branch-name-that-wont-fit");
const result = getResponsiveRepoText(undefined, 20);
// Branch is too long, repo should fit
expect(result).toBe("testuser/testrepo");
});
it("should return branch only when repo doesn't fit but branch does", async () => {
// When space is very limited, prefer shorter option
const gitModule = await import("../../util/git.js");
vi.mocked(gitModule.getGitRemoteUrl).mockReturnValue("https://github.com/very-long-repo-name/testrepo.git");
vi.mocked(gitModule.getGitBranch).mockReturnValue("main");
const result = getResponsiveRepoText(undefined, 10);
// "main" (4 chars) should fit, "very-long-repo-name/testrepo" won't
expect(result).toBe("main");
});
it("should return empty string when nothing fits", () => {
const result = getResponsiveRepoText(undefined, 5);
expect(result).toBe("");
});
it("should return empty string when width is too small", () => {
const result = getResponsiveRepoText(undefined, 2);
expect(result).toBe("");
});
it("should handle non-git repos", async () => {
const gitModule = await import("../../util/git.js");
vi.mocked(gitModule.isGitRepo).mockReturnValue(false);
vi.mocked(gitModule.getGitBranch).mockReturnValue(null);
const result = getResponsiveRepoText("https://github.com/user/repo.git", 50);
expect(result).toBe("user/repo");
});
it("should return empty string when repo name is too long in non-git scenario", async () => {
const gitModule = await import("../../util/git.js");
vi.mocked(gitModule.isGitRepo).mockReturnValue(false);
const result = getResponsiveRepoText("https://github.com/very-long-user/repo.git", 8);
expect(result).toBe("");
});
});
});

View file

@ -2,31 +2,107 @@ import { useCallback, useEffect, useState } from "react";
import type { PermissionMode } from "../../permissions/types.js";
import { modeService } from "../../services/ModeService.js";
import { getGitRemoteUrl, isGitRepo } from "../../util/git.js";
import { getGitBranch, getGitRemoteUrl, isGitRepo } from "../../util/git.js";
import type { ConfigOption, ModelOption } from "../types/selectorTypes.js";
import { useConfigSelector } from "./useConfigSelector.js";
import { useModelSelector } from "./useModelSelector.js";
// Helper function to get repo URL text
export function getRepoUrlText(remoteUrl?: string): string {
// Helper function to get repo info for responsive display
export function getRepoInfo(remoteUrl?: string): {
repoName: string;
branchName: string | null;
fullPath: string;
isGitRepo: boolean;
} {
let url = remoteUrl ?? "";
if (!url) {
const isGit = isGitRepo();
if (isGit) {
const gitUrl = getGitRemoteUrl();
if (gitUrl) {
url = gitUrl;
}
const isGit = isGitRepo();
let branchName: string | null = null;
if (!url && isGit) {
const gitUrl = getGitRemoteUrl();
if (gitUrl) {
url = gitUrl;
}
}
if (!url) {
url = process.cwd();
}
url = url.replace(/\.git$/, "");
url = url.replace(/^(https|http):\/\/.*?\//, "");
return url;
// Get branch info if we're in a git repo
if (isGit) {
branchName = getGitBranch();
}
// Clean up the URL
const cleanUrl = url
.replace(/\.git$/, "")
.replace(/^(https|http):\/\/.*?\//, "");
return {
repoName: cleanUrl,
branchName,
fullPath: url,
isGitRepo: isGit,
};
}
// Helper function to get responsive repo URL text based on available width
export function getResponsiveRepoText(
remoteUrl?: string,
availableWidth: number = 0,
): string {
const repoInfo = getRepoInfo(remoteUrl);
// If no available width provided, return full format
if (availableWidth <= 0) {
return "";
}
// Calculate the minimum space needed for different display options
const branchSeparator = " ⊦";
const branchText = repoInfo.branchName || "";
const repoText = repoInfo.repoName;
// Priority order for display:
// 1. repo + branch (if everything fits)
// 2. branch only (preferred when both fit individually)
// 3. repo only (fallback when branch doesn't fit)
// 4. nothing if neither fit
if (repoInfo.isGitRepo && repoInfo.branchName) {
const fullText = `${repoText}${branchSeparator}${branchText}`;
const branchOnlyText = branchText;
const repoOnlyText = repoText;
// If full text fits, use it
if (fullText.length <= availableWidth) {
return fullText;
}
// Prefer branch if it fits (more immediately useful)
if (branchOnlyText.length <= availableWidth) {
return branchOnlyText;
}
// If branch doesn't fit but repo does, use repo
if (repoOnlyText.length <= availableWidth) {
return repoOnlyText;
}
}
// No branch or not in git repo
if (repoText.length <= availableWidth) {
return repoText;
}
return "";
}
// Helper function to get repo URL text (legacy compatibility)
export function getRepoUrlText(remoteUrl?: string): string {
return getResponsiveRepoText(remoteUrl);
}
// Custom hook for intro message

View file

@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it } from "vitest";
import { getGitHubActionsRepoUrl, isGitHubActions } from "./git.js";
import { getGitBranch, getGitHubActionsRepoUrl, isGitHubActions } from "./git.js";
describe("git utilities - GitHub Actions detection", () => {
beforeEach(() => {
@ -74,4 +74,13 @@ describe("git utilities - GitHub Actions detection", () => {
expect(result).toBe("https://git.company.com/enterprise/repo");
});
});
describe("getGitBranch", () => {
it("should return null when not in a git repo or when git command fails", () => {
// Since we can't easily mock git commands in this test environment,
// we just test that the function returns either a string or null
const result = getGitBranch();
expect(typeof result === "string" || result === null).toBe(true);
});
});
});

View file

@ -18,6 +18,23 @@ export function getGitRemoteUrl(remote: string = "origin"): string | null {
}
}
/**
* Get the current git branch name
* @returns The current branch name or null if not found
*/
export function getGitBranch(): string | null {
try {
const result = execSync("git branch --show-current", {
encoding: "utf-8",
cwd: process.cwd(),
stdio: "pipe",
});
return result.trim() || null;
} catch {
return null;
}
}
/**
* Check if current directory is a git repository
*/