package cmd import ( "fmt" "os" "strings" "github.com/spf13/cobra" "github.com/spf13/viper" "codeberg.org/romaintb/fgj/internal/git" ) var cfgFile string var rootCmd = &cobra.Command{ Use: "fgj", Short: "Forgejo CLI tool - work seamlessly with Forgejo from the command line", Long: `fgj is a command line tool for Forgejo instances (including Codeberg). It brings pull requests, issues, and other Forgejo concepts to the terminal.`, Version: "0.2.0", } func Execute() error { return rootCmd.Execute() } func init() { cobra.OnInitialize(initConfig) rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.config/fgj/config.yaml)") rootCmd.PersistentFlags().String("hostname", "", "Forgejo instance hostname") _ = viper.BindPFlag("hostname", rootCmd.PersistentFlags().Lookup("hostname")) } func initConfig() { if cfgFile != "" { viper.SetConfigFile(cfgFile) } else { home, err := os.UserHomeDir() if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } configDir := home + "/.config/fgj" _ = os.MkdirAll(configDir, 0755) viper.AddConfigPath(configDir) viper.SetConfigType("yaml") viper.SetConfigName("config") } viper.AutomaticEnv() viper.SetEnvPrefix("FGJ") _ = viper.ReadInConfig() } // parseRepo parses the repository string in the format "owner/name". // If not provided, it attempts to auto-detect from the git repository. func parseRepo(repo string) (string, string, error) { // If repo flag is provided, use it if repo != "" { parts := strings.Split(repo, "/") if len(parts) != 2 { return "", "", fmt.Errorf("invalid repository format: %s (expected: owner/name)", repo) } return parts[0], parts[1], nil } // Try to auto-detect from git owner, name, err := git.DetectRepo() if err != nil { return "", "", fmt.Errorf("repository flag is required (use -R owner/name) or run from a git repository: %w", err) } return owner, name, nil } // getDetectedHost attempts to auto-detect the Forgejo instance hostname. // Returns empty string if detection fails, which will fall back to other methods. func getDetectedHost() string { host, err := git.DetectHost() if err != nil { return "" } return host }