1package commands
2
3import (
4	"bufio"
5	"fmt"
6	"os"
7	"regexp"
8	"strings"
9
10	"github.com/github/hub/github"
11	"github.com/github/hub/ui"
12	"github.com/github/hub/utils"
13)
14
15var cmdDelete = &Command{
16	Run:   deleteRepo,
17	Usage: "delete [-y] [<ORGANIZATION>/]<NAME>",
18	Long: `Delete an existing repository on GitHub.
19
20## Options:
21
22	-y, --yes
23		Skip the confirmation prompt and immediately delete the repository.
24
25	[<ORGANIZATION>/]<NAME>
26		The name for the repository on GitHub.
27
28## Examples:
29		$ hub delete recipes
30		[ personal repo deleted on GitHub ]
31
32		$ hub delete sinatra/recipes
33		[ repo deleted in GitHub organization ]
34
35## See also:
36
37hub-init(1), hub(1)
38`,
39}
40
41func init() {
42	CmdRunner.Use(cmdDelete)
43}
44
45func deleteRepo(command *Command, args *Args) {
46	var repoName string
47	if !args.IsParamsEmpty() {
48		repoName = args.FirstParam()
49	}
50
51	re := regexp.MustCompile(NameWithOwnerRe)
52	if !re.MatchString(repoName) {
53		utils.Check(command.UsageError(""))
54	}
55
56	config := github.CurrentConfig()
57	host, err := config.DefaultHost()
58	if err != nil {
59		utils.Check(github.FormatError("deleting repository", err))
60	}
61
62	owner := host.User
63	if strings.Contains(repoName, "/") {
64		split := strings.SplitN(repoName, "/", 2)
65		owner, repoName = split[0], split[1]
66	}
67
68	project := github.NewProject(owner, repoName, host.Host)
69	gh := github.NewClient(project.Host)
70
71	if !args.Flag.Bool("--yes") {
72		ui.Printf("Really delete repository '%s' (yes/N)? ", project)
73		answer := ""
74		scanner := bufio.NewScanner(os.Stdin)
75		if scanner.Scan() {
76			answer = strings.TrimSpace(scanner.Text())
77		}
78		utils.Check(scanner.Err())
79		if answer != "yes" {
80			utils.Check(fmt.Errorf("Please type 'yes' for confirmation."))
81		}
82	}
83
84	if args.Noop {
85		ui.Printf("Would delete repository '%s'.\n", project)
86	} else {
87		err = gh.DeleteRepository(project)
88		if err != nil && strings.Contains(err.Error(), "HTTP 403") {
89			ui.Errorf("Please edit the token used for hub at https://%s/settings/tokens\n", project.Host)
90			ui.Errorln("and verify that the `delete_repo` scope is enabled.")
91		}
92		utils.Check(err)
93		ui.Printf("Deleted repository '%s'.\n", project)
94	}
95
96	args.NoForward()
97}
98