raps-cli 4.15.0

RAPS (rapeseed) - Rust Autodesk Platform Services CLI
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2025 Dmytro Yemelianov

//! Item (file) management commands
//!
//! Commands for listing, viewing, and downloading items (requires 3-legged auth).

use anyhow::Result;
use clap::Subcommand;
use colored::Colorize;
use serde::Serialize;

use crate::commands::tracked::tracked_op;
use crate::output::OutputFormat;
use raps_dm::DataManagementClient;
// use raps_kernel::output::OutputFormat;

#[derive(Debug, Subcommand)]
pub enum ItemCommands {
    /// Get item details
    Info {
        /// Project ID
        project_id: String,
        /// Item ID
        item_id: String,
    },

    /// List item versions
    Versions {
        /// Project ID
        project_id: String,
        /// Item ID
        item_id: String,
    },

    /// Create an item from an OSS object (bind OSS upload to ACC folder)
    #[command(name = "create-from-oss")]
    CreateFromOss {
        /// Project ID (with "b." prefix)
        project_id: String,
        /// Target folder ID (get from folder list)
        folder_id: String,
        /// Display name for the item
        #[arg(short, long)]
        name: String,
        /// OSS object ID (urn:adsk.objects:os.object:bucket/objectkey)
        #[arg(long)]
        object_id: String,
    },

    /// Delete an item from a project
    Delete {
        /// Project ID
        project_id: String,
        /// Item ID
        item_id: String,
    },

    /// Rename an item (update display name)
    Rename {
        /// Project ID
        project_id: String,
        /// Item ID
        item_id: String,
        /// New display name
        #[arg(short, long)]
        name: String,
    },
}

impl ItemCommands {
    pub async fn execute(
        self,
        client: &DataManagementClient,
        output_format: OutputFormat,
    ) -> Result<()> {
        match self {
            ItemCommands::Info {
                project_id,
                item_id,
            } => item_info(client, &project_id, &item_id, output_format).await,
            ItemCommands::Versions {
                project_id,
                item_id,
            } => list_versions(client, &project_id, &item_id, output_format).await,
            ItemCommands::CreateFromOss {
                project_id,
                folder_id,
                name,
                object_id,
            } => {
                create_from_oss(
                    client,
                    &project_id,
                    &folder_id,
                    &name,
                    &object_id,
                    output_format,
                )
                .await
            }
            ItemCommands::Delete {
                project_id,
                item_id,
            } => delete_item(client, &project_id, &item_id, output_format).await,
            ItemCommands::Rename {
                project_id,
                item_id,
                name,
            } => rename_item(client, &project_id, &item_id, &name, output_format).await,
        }
    }
}

#[derive(Serialize)]
struct ItemInfoOutput {
    id: String,
    name: String,
    item_type: String,
    create_time: Option<String>,
    modified_time: Option<String>,
    extension_type: Option<String>,
    extension_version: Option<String>,
}

async fn item_info(
    client: &DataManagementClient,
    project_id: &str,
    item_id: &str,
    output_format: OutputFormat,
) -> Result<()> {
    let item = tracked_op("Fetching item details", output_format, || {
        client.get_item(project_id, item_id)
    })
    .await?;

    let extension_type = item
        .attributes
        .extension
        .as_ref()
        .and_then(|e| e.extension_type.clone());
    let extension_version = item
        .attributes
        .extension
        .as_ref()
        .and_then(|e| e.version.clone());

    let output = ItemInfoOutput {
        id: item.id.clone(),
        name: item.attributes.display_name.clone(),
        item_type: item.item_type.clone(),
        create_time: item.attributes.create_time.clone(),
        modified_time: item.attributes.last_modified_time.clone(),
        extension_type,
        extension_version,
    };

    match output_format {
        OutputFormat::Table => {
            println!("\n{}", "Item Details".bold());
            println!("{}", "-".repeat(60));
            println!("  {} {}", "Name:".bold(), output.name.cyan());
            println!("  {} {}", "ID:".bold(), output.id);
            println!("  {} {}", "Type:".bold(), output.item_type);

            if let Some(ref create_time) = output.create_time {
                println!("  {} {}", "Created:".bold(), create_time);
            }

            if let Some(ref modified_time) = output.modified_time {
                println!("  {} {}", "Modified:".bold(), modified_time);
            }

            if let Some(ref ext_type) = output.extension_type {
                println!("  {} {}", "Extension:".bold(), ext_type);
            }
            if let Some(version) = output.extension_version {
                println!("  {} {}", "Ext Version:".bold(), version);
            }

            println!("{}", "-".repeat(60));
            println!(
                "\n{}",
                "Use 'raps item versions' to see version history".dimmed()
            );
        }
        _ => {
            output_format.write(&output)?;
        }
    }
    Ok(())
}

#[derive(Serialize)]
struct VersionOutput {
    version_number: Option<i32>,
    name: String,
    size: Option<u64>,
    size_human: Option<String>,
    create_time: Option<String>,
}

async fn list_versions(
    client: &DataManagementClient,
    project_id: &str,
    item_id: &str,
    output_format: OutputFormat,
) -> Result<()> {
    let versions = tracked_op("Fetching item versions", output_format, || {
        client.get_item_versions(project_id, item_id)
    })
    .await?;

    let version_outputs: Vec<VersionOutput> = versions
        .iter()
        .map(|v| {
            let name = v
                .attributes
                .display_name
                .as_ref()
                .or(Some(&v.attributes.name))
                .cloned()
                .unwrap_or_default();
            VersionOutput {
                version_number: v.attributes.version_number,
                name,
                size: v.attributes.storage_size.map(|s| s as u64),
                size_human: v.attributes.storage_size.map(|s| format_size(s as u64)),
                create_time: v.attributes.create_time.clone(),
            }
        })
        .collect();

    if version_outputs.is_empty() {
        match output_format {
            OutputFormat::Table => println!("{}", "No versions found.".yellow()),
            _ => {
                output_format.write(&Vec::<VersionOutput>::new())?;
            }
        }
        return Ok(());
    }

    match output_format {
        OutputFormat::Table => {
            println!("\n{}", "Item Versions:".bold());
            println!("{}", "-".repeat(80));
            println!(
                "{:<6} {:<40} {:>12} {}",
                "Ver".bold(),
                "Name".bold(),
                "Size".bold(),
                "Created".bold()
            );
            println!("{}", "-".repeat(80));

            for version in &version_outputs {
                let ver_num = version
                    .version_number
                    .map(|n| n.to_string())
                    .unwrap_or_else(|| "-".to_string());
                let name = truncate_str(&version.name, 40);
                let size = version.size_human.as_deref().unwrap_or("-");
                let created = version.create_time.as_deref().unwrap_or("-");

                println!(
                    "{:<6} {:<40} {:>12} {}",
                    ver_num.cyan(),
                    name,
                    size,
                    created.dimmed()
                );
            }

            println!("{}", "-".repeat(80));
        }
        _ => {
            output_format.write(&version_outputs)?;
        }
    }
    Ok(())
}

/// Format file size in human-readable format
fn format_size(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;

    if bytes >= GB {
        format!("{:.2} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.2} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.2} KB", bytes as f64 / KB as f64)
    } else {
        format!("{} B", bytes)
    }
}

/// Truncate string with ellipsis
fn truncate_str(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len - 3])
    }
}

#[derive(Serialize)]
struct CreateFromOssOutput {
    success: bool,
    item_id: String,
    name: String,
    message: String,
}

async fn create_from_oss(
    client: &DataManagementClient,
    project_id: &str,
    folder_id: &str,
    name: &str,
    object_id: &str,
    output_format: OutputFormat,
) -> Result<()> {
    if output_format.supports_colors() {
        println!("{}", "Creating item from OSS object...".dimmed());
        println!("  {} {}", "Project:".bold(), project_id);
        println!("  {} {}", "Folder:".bold(), folder_id);
        println!("  {} {}", "Name:".bold(), name.cyan());
        println!("  {} {}", "Object ID:".bold(), object_id.dimmed());
    }

    // Create the item using the Data Management API
    let item = client
        .create_item_from_storage(project_id, folder_id, name, object_id)
        .await?;

    let output = CreateFromOssOutput {
        success: true,
        item_id: item.id.clone(),
        name: item.attributes.display_name.clone(),
        message: format!("Item '{}' created successfully from OSS object", name),
    };

    match output_format {
        OutputFormat::Table => {
            println!("\n{} {}", "".green().bold(), output.message);
            println!("  {} {}", "Item ID:".bold(), output.item_id);
            println!("  {} {}", "Name:".bold(), output.name.cyan());
        }
        _ => {
            output_format.write(&output)?;
        }
    }

    Ok(())
}

async fn delete_item(
    client: &DataManagementClient,
    project_id: &str,
    item_id: &str,
    output_format: OutputFormat,
) -> Result<()> {
    if output_format.supports_colors() {
        println!("{}", "Deleting item...".dimmed());
    }

    client.delete_item(project_id, item_id).await?;

    match output_format {
        OutputFormat::Table => {
            println!("\n{} Item deleted successfully!", "".green().bold());
            println!("  {} {}", "Item ID:".bold(), item_id.cyan());
        }
        _ => {
            output_format.write(&serde_json::json!({
                "id": item_id,
                "deleted": true
            }))?;
        }
    }

    Ok(())
}

#[derive(Serialize)]
struct RenameItemOutput {
    id: String,
    name: String,
    renamed: bool,
}

async fn rename_item(
    client: &DataManagementClient,
    project_id: &str,
    item_id: &str,
    new_name: &str,
    output_format: OutputFormat,
) -> Result<()> {
    if output_format.supports_colors() {
        println!("{}", "Renaming item...".dimmed());
    }

    let item = client.rename_item(project_id, item_id, new_name).await?;

    let output = RenameItemOutput {
        id: item.id.clone(),
        name: item.attributes.display_name.clone(),
        renamed: true,
    };

    match output_format {
        OutputFormat::Table => {
            println!("\n{} Item renamed successfully!", "".green().bold());
            println!("  {} {}", "Item ID:".bold(), output.id.cyan());
            println!("  {} {}", "Name:".bold(), output.name.cyan());
        }
        _ => {
            output_format.write(&output)?;
        }
    }

    Ok(())
}