lazygocd 0.6.1

A fast, keyboard-driven terminal UI for GoCD pipelines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
use crate::config::Config;
use crate::model::{
    ArtifactNode, DashboardEmbedded, DashboardResponse, HistoryResponse, PipelineInstance,
    ViewFilters,
};
use anyhow::{Context, Result};
use reqwest::Method;
use reqwest::blocking::{Client, RequestBuilder};

#[derive(Clone)]
pub struct GoCdClient {
    client: Client,
    base_url: String,
    username: Option<String>,
    password: Option<String>,
    token: Option<String>,
    /// `--demo`: serve canned fixtures and never touch the network.
    demo: bool,
}

impl GoCdClient {
    pub fn new(cfg: &Config) -> Result<Self> {
        let client = Client::builder()
            .danger_accept_invalid_certs(cfg.insecure_skip_verify)
            // gzip (below) turns /api/dashboard's ~20s uncompressed transfer into ~2s;
            // keep a generous ceiling anyway for slow networks or unusually large orgs.
            .timeout(std::time::Duration::from_secs(45))
            // Separate connect deadline: a dead route (VPN drop) fails in seconds
            // instead of hanging until the full 45s response budget runs out.
            .connect_timeout(std::time::Duration::from_secs(8))
            .build()
            .context("building HTTP client")?;

        Ok(GoCdClient {
            client,
            base_url: cfg.server_url.trim_end_matches('/').to_string(),
            username: cfg.username.clone(),
            password: cfg.password.clone(),
            demo: false,
            token: cfg.auth_token.clone(),
        })
    }

    /// Demo client: no credentials, no requests, fixtures only.
    pub fn demo() -> Result<Self> {
        Ok(GoCdClient {
            client: Client::builder().build().context("building demo HTTP client")?,
            base_url: "demo".to_string(),
            username: None,
            password: None,
            token: None,
            demo: true,
        })
    }

    fn request(&self, method: Method, path: &str, api_version: u8) -> RequestBuilder {
        let url = format!("{}{}", self.base_url, path);
        let mut rb = self.client.request(method, url).header(
            "Accept",
            format!("application/vnd.go.cd.v{api_version}+json"),
        );
        if let Some(token) = &self.token {
            rb = rb.bearer_auth(token);
        } else if let Some(user) = &self.username {
            rb = rb.basic_auth(user, self.password.clone());
        }
        rb
    }

    /// /go/files/... is a plain file server, not the versioned JSON API - no
    /// vnd.go.cd Accept header here.
    fn request_raw(&self, method: Method, path: &str) -> RequestBuilder {
        let url = format!("{}{}", self.base_url, path);
        let mut rb = self.client.request(method, url);
        if let Some(token) = &self.token {
            rb = rb.bearer_auth(token);
        } else if let Some(user) = &self.username {
            rb = rb.basic_auth(user, self.password.clone());
        }
        rb
    }

    /// One call returns pipeline groups, membership, pause state, and latest-run
    /// status for every pipeline the user can see. Accept v4, verified against a
    /// real GoCD 23.5.0 instance; per-pipeline status polling doesn't scale.
    /// Pass the previous ETag to let the server answer 304 (returns Ok(None)),
    /// which skips the multi-MB payload on unchanged polls.
    pub fn fetch_dashboard(
        &self,
        etag: Option<&str>,
        view: Option<&str>,
    ) -> Result<Option<(DashboardEmbedded, Option<String>)>> {
        if self.demo {
            let parsed: DashboardResponse = serde_json::from_str(&crate::demo::dashboard_json(view))
                .context("parsing demo dashboard")?;
            return Ok(Some((parsed.embedded, Some("demo-etag".to_string()))));
        }
        let mut rb = self.request(Method::GET, "/api/dashboard", 4);
        if let Some(name) = view {
            // The server filters to the personalized view, same as the web UI's tabs.
            rb = rb.query(&[("viewName", name)]);
        }
        if let Some(tag) = etag {
            rb = rb.header("If-None-Match", tag);
        }
        let resp = rb.send().context("requesting dashboard")?;
        let status = resp.status();
        if status == reqwest::StatusCode::NOT_MODIFIED {
            return Ok(None);
        }
        let new_etag = resp
            .headers()
            .get(reqwest::header::ETAG)
            .and_then(|v| v.to_str().ok())
            .map(str::to_string);
        let body = resp.text().context("reading dashboard response body")?;
        if !status.is_success() {
            anyhow::bail!("GoCD returned {status} for dashboard: {}", truncate(&body));
        }
        let parsed: DashboardResponse = serde_json::from_str(&body)
            .with_context(|| format!("parsing dashboard response: {}", truncate(&body)))?;
        Ok(Some((parsed.embedded, new_etag)))
    }

    /// One page of run history, newest first. `after` is the cursor from the
    /// previous page's _links.next.href; None fetches the first page. Returns
    /// the page's runs plus the next-page cursor, if any.
    pub fn fetch_history_page(
        &self,
        pipeline_name: &str,
        after: Option<u64>,
    ) -> Result<(Vec<PipelineInstance>, Option<u64>)> {
        if self.demo {
            let parsed: HistoryResponse =
                serde_json::from_str(&crate::demo::history_json(pipeline_name, after))
                    .context("parsing demo history")?;
            let next = parsed
                .links
                .and_then(|l| l.next)
                .and_then(|n| crate::model::next_page_cursor(&n.href));
            return Ok((parsed.pipelines, next));
        }

        let mut path = format!("/api/pipelines/{pipeline_name}/history");
        if let Some(cursor) = after {
            path.push_str(&format!("?after={cursor}"));
        }
        let resp = self
            .request(Method::GET, &path, 1)
            .send()
            .with_context(|| format!("requesting history for {pipeline_name}"))?;
        let status = resp.status();
        let body = resp.text().context("reading history response body")?;
        if !status.is_success() {
            anyhow::bail!(
                "GoCD returned {status} for {pipeline_name} history: {}",
                truncate(&body)
            );
        }
        let parsed: HistoryResponse = serde_json::from_str(&body).with_context(|| {
            format!(
                "parsing history response for {pipeline_name}: {}",
                truncate(&body)
            )
        })?;
        let next = parsed
            .links
            .and_then(|l| l.next)
            .and_then(|n| crate::model::next_page_cursor(&n.href));
        Ok((parsed.pipelines, next))
    }

    pub fn trigger_pipeline(&self, pipeline_name: &str) -> Result<()> {
        if self.demo {
            return Ok(());
        }

        let path = format!("/api/pipelines/{pipeline_name}/schedule");
        let resp = self
            .request(Method::POST, &path, 1)
            .header("X-GoCD-Confirm", "true")
            .header("Content-Type", "application/json")
            .body("{}")
            .send()
            .with_context(|| format!("triggering {pipeline_name}"))?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            anyhow::bail!(
                "GoCD returned {status} triggering {pipeline_name}: {}",
                truncate(&body)
            );
        }
        Ok(())
    }

    /// Trigger with one-off environment variable overrides for this run.
    pub fn trigger_pipeline_with_vars(
        &self,
        pipeline_name: &str,
        vars: &[(String, String)],
    ) -> Result<()> {
        if self.demo {
            return Ok(());
        }

        let env: Vec<serde_json::Value> = vars
            .iter()
            .map(|(name, value)| serde_json::json!({ "name": name, "value": value, "secure": false }))
            .collect();
        let path = format!("/api/pipelines/{pipeline_name}/schedule");
        let resp = self
            .request(Method::POST, &path, 1)
            .header("X-GoCD-Confirm", "true")
            .json(&serde_json::json!({
                "environment_variables": env,
                "update_materials_before_scheduling": true,
            }))
            .send()
            .with_context(|| format!("triggering {pipeline_name} with variables"))?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            anyhow::bail!(
                "GoCD returned {status} triggering {pipeline_name}: {}",
                truncate(&body)
            );
        }
        Ok(())
    }

    /// Reruns only the failed jobs of a completed stage instance.
    pub fn rerun_failed_jobs(
        &self,
        pipeline_name: &str,
        pipeline_counter: i64,
        stage_name: &str,
        stage_counter: &str,
    ) -> Result<()> {
        if self.demo {
            return Ok(());
        }

        self.rerun(
            pipeline_name,
            pipeline_counter,
            stage_name,
            stage_counter,
            "run-failed-jobs",
        )
    }

    /// Reruns the whole stage instance (all jobs, passed ones included).
    pub fn rerun_stage(
        &self,
        pipeline_name: &str,
        pipeline_counter: i64,
        stage_name: &str,
        stage_counter: &str,
    ) -> Result<()> {
        if self.demo {
            return Ok(());
        }

        self.rerun(
            pipeline_name,
            pipeline_counter,
            stage_name,
            stage_counter,
            "run",
        )
    }

    fn rerun(
        &self,
        pipeline_name: &str,
        pipeline_counter: i64,
        stage_name: &str,
        stage_counter: &str,
        verb: &str,
    ) -> Result<()> {
        let path = format!(
            "/api/stages/{pipeline_name}/{pipeline_counter}/{stage_name}/{stage_counter}/{verb}"
        );
        let resp = self
            .request(Method::POST, &path, 3)
            .header("X-GoCD-Confirm", "true")
            .send()
            .with_context(|| format!("rerunning ({verb}) {pipeline_name}/{pipeline_counter}/{stage_name}/{stage_counter}"))?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            anyhow::bail!(
                "GoCD returned {status} rerunning stage: {}",
                truncate(&body)
            );
        }
        Ok(())
    }

    pub fn pause_pipeline(&self, pipeline_name: &str, cause: &str) -> Result<()> {
        if self.demo {
            return Ok(());
        }

        let path = format!("/api/pipelines/{pipeline_name}/pause");
        let resp = self
            .request(Method::POST, &path, 1)
            .header("X-GoCD-Confirm", "true")
            .json(&serde_json::json!({ "pause_cause": cause }))
            .send()
            .with_context(|| format!("pausing {pipeline_name}"))?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            anyhow::bail!(
                "GoCD returned {status} pausing {pipeline_name}: {}",
                truncate(&body)
            );
        }
        Ok(())
    }

    pub fn unpause_pipeline(&self, pipeline_name: &str) -> Result<()> {
        if self.demo {
            return Ok(());
        }

        let path = format!("/api/pipelines/{pipeline_name}/unpause");
        let resp = self
            .request(Method::POST, &path, 1)
            .header("X-GoCD-Confirm", "true")
            .send()
            .with_context(|| format!("unpausing {pipeline_name}"))?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            anyhow::bail!(
                "GoCD returned {status} unpausing {pipeline_name}: {}",
                truncate(&body)
            );
        }
        Ok(())
    }

    /// Cancels a currently-running stage instance. Does not affect future
    /// scheduling (that's pause/unpause) - this stops a build in flight.
    pub fn cancel_stage(
        &self,
        pipeline_name: &str,
        pipeline_counter: i64,
        stage_name: &str,
        stage_counter: &str,
    ) -> Result<()> {
        if self.demo {
            return Ok(());
        }

        let path = format!(
            "/api/stages/{pipeline_name}/{pipeline_counter}/{stage_name}/{stage_counter}/cancel"
        );
        let resp = self
            .request(Method::POST, &path, 3)
            .header("X-GoCD-Confirm", "true")
            .send()
            .with_context(|| {
                format!(
                    "cancelling {pipeline_name}/{pipeline_counter}/{stage_name}/{stage_counter}"
                )
            })?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            anyhow::bail!(
                "GoCD returned {status} cancelling stage: {}",
                truncate(&body)
            );
        }
        Ok(())
    }

    /// The user's personalized dashboard views plus the optimistic-lock ETag.
    /// Internal (unversioned-contract) endpoint, but stable in practice - the
    /// web dashboard itself uses it.
    pub fn fetch_views(&self) -> Result<(ViewFilters, Option<String>)> {
        if self.demo {
            let f: ViewFilters = serde_json::from_str(crate::demo::views_json())
                .context("parsing demo views")?;
            return Ok((f, Some("demo-etag".to_string())));
        }

        let resp = self
            .request(Method::GET, "/api/internal/pipeline_selection", 1)
            .send()
            .context("requesting personalized views")?;
        let status = resp.status();
        let etag = resp
            .headers()
            .get(reqwest::header::ETAG)
            .and_then(|v| v.to_str().ok())
            .map(|t| t.replace("--gzip", ""));
        let body = resp.text().context("reading views body")?;
        if !status.is_success() {
            anyhow::bail!(
                "GoCD returned {status} for pipeline_selection: {}",
                truncate(&body)
            );
        }
        let filters = serde_json::from_str(&body)
            .with_context(|| format!("parsing views: {}", truncate(&body)))?;
        Ok((filters, etag))
    }

    /// Create or update a personalized view: fetch-fresh, upsert, PUT back with
    /// If-Match so a concurrent web-UI edit fails loudly instead of being lost.
    pub fn save_view(&self, name: &str, pipelines: Vec<String>) -> Result<()> {
        if self.demo {
            return Ok(());
        }

        let (mut current, etag) = self.fetch_views()?;
        let new_filter = crate::model::ViewFilter {
            name: name.to_string(),
            kind: "whitelist".to_string(),
            state: Vec::new(),
            pipelines,
        };
        match current.filters.iter_mut().find(|f| f.name == name) {
            Some(existing) => *existing = new_filter,
            None => current.filters.push(new_filter),
        }
        let mut rb = self
            .request(Method::PUT, "/api/internal/pipeline_selection", 1)
            .header("Content-Type", "application/json")
            .json(&current);
        if let Some(tag) = etag {
            rb = rb.header("If-Match", tag);
        }
        let resp = rb.send().context("saving view")?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            anyhow::bail!("GoCD returned {status} saving view: {}", truncate(&body));
        }
        Ok(())
    }

    /// Artifact tree for one job instance, from the plain file-server .json listing.
    pub fn fetch_artifacts(
        &self,
        pipeline_name: &str,
        pipeline_counter: i64,
        stage_name: &str,
        stage_counter: &str,
        job_name: &str,
    ) -> Result<Vec<ArtifactNode>> {
        if self.demo {
            return serde_json::from_str(crate::demo::artifacts_json())
                .context("parsing demo artifacts");
        }

        let path = format!(
            "/files/{pipeline_name}/{pipeline_counter}/{stage_name}/{stage_counter}/{job_name}.json"
        );
        let resp = self
            .request_raw(Method::GET, &path)
            .send()
            .context("requesting artifacts")?;
        let status = resp.status();
        let body = resp.text().context("reading artifacts body")?;
        if !status.is_success() {
            anyhow::bail!("GoCD returned {status} for artifacts: {}", truncate(&body));
        }
        serde_json::from_str(&body)
            .with_context(|| format!("parsing artifacts: {}", truncate(&body)))
    }

    /// Raw job console output. Not part of the versioned JSON API - a plain
    /// text file server endpoint, works while the job is still running too.
    /// `start_line` is 0-based; nonzero returns only lines from there on, so
    /// tail-follow appends instead of re-downloading the whole log.
    pub fn fetch_console_log(
        &self,
        pipeline_name: &str,
        pipeline_counter: i64,
        stage_name: &str,
        stage_counter: &str,
        job_name: &str,
        start_line: usize,
    ) -> Result<String> {
        if self.demo {
            return Ok(crate::demo::console_log(start_line));
        }

        let mut path = format!(
            "/files/{pipeline_name}/{pipeline_counter}/{stage_name}/{stage_counter}/{job_name}/cruise-output/console.log"
        );
        if start_line > 0 {
            path.push_str(&format!("?startLineNumber={start_line}"));
        }
        let resp = self
            .request_raw(Method::GET, &path)
            .send()
            .context("requesting console log")?;
        let status = resp.status();
        let body = resp.text().context("reading console log body")?;
        if !status.is_success() {
            anyhow::bail!(
                "GoCD returned {status} for console log: {}",
                truncate(&body)
            );
        }
        Ok(body)
    }
}

/// Error bodies are normally GoCD JSON, but a proxy or load balancer in front of
/// it answers with an HTML page. Echoing that markup into a one-line status bar
/// is noise, so collapse it to something a person can act on.
fn truncate(s: &str) -> String {
    let t = s.trim();
    if t.starts_with('<') || t.to_ascii_lowercase().contains("<html") {
        return "a proxy or gateway answered instead of GoCD".to_string();
    }
    t.chars().take(300).collect()
}