MCPcopy Create free account
hub / github.com/cli/cli / CreateJob

Method CreateJob

pkg/cmd/agent-task/capi/job.go:62–132  ·  view source on GitHub ↗

CreateJob queues a new job using the v1 Jobs API. It may or may not return Pull Request information. If Pull Request information is required following up by polling GetJob with the job ID is necessary.

(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string)

Source from the content-addressed store, hash-verified

60// return Pull Request information. If Pull Request information is required
61// following up by polling GetJob with the job ID is necessary.
62func (c *CAPIClient) CreateJob(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*Job, error) {
63 if owner == "" || repo == "" {
64 return nil, errors.New("owner and repo are required")
65 }
66 if problemStatement == "" {
67 return nil, errors.New("problem statement is required")
68 }
69
70 u, err := safeurl.JoinPathWithHostPrefix(c.jobsBasePathV1(), owner, repo)
71 if err != nil {
72 return nil, err
73 }
74
75 prOpts := JobPullRequest{}
76 if baseBranch != "" {
77 prOpts.BaseRef = "refs/heads/" + baseBranch
78 }
79
80 payload := &Job{
81 ProblemStatement: problemStatement,
82 CustomAgent: customAgent,
83 EventType: defaultEventType,
84 PullRequest: &prOpts,
85 }
86
87 b, _ := json.Marshal(payload)
88
89 req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(b))
90 if err != nil {
91 return nil, err
92 }
93 req.Header.Set("Content-Type", "application/json")
94 res, err := c.httpClient.Do(req)
95 if err != nil {
96 return nil, err
97 }
98 defer res.Body.Close()
99
100 body, _ := io.ReadAll(res.Body)
101
102 var j Job
103 if err := json.NewDecoder(bytes.NewReader(body)).Decode(&j); err != nil {
104 if res.StatusCode != http.StatusCreated && res.StatusCode != http.StatusOK { // accept 201 or 200
105 // This happens when there's an error like unauthorized (401).
106 statusText := fmt.Sprintf("%d %s", res.StatusCode, http.StatusText(res.StatusCode))
107 return nil, fmt.Errorf("failed to create job: %s", statusText)
108 }
109 return nil, fmt.Errorf("failed to decode create job response: %w", err)
110 }
111
112 if res.StatusCode != http.StatusCreated && res.StatusCode != http.StatusOK { // accept 201 or 200
113 statusText := fmt.Sprintf("%d %s", res.StatusCode, http.StatusText(res.StatusCode))
114
115 // If the response has error embedded, we can use that.
116 // TODO: Does this really ever happen?
117 if j.ErrorInfo != nil {
118 return nil, fmt.Errorf("failed to create job: %s: %s", statusText, j.ErrorInfo.Message)
119 }

Callers 2

TestCreateJobFunction · 0.95

Calls 7

jobsBasePathV1Method · 0.95
JoinPathWithHostPrefixFunction · 0.92
StringMethod · 0.65
SetMethod · 0.65
DoMethod · 0.65
CloseMethod · 0.65
ErrorfMethod · 0.65

Tested by 2

TestCreateJobFunction · 0.76