coralogix-cli 0.1.33

Coralogix CLI - the observability backbone for AI agents and engineering teams.
Documentation
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
pub mod api;

use std::sync::Arc;

use anyhow::Result;
use colored::Colorize;
use serde_json::{json, Value};
use toon_format::encode_default as toon_encode;

use crate::config::OutputFormat;
use crate::execution::{fan_out, report_errors_and_collect_successes, ExecutionTarget};
use crate::render;
use api::{TeamGroup, TeamGroupsApi};

fn group_to_json(group: &TeamGroup, include_profile: bool, profile: &str) -> Value {
    let mut v = json!({
        "group_id": group.group_id,
        "name": group.display_name(),
        "description": group.display_description(),
        "team_id": group.team_id,
        "group_type": group.group_type,
        "created_at": group.created_at,
    });
    if include_profile {
        if let Value::Object(ref mut m) = v {
            m.insert("profile".to_string(), Value::String(profile.to_string()));
        }
    }
    v
}

fn read_from_file(path: &str) -> Result<Value> {
    let raw = if path == "-" {
        eprintln!("{}", "Reading team group definition from stdin...".dimmed());
        use std::io::Read;
        let mut buf = String::new();
        std::io::stdin().read_to_string(&mut buf)?;
        buf
    } else {
        eprintln!(
            "{}",
            format!("Reading team group definition from {path}...").dimmed()
        );
        std::fs::read_to_string(path)?
    };
    Ok(serde_json::from_str(&raw)?)
}

pub async fn run_list(targets: &[Arc<ExecutionTarget>], output: OutputFormat) -> Result<()> {
    eprintln!("{}", "Fetching team groups...".dimmed());
    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| async move {
        let api = TeamGroupsApi::new(&t.client);
        Ok(api.list().await?)
    })
    .await;

    let mut all_json: Vec<Value> = Vec::new();
    let mut all_items: Vec<(String, TeamGroup)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        // Print the team groups list page link to stderr once per profile.
        // Skip when there are no groups, since there's nothing to view.
        if !resp.groups.is_empty() {
            crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
                crate::console_url::iam_groups_url(b)
            })
            .await;
        }
        for group in resp.groups {
            all_json.push(group_to_json(&group, include_profile, &profile));
            all_items.push((profile.clone(), group));
        }
    }

    match output {
        OutputFormat::Json => render::render_json(&all_json)?,
        OutputFormat::Toon => {
            let toon =
                toon_encode(&all_json).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if all_items.is_empty() {
                render::print_no_results("No team groups found.");
                return Ok(());
            }
            let rows: Vec<Vec<String>> = all_items
                .iter()
                .map(|(profile, group)| {
                    vec![
                        profile.clone(),
                        group.group_id.clone().unwrap_or_default(),
                        group.display_name().to_string(),
                        String::new(), // Members count not available in list response
                        group.display_description().to_string(),
                    ]
                })
                .collect();
            render::render_table(
                &["Group ID", "Name", "Members Count", "Description"],
                rows,
                include_profile,
            );
        }
    }
    Ok(())
}

pub async fn run_get(
    targets: &[Arc<ExecutionTarget>],
    group_id: &str,
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", format!("Fetching team group {group_id}...").dimmed());
    let include_profile = targets.len() > 1;
    let group_id = group_id.to_string();

    let per_profile = fan_out(targets, |t| {
        let group_id = group_id.clone();
        async move {
            let api = TeamGroupsApi::new(&t.client);
            Ok(api.get_by_id(&group_id).await?)
        }
    })
    .await;

    let mut all_json: Vec<Value> = Vec::new();
    let mut all_items: Vec<(String, TeamGroup)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        if let Some(group) = resp.group {
            all_json.push(group_to_json(&group, include_profile, &profile));
            all_items.push((profile.clone(), group));
        }
    }

    match output {
        OutputFormat::Json => render::render_json_auto(&all_json)?,
        OutputFormat::Toon => {
            let toon =
                toon_encode(&all_json).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if all_items.is_empty() {
                render::print_no_results("Team group not found.");
                return Ok(());
            }
            let rows: Vec<Vec<String>> = all_items
                .iter()
                .map(|(profile, group)| {
                    vec![
                        profile.clone(),
                        group.group_id.clone().unwrap_or_default(),
                        group.display_name().to_string(),
                        group.display_description().to_string(),
                        group.group_type.clone().unwrap_or_default(),
                    ]
                })
                .collect();
            render::render_table(
                &["Group ID", "Name", "Description", "Type"],
                rows,
                include_profile,
            );
        }
    }
    Ok(())
}

pub async fn run_get_by_name(
    targets: &[Arc<ExecutionTarget>],
    name: &str,
    output: OutputFormat,
) -> Result<()> {
    eprintln!(
        "{}",
        format!("Fetching team group by name '{name}'...").dimmed()
    );
    let include_profile = targets.len() > 1;
    let name = name.to_string();

    let per_profile = fan_out(targets, |t| {
        let name = name.clone();
        async move {
            let api = TeamGroupsApi::new(&t.client);
            Ok(api.get_by_name(&name).await?)
        }
    })
    .await;

    let mut all_json: Vec<Value> = Vec::new();
    let mut all_items: Vec<(String, TeamGroup)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        if let Some(group) = resp.group {
            all_json.push(group_to_json(&group, include_profile, &profile));
            all_items.push((profile.clone(), group));
        }
    }

    match output {
        OutputFormat::Json => render::render_json_auto(&all_json)?,
        OutputFormat::Toon => {
            let toon =
                toon_encode(&all_json).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if all_items.is_empty() {
                render::print_no_results("Team group not found.");
                return Ok(());
            }
            let rows: Vec<Vec<String>> = all_items
                .iter()
                .map(|(profile, group)| {
                    vec![
                        profile.clone(),
                        group.group_id.clone().unwrap_or_default(),
                        group.display_name().to_string(),
                        group.display_description().to_string(),
                        group.group_type.clone().unwrap_or_default(),
                    ]
                })
                .collect();
            render::render_table(
                &["Group ID", "Name", "Description", "Type"],
                rows,
                include_profile,
            );
        }
    }
    Ok(())
}

pub async fn run_users(
    targets: &[Arc<ExecutionTarget>],
    group_id: &str,
    output: OutputFormat,
) -> Result<()> {
    eprintln!(
        "{}",
        format!("Fetching users in team group {group_id}...").dimmed()
    );
    let include_profile = targets.len() > 1;
    let group_id = group_id.to_string();

    let per_profile = fan_out(targets, |t| {
        let group_id = group_id.clone();
        async move {
            let api = TeamGroupsApi::new(&t.client);
            let resp = api.get_users(&group_id).await?;
            Ok(serde_json::to_value(resp.users)?)
        }
    })
    .await;

    let mut all_results: Vec<Value> = Vec::new();
    for (profile, mut val) in report_errors_and_collect_successes(per_profile)? {
        if include_profile {
            render::tag_get_result(&mut val, &profile);
        }
        all_results.push(val);
    }

    match output {
        OutputFormat::Json => render::render_json_auto(&all_results)?,
        OutputFormat::Toon => {
            let toon = toon_encode(&all_results)
                .map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            render::render_get_text(
                &all_results,
                include_profile,
                "No users found in group.",
                None::<&dyn Fn(&Value)>,
            )?;
        }
    }
    Ok(())
}

pub async fn run_create(
    targets: &[Arc<ExecutionTarget>],
    from_file: &str,
    output: OutputFormat,
) -> Result<()> {
    let body = read_from_file(from_file)?;
    eprintln!("{}", "Creating team group...".dimmed());
    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| {
        let body = body.clone();
        async move {
            let api = TeamGroupsApi::new(&t.client);
            Ok(api.create(&body).await?)
        }
    })
    .await;

    let mut all_results: Vec<Value> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        if let Some(group) = resp.group {
            let name = group.display_name().to_string();
            render::print_created(
                "Created",
                "team group",
                Some(&name),
                group.group_id.as_deref(),
                &profile,
            );
            if let Some(id) = group.group_id.as_deref() {
                crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
                    crate::console_url::iam_group_url(b, id)
                })
                .await;
            }
            let group_json = group_to_json(&group, include_profile, &profile);
            all_results.push(group_json);
        }
    }

    match output {
        OutputFormat::Json => render::render_json_auto(&all_results)?,
        OutputFormat::Toon => {
            let toon = toon_encode(&all_results)
                .map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {}
    }
    Ok(())
}

pub async fn run_update(
    targets: &[Arc<ExecutionTarget>],
    group_id: &str,
    from_file: &str,
    output: OutputFormat,
) -> Result<()> {
    let body = read_from_file(from_file)?;
    eprintln!("{}", format!("Updating team group {group_id}...").dimmed());
    let group_id = group_id.to_string();

    let per_profile = fan_out(targets, |t| {
        let body = body.clone();
        let group_id = group_id.clone();
        async move {
            let api = TeamGroupsApi::new(&t.client);
            Ok(api.update(&group_id, &body).await?)
        }
    })
    .await;

    let mut all_results: Vec<Value> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        if let Some(group) = resp.group {
            eprintln!(
                "{}",
                format!("Updated team group in profile '{profile}'.").green()
            );
            let group_json = group_to_json(&group, targets.len() > 1, &profile);
            crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
                crate::console_url::iam_group_url(b, &group_id)
            })
            .await;
            all_results.push(group_json);
        }
    }

    match output {
        OutputFormat::Json => render::render_json_auto(&all_results)?,
        OutputFormat::Toon => {
            let toon = toon_encode(&all_results)
                .map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {}
    }
    Ok(())
}

pub async fn run_delete(targets: &[Arc<ExecutionTarget>], group_id: &str) -> Result<()> {
    eprintln!("{}", format!("Deleting team group {group_id}...").dimmed());
    let group_id = group_id.to_string();
    let per_profile = fan_out(targets, |t| {
        let group_id = group_id.clone();
        async move {
            let api = TeamGroupsApi::new(&t.client);
            api.delete(&group_id).await?;
            Ok(())
        }
    })
    .await;
    for (profile, ()) in report_errors_and_collect_successes(per_profile)? {
        eprintln!(
            "{}",
            format!("Team group {group_id} deleted in profile '{profile}'.").green()
        );
    }
    Ok(())
}