Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,40 @@ require (
github.com/charmbracelet/lipgloss v1.1.0
github.com/docker/docker v28.5.1+incompatible
github.com/docker/go-connections v0.6.0
github.com/go-git/go-git/v5 v5.16.3
github.com/spf13/cobra v1.10.1
github.com/stretchr/testify v1.11.1
gopkg.in/yaml.v3 v3.0.1
)

require (
dario.cat/mergo v1.0.0 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/ProtonMail/go-crypto v1.1.6 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
github.com/charmbracelet/x/ansi v0.8.0 // indirect
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 // indirect
github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/cloudflare/circl v1.6.1 // indirect
github.com/containerd/errdefs v1.0.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/cyphar/filepath-securejoin v0.4.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
github.com/go-git/go-billy/v5 v5.6.2 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/kevinburke/ssh_config v1.2.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
Expand All @@ -39,18 +50,25 @@ require (
github.com/muesli/termenv v0.16.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/pjbgf/sha1cd v0.3.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect
github.com/skeema/knownhosts v1.3.1 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect
go.opentelemetry.io/otel v1.38.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 // indirect
go.opentelemetry.io/otel/metric v1.38.0 // indirect
go.opentelemetry.io/otel/trace v1.38.0 // indirect
golang.org/x/crypto v0.41.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/time v0.14.0 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
gotest.tools/v3 v3.5.2 // indirect
)
79 changes: 75 additions & 4 deletions go.sum

Large diffs are not rendered by default.

276 changes: 276 additions & 0 deletions internal/cli/scan.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
package cli

import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"

"github.com/charmbracelet/lipgloss"
"github.com/ork-cli/ork/internal/config"
"github.com/ork-cli/ork/internal/git"
"github.com/ork-cli/ork/internal/ui"
"github.com/spf13/cobra"
)

var scanCmd = &cobra.Command{
Use: "scan",
Short: "Scan workspace directories for git repositories",
Long: `
Scan configured workspace directories to discover git repositories.

The scan results are cached for 24 hours to improve performance. Use --refresh to force a new scan.

Workspace directories can be configured in ~/.ork/config.yml:

workspaces:
- ~/code
- ~/projects
- ~/workspace

If no configuration exists, ork will scan default directories: ~/code, ~/projects, ~/workspace`,
RunE: runScan,
}

const (
bulletFormat = " • %s"
tableRowFormat = "%s %s %s\n"
)

var (
scanRefresh bool
)

func init() {
rootCmd.AddCommand(scanCmd)
scanCmd.Flags().BoolVar(&scanRefresh, "refresh", false, "Force a fresh scan, ignoring cache")
}

func runScan(cmd *cobra.Command, args []string) error {
// Load global config
globalConfig, err := config.LoadGlobal()
if err != nil {
return fmt.Errorf("failed to load global config: %w", err)
}

// Try to load from cache if not refreshing
if !scanRefresh {
if repos := tryLoadCache(globalConfig.Workspaces); repos != nil {
return nil // Cache was loaded and displayed
}
}

// Invalidate cache if refreshing
if scanRefresh {
if err := git.InvalidateCache(); err != nil {
return fmt.Errorf("failed to invalidate cache: %w", err)
}
}

// Filter and validate workspaces
existingWorkspaces := filterExistingWorkspaces(globalConfig.Workspaces)
if len(existingWorkspaces) == 0 {
return handleNoWorkspaces(globalConfig.Workspaces)
}

// Display scanning message
displayScanningMessage(existingWorkspaces)

// Perform discovery
repos, elapsed, err := performDiscovery(globalConfig.Workspaces)
if err != nil {
return err
}

// Save to cache (non-fatal if it fails)
saveCacheIfPossible(repos)

// Display results
displayResults(repos, elapsed, globalConfig.Workspaces)

return nil
}

func tryLoadCache(workspaces []string) []git.Repository {
cached, err := git.LoadCache()
if err == nil && cached != nil {
ui.Success("Loaded repositories from cache")
printRepositories(cached, workspaces)
fmt.Println()
fmt.Println(ui.Dim("Use 'ork scan --refresh' to force a fresh scan"))
return cached
}
return nil
}

func filterExistingWorkspaces(workspaces []string) []string {
existing := []string{}
for _, workspace := range workspaces {
if workspaceExists(workspace) {
existing = append(existing, workspace)
}
}
return existing
}

func workspaceExists(workspace string) bool {
// Expand ~ to the home directory
expandedPath := workspace
if strings.HasPrefix(workspace, "~/") {
home, err := os.UserHomeDir()
if err == nil {
expandedPath = filepath.Join(home, workspace[2:])
}
}

// Check if the directory exists
_, err := os.Stat(expandedPath)
return err == nil
}

func handleNoWorkspaces(configuredWorkspaces []string) error {
ui.Warning("No workspace directories found")
fmt.Println()
fmt.Println("Configure workspaces in ~/.ork/config.yml or ensure these directories exist:")
for _, workspace := range configuredWorkspaces {
fmt.Println(ui.Dim(fmt.Sprintf(bulletFormat, workspace)))
}
return nil
}

func displayScanningMessage(workspaces []string) {
ui.Info(fmt.Sprintf("Scanning %d workspace(s)...", len(workspaces)))
for _, workspace := range workspaces {
fmt.Println(ui.Dim(fmt.Sprintf(bulletFormat, workspace)))
}
fmt.Println()
}

func performDiscovery(workspaces []string) ([]git.Repository, time.Duration, error) {
start := time.Now()
repos, err := git.DiscoverRepositories(workspaces, 3)
if err != nil {
return nil, 0, fmt.Errorf("failed to discover repositories: %w", err)
}
elapsed := time.Since(start)
return repos, elapsed, nil
}

func saveCacheIfPossible(repos []git.Repository) {
if err := git.SaveCache(repos); err != nil {
ui.Warning(fmt.Sprintf("Warning: Failed to save cache: %v", err))
}
}

func displayResults(repos []git.Repository, elapsed time.Duration, workspaces []string) {
ui.Success(fmt.Sprintf("Found %d repositories in %v", len(repos), elapsed.Round(time.Millisecond)))
fmt.Println()
printRepositories(repos, workspaces)
}

func printRepositories(repos []git.Repository, workspaces []string) {
if len(repos) == 0 {
ui.Warning("No git repositories found")
fmt.Println()
fmt.Println("Make sure you have repositories in your workspace directories:")
for _, workspace := range workspaces {
fmt.Println(ui.Dim(fmt.Sprintf(bulletFormat, workspace)))
}
return
}

// Sort repositories by name
sort.Slice(repos, func(i, j int) bool {
return repos[i].Name < repos[j].Name
})

// Create header style
headerStyle := lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("12"))

// Calculate column widths
nameWidth := len("NAME")
pathWidth := len("PATH")
urlWidth := len("GIT URL")

for _, repo := range repos {
if len(repo.Name) > nameWidth {
nameWidth = len(repo.Name)
}
if len(repo.Path) > pathWidth {
pathWidth = len(repo.Path)
}
if len(repo.URL) > urlWidth {
urlWidth = len(repo.URL)
}
}

// Limit max widths
if nameWidth > 30 {
nameWidth = 30
}
if pathWidth > 60 {
pathWidth = 60
}
if urlWidth > 60 {
urlWidth = 60
}

// Print header (pad first, then style)
fmt.Printf(tableRowFormat,
headerStyle.Render(padRight("NAME", nameWidth)),
headerStyle.Render(padRight("PATH", pathWidth)),
headerStyle.Render(padRight("GIT URL", urlWidth)))

// Print separator
separatorStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("8"))
fmt.Printf(tableRowFormat,
separatorStyle.Render(repeatChar("─", nameWidth)),
separatorStyle.Render(repeatChar("─", pathWidth)),
separatorStyle.Render(repeatChar("─", urlWidth)))

// Print repositories
nameStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("14")).Bold(true)
pathStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("8"))
urlStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("6"))

for _, repo := range repos {
name := truncate(repo.Name, nameWidth)
path := truncate(repo.Path, pathWidth)
url := truncate(repo.URL, urlWidth)

// Pad first, then style - this keeps alignment correct
fmt.Printf(tableRowFormat,
nameStyle.Render(padRight(name, nameWidth)),
pathStyle.Render(padRight(path, pathWidth)),
urlStyle.Render(padRight(url, urlWidth)))
}
}

func truncate(s string, maxLen int) string {
if len(s) <= maxLen {
return s
}
if maxLen <= 3 {
return s[:maxLen]
}
return s[:maxLen-3] + "..."
}

func padRight(s string, width int) string {
if len(s) >= width {
return s
}
return s + repeatChar(" ", width-len(s))
}

func repeatChar(char string, count int) string {
result := ""
for i := 0; i < count; i++ {
result += char
}
return result
}
5 changes: 5 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,8 @@ type HealthCheck struct {
Timeout string `yaml:"timeout"` // Request timeout (e.g., 3s)
Retries int `yaml:"retries"` // Number of retries before unhealthy
}

// GlobalConfig represents the global ~/.ork/config.yml file structure
type GlobalConfig struct {
Workspaces []string `yaml:"workspaces"` // List of workspace directories to scan for git repos
}
Loading