Repository: cli/cli
Pull request #7916 (2023-08-30 16:47:33)

mark and unmark project as template
Closes https://github.com/cli/cli/issues/7915

Tested:
1. command shows up in project commands
```
go run cmd/gh/main.go project -h
...
AVAILABLE COMMANDS
...
template:    Mark a project as a template
```

2. Mark a project as a template
```
go run cmd/gh/main.go project template 1 --owner "github"
# Marked project 104 as a template.
```

3. Unmark a project as a template with `--undo`
```
go run cmd/gh/main.go project template 1 --owner "github" --undo
# Unmarked project 104 as a template.
```

4. JSON format and addition of `template` field tested with the following commands
```
# mark project
go run cmd/gh/main.go project template 1 --owner "github" --format json | jq .

# view project
go run cmd/gh/main.go project view 1 --owner "github"  --format json | jq .
```

**Caveats:**

a. These mutations only work with org owned projects as called out in the [docs](https://docs.github.com/en/graphql/reference/mutations#markprojectv2astemplate). Attempting to mark a user project as a template returns an error
```
go run cmd/gh/main.go project view 1 --owner "@me"
GraphQL: Only projects owned by an Organization can be marked as a template. (markProjectV2AsTemplate)
exit status 1
```

b. I found a bug in the api response when formatting JSON - it returns the old value, rather than the new value for `template`. This isn't a CLI issue, it's a data issue which should be fixed.


Patch:
diff --git a/go.mod b/go.mod
index 347f4a5d2..4a97a0e94 100644
--- a/go.mod
+++ b/go.mod
@@ -30,16 +30,16 @@ require (
 	github.com/muhammadmuzzammil1998/jsonc v0.0.0-20201229145248-615b0916ca38
 	github.com/opentracing/opentracing-go v1.1.0
 	github.com/rivo/tview v0.0.0-20221029100920-c4a7e501810d
-	github.com/shurcooL/githubv4 v0.0.0-20230424031643-6cea62ecd5a9
+	github.com/shurcooL/githubv4 v0.0.0-20230704064427-599ae7bbf278
 	github.com/sourcegraph/jsonrpc2 v0.1.0
 	github.com/spf13/cobra v1.6.1
 	github.com/spf13/pflag v1.0.5
 	github.com/stretchr/testify v1.8.4
 	github.com/zalando/go-keyring v0.2.3
-	golang.org/x/crypto v0.0.0-20210921155107-089bfa567519
+	golang.org/x/crypto v0.12.0
 	golang.org/x/sync v0.1.0
-	golang.org/x/term v0.7.0
-	golang.org/x/text v0.9.0
+	golang.org/x/term v0.11.0
+	golang.org/x/text v0.12.0
 	google.golang.org/grpc v1.53.0
 	google.golang.org/protobuf v1.28.1
 	gopkg.in/h2non/gock.v1 v1.1.2
@@ -76,13 +76,13 @@ require (
 	github.com/pmezard/go-difflib v1.0.0 // indirect
 	github.com/rivo/uniseg v0.4.4 // indirect
 	github.com/russross/blackfriday/v2 v2.1.0 // indirect
-	github.com/shurcooL/graphql v0.0.0-20220606043923-3cf50f8a0a29 // indirect
+	github.com/shurcooL/graphql v0.0.0-20230722043721-ed46e5a46466 // indirect
 	github.com/stretchr/objx v0.5.0 // indirect
 	github.com/thlib/go-timezone-local v0.0.0-20210907160436-ef149e42d28e // indirect
 	github.com/yuin/goldmark v1.5.2 // indirect
 	github.com/yuin/goldmark-emoji v1.0.1 // indirect
-	golang.org/x/net v0.9.0 // indirect
-	golang.org/x/sys v0.8.0 // indirect
+	golang.org/x/net v0.14.0 // indirect
+	golang.org/x/sys v0.11.0 // indirect
 	google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect
 	gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
 )
diff --git a/go.sum b/go.sum
index 087dfa690..e2996530f 100644
--- a/go.sum
+++ b/go.sum
@@ -141,10 +141,10 @@ github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis=
 github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
 github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
 github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
-github.com/shurcooL/githubv4 v0.0.0-20230424031643-6cea62ecd5a9 h1:nCBaIs5/R0HFP5+aPW/SzFUF8z0oKuCXmuDmHWaxzjY=
-github.com/shurcooL/githubv4 v0.0.0-20230424031643-6cea62ecd5a9/go.mod h1:hAF0iLZy4td2EX+/8Tw+4nodhlMrwN3HupfaXj3zkGo=
-github.com/shurcooL/graphql v0.0.0-20220606043923-3cf50f8a0a29 h1:B1PEwpArrNp4dkQrfxh/abbBAOZBVp0ds+fBEOUOqOc=
-github.com/shurcooL/graphql v0.0.0-20220606043923-3cf50f8a0a29/go.mod h1:AuYgA5Kyo4c7HfUmvRGs/6rGlMMV/6B1bVnB9JxJEEg=
+github.com/shurcooL/githubv4 v0.0.0-20230704064427-599ae7bbf278 h1:kdEGVAV4sO46DPtb8k793jiecUEhaX9ixoIBt41HEGU=
+github.com/shurcooL/githubv4 v0.0.0-20230704064427-599ae7bbf278/go.mod h1:zqMwyHmnN/eDOZOdiTohqIUKUrTFX62PNlu7IJdu0q8=
+github.com/shurcooL/graphql v0.0.0-20230722043721-ed46e5a46466 h1:17JxqqJY66GmZVHkmAsGEkcIu0oCe3AM420QDgGwZx0=
+github.com/shurcooL/graphql v0.0.0-20230722043721-ed46e5a46466/go.mod h1:9dIRpgIY7hVhoqfe0/FcYp0bpInZaT7dc3BYOprrIUE=
 github.com/sourcegraph/jsonrpc2 v0.1.0 h1:ohJHjZ+PcaLxDUjqk2NC3tIGsVa5bXThe1ZheSXOjuk=
 github.com/sourcegraph/jsonrpc2 v0.1.0/go.mod h1:ZafdZgk/axhT1cvZAPOhw+95nz2I/Ra5qMlU4gTRwIo=
 github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
@@ -180,8 +180,8 @@ golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qx
 golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
 golang.org/x/net v0.0.0-20220923203811-8be639271d50/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
 golang.org/x/net v0.0.0-20221002022538-bcab6841153b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
-golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM=
-golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
+golang.org/x/net v0.14.0 h1:BONx9s002vGdD9umnlX1Po8vOZmrgH34qlHcD1MfK14=
+golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI=
 golang.org/x/oauth2 v0.4.0 h1:NF0gk8LVPg1Ml7SSbGyySuoxdsXitj7TvgvuRxIMc/M=
 golang.org/x/oauth2 v0.4.0/go.mod h1:RznEsdpjGAINPTOF0UH/t+xJ75L18YO3Ho6Pyn+uRec=
 golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -203,20 +203,20 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
 golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
-golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
+golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
 golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
-golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ=
-golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
+golang.org/x/term v0.11.0 h1:F9tnn/DA/Im8nCwm+fX+1/eBwi4qFjRT++MhtVC4ZX0=
+golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU=
 golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
 golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
 golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
 golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
 golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
 golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
-golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
-golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
+golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc=
+golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
 golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
 golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
 golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=
diff --git a/pkg/cmd/project/project.go b/pkg/cmd/project/project.go
index dc3365696..d9858953d 100644
--- a/pkg/cmd/project/project.go
+++ b/pkg/cmd/project/project.go
@@ -17,6 +17,7 @@ import (
 	cmdItemEdit "github.com/cli/cli/v2/pkg/cmd/project/item-edit"
 	cmdItemList "github.com/cli/cli/v2/pkg/cmd/project/item-list"
 	cmdList "github.com/cli/cli/v2/pkg/cmd/project/list"
+	cmdTemplate "github.com/cli/cli/v2/pkg/cmd/project/template"
 	cmdView "github.com/cli/cli/v2/pkg/cmd/project/view"
 	"github.com/cli/cli/v2/pkg/cmdutil"
 	"github.com/spf13/cobra"
@@ -43,6 +44,7 @@ func NewCmdProject(f *cmdutil.Factory) *cobra.Command {
 	cmd.AddCommand(cmdDelete.NewCmdDelete(f, nil))
 	cmd.AddCommand(cmdEdit.NewCmdEdit(f, nil))
 	cmd.AddCommand(cmdView.NewCmdView(f, nil))
+	cmd.AddCommand(cmdTemplate.NewCmdTemplate(f, nil))
 
 	// items
 	cmd.AddCommand(cmdItemList.NewCmdList(f, nil))
diff --git a/pkg/cmd/project/shared/format/json.go b/pkg/cmd/project/shared/format/json.go
index 17509c6c5..7bfebdeda 100644
--- a/pkg/cmd/project/shared/format/json.go
+++ b/pkg/cmd/project/shared/format/json.go
@@ -15,6 +15,7 @@ func JSONProject(project queries.Project) ([]byte, error) {
 		ShortDescription: project.ShortDescription,
 		Public:           project.Public,
 		Closed:           project.Closed,
+		Template:         project.Template,
 		Title:            project.Title,
 		ID:               project.ID,
 		Readme:           project.Readme,
@@ -49,6 +50,7 @@ func JSONProjects(projects []queries.Project, totalCount int) ([]byte, error) {
 			ShortDescription: p.ShortDescription,
 			Public:           p.Public,
 			Closed:           p.Closed,
+			Template:         p.Template,
 			Title:            p.Title,
 			ID:               p.ID,
 			Readme:           p.Readme,
@@ -87,6 +89,7 @@ type projectJSON struct {
 	ShortDescription string `json:"shortDescription"`
 	Public           bool   `json:"public"`
 	Closed           bool   `json:"closed"`
+	Template         bool   `json:"template"`
 	Title            string `json:"title"`
 	ID               string `json:"id"`
 	Readme           string `json:"readme"`
diff --git a/pkg/cmd/project/shared/queries/queries.go b/pkg/cmd/project/shared/queries/queries.go
index b540b347f..ff68d4583 100644
--- a/pkg/cmd/project/shared/queries/queries.go
+++ b/pkg/cmd/project/shared/queries/queries.go
@@ -109,6 +109,7 @@ type Project struct {
 	ShortDescription string
 	Public           bool
 	Closed           bool
+	Template         bool
 	Title            string
 	ID               string
 	Readme           string
diff --git a/pkg/cmd/project/template/template.go b/pkg/cmd/project/template/template.go
new file mode 100644
index 000000000..9ef0732b9
--- /dev/null
+++ b/pkg/cmd/project/template/template.go
@@ -0,0 +1,176 @@
+package template
+
+import (
+	"fmt"
+	"strconv"
+
+	"github.com/MakeNowJust/heredoc"
+	"github.com/cli/cli/v2/pkg/cmd/project/shared/client"
+	"github.com/cli/cli/v2/pkg/cmd/project/shared/format"
+	"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
+	"github.com/cli/cli/v2/pkg/cmdutil"
+	"github.com/cli/cli/v2/pkg/iostreams"
+	"github.com/shurcooL/githubv4"
+	"github.com/spf13/cobra"
+)
+
+type templateOpts struct {
+	owner     string
+	undo      bool
+	number    int32
+	projectID string
+	format    string
+}
+
+type templateConfig struct {
+	client *queries.Client
+	opts   templateOpts
+	io     *iostreams.IOStreams
+}
+
+type markProjectTemplateMutation struct {
+	TemplateProject struct {
+		Project queries.Project `graphql:"projectV2"`
+	} `graphql:"markProjectV2AsTemplate(input:$input)"`
+}
+type unmarkProjectTemplateMutation struct {
+	TemplateProject struct {
+		Project queries.Project `graphql:"projectV2"`
+	} `graphql:"unmarkProjectV2AsTemplate(input:$input)"`
+}
+
+func NewCmdTemplate(f *cmdutil.Factory, runF func(config templateConfig) error) *cobra.Command {
+	opts := templateOpts{}
+	templateCmd := &cobra.Command{
+		Short: "Mark a project as a template",
+		Use:   "template [<number>]",
+		Example: heredoc.Doc(`
+			# mark the github org's project "1" as a template
+			gh project template 1 --owner "github"
+
+			# unmark the github org's project "1" as a template
+			gh project template 1 --owner "github" --undo
+		`),
+		Args: cobra.MaximumNArgs(1),
+		RunE: func(cmd *cobra.Command, args []string) error {
+			client, err := client.New(f)
+			if err != nil {
+				return err
+			}
+
+			if len(args) == 1 {
+				num, err := strconv.ParseInt(args[0], 10, 32)
+				if err != nil {
+					return cmdutil.FlagErrorf("invalid number: %v", args[0])
+				}
+				opts.number = int32(num)
+			}
+
+			config := templateConfig{
+				client: client,
+				opts:   opts,
+				io:     f.IOStreams,
+			}
+
+			// allow testing of the command without actually running it
+			if runF != nil {
+				return runF(config)
+			}
+			return runTemplate(config)
+		},
+	}
+
+	templateCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the org owner.")
+	templateCmd.Flags().BoolVar(&opts.undo, "undo", false, "Unmark the project as a template.")
+	cmdutil.StringEnumFlag(templateCmd, &opts.format, "format", "", "", []string{"json"}, "Output format")
+
+	return templateCmd
+}
+
+func runTemplate(config templateConfig) error {
+	canPrompt := config.io.CanPrompt()
+	owner, err := config.client.NewOwner(canPrompt, config.opts.owner)
+	if err != nil {
+		return err
+	}
+
+	project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false)
+	if err != nil {
+		return err
+	}
+	config.opts.projectID = project.ID
+
+	if config.opts.undo {
+		query, variables := unmarkTemplateArgs(config)
+		err = config.client.Mutate("UnmarkProjectTemplate", query, variables)
+		if err != nil {
+			return err
+		}
+
+		if config.opts.format == "json" {
+			return printJSON(config, *project)
+		}
+
+		return printResults(config, query.TemplateProject.Project)
+
+	}
+	query, variables := markTemplateArgs(config)
+	err = config.client.Mutate("MarkProjectTemplate", query, variables)
+	if err != nil {
+		return err
+	}
+
+	if config.opts.format == "json" {
+		return printJSON(config, *project)
+	}
+
+	return printResults(config, query.TemplateProject.Project)
+}
+
+func markTemplateArgs(config templateConfig) (*markProjectTemplateMutation, map[string]interface{}) {
+	return &markProjectTemplateMutation{}, map[string]interface{}{
+		"input": githubv4.MarkProjectV2AsTemplateInput{
+			ProjectID: githubv4.ID(config.opts.projectID),
+		},
+		"firstItems":  githubv4.Int(0),
+		"afterItems":  (*githubv4.String)(nil),
+		"firstFields": githubv4.Int(0),
+		"afterFields": (*githubv4.String)(nil),
+	}
+}
+
+func unmarkTemplateArgs(config templateConfig) (*unmarkProjectTemplateMutation, map[string]interface{}) {
+	return &unmarkProjectTemplateMutation{}, map[string]interface{}{
+		"input": githubv4.UnmarkProjectV2AsTemplateInput{
+			ProjectID: githubv4.ID(config.opts.projectID),
+		},
+		"firstItems":  githubv4.Int(0),
+		"afterItems":  (*githubv4.String)(nil),
+		"firstFields": githubv4.Int(0),
+		"afterFields": (*githubv4.String)(nil),
+	}
+}
+
+func printResults(config templateConfig, project queries.Project) error {
+	if !config.io.IsStdoutTTY() {
+		return nil
+	}
+
+	if config.opts.undo {
+		_, err := fmt.Fprintf(config.io.Out, "Unmarked project %d as a template.\n", project.Number)
+		return err
+	}
+
+	_, err := fmt.Fprintf(config.io.Out, "Marked project %d as a template.\n", project.Number)
+	return err
+}
+
+func printJSON(config templateConfig, project queries.Project) error {
+	b, err := format.JSONProject(project)
+	if err != nil {
+		return err
+	}
+
+	_, err = config.io.Out.Write(b)
+	return err
+}


Test patch:
diff --git a/pkg/cmd/project/shared/format/json_test.go b/pkg/cmd/project/shared/format/json_test.go
index c05a3e5ff..9e75167c5 100644
--- a/pkg/cmd/project/shared/format/json_test.go
+++ b/pkg/cmd/project/shared/format/json_test.go
@@ -25,7 +25,7 @@ func TestJSONProject_User(t *testing.T) {
 	b, err := JSONProject(project)
 	assert.NoError(t, err)
 
-	assert.Equal(t, `{"number":2,"url":"a url","shortDescription":"short description","public":true,"closed":false,"title":"","id":"123","readme":"readme","items":{"totalCount":1},"fields":{"totalCount":2},"owner":{"type":"User","login":"monalisa"}}`, string(b))
+	assert.Equal(t, `{"number":2,"url":"a url","shortDescription":"short description","public":true,"closed":false,"template":false,"title":"","id":"123","readme":"readme","items":{"totalCount":1},"fields":{"totalCount":2},"owner":{"type":"User","login":"monalisa"}}`, string(b))
 }
 
 func TestJSONProject_Org(t *testing.T) {
@@ -36,6 +36,7 @@ func TestJSONProject_Org(t *testing.T) {
 		ShortDescription: "short description",
 		Public:           true,
 		Readme:           "readme",
+		Template:         true,
 	}
 
 	project.Items.TotalCount = 1
@@ -45,7 +46,7 @@ func TestJSONProject_Org(t *testing.T) {
 	b, err := JSONProject(project)
 	assert.NoError(t, err)
 
-	assert.Equal(t, `{"number":2,"url":"a url","shortDescription":"short description","public":true,"closed":false,"title":"","id":"123","readme":"readme","items":{"totalCount":1},"fields":{"totalCount":2},"owner":{"type":"Organization","login":"github"}}`, string(b))
+	assert.Equal(t, `{"number":2,"url":"a url","shortDescription":"short description","public":true,"closed":false,"template":true,"title":"","id":"123","readme":"readme","items":{"totalCount":1},"fields":{"totalCount":2},"owner":{"type":"Organization","login":"github"}}`, string(b))
 }
 
 func TestJSONProjects(t *testing.T) {
@@ -70,6 +71,7 @@ func TestJSONProjects(t *testing.T) {
 		ShortDescription: "short description",
 		Public:           true,
 		Readme:           "readme",
+		Template:         true,
 	}
 
 	orgProject.Items.TotalCount = 1
@@ -81,7 +83,7 @@ func TestJSONProjects(t *testing.T) {
 
 	assert.Equal(
 		t,
-		`{"projects":[{"number":2,"url":"a url","shortDescription":"short description","public":true,"closed":false,"title":"","id":"123","readme":"readme","items":{"totalCount":1},"fields":{"totalCount":2},"owner":{"type":"User","login":"monalisa"}},{"number":2,"url":"a url","shortDescription":"short description","public":true,"closed":false,"title":"","id":"123","readme":"readme","items":{"totalCount":1},"fields":{"totalCount":2},"owner":{"type":"Organization","login":"github"}}],"totalCount":2}`,
+		`{"projects":[{"number":2,"url":"a url","shortDescription":"short description","public":true,"closed":false,"template":false,"title":"","id":"123","readme":"readme","items":{"totalCount":1},"fields":{"totalCount":2},"owner":{"type":"User","login":"monalisa"}},{"number":2,"url":"a url","shortDescription":"short description","public":true,"closed":false,"template":true,"title":"","id":"123","readme":"readme","items":{"totalCount":1},"fields":{"totalCount":2},"owner":{"type":"Organization","login":"github"}}],"totalCount":2}`,
 		string(b))
 }
 
diff --git a/pkg/cmd/project/template/template_test.go b/pkg/cmd/project/template/template_test.go
new file mode 100644
index 000000000..df42ae5ca
--- /dev/null
+++ b/pkg/cmd/project/template/template_test.go
@@ -0,0 +1,275 @@
+package template
+
+import (
+	"testing"
+
+	"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
+	"github.com/cli/cli/v2/pkg/cmdutil"
+	"github.com/cli/cli/v2/pkg/iostreams"
+	"github.com/google/shlex"
+	"github.com/stretchr/testify/assert"
+	"gopkg.in/h2non/gock.v1"
+)
+
+func TestNewCmdTemplate(t *testing.T) {
+	tests := []struct {
+		name        string
+		cli         string
+		wants       templateOpts
+		wantsErr    bool
+		wantsErrMsg string
+	}{
+		{
+			name:        "not-a-number",
+			cli:         "x",
+			wantsErr:    true,
+			wantsErrMsg: "invalid number: x",
+		},
+		{
+			name: "number",
+			cli:  "123",
+			wants: templateOpts{
+				number: 123,
+			},
+		},
+		{
+			name: "owner",
+			cli:  "--owner monalisa",
+			wants: templateOpts{
+				owner: "monalisa",
+			},
+		},
+		{
+			name: "undo",
+			cli:  "--undo",
+			wants: templateOpts{
+				undo: true,
+			},
+		},
+
+		{
+			name: "json",
+			cli:  "--format json",
+			wants: templateOpts{
+				format: "json",
+			},
+		},
+	}
+
+	t.Setenv("GH_TOKEN", "auth-token")
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ios, _, _, _ := iostreams.Test()
+			f := &cmdutil.Factory{
+				IOStreams: ios,
+			}
+
+			argv, err := shlex.Split(tt.cli)
+			assert.NoError(t, err)
+
+			var gotOpts templateOpts
+			cmd := NewCmdTemplate(f, func(config templateConfig) error {
+				gotOpts = config.opts
+				return nil
+			})
+
+			cmd.SetArgs(argv)
+			_, err = cmd.ExecuteC()
+			if tt.wantsErr {
+				assert.Error(t, err)
+				assert.Equal(t, tt.wantsErrMsg, err.Error())
+				return
+			}
+			assert.NoError(t, err)
+
+			assert.Equal(t, tt.wants.number, gotOpts.number)
+			assert.Equal(t, tt.wants.owner, gotOpts.owner)
+			assert.Equal(t, tt.wants.format, gotOpts.format)
+		})
+	}
+}
+func TestRunMarkTemplate_Org(t *testing.T) {
+	defer gock.Off()
+	gock.Observe(gock.DumpRequest)
+
+	// get org ID
+	gock.New("https://api.github.com").
+		Post("/graphql").
+		MatchType("json").
+		JSON(map[string]interface{}{
+			"query": "query UserOrgOwner.*",
+			"variables": map[string]interface{}{
+				"login": "github",
+			},
+		}).
+		Reply(200).
+		JSON(map[string]interface{}{
+			"data": map[string]interface{}{
+				"organization": map[string]interface{}{
+					"id": "an ID",
+				},
+			},
+			"errors": []interface{}{
+				map[string]interface{}{
+					"type": "NOT_FOUND",
+					"path": []string{"user"},
+				},
+			},
+		})
+
+	// get project ID
+	gock.New("https://api.github.com").
+		Post("/graphql").
+		MatchType("json").
+		JSON(map[string]interface{}{
+			"query": "query OrgProject.*",
+			"variables": map[string]interface{}{
+				"login":       "github",
+				"number":      1,
+				"firstItems":  0,
+				"afterItems":  nil,
+				"firstFields": 0,
+				"afterFields": nil,
+			},
+		}).
+		Reply(200).
+		JSON(map[string]interface{}{
+			"data": map[string]interface{}{
+				"organization": map[string]interface{}{
+					"projectV2": map[string]interface{}{
+						"id": "an ID",
+					},
+				},
+			},
+		})
+
+	// template project
+	gock.New("https://api.github.com").
+		Post("/graphql").
+		BodyString(`{"query":"mutation MarkProjectTemplate.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID"}}}`).
+		Reply(200).
+		JSON(map[string]interface{}{
+			"data": map[string]interface{}{
+				"markProjectV2AsTemplate": map[string]interface{}{
+					"projectV2": map[string]interface{}{
+						"id":     "project ID",
+						"number": 1,
+					},
+				},
+			},
+		})
+
+	client := queries.NewTestClient()
+
+	ios, _, stdout, _ := iostreams.Test()
+	ios.SetStdoutTTY(true)
+	config := templateConfig{
+		opts: templateOpts{
+			owner:  "github",
+			number: 1,
+		},
+		client: client,
+		io:     ios,
+	}
+
+	err := runTemplate(config)
+	assert.NoError(t, err)
+	assert.Equal(
+		t,
+		"Marked project 1 as a template.\n",
+		stdout.String())
+}
+
+func TestRunUnmarkTemplate_Org(t *testing.T) {
+	defer gock.Off()
+	gock.Observe(gock.DumpRequest)
+
+	// get org ID
+	gock.New("https://api.github.com").
+		Post("/graphql").
+		MatchType("json").
+		JSON(map[string]interface{}{
+			"query": "query UserOrgOwner.*",
+			"variables": map[string]interface{}{
+				"login": "github",
+			},
+		}).
+		Reply(200).
+		JSON(map[string]interface{}{
+			"data": map[string]interface{}{
+				"organization": map[string]interface{}{
+					"id": "an ID",
+				},
+			},
+			"errors": []interface{}{
+				map[string]interface{}{
+					"type": "NOT_FOUND",
+					"path": []string{"user"},
+				},
+			},
+		})
+
+	// get project ID
+	gock.New("https://api.github.com").
+		Post("/graphql").
+		MatchType("json").
+		JSON(map[string]interface{}{
+			"query": "query OrgProject.*",
+			"variables": map[string]interface{}{
+				"login":       "github",
+				"number":      1,
+				"firstItems":  0,
+				"afterItems":  nil,
+				"firstFields": 0,
+				"afterFields": nil,
+			},
+		}).
+		Reply(200).
+		JSON(map[string]interface{}{
+			"data": map[string]interface{}{
+				"organization": map[string]interface{}{
+					"projectV2": map[string]interface{}{
+						"id": "an ID",
+					},
+				},
+			},
+		})
+
+	// template project
+	gock.New("https://api.github.com").
+		Post("/graphql").
+		BodyString(`{"query":"mutation UnmarkProjectTemplate.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID"}}}`).
+		Reply(200).
+		JSON(map[string]interface{}{
+			"data": map[string]interface{}{
+				"unmarkProjectV2AsTemplate": map[string]interface{}{
+					"projectV2": map[string]interface{}{
+						"id":     "project ID",
+						"number": 1,
+					},
+				},
+			},
+		})
+
+	client := queries.NewTestClient()
+
+	ios, _, stdout, _ := iostreams.Test()
+	ios.SetStdoutTTY(true)
+	config := templateConfig{
+		opts: templateOpts{
+			owner:  "github",
+			number: 1,
+			undo:   true,
+		},
+		client: client,
+		io:     ios,
+	}
+
+	err := runTemplate(config)
+	assert.NoError(t, err)
+	assert.Equal(
+		t,
+		"Unmarked project 1 as a template.\n",
+		stdout.String())
+}