pcloud/folder/
rename.rs

1use std::borrow::Cow;
2
3use super::{Folder, FolderIdentifier, FolderResponse};
4
5/// Internal parameter structure for renaming a folder.
6#[derive(serde::Serialize)]
7struct FolderRenameParams<'a> {
8    /// The folder identifier (either folder ID or path).
9    #[serde(flatten)]
10    identifier: FolderIdentifier<'a>,
11
12    /// The new name for the folder.
13    #[serde(rename = "toname")]
14    to_name: Cow<'a, str>,
15}
16
17impl crate::Client {
18    /// Renames an existing folder in pCloud.
19    ///
20    /// This function calls the `renamefolder` API endpoint to rename the specified folder.
21    /// The folder is identified either by its folder ID or its path, and the new name is provided
22    /// as a string.
23    ///
24    /// # Arguments
25    ///
26    /// * `identifier` - The identifier for the folder to be renamed, which can be provided either
27    ///                  by folder ID or path.
28    /// * `name` - The new name for the folder.
29    ///
30    /// # Returns
31    ///
32    /// A [`Folder`] struct containing the metadata of the renamed folder.
33    ///
34    /// # Errors
35    ///
36    /// Returns a [`crate::Error`] if the rename operation fails, for example, if the folder does
37    /// not exist or the API request encounters an issue.
38    ///
39    /// # Examples
40    ///
41    /// ```rust,no_run
42    /// # async fn example(client: &pcloud::Client) -> Result<(), pcloud::Error> {
43    /// let renamed_folder = client.rename_folder("/OldFolder", "NewFolderName").await?;
44    /// println!("Renamed folder: {:?}", renamed_folder.base.name);
45    /// # Ok(())
46    /// # }
47    /// ```
48    pub async fn rename_folder<'a>(
49        &self,
50        identifier: impl Into<FolderIdentifier<'a>>,
51        name: impl Into<Cow<'a, str>>,
52    ) -> crate::Result<Folder> {
53        self.get_request::<FolderResponse, _>(
54            "renamefolder",
55            FolderRenameParams {
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", "/renamefolder")
75            .match_query(Matcher::AllOf(vec![
76                Matcher::UrlEncoded("access_token".into(), "access-token".into()),
77                Matcher::UrlEncoded("folderid".into(), "42".into()),
78                Matcher::UrlEncoded("toname".into(), "yolo".into()),
79            ]))
80            .with_status(200)
81            .with_body(
82                r#"{
83    "result": 0,
84    "metadata": {
85        "path": "\/testing",
86        "name": "testing",
87        "created": "Fri, 23 Jul 2021 19:39:09 +0000",
88        "ismine": true,
89        "thumb": false,
90        "modified": "Fri, 23 Jul 2021 19:39:09 +0000",
91        "id": "d10",
92        "isshared": false,
93        "icon": "folder",
94        "isfolder": true,
95        "parentfolderid": 0,
96        "folderid": 42
97    }
98}"#,
99            )
100            .create();
101        let client = Client::new(server.url(), Credentials::access_token("access-token")).unwrap();
102        let result = client.rename_folder(42, "yolo").await.unwrap();
103        assert_eq!(result.folder_id, 42);
104        m.assert();
105    }
106}