pcloud/file/
rename.rs

1use std::borrow::Cow;
2
3use super::{File, FileIdentifier, FileResponse};
4
5/// Parameters used to rename a file on pCloud.
6///
7/// This structure is serialized for the `renamefile` API endpoint.
8/// It includes the file identifier and the new name for the file.
9#[derive(serde::Serialize)]
10struct FileRenameParams<'a> {
11    /// The file to rename, identified by file ID or path.
12    #[serde(flatten)]
13    identifier: FileIdentifier<'a>,
14
15    /// The new name to assign to the file.
16    #[serde(rename = "toname")]
17    to_name: Cow<'a, str>,
18}
19
20impl crate::Client {
21    /// Renames a file on pCloud.
22    ///
23    /// This function calls the `renamefile` API endpoint to change the name of a file.
24    /// The file can be specified by its ID or path, and the new name must be a string.
25    ///
26    /// # Arguments
27    ///
28    /// * `identifier` - A value convertible into a [`FileIdentifier`] representing the file to rename.
29    /// * `name` - The new name to assign to the file.
30    ///
31    /// # Returns
32    ///
33    /// On success, returns a [`File`] struct containing metadata about the renamed file.
34    ///
35    /// # Errors
36    ///
37    /// Returns a [`crate::Error`] if the file doesn't exist or if the API request fails.
38    ///
39    /// # Examples
40    ///
41    /// ```rust,no_run
42    /// # async fn example(client: &pcloud::Client) -> Result<(), pcloud::Error> {
43    /// let renamed = client.rename_file(12345678u64, "new_name.txt").await?;
44    /// println!("Renamed file: {:?}", renamed.base.name);
45    /// # Ok(())
46    /// # }
47    /// ```
48    pub async fn rename_file<'a>(
49        &self,
50        identifier: impl Into<FileIdentifier<'a>>,
51        name: impl Into<Cow<'a, str>>,
52    ) -> crate::Result<File> {
53        self.get_request::<FileResponse, _>(
54            "renamefile",
55            FileRenameParams {
56                identifier: identifier.into(),
57                to_name: name.into(),
58            },
59        )
60        .await
61        .map(|res| res.metadata)
62    }
63}
64
65#[cfg(test)]
66mod tests {
67    use crate::{Client, Credentials};
68    use mockito::Matcher;
69
70    #[tokio::test]
71    async fn success() {
72        let mut server = mockito::Server::new_async().await;
73        let m = server
74            .mock("GET", "/renamefile")
75            .match_query(Matcher::AllOf(vec![
76                Matcher::UrlEncoded("access_token".into(), "access-token".into()),
77                Matcher::UrlEncoded("fileid".into(), "42".into()),
78                Matcher::UrlEncoded("toname".into(), "yolo.bin".into()),
79            ]))
80            .with_status(200)
81            .with_body(
82                r#"{
83    "result": 0,
84    "metadata": {
85        "name": "yolo.bin",
86        "created": "Sat, 24 Jul 2021 07:38:41 +0000",
87        "thumb": false,
88        "modified": "Sat, 24 Jul 2021 07:38:41 +0000",
89        "isfolder": false,
90        "isdeleted": true,
91        "fileid": 42,
92        "hash": 9403476549337371523,
93        "comments": 0,
94        "category": 0,
95        "id": "f5257731387",
96        "isshared": false,
97        "ismine": true,
98        "size": 10485760,
99        "parentfolderid": 1075398908,
100        "contenttype": "application\/octet-stream",
101        "icon": "file"
102    }
103}"#,
104            )
105            .create();
106        let client = Client::new(server.url(), Credentials::access_token("access-token")).unwrap();
107        let result = client.rename_file(42, "yolo.bin").await.unwrap();
108        assert_eq!(result.file_id, 42);
109        m.assert();
110    }
111}