Skip to content

Commit

Permalink
resource/repository: add support for enabling github pages (integrati…
Browse files Browse the repository at this point in the history
…ons#490)

* add support for enabling github pages

* update resource comments

* add additional comments in expand methods

* add formatting fixes

Co-authored-by: Jeremy Udit <[email protected]>
  • Loading branch information
anGie44 and Jeremy Udit authored Jan 14, 2021
1 parent e7527ef commit 60f629e
Show file tree
Hide file tree
Showing 6 changed files with 354 additions and 10 deletions.
54 changes: 54 additions & 0 deletions github/data_source_github_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,50 @@ func dataSourceGithubRepository() *schema.Resource {
Type: schema.TypeBool,
Computed: true,
},
"pages": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"source": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"branch": {
Type: schema.TypeString,
Computed: true,
},
"path": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"cname": {
Type: schema.TypeString,
Computed: true,
},
"custom_404": {
Type: schema.TypeBool,
Computed: true,
},
"html_url": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"url": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"topics": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Expand Down Expand Up @@ -164,6 +208,16 @@ func dataSourceGithubRepositoryRead(d *schema.ResourceData, meta interface{}) er
d.Set("node_id", repo.GetNodeID())
d.Set("repo_id", repo.GetID())

if repo.GetHasPages() {
pages, _, err := client.Repositories.GetPagesInfo(context.TODO(), owner, repoName)
if err != nil {
return err
}
if err := d.Set("pages", flattenPages(pages)); err != nil {
return fmt.Errorf("error setting pages: %w", err)
}
}

err = d.Set("topics", flattenStringList(repo.Topics))
if err != nil {
return err
Expand Down
67 changes: 58 additions & 9 deletions github/data_source_github_repository_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import (
"regexp"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)

func TestAccGithubRepositoryDataSource(t *testing.T) {

t.Run("queries a repository without error", func(t *testing.T) {
t.Run("anonymously queries a repository without error", func(t *testing.T) {

config := fmt.Sprintf(`
data "github_repositories" "test" {
Expand Down Expand Up @@ -48,14 +49,6 @@ func TestAccGithubRepositoryDataSource(t *testing.T) {
testCase(t, anonymous)
})

t.Run("with an individual account", func(t *testing.T) {
testCase(t, individual)
})

t.Run("with an organization account", func(t *testing.T) {
testCase(t, organization)
})

})

t.Run("raises expected errors when querying for a repository", func(t *testing.T) {
Expand Down Expand Up @@ -102,4 +95,60 @@ func TestAccGithubRepositoryDataSource(t *testing.T) {
testCase(t, organization)
})
})

t.Run("queries a repository with pages configured", func(t *testing.T) {

randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)

config := fmt.Sprintf(`
resource "github_repository" "test" {
name = "tf-acc-%s"
auto_init = true
pages {
source {
branch = "main"
}
}
}
data "github_repository" "test" {
name = github_repository.test.name
}
`, randomID)

check := resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"data.github_repository.test", "pages.0.source.0.branch",
"main",
),
)

testCase := func(t *testing.T, mode string) {
resource.Test(t, resource.TestCase{
PreCheck: func() { skipUnlessMode(t, mode) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: config,
Check: check,
},
},
})
}

t.Run("with an anonymous account", func(t *testing.T) {
t.Skip("anonymous account not supported for this operation")
})

t.Run("with an individual account", func(t *testing.T) {
testCase(t, individual)
})

t.Run("with an organization account", func(t *testing.T) {
testCase(t, organization)
})

})

}
148 changes: 147 additions & 1 deletion github/resource_github_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,53 @@ func resourceGithubRepository() *schema.Resource {
Type: schema.TypeBool,
Optional: true,
},
"pages": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"source": {
Type: schema.TypeList,
MaxItems: 1,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"branch": {
Type: schema.TypeString,
Required: true,
},
"path": {
Type: schema.TypeString,
Optional: true,
Default: "/",
},
},
},
},
"cname": {
Type: schema.TypeString,
Optional: true,
},
"custom_404": {
Type: schema.TypeBool,
Computed: true,
},
"html_url": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"url": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"topics": {
Type: schema.TypeSet,
Optional: true,
Expand All @@ -133,7 +180,6 @@ func resourceGithubRepository() *schema.Resource {
Type: schema.TypeBool,
Optional: true,
},

"full_name": {
Type: schema.TypeString,
Computed: true,
Expand Down Expand Up @@ -308,6 +354,14 @@ func resourceGithubRepositoryCreate(d *schema.ResourceData, meta interface{}) er
}
}

pages := expandPages(d.Get("pages").([]interface{}))
if pages != nil {
_, _, err := client.Repositories.EnablePages(ctx, owner, repoName, pages)
if err != nil {
return err
}
}

return resourceGithubRepositoryUpdate(d, meta)
}

Expand Down Expand Up @@ -366,6 +420,16 @@ func resourceGithubRepositoryRead(d *schema.ResourceData, meta interface{}) erro
d.Set("node_id", repo.GetNodeID())
d.Set("repo_id", repo.GetID())

if repo.GetHasPages() {
pages, _, err := client.Repositories.GetPagesInfo(ctx, owner, repoName)
if err != nil {
return err
}
if err := d.Set("pages", flattenPages(pages)); err != nil {
return fmt.Errorf("error setting pages: %w", err)
}
}

if repo.TemplateRepository != nil {
d.Set("template", []interface{}{
map[string]interface{}{
Expand Down Expand Up @@ -423,6 +487,21 @@ func resourceGithubRepositoryUpdate(d *schema.ResourceData, meta interface{}) er
}
d.SetId(*repo.Name)

if d.HasChange("pages") && !d.IsNewResource() {
opts := expandPagesUpdate(d.Get("pages").([]interface{}))
if opts != nil {
_, err := client.Repositories.UpdatePages(ctx, owner, repoName, opts)
if err != nil {
return err
}
} else {
_, err := client.Repositories.DisablePages(ctx, owner, repoName)
if err != nil {
return err
}
}
}

if d.HasChange("topics") {
topics := repoReq.Topics
_, _, err = client.Repositories.ReplaceAllTopics(ctx, owner, *repo.Name, topics)
Expand Down Expand Up @@ -479,3 +558,70 @@ func resourceGithubRepositoryDelete(d *schema.ResourceData, meta interface{}) er
_, err := client.Repositories.Delete(ctx, owner, repoName)
return err
}

func expandPages(input []interface{}) *github.Pages {
if len(input) == 0 || input[0] == nil {
return nil
}
pages := input[0].(map[string]interface{})
pagesSource := pages["source"].([]interface{})[0].(map[string]interface{})
source := &github.PagesSource{
Branch: github.String(pagesSource["branch"].(string)),
}
if v, ok := pagesSource["path"].(string); ok {
// To set to the root directory "/", leave source.Path unset
if v != "" && v != "/" {
source.Path = github.String(v)
}
}
return &github.Pages{Source: source}
}

func expandPagesUpdate(input []interface{}) *github.PagesUpdate {
if len(input) == 0 || input[0] == nil {
return nil
}

pages := input[0].(map[string]interface{})
update := &github.PagesUpdate{}

// Only set the github.PagesUpdate CNAME field if the value is a non-empty string.
// Leaving the CNAME field unset will remove the custom domain.
if v, ok := pages["cname"].(string); ok && v != "" {
update.CNAME = github.String(v)
}

// To update the Github Pages source, the github.PagesUpdate Source field
// must include the branch name and optionally the subdirectory /docs.
// e.g. "master" or "master /docs"
pagesSource := pages["source"].([]interface{})[0].(map[string]interface{})
source := pagesSource["branch"].(string)
if v, ok := pagesSource["path"].(string); ok {
if v != "" && v != "/" {
source += fmt.Sprintf(" %s", v)
}
}
update.Source = github.String(source)

return update
}

func flattenPages(pages *github.Pages) []interface{} {
if pages == nil {
return []interface{}{}
}

sourceMap := make(map[string]interface{})
sourceMap["branch"] = pages.GetSource().GetBranch()
sourceMap["path"] = pages.GetSource().GetPath()

pagesMap := make(map[string]interface{})
pagesMap["source"] = []interface{}{sourceMap}
pagesMap["url"] = pages.GetURL()
pagesMap["status"] = pages.GetStatus()
pagesMap["cname"] = pages.GetCNAME()
pagesMap["custom_404"] = pages.GetCustom404()
pagesMap["html_url"] = pages.GetHTMLURL()

return []interface{}{pagesMap}
}
Loading

0 comments on commit 60f629e

Please sign in to comment.