rexec/files.rs
1//! File service for managing files in containers.
2
3use reqwest::Method;
4use std::sync::Arc;
5
6use crate::client::ClientInner;
7use crate::error::Result;
8use crate::types::FileInfo;
9
10/// Service for file operations in containers.
11pub struct FileService {
12 client: Arc<ClientInner>,
13}
14
15impl FileService {
16 pub(crate) fn new(client: Arc<ClientInner>) -> Self {
17 Self { client }
18 }
19
20 /// List files in a container directory.
21 ///
22 /// # Arguments
23 ///
24 /// * `container_id` - Container ID
25 /// * `path` - Directory path to list
26 ///
27 /// # Example
28 ///
29 /// ```rust,no_run
30 /// # use rexec::RexecClient;
31 /// # async fn example() -> Result<(), rexec::Error> {
32 /// let client = RexecClient::new("https://example.com", "token");
33 /// let files = client.files().list("container-id", "/home").await?;
34 /// for f in files {
35 /// let icon = if f.is_dir { "📁" } else { "📄" };
36 /// println!("{} {}", icon, f.name);
37 /// }
38 /// # Ok(())
39 /// # }
40 /// ```
41 pub async fn list(&self, container_id: &str, path: &str) -> Result<Vec<FileInfo>> {
42 let encoded_path = urlencoding::encode(path);
43 self.client
44 .request(
45 Method::GET,
46 &format!("/api/containers/{}/files/list?path={}", container_id, encoded_path),
47 )
48 .await
49 }
50
51 /// Download a file from a container.
52 ///
53 /// # Arguments
54 ///
55 /// * `container_id` - Container ID
56 /// * `path` - Path to the file
57 ///
58 /// # Returns
59 ///
60 /// File contents as bytes.
61 pub async fn download(&self, container_id: &str, path: &str) -> Result<Vec<u8>> {
62 let encoded_path = urlencoding::encode(path);
63 let response = self
64 .client
65 .raw_request(
66 Method::GET,
67 &format!("/api/containers/{}/files?path={}", container_id, encoded_path),
68 None::<&()>,
69 )
70 .await?;
71
72 Ok(response.bytes().await?.to_vec())
73 }
74
75 /// Create a directory in a container.
76 ///
77 /// # Arguments
78 ///
79 /// * `container_id` - Container ID
80 /// * `path` - Directory path to create
81 pub async fn mkdir(&self, container_id: &str, path: &str) -> Result<()> {
82 #[derive(serde::Serialize)]
83 struct MkdirRequest<'a> {
84 path: &'a str,
85 }
86
87 self.client
88 .request_with_body::<serde_json::Value, _>(
89 Method::POST,
90 &format!("/api/containers/{}/files/mkdir", container_id),
91 &MkdirRequest { path },
92 )
93 .await?;
94
95 Ok(())
96 }
97
98 /// Delete a file or directory from a container.
99 ///
100 /// # Arguments
101 ///
102 /// * `container_id` - Container ID
103 /// * `path` - Path to delete
104 pub async fn delete(&self, container_id: &str, path: &str) -> Result<()> {
105 let encoded_path = urlencoding::encode(path);
106 self.client
107 .request_empty(
108 Method::DELETE,
109 &format!("/api/containers/{}/files?path={}", container_id, encoded_path),
110 )
111 .await
112 }
113}