|
| 1 | +package provider |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" |
| 7 | + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" |
| 8 | + "github.com/xanzy/go-gitlab" |
| 9 | +) |
| 10 | + |
| 11 | +var _ = registerDataSource("gitlab_project_hooks", func() *schema.Resource { |
| 12 | + return &schema.Resource{ |
| 13 | + Description: `The ` + "`gitlab_project_hooks`" + ` data source allows to retrieve details about hooks in a project. |
| 14 | +
|
| 15 | +**Upstream API**: [GitLab REST API docs](https://docs.gitlab.com/ee/api/projects.html#list-project-hooks)`, |
| 16 | + |
| 17 | + ReadContext: dataSourceGitlabProjectHooksRead, |
| 18 | + Schema: map[string]*schema.Schema{ |
| 19 | + "project": { |
| 20 | + Description: "The name or id of the project.", |
| 21 | + Type: schema.TypeString, |
| 22 | + Required: true, |
| 23 | + }, |
| 24 | + "hooks": { |
| 25 | + Description: "The list of hooks.", |
| 26 | + Type: schema.TypeList, |
| 27 | + Computed: true, |
| 28 | + Elem: &schema.Resource{ |
| 29 | + Schema: datasourceSchemaFromResourceSchema(gitlabProjectHookSchema(), nil, nil), |
| 30 | + }, |
| 31 | + }, |
| 32 | + }, |
| 33 | + } |
| 34 | +}) |
| 35 | + |
| 36 | +func dataSourceGitlabProjectHooksRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { |
| 37 | + client := meta.(*gitlab.Client) |
| 38 | + |
| 39 | + project := d.Get("project").(string) |
| 40 | + options := gitlab.ListProjectHooksOptions{ |
| 41 | + PerPage: 20, |
| 42 | + Page: 1, |
| 43 | + } |
| 44 | + |
| 45 | + var hooks []*gitlab.ProjectHook |
| 46 | + for options.Page != 0 { |
| 47 | + paginatedHooks, resp, err := client.Projects.ListProjectHooks(project, &options, gitlab.WithContext(ctx)) |
| 48 | + if err != nil { |
| 49 | + return diag.FromErr(err) |
| 50 | + } |
| 51 | + |
| 52 | + hooks = append(hooks, paginatedHooks...) |
| 53 | + options.Page = resp.NextPage |
| 54 | + } |
| 55 | + |
| 56 | + d.SetId(project) |
| 57 | + if err := d.Set("hooks", flattenGitlabProjectHooks(project, hooks)); err != nil { |
| 58 | + return diag.Errorf("failed to set hooks to state: %v", err) |
| 59 | + } |
| 60 | + |
| 61 | + return nil |
| 62 | +} |
| 63 | + |
| 64 | +func flattenGitlabProjectHooks(project string, hooks []*gitlab.ProjectHook) (values []map[string]interface{}) { |
| 65 | + for _, hook := range hooks { |
| 66 | + values = append(values, gitlabProjectHookToStateMap(project, hook)) |
| 67 | + } |
| 68 | + return values |
| 69 | +} |
0 commit comments