Skip to content

Commit c34054b

Browse files
committed
isolate repo create command
1 parent 7512034 commit c34054b

File tree

13 files changed

+635
-518
lines changed

13 files changed

+635
-518
lines changed

api/queries_org.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"github.com/shurcooL/githubv4"
88
)
99

10+
// TODO clean up
1011
// using API v3 here because the equivalent in GraphQL needs `read:org` scope
1112
func resolveOrganization(client *Client, orgName string) (string, error) {
1213
var response struct {

api/queries_repo.go

Lines changed: 4 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ func GitHubRepo(client *Client, repo ghrepo.Interface) (*Repository, error) {
109109
return nil, err
110110
}
111111

112-
return initRepoHostname(&result.Repository, repo.RepoHost()), nil
112+
return InitRepoHostname(&result.Repository, repo.RepoHost()), nil
113113
}
114114

115115
func RepoDefaultBranch(client *Client, repo ghrepo.Interface) (string, error) {
@@ -250,15 +250,15 @@ func RepoNetwork(client *Client, repos []ghrepo.Interface) (RepoNetworkResult, e
250250
if err := decoder.Decode(&repo); err != nil {
251251
return result, err
252252
}
253-
result.Repositories = append(result.Repositories, initRepoHostname(&repo, hostname))
253+
result.Repositories = append(result.Repositories, InitRepoHostname(&repo, hostname))
254254
} else {
255255
return result, fmt.Errorf("unknown GraphQL result key %q", name)
256256
}
257257
}
258258
return result, nil
259259
}
260260

261-
func initRepoHostname(repo *Repository, hostname string) *Repository {
261+
func InitRepoHostname(repo *Repository, hostname string) *Repository {
262262
repo.hostname = hostname
263263
if repo.Parent != nil {
264264
repo.Parent.hostname = hostname
@@ -338,72 +338,11 @@ func RepoFindFork(client *Client, repo ghrepo.Interface) (*Repository, error) {
338338
// `affiliations` condition, to guard against versions of GitHub with a
339339
// faulty `affiliations` implementation
340340
if len(forks) > 0 && forks[0].ViewerCanPush() {
341-
return initRepoHostname(&forks[0], repo.RepoHost()), nil
341+
return InitRepoHostname(&forks[0], repo.RepoHost()), nil
342342
}
343343
return nil, &NotFoundError{errors.New("no fork found")}
344344
}
345345

346-
// RepoCreateInput represents input parameters for RepoCreate
347-
type RepoCreateInput struct {
348-
Name string `json:"name"`
349-
Visibility string `json:"visibility"`
350-
HomepageURL string `json:"homepageUrl,omitempty"`
351-
Description string `json:"description,omitempty"`
352-
353-
OwnerID string `json:"ownerId,omitempty"`
354-
TeamID string `json:"teamId,omitempty"`
355-
356-
HasIssuesEnabled bool `json:"hasIssuesEnabled"`
357-
HasWikiEnabled bool `json:"hasWikiEnabled"`
358-
}
359-
360-
// RepoCreate creates a new GitHub repository
361-
func RepoCreate(client *Client, input RepoCreateInput) (*Repository, error) {
362-
var response struct {
363-
CreateRepository struct {
364-
Repository Repository
365-
}
366-
}
367-
368-
if input.TeamID != "" {
369-
orgID, teamID, err := resolveOrganizationTeam(client, input.OwnerID, input.TeamID)
370-
if err != nil {
371-
return nil, err
372-
}
373-
input.TeamID = teamID
374-
input.OwnerID = orgID
375-
} else if input.OwnerID != "" {
376-
orgID, err := resolveOrganization(client, input.OwnerID)
377-
if err != nil {
378-
return nil, err
379-
}
380-
input.OwnerID = orgID
381-
}
382-
383-
variables := map[string]interface{}{
384-
"input": input,
385-
}
386-
387-
err := client.GraphQL(`
388-
mutation RepositoryCreate($input: CreateRepositoryInput!) {
389-
createRepository(input: $input) {
390-
repository {
391-
id
392-
name
393-
owner { login }
394-
url
395-
}
396-
}
397-
}
398-
`, variables, &response)
399-
if err != nil {
400-
return nil, err
401-
}
402-
403-
// FIXME: support Enterprise hosts
404-
return initRepoHostname(&response.CreateRepository.Repository, "github.com"), nil
405-
}
406-
407346
type RepoMetadataResult struct {
408347
AssignableUsers []RepoAssignee
409348
Labels []RepoLabel

api/queries_repo_test.go

Lines changed: 0 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,12 @@
11
package api
22

33
import (
4-
"bytes"
5-
"encoding/json"
6-
"io/ioutil"
74
"testing"
85

96
"github.com/cli/cli/internal/ghrepo"
107
"github.com/cli/cli/pkg/httpmock"
118
)
129

13-
func Test_RepoCreate(t *testing.T) {
14-
http := &httpmock.Registry{}
15-
client := NewClient(ReplaceTripper(http))
16-
17-
http.StubResponse(200, bytes.NewBufferString(`{}`))
18-
19-
input := RepoCreateInput{
20-
Description: "roasted chesnuts",
21-
HomepageURL: "http://example.com",
22-
}
23-
24-
_, err := RepoCreate(client, input)
25-
if err != nil {
26-
t.Fatalf("unexpected error: %v", err)
27-
}
28-
29-
if len(http.Requests) != 1 {
30-
t.Fatalf("expected 1 HTTP request, seen %d", len(http.Requests))
31-
}
32-
33-
var reqBody struct {
34-
Query string
35-
Variables struct {
36-
Input map[string]interface{}
37-
}
38-
}
39-
40-
bodyBytes, _ := ioutil.ReadAll(http.Requests[0].Body)
41-
_ = json.Unmarshal(bodyBytes, &reqBody)
42-
if description := reqBody.Variables.Input["description"].(string); description != "roasted chesnuts" {
43-
t.Errorf("expected description to be %q, got %q", "roasted chesnuts", description)
44-
}
45-
if homepage := reqBody.Variables.Input["homepageUrl"].(string); homepage != "http://example.com" {
46-
t.Errorf("expected homepageUrl to be %q, got %q", "http://example.com", homepage)
47-
}
48-
}
4910
func Test_RepoMetadata(t *testing.T) {
5011
http := &httpmock.Registry{}
5112
client := NewClient(ReplaceTripper(http))

command/repo.go

Lines changed: 3 additions & 176 deletions
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,20 @@ import (
44
"errors"
55
"fmt"
66
"net/url"
7-
"os"
8-
"path"
97
"strings"
108
"time"
119

12-
"github.com/AlecAivazis/survey/v2"
1310
"github.com/MakeNowJust/heredoc"
1411
"github.com/cli/cli/api"
1512
"github.com/cli/cli/git"
1613
"github.com/cli/cli/internal/ghrepo"
1714
"github.com/cli/cli/internal/run"
15+
"github.com/cli/cli/pkg/prompt"
1816
"github.com/cli/cli/utils"
1917
"github.com/spf13/cobra"
2018
)
2119

2220
func init() {
23-
repoCmd.AddCommand(repoCreateCmd)
24-
repoCreateCmd.Flags().StringP("description", "d", "", "Description of repository")
25-
repoCreateCmd.Flags().StringP("homepage", "h", "", "Repository home page URL")
26-
repoCreateCmd.Flags().StringP("team", "t", "", "The name of the organization team to be granted access")
27-
repoCreateCmd.Flags().Bool("enable-issues", true, "Enable issues in the new repository")
28-
repoCreateCmd.Flags().Bool("enable-wiki", true, "Enable wiki in the new repository")
29-
repoCreateCmd.Flags().Bool("public", false, "Make the new repository public (default: private)")
30-
3121
repoCmd.AddCommand(repoForkCmd)
3222
repoForkCmd.Flags().String("clone", "prompt", "Clone fork: {true|false|prompt}")
3323
repoForkCmd.Flags().String("remote", "prompt", "Add remote for fork: {true|false|prompt}")
@@ -55,26 +45,6 @@ A repository can be supplied as an argument in any of the following formats:
5545
- by URL, e.g. "https://github.com/OWNER/REPO"`},
5646
}
5747

58-
var repoCreateCmd = &cobra.Command{
59-
Use: "create [<name>]",
60-
Short: "Create a new repository",
61-
Long: `Create a new GitHub repository.`,
62-
Example: heredoc.Doc(`
63-
# create a repository under your account using the current directory name
64-
$ gh repo create
65-
66-
# create a repository with a specific name
67-
$ gh repo create my-project
68-
69-
# create a repository in an organization
70-
$ gh repo create cli/my-project
71-
`),
72-
Annotations: map[string]string{"help:arguments": `A repository can be supplied as an argument in any of the following formats:
73-
- <OWNER/REPO>
74-
- by URL, e.g. "https://github.com/OWNER/REPO"`},
75-
RunE: repoCreate,
76-
}
77-
7848
var repoForkCmd = &cobra.Command{
7949
Use: "fork [<repository>]",
8050
Short: "Create a fork of a repository",
@@ -105,141 +75,6 @@ var repoCreditsCmd = &cobra.Command{
10575
Hidden: true,
10676
}
10777

108-
func repoCreate(cmd *cobra.Command, args []string) error {
109-
projectDir, projectDirErr := git.ToplevelDir()
110-
111-
orgName := ""
112-
teamSlug, err := cmd.Flags().GetString("team")
113-
if err != nil {
114-
return err
115-
}
116-
117-
var name string
118-
if len(args) > 0 {
119-
name = args[0]
120-
if strings.Contains(name, "/") {
121-
newRepo, err := ghrepo.FromFullName(name)
122-
if err != nil {
123-
return fmt.Errorf("argument error: %w", err)
124-
}
125-
orgName = newRepo.RepoOwner()
126-
name = newRepo.RepoName()
127-
}
128-
} else {
129-
if projectDirErr != nil {
130-
return projectDirErr
131-
}
132-
name = path.Base(projectDir)
133-
}
134-
135-
isPublic, err := cmd.Flags().GetBool("public")
136-
if err != nil {
137-
return err
138-
}
139-
hasIssuesEnabled, err := cmd.Flags().GetBool("enable-issues")
140-
if err != nil {
141-
return err
142-
}
143-
hasWikiEnabled, err := cmd.Flags().GetBool("enable-wiki")
144-
if err != nil {
145-
return err
146-
}
147-
description, err := cmd.Flags().GetString("description")
148-
if err != nil {
149-
return err
150-
}
151-
homepage, err := cmd.Flags().GetString("homepage")
152-
if err != nil {
153-
return err
154-
}
155-
156-
// TODO: move this into constant within `api`
157-
visibility := "PRIVATE"
158-
if isPublic {
159-
visibility = "PUBLIC"
160-
}
161-
162-
input := api.RepoCreateInput{
163-
Name: name,
164-
Visibility: visibility,
165-
OwnerID: orgName,
166-
TeamID: teamSlug,
167-
Description: description,
168-
HomepageURL: homepage,
169-
HasIssuesEnabled: hasIssuesEnabled,
170-
HasWikiEnabled: hasWikiEnabled,
171-
}
172-
173-
ctx := contextForCommand(cmd)
174-
client, err := apiClientForContext(ctx)
175-
if err != nil {
176-
return err
177-
}
178-
179-
repo, err := api.RepoCreate(client, input)
180-
if err != nil {
181-
return err
182-
}
183-
184-
out := cmd.OutOrStdout()
185-
greenCheck := utils.Green("✓")
186-
isTTY := false
187-
if outFile, isFile := out.(*os.File); isFile {
188-
isTTY = utils.IsTerminal(outFile)
189-
if isTTY {
190-
// FIXME: duplicates colorableOut
191-
out = utils.NewColorable(outFile)
192-
}
193-
}
194-
195-
if isTTY {
196-
fmt.Fprintf(out, "%s Created repository %s on GitHub\n", greenCheck, ghrepo.FullName(repo))
197-
} else {
198-
fmt.Fprintln(out, repo.URL)
199-
}
200-
201-
remoteURL := formatRemoteURL(cmd, repo)
202-
203-
if projectDirErr == nil {
204-
_, err = git.AddRemote("origin", remoteURL)
205-
if err != nil {
206-
return err
207-
}
208-
if isTTY {
209-
fmt.Fprintf(out, "%s Added remote %s\n", greenCheck, remoteURL)
210-
}
211-
} else if isTTY {
212-
doSetup := false
213-
err := Confirm(fmt.Sprintf("Create a local project directory for %s?", ghrepo.FullName(repo)), &doSetup)
214-
if err != nil {
215-
return err
216-
}
217-
218-
if doSetup {
219-
path := repo.Name
220-
221-
gitInit := git.GitCommand("init", path)
222-
gitInit.Stdout = os.Stdout
223-
gitInit.Stderr = os.Stderr
224-
err = run.PrepareCmd(gitInit).Run()
225-
if err != nil {
226-
return err
227-
}
228-
gitRemoteAdd := git.GitCommand("-C", path, "remote", "add", "origin", remoteURL)
229-
gitRemoteAdd.Stdout = os.Stdout
230-
gitRemoteAdd.Stderr = os.Stderr
231-
err = run.PrepareCmd(gitRemoteAdd).Run()
232-
if err != nil {
233-
return err
234-
}
235-
236-
fmt.Fprintf(out, "%s Initialized repository in './%s/'\n", greenCheck, path)
237-
}
238-
}
239-
240-
return nil
241-
}
242-
24378
var Since = func(t time.Time) time.Duration {
24479
return time.Since(t)
24580
}
@@ -371,7 +206,7 @@ func repoFork(cmd *cobra.Command, args []string) error {
371206

372207
remoteDesired := remotePref == "true"
373208
if remotePref == "prompt" {
374-
err = Confirm("Would you like to add a remote for the fork?", &remoteDesired)
209+
err = prompt.Confirm("Would you like to add a remote for the fork?", &remoteDesired)
375210
if err != nil {
376211
return fmt.Errorf("failed to prompt: %w", err)
377212
}
@@ -409,7 +244,7 @@ func repoFork(cmd *cobra.Command, args []string) error {
409244
} else {
410245
cloneDesired := clonePref == "true"
411246
if clonePref == "prompt" {
412-
err = Confirm("Would you like to clone the fork?", &cloneDesired)
247+
err = prompt.Confirm("Would you like to clone the fork?", &cloneDesired)
413248
if err != nil {
414249
return fmt.Errorf("failed to prompt: %w", err)
415250
}
@@ -447,14 +282,6 @@ func repoFork(cmd *cobra.Command, args []string) error {
447282
return nil
448283
}
449284

450-
var Confirm = func(prompt string, result *bool) error {
451-
p := &survey.Confirm{
452-
Message: prompt,
453-
Default: true,
454-
}
455-
return survey.AskOne(p, result)
456-
}
457-
458285
func repoCredits(cmd *cobra.Command, args []string) error {
459286
return credits(cmd, args)
460287
}

0 commit comments

Comments
 (0)