Make gh gist view and edit commands reuse logic for id extraction

This commit is contained in:
Cristian Dominguez 2020-09-21 21:28:04 -03:00
parent d685d666b2
commit 55a8f3d8ca
3 changed files with 28 additions and 15 deletions

View file

@ -6,7 +6,6 @@ import (
"errors"
"fmt"
"net/http"
"net/url"
"sort"
"strings"
@ -69,11 +68,12 @@ func NewCmdEdit(f *cmdutil.Factory, runF func(*EditOptions) error) *cobra.Comman
func editRun(opts *EditOptions) error {
gistID := opts.Selector
u, err := url.Parse(opts.Selector)
if err == nil {
if strings.HasPrefix(u.Path, "/") {
gistID = u.Path[1:]
if strings.Contains(gistID, "/") {
id, err := shared.GistIDFromURL(gistID)
if err != nil {
return err
}
gistID = id
}
client, err := opts.HttpClient()

View file

@ -3,6 +3,8 @@ package shared
import (
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/cli/cli/api"
@ -37,3 +39,20 @@ func GetGist(client *http.Client, hostname, gistID string) (*Gist, error) {
return &gist, nil
}
func GistIDFromURL(gistURL string) (string, error) {
u, err := url.Parse(gistURL)
if err == nil && strings.HasPrefix(u.Path, "/") {
split := strings.Split(u.Path, "/")
if len(split) > 2 {
return split[2], nil
}
if len(split) == 2 && split[1] != "" {
return split[1], nil
}
}
return "", fmt.Errorf("Invalid gist URL %s", u)
}

View file

@ -3,7 +3,6 @@ package view
import (
"fmt"
"net/http"
"net/url"
"sort"
"strings"
@ -72,16 +71,11 @@ func viewRun(opts *ViewOptions) error {
}
if strings.Contains(gistID, "/") {
u, err := url.Parse(opts.Selector)
if err == nil && strings.HasPrefix(u.Path, "/") {
split := strings.Split(u.Path, "/")
if len(split) > 2 && split[2] != "" {
gistID = strings.Split(u.Path, "/")[2]
} else {
return fmt.Errorf("Invalid gist URL %s", u)
}
id, err := shared.GistIDFromURL(gistID)
if err != nil {
return err
}
gistID = id
}
client, err := opts.HttpClient()