Add more command shorthands #307

Merged
6543 merged 2 commits from noerw/tea:aliases into master 2020-12-16 16:47:41 +00:00
33 changed files with 228 additions and 128 deletions
Showing only changes of commit 753d9b3c9e - Show all commits

View File

@ -31,6 +31,9 @@ brew install tea
Distribution packages exist for: **alpinelinux ([tea](https://pkgs.alpinelinux.org/packages?name=tea&branch=edge))** and **archlinux ([gitea-tea](https://aur.archlinux.org/packages/gitea-tea))**
Shell completion can be added via `tea autocomplete --install`.
## Usage
First of all, you have to create a token on your `personal settings -> application` page of your gitea instance.

105
cmd/autocomplete.go Normal file
View File

@ -0,0 +1,105 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package cmd
import (
"fmt"
"io"
"net/http"
"os"
"os/exec"
"github.com/adrg/xdg"
"github.com/urfave/cli/v2"
)
// CmdAutocomplete manages autocompletion
var CmdAutocomplete = cli.Command{
Name: "shellcompletion",
Aliases: []string{"autocomplete"},
Usage: "Install shell completion for tea",
Description: "Install shell completion for tea",
ArgsUsage: "<shell type> (bash, zsh, powershell)",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "install",
Usage: "Persist in shell config instead of printing commands",
},
},
Action: runAutocompleteAdd,
}
func runAutocompleteAdd(ctx *cli.Context) error {
var remoteFile, localFile, cmds string
shell := ctx.Args().First()
switch shell {
case "zsh":
remoteFile = "contrib/autocomplete.zsh"
localFile = "autocomplete.zsh"
cmds = "echo 'PROG=tea _CLI_ZSH_AUTOCOMPLETE_HACK=1 source %s' >> ~/.zshrc && source ~/.zshrc"
case "bash":
remoteFile = "contrib/autocomplete.sh"
localFile = "autocomplete.sh"
cmds = "echo 'PROG=tea source %s' >> ~/.bashrc && source ~/.bashrc"
case "powershell":
remoteFile = "contrib/autocomplete.ps1"
localFile = "tea.ps1"
cmds = "\"& %s\" >> $profile"
default:
return fmt.Errorf("Must specify valid shell type")
}
localPath, err := xdg.ConfigFile("tea/" + localFile)
if err != nil {
return err
}
cmds = fmt.Sprintf(cmds, localPath)
if err := saveAutoCompleteFile(remoteFile, localPath); err != nil {
return err
}
if ctx.Bool("install") {
fmt.Println("Installing in your shellrc")
installer := exec.Command(shell, "-c", cmds)
if shell == "powershell" {
installer = exec.Command("powershell.exe", "-Command", cmds)
}
out, err := installer.CombinedOutput()
if err != nil {
return fmt.Errorf("Couldn't run the commands: %s %s", err, out)
}
} else {
fmt.Println("\n# Run the following commands to install autocompletion (or use --install)")
fmt.Println(cmds)
}
return nil
}
func saveAutoCompleteFile(file, destPath string) error {
url := fmt.Sprintf("https://gitea.com/gitea/tea/raw/branch/master/%s", file)
fmt.Println("Fetching " + url)
res, err := http.Get(url)
if err != nil {
return err
}
defer res.Body.Close()
writer, err := os.Create(destPath)
if err != nil {
return err
}
defer writer.Close()
_, err = io.Copy(writer, res.Body)
return err
}

View File

@ -5,7 +5,7 @@
package issues
import (
"log"
"fmt"
"code.gitea.io/tea/cmd/flags"
"code.gitea.io/tea/modules/context"
@ -34,7 +34,7 @@ func editIssueState(cmd *cli.Context, opts gitea.EditIssueOption) error {
ctx := context.InitCommand(cmd)
ctx.Ensure(context.CtxRequirement{RemoteRepo: true})
if ctx.Args().Len() == 0 {
log.Fatal(ctx.Command.ArgsUsage)
return fmt.Errorf(ctx.Command.ArgsUsage)
}
index, err := utils.ArgToIndex(ctx.Args().First())

View File

@ -5,8 +5,6 @@
package issues
import (
"log"
"code.gitea.io/tea/cmd/flags"
"code.gitea.io/tea/modules/context"
"code.gitea.io/tea/modules/print"
@ -47,7 +45,7 @@ func RunIssuesList(cmd *cli.Context) error {
})
if err != nil {
log.Fatal(err)
return err
}
print.IssuesList(issues, ctx.Output)

View File

@ -5,7 +5,7 @@
package cmd
import (
"log"
"fmt"
"code.gitea.io/tea/cmd/labels"
"github.com/urfave/cli/v2"
@ -34,6 +34,5 @@ func runLabels(ctx *cli.Context) error {
}
func runLabelsDetails(ctx *cli.Context) error {
log.Fatal("Not yet implemented.")
return nil
return fmt.Errorf("Not yet implemented")
}

View File

@ -81,11 +81,7 @@ func runLabelCreate(cmd *cli.Context) error {
}
}
if err != nil {
log.Fatal(err)
}
return nil
return err
}
func splitLabelLine(line string) (string, string, string) {

View File

@ -5,8 +5,6 @@
package labels
import (
"log"
"code.gitea.io/tea/modules/context"
"github.com/urfave/cli/v2"
@ -32,9 +30,5 @@ func runLabelDelete(cmd *cli.Context) error {
ctx.Ensure(context.CtxRequirement{RemoteRepo: true})
_, err := ctx.Login.Client().DeleteLabel(ctx.Owner, ctx.Repo, ctx.Int64("id"))
if err != nil {
log.Fatal(err)
}
return nil
return err
}

View File

@ -5,8 +5,6 @@
package labels
import (
"log"
"code.gitea.io/tea/cmd/flags"
"code.gitea.io/tea/modules/context"
"code.gitea.io/tea/modules/print"
@ -44,7 +42,7 @@ func RunLabelsList(cmd *cli.Context) error {
ListOptions: ctx.GetListOptions(),
})
if err != nil {
log.Fatal(err)
return err
}
if ctx.IsSet("save") {

View File

@ -5,8 +5,6 @@
package labels
import (
"log"
"code.gitea.io/tea/modules/context"
"code.gitea.io/sdk/gitea"
@ -68,7 +66,7 @@ func runLabelUpdate(cmd *cli.Context) error {
})
if err != nil {
log.Fatal(err)
return err
}
return nil

View File

@ -5,8 +5,6 @@
package login
import (
"log"
"code.gitea.io/tea/cmd/flags"
"code.gitea.io/tea/modules/config"
"code.gitea.io/tea/modules/print"
@ -28,7 +26,7 @@ var CmdLoginList = cli.Command{
func RunLoginList(cmd *cli.Context) error {
logins, err := config.GetLogins()
if err != nil {
log.Fatal(err)
return err
}
print.LoginsList(logins, cmd.String("output"))
return nil

View File

@ -6,7 +6,6 @@ package milestones
import (
"fmt"
"log"
"code.gitea.io/tea/cmd/flags"
"code.gitea.io/tea/modules/context"
@ -63,7 +62,7 @@ func runMilestonesCreate(cmd *cli.Context) error {
State: state,
})
if err != nil {
log.Fatal(err)
return err
}
print.MilestoneDetails(mile)

View File

@ -5,8 +5,6 @@
package milestones
import (
"log"
"code.gitea.io/tea/cmd/flags"
"code.gitea.io/tea/modules/context"
"code.gitea.io/tea/modules/print"
@ -53,7 +51,7 @@ func RunMilestonesList(cmd *cli.Context) error {
})
if err != nil {
log.Fatal(err)
return err
}
print.MilestonesList(milestones, ctx.Output, state)

View File

@ -5,8 +5,6 @@
package cmd
import (
"log"
"code.gitea.io/tea/cmd/flags"
"code.gitea.io/tea/modules/context"
"code.gitea.io/tea/modules/print"
@ -76,7 +74,7 @@ func runNotifications(cmd *cli.Context) error {
})
}
if err != nil {
log.Fatal(err)
return err
}
print.NotificationsList(news, ctx.Output, ctx.Bool("all"))

View File

@ -5,7 +5,6 @@
package cmd
import (
"log"
"path"
"strings"
@ -43,12 +42,11 @@ func runOpen(cmd *cli.Context) error {
case strings.EqualFold(number, "commits"):
repo, err := local_git.RepoForWorkdir()
if err != nil {
log.Fatal(err)
return err
}
b, err := repo.Head()
if err != nil {
log.Fatal(err)
return nil
return err
}
name := b.Name()
switch {
@ -75,11 +73,6 @@ func runOpen(cmd *cli.Context) error {
suffix = number
}
u := path.Join(ctx.Login.URL, ctx.RepoSlug, suffix)
err := open.Run(u)
if err != nil {
log.Fatal(err)
}
return nil
u := path.Join(ctx.Login.URL, ctx.Owner, ctx.Repo, suffix)
return open.Run(u)
}

View File

@ -5,7 +5,7 @@
package cmd
import (
"log"
"fmt"
"code.gitea.io/tea/cmd/organizations"
@ -34,7 +34,5 @@ func runOrganizations(ctx *cli.Context) error {
}
func runOrganizationDetail(path string) error {
log.Fatal("Not yet implemented.")
return nil
return fmt.Errorf("Not yet implemented")
}

View File

@ -5,7 +5,7 @@
package organizations
import (
"log"
"fmt"
"code.gitea.io/tea/modules/context"
"github.com/urfave/cli/v2"
@ -28,14 +28,12 @@ func RunOrganizationDelete(cmd *cli.Context) error {
client := ctx.Login.Client()
if ctx.Args().Len() < 1 {
log.Fatal("You have to specify the organization name you want to delete.")
return nil
return fmt.Errorf("You have to specify the organization name you want to delete")
}
response, err := client.DeleteOrg(ctx.Args().First())
if response != nil && response.StatusCode == 404 {
log.Fatal("The given organization does not exist.")
return nil
return fmt.Errorf("The given organization does not exist")
}
return err

View File

@ -5,8 +5,6 @@
package organizations
import (
"log"
"code.gitea.io/tea/cmd/flags"
"code.gitea.io/tea/modules/context"
"code.gitea.io/tea/modules/print"
@ -37,7 +35,7 @@ func RunOrganizationList(cmd *cli.Context) error {
ListOptions: ctx.GetListOptions(),
})
if err != nil {
log.Fatal(err)
return err
}
print.OrganizationsList(userOrganizations, ctx.Output)

View File

@ -5,7 +5,7 @@
package pulls
import (
"log"
"fmt"
"code.gitea.io/tea/cmd/flags"
"code.gitea.io/tea/modules/context"
@ -31,7 +31,7 @@ func runPullsCheckout(cmd *cli.Context) error {
ctx := context.InitCommand(cmd)
ctx.Ensure(context.CtxRequirement{LocalRepo: true})
if ctx.Args().Len() != 1 {
log.Fatal("Must specify a PR index")
return fmt.Errorf("Must specify a PR index")
}
idx, err := utils.ArgToIndex(ctx.Args().First())
if err != nil {

View File

@ -5,8 +5,6 @@
package pulls
import (
"log"
"code.gitea.io/tea/cmd/flags"
"code.gitea.io/tea/modules/context"
"code.gitea.io/tea/modules/print"
@ -45,7 +43,7 @@ func RunPullsList(cmd *cli.Context) error {
})
if err != nil {
log.Fatal(err)
return err
}
print.PullsList(prs, ctx.Output)

View File

@ -6,7 +6,6 @@ package releases
import (
"fmt"
"log"
"net/http"
"os"
"path/filepath"
@ -77,24 +76,23 @@ func runReleaseCreate(cmd *cli.Context) error {
if err != nil {
if resp != nil && resp.StatusCode == http.StatusConflict {
fmt.Println("error: There already is a release for this tag")
return nil
return fmt.Errorf("There already is a release for this tag")
}
log.Fatal(err)
return err
}
for _, asset := range ctx.StringSlice("asset") {
var file *os.File
if file, err = os.Open(asset); err != nil {
log.Fatal(err)
return err
}
filePath := filepath.Base(asset)
if _, _, err = ctx.Login.Client().CreateReleaseAttachment(ctx.Owner, ctx.Repo, release.ID, file, filePath); err != nil {
file.Close()
log.Fatal(err)
return err
}
file.Close()

View File

@ -6,7 +6,6 @@ package releases
import (
"fmt"
"log"
"code.gitea.io/tea/cmd/flags"
"code.gitea.io/tea/modules/context"
@ -38,7 +37,7 @@ func RunReleasesList(cmd *cli.Context) error {
ListOptions: ctx.GetListOptions(),
})
if err != nil {
log.Fatal(err)
return err
}
print.ReleasesList(releases, ctx.Output)

View File

@ -5,7 +5,7 @@
package repos
import (
"log"
"fmt"
"strings"
"code.gitea.io/tea/cmd/flags"
@ -67,7 +67,7 @@ func runReposSearch(cmd *cli.Context) error {
if err != nil {
// HACK: the client does not return a response on 404, so we can't check res.StatusCode
if err.Error() != "404 Not Found" {
log.Fatal("could not find owner: ", err)
return fmt.Errorf("Could not find owner: %s", err)
}
// if owner is no org, its a user

View File

@ -6,7 +6,6 @@ package times
import (
"fmt"
"log"
"strings"
"time"
@ -42,20 +41,16 @@ func runTrackedTimesAdd(cmd *cli.Context) error {
issue, err := utils.ArgToIndex(ctx.Args().First())
if err != nil {
log.Fatal(err)
return err
}
duration, err := time.ParseDuration(strings.Join(ctx.Args().Tail(), ""))
if err != nil {
log.Fatal(err)
return err
}
_, _, err = ctx.Login.Client().AddTime(ctx.Owner, ctx.Repo, issue, gitea.AddTimeOption{
Time: int64(duration.Seconds()),
})
if err != nil {
log.Fatal(err)
}
return nil
return err
}

View File

@ -6,7 +6,6 @@ package times
import (
"fmt"
"log"
"strconv"
"code.gitea.io/tea/cmd/flags"
@ -37,18 +36,14 @@ func runTrackedTimesDelete(cmd *cli.Context) error {
issue, err := utils.ArgToIndex(ctx.Args().First())
if err != nil {
log.Fatal(err)
return err
}
timeID, err := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
if err != nil {
log.Fatal(err)
return err
}
_, err = client.DeleteTime(ctx.Owner, ctx.Repo, issue, timeID)
if err != nil {
log.Fatal(err)
}
return nil
return err
}

View File

@ -6,7 +6,6 @@ package times
import (
"fmt"
"log"
"code.gitea.io/tea/cmd/flags"
"code.gitea.io/tea/modules/context"
@ -36,13 +35,9 @@ func runTrackedTimesReset(cmd *cli.Context) error {
issue, err := utils.ArgToIndex(ctx.Args().First())
if err != nil {
log.Fatal(err)
return err
}
_, err = client.ResetIssueTime(ctx.Owner, ctx.Repo, issue)
if err != nil {
log.Fatal(err)
}
return nil
return err
}

9
contrib/autocomplete.ps1 Normal file
View File

@ -0,0 +1,9 @@
$fn = $($MyInvocation.MyCommand.Name)
$name = $fn -replace "(.*)\.ps1$", '$1'
Register-ArgumentCompleter -Native -CommandName $name -ScriptBlock {
param($commandName, $wordToComplete, $cursorPosition)
$other = "$wordToComplete --generate-bash-completion"
Invoke-Expression $other | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
}
}

21
contrib/autocomplete.sh Normal file
View File

@ -0,0 +1,21 @@
#! /bin/bash
: ${PROG:=$(basename ${BASH_SOURCE})}
_cli_bash_autocomplete() {
if [[ "${COMP_WORDS[0]}" != "source" ]]; then
local cur opts base
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
if [[ "$cur" == "-"* ]]; then
opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} ${cur} --generate-bash-completion )
else
opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion )
fi
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
fi
}
complete -o bashdefault -o default -o nospace -F _cli_bash_autocomplete $PROG
unset PROG

23
contrib/autocomplete.zsh Normal file
View File

@ -0,0 +1,23 @@
#compdef $PROG
_cli_zsh_autocomplete() {
local -a opts
local cur
cur=${words[-1]}
if [[ "$cur" == "-"* ]]; then
opts=("${(@f)$(_CLI_ZSH_AUTOCOMPLETE_HACK=1 ${words[@]:0:#words[@]-1} ${cur} --generate-bash-completion)}")
else
opts=("${(@f)$(_CLI_ZSH_AUTOCOMPLETE_HACK=1 ${words[@]:0:#words[@]-1} --generate-bash-completion)}")
fi
if [[ "${opts[1]}" != "" ]]; then
_describe 'values' opts
else
_files
fi
return
}
compdef _cli_zsh_autocomplete $PROG

11
main.go
View File

@ -1,4 +1,4 @@
// Copyright 2018 The Gitea Authors. All rights reserved.
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
@ -6,7 +6,7 @@
package main // import "code.gitea.io/tea"
import (
"log"
"fmt"
"os"
"strings"
@ -25,7 +25,6 @@ func main() {
app := cli.NewApp()
app.Name = "tea"
app.Usage = "Command line tool to interact with Gitea"
app.Description = ``
app.Version = Version + formatBuiltWith(Tags)
app.Commands = []*cli.Command{
&cmd.CmdLogin,
@ -40,11 +39,15 @@ func main() {
&cmd.CmdNotifications,
&cmd.CmdMilestones,
&cmd.CmdOrgs,
&cmd.CmdAutocomplete,
}
app.EnableBashCompletion = true
err := app.Run(os.Args)
if err != nil {
log.Fatalf("Failed to run app with %s: %v", os.Args, err)
// app.Run already exits for errors implementing ErrorCoder,
// so we only handle generic errors with code 1 here.
fmt.Fprintf(app.ErrWriter, "Error: %v\n", err)
os.Exit(1)
}
}

View File

@ -6,7 +6,6 @@ package task
import (
"fmt"
"log"
"code.gitea.io/sdk/gitea"
"code.gitea.io/tea/modules/config"
@ -34,12 +33,12 @@ func CreateIssue(login *config.Login, repoOwner, repoName, title, description st
})
if err != nil {
log.Fatalf("could not create issue: %s", err)
return fmt.Errorf("could not create issue: %s", err)
}
print.IssueDetails(issue)
fmt.Println(issue.HTMLURL)
return err
return nil
}

View File

@ -6,7 +6,6 @@ package task
import (
"fmt"
"log"
"os"
"code.gitea.io/sdk/gitea"
@ -16,7 +15,7 @@ import (
func LabelsExport(labels []*gitea.Label, path string) error {
f, err := os.Create(path)
if err != nil {
log.Fatal(err)
return err
}
defer f.Close()

View File

@ -6,7 +6,6 @@ package task
import (
"fmt"
"log"
"os"
"time"
@ -21,7 +20,7 @@ func CreateLogin(name, token, user, passwd, sshKey, giteaURL string, insecure bo
// checks ...
// ... if we have a url
if len(giteaURL) == 0 {
log.Fatal("You have to input Gitea server URL")
return fmt.Errorf("You have to input Gitea server URL")
}
// ... if there already exist a login with same name
@ -35,17 +34,17 @@ func CreateLogin(name, token, user, passwd, sshKey, giteaURL string, insecure bo
// .. if we have enough information to authenticate
if len(token) == 0 && (len(user)+len(passwd)) == 0 {
log.Fatal("No token set")
return fmt.Errorf("No token set")
} else if len(user) != 0 && len(passwd) == 0 {
log.Fatal("No password set")
return fmt.Errorf("No password set")
} else if len(user) == 0 && len(passwd) != 0 {
log.Fatal("No user set")
return fmt.Errorf("No user set")
}
// Normalize URL
serverURL, err := utils.NormalizeURL(giteaURL)
if err != nil {
log.Fatal("Unable to parse URL", err)
return fmt.Errorf("Unable to parse URL: %s", err)
}
login := config.Login{
@ -60,23 +59,21 @@ func CreateLogin(name, token, user, passwd, sshKey, giteaURL string, insecure bo
client := login.Client()
if len(token) == 0 {
login.Token, err = generateToken(client, user, passwd)
if err != nil {
log.Fatal(err)
if login.Token, err = generateToken(client, user, passwd); err != nil {
return err
}
}
// Verify if authentication works and get user info
u, _, err := client.GetMyUserInfo()
if err != nil {
log.Fatal(err)
return err
}
login.User = u.UserName
if len(login.Name) == 0 {
login.Name, err = GenerateLoginName(giteaURL, login.User)
if err != nil {
log.Fatal(err)
if login.Name, err = GenerateLoginName(giteaURL, login.User); err != nil {
return err
}
}
@ -91,9 +88,8 @@ func CreateLogin(name, token, user, passwd, sshKey, giteaURL string, insecure bo
}
}
err = config.AddLogin(&login)
if err != nil {
log.Fatal(err)
if err = config.AddLogin(&login); err != nil {
return err
}
fmt.Printf("Login as %s on %s successful. Added this login as %s\n", login.User, login.URL, login.Name)

View File

@ -6,7 +6,6 @@ package task
import (
"fmt"
"log"
"strings"
"code.gitea.io/sdk/gitea"
@ -24,14 +23,14 @@ func CreatePull(login *config.Login, repoOwner, repoName, base, head, title, des
// open local git repo
localRepo, err := local_git.RepoForWorkdir()
if err != nil {
log.Fatal("could not open local repo: ", err)
return fmt.Errorf("Could not open local repo: %s", err)
}
// push if possible
log.Println("git push")
fmt.Println("git push")
err = localRepo.Push(&git.PushOptions{})
if err != nil && err != git.NoErrAlreadyUpToDate {
log.Printf("Error occurred during 'git push':\n%s\n", err.Error())
fmt.Printf("Error occurred during 'git push':\n%s\n", err.Error())
}
// default is default branch
@ -74,7 +73,7 @@ func CreatePull(login *config.Login, repoOwner, repoName, base, head, title, des
})
if err != nil {
log.Fatalf("could not create PR from %s to %s:%s: %s", head, repoOwner, base, err)
return fmt.Errorf("Could not create PR from %s to %s:%s: %s", head, repoOwner, base, err)
}
print.PullDetails(pr, nil)