hugging_face_client/api/
create_repo.rs1use serde::{Deserialize, Serialize};
2
3use crate::{repo::RepoType, space::SpaceSdkType};
4
5#[derive(Debug, Serialize)]
7pub struct CreateRepoReq<'a> {
8 name: &'a str,
9
10 #[serde(rename = "type")]
11 repo_type: RepoType,
12
13 #[serde(skip_serializing_if = "Option::is_none")]
14 organization: Option<&'a str>,
15
16 private: bool,
17
18 #[serde(skip_serializing_if = "Option::is_none")]
19 sdk: Option<SpaceSdkType>,
20}
21
22impl<'a> CreateRepoReq<'a> {
23 pub fn new(name: &'a str) -> Self {
24 CreateRepoReq {
25 name,
26 repo_type: RepoType::default(),
27 organization: None,
28 private: false,
29 sdk: None,
30 }
31 }
32
33 pub fn repo_type(mut self, repo_type: RepoType) -> Self {
34 self.repo_type = repo_type;
35 self
36 }
37
38 pub fn organization(mut self, organization: &'a str) -> Self {
39 self.organization = Some(organization);
40 self
41 }
42
43 pub fn private(mut self, private: bool) -> Self {
44 self.private = private;
45 self
46 }
47
48 pub fn sdk(mut self, sdk_type: SpaceSdkType) -> Self {
49 if matches!(self.repo_type, RepoType::Dataset) {
50 self.sdk = Some(sdk_type);
51 }
52 self
53 }
54}
55
56#[derive(Debug, Deserialize)]
58pub struct CreateRepoRes {
59 id: String,
60
61 name: String,
62
63 url: String,
64}
65
66impl CreateRepoRes {
67 pub fn id(&self) -> &str {
68 &self.name
69 }
70
71 pub fn name(&self) -> &str {
72 &self.name
73 }
74
75 pub fn url(&self) -> &str {
76 &self.url
77 }
78}
79
80#[cfg(test)]
81mod test {
82 use std::assert_matches::assert_matches;
83
84 use crate::{
85 api::{CreateRepoReq, CreateRepoRes},
86 repo::RepoType,
87 };
88
89 #[test]
90 fn test_serde_req() {
91 let req = CreateRepoReq::new("my-repo")
92 .organization("my-org")
93 .repo_type(RepoType::Model)
94 .private(true);
95 let json = serde_json::to_string(&req);
96 assert_matches!(json, Ok(v) if v == "{\"name\":\"my-repo\",\"type\":\"model\",\"organization\":\"my-org\",\"private\":true,\"sdk\":null}");
97 }
98
99 #[test]
100 fn test_serde_res() {
101 let json = "{\"url\":\"https://huggingface.co/dlzht/my-repo0\",\"name\":\"dlzht/my-repo0\",\"id\":\"680673d1e332a61dd92e9237\"}";
102 let res = serde_json::from_str::<CreateRepoRes>(json);
103 assert_matches!(res, Ok(v) if v.id() == "680673d1e332a61dd92e9237" && v.name() == "dlzht/my-repo0" && v.url() == "https://huggingface.co/dlzht/my-repo0");
104 }
105}