Add gtea connect command for existing repos

Connects the current directory to a new Gitea repo — creates the remote,
adds the origin, and pushes. Sanitizes the folder name to meet Gitea's
AlphaDashDot naming rules.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-17 14:17:06 -04:00
parent b7ea167786
commit bd809d11d9

68
cmd/connect.go Normal file
View File

@@ -0,0 +1,68 @@
package cmd
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
gogitea "code.gitea.io/sdk/gitea"
"github.com/spf13/cobra"
)
var connectCmd = &cobra.Command{
Use: "connect",
Short: "Create a Gitea repo for the current directory and push",
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadConfig()
if err != nil {
return err
}
// Use current folder name as repo name
cwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("getting current directory: %w", err)
}
raw := filepath.Base(cwd)
// Gitea repo names: only alphanumeric, dash, dot — replace everything else with a dash
name := regexp.MustCompile(`[^a-zA-Z0-9.\-]`).ReplaceAllString(raw, "-")
name = strings.Trim(name, "-")
fmt.Printf("Using repo name: %s\n", name)
client, err := gogitea.NewClient(cfg.URL, gogitea.SetToken(cfg.Token))
if err != nil {
return fmt.Errorf("connecting to Gitea: %w", err)
}
repo, _, err := client.CreateRepo(gogitea.CreateRepoOption{
Name: name,
Description: repoDesc,
Private: repoPrivate,
AutoInit: false,
})
if err != nil {
return fmt.Errorf("creating Gitea repo: %w", err)
}
fmt.Println("Created Gitea repo:", repo.HTMLURL)
remote := authCloneURL(cfg, repo.CloneURL)
if err := runGit(".", "remote", "add", "origin", remote); err != nil {
return err
}
if err := runGit(".", "push", "-u", "origin", "main"); err != nil {
return err
}
fmt.Println("Pushed to:", repo.HTMLURL)
return nil
},
}
func init() {
connectCmd.Flags().BoolVarP(&repoPrivate, "private", "p", false, "Make the repo private")
connectCmd.Flags().StringVarP(&repoDesc, "desc", "d", "", "Repo description")
rootCmd.AddCommand(connectCmd)
}