opendal_core/services/github/
writer.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::sync::Arc;
19
20use bytes::Buf;
21use http::StatusCode;
22
23use super::core::GithubCore;
24use super::error::parse_error;
25use crate::raw::*;
26use crate::*;
27
28pub type GithubWriters = oio::OneShotWriter<GithubWriter>;
29
30pub struct GithubWriter {
31    core: Arc<GithubCore>,
32    path: String,
33}
34
35impl GithubWriter {
36    pub fn new(core: Arc<GithubCore>, path: String) -> Self {
37        GithubWriter { core, path }
38    }
39
40    fn parse_metadata(content: &super::core::Entry) -> Result<Metadata> {
41        let mode = if content.type_field == "dir" {
42            EntryMode::DIR
43        } else {
44            EntryMode::FILE
45        };
46
47        let mut meta = Metadata::new(mode);
48        if mode == EntryMode::FILE {
49            meta.set_content_length(content.size);
50            meta.set_etag(&content.sha);
51        }
52
53        Ok(meta)
54    }
55}
56
57impl oio::OneShotWrite for GithubWriter {
58    async fn write_once(&self, bs: Buffer) -> Result<Metadata> {
59        let resp = self.core.upload(&self.path, bs).await?;
60
61        let status = resp.status();
62
63        match status {
64            StatusCode::OK | StatusCode::CREATED => {
65                let body = resp.into_body();
66                let content_resp: super::core::ContentResponse =
67                    serde_json::from_reader(body.reader()).map_err(new_json_deserialize_error)?;
68                let metadata = GithubWriter::parse_metadata(&content_resp.content)?;
69                Ok(metadata)
70            }
71            _ => Err(parse_error(resp)),
72        }
73    }
74}