diff --git a/README.md b/README.md index 5d00ed2..be61f5b 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ A GitHub CLI-inspired command-line interface for ClickUp. - **GitHub CLI-like Interface**: Familiar command structure for developers who use `gh` - **Task Management**: Create, view, update, and manage tasks from the command line - **Comment Management**: Add, list, and delete comments on tasks with user assignment -- **Custom Fields**: Read and write ClickUp custom fields, resolving names to option ids +- **Custom Fields**: Read and write ClickUp custom fields, resolving names to option ids, and find tasks by field value - **Cache Management**: Optimize performance with intelligent caching and cache control commands - **Project Configuration**: Set project-specific defaults with `.cu.yml` configuration files - **API Passthrough**: Direct access to ClickUp API endpoints for advanced operations @@ -122,6 +122,9 @@ cu field set Machine "Chilastra,Sunrunner" # Clear a value cu field clear "Last synced" + +# Reverse lookup: find the task whose field holds a given value +cu field find Repo https://github.com/owner/repo ``` ### Machine-readable output diff --git a/docs/site/commands/cu_export_tasks.md b/docs/site/commands/cu_export_tasks.md index dc8718d..695477e 100644 --- a/docs/site/commands/cu_export_tasks.md +++ b/docs/site/commands/cu_export_tasks.md @@ -30,10 +30,12 @@ cu export tasks [flags] -F, --file string Write to a file instead of stdout -f, --format string Export format (csv, json, markdown) (default "csv") -h, --help help for tasks + --include-closed Include closed tasks in the export -l, --list string List ID to export tasks from --priority string Filter by priority -s, --space string Space ID to export tasks from --status string Filter by status + --subtasks Include subtasks in the export ``` ### Options inherited from parent commands diff --git a/docs/site/commands/cu_field.md b/docs/site/commands/cu_field.md index 544f8a2..7ca2c0c 100644 --- a/docs/site/commands/cu_field.md +++ b/docs/site/commands/cu_field.md @@ -28,6 +28,7 @@ for dropdowns and labels — so names can be used on the command line. * [cu](cu.md) - A GitHub CLI-inspired command-line interface for ClickUp * [cu field clear](cu_field_clear.md) - Clear a custom field value on a task +* [cu field find](cu_field_find.md) - Find tasks whose custom field equals a value * [cu field get](cu_field_get.md) - Show custom field values on a task * [cu field list](cu_field_list.md) - List custom fields available on a list * [cu field set](cu_field_set.md) - Set a custom field value on a task diff --git a/docs/site/commands/cu_field_find.md b/docs/site/commands/cu_field_find.md new file mode 100644 index 0000000..b189331 --- /dev/null +++ b/docs/site/commands/cu_field_find.md @@ -0,0 +1,44 @@ +## cu field find + +Find tasks whose custom field equals a value + +### Synopsis + +Find tasks across the workspace whose custom field equals a value. + +Filtering happens server-side via Get Filtered Team Tasks, so this does not walk +every list. This is the reverse lookup: from an external identifier stored in a +custom field back to the task that owns it. + +A field id (a UUID) works anywhere and is used as given. A field *name* has to +be resolved against a list, so pass --list or set a default; the resolved field +itself is workspace-wide. + +Examples: + cu field find Repo https://github.com/owner/repo + cu field find a5013cb5-9244-49be-a6a2-90e1cc8a1d31 https://github.com/owner/repo + +``` +cu field find [flags] +``` + +### Options + +``` + -h, --help help for find + -l, --list string List used to resolve a field name to an id (defaults to the configured default list) +``` + +### Options inherited from parent commands + +``` + --config string config file (default is $HOME/.config/cu/config.yaml) + --debug enable debug mode + -o, --output string output format (table|json|yaml|csv) (default "table") +``` + +### SEE ALSO + +* [cu field](cu_field.md) - Manage custom field values + +###### Auto generated by spf13/cobra on 15-Nov-2026 diff --git a/docs/site/commands/cu_task_search.md b/docs/site/commands/cu_task_search.md index 047dc31..ef7a023 100644 --- a/docs/site/commands/cu_task_search.md +++ b/docs/site/commands/cu_task_search.md @@ -14,10 +14,12 @@ cu task search [query] [flags] ``` -h, --help help for search + --include-closed Include closed tasks in the search --include-description Search in task descriptions as well as names --limit int Maximum number of results to return (default 50) -l, --list string Limit search to specific list -s, --space string Limit search to specific space + --subtasks Include subtasks in the search ``` ### Options inherited from parent commands diff --git a/internal/api/teamtasks.go b/internal/api/teamtasks.go new file mode 100644 index 0000000..3d1cbba --- /dev/null +++ b/internal/api/teamtasks.go @@ -0,0 +1,228 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strconv" + + "github.com/raksul/go-clickup/clickup" +) + +// tasksPerPage is the page size ClickUp uses for paged task endpoints. It is +// fixed server-side, so a short page means the last page. +const tasksPerPage = 100 + +// DefaultMaxTaskPages bounds pagination so a mistaken filter cannot walk an +// entire workspace forever under the rate limiter. Callers that genuinely want +// everything can set TeamTaskQuery.MaxPages. +const DefaultMaxTaskPages = 50 + +// TeamTaskQuery filters a workspace-wide task search. Zero values mean "no +// filter", matching the API. +type TeamTaskQuery struct { + Statuses []string + Assignees []string // user ids; the endpoint does not accept usernames + Tags []string + + // Location filters. Applying these server-side matters: filtering after + // the fact runs into MaxPages first, so a narrow space in a large + // workspace could come back empty and merely "truncated". + SpaceIDs []string + ProjectIDs []string // folder ids — the API still calls folders projects + ListIDs []string + + IncludeClosed bool + Subtasks bool + Archived bool + OrderBy string + Reverse bool + + // CustomFields filters server-side on custom field values — the only way + // to answer "which task has Repo = X" without walking every list. + CustomFields clickup.CustomFieldsInGetTasksRequest + + // MaxPages bounds pagination; zero means DefaultMaxTaskPages. + MaxPages int +} + +// values encodes the query for GET /team/{team_id}/task. +// +// This is built by hand rather than through clickup.GetTasksOptions for two +// reasons: the SDK has no space_ids[]/project_ids[]/list_ids[], and its +// custom_fields encoder concatenates JSON strings without escaping, so a value +// containing a quote or backslash produced a malformed filter. +func (q *TeamTaskQuery) values(page int) (url.Values, error) { + v := url.Values{} + v.Set("page", strconv.Itoa(page)) + + setBool := func(key string, b bool) { + if b { + v.Set(key, "true") + } + } + setBool("include_closed", q.IncludeClosed) + setBool("subtasks", q.Subtasks) + setBool("archived", q.Archived) + setBool("reverse", q.Reverse) + if q.OrderBy != "" { + v.Set("order_by", q.OrderBy) + } + + for key, vals := range map[string][]string{ + "statuses[]": q.Statuses, + "assignees[]": q.Assignees, + "tags[]": q.Tags, + "space_ids[]": q.SpaceIDs, + "project_ids[]": q.ProjectIDs, + "list_ids[]": q.ListIDs, + } { + for _, val := range vals { + v.Add(key, val) + } + } + + if len(q.CustomFields) > 0 { + cf, err := encodeCustomFieldFilter(q.CustomFields) + if err != nil { + return nil, err + } + v.Set("custom_fields", cf) + } + return v, nil +} + +// customFieldFilter is the JSON shape the endpoint expects for each +// custom_fields entry. Value is a bare string for one value and an array for +// several, matching what the API documents. +type customFieldFilter struct { + FieldID string `json:"field_id"` + Operator string `json:"operator"` + Value any `json:"value,omitempty"` +} + +func encodeCustomFieldFilter(fields clickup.CustomFieldsInGetTasksRequest) (string, error) { + out := make([]customFieldFilter, 0, len(fields)) + for _, f := range fields { + entry := customFieldFilter{FieldID: f.FieldId, Operator: f.Operator.String()} + switch len(f.Value) { + case 0: + case 1: + entry.Value = f.Value[0] + default: + entry.Value = f.Value + } + out = append(out, entry) + } + b, err := json.Marshal(out) + if err != nil { + return "", err + } + return string(b), nil +} + +// TaskPageResult reports what a paged fetch actually covered, so callers can +// tell "no more results" from "we stopped early". +type TaskPageResult struct { + Tasks []clickup.Task + Pages int + Truncated bool // hit MaxPages with a full page still coming back +} + +// paginate walks pages until a short page (the last one) or maxPages, whichever +// comes first. Kept separate from the API calls so the termination and +// truncation rules are testable without a network round trip. +func paginate(maxPages int, fetch func(page int) ([]clickup.Task, error)) (*TaskPageResult, error) { + if maxPages <= 0 { + maxPages = DefaultMaxTaskPages + } + + result := &TaskPageResult{} + for page := 0; page < maxPages; page++ { + tasks, err := fetch(page) + if err != nil { + return nil, err + } + + result.Tasks = append(result.Tasks, tasks...) + result.Pages = page + 1 + + // A short page is the last page. + if len(tasks) < tasksPerPage { + return result, nil + } + } + + // Stopped at the cap with a full page still arriving — the caller must be + // able to say so rather than present a partial set as complete. + result.Truncated = true + return result, nil +} + +// SearchTeamTasks queries the workspace-wide Get Filtered Team Tasks endpoint, +// paging until exhaustion. +// +// This replaces walking workspace → spaces → folders → lists and calling +// GetTasks per list: that fan-out costs one request per list under a 100 +// req/min limit, and it only ever fetched page 0, so any list past 100 tasks +// was silently cut off. +func (c *Client) SearchTeamTasks(ctx context.Context, teamID string, query *TeamTaskQuery) (*TaskPageResult, error) { + if query == nil { + query = &TeamTaskQuery{} + } + return paginate(query.MaxPages, func(page int) ([]clickup.Task, error) { + if err := c.rateLimiter.Wait(ctx); err != nil { + return nil, err + } + v, err := query.values(page) + if err != nil { + return nil, err + } + req, err := c.client.NewRequest(http.MethodGet, fmt.Sprintf("team/%s/task?%s", url.PathEscape(teamID), v.Encode()), nil) + if err != nil { + return nil, err + } + var resp clickup.GetTasksResponse + if _, err := c.client.Do(ctx, req, &resp); err != nil { + return nil, c.handleError(err) + } + return resp.Tasks, nil + }) +} + +// ListTasksAllPages pages a single list to exhaustion. GetTasks fetches only +// the page it is asked for, so callers that want a whole list need this. +func (c *Client) ListTasksAllPages(ctx context.Context, listID string, options *TaskQueryOptions, maxPages int) (*TaskPageResult, error) { + if options == nil { + options = &TaskQueryOptions{} + } + return paginate(maxPages, func(page int) ([]clickup.Task, error) { + opts := *options + opts.Page = page + return c.GetTasks(ctx, listID, &opts) + }) +} + +// FindTasksByCustomField returns the tasks in a workspace whose custom field +// equals value — the reverse lookup from an external identifier back to a task. +// The page result is returned whole so callers can report truncation. +func (c *Client) FindTasksByCustomField(ctx context.Context, teamID, fieldID, value string) (*TaskPageResult, error) { + if fieldID == "" { + return nil, fmt.Errorf("a custom field id is required") + } + + query := &TeamTaskQuery{ + IncludeClosed: true, // a match must not depend on the task being open + CustomFields: clickup.CustomFieldsInGetTasksRequest{ + { + FieldId: fieldID, + Operator: clickup.Equals, + Value: []string{value}, + }, + }, + } + + return c.SearchTeamTasks(ctx, teamID, query) +} diff --git a/internal/api/teamtasks_test.go b/internal/api/teamtasks_test.go new file mode 100644 index 0000000..d3b4dc5 --- /dev/null +++ b/internal/api/teamtasks_test.go @@ -0,0 +1,252 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "testing" + + "github.com/raksul/go-clickup/clickup" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// pages builds a fetch func returning the given page sizes, recording which +// pages were actually requested. +func pages(sizes ...int) (func(int) ([]clickup.Task, error), *[]int) { + var requested []int + return func(page int) ([]clickup.Task, error) { + requested = append(requested, page) + if page >= len(sizes) { + return nil, nil + } + return make([]clickup.Task, sizes[page]), nil + }, &requested +} + +func TestPaginate(t *testing.T) { + t.Run("stops on the first short page", func(t *testing.T) { + fetch, requested := pages(tasksPerPage, tasksPerPage, 7) + + res, err := paginate(0, fetch) + require.NoError(t, err) + + assert.Len(t, res.Tasks, tasksPerPage*2+7) + assert.Equal(t, 3, res.Pages) + assert.False(t, res.Truncated) + assert.Equal(t, []int{0, 1, 2}, *requested, "pages are requested in order, and no further") + }) + + t.Run("a single short page is one request", func(t *testing.T) { + fetch, requested := pages(5) + + res, err := paginate(0, fetch) + require.NoError(t, err) + + assert.Len(t, res.Tasks, 5) + assert.Equal(t, []int{0}, *requested) + }) + + t.Run("an empty first page terminates", func(t *testing.T) { + fetch, requested := pages(0) + + res, err := paginate(0, fetch) + require.NoError(t, err) + + assert.Empty(t, res.Tasks) + assert.Equal(t, 1, res.Pages) + assert.False(t, res.Truncated) + assert.Equal(t, []int{0}, *requested) + }) + + t.Run("an exactly-full last page costs one extra request", func(t *testing.T) { + // A full page is indistinguishable from "more to come", so the next + // page must be requested to learn the set is exhausted. + fetch, requested := pages(tasksPerPage, 0) + + res, err := paginate(0, fetch) + require.NoError(t, err) + + assert.Len(t, res.Tasks, tasksPerPage) + assert.False(t, res.Truncated) + assert.Equal(t, []int{0, 1}, *requested) + }) + + t.Run("hitting the cap reports truncation instead of pretending completeness", func(t *testing.T) { + fetch, requested := pages(tasksPerPage, tasksPerPage, tasksPerPage, tasksPerPage) + + res, err := paginate(2, fetch) + require.NoError(t, err) + + assert.Len(t, res.Tasks, tasksPerPage*2) + assert.Equal(t, 2, res.Pages) + assert.True(t, res.Truncated, "callers must be able to tell a capped result from a complete one") + assert.Equal(t, []int{0, 1}, *requested, "the cap is respected exactly") + }) + + t.Run("errors abort rather than returning a partial page set", func(t *testing.T) { + boom := errors.New("boom") + fetch := func(page int) ([]clickup.Task, error) { + if page == 1 { + return nil, boom + } + return make([]clickup.Task, tasksPerPage), nil + } + + res, err := paginate(0, fetch) + require.ErrorIs(t, err, boom) + assert.Nil(t, res, "a partial result must not be mistaken for a complete one") + }) +} + +func TestTeamTaskQueryValues(t *testing.T) { + t.Run("empty filters are omitted", func(t *testing.T) { + v, err := (&TeamTaskQuery{}).values(3) + require.NoError(t, err) + + assert.Equal(t, url.Values{"page": {"3"}}, v) + }) + + t.Run("filters are passed through", func(t *testing.T) { + q := &TeamTaskQuery{ + Statuses: []string{"in review", "open"}, + Assignees: []string{"123"}, + Tags: []string{"unreleased"}, + SpaceIDs: []string{"s1"}, + ProjectIDs: []string{"f1"}, + ListIDs: []string{"l1", "l2"}, + IncludeClosed: true, + Subtasks: true, + OrderBy: "updated", + Reverse: true, + } + + v, err := q.values(0) + require.NoError(t, err) + + assert.Equal(t, "0", v.Get("page"), "page 0 is sent explicitly") + assert.Equal(t, []string{"in review", "open"}, v["statuses[]"]) + assert.Equal(t, []string{"123"}, v["assignees[]"]) + assert.Equal(t, []string{"unreleased"}, v["tags[]"]) + assert.Equal(t, []string{"s1"}, v["space_ids[]"]) + assert.Equal(t, []string{"f1"}, v["project_ids[]"]) + assert.Equal(t, []string{"l1", "l2"}, v["list_ids[]"]) + assert.Equal(t, "true", v.Get("include_closed")) + assert.Equal(t, "true", v.Get("subtasks")) + assert.Equal(t, "updated", v.Get("order_by")) + assert.Equal(t, "true", v.Get("reverse")) + assert.Empty(t, v.Get("archived")) + }) + + t.Run("custom field values are JSON-escaped", func(t *testing.T) { + q := &TeamTaskQuery{CustomFields: clickup.CustomFieldsInGetTasksRequest{ + {FieldId: "f1", Operator: clickup.Equals, Value: []string{`say "hi" \ bye`}}, + {FieldId: "f2", Operator: clickup.Any, Value: []string{"a", `b"c`}}, + {FieldId: "f3", Operator: clickup.IsNull}, + }} + + v, err := q.values(0) + require.NoError(t, err) + + raw := v.Get("custom_fields") + var decoded []map[string]any + require.NoError(t, json.Unmarshal([]byte(raw), &decoded), "must be valid JSON: %s", raw) + require.Len(t, decoded, 3) + assert.Equal(t, `say "hi" \ bye`, decoded[0]["value"]) + assert.Equal(t, "=", decoded[0]["operator"]) + assert.Equal(t, []any{"a", `b"c`}, decoded[1]["value"]) + assert.NotContains(t, decoded[2], "value") + }) +} + +// pagedServer serves page sizes in order for path, recording every raw query. +func pagedServer(t *testing.T, path string, sizes ...int) (*httptest.Server, *[]string) { + t.Helper() + var queries []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != path { + http.NotFound(w, r) + return + } + queries = append(queries, r.URL.RawQuery) + + page, _ := strconv.Atoi(r.URL.Query().Get("page")) + n := 0 + if page < len(sizes) { + n = sizes[page] + } + tasks := make([]clickup.Task, n) + for i := range tasks { + tasks[i].ID = fmt.Sprintf("p%d-%d", page, i) + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(clickup.GetTasksResponse{Tasks: tasks}) + })) + t.Cleanup(srv.Close) + return srv, &queries +} + +func TestSearchTeamTasksOverHTTP(t *testing.T) { + srv, queries := pagedServer(t, "/team/T1/task", 100, 100, 3) + c := newTestClient(t, srv) + + res, err := c.SearchTeamTasks(context.Background(), "T1", &TeamTaskQuery{ + SpaceIDs: []string{"S9"}, + Statuses: []string{"in progress"}, + CustomFields: clickup.CustomFieldsInGetTasksRequest{ + {FieldId: "f1", Operator: clickup.Equals, Value: []string{`a"b\c`}}, + }, + }) + require.NoError(t, err) + + assert.Len(t, res.Tasks, 203) + assert.Equal(t, 3, res.Pages) + assert.False(t, res.Truncated) + require.Len(t, *queries, 3) + + wantCF := url.QueryEscape(`[{"field_id":"f1","operator":"=","value":"a\"b\\c"}]`) + for i, raw := range *queries { + // url.Values.Encode sorts keys, so the raw string is deterministic. + want := "custom_fields=" + wantCF + + "&page=" + strconv.Itoa(i) + + "&space_ids%5B%5D=S9" + + "&statuses%5B%5D=in+progress" + assert.Equal(t, want, raw, "page %d", i) + } +} + +func TestSearchTeamTasksReportsTruncation(t *testing.T) { + srv, queries := pagedServer(t, "/team/T1/task", 100, 100, 100) + c := newTestClient(t, srv) + + res, err := c.SearchTeamTasks(context.Background(), "T1", &TeamTaskQuery{MaxPages: 2}) + require.NoError(t, err) + + assert.Len(t, res.Tasks, 200) + assert.True(t, res.Truncated) + assert.Len(t, *queries, 2) +} + +func TestListTasksAllPagesOverHTTP(t *testing.T) { + srv, queries := pagedServer(t, "/list/L1/task", 100, 100, 3) + c := newTestClient(t, srv) + + res, err := c.ListTasksAllPages(context.Background(), "L1", &TaskQueryOptions{ + Statuses: []string{"open"}, + }, 0) + require.NoError(t, err) + + assert.Len(t, res.Tasks, 203) + assert.False(t, res.Truncated) + // The SDK omits page=0, so the first request carries only the filter. + assert.Equal(t, []string{ + "statuses%5B%5D=open", + "page=1&statuses%5B%5D=open", + "page=2&statuses%5B%5D=open", + }, *queries) +} diff --git a/internal/cmd/export.go b/internal/cmd/export.go index 6661a68..a4fce05 100644 --- a/internal/cmd/export.go +++ b/internal/cmd/export.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "path/filepath" + "strconv" "strings" "time" @@ -91,12 +92,20 @@ Examples: } } - tasks, err = client.GetTasks(ctx, listID, queryOpts) + res, err := client.ListTasksAllPages(ctx, listID, queryOpts, 0) if err != nil { fmt.Fprintf(os.Stderr, "Failed to get tasks: %v\n", err) os.Exit(1) } + if res.Truncated { + fmt.Fprintf(os.Stderr, "Warning: stopped after %d pages; export may be incomplete.\n", api.DefaultMaxTaskPages) + } + tasks = res.Tasks } else { + // Defaults mirror the previous crawl (open tasks, no subtasks). + includeClosed, _ := cmd.Flags().GetBool("include-closed") + includeSubtasks, _ := cmd.Flags().GetBool("subtasks") + // Get all tasks from workspace or space workspaces, err := client.GetWorkspaces(ctx) if err != nil { @@ -104,42 +113,67 @@ Examples: os.Exit(1) } + // One server-side query per workspace instead of walking + // spaces → folders → lists. The crawl discarded GetFolders and + // GetLists errors, so an export could silently omit whole + // subtrees and still look successful. + // + // --space, --status and --assignee go to the server so they + // narrow the paged set; applied afterwards they would run into + // the page cap first and a narrow filter could come back empty. + var truncated, spaceFound bool for _, workspace := range workspaces { - spaces, err := client.GetSpaces(ctx, workspace.ID) - if err != nil { - continue + query := &api.TeamTaskQuery{ + IncludeClosed: includeClosed, + Subtasks: includeSubtasks, } - - for _, space := range spaces { - if spaceID != "" && space.ID != spaceID && space.Name != spaceID { - continue + if spaceID != "" { + id, err := resolveSpaceInWorkspace(ctx, client, workspace, spaceID) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) } - - // Get tasks from all lists in space - folders, _ := client.GetFolders(ctx, space.ID) - for _, folder := range folders { - lists, _ := client.GetLists(ctx, folder.ID) - for _, list := range lists { - listTasks, err := client.GetTasks(ctx, list.ID, &api.TaskQueryOptions{}) - if err == nil { - tasks = append(tasks, listTasks...) - } - } + if id == "" { + continue // the space lives in another workspace } - - // Get folderless lists - lists, _ := client.GetFolderlessLists(ctx, space.ID) - for _, list := range lists { - listTasks, err := client.GetTasks(ctx, list.ID, &api.TaskQueryOptions{}) - if err == nil { - tasks = append(tasks, listTasks...) - } + query.SpaceIDs = []string{id} + spaceFound = true + } + if status != "" { + query.Statuses = []string{status} + } + if assignee != "" { + id, err := resolveAssigneeInWorkspace(ctx, client, workspace.ID, assignee) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + if id == "" { + continue // not a member here, so no tasks can match } + query.Assignees = []string{id} } + + res, err := client.SearchTeamTasks(ctx, workspace.ID, query) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to read tasks for workspace %s: %v\n", workspace.Name, err) + os.Exit(1) + } + tasks = append(tasks, res.Tasks...) + truncated = truncated || res.Truncated + } + + if spaceID != "" && !spaceFound { + fmt.Fprintf(os.Stderr, "Space not found: %s\n", spaceID) + os.Exit(1) + } + if truncated { + fmt.Fprintf(os.Stderr, "Warning: stopped after %d pages; export may be incomplete. Narrow it with --space, --status or --assignee.\n", api.DefaultMaxTaskPages) } - // Client-side filtering - tasks = filterTasksForExport(tasks, status, priority, assignee) + // The endpoint has no priority filter, so that one stays + // client-side. + tasks = filterTasksForExport(tasks, "", priority, "") } // Open output file or use stdout @@ -248,6 +282,24 @@ func unsupportedExportFormat(flag, value string) error { return base } +// resolveAssigneeInWorkspace maps an --assignee value (user id or username) to +// the user id the endpoint's assignees[] filter needs. It returns "" when the +// username is not a member of the workspace. +func resolveAssigneeInWorkspace(ctx context.Context, client *api.Client, workspaceID, assignee string) (string, error) { + if _, err := strconv.Atoi(assignee); err == nil { + return assignee, nil + } + lookup := client.UserLookup() + if err := lookup.LoadWorkspaceUsers(ctx, workspaceID); err != nil { + return "", fmt.Errorf("failed to load workspace members to resolve %s: %w", assignee, err) + } + user, err := lookup.LookupByUsername(assignee) + if err != nil { + return "", nil + } + return strconv.Itoa(user.ID), nil +} + func filterTasksForExport(tasks []clickup.Task, status, priority, assignee string) []clickup.Task { var filtered []clickup.Task @@ -413,6 +465,8 @@ func init() { exportTasksCmd.Flags().StringP("list", "l", "", "List ID to export tasks from") exportTasksCmd.Flags().StringP("space", "s", "", "Space ID to export tasks from") exportTasksCmd.Flags().StringP("format", "f", "csv", "Export format (csv, json, markdown)") + exportTasksCmd.Flags().Bool("include-closed", false, "Include closed tasks in the export") + exportTasksCmd.Flags().Bool("subtasks", false, "Include subtasks in the export") // Deliberately not "output"/-o: that is the global format flag, and // redefining it here shadowed it, so `-o json` wrote a file named "json". exportTasksCmd.Flags().StringP("file", "F", "", "Write to a file instead of stdout") diff --git a/internal/cmd/field.go b/internal/cmd/field.go index 72e3f57..bca99a5 100644 --- a/internal/cmd/field.go +++ b/internal/cmd/field.go @@ -3,6 +3,8 @@ package cmd import ( "context" "fmt" + "os" + "regexp" "github.com/raksul/go-clickup/clickup" "github.com/spf13/cobra" @@ -210,6 +212,111 @@ func resolveTaskField(ctx context.Context, client *api.Client, taskID, nameOrID return api.FindCustomField(fields, nameOrID) } +var fieldFindCmd = &cobra.Command{ + Use: "find ", + Short: "Find tasks whose custom field equals a value", + Long: `Find tasks across the workspace whose custom field equals a value. + +Filtering happens server-side via Get Filtered Team Tasks, so this does not walk +every list. This is the reverse lookup: from an external identifier stored in a +custom field back to the task that owns it. + +A field id (a UUID) works anywhere and is used as given. A field *name* has to +be resolved against a list, so pass --list or set a default; the resolved field +itself is workspace-wide. + +Examples: + cu field find Repo https://github.com/owner/repo + cu field find a5013cb5-9244-49be-a6a2-90e1cc8a1d31 https://github.com/owner/repo`, + Args: cobra.ExactArgs(2), + SilenceUsage: true, // API and lookup failures are not usage errors + RunE: func(cmd *cobra.Command, args []string) error { + name, value := args[0], args[1] + + client, err := api.NewClient() + if err != nil { + return err + } + ctx := context.Background() + + fieldID, err := resolveFieldID(ctx, client, cmd, name) + if err != nil { + return err + } + + workspaces, err := client.GetWorkspaces(ctx) + if err != nil { + return err + } + + rows := []taskMatchRow{} // "[]", not "null", when nothing matches + var truncated bool + for _, w := range workspaces { + res, err := client.FindTasksByCustomField(ctx, w.ID, fieldID, value) + if err != nil { + return err + } + truncated = truncated || res.Truncated + for _, t := range res.Tasks { + rows = append(rows, taskMatchRow{ + ID: t.ID, + Name: t.Name, + Status: t.Status.Status, + List: t.List.Name, + URL: t.URL, + }) + } + } + + if truncated { + fmt.Fprintf(os.Stderr, "Warning: stopped after %d pages; matches may be incomplete.\n", api.DefaultMaxTaskPages) + } + + return output.Format(outputFormat, rows) + }, +} + +// taskMatchRow is the shape `field find` reports, kept narrow so the output is +// usable as input to other commands. +type taskMatchRow struct { + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Status string `json:"status" yaml:"status"` + List string `json:"list" yaml:"list"` + URL string `json:"url" yaml:"url"` +} + +// fieldIDPattern matches ClickUp custom field ids, which are UUIDs. +var fieldIDPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) + +// resolveFieldID accepts either a field id or a field name. An id is used as +// given — fields are workspace-wide, so it must not be checked against a list +// it may not belong to. A name is looked up against a list, since fields are +// only enumerable per list. +func resolveFieldID(ctx context.Context, client *api.Client, cmd *cobra.Command, nameOrID string) (string, error) { + if fieldIDPattern.MatchString(nameOrID) { + return nameOrID, nil + } + + listID, _ := cmd.Flags().GetString("list") + if listID == "" { + listID = config.GetString("default_list") + } + if listID == "" { + return "", fmt.Errorf("%q is not a field id; pass --list (or set a default list) so the field name can be resolved", nameOrID) + } + + fields, err := client.GetCustomFields(ctx, listID) + if err != nil { + return "", err + } + field, err := api.FindCustomField(fields, nameOrID) + if err != nil { + return "", err + } + return field.ID, nil +} + func init() { fieldListCmd.Flags().StringP("list", "l", "", "List ID (defaults to the configured default list)") @@ -217,4 +324,7 @@ func init() { fieldCmd.AddCommand(fieldGetCmd) fieldCmd.AddCommand(fieldSetCmd) fieldCmd.AddCommand(fieldClearCmd) + + fieldFindCmd.Flags().StringP("list", "l", "", "List used to resolve a field name to an id (defaults to the configured default list)") + fieldCmd.AddCommand(fieldFindCmd) } diff --git a/internal/cmd/field_test.go b/internal/cmd/field_test.go new file mode 100644 index 0000000..634d6f0 --- /dev/null +++ b/internal/cmd/field_test.go @@ -0,0 +1,44 @@ +package cmd + +import ( + "context" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestResolveFieldID(t *testing.T) { + newCmd := func() *cobra.Command { + c := &cobra.Command{} + c.Flags().StringP("list", "l", "", "") + return c + } + + t.Run("a field id is used as given, even with a default list", func(t *testing.T) { + prev := viper.Get("default_list") + viper.Set("default_list", "some-other-list") + t.Cleanup(func() { viper.Set("default_list", prev) }) + + // A nil client proves no list lookup happens for an id. + id, err := resolveFieldID(context.Background(), nil, newCmd(), "a5013cb5-9244-49be-a6a2-90e1cc8a1d31") + require.NoError(t, err) + assert.Equal(t, "a5013cb5-9244-49be-a6a2-90e1cc8a1d31", id) + }) + + t.Run("a name without any list is a clear error, not a raw API call", func(t *testing.T) { + prev := viper.Get("default_list") + viper.Set("default_list", "") + t.Cleanup(func() { viper.Set("default_list", prev) }) + + _, err := resolveFieldID(context.Background(), nil, newCmd(), "Repo") + require.Error(t, err) + assert.Contains(t, err.Error(), "--list") + }) + + t.Run("find does not print usage on API errors", func(t *testing.T) { + assert.True(t, fieldFindCmd.SilenceUsage) + }) +} diff --git a/internal/cmd/task.go b/internal/cmd/task.go index f802ae8..d307cfe 100644 --- a/internal/cmd/task.go +++ b/internal/cmd/task.go @@ -560,6 +560,8 @@ var taskSearchCmd = &cobra.Command{ spaceID, _ := cmd.Flags().GetString("space") listID, _ := cmd.Flags().GetString("list") searchDescription, _ := cmd.Flags().GetBool("include-description") + includeClosed, _ := cmd.Flags().GetBool("include-closed") + includeSubtasks, _ := cmd.Flags().GetBool("subtasks") limit, _ := cmd.Flags().GetInt("limit") // Get workspaces to search @@ -575,81 +577,66 @@ var taskSearchCmd = &cobra.Command{ } var allTasks []clickup.Task - var searchErrors []string + var truncated bool - // If specific list is provided, search only that list if listID != "" { - tasks, err := client.GetTasks(ctx, listID, &api.TaskQueryOptions{}) + // A single list is already a direct query; page it to exhaustion + // rather than returning only the first 100 tasks. + res, err := client.ListTasksAllPages(ctx, listID, &api.TaskQueryOptions{}, 0) if err != nil { fmt.Fprintf(os.Stderr, "Failed to get tasks from list %s: %v\n", listID, err) os.Exit(1) } - allTasks = tasks + allTasks = res.Tasks + truncated = res.Truncated } else { - // Search across all lists in workspace or space + // One server-side query per workspace, paged to exhaustion — + // instead of walking spaces → folders → lists and issuing a + // request per list, which cost a request per list under the + // 100 req/min limit and only ever read each list's first page. + spaceFound := false for _, workspace := range workspaces { - spaces, err := client.GetSpaces(ctx, workspace.ID) - if err != nil { - searchErrors = append(searchErrors, fmt.Sprintf("Failed to get spaces for workspace %s: %v", workspace.Name, err)) - continue - } - - for _, space := range spaces { - // Skip if specific space is requested and this isn't it - if spaceID != "" && space.ID != spaceID && space.Name != spaceID { - continue - } - - // Get folders in space - folders, err := client.GetFolders(ctx, space.ID) + // --space is applied server-side via space_ids[]; filtering + // afterwards would run into the page cap first. + var spaceIDs []string + if spaceID != "" { + id, err := resolveSpaceInWorkspace(ctx, client, workspace, spaceID) if err != nil { - searchErrors = append(searchErrors, fmt.Sprintf("Failed to get folders for space %s: %v", space.Name, err)) - continue + fmt.Fprintln(os.Stderr, err) + os.Exit(1) } - - // Get tasks from folders - for _, folder := range folders { - lists, err := client.GetLists(ctx, folder.ID) - if err != nil { - searchErrors = append(searchErrors, fmt.Sprintf("Failed to get lists for folder %s: %v", folder.Name, err)) - continue - } - - for _, list := range lists { - tasks, err := client.GetTasks(ctx, list.ID, &api.TaskQueryOptions{}) - if err != nil { - searchErrors = append(searchErrors, fmt.Sprintf("Failed to get tasks for list %s: %v", list.Name, err)) - continue - } - allTasks = append(allTasks, tasks...) - } - } - - // Get folderless lists - lists, err := client.GetFolderlessLists(ctx, space.ID) - if err != nil { - searchErrors = append(searchErrors, fmt.Sprintf("Failed to get folderless lists for space %s: %v", space.Name, err)) - continue + if id == "" { + continue // the space lives in another workspace } + spaceIDs = []string{id} + spaceFound = true + } - for _, list := range lists { - tasks, err := client.GetTasks(ctx, list.ID, &api.TaskQueryOptions{}) - if err != nil { - searchErrors = append(searchErrors, fmt.Sprintf("Failed to get tasks for list %s: %v", list.Name, err)) - continue - } - allTasks = append(allTasks, tasks...) - } + // Defaults mirror the previous per-list crawl (open tasks, + // no subtasks) so this stays a performance fix; the endpoint + // makes the fuller set reachable behind explicit flags. + res, err := client.SearchTeamTasks(ctx, workspace.ID, &api.TeamTaskQuery{ + SpaceIDs: spaceIDs, + IncludeClosed: includeClosed, + Subtasks: includeSubtasks, + }) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to search workspace %s: %v\n", workspace.Name, err) + os.Exit(1) } + allTasks = append(allTasks, res.Tasks...) + truncated = truncated || res.Truncated + } + if spaceID != "" && !spaceFound { + fmt.Fprintf(os.Stderr, "Space not found: %s\n", spaceID) + os.Exit(1) } } - // Print any errors encountered during search - if len(searchErrors) > 0 { - fmt.Fprintln(os.Stderr, "Some errors occurred during search:") - for _, err := range searchErrors { - fmt.Fprintf(os.Stderr, " - %s\n", err) - } + if truncated { + fmt.Fprintf(os.Stderr, + "Warning: stopped after %d pages; results may be incomplete. Narrow the search with --space or --list.\n", + api.DefaultMaxTaskPages) } // Filter tasks based on search query @@ -772,6 +759,8 @@ func init() { // Search command flags taskSearchCmd.Flags().StringP("space", "s", "", "Limit search to specific space") taskSearchCmd.Flags().StringP("list", "l", "", "Limit search to specific list") + taskSearchCmd.Flags().Bool("include-closed", false, "Include closed tasks in the search") + taskSearchCmd.Flags().Bool("subtasks", false, "Include subtasks in the search") taskSearchCmd.Flags().Bool("include-description", false, "Search in task descriptions as well as names") taskSearchCmd.Flags().Int("limit", 50, "Maximum number of results to return") } @@ -990,3 +979,19 @@ func getPriorityValue(priority string) int { return 3 // Default to normal } } + +// resolveSpaceInWorkspace maps a --space value (id or name) to a space id in +// one workspace. It returns "" when the workspace has no such space, so a +// multi-workspace caller can skip it. +func resolveSpaceInWorkspace(ctx context.Context, client *api.Client, workspace clickup.Team, idOrName string) (string, error) { + spaces, err := client.GetSpaces(ctx, workspace.ID) + if err != nil { + return "", fmt.Errorf("failed to resolve spaces for workspace %s: %w", workspace.Name, err) + } + for _, sp := range spaces { + if sp.ID == idOrName || sp.Name == idOrName { + return sp.ID, nil + } + } + return "", nil +} diff --git a/mkdocs.yml b/mkdocs.yml index c486d28..6063e87 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -65,6 +65,7 @@ nav: - cu field get: commands/cu_field_get.md - cu field set: commands/cu_field_set.md - cu field clear: commands/cu_field_clear.md + - cu field find: commands/cu_field_find.md - Comments: - cu comment: commands/cu_comment.md - cu comment list: commands/cu_comment_list.md