hugging_face_client/api/
create_repo.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{repo::RepoType, space::SpaceSdkType};
4
5/// Request of [`crate::client::Client::create_repo`]
6#[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/// Response of [`crate::client::Client::create_repo`]
57#[derive(Debug, Deserialize)]
58pub struct CreateRepoRes {
59  pub id: String,
60  pub name: String,
61  pub url: String,
62}
63
64#[cfg(test)]
65mod test {
66  use std::assert_matches::assert_matches;
67
68  use crate::{
69    api::{CreateRepoReq, CreateRepoRes},
70    repo::RepoType,
71  };
72
73  #[test]
74  fn test_serde_req() {
75    let req = CreateRepoReq::new("my-repo")
76      .organization("my-org")
77      .repo_type(RepoType::Model)
78      .private(true);
79    let json = serde_json::to_string(&req);
80    assert_matches!(json, Ok(v) if v == "{\"name\":\"my-repo\",\"type\":\"model\",\"organization\":\"my-org\",\"private\":true}");
81  }
82
83  #[test]
84  fn test_serde_res() {
85    let json = "{\"url\":\"https://huggingface.co/dlzht/my-repo0\",\"name\":\"dlzht/my-repo0\",\"id\":\"680673d1e332a61dd92e9237\"}";
86    let res = serde_json::from_str::<CreateRepoRes>(json);
87    assert_matches!(res, Ok(v) if v.id == "680673d1e332a61dd92e9237" && v.name == "dlzht/my-repo0" && v.url == "https://huggingface.co/dlzht/my-repo0");
88  }
89}