view generate/templates.py @ 225:ff8d54205cb6

conflict resolution
author Daniel Boline <ddboline@gmail.com>
date Mon, 01 Mar 2021 06:51:13 -0500
parents a19056bcc2c9 eebc8dacb51c
children
line wrap: on
line source

# General imports and error type.
RustHeader = '''
#![allow(unused_variables, unused_mut, dead_code, non_camel_case_types)]
//! This file was generated by async-google-apis. (https://github.com/dermesser/async-google-apis)
//!
//! (c) 2020 Lewin Bormann <lbo@spheniscida.de>
//!
//! ## Getting started
//!
//! **Tip**: Take a look at those types ending in `...Service`. These represent API resources
//! and contain methods to interact with an API. The remaining types are used by those methods
//! and can be explored starting from a method you want to use.
//!
//! The generated code's dependencies are in the `async-google-apis-common` crate. The main
//! dependencies are hyper, yup-oauth2 (for OAuth authentication), and serde.
//!
//! I'd be happy if you let me know about your use case of this code.
//!
//! THIS FILE HAS BEEN GENERATED -- SAVE ANY MODIFICATIONS BEFORE REPLACING.

use async_google_apis_common::*;

'''

# Dict contents --
# name (of API, Capitalized)
# scopes: [{name, url, desc}]
OauthScopesType = '''
/// Scopes of this API. Convertible to their string representation with `AsRef`.
#[derive(Debug, Clone, Copy)]
pub enum {{{name}}} {
    {{#scopes}}
    {{#desc}}
    /// {{{desc}}}
    ///
    {{/desc}}
    /// URL: {{{url}}}
    {{{scope_name}}},
    {{/scopes}}
}

impl std::convert::AsRef<str> for {{{name}}} {
    fn as_ref(&self) -> &'static str {
        match self {
            {{#scopes}}
            {{{name}}}::{{{scope_name}}} => "{{{url}}}",
            {{/scopes}}
        }
    }
}

'''

# An API enum.
#
# fields: {name, values: [{desc, line}]}
SchemaEnumTmpl = '''
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum {{{name}}} {
    Undefined,
    {{#values}}
    {{#desc}}
    /// {{{desc}}}
    {{/desc}}
    #[serde(rename = "{{{jsonvalue}}}")]
    {{{line}}},
    {{/values}}
}

impl std::default::Default for {{{name}}} {
    fn default() -> {{{name}}} {
        {{{name}}}::Undefined
    }
}

impl std::fmt::Display for {{{name}}} {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            {{{name}}}::Undefined => write!(f, "undefined"),
            {{#values}}
            {{{name}}}::{{{line}}} => write!(f, "{{{jsonvalue}}}"),
            {{/values}}
        };
        Ok(())
    }
}
'''

# A struct for parameters or input/output API types.
# Dict contents --
# name
# fields: [{name, comment, attr, typ}]
SchemaStructTmpl = '''
{{#description}}
/// {{{description}}}
{{/description}}
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct {{{name}}} {
{{#fields}}
    {{#comment}}
    /// {{{comment}}}
    {{/comment}}
    {{#attr}}
    {{{attr}}}
    {{/attr}}
    pub {{{name}}}: {{{typ}}},
{{/fields}}
}
'''

# Serialize a global params struct to a URL query string.
SchemaDisplayTmpl = '''
impl std::fmt::Display for {{{name}}} {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        {{#required_fields}}
        write!(f, "&{{{original_name}}}={}", percent_encode(format!("{}", self.{{{name}}}).as_bytes(), NON_ALPHANUMERIC).to_string())?;
        {{/required_fields}}
        {{#optional_fields}}
        if let Some(ref v) = self.{{{name}}} {
            write!(f, "&{{{original_name}}}={}", percent_encode(format!("{}", v).as_bytes(), NON_ALPHANUMERIC).to_string())?;
        }
        {{/optional_fields}}
        {{#datetime_fields}}
        if let Some(ref v) = self.{{{name}}} {
            write!(f, "&{{{original_name}}}={}", percent_encode(v.to_rfc3339().as_bytes(), NON_ALPHANUMERIC).to_string())?;
        }
        {{/datetime_fields}}
        Ok(())
    }
}
'''

# Dict contents --
#
# api, service (names: e.g. Files)
# methods: [{text}] (the method implementations as {'text': ...} dicts)
# name (API name)
ServiceImplementationTmpl = '''
/// The {{{name}}} {{{service}}} service represents the {{{service}}} resource.
pub struct {{{service}}}Service {
    client: TlsClient,
    {{#wants_auth}}
    authenticator: Box<dyn 'static + DerefAuth>,
    scopes: Vec<String>,
    {{/wants_auth}}

    base_url: String,
    root_url: String,
}

impl {{{service}}}Service {
    /// Create a new {{{service}}}Service object. The easiest way to call this is wrapping the Authenticator
    /// into an `Arc`: `new(client.clone(), Arc::new(authenticator))`.
    /// This way, one authenticator can be shared among several services.
    pub fn new
    {{#wants_auth}}<A: 'static + DerefAuth>
    {{/wants_auth}}(client: TlsClient{{#wants_auth}}, auth: A{{/wants_auth}}) -> {{{service}}}Service {
        {{{service}}}Service { client: client
            {{#wants_auth}}, authenticator: Box::new(auth), scopes: vec![]{{/wants_auth}},
            base_url: "{{{base_path}}}".into(), root_url: "{{{root_path}}}".into() }
    }

    /// Provide the base URL of this API. The returned URL is guaranteed to end with a '/'.
    fn base_url(&self) -> String {
        if self.base_url.ends_with("/") {
            return self.base_url.clone();
        }
        return self.base_url.clone() + "/";
    }
    /// Provide the root URL of this API. The returned URL is guaranteed to end with a '/'.
    fn root_url(&self) -> String {
        if self.root_url.ends_with("/") {
            return self.root_url.clone();
        }
        return self.root_url.clone();
    }
    /// Returns appropriate URLs for relative and absolute paths.
    fn format_path(&self, path: &str) -> String {
        if path.starts_with("/") {
            return self.root_url().trim_end_matches("/").to_string() + path;
        } else {
            return self.base_url() + path;
        }
    }

    #[cfg(test)]
    /// Override API URLs. `base` is the base path relative to which (relative) method paths are interpreted,
    /// whereas `root` is the URL relative to which absolute paths are interpreted.
    pub fn set_urls(&mut self, base: String, root: String) {
        self.base_url = base;
        self.root_url = root;
    }

    {{#wants_auth}}
    /// Explicitly select which scopes should be requested for authorization. Otherwise,
    /// a possibly too large scope will be requested.
    ///
    /// It is most convenient to supply a vec or slice of {{{name}}}Scopes enum values.
    pub fn set_scopes<S: AsRef<str>, T: AsRef<[S]>>(&mut self, scopes: T) {
        self.scopes = scopes.as_ref().into_iter().map(|s| s.as_ref().to_string()).collect();
    }
    {{/wants_auth}}

    {{#methods}}
    {{{text}}}
    {{/methods}}
}
'''

# Takes dict contents:
# name, description, param_type, in_type, out_type
# base_path, rel_path_expr, scopes (string repr. of rust string array),
# params: [{param, snake_param}]
# http_method
NormalMethodTmpl = '''
{{#description}}
/// {{{description}}}
{{/description}}
pub async fn {{{name}}}(
    &self, params: &{{{param_type}}}
    {{#in_type}}, req: &{{{in_type}}}{{/in_type}}) -> Result<{{{out_type}}}> {

    let rel_path = {{{rel_path_expr}}};
    let path = self.format_path(rel_path.as_str());

    let mut headers = vec![];
    {{#wants_auth}}
    let tok;
    if self.scopes.is_empty() {
        let scopes = &[{{#scopes}}{{{scope}}}.as_ref().to_string(),
        {{/scopes}}];
        tok = self.authenticator.token(scopes).await?;
    } else {
        tok = self.authenticator.token(&self.scopes).await?;
    }
    headers.push((hyper::header::AUTHORIZATION, format!("Bearer {token}", token=tok.as_str())));
    {{/wants_auth}}

    let mut url_params = format!("?{params}", params=params);
    {{#global_params_name}}
    if let Some(ref api_params) = &params.{{{global_params_name}}} {
        url_params.push_str(&format!("{}", api_params));
    }
    {{/global_params_name}}

    let full_uri = path + &url_params;

    let opt_request: Option<&EmptyRequest> = None;
    {{#in_type}}
    let opt_request = Some(req);
    {{/in_type}}
    do_request(&self.client, &full_uri,
        &headers,
        "{{{http_method}}}", opt_request).await
  }
'''

# Takes:
# name, param_type, in_type, out_type
# base_path, rel_path_expr
# params: [{param, snake_param}]
# http_method
UploadMethodTmpl = '''
{{#description}}
/// {{{description}}}
///
{{/description}}
/// This method is a variant of `{{{name}}}()`, taking data for upload. It performs a multipart upload.
pub async fn {{{name}}}_upload(
    &self, params: &{{{param_type}}}, {{#in_type}}req: &{{{in_type}}},{{/in_type}} data: hyper::body::Bytes) -> Result<{{{out_type}}}> {
    let rel_path = {{{simple_rel_path_expr}}};
    let path = self.format_path(rel_path.as_str());

    let mut headers = vec![];
    {{#wants_auth}}
    let tok;
    if self.scopes.is_empty() {
        let scopes = &[{{#scopes}}{{{scope}}}.as_ref().to_string(),
        {{/scopes}}];
        tok = self.authenticator.token(scopes).await?;
    } else {
        tok = self.authenticator.token(&self.scopes).await?;
    }
    headers.push((hyper::header::AUTHORIZATION, format!("Bearer {token}", token=tok.as_str())));
    {{/wants_auth}}

    let mut url_params = format!("?uploadType=multipart{params}", params=params);

    {{#global_params_name}}
    if let Some(ref api_params) = &params.{{{global_params_name}}} {
        url_params.push_str(&format!("{}", api_params));
    }
    {{/global_params_name}}

    let full_uri = path + &url_params;
    let opt_request: Option<&EmptyRequest> = None;
    {{#in_type}}
    let opt_request = Some(req);
    {{/in_type}}

    do_upload_multipart(&self.client, &full_uri,
        &headers,
        "{{{http_method}}}", opt_request, data).await
  }
'''

# Takes:
# name, param_type, in_type, out_type
# base_path, rel_path_expr
# params: [{param, snake_param}]
# http_method
ResumableUploadMethodTmpl = '''
{{#description}}
/// {{{description}}}
///
{{/description}}
/// This method is a variant of `{{{name}}}()`, taking data for upload.
/// It returns a `ResumableUpload` upload manager which you can use to stream larger amounts
/// of data to the API. The result of this call will be returned by the `ResumableUpload` method
/// you choose for the upload.
pub async fn {{{name}}}_resumable_upload<'client>(
    &'client self, params: &{{{param_type}}}, {{#in_type}}req: &{{{in_type}}}{{/in_type}}) -> Result<ResumableUpload<'client, {{{out_type}}}>> {

    let rel_path = {{{resumable_rel_path_expr}}};
    let path = self.format_path(rel_path.as_str());

    let mut headers = vec![];
    {{#wants_auth}}
    let tok;
    if self.scopes.is_empty() {
        let scopes = &[{{#scopes}}{{{scope}}}.as_ref().to_string(),
        {{/scopes}}];
        tok = self.authenticator.token(scopes).await?;
    } else {
        tok = self.authenticator.token(&self.scopes).await?;
    }
    headers.push((hyper::header::AUTHORIZATION, format!("Bearer {token}", token=tok.as_str())));
    {{/wants_auth}}

    let mut url_params = format!("?uploadType=resumable{params}", params=params);
    {{#global_params_name}}
    if let Some(ref api_params) = &params.{{{global_params_name}}} {
        url_params.push_str(&format!("{}", api_params));
    }
    {{/global_params_name}}

    let full_uri = path + &url_params;

    let opt_request: Option<&EmptyRequest> = None;
    {{#in_type}}
    let opt_request = Some(req);
    {{/in_type}}
    let (_resp, headers): (EmptyResponse, hyper::HeaderMap) = do_request_with_headers(
        &self.client, &full_uri, &headers, "{{{http_method}}}", opt_request).await?;
    if let Some(dest) = headers.get(hyper::header::LOCATION) {
        use std::convert::TryFrom;
        Ok(ResumableUpload::new(hyper::Uri::try_from(dest.to_str()?)?, &self.client, 5*1024*1024))
    } else {
        Err(Error::from(ApiError::RedirectError(format!("Resumable upload response didn't contain Location: {:?}", headers)))
        .context(format!("{:?}", headers)))?
    }
  }
'''

# Takes:
# name, param_type, in_type, out_type
# base_path, rel_path_expr
# params: [{param, snake_param}]
# http_method
DownloadMethodTmpl = '''
{{#description}}
/// {{{description}}}
///
{{/description}}
/// This method potentially downloads data. See documentation of `Download`.
pub async fn {{{name}}}<'a>(
    &'a self, params: &{{{param_type}}}, {{#in_type}}req: &'a {{{in_type}}}{{/in_type}})
    -> Result<Download<'a, {{{download_in_type}}}, {{{out_type}}}>> {

    let rel_path = {{{rel_path_expr}}};
    let path = self.format_path(rel_path.as_str());

    let mut headers = vec![];
    {{#wants_auth}}
    let tok;
    if self.scopes.is_empty() {
        let scopes = &[{{#scopes}}{{{scope}}}.as_ref().to_string(),
        {{/scopes}}];
        tok = self.authenticator.token(scopes).await?;
    } else {
        tok = self.authenticator.token(&self.scopes).await?;
    }
    headers.push((hyper::header::AUTHORIZATION, format!("Bearer {token}", token=tok.as_str())));
    {{/wants_auth}}

    let mut url_params = format!("?{params}", params=params);
    {{#global_params_name}}
    if let Some(ref api_params) = &params.{{{global_params_name}}} {
        url_params.push_str(&format!("{}", api_params));
    }
    {{/global_params_name}}

    let full_uri = path + &url_params;
    let opt_request: Option<&EmptyRequest> = None;
    {{#in_type}}
    let opt_request = Some(req);
    {{/in_type}}

    do_download(&self.client, &full_uri,
        headers,
        "{{{http_method}}}".into(), opt_request).await
  }
'''