Skip to content
Merged
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
44 changes: 33 additions & 11 deletions cmd/gitx/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ package main
import (
"errors"
"fmt"
"log"
"os"
"os/exec"

tea "github.com/charmbracelet/bubbletea"
"github.com/gitxtui/gitx/internal/git"
gitxlog "github.com/gitxtui/gitx/internal/log"
"github.com/gitxtui/gitx/internal/tui"
zone "github.com/lrstanley/bubblezone"
"log"
"os"
"os/exec"
)

var version = "dev"
Expand All @@ -22,8 +24,10 @@ func printHelp() {
fmt.Println("Options:")
fmt.Println(" -v, --version Show version information")
fmt.Println(" -h, --help Show this help message")
fmt.Println(" -i, --init Initialize a new Git repository")
fmt.Println()
fmt.Println("Run 'gitx' inside a Git repository to start the TUI.")
fmt.Println("Or run 'gitx -i' to initialize a new Git repository in the current directory.")
}

func main() {
Expand All @@ -37,11 +41,8 @@ func main() {
}
}()

if err := ensureGitRepo(); err != nil {
fmt.Fprintln(os.Stderr, err) // print to stderr
os.Exit(1)
}

// Parse flags
shouldInit := false
if len(os.Args) > 1 {
switch os.Args[1] {
case "--version", "-v":
Expand All @@ -50,9 +51,17 @@ func main() {
case "--help", "-h":
printHelp()
return
case "--init", "-i":
shouldInit = true
}
}

// Ensure git repo exists (initialize if flag is set)
if err := ensureGitRepo(shouldInit); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}

zone.NewGlobal()
defer zone.Close()

Expand All @@ -66,10 +75,23 @@ func main() {
fmt.Println("Bye from gitx! :)")
}

func ensureGitRepo() error {
func ensureGitRepo(shouldInit bool) error {
cmd := exec.Command("git", "rev-parse", "--is-inside-work-tree")
if err := cmd.Run(); err != nil {
return fmt.Errorf("error: not a git repository")
if err := cmd.Run(); err == nil {
return nil // Already inside a git repo
}

if !shouldInit {
return fmt.Errorf("error: not a git repository\nrun gitx -i/--init to initialize a new git repository and open gitx")
}

// Initialize a new git repository
g := &git.GitCommands{}
_, err := g.InitRepository(".")
if err != nil {
return fmt.Errorf("failed to initialize git repository: %w", err)
}

fmt.Println("Initialized new git repository in current directory")
return nil
}