Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 173 additions & 0 deletions acceptance/pipeline_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -714,3 +714,176 @@ func TestPipelineCancel_NoToken(t *testing.T) {

assert.Equal(t, result.ExitCode, 3, "stderr: %s", result.Stderr)
}

// --- pipeline search tests ---

const searchProjectID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"

func fakeProjectInfo(slug, id string) map[string]any {
return map[string]any{
"id": id,
"slug": slug,
"name": "testrepo",
}
}

func fakeSearchPipeline(id string, number int, status, branch string) map[string]any {
now := time.Date(2020, 1, 1, 12, 0, 0, 0, time.UTC)
return map[string]any{
"id": id,
"number": number,
"state": "created",
"status": status,
"created_at": now.Format(time.RFC3339),
"updated_at": now.Format(time.RFC3339),
"trigger": map[string]any{
"type": "webhook",
"received_at": now.Format(time.RFC3339),
"actor": map[string]any{"id": "actor-uuid-1"},
},
"vcs": map[string]any{
"branch": branch,
"revision": "abc1234def5678",
},
"project": map[string]any{
"id": searchProjectID,
},
"workflows_summary": map[string]any{
"count_by_status": map[string]any{
"success": 2,
"failed": 1,
},
},
}
}

func TestPipelineSearch(t *testing.T) {
fake := fakes.NewCircleCI(t)
fake.AddProjectInfo(watchSlug, fakeProjectInfo(watchSlug, searchProjectID))
fake.SetSearchResponse(map[string]any{
"items": []any{
fakeSearchPipeline("pid-search-1", 10, "success", "main"),
fakeSearchPipeline("pid-search-2", 9, "failed", "feature"),
},
"next_page_token": nil,
"total_size": 2,
})

env := testenv.New(t)
env.Token = testToken
env.CircleCIURL = fake.URL()

result := binary.RunCLI(t, binary.RunOpts{
Binary: binaryPath,
Args: []string{"pipeline", "search", "--project", watchSlug},
Env: env.Environ(),
WorkDir: t.TempDir(),
})

assert.Equal(t, result.ExitCode, 0, "stderr: %s", result.Stderr)
assert.Check(t, golden.String(result.Stdout, t.Name()+".txt"))
}

func TestPipelineSearch_JSON(t *testing.T) {
fake := fakes.NewCircleCI(t)
fake.AddProjectInfo(watchSlug, fakeProjectInfo(watchSlug, searchProjectID))
fake.SetSearchResponse(map[string]any{
"items": []any{
fakeSearchPipeline("pid-search-1", 10, "success", "main"),
},
"next_page_token": nil,
"total_size": 1,
})

env := testenv.New(t)
env.Token = testToken
env.CircleCIURL = fake.URL()

result := binary.RunCLI(t, binary.RunOpts{
Binary: binaryPath,
Args: []string{"pipeline", "search", "--project", watchSlug, "--json"},
Env: env.Environ(),
WorkDir: t.TempDir(),
})

assert.Equal(t, result.ExitCode, 0, "stderr: %s", result.Stderr)
assert.Check(t, golden.String(result.Stdout, t.Name()+".json"))
}

func TestPipelineSearch_WithFilter(t *testing.T) {
fake := fakes.NewCircleCI(t)
fake.AddProjectInfo(watchSlug, fakeProjectInfo(watchSlug, searchProjectID))
fake.SetSearchResponse(map[string]any{
"items": []any{fakeSearchPipeline("pid-search-1", 10, "failed", "main")},
"next_page_token": nil,
"total_size": 1,
})

env := testenv.New(t)
env.Token = testToken
env.CircleCIURL = fake.URL()

rawFilter := `pipeline.git.branch == "main" and pipeline.state == "errored"`
result := binary.RunCLI(t, binary.RunOpts{
Binary: binaryPath,
Args: []string{"pipeline", "search", "--project", watchSlug, "--filter", rawFilter},
Env: env.Environ(),
WorkDir: t.TempDir(),
})

assert.Equal(t, result.ExitCode, 0, "stderr: %s", result.Stderr)
assert.Check(t, cmp.Contains(result.Stdout, "pid-search-1"))

req := fake.LastSearchRequest()
assert.Assert(t, req != nil, "search endpoint was not called")
assert.Equal(t, req["filter"], rawFilter)
}

// The /pipeline/search API returns "" for timestamps on some pipelines.
// This must not crash the JSON decoder.
func TestPipelineSearch_EmptyTimestamp(t *testing.T) {
fake := fakes.NewCircleCI(t)
fake.AddProjectInfo(watchSlug, fakeProjectInfo(watchSlug, searchProjectID))
pip := fakeSearchPipeline("pid-search-1", 10, "success", "main")
pip["created_at"] = ""
pip["updated_at"] = ""
fake.SetSearchResponse(map[string]any{
"items": []any{pip},
"next_page_token": nil,
"total_size": 1,
})

env := testenv.New(t)
env.Token = testToken
env.CircleCIURL = fake.URL()

result := binary.RunCLI(t, binary.RunOpts{
Binary: binaryPath,
Args: []string{"pipeline", "search", "--project", watchSlug},
Env: env.Environ(),
WorkDir: t.TempDir(),
})

assert.Equal(t, result.ExitCode, 0, "stderr: %s", result.Stderr)
assert.Check(t, cmp.Contains(result.Stdout, "pid-search-1"))
}

func TestPipelineSearch_EmptyResults(t *testing.T) {
fake := fakes.NewCircleCI(t)
fake.AddProjectInfo(watchSlug, fakeProjectInfo(watchSlug, searchProjectID))
// No SetSearchResponse → handler returns empty items list.

env := testenv.New(t)
env.Token = testToken
env.CircleCIURL = fake.URL()

result := binary.RunCLI(t, binary.RunOpts{
Binary: binaryPath,
Args: []string{"pipeline", "search", "--project", watchSlug},
Env: env.Environ(),
WorkDir: t.TempDir(),
})

assert.Equal(t, result.ExitCode, 0, "stderr: %s", result.Stderr)
assert.Check(t, cmp.Contains(result.Stderr, "No pipelines found."))
}
5 changes: 5 additions & 0 deletions acceptance/testdata/TestPipelineSearch.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Pipeline Search Results
| # | Branch | Revision | Status | Workflows | Created | Pipeline |
| -- | ------- | -------- | ------- | ------------------- | -------------------- | -------------- |
| 10 | main | abc1234 | success | 1 failed, 2 success | 2020-01-01 12:00 UTC | `pid-search-1` |
| 9 | feature | abc1234 | failed | 1 failed, 2 success | 2020-01-01 12:00 UTC | `pid-search-2` |
1 change: 1 addition & 0 deletions acceptance/testdata/TestPipelineSearch_JSON.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{"id":"pid-search-1","number":10,"state":"created","status":"success","branch":"main","revision":"abc1234def5678","workflows_summary":{"failed":1,"success":2},"created_at":"2020-01-01T12:00:00Z"}]
68 changes: 68 additions & 0 deletions internal/apiclient/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,74 @@ func (c *Client) TriggerPipeline(ctx context.Context, projectSlug, branch string
return &resp, nil
}

// SearchPipeline is a pipeline item returned by the search API. It has a
// richer shape than Pipeline: a separate Status field, a WorkflowsSummary,
// and a Project struct instead of a flat project_slug.
type SearchPipeline struct {
ID string `json:"id"`
Number int64 `json:"number"`
State string `json:"state"`
Status string `json:"status"`
CreatedAt FlexTime `json:"created_at"`
UpdatedAt FlexTime `json:"updated_at"`
Trigger PipelineTrigger `json:"trigger"`
VCS *PipelineVCS `json:"vcs,omitempty"`
Errors []PipelineError `json:"errors,omitempty"`
Project *SearchProject `json:"project,omitempty"`
WorkflowsSummary *WorkflowsSummary `json:"workflows_summary,omitempty"`
}

// SearchProject holds the project UUID returned by the search API.
type SearchProject struct {
ID string `json:"id"`
}

// WorkflowsSummary holds aggregated workflow status counts for a pipeline.
type WorkflowsSummary struct {
CountByStatus map[string]int `json:"count_by_status"`
}

// SearchPipelinesRequest is the request body for POST /api/v2/pipeline/search.
type SearchPipelinesRequest struct {
Scope *SearchScope `json:"scope,omitempty"`
Filter string `json:"filter,omitempty"`
OrderBy string `json:"order_by,omitempty"`
PageToken string `json:"page_token,omitempty"`
}

// SearchScope narrows a pipeline search to specific projects and/or a date range.
type SearchScope struct {
ProjectIDs []string `json:"project_ids,omitempty"`
CreatedAfter *time.Time `json:"created_after,omitempty"`
CreatedBefore *time.Time `json:"created_before,omitempty"`
}

type searchPipelinesResponse struct {
Items []SearchPipeline `json:"items"`
NextPageToken string `json:"next_page_token"`
TotalSize int `json:"total_size"`
}

// SearchPipelines calls POST /api/v2/pipeline/search and paginates up to limit
// results.
func (c *Client) SearchPipelines(ctx context.Context, req SearchPipelinesRequest, limit int) ([]SearchPipeline, error) {
var all []SearchPipeline
for {
var resp searchPipelinesResponse
if err := c.post(ctx, "/pipeline/search", req, &resp); err != nil {
return nil, err
}
all = append(all, resp.Items...)
if limit > 0 && len(all) >= limit {
return all[:limit], nil
}
if resp.NextPageToken == "" {
return all, nil
}
req.PageToken = resp.NextPageToken
}
}

// PipelineWorkflowSummary holds brief workflow status for a pipeline.
type PipelineWorkflowSummary struct {
ID string `json:"id"`
Expand Down
50 changes: 50 additions & 0 deletions internal/apiclient/time.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright (c) 2026 Circle Internet Services, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// SPDX-License-Identifier: MIT

package apiclient

import (
"strings"
"time"
)

// FlexTime is a time.Time that unmarshals an empty JSON string as the zero
// time rather than returning a parse error. The /pipeline/search endpoint
// returns "" for timestamps on some pipelines, which time.Time's UnmarshalJSON
// rejects.
type FlexTime struct {
time.Time
}

func (t *FlexTime) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), `"`)
if s == "" || s == "null" {
t.Time = time.Time{}
return nil
}
parsed, err := time.Parse(time.RFC3339Nano, s)
if err != nil {
return err
}
t.Time = parsed
return nil
}
1 change: 1 addition & 0 deletions internal/cmd/pipeline/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ func NewPipelineCmd() *cobra.Command {
cmd.AddCommand(newCancelCmd())
cmd.AddCommand(newGetCmd())
cmd.AddCommand(newListCmd())
cmd.AddCommand(newSearchCmd())
cmd.AddCommand(newTriggerCmd())
cmd.AddCommand(newWatchCmd())

Expand Down
Loading