chore(gen): adds all missing apis

With recent changes in the generator and or rust a bunch of api are now
working that were blacklisted. This commit adds the generated files for
those apis.
This commit is contained in:
Michael Daffin
2018-02-01 16:47:10 +00:00
parent 9e92a3c188
commit a0d6551dea
198 changed files with 124698 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-acceleratedmobilepageurl1-cli"
version = "1.0.7+20171202"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with acceleratedmobilepageurl (protocol v1)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/acceleratedmobilepageurl1-cli"
homepage = "https://developers.google.com/amp/cache/"
documentation = "http://byron.github.io/google-apis-rs/google_acceleratedmobilepageurl1_cli"
license = "MIT"
keywords = ["acceleratedmobilepag", "google", "cli"]
[[bin]]
name = "acceleratedmobilepageurl1"
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
strsim = "^0.5"
hyper-rustls = "^0.6"
yup-hyper-mock = "^2.0"
clap = "^2.0"
[features]
[dependencies.google-acceleratedmobilepageurl1]
path = "../acceleratedmobilepageurl1"
version = "1.0.7+20171202"

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,110 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/cli/README.md.mako'
DO NOT EDIT !
-->
The `acceleratedmobilepageurl1` command-line interface *(CLI)* allows to use most features of the *Google acceleratedmobilepageurl* service from the comfort of your terminal.
By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's
capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero.
If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools.
Everything else about the *acceleratedmobilepageurl* API can be found at the
[official documentation site](https://developers.google.com/amp/cache/).
# Installation and Source Code
Install the command-line interface with cargo using:
```bash
cargo install google-acceleratedmobilepageurl1-cli
```
Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/acceleratedmobilepageurl1-cli).
# Usage
This documentation was generated from the *acceleratedmobilepageurl* API at revision *20171202*. The CLI is at version *1.0.7*.
```bash
acceleratedmobilepageurl1 [options]
amp-urls
batch-get (-r <kv>)... [-p <v>]... [-o <out>]
acceleratedmobilepageurl1 --help
Configuration:
--config-dir <folder>
A directory into which we will store our persistent data. Defaults to
a user-writable directory that we will create during the first invocation.
[default: ~/.google-service-cli]
--debug
Output all server communication to standard error. `tx` and `rx` are placed
into the same stream.
--debug-auth
Output all communication related to authentication to standard error. `tx`
and `rx` are placed into the same stream.
```
# Configuration
The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `acceleratedmobilepageurl1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis.
More information about the various kinds of persistent data are given in the following paragraphs.
# Authentication
Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the
set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*.
If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a
method that is read-only, it will ask only for a read-only scope.
You may use the `--scope` flag to specify a scope directly.
All applicable scopes are documented in the respective method's CLI documentation.
The first time a scope is used, the user is asked for permission. Follow the instructions given
by the CLI to grant permissions, or to decline.
If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration
directory, e.g. `~/.google-service-cli/acceleratedmobilepageurl1-token-<scope-hash>.json`. No manual management of these tokens
is necessary.
To revoke granted authentication, please refer to the [official documentation][revoke-access].
# Application Secrets
In order to allow any application to use Google services, it will need to be registered using the
[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it
one by one. Most APIs can be used for free and have a daily quota.
To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI
comes with a default application secret that is configured accordingly. This also means that heavy usage
all around the world may deplete the daily quota.
You can workaround this limitation by putting your own secrets file at this location:
`~/.google-service-cli/acceleratedmobilepageurl1-secret.json`, assuming that the required *acceleratedmobilepageurl* API
was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at
*APIs & auth -> Credentials -> Download JSON* and used as is.
Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new].
# Debugging
Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know
what exactly led to a particular issue. This is done by allowing all client-server communication to be
output to standard error *as-is*.
The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag
will cause all communication related to authentication to standard error.
If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the
issue at hand.
You may consider redirecting standard error into a file for ease of use, e.g. `acceleratedmobilepageurl1 --debug <resource> <method> [options] 2>debug.txt`.
[scopes]: https://developers.google.com/+/api/oauth#scopes
[revoke-access]: http://webapps.stackexchange.com/a/30849
[google-dev-console]: https://console.developers.google.com/
[google-project-new]: https://developers.google.com/console/help/new/

View File

@@ -0,0 +1,17 @@
site_name: acceleratedmobilepageurl v1.0.7+20171202
site_url: http://byron.github.io/google-apis-rs/google-acceleratedmobilepageurl1-cli
site_description: A complete library to interact with acceleratedmobilepageurl (protocol v1)
repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/acceleratedmobilepageurl1-cli
docs_dir: docs
site_dir: build_html
pages:
- ['index.md', 'Home']
- ['amp-urls_batch-get.md', 'Amp Urls', 'Batch Get']
theme: readthedocs
copyright: Copyright &copy; 2015-2016, `Sebastian Thiel`

View File

@@ -0,0 +1,799 @@
// COPY OF 'src/rust/cli/cmn.rs'
// DO NOT EDIT
use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token};
use serde_json as json;
use serde_json::value::Value;
use mime::Mime;
use clap::{App, SubCommand};
use strsim;
use std::fs;
use std::env;
use std::io;
use std::error::Error as StdError;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
use std::io::{Write, Read, stdout};
use std::default::Default;
const FIELD_SEP: char = '.';
pub enum ComplexType {
Pod,
Vec,
Map,
}
// Null,
// Bool(bool),
// I64(i64),
// U64(u64),
// F64(f64),
// String(String),
pub enum JsonType {
Boolean,
Int,
Uint,
Float,
String,
}
pub struct JsonTypeInfo {
pub jtype: JsonType,
pub ctype: ComplexType,
}
// Based on @erickt user comment. Thanks for the idea !
// Remove all keys whose values are null from given value (changed in place)
pub fn remove_json_null_values(value: &mut Value) {
match *value {
Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}
fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> {
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values {
let confidence = strsim::jaro_winkler(v, pv);
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
}
pub enum CallType {
Upload(UploadProtocol),
Standard,
}
arg_enum!{
pub enum UploadProtocol {
Simple,
Resumable
}
}
impl AsRef<str> for UploadProtocol {
fn as_ref(&self) -> &str {
match *self {
UploadProtocol::Simple => "simple",
UploadProtocol::Resumable => "resumable",
}
}
}
impl AsRef<str> for CallType {
fn as_ref(&self) -> &str {
match *self {
CallType::Upload(ref proto) => proto.as_ref(),
CallType::Standard => "standard-request",
}
}
}
#[derive(Clone, Default)]
pub struct FieldCursor(Vec<String>);
impl ToString for FieldCursor {
fn to_string(&self) -> String {
self.0.join(".")
}
}
impl From<&'static str> for FieldCursor {
fn from(value: &'static str) -> FieldCursor {
let mut res = FieldCursor::default();
res.set(value).unwrap();
res
}
}
fn assure_entry<'a, 'b>(m: &'a mut json::Map<String, Value>, k: &'b String) -> &'a mut Value {
if m.contains_key(k) {
return m.get_mut(k).expect("value to exist");
}
m.insert(k.to_owned(), Value::Object(Default::default()));
m.get_mut(k).expect("value to exist")
}
impl FieldCursor {
pub fn set(&mut self, value: &str) -> Result<(), CLIError> {
if value.len() == 0 {
return Err(CLIError::Field(FieldError::Empty));
}
let mut first_is_field_sep = false;
let mut char_count: usize = 0;
let mut last_c = FIELD_SEP;
let mut num_conscutive_field_seps = 0;
let mut field = String::new();
let mut fields = self.0.clone();
let push_field = |fs: &mut Vec<String>, f: &mut String| {
if f.len() > 0 {
fs.push(f.clone());
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
char_count += 1;
if c == FIELD_SEP {
if cid == 0 {
first_is_field_sep = true;
}
num_conscutive_field_seps += 1;
if cid > 0 && last_c == FIELD_SEP {
if fields.pop().is_none() {
return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string())));
}
} else {
push_field(&mut fields, &mut field);
}
} else {
num_conscutive_field_seps = 0;
if cid == 1 {
if first_is_field_sep {
fields.truncate(0);
}
}
field.push(c);
}
last_c = c;
}
push_field(&mut fields, &mut field);
if char_count == 1 && first_is_field_sep {
fields.truncate(0);
}
if char_count > 1 && num_conscutive_field_seps == 1 {
return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string())));
}
self.0 = fields;
Ok(())
}
pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option<String> {
if value.len() == 0 {
return None;
}
let mut last_c = FIELD_SEP;
let mut field = String::new();
let mut output = String::new();
let push_field = |fs: &mut String, f: &mut String| {
if f.len() > 0 {
fs.push_str(match did_you_mean(&f, possible_values) {
Some(candidate) => candidate,
None => &f,
});
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
if c == FIELD_SEP {
if last_c != FIELD_SEP {
push_field(&mut output, &mut field);
}
output.push(c);
} else {
field.push(c);
}
last_c = c;
}
push_field(&mut output, &mut field);
if &output == value {
None
} else {
Some(output)
}
}
pub fn set_json_value(&self,
mut object: &mut Value,
value: &str,
type_info: JsonTypeInfo,
err: &mut InvalidOptionsError,
orig_cursor: &FieldCursor) {
assert!(self.0.len() > 0);
for field in &self.0[..self.0.len() - 1] {
let tmp = object;
object = match *tmp {
Value::Object(ref mut mapping) => {
assure_entry(mapping, &field)
}
_ => panic!("We don't expect non-object Values here ..."),
};
}
match *object {
Value::Object(ref mut mapping) => {
let field = &self.0[self.0.len() - 1];
let to_jval = |value: &str,
jtype: JsonType,
err: &mut InvalidOptionsError|
-> Value {
match jtype {
JsonType::Boolean =>
Value::Bool(arg_from_str(value, err, &field, "boolean")),
JsonType::Int =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"int"))
.expect("valid f64")),
JsonType::Uint =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"uint"))
.expect("valid f64")),
JsonType::Float =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"float"))
.expect("valid f64")),
JsonType::String => Value::String(value.to_owned()),
}
};
match type_info.ctype {
ComplexType::Pod => {
if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err))
.is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
ComplexType::Vec => {
match *assure_entry(mapping, field) {
Value::Array(ref mut values) =>
values.push(to_jval(value, type_info.jtype, err)),
_ => unreachable!(),
}
}
ComplexType::Map => {
let (key, value) = parse_kv_arg(value, err, true);
let jval = to_jval(value.unwrap_or(""), type_info.jtype, err);
match *assure_entry(mapping, &field) {
Value::Object(ref mut value_map) => {
if value_map.insert(key.to_owned(), jval).is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
_ => unreachable!(),
}
}
}
}
_ => unreachable!(),
}
}
pub fn num_fields(&self) -> usize {
self.0.len()
}
}
pub fn parse_kv_arg<'a>(kv: &'a str,
err: &mut InvalidOptionsError,
for_hashmap: bool)
-> (&'a str, Option<&'a str>) {
let mut add_err = || {
err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(), for_hashmap))
};
match kv.find('=') {
None => {
add_err();
return (kv, None);
}
Some(pos) => {
let key = &kv[..pos];
if kv.len() <= pos + 1 {
add_err();
return (key, Some(""));
}
(key, Some(&kv[pos + 1..]))
}
}
}
pub fn calltype_from_str(name: &str,
valid_protocols: Vec<String>,
err: &mut InvalidOptionsError)
-> CallType {
CallType::Upload(match UploadProtocol::from_str(name) {
Ok(up) => up,
Err(msg) => {
err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols));
UploadProtocol::Simple
}
})
}
pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option<fs::File> {
match fs::File::open(file_path) {
Ok(f) => Some(f),
Err(io_err) => {
err.issues.push(CLIError::Input(InputError::Io((file_path.to_string(), io_err))));
None
}
}
}
pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option<Mime> {
match mime.parse() {
Ok(m) => Some(m),
Err(_) => {
err.issues.push(CLIError::Input(InputError::Mime(mime.to_string())));
None
}
}
}
pub fn writer_from_opts(arg: Option<&str>) -> Result<Box<Write>, io::Error> {
let f = arg.unwrap_or("-");
match f {
"-" => Ok(Box::new(stdout())),
_ => match fs::OpenOptions::new().create(true).write(true).open(f) {
Ok(f) => Ok(Box::new(f)),
Err(io_err) => Err(io_err),
},
}
}
pub fn arg_from_str<'a, T>(arg: &str,
err: &mut InvalidOptionsError,
arg_name: &'a str,
arg_type: &'a str)
-> T
where T: FromStr + Default,
<T as FromStr>::Err: fmt::Display
{
match FromStr::from_str(arg) {
Err(perr) => {
err.issues.push(CLIError::ParseError(arg_name.to_owned(),
arg_type.to_owned(),
arg.to_string(),
format!("{}", perr)));
Default::default()
}
Ok(v) => v,
}
}
pub struct JsonTokenStorage {
pub program_name: &'static str,
pub db_dir: String,
}
impl JsonTokenStorage {
fn path(&self, scope_hash: u64) -> PathBuf {
Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash))
}
}
#[derive(Debug)]
pub enum TokenStorageError {
Json(json::Error),
Io(io::Error),
}
impl fmt::Display for TokenStorageError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
TokenStorageError::Json(ref err) => writeln!(f, "Could not serialize secrets: {}", err),
TokenStorageError::Io(ref err) => writeln!(f, "Failed to write secret token: {}", err),
}
}
}
impl StdError for TokenStorageError {
fn description(&self) -> &str {
"Failure when getting or setting the token storage"
}
}
impl TokenStorage for JsonTokenStorage {
type Error = TokenStorageError;
// NOTE: logging might be interesting, currently we swallow all errors
fn set(&mut self,
scope_hash: u64,
_: &Vec<&str>,
token: Option<Token>)
-> Result<(), TokenStorageError> {
match token {
None => {
match fs::remove_file(self.path(scope_hash)) {
Err(err) => match err.kind() {
io::ErrorKind::NotFound => Ok(()),
_ => Err(TokenStorageError::Io(err)),
},
Ok(_) => Ok(()),
}
}
Some(token) => {
match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) {
Ok(mut f) => {
match json::to_writer_pretty(&mut f, &token) {
Ok(_) => Ok(()),
Err(serde_err) => Err(TokenStorageError::Json(serde_err)),
}
}
Err(io_err) => Err(TokenStorageError::Io(io_err)),
}
}
}
}
fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result<Option<Token>, TokenStorageError> {
match fs::File::open(&self.path(scope_hash)) {
Ok(f) => {
match json::de::from_reader(f) {
Ok(token) => Ok(Some(token)),
Err(err) => Err(TokenStorageError::Json(err)),
}
}
Err(io_err) => {
match io_err.kind() {
io::ErrorKind::NotFound => Ok(None),
_ => Err(TokenStorageError::Io(io_err)),
}
}
}
}
}
#[derive(Debug)]
pub enum ApplicationSecretError {
DecoderError((String, json::Error)),
FormatError(String),
}
impl fmt::Display for ApplicationSecretError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ApplicationSecretError::DecoderError((ref path, ref err)) =>
writeln!(f,
"Could not decode file at '{}' with error: {}.",
path,
err),
ApplicationSecretError::FormatError(ref path) =>
writeln!(f,
"'installed' field is unset in secret file at '{}'.",
path),
}
}
}
#[derive(Debug)]
pub enum ConfigurationError {
DirectoryCreationFailed((String, io::Error)),
DirectoryUnset,
HomeExpansionFailed(String),
Secret(ApplicationSecretError),
Io((String, io::Error)),
}
impl fmt::Display for ConfigurationError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) =>
writeln!(f,
"Directory '{}' could not be created with error: {}.",
dir,
err),
ConfigurationError::DirectoryUnset => writeln!(f, "--config-dir was unset or empty."),
ConfigurationError::HomeExpansionFailed(ref dir) =>
writeln!(f,
"Couldn't find HOME directory of current user, failed to expand '{}'.",
dir),
ConfigurationError::Secret(ref err) => writeln!(f, "Secret -> {}", err),
ConfigurationError::Io((ref path, ref err)) =>
writeln!(f,
"IO operation failed on path '{}' with error: {}.",
path,
err),
}
}
}
#[derive(Debug)]
pub enum InputError {
Io((String, io::Error)),
Mime(String),
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
InputError::Io((ref file_path, ref io_err)) =>
writeln!(f,
"Failed to open '{}' for reading with error: {}.",
file_path,
io_err),
InputError::Mime(ref mime) => writeln!(f, "'{}' is not a known mime-type.", mime),
}
}
}
#[derive(Debug)]
pub enum FieldError {
PopOnEmpty(String),
TrailingFieldSep(String),
Unknown(String, Option<String>, Option<String>),
Duplicate(String),
Empty,
}
impl fmt::Display for FieldError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
FieldError::PopOnEmpty(ref field) =>
writeln!(f, "'{}': Cannot move up on empty field cursor.", field),
FieldError::TrailingFieldSep(ref field) =>
writeln!(f,
"'{}': Single field separator may not be last character.",
field),
FieldError::Unknown(ref field, ref suggestion, ref value) => {
let suffix = match *suggestion {
Some(ref s) => {
let kv = match *value {
Some(ref v) => format!("{}={}", s, v),
None => s.clone(),
};
format!(" Did you mean '{}' ?", kv)
}
None => String::new(),
};
writeln!(f, "Field '{}' does not exist.{}", field, suffix)
}
FieldError::Duplicate(ref cursor) =>
writeln!(f, "Value at '{}' was already set", cursor),
FieldError::Empty => writeln!(f, "Field names must not be empty."),
}
}
}
#[derive(Debug)]
pub enum CLIError {
Configuration(ConfigurationError),
ParseError(String, String, String, String),
UnknownParameter(String, Vec<&'static str>),
InvalidUploadProtocol(String, Vec<String>),
InvalidKeyValueSyntax(String, bool),
Input(InputError),
Field(FieldError),
MissingCommandError,
MissingMethodError(String),
}
impl fmt::Display for CLIError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err),
CLIError::Input(ref err) => write!(f, "Input -> {}", err),
CLIError::Field(ref err) => write!(f, "Field -> {}", err),
CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) =>
writeln!(f,
"'{}' is not a valid upload protocol. Choose from one of {}.",
proto_name,
valid_names.join(", ")),
CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) =>
writeln!(f,
"Failed to parse argument '{}' with value '{}' as {} with error: {}.",
arg_name,
value,
type_name,
err_desc),
CLIError::UnknownParameter(ref param_name, ref possible_values) => {
let suffix = match did_you_mean(param_name, &possible_values) {
Some(v) => format!(" Did you mean '{}' ?", v),
None => String::new(),
};
write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix)
}
CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => {
let hashmap_info = if is_hashmap {
"hashmap "
} else {
""
};
writeln!(f,
"'{}' does not match {}pattern <key>=<value>.",
kv,
hashmap_info)
}
CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."),
CLIError::MissingMethodError(ref cmd) =>
writeln!(f,
"Please specify the method to call on the '{}' command.",
cmd),
}
}
}
#[derive(Debug)]
pub struct InvalidOptionsError {
pub issues: Vec<CLIError>,
pub exit_code: i32,
}
impl fmt::Display for InvalidOptionsError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for issue in &self.issues {
try!(issue.fmt(f));
}
Ok(())
}
}
impl InvalidOptionsError {
pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError {
InvalidOptionsError {
issues: vec![err],
exit_code: exit_code,
}
}
pub fn new() -> InvalidOptionsError {
InvalidOptionsError {
issues: Vec::new(),
exit_code: 1,
}
}
}
pub fn assure_config_dir_exists(dir: &str) -> Result<String, CLIError> {
let trdir = dir.trim();
if trdir.len() == 0 {
return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset));
}
let expanded_config_dir = if trdir.as_bytes()[0] == b'~' {
match env::var("HOME").ok().or(env::var("UserProfile").ok()) {
None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))),
Some(mut user) => {
user.push_str(&trdir[1..]);
user
}
}
} else {
trdir.to_string()
};
if let Err(err) = fs::create_dir(&expanded_config_dir) {
if err.kind() != io::ErrorKind::AlreadyExists {
return Err(CLIError::Configuration(
ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err))));
}
}
Ok(expanded_config_dir)
}
pub fn application_secret_from_directory(dir: &str,
secret_basename: &str,
json_console_secret: &str)
-> Result<ApplicationSecret, CLIError> {
let secret_path = Path::new(dir).join(secret_basename);
let secret_str = || secret_path.as_path().to_str().unwrap().to_string();
let secret_io_error = |io_err: io::Error| {
Err(CLIError::Configuration(ConfigurationError::Io((secret_str(), io_err))))
};
for _ in 0..2 {
match fs::File::open(&secret_path) {
Err(mut err) => {
if err.kind() == io::ErrorKind::NotFound {
// Write our built-in one - user may adjust the written file at will
err = match fs::OpenOptions::new()
.create(true)
.write(true)
.open(&secret_path) {
Err(cfe) => cfe,
Ok(mut f) => {
// Assure we convert 'ugly' json string into pretty one
let console_secret: ConsoleApplicationSecret =
json::from_str(json_console_secret).unwrap();
match json::to_writer_pretty(&mut f, &console_secret) {
Err(serde_err) =>
panic!("Unexpected serde error: {:#?}", serde_err),
Ok(_) => continue,
}
}
};
// fall through to IO error handling
}
return secret_io_error(err);
}
Ok(f) => {
match json::de::from_reader::<_, ConsoleApplicationSecret>(f) {
Err(json_err) =>
return Err(CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::DecoderError(
(secret_str(), json_err)
)))),
Ok(console_secret) => match console_secret.installed {
Some(secret) => return Ok(secret),
None => return Err(
CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::FormatError(secret_str())
))),
},
}
}
}
}
unreachable!();
}

View File

@@ -0,0 +1,353 @@
// DO NOT EDIT !
// This file was generated automatically from 'src/mako/cli/main.rs.mako'
// DO NOT EDIT !
#![allow(unused_variables, unused_imports, dead_code, unused_mut)]
#[macro_use]
extern crate clap;
extern crate yup_oauth2 as oauth2;
extern crate yup_hyper_mock as mock;
extern crate hyper_rustls;
extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate mime;
extern crate strsim;
extern crate google_acceleratedmobilepageurl1 as api;
use std::env;
use std::io::{self, Write};
use clap::{App, SubCommand, Arg};
mod cmn;
use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg,
input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol,
calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo};
use std::default::Default;
use std::str::FromStr;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, FlowType};
use serde_json as json;
use clap::ArgMatches;
enum DoitError {
IoError(String, io::Error),
ApiError(api::Error),
}
struct Engine<'n> {
opt: ArgMatches<'n>,
hub: api::Acceleratedmobilepageurl<hyper::Client, Authenticator<DefaultAuthenticatorDelegate, JsonTokenStorage, hyper::Client>>,
gp: Vec<&'static str>,
gpm: Vec<(&'static str, &'static str)>,
}
impl<'n> Engine<'n> {
fn _amp_urls_batch_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"lookup-strategy" => Some(("lookupStrategy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"urls" => Some(("urls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["lookup-strategy", "urls"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::BatchGetAmpUrlsRequest = json::value::from_value(object).unwrap();
let mut call = self.hub.amp_urls().batch_get(request);
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _doit(&self, dry_run: bool) -> Result<Result<(), DoitError>, Option<InvalidOptionsError>> {
let mut err = InvalidOptionsError::new();
let mut call_result: Result<(), DoitError> = Ok(());
let mut err_opt: Option<InvalidOptionsError> = None;
match self.opt.subcommand() {
("amp-urls", Some(opt)) => {
match opt.subcommand() {
("batch-get", Some(opt)) => {
call_result = self._amp_urls_batch_get(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("amp-urls".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
_ => {
err.issues.push(CLIError::MissingCommandError);
writeln!(io::stderr(), "{}\n", self.opt.usage()).ok();
}
}
if dry_run {
if err.issues.len() > 0 {
err_opt = Some(err);
}
Err(err_opt)
} else {
Ok(call_result)
}
}
// Please note that this call will fail if any part of the opt can't be handled
fn new(opt: ArgMatches<'n>) -> Result<Engine<'n>, InvalidOptionsError> {
let (config_dir, secret) = {
let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) {
Err(e) => return Err(InvalidOptionsError::single(e, 3)),
Ok(p) => p,
};
match cmn::application_secret_from_directory(&config_dir, "acceleratedmobilepageurl1-secret.json",
"{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") {
Ok(secret) => (config_dir, secret),
Err(e) => return Err(InvalidOptionsError::single(e, 4))
}
};
let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate,
if opt.is_present("debug-auth") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
},
JsonTokenStorage {
program_name: "acceleratedmobilepageurl1",
db_dir: config_dir.clone(),
}, Some(FlowType::InstalledRedirect(54324)));
let client =
if opt.is_present("debug") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
};
let engine = Engine {
opt: opt,
hub: api::Acceleratedmobilepageurl::new(client, auth),
gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"],
gpm: vec![
("$-xgafv", "$.xgafv"),
("access-token", "access_token"),
("bearer-token", "bearer_token"),
("oauth-token", "oauth_token"),
("pretty-print", "prettyPrint"),
("quota-user", "quotaUser"),
("upload-type", "uploadType"),
("upload-protocol", "upload_protocol"),
]
};
match engine._doit(true) {
Err(Some(err)) => Err(err),
Err(None) => Ok(engine),
Ok(_) => unreachable!(),
}
}
fn doit(&self) -> Result<(), DoitError> {
match self._doit(false) {
Ok(res) => res,
Err(_) => unreachable!(),
}
}
}
fn main() {
let mut exit_status = 0i32;
let arg_data = [
("amp-urls", "methods: 'batch-get'", vec![
("batch-get",
Some(r##"Returns AMP URL(s) and equivalent
[AMP Cache URL(s)](/amp/cache/overview#amp-cache-url-format)."##),
"Details at http://byron.github.io/google-apis-rs/google_acceleratedmobilepageurl1_cli/amp-urls_batch-get",
vec![
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
];
let mut app = App::new("acceleratedmobilepageurl1")
.author("Sebastian Thiel <byronimo@gmail.com>")
.version("1.0.7+20171202")
.about("Retrieves the list of AMP URLs (and equivalent AMP Cache URLs) for a given list of public URL(s).
")
.after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_acceleratedmobilepageurl1_cli")
.arg(Arg::with_name("folder")
.long("config-dir")
.help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli")
.multiple(false)
.takes_value(true))
.arg(Arg::with_name("debug")
.long("debug")
.help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false))
.arg(Arg::with_name("debug-auth")
.long("debug-auth")
.help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false));
for &(main_command_name, about, ref subcommands) in arg_data.iter() {
let mut mcmd = SubCommand::with_name(main_command_name).about(about);
for &(sub_command_name, ref desc, url_info, ref args) in subcommands {
let mut scmd = SubCommand::with_name(sub_command_name);
if let &Some(desc) = desc {
scmd = scmd.about(desc);
}
scmd = scmd.after_help(url_info);
for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args {
let arg_name_str =
match (arg_name, flag) {
(&Some(an), _ ) => an,
(_ , &Some(f)) => f,
_ => unreachable!(),
};
let mut arg = Arg::with_name(arg_name_str)
.empty_values(false);
if let &Some(short_flag) = flag {
arg = arg.short(short_flag);
}
if let &Some(desc) = desc {
arg = arg.help(desc);
}
if arg_name.is_some() && flag.is_some() {
arg = arg.takes_value(true);
}
if let &Some(required) = required {
arg = arg.required(required);
}
if let &Some(multi) = multi {
arg = arg.multiple(multi);
}
scmd = scmd.arg(arg);
}
mcmd = mcmd.subcommand(scmd);
}
app = app.subcommand(mcmd);
}
let matches = app.get_matches();
let debug = matches.is_present("debug");
match Engine::new(matches) {
Err(err) => {
exit_status = err.exit_code;
writeln!(io::stderr(), "{}", err).ok();
},
Ok(engine) => {
if let Err(doit_err) = engine.doit() {
exit_status = 1;
match doit_err {
DoitError::IoError(path, err) => {
writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok();
},
DoitError::ApiError(err) => {
if debug {
writeln!(io::stderr(), "{:#?}", err).ok();
} else {
writeln!(io::stderr(), "{}", err).ok();
}
}
}
}
}
}
std::process::exit(exit_status);
}

View File

@@ -0,0 +1,31 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-acceleratedmobilepageurl1"
version = "1.0.7+20171202"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with acceleratedmobilepageurl (protocol v1)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/acceleratedmobilepageurl1"
homepage = "https://developers.google.com/amp/cache/"
documentation = "https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202"
license = "MIT"
keywords = ["acceleratedmobilepag", "google", "protocol", "web", "api"]
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
url = "= 0.5"
[features]

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,180 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/api/README.md.mako'
DO NOT EDIT !
-->
The `google-acceleratedmobilepageurl1` library allows access to all features of the *Google acceleratedmobilepageurl* service.
This documentation was generated from *acceleratedmobilepageurl* crate version *1.0.7+20171202*, where *20171202* is the exact revision of the *acceleratedmobilepageurl:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.7*.
Everything else about the *acceleratedmobilepageurl* *v1* API can be found at the
[official documentation site](https://developers.google.com/amp/cache/).
# Features
Handle the following *Resources* with ease from the central [hub](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/struct.Acceleratedmobilepageurl.html) ...
* [amp urls](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/struct.AmpUrl.html)
* [*batch get*](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/struct.AmpUrlBatchGetCall.html)
# Structure of this Library
The API is structured into the following primary items:
* **[Hub](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/struct.Acceleratedmobilepageurl.html)**
* a central object to maintain state and allow accessing all *Activities*
* creates [*Method Builders*](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.MethodsBuilder.html) which in turn
allow access to individual [*Call Builders*](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.CallBuilder.html)
* **[Resources](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.Resource.html)**
* primary types that you can apply *Activities* to
* a collection of properties and *Parts*
* **[Parts](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.Part.html)**
* a collection of properties
* never directly used in *Activities*
* **[Activities](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.CallBuilder.html)**
* operations to apply to *Resources*
All *structures* are marked with applicable traits to further categorize them and ease browsing.
Generally speaking, you can invoke *Activities* like this:
```Rust,ignore
let r = hub.resource().activity(...).doit()
```
Or specifically ...
```ignore
let r = hub.amp_urls().batch_get(...).doit()
```
The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
The `doit()` method performs the actual communication with the server and returns the respective result.
# Usage
## Setting up your Project
To use this library, you would put the following lines into your `Cargo.toml` file:
```toml
[dependencies]
google-acceleratedmobilepageurl1 = "*"
```
## A complete example
```Rust
extern crate hyper;
extern crate hyper_rustls;
extern crate yup_oauth2 as oauth2;
extern crate google_acceleratedmobilepageurl1 as acceleratedmobilepageurl1;
use acceleratedmobilepageurl1::BatchGetAmpUrlsRequest;
use acceleratedmobilepageurl1::{Result, Error};
use std::default::Default;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
use acceleratedmobilepageurl1::Acceleratedmobilepageurl;
// Get an ApplicationSecret instance by some means. It contains the `client_id` and
// `client_secret`, among other things.
let secret: ApplicationSecret = Default::default();
// Instantiate the authenticator. It will choose a suitable authentication flow for you,
// unless you replace `None` with the desired Flow.
// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
// retrieve them from storage.
let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
<MemoryStorage as Default>::default(), None);
let mut hub = Acceleratedmobilepageurl::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
// As the method needs a request, you would usually fill it with the desired information
// into the respective structure. Some of the parts shown here might not be applicable !
// Values shown here are possibly random and not representative !
let mut req = BatchGetAmpUrlsRequest::default();
// You can configure optional parameters by calling the respective setters at will, and
// execute the final call using `doit()`.
// Values shown here are possibly random and not representative !
let result = hub.amp_urls().batch_get(req)
.doit();
match result {
Err(e) => match e {
// The Error enum provides details about what exactly happened.
// You can also just use its `Debug`, `Display` or `Error` traits
Error::HttpError(_)
|Error::MissingAPIKey
|Error::MissingToken(_)
|Error::Cancelled
|Error::UploadSizeLimitExceeded(_, _)
|Error::Failure(_)
|Error::BadRequest(_)
|Error::FieldClash(_)
|Error::JsonDecodeError(_, _) => println!("{}", e),
},
Ok(res) => println!("Success: {:?}", res),
}
```
## Handling Errors
All errors produced by the system are provided either as [Result](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/enum.Result.html) enumeration as return value of
the doit() methods, or handed as possibly intermediate results to either the
[Hub Delegate](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.Delegate.html), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html).
When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
makes the system potentially resilient to all kinds of errors.
## Uploads and Downloads
If a method supports downloads, the response body, which is part of the [Result](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/enum.Result.html), should be
read by you to obtain the media.
If such a method also supports a [Response Result](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.ResponseResult.html), it will return that by default.
You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
this call: `.param("alt", "media")`.
Methods supporting uploads can do so using up to 2 different protocols:
*simple* and *resumable*. The distinctiveness of each is represented by customized
`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
## Customization and Callbacks
You may alter the way an `doit()` method is called by providing a [delegate](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.Delegate.html) to the
[Method Builder](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.CallBuilder.html) before making the final `doit()` call.
Respective methods will be called to provide progress information, as well as determine whether the system should
retry on failure.
The [delegate trait](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
## Optional Parts in Server-Requests
All structures provided by this library are made to be [enocodable](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.RequestValue.html) and
[decodable](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
are valid.
Most optionals are are considered [Parts](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.Part.html) which are identifiable by name, which will be sent to
the server to indicate either the set parts of the request or the desired parts in the response.
## Builder Arguments
Using [method builders](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods.
These will always take a single argument, for which the following statements are true.
* [PODs][wiki-pod] are handed by copy
* strings are passed as `&str`
* [request values](https://docs.rs/google-acceleratedmobilepageurl1/1.0.7+20171202/google_acceleratedmobilepageurl1/trait.RequestValue.html) are moved
Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
[google-go-api]: https://github.com/google/google-api-go-client
# License
The **acceleratedmobilepageurl1** library was generated by Sebastian Thiel, and is placed
under the *MIT* license.
You can read the full text at the repository's [license file][repo-license].
[repo-license]: https://github.com/Byron/google-apis-rsblob/master/LICENSE.md

View File

@@ -0,0 +1,753 @@
// COPY OF 'src/rust/api/cmn.rs'
// DO NOT EDIT
use std::io::{self, Read, Seek, Cursor, Write, SeekFrom};
use std;
use std::fmt::{self, Display};
use std::str::FromStr;
use std::error;
use std::thread::sleep;
use std::time::Duration;
use mime::{Mime, TopLevel, SubLevel, Attr, Value};
use oauth2::{TokenType, Retry, self};
use hyper;
use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header,
HeaderFormat, Bearer};
use hyper::http::h1::LINE_ENDING;
use hyper::method::Method;
use hyper::status::StatusCode;
use serde_json as json;
/// Identifies the Hub. There is only one per library, this trait is supposed
/// to make intended use more explicit.
/// The hub allows to access all resource methods more easily.
pub trait Hub {}
/// Identifies types for building methods of a particular resource type
pub trait MethodsBuilder {}
/// Identifies types which represent builders for a particular resource method
pub trait CallBuilder {}
/// Identifies types which can be inserted and deleted.
/// Types with this trait are most commonly used by clients of this API.
pub trait Resource {}
/// Identifies types which are used in API responses.
pub trait ResponseResult {}
/// Identifies types which are used in API requests.
pub trait RequestValue {}
/// Identifies types which are not actually used by the API
/// This might be a bug within the google API schema.
pub trait UnusedType {}
/// Identifies types which are only used as part of other types, which
/// usually are carrying the `Resource` trait.
pub trait Part {}
/// Identifies types which are only used by other types internally.
/// They have no special meaning, this trait just marks them for completeness.
pub trait NestedType {}
/// A utility to specify reader types which provide seeking capabilities too
pub trait ReadSeek: Seek + Read {}
impl<T: Seek + Read> ReadSeek for T {}
/// A trait for all types that can convert themselves into a *parts* string
pub trait ToParts {
fn to_parts(&self) -> String;
}
/// A utility type which can decode a server response that indicates error
#[derive(Deserialize)]
pub struct JsonServerError {
pub error: String,
pub error_description: Option<String>
}
/// A utility to represent detailed errors we might see in case there are BadRequests.
/// The latter happen if the sent parameters or request structures are unsound
#[derive(Deserialize, Serialize, Debug)]
pub struct ErrorResponse {
error: ServerError,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerError {
errors: Vec<ServerMessage>,
code: u16,
message: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerMessage {
domain: String,
reason: String,
message: String,
#[serde(rename="locationType")]
location_type: Option<String>,
location: Option<String>
}
#[derive(Copy, Clone)]
pub struct DummyNetworkStream;
impl Read for DummyNetworkStream {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl Write for DummyNetworkStream {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl hyper::net::NetworkStream for DummyNetworkStream {
fn peer_addr(&mut self) -> io::Result<std::net::SocketAddr> {
Ok("127.0.0.1:1337".parse().unwrap())
}
fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
}
/// A trait specifying functionality to help controlling any request performed by the API.
/// The trait has a conservative default implementation.
///
/// It contains methods to deal with all common issues, as well with the ones related to
/// uploading media
pub trait Delegate {
/// Called at the beginning of any API request. The delegate should store the method
/// information if he is interesting in knowing more context when further calls to it
/// are made.
/// The matching `finished()` call will always be made, no matter whether or not the API
/// request was successful. That way, the delegate may easily maintain a clean state
/// between various API calls.
fn begin(&mut self, MethodInfo) {}
/// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
///
/// Return retry information.
fn http_error(&mut self, &hyper::Error) -> Retry {
Retry::Abort
}
/// Called whenever there is the need for your applications API key after
/// the official authenticator implementation didn't provide one, for some reason.
/// If this method returns None as well, the underlying operation will fail
fn api_key(&mut self) -> Option<String> {
None
}
/// Called whenever the Authenticator didn't yield a token. The delegate
/// may attempt to provide one, or just take it as a general information about the
/// impending failure.
/// The given Error provides information about why the token couldn't be acquired in the
/// first place
fn token(&mut self, err: &error::Error) -> Option<oauth2::Token> {
let _ = err;
None
}
/// Called during resumable uploads to provide a URL for the impending upload.
/// It was saved after a previous call to `store_upload_url(...)`, and if not None,
/// will be used instead of asking the server for a new upload URL.
/// This is useful in case a previous resumable upload was aborted/canceled, but should now
/// be resumed.
/// The returned URL will be used exactly once - if it fails again and the delegate allows
/// to retry, we will ask the server for a new upload URL.
fn upload_url(&mut self) -> Option<String> {
None
}
/// Called after we have retrieved a new upload URL for a resumable upload to store it
/// in case we fail or cancel. That way, we can attempt to resume the upload later,
/// see `upload_url()`.
/// It will also be called with None after a successful upload, which allows the delegate
/// to forget the URL. That way, we will not attempt to resume an upload that has already
/// finished.
fn store_upload_url(&mut self, url: Option<&str>) {
let _ = url;
}
/// Called whenever a server response could not be decoded from json.
/// It's for informational purposes only, the caller will return with an error
/// accordingly.
///
/// # Arguments
///
/// * `json_encoded_value` - The json-encoded value which failed to decode.
/// * `json_decode_error` - The decoder error
fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &json::Error) {
let _ = json_encoded_value;
let _ = json_decode_error;
}
/// Called whenever the http request returns with a non-success status code.
/// This can involve authentication issues, or anything else that very much
/// depends on the used API method.
/// The delegate should check the status, header and decoded json error to decide
/// whether to retry or not. In the latter case, the underlying call will fail.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
fn http_failure(&mut self, _: &hyper::client::Response, Option<JsonServerError>, _: Option<ServerError>) -> Retry {
Retry::Abort
}
/// Called prior to sending the main request of the given method. It can be used to time
/// the call or to print progress information.
/// It's also useful as you can be sure that a request will definitely be made.
fn pre_request(&mut self) { }
/// Return the size of each chunk of a resumable upload.
/// Must be a power of two, with 1<<18 being the smallest allowed chunk size.
/// Will be called once before starting any resumable upload.
fn chunk_size(&mut self) -> u64 {
1 << 23
}
/// Called before the given chunk is uploaded to the server.
/// If true is returned, the upload will be interrupted.
/// However, it may be resumable if you stored the upload URL in a previous call
/// to `store_upload_url()`
fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool {
let _ = chunk;
false
}
/// Called before the API request method returns, in every case. It can be used to clean up
/// internal state between calls to the API.
/// This call always has a matching call to `begin(...)`.
///
/// # Arguments
///
/// * `is_success` - a true value indicates the operation was successful. If false, you should
/// discard all values stored during `store_upload_url`.
fn finished(&mut self, is_success: bool) {
let _ = is_success;
}
}
/// A delegate with a conservative default implementation, which is used if no other delegate is
/// set.
#[derive(Default)]
pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}
#[derive(Debug)]
pub enum Error {
/// The http connection failed
HttpError(hyper::Error),
/// An attempt was made to upload a resource with size stored in field `.0`
/// even though the maximum upload size is what is stored in field `.1`.
UploadSizeLimitExceeded(u64, u64),
/// Represents information about a request that was not understood by the server.
/// Details are included.
BadRequest(ErrorResponse),
/// We needed an API key for authentication, but didn't obtain one.
/// Neither through the authenticator, nor through the Delegate.
MissingAPIKey,
/// We required a Token, but didn't get one from the Authenticator
MissingToken(Box<error::Error>),
/// The delgate instructed to cancel the operation
Cancelled,
/// An additional, free form field clashed with one of the built-in optional ones
FieldClash(&'static str),
/// Shows that we failed to decode the server response.
/// This can happen if the protocol changes in conjunction with strict json decoding.
JsonDecodeError(String, json::Error),
/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref err) => err.fmt(f),
Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) =>
writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}"
, resource_size, max_size),
Error::MissingAPIKey => {
(writeln!(f, "The application's API key was not found in the configuration")).ok();
writeln!(f, "It is used as there are no Scopes defined for this method.")
},
Error::BadRequest(ref err) => {
try!(writeln!(f, "Bad Request ({}): {}", err.error.code, err.error.message));
for err in err.error.errors.iter() {
try!(writeln!(f, " {}: {}, {}{}",
err.domain,
err.message,
err.reason,
match &err.location {
&Some(ref loc) => format!("@{}", loc),
&None => String::new(),
}));
}
Ok(())
},
Error::MissingToken(ref err) =>
writeln!(f, "Token retrieval failed with error: {}", err),
Error::Cancelled =>
writeln!(f, "Operation cancelled by delegate"),
Error::FieldClash(field) =>
writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field),
Error::JsonDecodeError(ref json_str, ref err)
=> writeln!(f, "{}: {}", err, json_str),
Error::Failure(ref response) =>
writeln!(f, "Http status indicates failure: {:?}", response),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::HttpError(ref err) => err.description(),
Error::JsonDecodeError(_, ref err) => err.description(),
_ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead"
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::HttpError(ref err) => err.cause(),
Error::JsonDecodeError(_, ref err) => err.cause(),
_ => None
}
}
}
/// A universal result type used as return for all calls.
pub type Result<T> = std::result::Result<T, Error>;
/// Contains information about an API request.
pub struct MethodInfo {
pub id: &'static str,
pub http_method: Method,
}
const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d";
/// Provides a `Read` interface that converts multiple parts into the protocol
/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387).
/// **Note**: This implementation is just as rich as it needs to be to perform uploads
/// to google APIs, and might not be a fully-featured implementation.
#[derive(Default)]
pub struct MultiPartReader<'a> {
raw_parts: Vec<(Headers, &'a mut Read)>,
current_part: Option<(Cursor<Vec<u8>>, &'a mut Read)>,
last_part_boundary: Option<Cursor<Vec<u8>>>,
}
impl<'a> MultiPartReader<'a> {
/// Reserve memory for exactly the given amount of parts
pub fn reserve_exact(&mut self, cap: usize) {
self.raw_parts.reserve_exact(cap);
}
/// Add a new part to the queue of parts to be read on the first `read` call.
///
/// # Arguments
///
/// `headers` - identifying the body of the part. It's similar to the header
/// in an ordinary single-part call, and should thus contain the
/// same information.
/// `reader` - a reader providing the part's body
/// `size` - the amount of bytes provided by the reader. It will be put onto the header as
/// content-size.
/// `mime` - It will be put onto the content type
pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> {
let mut headers = Headers::new();
headers.set(ContentType(mime_type));
headers.set(ContentLength(size));
self.raw_parts.push((headers, reader));
self
}
/// Returns the mime-type representing our multi-part message.
/// Use it with the ContentType header.
pub fn mime_type(&self) -> Mime {
Mime(
TopLevel::Multipart,
SubLevel::Ext("Related".to_string()),
vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))],
)
}
/// Returns true if we are totally used
fn is_depleted(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none()
}
/// Returns true if we are handling our last part
fn is_last_part(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_some()
}
}
impl<'a> Read for MultiPartReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.raw_parts.len(),
self.current_part.is_none(),
self.last_part_boundary.is_none()) {
(_, _, false) => {
let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0);
if br < buf.len() {
self.last_part_boundary = None;
}
return Ok(br)
},
(0, true, true) => return Ok(0),
(n, true, _) if n > 0 => {
let (headers, reader) = self.raw_parts.remove(0);
let mut c = Cursor::new(Vec::<u8>::new());
(write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING,
headers, LINE_ENDING)).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
self.current_part = Some((c, reader));
}
_ => {},
}
// read headers as long as possible
let (hb, rr) = {
let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap();
let b = c.read(buf).unwrap_or(0);
(b, reader.read(&mut buf[b..]))
};
match rr {
Ok(bytes_read) => {
if hb < buf.len() && bytes_read == 0 {
if self.is_last_part() {
// before clearing the last part, we will add the boundary that
// will be written last
self.last_part_boundary = Some(Cursor::new(
format!("{}--{}--", LINE_ENDING, BOUNDARY).into_bytes()))
}
// We are depleted - this can trigger the next part to come in
self.current_part = None;
}
let mut total_bytes_read = hb + bytes_read;
while total_bytes_read < buf.len() && !self.is_depleted() {
match self.read(&mut buf[total_bytes_read ..]) {
Ok(br) => total_bytes_read += br,
Err(err) => return Err(err),
}
}
Ok(total_bytes_read)
}
Err(err) => {
// fail permanently
self.current_part = None;
self.last_part_boundary = None;
self.raw_parts.clear();
Err(err)
}
}
}
}
/// The `X-Upload-Content-Type` header.
///
/// Generated via rustc --pretty expanded -Z unstable-options, and manually
/// processed to be more readable.
#[derive(PartialEq, Debug, Clone)]
pub struct XUploadContentType(pub Mime);
impl ::std::ops::Deref for XUploadContentType {
type Target = Mime;
fn deref<'a>(&'a self) -> &'a Mime { &self.0 }
}
impl ::std::ops::DerefMut for XUploadContentType {
fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 }
}
impl Header for XUploadContentType {
fn header_name() -> &'static str { "X-Upload-Content-Type" }
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType)
}
}
impl HeaderFormat for XUploadContentType {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&**self, f)
}
}
impl Display for XUploadContentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chunk {
pub first: u64,
pub last: u64
}
impl fmt::Display for Chunk {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(write!(fmt, "{}-{}", self.first, self.last)).ok();
Ok(())
}
}
impl FromStr for Chunk {
type Err = &'static str;
/// NOTE: only implements `%i-%i`, not `*`
fn from_str(s: &str) -> std::result::Result<Chunk, &'static str> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 2 {
return Err("Expected two parts: %i-%i")
}
Ok(
Chunk {
first: match FromStr::from_str(parts[0]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'first' as digit")
},
last: match FromStr::from_str(parts[1]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'last' as digit")
}
}
)
}
}
/// Implements the Content-Range header, for serialization only
#[derive(Clone, PartialEq, Debug)]
pub struct ContentRange {
pub range: Option<Chunk>,
pub total_length: u64,
}
impl Header for ContentRange {
fn header_name() -> &'static str {
"Content-Range"
}
/// We are not parsable, as parsing is done by the `Range` header
fn parse_header(_: &[Vec<u8>]) -> hyper::error::Result<Self> {
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for ContentRange {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("bytes "));
match self.range {
Some(ref c) => try!(c.fmt(fmt)),
None => try!(fmt.write_str("*"))
}
(write!(fmt, "/{}", self.total_length)).ok();
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct RangeResponseHeader(pub Chunk);
impl Header for RangeResponseHeader {
fn header_name() -> &'static str {
"Range"
}
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
if raw.len() > 0 {
let v = &raw[0];
if let Ok(s) = std::str::from_utf8(v) {
const PREFIX: &'static str = "bytes ";
if s.starts_with(PREFIX) {
if let Ok(c) = <Chunk as FromStr>::from_str(&s[PREFIX.len()..]) {
return Ok(RangeResponseHeader(c))
}
}
}
}
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for RangeResponseHeader {
/// No implmentation necessary, we just need to parse
fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
/// A utility type to perform a resumable upload from start to end.
pub struct ResumableUploadHelper<'a, A: 'a> {
pub client: &'a mut hyper::client::Client,
pub delegate: &'a mut Delegate,
pub start_at: Option<u64>,
pub auth: &'a mut A,
pub user_agent: &'a str,
pub auth_header: Authorization<Bearer>,
pub url: &'a str,
pub reader: &'a mut ReadSeek,
pub media_type: Mime,
pub content_length: u64
}
impl<'a, A> ResumableUploadHelper<'a, A>
where A: oauth2::GetToken {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::Result<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
.header(ContentRange { range: None, total_length: self.content_length })
.header(self.auth_header.clone())
.send() {
Ok(r) => {
// 308 = resume-incomplete == PermanentRedirect
let headers = r.headers.clone();
let h: &RangeResponseHeader = match headers.get() {
Some(hh) if r.status == StatusCode::PermanentRedirect => hh,
None|Some(_) => {
if let Retry::After(d) = self.delegate.http_failure(&r, None, None) {
sleep(d);
continue;
}
return Err(Ok(r))
}
};
return Ok(h.0.last)
}
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Err(Err(err))
}
}
}
}
/// returns None if operation was cancelled by delegate, or the HttpResult.
/// It can be that we return the result just because we didn't understand the status code -
/// caller should check for status himself before assuming it's OK to use
pub fn upload(&mut self) -> Option<hyper::Result<hyper::client::Response>> {
let mut start = match self.start_at {
Some(s) => s,
None => match self.query_transfer_status() {
Ok(s) => s,
Err(result) => return Some(result)
}
};
const MIN_CHUNK_SIZE: u64 = 1 << 18;
let chunk_size = match self.delegate.chunk_size() {
cs if cs > MIN_CHUNK_SIZE => cs,
_ => MIN_CHUNK_SIZE
};
self.reader.seek(SeekFrom::Start(start)).unwrap();
loop {
let request_size = match self.content_length - start {
rs if rs > chunk_size => chunk_size,
rs => rs
};
let mut section_reader = self.reader.take(request_size);
let range_header = ContentRange {
range: Some(Chunk {first: start, last: start + request_size - 1}),
total_length: self.content_length
};
start += request_size;
if self.delegate.cancel_chunk_upload(&range_header) {
return None
}
let res = self.client.post(self.url)
.header(range_header)
.header(ContentType(self.media_type.clone()))
.header(UserAgent(self.user_agent.to_string()))
.body(&mut section_reader)
.send();
match res {
Ok(mut res) => {
if res.status == StatusCode::PermanentRedirect {
continue
}
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let Retry::After(d) = self.delegate.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
}
return Some(Ok(res))
},
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Some(Err(err))
}
}
}
}
}
// Copy of src/rust/cli/cmn.rs
// TODO(ST): Allow sharing common code between program types
pub fn remove_json_null_values(value: &mut json::value::Value) {
match *value {
json::value::Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}

View File

@@ -0,0 +1,725 @@
// DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.mako'
// DO NOT EDIT !
//! This documentation was generated from *acceleratedmobilepageurl* crate version *1.0.7+20171202*, where *20171202* is the exact revision of the *acceleratedmobilepageurl:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.7*.
//!
//! Everything else about the *acceleratedmobilepageurl* *v1* API can be found at the
//! [official documentation site](https://developers.google.com/amp/cache/).
//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/acceleratedmobilepageurl1).
//! # Features
//!
//! Handle the following *Resources* with ease from the central [hub](struct.Acceleratedmobilepageurl.html) ...
//!
//! * [amp urls](struct.AmpUrl.html)
//! * [*batch get*](struct.AmpUrlBatchGetCall.html)
//!
//!
//!
//!
//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](http://byron.github.io/google-apis-rs).
//!
//! # Structure of this Library
//!
//! The API is structured into the following primary items:
//!
//! * **[Hub](struct.Acceleratedmobilepageurl.html)**
//! * a central object to maintain state and allow accessing all *Activities*
//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn
//! allow access to individual [*Call Builders*](trait.CallBuilder.html)
//! * **[Resources](trait.Resource.html)**
//! * primary types that you can apply *Activities* to
//! * a collection of properties and *Parts*
//! * **[Parts](trait.Part.html)**
//! * a collection of properties
//! * never directly used in *Activities*
//! * **[Activities](trait.CallBuilder.html)**
//! * operations to apply to *Resources*
//!
//! All *structures* are marked with applicable traits to further categorize them and ease browsing.
//!
//! Generally speaking, you can invoke *Activities* like this:
//!
//! ```Rust,ignore
//! let r = hub.resource().activity(...).doit()
//! ```
//!
//! Or specifically ...
//!
//! ```ignore
//! let r = hub.amp_urls().batch_get(...).doit()
//! ```
//!
//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
//! The `doit()` method performs the actual communication with the server and returns the respective result.
//!
//! # Usage
//!
//! ## Setting up your Project
//!
//! To use this library, you would put the following lines into your `Cargo.toml` file:
//!
//! ```toml
//! [dependencies]
//! google-acceleratedmobilepageurl1 = "*"
//! ```
//!
//! ## A complete example
//!
//! ```test_harness,no_run
//! extern crate hyper;
//! extern crate hyper_rustls;
//! extern crate yup_oauth2 as oauth2;
//! extern crate google_acceleratedmobilepageurl1 as acceleratedmobilepageurl1;
//! use acceleratedmobilepageurl1::BatchGetAmpUrlsRequest;
//! use acceleratedmobilepageurl1::{Result, Error};
//! # #[test] fn egal() {
//! use std::default::Default;
//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
//! use acceleratedmobilepageurl1::Acceleratedmobilepageurl;
//!
//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and
//! // `client_secret`, among other things.
//! let secret: ApplicationSecret = Default::default();
//! // Instantiate the authenticator. It will choose a suitable authentication flow for you,
//! // unless you replace `None` with the desired Flow.
//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
//! // retrieve them from storage.
//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
//! hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
//! <MemoryStorage as Default>::default(), None);
//! let mut hub = Acceleratedmobilepageurl::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
//! // As the method needs a request, you would usually fill it with the desired information
//! // into the respective structure. Some of the parts shown here might not be applicable !
//! // Values shown here are possibly random and not representative !
//! let mut req = BatchGetAmpUrlsRequest::default();
//!
//! // You can configure optional parameters by calling the respective setters at will, and
//! // execute the final call using `doit()`.
//! // Values shown here are possibly random and not representative !
//! let result = hub.amp_urls().batch_get(req)
//! .doit();
//!
//! match result {
//! Err(e) => match e {
//! // The Error enum provides details about what exactly happened.
//! // You can also just use its `Debug`, `Display` or `Error` traits
//! Error::HttpError(_)
//! |Error::MissingAPIKey
//! |Error::MissingToken(_)
//! |Error::Cancelled
//! |Error::UploadSizeLimitExceeded(_, _)
//! |Error::Failure(_)
//! |Error::BadRequest(_)
//! |Error::FieldClash(_)
//! |Error::JsonDecodeError(_, _) => println!("{}", e),
//! },
//! Ok(res) => println!("Success: {:?}", res),
//! }
//! # }
//! ```
//! ## Handling Errors
//!
//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of
//! the doit() methods, or handed as possibly intermediate results to either the
//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html).
//!
//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
//! makes the system potentially resilient to all kinds of errors.
//!
//! ## Uploads and Downloads
//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be
//! read by you to obtain the media.
//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default.
//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
//! this call: `.param("alt", "media")`.
//!
//! Methods supporting uploads can do so using up to 2 different protocols:
//! *simple* and *resumable*. The distinctiveness of each is represented by customized
//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
//!
//! ## Customization and Callbacks
//!
//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the
//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call.
//! Respective methods will be called to provide progress information, as well as determine whether the system should
//! retry on failure.
//!
//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
//!
//! ## Optional Parts in Server-Requests
//!
//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and
//! [decodable](trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
//! are valid.
//! Most optionals are are considered [Parts](trait.Part.html) which are identifiable by name, which will be sent to
//! the server to indicate either the set parts of the request or the desired parts in the response.
//!
//! ## Builder Arguments
//!
//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods.
//! These will always take a single argument, for which the following statements are true.
//!
//! * [PODs][wiki-pod] are handed by copy
//! * strings are passed as `&str`
//! * [request values](trait.RequestValue.html) are moved
//!
//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
//!
//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
//! [google-go-api]: https://github.com/google/google-api-go-client
//!
//!
// Unused attributes happen thanks to defined, but unused structures
// We don't warn about this, as depending on the API, some data structures or facilities are never used.
// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any
// unused imports in fully featured APIs. Same with unused_mut ... .
#![allow(unused_imports, unused_mut, dead_code)]
// DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.mako'
// DO NOT EDIT !
#[macro_use]
extern crate serde_derive;
extern crate hyper;
extern crate serde;
extern crate serde_json;
extern crate yup_oauth2 as oauth2;
extern crate mime;
extern crate url;
mod cmn;
use std::collections::HashMap;
use std::cell::RefCell;
use std::borrow::BorrowMut;
use std::default::Default;
use std::collections::BTreeMap;
use serde_json as json;
use std::io;
use std::fs;
use std::mem;
use std::thread::sleep;
use std::time::Duration;
pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part,
ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder,
Resource, ErrorResponse, remove_json_null_values};
// ##############
// UTILITIES ###
// ############
// ########
// HUB ###
// ######
/// Central instance to access all Acceleratedmobilepageurl related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_acceleratedmobilepageurl1 as acceleratedmobilepageurl1;
/// use acceleratedmobilepageurl1::BatchGetAmpUrlsRequest;
/// use acceleratedmobilepageurl1::{Result, Error};
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use acceleratedmobilepageurl1::Acceleratedmobilepageurl;
///
/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
/// // `client_secret`, among other things.
/// let secret: ApplicationSecret = Default::default();
/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
/// // unless you replace `None` with the desired Flow.
/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
/// // retrieve them from storage.
/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = Acceleratedmobilepageurl::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = BatchGetAmpUrlsRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.amp_urls().batch_get(req)
/// .doit();
///
/// match result {
/// Err(e) => match e {
/// // The Error enum provides details about what exactly happened.
/// // You can also just use its `Debug`, `Display` or `Error` traits
/// Error::HttpError(_)
/// |Error::MissingAPIKey
/// |Error::MissingToken(_)
/// |Error::Cancelled
/// |Error::UploadSizeLimitExceeded(_, _)
/// |Error::Failure(_)
/// |Error::BadRequest(_)
/// |Error::FieldClash(_)
/// |Error::JsonDecodeError(_, _) => println!("{}", e),
/// },
/// Ok(res) => println!("Success: {:?}", res),
/// }
/// # }
/// ```
pub struct Acceleratedmobilepageurl<C, A> {
client: RefCell<C>,
auth: RefCell<A>,
_user_agent: String,
_base_url: String,
_root_url: String,
}
impl<'a, C, A> Hub for Acceleratedmobilepageurl<C, A> {}
impl<'a, C, A> Acceleratedmobilepageurl<C, A>
where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
pub fn new(client: C, authenticator: A) -> Acceleratedmobilepageurl<C, A> {
Acceleratedmobilepageurl {
client: RefCell::new(client),
auth: RefCell::new(authenticator),
_user_agent: "google-api-rust-client/1.0.7".to_string(),
_base_url: "https://acceleratedmobilepageurl.googleapis.com/".to_string(),
_root_url: "https://acceleratedmobilepageurl.googleapis.com/".to_string(),
}
}
pub fn amp_urls(&'a self) -> AmpUrlMethods<'a, C, A> {
AmpUrlMethods { hub: &self }
}
/// Set the user-agent header field to use in all requests to the server.
/// It defaults to `google-api-rust-client/1.0.7`.
///
/// Returns the previously set user-agent.
pub fn user_agent(&mut self, agent_name: String) -> String {
mem::replace(&mut self._user_agent, agent_name)
}
/// Set the base url to use in all requests to the server.
/// It defaults to `https://acceleratedmobilepageurl.googleapis.com/`.
///
/// Returns the previously set base url.
pub fn base_url(&mut self, new_base_url: String) -> String {
mem::replace(&mut self._base_url, new_base_url)
}
/// Set the root url to use in all requests to the server.
/// It defaults to `https://acceleratedmobilepageurl.googleapis.com/`.
///
/// Returns the previously set root url.
pub fn root_url(&mut self, new_root_url: String) -> String {
mem::replace(&mut self._root_url, new_root_url)
}
}
// ############
// SCHEMAS ###
// ##########
/// Batch AMP URL response.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [batch get amp urls](struct.AmpUrlBatchGetCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct BatchGetAmpUrlsResponse {
/// For each URL in BatchAmpUrlsRequest, the URL response. The response might
/// not be in the same order as URLs in the batch request.
/// If BatchAmpUrlsRequest contains duplicate URLs, AmpUrl is generated
/// only once.
#[serde(rename="ampUrls")]
pub amp_urls: Option<Vec<AmpUrl>>,
/// The errors for requested URLs that have no AMP URL.
#[serde(rename="urlErrors")]
pub url_errors: Option<Vec<AmpUrlError>>,
}
impl ResponseResult for BatchGetAmpUrlsResponse {}
/// AMP URL response for a requested URL.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [batch get amp urls](struct.AmpUrlBatchGetCall.html) (none)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AmpUrl {
/// The AMP URL pointing to the publisher's web server.
#[serde(rename="ampUrl")]
pub amp_url: Option<String>,
/// The [AMP Cache URL](/amp/cache/overview#amp-cache-url-format) pointing to
/// the cached document in the Google AMP Cache.
#[serde(rename="cdnAmpUrl")]
pub cdn_amp_url: Option<String>,
/// The original non-AMP URL.
#[serde(rename="originalUrl")]
pub original_url: Option<String>,
}
impl Resource for AmpUrl {}
/// AMP URL request for a batch of URLs.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [batch get amp urls](struct.AmpUrlBatchGetCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct BatchGetAmpUrlsRequest {
/// The lookup_strategy being requested.
#[serde(rename="lookupStrategy")]
pub lookup_strategy: Option<String>,
/// List of URLs to look up for the paired AMP URLs.
/// The URLs are case-sensitive. Up to 50 URLs per lookup
/// (see [Usage Limits](/amp/cache/reference/limits)).
pub urls: Option<Vec<String>>,
}
impl RequestValue for BatchGetAmpUrlsRequest {}
/// AMP URL Error resource for a requested URL that couldn't be found.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AmpUrlError {
/// The error code of an API call.
#[serde(rename="errorCode")]
pub error_code: Option<String>,
/// An optional descriptive error message.
#[serde(rename="errorMessage")]
pub error_message: Option<String>,
/// The original non-AMP URL.
#[serde(rename="originalUrl")]
pub original_url: Option<String>,
}
impl Part for AmpUrlError {}
// ###################
// MethodBuilders ###
// #################
/// A builder providing access to all methods supported on *ampUrl* resources.
/// It is not used directly, but through the `Acceleratedmobilepageurl` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_acceleratedmobilepageurl1 as acceleratedmobilepageurl1;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use acceleratedmobilepageurl1::Acceleratedmobilepageurl;
///
/// let secret: ApplicationSecret = Default::default();
/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = Acceleratedmobilepageurl::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `batch_get(...)`
/// // to build up your call.
/// let rb = hub.amp_urls();
/// # }
/// ```
pub struct AmpUrlMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Acceleratedmobilepageurl<C, A>,
}
impl<'a, C, A> MethodsBuilder for AmpUrlMethods<'a, C, A> {}
impl<'a, C, A> AmpUrlMethods<'a, C, A> {
/// Create a builder to help you perform the following task:
///
/// Returns AMP URL(s) and equivalent
/// [AMP Cache URL(s)](/amp/cache/overview#amp-cache-url-format).
///
/// # Arguments
///
/// * `request` - No description provided.
pub fn batch_get(&self, request: BatchGetAmpUrlsRequest) -> AmpUrlBatchGetCall<'a, C, A> {
AmpUrlBatchGetCall {
hub: self.hub,
_request: request,
_delegate: Default::default(),
_additional_params: Default::default(),
}
}
}
// ###################
// CallBuilders ###
// #################
/// Returns AMP URL(s) and equivalent
/// [AMP Cache URL(s)](/amp/cache/overview#amp-cache-url-format).
///
/// A builder for the *batchGet* method supported by a *ampUrl* resource.
/// It is not used directly, but through a `AmpUrlMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_acceleratedmobilepageurl1 as acceleratedmobilepageurl1;
/// use acceleratedmobilepageurl1::BatchGetAmpUrlsRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use acceleratedmobilepageurl1::Acceleratedmobilepageurl;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = Acceleratedmobilepageurl::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = BatchGetAmpUrlsRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.amp_urls().batch_get(req)
/// .doit();
/// # }
/// ```
pub struct AmpUrlBatchGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Acceleratedmobilepageurl<C, A>,
_request: BatchGetAmpUrlsRequest,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
}
impl<'a, C, A> CallBuilder for AmpUrlBatchGetCall<'a, C, A> {}
impl<'a, C, A> AmpUrlBatchGetCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, BatchGetAmpUrlsResponse)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "acceleratedmobilepageurl.ampUrls.batchGet",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len()));
for &field in ["alt"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/ampUrls:batchGet";
let mut key = self.hub.auth.borrow_mut().api_key();
if key.is_none() {
key = dlg.api_key();
}
match key {
Some(value) => params.push(("key", value)),
None => {
dlg.finished(false);
return Err(Error::MissingAPIKey)
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(ContentType(json_mime_type.clone()))
.header(ContentLength(request_size as u64))
.body(&mut request_value_reader);
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: BatchGetAmpUrlsRequest) -> AmpUrlBatchGetCall<'a, C, A> {
self._request = new_value;
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> AmpUrlBatchGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *bearer_token* (query-string) - OAuth bearer token.
/// * *pp* (query-boolean) - Pretty-print response.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
/// * *access_token* (query-string) - OAuth access token.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *callback* (query-string) - JSONP
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for response.
/// * *$.xgafv* (query-string) - V1 error format.
pub fn param<T>(mut self, name: T, value: T) -> AmpUrlBatchGetCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
}

View File

@@ -0,0 +1,40 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-adexchangebuyer2_v2_beta1-cli"
version = "1.0.7+20171208"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with AdExchangeBuyerII (protocol v2beta1)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/adexchangebuyer2_v2_beta1-cli"
homepage = "https://developers.google.com/ad-exchange/buyer-rest/reference/rest/"
documentation = "http://byron.github.io/google-apis-rs/google_adexchangebuyer2_v2_beta1_cli"
license = "MIT"
keywords = ["adexchangebuyer2", "google", "cli"]
[[bin]]
name = "adexchangebuyer2-v2-beta1"
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
strsim = "^0.5"
hyper-rustls = "^0.6"
yup-hyper-mock = "^2.0"
clap = "^2.0"
[features]
[dependencies.google-adexchangebuyer2_v2_beta1]
path = "../adexchangebuyer2_v2_beta1"
version = "1.0.7+20171208"

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,161 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/cli/README.md.mako'
DO NOT EDIT !
-->
The `adexchangebuyer2-v2-beta1` command-line interface *(CLI)* allows to use most features of the *Google AdExchangeBuyerII* service from the comfort of your terminal.
By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's
capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero.
If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools.
Everything else about the *AdExchangeBuyerII* API can be found at the
[official documentation site](https://developers.google.com/ad-exchange/buyer-rest/reference/rest/).
# Installation and Source Code
Install the command-line interface with cargo using:
```bash
cargo install google-adexchangebuyer2_v2_beta1-cli
```
Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/adexchangebuyer2_v2_beta1-cli).
# Usage
This documentation was generated from the *AdExchangeBuyerII* API at revision *20171208*. The CLI is at version *1.0.7*.
```bash
adexchangebuyer2-v2-beta1 [options]
accounts
clients-create <account-id> (-r <kv>)... [-p <v>]... [-o <out>]
clients-get <account-id> <client-account-id> [-p <v>]... [-o <out>]
clients-invitations-create <account-id> <client-account-id> (-r <kv>)... [-p <v>]... [-o <out>]
clients-invitations-get <account-id> <client-account-id> <invitation-id> [-p <v>]... [-o <out>]
clients-invitations-list <account-id> <client-account-id> [-p <v>]... [-o <out>]
clients-list <account-id> [-p <v>]... [-o <out>]
clients-update <account-id> <client-account-id> (-r <kv>)... [-p <v>]... [-o <out>]
clients-users-get <account-id> <client-account-id> <user-id> [-p <v>]... [-o <out>]
clients-users-list <account-id> <client-account-id> [-p <v>]... [-o <out>]
clients-users-update <account-id> <client-account-id> <user-id> (-r <kv>)... [-p <v>]... [-o <out>]
creatives-create <account-id> (-r <kv>)... [-p <v>]... [-o <out>]
creatives-deal-associations-add <account-id> <creative-id> (-r <kv>)... [-p <v>]... [-o <out>]
creatives-deal-associations-list <account-id> <creative-id> [-p <v>]... [-o <out>]
creatives-deal-associations-remove <account-id> <creative-id> (-r <kv>)... [-p <v>]... [-o <out>]
creatives-get <account-id> <creative-id> [-p <v>]... [-o <out>]
creatives-list <account-id> [-p <v>]... [-o <out>]
creatives-stop-watching <account-id> <creative-id> (-r <kv>)... [-p <v>]... [-o <out>]
creatives-update <account-id> <creative-id> (-r <kv>)... [-p <v>]... [-o <out>]
creatives-watch <account-id> <creative-id> (-r <kv>)... [-p <v>]... [-o <out>]
bidders
accounts-filter-sets-bid-metrics-list <filter-set-name> [-p <v>]... [-o <out>]
accounts-filter-sets-bid-response-errors-list <filter-set-name> [-p <v>]... [-o <out>]
accounts-filter-sets-bid-responses-without-bids-list <filter-set-name> [-p <v>]... [-o <out>]
accounts-filter-sets-create <owner-name> (-r <kv>)... [-p <v>]... [-o <out>]
accounts-filter-sets-delete <name> [-p <v>]... [-o <out>]
accounts-filter-sets-filtered-bid-requests-list <filter-set-name> [-p <v>]... [-o <out>]
accounts-filter-sets-filtered-bids-creatives-list <filter-set-name> <creative-status-id> [-p <v>]... [-o <out>]
accounts-filter-sets-filtered-bids-details-list <filter-set-name> <creative-status-id> [-p <v>]... [-o <out>]
accounts-filter-sets-filtered-bids-list <filter-set-name> [-p <v>]... [-o <out>]
accounts-filter-sets-get <name> [-p <v>]... [-o <out>]
accounts-filter-sets-impression-metrics-list <filter-set-name> [-p <v>]... [-o <out>]
accounts-filter-sets-list <owner-name> [-p <v>]... [-o <out>]
accounts-filter-sets-losing-bids-list <filter-set-name> [-p <v>]... [-o <out>]
accounts-filter-sets-non-billable-winning-bids-list <filter-set-name> [-p <v>]... [-o <out>]
filter-sets-bid-metrics-list <filter-set-name> [-p <v>]... [-o <out>]
filter-sets-bid-response-errors-list <filter-set-name> [-p <v>]... [-o <out>]
filter-sets-bid-responses-without-bids-list <filter-set-name> [-p <v>]... [-o <out>]
filter-sets-create <owner-name> (-r <kv>)... [-p <v>]... [-o <out>]
filter-sets-delete <name> [-p <v>]... [-o <out>]
filter-sets-filtered-bid-requests-list <filter-set-name> [-p <v>]... [-o <out>]
filter-sets-filtered-bids-creatives-list <filter-set-name> <creative-status-id> [-p <v>]... [-o <out>]
filter-sets-filtered-bids-details-list <filter-set-name> <creative-status-id> [-p <v>]... [-o <out>]
filter-sets-filtered-bids-list <filter-set-name> [-p <v>]... [-o <out>]
filter-sets-get <name> [-p <v>]... [-o <out>]
filter-sets-impression-metrics-list <filter-set-name> [-p <v>]... [-o <out>]
filter-sets-list <owner-name> [-p <v>]... [-o <out>]
filter-sets-losing-bids-list <filter-set-name> [-p <v>]... [-o <out>]
filter-sets-non-billable-winning-bids-list <filter-set-name> [-p <v>]... [-o <out>]
adexchangebuyer2-v2-beta1 --help
Configuration:
[--scope <url>]...
Specify the authentication a method should be executed in. Each scope
requires the user to grant this application permission to use it.
If unset, it defaults to the shortest scope url for a particular method.
--config-dir <folder>
A directory into which we will store our persistent data. Defaults to
a user-writable directory that we will create during the first invocation.
[default: ~/.google-service-cli]
--debug
Output all server communication to standard error. `tx` and `rx` are placed
into the same stream.
--debug-auth
Output all communication related to authentication to standard error. `tx`
and `rx` are placed into the same stream.
```
# Configuration
The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `adexchangebuyer2-v2-beta1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis.
More information about the various kinds of persistent data are given in the following paragraphs.
# Authentication
Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the
set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*.
If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a
method that is read-only, it will ask only for a read-only scope.
You may use the `--scope` flag to specify a scope directly.
All applicable scopes are documented in the respective method's CLI documentation.
The first time a scope is used, the user is asked for permission. Follow the instructions given
by the CLI to grant permissions, or to decline.
If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration
directory, e.g. `~/.google-service-cli/adexchangebuyer2-v2-beta1-token-<scope-hash>.json`. No manual management of these tokens
is necessary.
To revoke granted authentication, please refer to the [official documentation][revoke-access].
# Application Secrets
In order to allow any application to use Google services, it will need to be registered using the
[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it
one by one. Most APIs can be used for free and have a daily quota.
To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI
comes with a default application secret that is configured accordingly. This also means that heavy usage
all around the world may deplete the daily quota.
You can workaround this limitation by putting your own secrets file at this location:
`~/.google-service-cli/adexchangebuyer2-v2-beta1-secret.json`, assuming that the required *adexchangebuyer2* API
was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at
*APIs & auth -> Credentials -> Download JSON* and used as is.
Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new].
# Debugging
Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know
what exactly led to a particular issue. This is done by allowing all client-server communication to be
output to standard error *as-is*.
The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag
will cause all communication related to authentication to standard error.
If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the
issue at hand.
You may consider redirecting standard error into a file for ease of use, e.g. `adexchangebuyer2-v2-beta1 --debug <resource> <method> [options] 2>debug.txt`.
[scopes]: https://developers.google.com/+/api/oauth#scopes
[revoke-access]: http://webapps.stackexchange.com/a/30849
[google-dev-console]: https://console.developers.google.com/
[google-project-new]: https://developers.google.com/console/help/new/

View File

@@ -0,0 +1,63 @@
site_name: AdExchangeBuyerII v1.0.7+20171208
site_url: http://byron.github.io/google-apis-rs/google-adexchangebuyer2_v2_beta1-cli
site_description: A complete library to interact with AdExchangeBuyerII (protocol v2beta1)
repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/adexchangebuyer2_v2_beta1-cli
docs_dir: docs
site_dir: build_html
pages:
- ['index.md', 'Home']
- ['accounts_clients-create.md', 'Accounts', 'Clients Create']
- ['accounts_clients-get.md', 'Accounts', 'Clients Get']
- ['accounts_clients-invitations-create.md', 'Accounts', 'Clients Invitations Create']
- ['accounts_clients-invitations-get.md', 'Accounts', 'Clients Invitations Get']
- ['accounts_clients-invitations-list.md', 'Accounts', 'Clients Invitations List']
- ['accounts_clients-list.md', 'Accounts', 'Clients List']
- ['accounts_clients-update.md', 'Accounts', 'Clients Update']
- ['accounts_clients-users-get.md', 'Accounts', 'Clients Users Get']
- ['accounts_clients-users-list.md', 'Accounts', 'Clients Users List']
- ['accounts_clients-users-update.md', 'Accounts', 'Clients Users Update']
- ['accounts_creatives-create.md', 'Accounts', 'Creatives Create']
- ['accounts_creatives-deal-associations-add.md', 'Accounts', 'Creatives Deal Associations Add']
- ['accounts_creatives-deal-associations-list.md', 'Accounts', 'Creatives Deal Associations List']
- ['accounts_creatives-deal-associations-remove.md', 'Accounts', 'Creatives Deal Associations Remove']
- ['accounts_creatives-get.md', 'Accounts', 'Creatives Get']
- ['accounts_creatives-list.md', 'Accounts', 'Creatives List']
- ['accounts_creatives-stop-watching.md', 'Accounts', 'Creatives Stop Watching']
- ['accounts_creatives-update.md', 'Accounts', 'Creatives Update']
- ['accounts_creatives-watch.md', 'Accounts', 'Creatives Watch']
- ['bidders_accounts-filter-sets-bid-metrics-list.md', 'Bidders', 'Accounts Filter Sets Bid Metrics List']
- ['bidders_accounts-filter-sets-bid-response-errors-list.md', 'Bidders', 'Accounts Filter Sets Bid Response Errors List']
- ['bidders_accounts-filter-sets-bid-responses-without-bids-list.md', 'Bidders', 'Accounts Filter Sets Bid Responses Without Bids List']
- ['bidders_accounts-filter-sets-create.md', 'Bidders', 'Accounts Filter Sets Create']
- ['bidders_accounts-filter-sets-delete.md', 'Bidders', 'Accounts Filter Sets Delete']
- ['bidders_accounts-filter-sets-filtered-bid-requests-list.md', 'Bidders', 'Accounts Filter Sets Filtered Bid Requests List']
- ['bidders_accounts-filter-sets-filtered-bids-creatives-list.md', 'Bidders', 'Accounts Filter Sets Filtered Bids Creatives List']
- ['bidders_accounts-filter-sets-filtered-bids-details-list.md', 'Bidders', 'Accounts Filter Sets Filtered Bids Details List']
- ['bidders_accounts-filter-sets-filtered-bids-list.md', 'Bidders', 'Accounts Filter Sets Filtered Bids List']
- ['bidders_accounts-filter-sets-get.md', 'Bidders', 'Accounts Filter Sets Get']
- ['bidders_accounts-filter-sets-impression-metrics-list.md', 'Bidders', 'Accounts Filter Sets Impression Metrics List']
- ['bidders_accounts-filter-sets-list.md', 'Bidders', 'Accounts Filter Sets List']
- ['bidders_accounts-filter-sets-losing-bids-list.md', 'Bidders', 'Accounts Filter Sets Losing Bids List']
- ['bidders_accounts-filter-sets-non-billable-winning-bids-list.md', 'Bidders', 'Accounts Filter Sets Non Billable Winning Bids List']
- ['bidders_filter-sets-bid-metrics-list.md', 'Bidders', 'Filter Sets Bid Metrics List']
- ['bidders_filter-sets-bid-response-errors-list.md', 'Bidders', 'Filter Sets Bid Response Errors List']
- ['bidders_filter-sets-bid-responses-without-bids-list.md', 'Bidders', 'Filter Sets Bid Responses Without Bids List']
- ['bidders_filter-sets-create.md', 'Bidders', 'Filter Sets Create']
- ['bidders_filter-sets-delete.md', 'Bidders', 'Filter Sets Delete']
- ['bidders_filter-sets-filtered-bid-requests-list.md', 'Bidders', 'Filter Sets Filtered Bid Requests List']
- ['bidders_filter-sets-filtered-bids-creatives-list.md', 'Bidders', 'Filter Sets Filtered Bids Creatives List']
- ['bidders_filter-sets-filtered-bids-details-list.md', 'Bidders', 'Filter Sets Filtered Bids Details List']
- ['bidders_filter-sets-filtered-bids-list.md', 'Bidders', 'Filter Sets Filtered Bids List']
- ['bidders_filter-sets-get.md', 'Bidders', 'Filter Sets Get']
- ['bidders_filter-sets-impression-metrics-list.md', 'Bidders', 'Filter Sets Impression Metrics List']
- ['bidders_filter-sets-list.md', 'Bidders', 'Filter Sets List']
- ['bidders_filter-sets-losing-bids-list.md', 'Bidders', 'Filter Sets Losing Bids List']
- ['bidders_filter-sets-non-billable-winning-bids-list.md', 'Bidders', 'Filter Sets Non Billable Winning Bids List']
theme: readthedocs
copyright: Copyright &copy; 2015-2016, `Sebastian Thiel`

View File

@@ -0,0 +1,799 @@
// COPY OF 'src/rust/cli/cmn.rs'
// DO NOT EDIT
use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token};
use serde_json as json;
use serde_json::value::Value;
use mime::Mime;
use clap::{App, SubCommand};
use strsim;
use std::fs;
use std::env;
use std::io;
use std::error::Error as StdError;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
use std::io::{Write, Read, stdout};
use std::default::Default;
const FIELD_SEP: char = '.';
pub enum ComplexType {
Pod,
Vec,
Map,
}
// Null,
// Bool(bool),
// I64(i64),
// U64(u64),
// F64(f64),
// String(String),
pub enum JsonType {
Boolean,
Int,
Uint,
Float,
String,
}
pub struct JsonTypeInfo {
pub jtype: JsonType,
pub ctype: ComplexType,
}
// Based on @erickt user comment. Thanks for the idea !
// Remove all keys whose values are null from given value (changed in place)
pub fn remove_json_null_values(value: &mut Value) {
match *value {
Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}
fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> {
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values {
let confidence = strsim::jaro_winkler(v, pv);
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
}
pub enum CallType {
Upload(UploadProtocol),
Standard,
}
arg_enum!{
pub enum UploadProtocol {
Simple,
Resumable
}
}
impl AsRef<str> for UploadProtocol {
fn as_ref(&self) -> &str {
match *self {
UploadProtocol::Simple => "simple",
UploadProtocol::Resumable => "resumable",
}
}
}
impl AsRef<str> for CallType {
fn as_ref(&self) -> &str {
match *self {
CallType::Upload(ref proto) => proto.as_ref(),
CallType::Standard => "standard-request",
}
}
}
#[derive(Clone, Default)]
pub struct FieldCursor(Vec<String>);
impl ToString for FieldCursor {
fn to_string(&self) -> String {
self.0.join(".")
}
}
impl From<&'static str> for FieldCursor {
fn from(value: &'static str) -> FieldCursor {
let mut res = FieldCursor::default();
res.set(value).unwrap();
res
}
}
fn assure_entry<'a, 'b>(m: &'a mut json::Map<String, Value>, k: &'b String) -> &'a mut Value {
if m.contains_key(k) {
return m.get_mut(k).expect("value to exist");
}
m.insert(k.to_owned(), Value::Object(Default::default()));
m.get_mut(k).expect("value to exist")
}
impl FieldCursor {
pub fn set(&mut self, value: &str) -> Result<(), CLIError> {
if value.len() == 0 {
return Err(CLIError::Field(FieldError::Empty));
}
let mut first_is_field_sep = false;
let mut char_count: usize = 0;
let mut last_c = FIELD_SEP;
let mut num_conscutive_field_seps = 0;
let mut field = String::new();
let mut fields = self.0.clone();
let push_field = |fs: &mut Vec<String>, f: &mut String| {
if f.len() > 0 {
fs.push(f.clone());
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
char_count += 1;
if c == FIELD_SEP {
if cid == 0 {
first_is_field_sep = true;
}
num_conscutive_field_seps += 1;
if cid > 0 && last_c == FIELD_SEP {
if fields.pop().is_none() {
return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string())));
}
} else {
push_field(&mut fields, &mut field);
}
} else {
num_conscutive_field_seps = 0;
if cid == 1 {
if first_is_field_sep {
fields.truncate(0);
}
}
field.push(c);
}
last_c = c;
}
push_field(&mut fields, &mut field);
if char_count == 1 && first_is_field_sep {
fields.truncate(0);
}
if char_count > 1 && num_conscutive_field_seps == 1 {
return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string())));
}
self.0 = fields;
Ok(())
}
pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option<String> {
if value.len() == 0 {
return None;
}
let mut last_c = FIELD_SEP;
let mut field = String::new();
let mut output = String::new();
let push_field = |fs: &mut String, f: &mut String| {
if f.len() > 0 {
fs.push_str(match did_you_mean(&f, possible_values) {
Some(candidate) => candidate,
None => &f,
});
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
if c == FIELD_SEP {
if last_c != FIELD_SEP {
push_field(&mut output, &mut field);
}
output.push(c);
} else {
field.push(c);
}
last_c = c;
}
push_field(&mut output, &mut field);
if &output == value {
None
} else {
Some(output)
}
}
pub fn set_json_value(&self,
mut object: &mut Value,
value: &str,
type_info: JsonTypeInfo,
err: &mut InvalidOptionsError,
orig_cursor: &FieldCursor) {
assert!(self.0.len() > 0);
for field in &self.0[..self.0.len() - 1] {
let tmp = object;
object = match *tmp {
Value::Object(ref mut mapping) => {
assure_entry(mapping, &field)
}
_ => panic!("We don't expect non-object Values here ..."),
};
}
match *object {
Value::Object(ref mut mapping) => {
let field = &self.0[self.0.len() - 1];
let to_jval = |value: &str,
jtype: JsonType,
err: &mut InvalidOptionsError|
-> Value {
match jtype {
JsonType::Boolean =>
Value::Bool(arg_from_str(value, err, &field, "boolean")),
JsonType::Int =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"int"))
.expect("valid f64")),
JsonType::Uint =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"uint"))
.expect("valid f64")),
JsonType::Float =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"float"))
.expect("valid f64")),
JsonType::String => Value::String(value.to_owned()),
}
};
match type_info.ctype {
ComplexType::Pod => {
if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err))
.is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
ComplexType::Vec => {
match *assure_entry(mapping, field) {
Value::Array(ref mut values) =>
values.push(to_jval(value, type_info.jtype, err)),
_ => unreachable!(),
}
}
ComplexType::Map => {
let (key, value) = parse_kv_arg(value, err, true);
let jval = to_jval(value.unwrap_or(""), type_info.jtype, err);
match *assure_entry(mapping, &field) {
Value::Object(ref mut value_map) => {
if value_map.insert(key.to_owned(), jval).is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
_ => unreachable!(),
}
}
}
}
_ => unreachable!(),
}
}
pub fn num_fields(&self) -> usize {
self.0.len()
}
}
pub fn parse_kv_arg<'a>(kv: &'a str,
err: &mut InvalidOptionsError,
for_hashmap: bool)
-> (&'a str, Option<&'a str>) {
let mut add_err = || {
err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(), for_hashmap))
};
match kv.find('=') {
None => {
add_err();
return (kv, None);
}
Some(pos) => {
let key = &kv[..pos];
if kv.len() <= pos + 1 {
add_err();
return (key, Some(""));
}
(key, Some(&kv[pos + 1..]))
}
}
}
pub fn calltype_from_str(name: &str,
valid_protocols: Vec<String>,
err: &mut InvalidOptionsError)
-> CallType {
CallType::Upload(match UploadProtocol::from_str(name) {
Ok(up) => up,
Err(msg) => {
err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols));
UploadProtocol::Simple
}
})
}
pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option<fs::File> {
match fs::File::open(file_path) {
Ok(f) => Some(f),
Err(io_err) => {
err.issues.push(CLIError::Input(InputError::Io((file_path.to_string(), io_err))));
None
}
}
}
pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option<Mime> {
match mime.parse() {
Ok(m) => Some(m),
Err(_) => {
err.issues.push(CLIError::Input(InputError::Mime(mime.to_string())));
None
}
}
}
pub fn writer_from_opts(arg: Option<&str>) -> Result<Box<Write>, io::Error> {
let f = arg.unwrap_or("-");
match f {
"-" => Ok(Box::new(stdout())),
_ => match fs::OpenOptions::new().create(true).write(true).open(f) {
Ok(f) => Ok(Box::new(f)),
Err(io_err) => Err(io_err),
},
}
}
pub fn arg_from_str<'a, T>(arg: &str,
err: &mut InvalidOptionsError,
arg_name: &'a str,
arg_type: &'a str)
-> T
where T: FromStr + Default,
<T as FromStr>::Err: fmt::Display
{
match FromStr::from_str(arg) {
Err(perr) => {
err.issues.push(CLIError::ParseError(arg_name.to_owned(),
arg_type.to_owned(),
arg.to_string(),
format!("{}", perr)));
Default::default()
}
Ok(v) => v,
}
}
pub struct JsonTokenStorage {
pub program_name: &'static str,
pub db_dir: String,
}
impl JsonTokenStorage {
fn path(&self, scope_hash: u64) -> PathBuf {
Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash))
}
}
#[derive(Debug)]
pub enum TokenStorageError {
Json(json::Error),
Io(io::Error),
}
impl fmt::Display for TokenStorageError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
TokenStorageError::Json(ref err) => writeln!(f, "Could not serialize secrets: {}", err),
TokenStorageError::Io(ref err) => writeln!(f, "Failed to write secret token: {}", err),
}
}
}
impl StdError for TokenStorageError {
fn description(&self) -> &str {
"Failure when getting or setting the token storage"
}
}
impl TokenStorage for JsonTokenStorage {
type Error = TokenStorageError;
// NOTE: logging might be interesting, currently we swallow all errors
fn set(&mut self,
scope_hash: u64,
_: &Vec<&str>,
token: Option<Token>)
-> Result<(), TokenStorageError> {
match token {
None => {
match fs::remove_file(self.path(scope_hash)) {
Err(err) => match err.kind() {
io::ErrorKind::NotFound => Ok(()),
_ => Err(TokenStorageError::Io(err)),
},
Ok(_) => Ok(()),
}
}
Some(token) => {
match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) {
Ok(mut f) => {
match json::to_writer_pretty(&mut f, &token) {
Ok(_) => Ok(()),
Err(serde_err) => Err(TokenStorageError::Json(serde_err)),
}
}
Err(io_err) => Err(TokenStorageError::Io(io_err)),
}
}
}
}
fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result<Option<Token>, TokenStorageError> {
match fs::File::open(&self.path(scope_hash)) {
Ok(f) => {
match json::de::from_reader(f) {
Ok(token) => Ok(Some(token)),
Err(err) => Err(TokenStorageError::Json(err)),
}
}
Err(io_err) => {
match io_err.kind() {
io::ErrorKind::NotFound => Ok(None),
_ => Err(TokenStorageError::Io(io_err)),
}
}
}
}
}
#[derive(Debug)]
pub enum ApplicationSecretError {
DecoderError((String, json::Error)),
FormatError(String),
}
impl fmt::Display for ApplicationSecretError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ApplicationSecretError::DecoderError((ref path, ref err)) =>
writeln!(f,
"Could not decode file at '{}' with error: {}.",
path,
err),
ApplicationSecretError::FormatError(ref path) =>
writeln!(f,
"'installed' field is unset in secret file at '{}'.",
path),
}
}
}
#[derive(Debug)]
pub enum ConfigurationError {
DirectoryCreationFailed((String, io::Error)),
DirectoryUnset,
HomeExpansionFailed(String),
Secret(ApplicationSecretError),
Io((String, io::Error)),
}
impl fmt::Display for ConfigurationError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) =>
writeln!(f,
"Directory '{}' could not be created with error: {}.",
dir,
err),
ConfigurationError::DirectoryUnset => writeln!(f, "--config-dir was unset or empty."),
ConfigurationError::HomeExpansionFailed(ref dir) =>
writeln!(f,
"Couldn't find HOME directory of current user, failed to expand '{}'.",
dir),
ConfigurationError::Secret(ref err) => writeln!(f, "Secret -> {}", err),
ConfigurationError::Io((ref path, ref err)) =>
writeln!(f,
"IO operation failed on path '{}' with error: {}.",
path,
err),
}
}
}
#[derive(Debug)]
pub enum InputError {
Io((String, io::Error)),
Mime(String),
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
InputError::Io((ref file_path, ref io_err)) =>
writeln!(f,
"Failed to open '{}' for reading with error: {}.",
file_path,
io_err),
InputError::Mime(ref mime) => writeln!(f, "'{}' is not a known mime-type.", mime),
}
}
}
#[derive(Debug)]
pub enum FieldError {
PopOnEmpty(String),
TrailingFieldSep(String),
Unknown(String, Option<String>, Option<String>),
Duplicate(String),
Empty,
}
impl fmt::Display for FieldError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
FieldError::PopOnEmpty(ref field) =>
writeln!(f, "'{}': Cannot move up on empty field cursor.", field),
FieldError::TrailingFieldSep(ref field) =>
writeln!(f,
"'{}': Single field separator may not be last character.",
field),
FieldError::Unknown(ref field, ref suggestion, ref value) => {
let suffix = match *suggestion {
Some(ref s) => {
let kv = match *value {
Some(ref v) => format!("{}={}", s, v),
None => s.clone(),
};
format!(" Did you mean '{}' ?", kv)
}
None => String::new(),
};
writeln!(f, "Field '{}' does not exist.{}", field, suffix)
}
FieldError::Duplicate(ref cursor) =>
writeln!(f, "Value at '{}' was already set", cursor),
FieldError::Empty => writeln!(f, "Field names must not be empty."),
}
}
}
#[derive(Debug)]
pub enum CLIError {
Configuration(ConfigurationError),
ParseError(String, String, String, String),
UnknownParameter(String, Vec<&'static str>),
InvalidUploadProtocol(String, Vec<String>),
InvalidKeyValueSyntax(String, bool),
Input(InputError),
Field(FieldError),
MissingCommandError,
MissingMethodError(String),
}
impl fmt::Display for CLIError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err),
CLIError::Input(ref err) => write!(f, "Input -> {}", err),
CLIError::Field(ref err) => write!(f, "Field -> {}", err),
CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) =>
writeln!(f,
"'{}' is not a valid upload protocol. Choose from one of {}.",
proto_name,
valid_names.join(", ")),
CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) =>
writeln!(f,
"Failed to parse argument '{}' with value '{}' as {} with error: {}.",
arg_name,
value,
type_name,
err_desc),
CLIError::UnknownParameter(ref param_name, ref possible_values) => {
let suffix = match did_you_mean(param_name, &possible_values) {
Some(v) => format!(" Did you mean '{}' ?", v),
None => String::new(),
};
write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix)
}
CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => {
let hashmap_info = if is_hashmap {
"hashmap "
} else {
""
};
writeln!(f,
"'{}' does not match {}pattern <key>=<value>.",
kv,
hashmap_info)
}
CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."),
CLIError::MissingMethodError(ref cmd) =>
writeln!(f,
"Please specify the method to call on the '{}' command.",
cmd),
}
}
}
#[derive(Debug)]
pub struct InvalidOptionsError {
pub issues: Vec<CLIError>,
pub exit_code: i32,
}
impl fmt::Display for InvalidOptionsError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for issue in &self.issues {
try!(issue.fmt(f));
}
Ok(())
}
}
impl InvalidOptionsError {
pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError {
InvalidOptionsError {
issues: vec![err],
exit_code: exit_code,
}
}
pub fn new() -> InvalidOptionsError {
InvalidOptionsError {
issues: Vec::new(),
exit_code: 1,
}
}
}
pub fn assure_config_dir_exists(dir: &str) -> Result<String, CLIError> {
let trdir = dir.trim();
if trdir.len() == 0 {
return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset));
}
let expanded_config_dir = if trdir.as_bytes()[0] == b'~' {
match env::var("HOME").ok().or(env::var("UserProfile").ok()) {
None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))),
Some(mut user) => {
user.push_str(&trdir[1..]);
user
}
}
} else {
trdir.to_string()
};
if let Err(err) = fs::create_dir(&expanded_config_dir) {
if err.kind() != io::ErrorKind::AlreadyExists {
return Err(CLIError::Configuration(
ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err))));
}
}
Ok(expanded_config_dir)
}
pub fn application_secret_from_directory(dir: &str,
secret_basename: &str,
json_console_secret: &str)
-> Result<ApplicationSecret, CLIError> {
let secret_path = Path::new(dir).join(secret_basename);
let secret_str = || secret_path.as_path().to_str().unwrap().to_string();
let secret_io_error = |io_err: io::Error| {
Err(CLIError::Configuration(ConfigurationError::Io((secret_str(), io_err))))
};
for _ in 0..2 {
match fs::File::open(&secret_path) {
Err(mut err) => {
if err.kind() == io::ErrorKind::NotFound {
// Write our built-in one - user may adjust the written file at will
err = match fs::OpenOptions::new()
.create(true)
.write(true)
.open(&secret_path) {
Err(cfe) => cfe,
Ok(mut f) => {
// Assure we convert 'ugly' json string into pretty one
let console_secret: ConsoleApplicationSecret =
json::from_str(json_console_secret).unwrap();
match json::to_writer_pretty(&mut f, &console_secret) {
Err(serde_err) =>
panic!("Unexpected serde error: {:#?}", serde_err),
Ok(_) => continue,
}
}
};
// fall through to IO error handling
}
return secret_io_error(err);
}
Ok(f) => {
match json::de::from_reader::<_, ConsoleApplicationSecret>(f) {
Err(json_err) =>
return Err(CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::DecoderError(
(secret_str(), json_err)
)))),
Ok(console_secret) => match console_secret.installed {
Some(secret) => return Ok(secret),
None => return Err(
CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::FormatError(secret_str())
))),
},
}
}
}
}
unreachable!();
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,31 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-adexchangebuyer2_v2_beta1"
version = "1.0.7+20171208"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with AdExchangeBuyerII (protocol v2beta1)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/adexchangebuyer2_v2_beta1"
homepage = "https://developers.google.com/ad-exchange/buyer-rest/reference/rest/"
documentation = "https://docs.rs/google-adexchangebuyer2_v2_beta1/1.0.7+20171208"
license = "MIT"
keywords = ["adexchangebuyer2", "google", "protocol", "web", "api"]
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
url = "= 0.5"
[features]

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,753 @@
// COPY OF 'src/rust/api/cmn.rs'
// DO NOT EDIT
use std::io::{self, Read, Seek, Cursor, Write, SeekFrom};
use std;
use std::fmt::{self, Display};
use std::str::FromStr;
use std::error;
use std::thread::sleep;
use std::time::Duration;
use mime::{Mime, TopLevel, SubLevel, Attr, Value};
use oauth2::{TokenType, Retry, self};
use hyper;
use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header,
HeaderFormat, Bearer};
use hyper::http::h1::LINE_ENDING;
use hyper::method::Method;
use hyper::status::StatusCode;
use serde_json as json;
/// Identifies the Hub. There is only one per library, this trait is supposed
/// to make intended use more explicit.
/// The hub allows to access all resource methods more easily.
pub trait Hub {}
/// Identifies types for building methods of a particular resource type
pub trait MethodsBuilder {}
/// Identifies types which represent builders for a particular resource method
pub trait CallBuilder {}
/// Identifies types which can be inserted and deleted.
/// Types with this trait are most commonly used by clients of this API.
pub trait Resource {}
/// Identifies types which are used in API responses.
pub trait ResponseResult {}
/// Identifies types which are used in API requests.
pub trait RequestValue {}
/// Identifies types which are not actually used by the API
/// This might be a bug within the google API schema.
pub trait UnusedType {}
/// Identifies types which are only used as part of other types, which
/// usually are carrying the `Resource` trait.
pub trait Part {}
/// Identifies types which are only used by other types internally.
/// They have no special meaning, this trait just marks them for completeness.
pub trait NestedType {}
/// A utility to specify reader types which provide seeking capabilities too
pub trait ReadSeek: Seek + Read {}
impl<T: Seek + Read> ReadSeek for T {}
/// A trait for all types that can convert themselves into a *parts* string
pub trait ToParts {
fn to_parts(&self) -> String;
}
/// A utility type which can decode a server response that indicates error
#[derive(Deserialize)]
pub struct JsonServerError {
pub error: String,
pub error_description: Option<String>
}
/// A utility to represent detailed errors we might see in case there are BadRequests.
/// The latter happen if the sent parameters or request structures are unsound
#[derive(Deserialize, Serialize, Debug)]
pub struct ErrorResponse {
error: ServerError,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerError {
errors: Vec<ServerMessage>,
code: u16,
message: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerMessage {
domain: String,
reason: String,
message: String,
#[serde(rename="locationType")]
location_type: Option<String>,
location: Option<String>
}
#[derive(Copy, Clone)]
pub struct DummyNetworkStream;
impl Read for DummyNetworkStream {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl Write for DummyNetworkStream {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl hyper::net::NetworkStream for DummyNetworkStream {
fn peer_addr(&mut self) -> io::Result<std::net::SocketAddr> {
Ok("127.0.0.1:1337".parse().unwrap())
}
fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
}
/// A trait specifying functionality to help controlling any request performed by the API.
/// The trait has a conservative default implementation.
///
/// It contains methods to deal with all common issues, as well with the ones related to
/// uploading media
pub trait Delegate {
/// Called at the beginning of any API request. The delegate should store the method
/// information if he is interesting in knowing more context when further calls to it
/// are made.
/// The matching `finished()` call will always be made, no matter whether or not the API
/// request was successful. That way, the delegate may easily maintain a clean state
/// between various API calls.
fn begin(&mut self, MethodInfo) {}
/// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
///
/// Return retry information.
fn http_error(&mut self, &hyper::Error) -> Retry {
Retry::Abort
}
/// Called whenever there is the need for your applications API key after
/// the official authenticator implementation didn't provide one, for some reason.
/// If this method returns None as well, the underlying operation will fail
fn api_key(&mut self) -> Option<String> {
None
}
/// Called whenever the Authenticator didn't yield a token. The delegate
/// may attempt to provide one, or just take it as a general information about the
/// impending failure.
/// The given Error provides information about why the token couldn't be acquired in the
/// first place
fn token(&mut self, err: &error::Error) -> Option<oauth2::Token> {
let _ = err;
None
}
/// Called during resumable uploads to provide a URL for the impending upload.
/// It was saved after a previous call to `store_upload_url(...)`, and if not None,
/// will be used instead of asking the server for a new upload URL.
/// This is useful in case a previous resumable upload was aborted/canceled, but should now
/// be resumed.
/// The returned URL will be used exactly once - if it fails again and the delegate allows
/// to retry, we will ask the server for a new upload URL.
fn upload_url(&mut self) -> Option<String> {
None
}
/// Called after we have retrieved a new upload URL for a resumable upload to store it
/// in case we fail or cancel. That way, we can attempt to resume the upload later,
/// see `upload_url()`.
/// It will also be called with None after a successful upload, which allows the delegate
/// to forget the URL. That way, we will not attempt to resume an upload that has already
/// finished.
fn store_upload_url(&mut self, url: Option<&str>) {
let _ = url;
}
/// Called whenever a server response could not be decoded from json.
/// It's for informational purposes only, the caller will return with an error
/// accordingly.
///
/// # Arguments
///
/// * `json_encoded_value` - The json-encoded value which failed to decode.
/// * `json_decode_error` - The decoder error
fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &json::Error) {
let _ = json_encoded_value;
let _ = json_decode_error;
}
/// Called whenever the http request returns with a non-success status code.
/// This can involve authentication issues, or anything else that very much
/// depends on the used API method.
/// The delegate should check the status, header and decoded json error to decide
/// whether to retry or not. In the latter case, the underlying call will fail.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
fn http_failure(&mut self, _: &hyper::client::Response, Option<JsonServerError>, _: Option<ServerError>) -> Retry {
Retry::Abort
}
/// Called prior to sending the main request of the given method. It can be used to time
/// the call or to print progress information.
/// It's also useful as you can be sure that a request will definitely be made.
fn pre_request(&mut self) { }
/// Return the size of each chunk of a resumable upload.
/// Must be a power of two, with 1<<18 being the smallest allowed chunk size.
/// Will be called once before starting any resumable upload.
fn chunk_size(&mut self) -> u64 {
1 << 23
}
/// Called before the given chunk is uploaded to the server.
/// If true is returned, the upload will be interrupted.
/// However, it may be resumable if you stored the upload URL in a previous call
/// to `store_upload_url()`
fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool {
let _ = chunk;
false
}
/// Called before the API request method returns, in every case. It can be used to clean up
/// internal state between calls to the API.
/// This call always has a matching call to `begin(...)`.
///
/// # Arguments
///
/// * `is_success` - a true value indicates the operation was successful. If false, you should
/// discard all values stored during `store_upload_url`.
fn finished(&mut self, is_success: bool) {
let _ = is_success;
}
}
/// A delegate with a conservative default implementation, which is used if no other delegate is
/// set.
#[derive(Default)]
pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}
#[derive(Debug)]
pub enum Error {
/// The http connection failed
HttpError(hyper::Error),
/// An attempt was made to upload a resource with size stored in field `.0`
/// even though the maximum upload size is what is stored in field `.1`.
UploadSizeLimitExceeded(u64, u64),
/// Represents information about a request that was not understood by the server.
/// Details are included.
BadRequest(ErrorResponse),
/// We needed an API key for authentication, but didn't obtain one.
/// Neither through the authenticator, nor through the Delegate.
MissingAPIKey,
/// We required a Token, but didn't get one from the Authenticator
MissingToken(Box<error::Error>),
/// The delgate instructed to cancel the operation
Cancelled,
/// An additional, free form field clashed with one of the built-in optional ones
FieldClash(&'static str),
/// Shows that we failed to decode the server response.
/// This can happen if the protocol changes in conjunction with strict json decoding.
JsonDecodeError(String, json::Error),
/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref err) => err.fmt(f),
Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) =>
writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}"
, resource_size, max_size),
Error::MissingAPIKey => {
(writeln!(f, "The application's API key was not found in the configuration")).ok();
writeln!(f, "It is used as there are no Scopes defined for this method.")
},
Error::BadRequest(ref err) => {
try!(writeln!(f, "Bad Request ({}): {}", err.error.code, err.error.message));
for err in err.error.errors.iter() {
try!(writeln!(f, " {}: {}, {}{}",
err.domain,
err.message,
err.reason,
match &err.location {
&Some(ref loc) => format!("@{}", loc),
&None => String::new(),
}));
}
Ok(())
},
Error::MissingToken(ref err) =>
writeln!(f, "Token retrieval failed with error: {}", err),
Error::Cancelled =>
writeln!(f, "Operation cancelled by delegate"),
Error::FieldClash(field) =>
writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field),
Error::JsonDecodeError(ref json_str, ref err)
=> writeln!(f, "{}: {}", err, json_str),
Error::Failure(ref response) =>
writeln!(f, "Http status indicates failure: {:?}", response),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::HttpError(ref err) => err.description(),
Error::JsonDecodeError(_, ref err) => err.description(),
_ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead"
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::HttpError(ref err) => err.cause(),
Error::JsonDecodeError(_, ref err) => err.cause(),
_ => None
}
}
}
/// A universal result type used as return for all calls.
pub type Result<T> = std::result::Result<T, Error>;
/// Contains information about an API request.
pub struct MethodInfo {
pub id: &'static str,
pub http_method: Method,
}
const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d";
/// Provides a `Read` interface that converts multiple parts into the protocol
/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387).
/// **Note**: This implementation is just as rich as it needs to be to perform uploads
/// to google APIs, and might not be a fully-featured implementation.
#[derive(Default)]
pub struct MultiPartReader<'a> {
raw_parts: Vec<(Headers, &'a mut Read)>,
current_part: Option<(Cursor<Vec<u8>>, &'a mut Read)>,
last_part_boundary: Option<Cursor<Vec<u8>>>,
}
impl<'a> MultiPartReader<'a> {
/// Reserve memory for exactly the given amount of parts
pub fn reserve_exact(&mut self, cap: usize) {
self.raw_parts.reserve_exact(cap);
}
/// Add a new part to the queue of parts to be read on the first `read` call.
///
/// # Arguments
///
/// `headers` - identifying the body of the part. It's similar to the header
/// in an ordinary single-part call, and should thus contain the
/// same information.
/// `reader` - a reader providing the part's body
/// `size` - the amount of bytes provided by the reader. It will be put onto the header as
/// content-size.
/// `mime` - It will be put onto the content type
pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> {
let mut headers = Headers::new();
headers.set(ContentType(mime_type));
headers.set(ContentLength(size));
self.raw_parts.push((headers, reader));
self
}
/// Returns the mime-type representing our multi-part message.
/// Use it with the ContentType header.
pub fn mime_type(&self) -> Mime {
Mime(
TopLevel::Multipart,
SubLevel::Ext("Related".to_string()),
vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))],
)
}
/// Returns true if we are totally used
fn is_depleted(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none()
}
/// Returns true if we are handling our last part
fn is_last_part(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_some()
}
}
impl<'a> Read for MultiPartReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.raw_parts.len(),
self.current_part.is_none(),
self.last_part_boundary.is_none()) {
(_, _, false) => {
let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0);
if br < buf.len() {
self.last_part_boundary = None;
}
return Ok(br)
},
(0, true, true) => return Ok(0),
(n, true, _) if n > 0 => {
let (headers, reader) = self.raw_parts.remove(0);
let mut c = Cursor::new(Vec::<u8>::new());
(write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING,
headers, LINE_ENDING)).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
self.current_part = Some((c, reader));
}
_ => {},
}
// read headers as long as possible
let (hb, rr) = {
let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap();
let b = c.read(buf).unwrap_or(0);
(b, reader.read(&mut buf[b..]))
};
match rr {
Ok(bytes_read) => {
if hb < buf.len() && bytes_read == 0 {
if self.is_last_part() {
// before clearing the last part, we will add the boundary that
// will be written last
self.last_part_boundary = Some(Cursor::new(
format!("{}--{}--", LINE_ENDING, BOUNDARY).into_bytes()))
}
// We are depleted - this can trigger the next part to come in
self.current_part = None;
}
let mut total_bytes_read = hb + bytes_read;
while total_bytes_read < buf.len() && !self.is_depleted() {
match self.read(&mut buf[total_bytes_read ..]) {
Ok(br) => total_bytes_read += br,
Err(err) => return Err(err),
}
}
Ok(total_bytes_read)
}
Err(err) => {
// fail permanently
self.current_part = None;
self.last_part_boundary = None;
self.raw_parts.clear();
Err(err)
}
}
}
}
/// The `X-Upload-Content-Type` header.
///
/// Generated via rustc --pretty expanded -Z unstable-options, and manually
/// processed to be more readable.
#[derive(PartialEq, Debug, Clone)]
pub struct XUploadContentType(pub Mime);
impl ::std::ops::Deref for XUploadContentType {
type Target = Mime;
fn deref<'a>(&'a self) -> &'a Mime { &self.0 }
}
impl ::std::ops::DerefMut for XUploadContentType {
fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 }
}
impl Header for XUploadContentType {
fn header_name() -> &'static str { "X-Upload-Content-Type" }
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType)
}
}
impl HeaderFormat for XUploadContentType {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&**self, f)
}
}
impl Display for XUploadContentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chunk {
pub first: u64,
pub last: u64
}
impl fmt::Display for Chunk {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(write!(fmt, "{}-{}", self.first, self.last)).ok();
Ok(())
}
}
impl FromStr for Chunk {
type Err = &'static str;
/// NOTE: only implements `%i-%i`, not `*`
fn from_str(s: &str) -> std::result::Result<Chunk, &'static str> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 2 {
return Err("Expected two parts: %i-%i")
}
Ok(
Chunk {
first: match FromStr::from_str(parts[0]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'first' as digit")
},
last: match FromStr::from_str(parts[1]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'last' as digit")
}
}
)
}
}
/// Implements the Content-Range header, for serialization only
#[derive(Clone, PartialEq, Debug)]
pub struct ContentRange {
pub range: Option<Chunk>,
pub total_length: u64,
}
impl Header for ContentRange {
fn header_name() -> &'static str {
"Content-Range"
}
/// We are not parsable, as parsing is done by the `Range` header
fn parse_header(_: &[Vec<u8>]) -> hyper::error::Result<Self> {
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for ContentRange {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("bytes "));
match self.range {
Some(ref c) => try!(c.fmt(fmt)),
None => try!(fmt.write_str("*"))
}
(write!(fmt, "/{}", self.total_length)).ok();
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct RangeResponseHeader(pub Chunk);
impl Header for RangeResponseHeader {
fn header_name() -> &'static str {
"Range"
}
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
if raw.len() > 0 {
let v = &raw[0];
if let Ok(s) = std::str::from_utf8(v) {
const PREFIX: &'static str = "bytes ";
if s.starts_with(PREFIX) {
if let Ok(c) = <Chunk as FromStr>::from_str(&s[PREFIX.len()..]) {
return Ok(RangeResponseHeader(c))
}
}
}
}
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for RangeResponseHeader {
/// No implmentation necessary, we just need to parse
fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
/// A utility type to perform a resumable upload from start to end.
pub struct ResumableUploadHelper<'a, A: 'a> {
pub client: &'a mut hyper::client::Client,
pub delegate: &'a mut Delegate,
pub start_at: Option<u64>,
pub auth: &'a mut A,
pub user_agent: &'a str,
pub auth_header: Authorization<Bearer>,
pub url: &'a str,
pub reader: &'a mut ReadSeek,
pub media_type: Mime,
pub content_length: u64
}
impl<'a, A> ResumableUploadHelper<'a, A>
where A: oauth2::GetToken {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::Result<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
.header(ContentRange { range: None, total_length: self.content_length })
.header(self.auth_header.clone())
.send() {
Ok(r) => {
// 308 = resume-incomplete == PermanentRedirect
let headers = r.headers.clone();
let h: &RangeResponseHeader = match headers.get() {
Some(hh) if r.status == StatusCode::PermanentRedirect => hh,
None|Some(_) => {
if let Retry::After(d) = self.delegate.http_failure(&r, None, None) {
sleep(d);
continue;
}
return Err(Ok(r))
}
};
return Ok(h.0.last)
}
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Err(Err(err))
}
}
}
}
/// returns None if operation was cancelled by delegate, or the HttpResult.
/// It can be that we return the result just because we didn't understand the status code -
/// caller should check for status himself before assuming it's OK to use
pub fn upload(&mut self) -> Option<hyper::Result<hyper::client::Response>> {
let mut start = match self.start_at {
Some(s) => s,
None => match self.query_transfer_status() {
Ok(s) => s,
Err(result) => return Some(result)
}
};
const MIN_CHUNK_SIZE: u64 = 1 << 18;
let chunk_size = match self.delegate.chunk_size() {
cs if cs > MIN_CHUNK_SIZE => cs,
_ => MIN_CHUNK_SIZE
};
self.reader.seek(SeekFrom::Start(start)).unwrap();
loop {
let request_size = match self.content_length - start {
rs if rs > chunk_size => chunk_size,
rs => rs
};
let mut section_reader = self.reader.take(request_size);
let range_header = ContentRange {
range: Some(Chunk {first: start, last: start + request_size - 1}),
total_length: self.content_length
};
start += request_size;
if self.delegate.cancel_chunk_upload(&range_header) {
return None
}
let res = self.client.post(self.url)
.header(range_header)
.header(ContentType(self.media_type.clone()))
.header(UserAgent(self.user_agent.to_string()))
.body(&mut section_reader)
.send();
match res {
Ok(mut res) => {
if res.status == StatusCode::PermanentRedirect {
continue
}
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let Retry::After(d) = self.delegate.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
}
return Some(Ok(res))
},
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Some(Err(err))
}
}
}
}
}
// Copy of src/rust/cli/cmn.rs
// TODO(ST): Allow sharing common code between program types
pub fn remove_json_null_values(value: &mut json::value::Value) {
match *value {
json::value::Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-analyticsreporting4-cli"
version = "1.0.7+20171108"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with AnalyticsReporting (protocol v4)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/analyticsreporting4-cli"
homepage = "https://developers.google.com/analytics/devguides/reporting/core/v4/"
documentation = "http://byron.github.io/google-apis-rs/google_analyticsreporting4_cli"
license = "MIT"
keywords = ["analyticsreporting", "google", "cli"]
[[bin]]
name = "analyticsreporting4"
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
strsim = "^0.5"
hyper-rustls = "^0.6"
yup-hyper-mock = "^2.0"
clap = "^2.0"
[features]
[dependencies.google-analyticsreporting4]
path = "../analyticsreporting4"
version = "1.0.7+20171108"

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,114 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/cli/README.md.mako'
DO NOT EDIT !
-->
The `analyticsreporting4` command-line interface *(CLI)* allows to use most features of the *Google AnalyticsReporting* service from the comfort of your terminal.
By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's
capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero.
If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools.
Everything else about the *AnalyticsReporting* API can be found at the
[official documentation site](https://developers.google.com/analytics/devguides/reporting/core/v4/).
# Installation and Source Code
Install the command-line interface with cargo using:
```bash
cargo install google-analyticsreporting4-cli
```
Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/analyticsreporting4-cli).
# Usage
This documentation was generated from the *AnalyticsReporting* API at revision *20171108*. The CLI is at version *1.0.7*.
```bash
analyticsreporting4 [options]
reports
batch-get (-r <kv>)... [-p <v>]... [-o <out>]
analyticsreporting4 --help
Configuration:
[--scope <url>]...
Specify the authentication a method should be executed in. Each scope
requires the user to grant this application permission to use it.
If unset, it defaults to the shortest scope url for a particular method.
--config-dir <folder>
A directory into which we will store our persistent data. Defaults to
a user-writable directory that we will create during the first invocation.
[default: ~/.google-service-cli]
--debug
Output all server communication to standard error. `tx` and `rx` are placed
into the same stream.
--debug-auth
Output all communication related to authentication to standard error. `tx`
and `rx` are placed into the same stream.
```
# Configuration
The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `analyticsreporting4-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis.
More information about the various kinds of persistent data are given in the following paragraphs.
# Authentication
Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the
set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*.
If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a
method that is read-only, it will ask only for a read-only scope.
You may use the `--scope` flag to specify a scope directly.
All applicable scopes are documented in the respective method's CLI documentation.
The first time a scope is used, the user is asked for permission. Follow the instructions given
by the CLI to grant permissions, or to decline.
If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration
directory, e.g. `~/.google-service-cli/analyticsreporting4-token-<scope-hash>.json`. No manual management of these tokens
is necessary.
To revoke granted authentication, please refer to the [official documentation][revoke-access].
# Application Secrets
In order to allow any application to use Google services, it will need to be registered using the
[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it
one by one. Most APIs can be used for free and have a daily quota.
To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI
comes with a default application secret that is configured accordingly. This also means that heavy usage
all around the world may deplete the daily quota.
You can workaround this limitation by putting your own secrets file at this location:
`~/.google-service-cli/analyticsreporting4-secret.json`, assuming that the required *analyticsreporting* API
was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at
*APIs & auth -> Credentials -> Download JSON* and used as is.
Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new].
# Debugging
Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know
what exactly led to a particular issue. This is done by allowing all client-server communication to be
output to standard error *as-is*.
The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag
will cause all communication related to authentication to standard error.
If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the
issue at hand.
You may consider redirecting standard error into a file for ease of use, e.g. `analyticsreporting4 --debug <resource> <method> [options] 2>debug.txt`.
[scopes]: https://developers.google.com/+/api/oauth#scopes
[revoke-access]: http://webapps.stackexchange.com/a/30849
[google-dev-console]: https://console.developers.google.com/
[google-project-new]: https://developers.google.com/console/help/new/

View File

@@ -0,0 +1,17 @@
site_name: AnalyticsReporting v1.0.7+20171108
site_url: http://byron.github.io/google-apis-rs/google-analyticsreporting4-cli
site_description: A complete library to interact with AnalyticsReporting (protocol v4)
repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/analyticsreporting4-cli
docs_dir: docs
site_dir: build_html
pages:
- ['index.md', 'Home']
- ['reports_batch-get.md', 'Reports', 'Batch Get']
theme: readthedocs
copyright: Copyright &copy; 2015-2016, `Sebastian Thiel`

View File

@@ -0,0 +1,799 @@
// COPY OF 'src/rust/cli/cmn.rs'
// DO NOT EDIT
use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token};
use serde_json as json;
use serde_json::value::Value;
use mime::Mime;
use clap::{App, SubCommand};
use strsim;
use std::fs;
use std::env;
use std::io;
use std::error::Error as StdError;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
use std::io::{Write, Read, stdout};
use std::default::Default;
const FIELD_SEP: char = '.';
pub enum ComplexType {
Pod,
Vec,
Map,
}
// Null,
// Bool(bool),
// I64(i64),
// U64(u64),
// F64(f64),
// String(String),
pub enum JsonType {
Boolean,
Int,
Uint,
Float,
String,
}
pub struct JsonTypeInfo {
pub jtype: JsonType,
pub ctype: ComplexType,
}
// Based on @erickt user comment. Thanks for the idea !
// Remove all keys whose values are null from given value (changed in place)
pub fn remove_json_null_values(value: &mut Value) {
match *value {
Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}
fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> {
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values {
let confidence = strsim::jaro_winkler(v, pv);
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
}
pub enum CallType {
Upload(UploadProtocol),
Standard,
}
arg_enum!{
pub enum UploadProtocol {
Simple,
Resumable
}
}
impl AsRef<str> for UploadProtocol {
fn as_ref(&self) -> &str {
match *self {
UploadProtocol::Simple => "simple",
UploadProtocol::Resumable => "resumable",
}
}
}
impl AsRef<str> for CallType {
fn as_ref(&self) -> &str {
match *self {
CallType::Upload(ref proto) => proto.as_ref(),
CallType::Standard => "standard-request",
}
}
}
#[derive(Clone, Default)]
pub struct FieldCursor(Vec<String>);
impl ToString for FieldCursor {
fn to_string(&self) -> String {
self.0.join(".")
}
}
impl From<&'static str> for FieldCursor {
fn from(value: &'static str) -> FieldCursor {
let mut res = FieldCursor::default();
res.set(value).unwrap();
res
}
}
fn assure_entry<'a, 'b>(m: &'a mut json::Map<String, Value>, k: &'b String) -> &'a mut Value {
if m.contains_key(k) {
return m.get_mut(k).expect("value to exist");
}
m.insert(k.to_owned(), Value::Object(Default::default()));
m.get_mut(k).expect("value to exist")
}
impl FieldCursor {
pub fn set(&mut self, value: &str) -> Result<(), CLIError> {
if value.len() == 0 {
return Err(CLIError::Field(FieldError::Empty));
}
let mut first_is_field_sep = false;
let mut char_count: usize = 0;
let mut last_c = FIELD_SEP;
let mut num_conscutive_field_seps = 0;
let mut field = String::new();
let mut fields = self.0.clone();
let push_field = |fs: &mut Vec<String>, f: &mut String| {
if f.len() > 0 {
fs.push(f.clone());
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
char_count += 1;
if c == FIELD_SEP {
if cid == 0 {
first_is_field_sep = true;
}
num_conscutive_field_seps += 1;
if cid > 0 && last_c == FIELD_SEP {
if fields.pop().is_none() {
return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string())));
}
} else {
push_field(&mut fields, &mut field);
}
} else {
num_conscutive_field_seps = 0;
if cid == 1 {
if first_is_field_sep {
fields.truncate(0);
}
}
field.push(c);
}
last_c = c;
}
push_field(&mut fields, &mut field);
if char_count == 1 && first_is_field_sep {
fields.truncate(0);
}
if char_count > 1 && num_conscutive_field_seps == 1 {
return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string())));
}
self.0 = fields;
Ok(())
}
pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option<String> {
if value.len() == 0 {
return None;
}
let mut last_c = FIELD_SEP;
let mut field = String::new();
let mut output = String::new();
let push_field = |fs: &mut String, f: &mut String| {
if f.len() > 0 {
fs.push_str(match did_you_mean(&f, possible_values) {
Some(candidate) => candidate,
None => &f,
});
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
if c == FIELD_SEP {
if last_c != FIELD_SEP {
push_field(&mut output, &mut field);
}
output.push(c);
} else {
field.push(c);
}
last_c = c;
}
push_field(&mut output, &mut field);
if &output == value {
None
} else {
Some(output)
}
}
pub fn set_json_value(&self,
mut object: &mut Value,
value: &str,
type_info: JsonTypeInfo,
err: &mut InvalidOptionsError,
orig_cursor: &FieldCursor) {
assert!(self.0.len() > 0);
for field in &self.0[..self.0.len() - 1] {
let tmp = object;
object = match *tmp {
Value::Object(ref mut mapping) => {
assure_entry(mapping, &field)
}
_ => panic!("We don't expect non-object Values here ..."),
};
}
match *object {
Value::Object(ref mut mapping) => {
let field = &self.0[self.0.len() - 1];
let to_jval = |value: &str,
jtype: JsonType,
err: &mut InvalidOptionsError|
-> Value {
match jtype {
JsonType::Boolean =>
Value::Bool(arg_from_str(value, err, &field, "boolean")),
JsonType::Int =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"int"))
.expect("valid f64")),
JsonType::Uint =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"uint"))
.expect("valid f64")),
JsonType::Float =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"float"))
.expect("valid f64")),
JsonType::String => Value::String(value.to_owned()),
}
};
match type_info.ctype {
ComplexType::Pod => {
if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err))
.is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
ComplexType::Vec => {
match *assure_entry(mapping, field) {
Value::Array(ref mut values) =>
values.push(to_jval(value, type_info.jtype, err)),
_ => unreachable!(),
}
}
ComplexType::Map => {
let (key, value) = parse_kv_arg(value, err, true);
let jval = to_jval(value.unwrap_or(""), type_info.jtype, err);
match *assure_entry(mapping, &field) {
Value::Object(ref mut value_map) => {
if value_map.insert(key.to_owned(), jval).is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
_ => unreachable!(),
}
}
}
}
_ => unreachable!(),
}
}
pub fn num_fields(&self) -> usize {
self.0.len()
}
}
pub fn parse_kv_arg<'a>(kv: &'a str,
err: &mut InvalidOptionsError,
for_hashmap: bool)
-> (&'a str, Option<&'a str>) {
let mut add_err = || {
err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(), for_hashmap))
};
match kv.find('=') {
None => {
add_err();
return (kv, None);
}
Some(pos) => {
let key = &kv[..pos];
if kv.len() <= pos + 1 {
add_err();
return (key, Some(""));
}
(key, Some(&kv[pos + 1..]))
}
}
}
pub fn calltype_from_str(name: &str,
valid_protocols: Vec<String>,
err: &mut InvalidOptionsError)
-> CallType {
CallType::Upload(match UploadProtocol::from_str(name) {
Ok(up) => up,
Err(msg) => {
err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols));
UploadProtocol::Simple
}
})
}
pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option<fs::File> {
match fs::File::open(file_path) {
Ok(f) => Some(f),
Err(io_err) => {
err.issues.push(CLIError::Input(InputError::Io((file_path.to_string(), io_err))));
None
}
}
}
pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option<Mime> {
match mime.parse() {
Ok(m) => Some(m),
Err(_) => {
err.issues.push(CLIError::Input(InputError::Mime(mime.to_string())));
None
}
}
}
pub fn writer_from_opts(arg: Option<&str>) -> Result<Box<Write>, io::Error> {
let f = arg.unwrap_or("-");
match f {
"-" => Ok(Box::new(stdout())),
_ => match fs::OpenOptions::new().create(true).write(true).open(f) {
Ok(f) => Ok(Box::new(f)),
Err(io_err) => Err(io_err),
},
}
}
pub fn arg_from_str<'a, T>(arg: &str,
err: &mut InvalidOptionsError,
arg_name: &'a str,
arg_type: &'a str)
-> T
where T: FromStr + Default,
<T as FromStr>::Err: fmt::Display
{
match FromStr::from_str(arg) {
Err(perr) => {
err.issues.push(CLIError::ParseError(arg_name.to_owned(),
arg_type.to_owned(),
arg.to_string(),
format!("{}", perr)));
Default::default()
}
Ok(v) => v,
}
}
pub struct JsonTokenStorage {
pub program_name: &'static str,
pub db_dir: String,
}
impl JsonTokenStorage {
fn path(&self, scope_hash: u64) -> PathBuf {
Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash))
}
}
#[derive(Debug)]
pub enum TokenStorageError {
Json(json::Error),
Io(io::Error),
}
impl fmt::Display for TokenStorageError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
TokenStorageError::Json(ref err) => writeln!(f, "Could not serialize secrets: {}", err),
TokenStorageError::Io(ref err) => writeln!(f, "Failed to write secret token: {}", err),
}
}
}
impl StdError for TokenStorageError {
fn description(&self) -> &str {
"Failure when getting or setting the token storage"
}
}
impl TokenStorage for JsonTokenStorage {
type Error = TokenStorageError;
// NOTE: logging might be interesting, currently we swallow all errors
fn set(&mut self,
scope_hash: u64,
_: &Vec<&str>,
token: Option<Token>)
-> Result<(), TokenStorageError> {
match token {
None => {
match fs::remove_file(self.path(scope_hash)) {
Err(err) => match err.kind() {
io::ErrorKind::NotFound => Ok(()),
_ => Err(TokenStorageError::Io(err)),
},
Ok(_) => Ok(()),
}
}
Some(token) => {
match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) {
Ok(mut f) => {
match json::to_writer_pretty(&mut f, &token) {
Ok(_) => Ok(()),
Err(serde_err) => Err(TokenStorageError::Json(serde_err)),
}
}
Err(io_err) => Err(TokenStorageError::Io(io_err)),
}
}
}
}
fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result<Option<Token>, TokenStorageError> {
match fs::File::open(&self.path(scope_hash)) {
Ok(f) => {
match json::de::from_reader(f) {
Ok(token) => Ok(Some(token)),
Err(err) => Err(TokenStorageError::Json(err)),
}
}
Err(io_err) => {
match io_err.kind() {
io::ErrorKind::NotFound => Ok(None),
_ => Err(TokenStorageError::Io(io_err)),
}
}
}
}
}
#[derive(Debug)]
pub enum ApplicationSecretError {
DecoderError((String, json::Error)),
FormatError(String),
}
impl fmt::Display for ApplicationSecretError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ApplicationSecretError::DecoderError((ref path, ref err)) =>
writeln!(f,
"Could not decode file at '{}' with error: {}.",
path,
err),
ApplicationSecretError::FormatError(ref path) =>
writeln!(f,
"'installed' field is unset in secret file at '{}'.",
path),
}
}
}
#[derive(Debug)]
pub enum ConfigurationError {
DirectoryCreationFailed((String, io::Error)),
DirectoryUnset,
HomeExpansionFailed(String),
Secret(ApplicationSecretError),
Io((String, io::Error)),
}
impl fmt::Display for ConfigurationError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) =>
writeln!(f,
"Directory '{}' could not be created with error: {}.",
dir,
err),
ConfigurationError::DirectoryUnset => writeln!(f, "--config-dir was unset or empty."),
ConfigurationError::HomeExpansionFailed(ref dir) =>
writeln!(f,
"Couldn't find HOME directory of current user, failed to expand '{}'.",
dir),
ConfigurationError::Secret(ref err) => writeln!(f, "Secret -> {}", err),
ConfigurationError::Io((ref path, ref err)) =>
writeln!(f,
"IO operation failed on path '{}' with error: {}.",
path,
err),
}
}
}
#[derive(Debug)]
pub enum InputError {
Io((String, io::Error)),
Mime(String),
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
InputError::Io((ref file_path, ref io_err)) =>
writeln!(f,
"Failed to open '{}' for reading with error: {}.",
file_path,
io_err),
InputError::Mime(ref mime) => writeln!(f, "'{}' is not a known mime-type.", mime),
}
}
}
#[derive(Debug)]
pub enum FieldError {
PopOnEmpty(String),
TrailingFieldSep(String),
Unknown(String, Option<String>, Option<String>),
Duplicate(String),
Empty,
}
impl fmt::Display for FieldError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
FieldError::PopOnEmpty(ref field) =>
writeln!(f, "'{}': Cannot move up on empty field cursor.", field),
FieldError::TrailingFieldSep(ref field) =>
writeln!(f,
"'{}': Single field separator may not be last character.",
field),
FieldError::Unknown(ref field, ref suggestion, ref value) => {
let suffix = match *suggestion {
Some(ref s) => {
let kv = match *value {
Some(ref v) => format!("{}={}", s, v),
None => s.clone(),
};
format!(" Did you mean '{}' ?", kv)
}
None => String::new(),
};
writeln!(f, "Field '{}' does not exist.{}", field, suffix)
}
FieldError::Duplicate(ref cursor) =>
writeln!(f, "Value at '{}' was already set", cursor),
FieldError::Empty => writeln!(f, "Field names must not be empty."),
}
}
}
#[derive(Debug)]
pub enum CLIError {
Configuration(ConfigurationError),
ParseError(String, String, String, String),
UnknownParameter(String, Vec<&'static str>),
InvalidUploadProtocol(String, Vec<String>),
InvalidKeyValueSyntax(String, bool),
Input(InputError),
Field(FieldError),
MissingCommandError,
MissingMethodError(String),
}
impl fmt::Display for CLIError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err),
CLIError::Input(ref err) => write!(f, "Input -> {}", err),
CLIError::Field(ref err) => write!(f, "Field -> {}", err),
CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) =>
writeln!(f,
"'{}' is not a valid upload protocol. Choose from one of {}.",
proto_name,
valid_names.join(", ")),
CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) =>
writeln!(f,
"Failed to parse argument '{}' with value '{}' as {} with error: {}.",
arg_name,
value,
type_name,
err_desc),
CLIError::UnknownParameter(ref param_name, ref possible_values) => {
let suffix = match did_you_mean(param_name, &possible_values) {
Some(v) => format!(" Did you mean '{}' ?", v),
None => String::new(),
};
write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix)
}
CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => {
let hashmap_info = if is_hashmap {
"hashmap "
} else {
""
};
writeln!(f,
"'{}' does not match {}pattern <key>=<value>.",
kv,
hashmap_info)
}
CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."),
CLIError::MissingMethodError(ref cmd) =>
writeln!(f,
"Please specify the method to call on the '{}' command.",
cmd),
}
}
}
#[derive(Debug)]
pub struct InvalidOptionsError {
pub issues: Vec<CLIError>,
pub exit_code: i32,
}
impl fmt::Display for InvalidOptionsError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for issue in &self.issues {
try!(issue.fmt(f));
}
Ok(())
}
}
impl InvalidOptionsError {
pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError {
InvalidOptionsError {
issues: vec![err],
exit_code: exit_code,
}
}
pub fn new() -> InvalidOptionsError {
InvalidOptionsError {
issues: Vec::new(),
exit_code: 1,
}
}
}
pub fn assure_config_dir_exists(dir: &str) -> Result<String, CLIError> {
let trdir = dir.trim();
if trdir.len() == 0 {
return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset));
}
let expanded_config_dir = if trdir.as_bytes()[0] == b'~' {
match env::var("HOME").ok().or(env::var("UserProfile").ok()) {
None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))),
Some(mut user) => {
user.push_str(&trdir[1..]);
user
}
}
} else {
trdir.to_string()
};
if let Err(err) = fs::create_dir(&expanded_config_dir) {
if err.kind() != io::ErrorKind::AlreadyExists {
return Err(CLIError::Configuration(
ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err))));
}
}
Ok(expanded_config_dir)
}
pub fn application_secret_from_directory(dir: &str,
secret_basename: &str,
json_console_secret: &str)
-> Result<ApplicationSecret, CLIError> {
let secret_path = Path::new(dir).join(secret_basename);
let secret_str = || secret_path.as_path().to_str().unwrap().to_string();
let secret_io_error = |io_err: io::Error| {
Err(CLIError::Configuration(ConfigurationError::Io((secret_str(), io_err))))
};
for _ in 0..2 {
match fs::File::open(&secret_path) {
Err(mut err) => {
if err.kind() == io::ErrorKind::NotFound {
// Write our built-in one - user may adjust the written file at will
err = match fs::OpenOptions::new()
.create(true)
.write(true)
.open(&secret_path) {
Err(cfe) => cfe,
Ok(mut f) => {
// Assure we convert 'ugly' json string into pretty one
let console_secret: ConsoleApplicationSecret =
json::from_str(json_console_secret).unwrap();
match json::to_writer_pretty(&mut f, &console_secret) {
Err(serde_err) =>
panic!("Unexpected serde error: {:#?}", serde_err),
Ok(_) => continue,
}
}
};
// fall through to IO error handling
}
return secret_io_error(err);
}
Ok(f) => {
match json::de::from_reader::<_, ConsoleApplicationSecret>(f) {
Err(json_err) =>
return Err(CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::DecoderError(
(secret_str(), json_err)
)))),
Ok(console_secret) => match console_secret.installed {
Some(secret) => return Ok(secret),
None => return Err(
CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::FormatError(secret_str())
))),
},
}
}
}
}
unreachable!();
}

View File

@@ -0,0 +1,358 @@
// DO NOT EDIT !
// This file was generated automatically from 'src/mako/cli/main.rs.mako'
// DO NOT EDIT !
#![allow(unused_variables, unused_imports, dead_code, unused_mut)]
#[macro_use]
extern crate clap;
extern crate yup_oauth2 as oauth2;
extern crate yup_hyper_mock as mock;
extern crate hyper_rustls;
extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate mime;
extern crate strsim;
extern crate google_analyticsreporting4 as api;
use std::env;
use std::io::{self, Write};
use clap::{App, SubCommand, Arg};
mod cmn;
use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg,
input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol,
calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo};
use std::default::Default;
use std::str::FromStr;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, FlowType};
use serde_json as json;
use clap::ArgMatches;
enum DoitError {
IoError(String, io::Error),
ApiError(api::Error),
}
struct Engine<'n> {
opt: ArgMatches<'n>,
hub: api::AnalyticsReporting<hyper::Client, Authenticator<DefaultAuthenticatorDelegate, JsonTokenStorage, hyper::Client>>,
gp: Vec<&'static str>,
gpm: Vec<(&'static str, &'static str)>,
}
impl<'n> Engine<'n> {
fn _reports_batch_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"use-resource-quotas" => Some(("useResourceQuotas", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["use-resource-quotas"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::GetReportsRequest = json::value::from_value(object).unwrap();
let mut call = self.hub.reports().batch_get(request);
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _doit(&self, dry_run: bool) -> Result<Result<(), DoitError>, Option<InvalidOptionsError>> {
let mut err = InvalidOptionsError::new();
let mut call_result: Result<(), DoitError> = Ok(());
let mut err_opt: Option<InvalidOptionsError> = None;
match self.opt.subcommand() {
("reports", Some(opt)) => {
match opt.subcommand() {
("batch-get", Some(opt)) => {
call_result = self._reports_batch_get(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("reports".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
_ => {
err.issues.push(CLIError::MissingCommandError);
writeln!(io::stderr(), "{}\n", self.opt.usage()).ok();
}
}
if dry_run {
if err.issues.len() > 0 {
err_opt = Some(err);
}
Err(err_opt)
} else {
Ok(call_result)
}
}
// Please note that this call will fail if any part of the opt can't be handled
fn new(opt: ArgMatches<'n>) -> Result<Engine<'n>, InvalidOptionsError> {
let (config_dir, secret) = {
let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) {
Err(e) => return Err(InvalidOptionsError::single(e, 3)),
Ok(p) => p,
};
match cmn::application_secret_from_directory(&config_dir, "analyticsreporting4-secret.json",
"{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") {
Ok(secret) => (config_dir, secret),
Err(e) => return Err(InvalidOptionsError::single(e, 4))
}
};
let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate,
if opt.is_present("debug-auth") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
},
JsonTokenStorage {
program_name: "analyticsreporting4",
db_dir: config_dir.clone(),
}, Some(FlowType::InstalledRedirect(54324)));
let client =
if opt.is_present("debug") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
};
let engine = Engine {
opt: opt,
hub: api::AnalyticsReporting::new(client, auth),
gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"],
gpm: vec![
("$-xgafv", "$.xgafv"),
("access-token", "access_token"),
("bearer-token", "bearer_token"),
("oauth-token", "oauth_token"),
("pretty-print", "prettyPrint"),
("quota-user", "quotaUser"),
("upload-type", "uploadType"),
("upload-protocol", "upload_protocol"),
]
};
match engine._doit(true) {
Err(Some(err)) => Err(err),
Err(None) => Ok(engine),
Ok(_) => unreachable!(),
}
}
fn doit(&self) -> Result<(), DoitError> {
match self._doit(false) {
Ok(res) => res,
Err(_) => unreachable!(),
}
}
}
fn main() {
let mut exit_status = 0i32;
let arg_data = [
("reports", "methods: 'batch-get'", vec![
("batch-get",
Some(r##"Returns the Analytics data."##),
"Details at http://byron.github.io/google-apis-rs/google_analyticsreporting4_cli/reports_batch-get",
vec![
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
];
let mut app = App::new("analyticsreporting4")
.author("Sebastian Thiel <byronimo@gmail.com>")
.version("1.0.7+20171108")
.about("Accesses Analytics report data.")
.after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_analyticsreporting4_cli")
.arg(Arg::with_name("url")
.long("scope")
.help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.")
.multiple(true)
.takes_value(true))
.arg(Arg::with_name("folder")
.long("config-dir")
.help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli")
.multiple(false)
.takes_value(true))
.arg(Arg::with_name("debug")
.long("debug")
.help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false))
.arg(Arg::with_name("debug-auth")
.long("debug-auth")
.help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false));
for &(main_command_name, about, ref subcommands) in arg_data.iter() {
let mut mcmd = SubCommand::with_name(main_command_name).about(about);
for &(sub_command_name, ref desc, url_info, ref args) in subcommands {
let mut scmd = SubCommand::with_name(sub_command_name);
if let &Some(desc) = desc {
scmd = scmd.about(desc);
}
scmd = scmd.after_help(url_info);
for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args {
let arg_name_str =
match (arg_name, flag) {
(&Some(an), _ ) => an,
(_ , &Some(f)) => f,
_ => unreachable!(),
};
let mut arg = Arg::with_name(arg_name_str)
.empty_values(false);
if let &Some(short_flag) = flag {
arg = arg.short(short_flag);
}
if let &Some(desc) = desc {
arg = arg.help(desc);
}
if arg_name.is_some() && flag.is_some() {
arg = arg.takes_value(true);
}
if let &Some(required) = required {
arg = arg.required(required);
}
if let &Some(multi) = multi {
arg = arg.multiple(multi);
}
scmd = scmd.arg(arg);
}
mcmd = mcmd.subcommand(scmd);
}
app = app.subcommand(mcmd);
}
let matches = app.get_matches();
let debug = matches.is_present("debug");
match Engine::new(matches) {
Err(err) => {
exit_status = err.exit_code;
writeln!(io::stderr(), "{}", err).ok();
},
Ok(engine) => {
if let Err(doit_err) = engine.doit() {
exit_status = 1;
match doit_err {
DoitError::IoError(path, err) => {
writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok();
},
DoitError::ApiError(err) => {
if debug {
writeln!(io::stderr(), "{:#?}", err).ok();
} else {
writeln!(io::stderr(), "{}", err).ok();
}
}
}
}
}
}
std::process::exit(exit_status);
}

View File

@@ -0,0 +1,31 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-analyticsreporting4"
version = "1.0.7+20171108"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with AnalyticsReporting (protocol v4)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/analyticsreporting4"
homepage = "https://developers.google.com/analytics/devguides/reporting/core/v4/"
documentation = "https://docs.rs/google-analyticsreporting4/1.0.7+20171108"
license = "MIT"
keywords = ["analyticsreporting", "google", "protocol", "web", "api"]
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
url = "= 0.5"
[features]

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,180 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/api/README.md.mako'
DO NOT EDIT !
-->
The `google-analyticsreporting4` library allows access to all features of the *Google AnalyticsReporting* service.
This documentation was generated from *AnalyticsReporting* crate version *1.0.7+20171108*, where *20171108* is the exact revision of the *analyticsreporting:v4* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.7*.
Everything else about the *AnalyticsReporting* *v4* API can be found at the
[official documentation site](https://developers.google.com/analytics/devguides/reporting/core/v4/).
# Features
Handle the following *Resources* with ease from the central [hub](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/struct.AnalyticsReporting.html) ...
* [reports](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/struct.Report.html)
* [*batch get*](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/struct.ReportBatchGetCall.html)
# Structure of this Library
The API is structured into the following primary items:
* **[Hub](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/struct.AnalyticsReporting.html)**
* a central object to maintain state and allow accessing all *Activities*
* creates [*Method Builders*](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.MethodsBuilder.html) which in turn
allow access to individual [*Call Builders*](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.CallBuilder.html)
* **[Resources](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.Resource.html)**
* primary types that you can apply *Activities* to
* a collection of properties and *Parts*
* **[Parts](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.Part.html)**
* a collection of properties
* never directly used in *Activities*
* **[Activities](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.CallBuilder.html)**
* operations to apply to *Resources*
All *structures* are marked with applicable traits to further categorize them and ease browsing.
Generally speaking, you can invoke *Activities* like this:
```Rust,ignore
let r = hub.resource().activity(...).doit()
```
Or specifically ...
```ignore
let r = hub.reports().batch_get(...).doit()
```
The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
The `doit()` method performs the actual communication with the server and returns the respective result.
# Usage
## Setting up your Project
To use this library, you would put the following lines into your `Cargo.toml` file:
```toml
[dependencies]
google-analyticsreporting4 = "*"
```
## A complete example
```Rust
extern crate hyper;
extern crate hyper_rustls;
extern crate yup_oauth2 as oauth2;
extern crate google_analyticsreporting4 as analyticsreporting4;
use analyticsreporting4::GetReportsRequest;
use analyticsreporting4::{Result, Error};
use std::default::Default;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
use analyticsreporting4::AnalyticsReporting;
// Get an ApplicationSecret instance by some means. It contains the `client_id` and
// `client_secret`, among other things.
let secret: ApplicationSecret = Default::default();
// Instantiate the authenticator. It will choose a suitable authentication flow for you,
// unless you replace `None` with the desired Flow.
// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
// retrieve them from storage.
let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
<MemoryStorage as Default>::default(), None);
let mut hub = AnalyticsReporting::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
// As the method needs a request, you would usually fill it with the desired information
// into the respective structure. Some of the parts shown here might not be applicable !
// Values shown here are possibly random and not representative !
let mut req = GetReportsRequest::default();
// You can configure optional parameters by calling the respective setters at will, and
// execute the final call using `doit()`.
// Values shown here are possibly random and not representative !
let result = hub.reports().batch_get(req)
.doit();
match result {
Err(e) => match e {
// The Error enum provides details about what exactly happened.
// You can also just use its `Debug`, `Display` or `Error` traits
Error::HttpError(_)
|Error::MissingAPIKey
|Error::MissingToken(_)
|Error::Cancelled
|Error::UploadSizeLimitExceeded(_, _)
|Error::Failure(_)
|Error::BadRequest(_)
|Error::FieldClash(_)
|Error::JsonDecodeError(_, _) => println!("{}", e),
},
Ok(res) => println!("Success: {:?}", res),
}
```
## Handling Errors
All errors produced by the system are provided either as [Result](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/enum.Result.html) enumeration as return value of
the doit() methods, or handed as possibly intermediate results to either the
[Hub Delegate](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.Delegate.html), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html).
When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
makes the system potentially resilient to all kinds of errors.
## Uploads and Downloads
If a method supports downloads, the response body, which is part of the [Result](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/enum.Result.html), should be
read by you to obtain the media.
If such a method also supports a [Response Result](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.ResponseResult.html), it will return that by default.
You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
this call: `.param("alt", "media")`.
Methods supporting uploads can do so using up to 2 different protocols:
*simple* and *resumable*. The distinctiveness of each is represented by customized
`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
## Customization and Callbacks
You may alter the way an `doit()` method is called by providing a [delegate](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.Delegate.html) to the
[Method Builder](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.CallBuilder.html) before making the final `doit()` call.
Respective methods will be called to provide progress information, as well as determine whether the system should
retry on failure.
The [delegate trait](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
## Optional Parts in Server-Requests
All structures provided by this library are made to be [enocodable](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.RequestValue.html) and
[decodable](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
are valid.
Most optionals are are considered [Parts](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.Part.html) which are identifiable by name, which will be sent to
the server to indicate either the set parts of the request or the desired parts in the response.
## Builder Arguments
Using [method builders](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods.
These will always take a single argument, for which the following statements are true.
* [PODs][wiki-pod] are handed by copy
* strings are passed as `&str`
* [request values](https://docs.rs/google-analyticsreporting4/1.0.7+20171108/google_analyticsreporting4/trait.RequestValue.html) are moved
Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
[google-go-api]: https://github.com/google/google-api-go-client
# License
The **analyticsreporting4** library was generated by Sebastian Thiel, and is placed
under the *MIT* license.
You can read the full text at the repository's [license file][repo-license].
[repo-license]: https://github.com/Byron/google-apis-rsblob/master/LICENSE.md

View File

@@ -0,0 +1,753 @@
// COPY OF 'src/rust/api/cmn.rs'
// DO NOT EDIT
use std::io::{self, Read, Seek, Cursor, Write, SeekFrom};
use std;
use std::fmt::{self, Display};
use std::str::FromStr;
use std::error;
use std::thread::sleep;
use std::time::Duration;
use mime::{Mime, TopLevel, SubLevel, Attr, Value};
use oauth2::{TokenType, Retry, self};
use hyper;
use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header,
HeaderFormat, Bearer};
use hyper::http::h1::LINE_ENDING;
use hyper::method::Method;
use hyper::status::StatusCode;
use serde_json as json;
/// Identifies the Hub. There is only one per library, this trait is supposed
/// to make intended use more explicit.
/// The hub allows to access all resource methods more easily.
pub trait Hub {}
/// Identifies types for building methods of a particular resource type
pub trait MethodsBuilder {}
/// Identifies types which represent builders for a particular resource method
pub trait CallBuilder {}
/// Identifies types which can be inserted and deleted.
/// Types with this trait are most commonly used by clients of this API.
pub trait Resource {}
/// Identifies types which are used in API responses.
pub trait ResponseResult {}
/// Identifies types which are used in API requests.
pub trait RequestValue {}
/// Identifies types which are not actually used by the API
/// This might be a bug within the google API schema.
pub trait UnusedType {}
/// Identifies types which are only used as part of other types, which
/// usually are carrying the `Resource` trait.
pub trait Part {}
/// Identifies types which are only used by other types internally.
/// They have no special meaning, this trait just marks them for completeness.
pub trait NestedType {}
/// A utility to specify reader types which provide seeking capabilities too
pub trait ReadSeek: Seek + Read {}
impl<T: Seek + Read> ReadSeek for T {}
/// A trait for all types that can convert themselves into a *parts* string
pub trait ToParts {
fn to_parts(&self) -> String;
}
/// A utility type which can decode a server response that indicates error
#[derive(Deserialize)]
pub struct JsonServerError {
pub error: String,
pub error_description: Option<String>
}
/// A utility to represent detailed errors we might see in case there are BadRequests.
/// The latter happen if the sent parameters or request structures are unsound
#[derive(Deserialize, Serialize, Debug)]
pub struct ErrorResponse {
error: ServerError,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerError {
errors: Vec<ServerMessage>,
code: u16,
message: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerMessage {
domain: String,
reason: String,
message: String,
#[serde(rename="locationType")]
location_type: Option<String>,
location: Option<String>
}
#[derive(Copy, Clone)]
pub struct DummyNetworkStream;
impl Read for DummyNetworkStream {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl Write for DummyNetworkStream {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl hyper::net::NetworkStream for DummyNetworkStream {
fn peer_addr(&mut self) -> io::Result<std::net::SocketAddr> {
Ok("127.0.0.1:1337".parse().unwrap())
}
fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
}
/// A trait specifying functionality to help controlling any request performed by the API.
/// The trait has a conservative default implementation.
///
/// It contains methods to deal with all common issues, as well with the ones related to
/// uploading media
pub trait Delegate {
/// Called at the beginning of any API request. The delegate should store the method
/// information if he is interesting in knowing more context when further calls to it
/// are made.
/// The matching `finished()` call will always be made, no matter whether or not the API
/// request was successful. That way, the delegate may easily maintain a clean state
/// between various API calls.
fn begin(&mut self, MethodInfo) {}
/// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
///
/// Return retry information.
fn http_error(&mut self, &hyper::Error) -> Retry {
Retry::Abort
}
/// Called whenever there is the need for your applications API key after
/// the official authenticator implementation didn't provide one, for some reason.
/// If this method returns None as well, the underlying operation will fail
fn api_key(&mut self) -> Option<String> {
None
}
/// Called whenever the Authenticator didn't yield a token. The delegate
/// may attempt to provide one, or just take it as a general information about the
/// impending failure.
/// The given Error provides information about why the token couldn't be acquired in the
/// first place
fn token(&mut self, err: &error::Error) -> Option<oauth2::Token> {
let _ = err;
None
}
/// Called during resumable uploads to provide a URL for the impending upload.
/// It was saved after a previous call to `store_upload_url(...)`, and if not None,
/// will be used instead of asking the server for a new upload URL.
/// This is useful in case a previous resumable upload was aborted/canceled, but should now
/// be resumed.
/// The returned URL will be used exactly once - if it fails again and the delegate allows
/// to retry, we will ask the server for a new upload URL.
fn upload_url(&mut self) -> Option<String> {
None
}
/// Called after we have retrieved a new upload URL for a resumable upload to store it
/// in case we fail or cancel. That way, we can attempt to resume the upload later,
/// see `upload_url()`.
/// It will also be called with None after a successful upload, which allows the delegate
/// to forget the URL. That way, we will not attempt to resume an upload that has already
/// finished.
fn store_upload_url(&mut self, url: Option<&str>) {
let _ = url;
}
/// Called whenever a server response could not be decoded from json.
/// It's for informational purposes only, the caller will return with an error
/// accordingly.
///
/// # Arguments
///
/// * `json_encoded_value` - The json-encoded value which failed to decode.
/// * `json_decode_error` - The decoder error
fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &json::Error) {
let _ = json_encoded_value;
let _ = json_decode_error;
}
/// Called whenever the http request returns with a non-success status code.
/// This can involve authentication issues, or anything else that very much
/// depends on the used API method.
/// The delegate should check the status, header and decoded json error to decide
/// whether to retry or not. In the latter case, the underlying call will fail.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
fn http_failure(&mut self, _: &hyper::client::Response, Option<JsonServerError>, _: Option<ServerError>) -> Retry {
Retry::Abort
}
/// Called prior to sending the main request of the given method. It can be used to time
/// the call or to print progress information.
/// It's also useful as you can be sure that a request will definitely be made.
fn pre_request(&mut self) { }
/// Return the size of each chunk of a resumable upload.
/// Must be a power of two, with 1<<18 being the smallest allowed chunk size.
/// Will be called once before starting any resumable upload.
fn chunk_size(&mut self) -> u64 {
1 << 23
}
/// Called before the given chunk is uploaded to the server.
/// If true is returned, the upload will be interrupted.
/// However, it may be resumable if you stored the upload URL in a previous call
/// to `store_upload_url()`
fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool {
let _ = chunk;
false
}
/// Called before the API request method returns, in every case. It can be used to clean up
/// internal state between calls to the API.
/// This call always has a matching call to `begin(...)`.
///
/// # Arguments
///
/// * `is_success` - a true value indicates the operation was successful. If false, you should
/// discard all values stored during `store_upload_url`.
fn finished(&mut self, is_success: bool) {
let _ = is_success;
}
}
/// A delegate with a conservative default implementation, which is used if no other delegate is
/// set.
#[derive(Default)]
pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}
#[derive(Debug)]
pub enum Error {
/// The http connection failed
HttpError(hyper::Error),
/// An attempt was made to upload a resource with size stored in field `.0`
/// even though the maximum upload size is what is stored in field `.1`.
UploadSizeLimitExceeded(u64, u64),
/// Represents information about a request that was not understood by the server.
/// Details are included.
BadRequest(ErrorResponse),
/// We needed an API key for authentication, but didn't obtain one.
/// Neither through the authenticator, nor through the Delegate.
MissingAPIKey,
/// We required a Token, but didn't get one from the Authenticator
MissingToken(Box<error::Error>),
/// The delgate instructed to cancel the operation
Cancelled,
/// An additional, free form field clashed with one of the built-in optional ones
FieldClash(&'static str),
/// Shows that we failed to decode the server response.
/// This can happen if the protocol changes in conjunction with strict json decoding.
JsonDecodeError(String, json::Error),
/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref err) => err.fmt(f),
Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) =>
writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}"
, resource_size, max_size),
Error::MissingAPIKey => {
(writeln!(f, "The application's API key was not found in the configuration")).ok();
writeln!(f, "It is used as there are no Scopes defined for this method.")
},
Error::BadRequest(ref err) => {
try!(writeln!(f, "Bad Request ({}): {}", err.error.code, err.error.message));
for err in err.error.errors.iter() {
try!(writeln!(f, " {}: {}, {}{}",
err.domain,
err.message,
err.reason,
match &err.location {
&Some(ref loc) => format!("@{}", loc),
&None => String::new(),
}));
}
Ok(())
},
Error::MissingToken(ref err) =>
writeln!(f, "Token retrieval failed with error: {}", err),
Error::Cancelled =>
writeln!(f, "Operation cancelled by delegate"),
Error::FieldClash(field) =>
writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field),
Error::JsonDecodeError(ref json_str, ref err)
=> writeln!(f, "{}: {}", err, json_str),
Error::Failure(ref response) =>
writeln!(f, "Http status indicates failure: {:?}", response),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::HttpError(ref err) => err.description(),
Error::JsonDecodeError(_, ref err) => err.description(),
_ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead"
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::HttpError(ref err) => err.cause(),
Error::JsonDecodeError(_, ref err) => err.cause(),
_ => None
}
}
}
/// A universal result type used as return for all calls.
pub type Result<T> = std::result::Result<T, Error>;
/// Contains information about an API request.
pub struct MethodInfo {
pub id: &'static str,
pub http_method: Method,
}
const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d";
/// Provides a `Read` interface that converts multiple parts into the protocol
/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387).
/// **Note**: This implementation is just as rich as it needs to be to perform uploads
/// to google APIs, and might not be a fully-featured implementation.
#[derive(Default)]
pub struct MultiPartReader<'a> {
raw_parts: Vec<(Headers, &'a mut Read)>,
current_part: Option<(Cursor<Vec<u8>>, &'a mut Read)>,
last_part_boundary: Option<Cursor<Vec<u8>>>,
}
impl<'a> MultiPartReader<'a> {
/// Reserve memory for exactly the given amount of parts
pub fn reserve_exact(&mut self, cap: usize) {
self.raw_parts.reserve_exact(cap);
}
/// Add a new part to the queue of parts to be read on the first `read` call.
///
/// # Arguments
///
/// `headers` - identifying the body of the part. It's similar to the header
/// in an ordinary single-part call, and should thus contain the
/// same information.
/// `reader` - a reader providing the part's body
/// `size` - the amount of bytes provided by the reader. It will be put onto the header as
/// content-size.
/// `mime` - It will be put onto the content type
pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> {
let mut headers = Headers::new();
headers.set(ContentType(mime_type));
headers.set(ContentLength(size));
self.raw_parts.push((headers, reader));
self
}
/// Returns the mime-type representing our multi-part message.
/// Use it with the ContentType header.
pub fn mime_type(&self) -> Mime {
Mime(
TopLevel::Multipart,
SubLevel::Ext("Related".to_string()),
vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))],
)
}
/// Returns true if we are totally used
fn is_depleted(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none()
}
/// Returns true if we are handling our last part
fn is_last_part(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_some()
}
}
impl<'a> Read for MultiPartReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.raw_parts.len(),
self.current_part.is_none(),
self.last_part_boundary.is_none()) {
(_, _, false) => {
let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0);
if br < buf.len() {
self.last_part_boundary = None;
}
return Ok(br)
},
(0, true, true) => return Ok(0),
(n, true, _) if n > 0 => {
let (headers, reader) = self.raw_parts.remove(0);
let mut c = Cursor::new(Vec::<u8>::new());
(write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING,
headers, LINE_ENDING)).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
self.current_part = Some((c, reader));
}
_ => {},
}
// read headers as long as possible
let (hb, rr) = {
let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap();
let b = c.read(buf).unwrap_or(0);
(b, reader.read(&mut buf[b..]))
};
match rr {
Ok(bytes_read) => {
if hb < buf.len() && bytes_read == 0 {
if self.is_last_part() {
// before clearing the last part, we will add the boundary that
// will be written last
self.last_part_boundary = Some(Cursor::new(
format!("{}--{}--", LINE_ENDING, BOUNDARY).into_bytes()))
}
// We are depleted - this can trigger the next part to come in
self.current_part = None;
}
let mut total_bytes_read = hb + bytes_read;
while total_bytes_read < buf.len() && !self.is_depleted() {
match self.read(&mut buf[total_bytes_read ..]) {
Ok(br) => total_bytes_read += br,
Err(err) => return Err(err),
}
}
Ok(total_bytes_read)
}
Err(err) => {
// fail permanently
self.current_part = None;
self.last_part_boundary = None;
self.raw_parts.clear();
Err(err)
}
}
}
}
/// The `X-Upload-Content-Type` header.
///
/// Generated via rustc --pretty expanded -Z unstable-options, and manually
/// processed to be more readable.
#[derive(PartialEq, Debug, Clone)]
pub struct XUploadContentType(pub Mime);
impl ::std::ops::Deref for XUploadContentType {
type Target = Mime;
fn deref<'a>(&'a self) -> &'a Mime { &self.0 }
}
impl ::std::ops::DerefMut for XUploadContentType {
fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 }
}
impl Header for XUploadContentType {
fn header_name() -> &'static str { "X-Upload-Content-Type" }
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType)
}
}
impl HeaderFormat for XUploadContentType {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&**self, f)
}
}
impl Display for XUploadContentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chunk {
pub first: u64,
pub last: u64
}
impl fmt::Display for Chunk {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(write!(fmt, "{}-{}", self.first, self.last)).ok();
Ok(())
}
}
impl FromStr for Chunk {
type Err = &'static str;
/// NOTE: only implements `%i-%i`, not `*`
fn from_str(s: &str) -> std::result::Result<Chunk, &'static str> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 2 {
return Err("Expected two parts: %i-%i")
}
Ok(
Chunk {
first: match FromStr::from_str(parts[0]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'first' as digit")
},
last: match FromStr::from_str(parts[1]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'last' as digit")
}
}
)
}
}
/// Implements the Content-Range header, for serialization only
#[derive(Clone, PartialEq, Debug)]
pub struct ContentRange {
pub range: Option<Chunk>,
pub total_length: u64,
}
impl Header for ContentRange {
fn header_name() -> &'static str {
"Content-Range"
}
/// We are not parsable, as parsing is done by the `Range` header
fn parse_header(_: &[Vec<u8>]) -> hyper::error::Result<Self> {
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for ContentRange {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("bytes "));
match self.range {
Some(ref c) => try!(c.fmt(fmt)),
None => try!(fmt.write_str("*"))
}
(write!(fmt, "/{}", self.total_length)).ok();
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct RangeResponseHeader(pub Chunk);
impl Header for RangeResponseHeader {
fn header_name() -> &'static str {
"Range"
}
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
if raw.len() > 0 {
let v = &raw[0];
if let Ok(s) = std::str::from_utf8(v) {
const PREFIX: &'static str = "bytes ";
if s.starts_with(PREFIX) {
if let Ok(c) = <Chunk as FromStr>::from_str(&s[PREFIX.len()..]) {
return Ok(RangeResponseHeader(c))
}
}
}
}
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for RangeResponseHeader {
/// No implmentation necessary, we just need to parse
fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
/// A utility type to perform a resumable upload from start to end.
pub struct ResumableUploadHelper<'a, A: 'a> {
pub client: &'a mut hyper::client::Client,
pub delegate: &'a mut Delegate,
pub start_at: Option<u64>,
pub auth: &'a mut A,
pub user_agent: &'a str,
pub auth_header: Authorization<Bearer>,
pub url: &'a str,
pub reader: &'a mut ReadSeek,
pub media_type: Mime,
pub content_length: u64
}
impl<'a, A> ResumableUploadHelper<'a, A>
where A: oauth2::GetToken {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::Result<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
.header(ContentRange { range: None, total_length: self.content_length })
.header(self.auth_header.clone())
.send() {
Ok(r) => {
// 308 = resume-incomplete == PermanentRedirect
let headers = r.headers.clone();
let h: &RangeResponseHeader = match headers.get() {
Some(hh) if r.status == StatusCode::PermanentRedirect => hh,
None|Some(_) => {
if let Retry::After(d) = self.delegate.http_failure(&r, None, None) {
sleep(d);
continue;
}
return Err(Ok(r))
}
};
return Ok(h.0.last)
}
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Err(Err(err))
}
}
}
}
/// returns None if operation was cancelled by delegate, or the HttpResult.
/// It can be that we return the result just because we didn't understand the status code -
/// caller should check for status himself before assuming it's OK to use
pub fn upload(&mut self) -> Option<hyper::Result<hyper::client::Response>> {
let mut start = match self.start_at {
Some(s) => s,
None => match self.query_transfer_status() {
Ok(s) => s,
Err(result) => return Some(result)
}
};
const MIN_CHUNK_SIZE: u64 = 1 << 18;
let chunk_size = match self.delegate.chunk_size() {
cs if cs > MIN_CHUNK_SIZE => cs,
_ => MIN_CHUNK_SIZE
};
self.reader.seek(SeekFrom::Start(start)).unwrap();
loop {
let request_size = match self.content_length - start {
rs if rs > chunk_size => chunk_size,
rs => rs
};
let mut section_reader = self.reader.take(request_size);
let range_header = ContentRange {
range: Some(Chunk {first: start, last: start + request_size - 1}),
total_length: self.content_length
};
start += request_size;
if self.delegate.cancel_chunk_upload(&range_header) {
return None
}
let res = self.client.post(self.url)
.header(range_header)
.header(ContentType(self.media_type.clone()))
.header(UserAgent(self.user_agent.to_string()))
.body(&mut section_reader)
.send();
match res {
Ok(mut res) => {
if res.status == StatusCode::PermanentRedirect {
continue
}
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let Retry::After(d) = self.delegate.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
}
return Some(Ok(res))
},
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Some(Err(err))
}
}
}
}
}
// Copy of src/rust/cli/cmn.rs
// TODO(ST): Allow sharing common code between program types
pub fn remove_json_null_values(value: &mut json::value::Value) {
match *value {
json::value::Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-cloudbuild1-cli"
version = "1.0.7+20171205"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with Cloud Build (protocol v1)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudbuild1-cli"
homepage = "https://cloud.google.com/container-builder/docs/"
documentation = "http://byron.github.io/google-apis-rs/google_cloudbuild1_cli"
license = "MIT"
keywords = ["cloudbuild", "google", "cli"]
[[bin]]
name = "cloudbuild1"
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
strsim = "^0.5"
hyper-rustls = "^0.6"
yup-hyper-mock = "^2.0"
clap = "^2.0"
[features]
[dependencies.google-cloudbuild1]
path = "../cloudbuild1"
version = "1.0.7+20171205"

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,128 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/cli/README.md.mako'
DO NOT EDIT !
-->
The `cloudbuild1` command-line interface *(CLI)* allows to use most features of the *Google Cloud Build* service from the comfort of your terminal.
By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's
capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero.
If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools.
Everything else about the *Cloud Build* API can be found at the
[official documentation site](https://cloud.google.com/container-builder/docs/).
# Installation and Source Code
Install the command-line interface with cargo using:
```bash
cargo install google-cloudbuild1-cli
```
Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/cloudbuild1-cli).
# Usage
This documentation was generated from the *Cloud Build* API at revision *20171205*. The CLI is at version *1.0.7*.
```bash
cloudbuild1 [options]
operations
cancel <name> (-r <kv>)... [-p <v>]... [-o <out>]
get <name> [-p <v>]... [-o <out>]
list <name> [-p <v>]... [-o <out>]
projects
builds-cancel <project-id> <id> (-r <kv>)... [-p <v>]... [-o <out>]
builds-create <project-id> (-r <kv>)... [-p <v>]... [-o <out>]
builds-get <project-id> <id> [-p <v>]... [-o <out>]
builds-list <project-id> [-p <v>]... [-o <out>]
builds-retry <project-id> <id> (-r <kv>)... [-p <v>]... [-o <out>]
triggers-create <project-id> (-r <kv>)... [-p <v>]... [-o <out>]
triggers-delete <project-id> <trigger-id> [-p <v>]... [-o <out>]
triggers-get <project-id> <trigger-id> [-p <v>]... [-o <out>]
triggers-list <project-id> [-p <v>]... [-o <out>]
triggers-patch <project-id> <trigger-id> (-r <kv>)... [-p <v>]... [-o <out>]
triggers-run <project-id> <trigger-id> (-r <kv>)... [-p <v>]... [-o <out>]
cloudbuild1 --help
Configuration:
[--scope <url>]...
Specify the authentication a method should be executed in. Each scope
requires the user to grant this application permission to use it.
If unset, it defaults to the shortest scope url for a particular method.
--config-dir <folder>
A directory into which we will store our persistent data. Defaults to
a user-writable directory that we will create during the first invocation.
[default: ~/.google-service-cli]
--debug
Output all server communication to standard error. `tx` and `rx` are placed
into the same stream.
--debug-auth
Output all communication related to authentication to standard error. `tx`
and `rx` are placed into the same stream.
```
# Configuration
The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `cloudbuild1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis.
More information about the various kinds of persistent data are given in the following paragraphs.
# Authentication
Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the
set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*.
If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a
method that is read-only, it will ask only for a read-only scope.
You may use the `--scope` flag to specify a scope directly.
All applicable scopes are documented in the respective method's CLI documentation.
The first time a scope is used, the user is asked for permission. Follow the instructions given
by the CLI to grant permissions, or to decline.
If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration
directory, e.g. `~/.google-service-cli/cloudbuild1-token-<scope-hash>.json`. No manual management of these tokens
is necessary.
To revoke granted authentication, please refer to the [official documentation][revoke-access].
# Application Secrets
In order to allow any application to use Google services, it will need to be registered using the
[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it
one by one. Most APIs can be used for free and have a daily quota.
To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI
comes with a default application secret that is configured accordingly. This also means that heavy usage
all around the world may deplete the daily quota.
You can workaround this limitation by putting your own secrets file at this location:
`~/.google-service-cli/cloudbuild1-secret.json`, assuming that the required *cloudbuild* API
was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at
*APIs & auth -> Credentials -> Download JSON* and used as is.
Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new].
# Debugging
Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know
what exactly led to a particular issue. This is done by allowing all client-server communication to be
output to standard error *as-is*.
The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag
will cause all communication related to authentication to standard error.
If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the
issue at hand.
You may consider redirecting standard error into a file for ease of use, e.g. `cloudbuild1 --debug <resource> <method> [options] 2>debug.txt`.
[scopes]: https://developers.google.com/+/api/oauth#scopes
[revoke-access]: http://webapps.stackexchange.com/a/30849
[google-dev-console]: https://console.developers.google.com/
[google-project-new]: https://developers.google.com/console/help/new/

View File

@@ -0,0 +1,30 @@
site_name: Cloud Build v1.0.7+20171205
site_url: http://byron.github.io/google-apis-rs/google-cloudbuild1-cli
site_description: A complete library to interact with Cloud Build (protocol v1)
repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/cloudbuild1-cli
docs_dir: docs
site_dir: build_html
pages:
- ['index.md', 'Home']
- ['operations_cancel.md', 'Operations', 'Cancel']
- ['operations_get.md', 'Operations', 'Get']
- ['operations_list.md', 'Operations', 'List']
- ['projects_builds-cancel.md', 'Projects', 'Builds Cancel']
- ['projects_builds-create.md', 'Projects', 'Builds Create']
- ['projects_builds-get.md', 'Projects', 'Builds Get']
- ['projects_builds-list.md', 'Projects', 'Builds List']
- ['projects_builds-retry.md', 'Projects', 'Builds Retry']
- ['projects_triggers-create.md', 'Projects', 'Triggers Create']
- ['projects_triggers-delete.md', 'Projects', 'Triggers Delete']
- ['projects_triggers-get.md', 'Projects', 'Triggers Get']
- ['projects_triggers-list.md', 'Projects', 'Triggers List']
- ['projects_triggers-patch.md', 'Projects', 'Triggers Patch']
- ['projects_triggers-run.md', 'Projects', 'Triggers Run']
theme: readthedocs
copyright: Copyright &copy; 2015-2016, `Sebastian Thiel`

View File

@@ -0,0 +1,799 @@
// COPY OF 'src/rust/cli/cmn.rs'
// DO NOT EDIT
use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token};
use serde_json as json;
use serde_json::value::Value;
use mime::Mime;
use clap::{App, SubCommand};
use strsim;
use std::fs;
use std::env;
use std::io;
use std::error::Error as StdError;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
use std::io::{Write, Read, stdout};
use std::default::Default;
const FIELD_SEP: char = '.';
pub enum ComplexType {
Pod,
Vec,
Map,
}
// Null,
// Bool(bool),
// I64(i64),
// U64(u64),
// F64(f64),
// String(String),
pub enum JsonType {
Boolean,
Int,
Uint,
Float,
String,
}
pub struct JsonTypeInfo {
pub jtype: JsonType,
pub ctype: ComplexType,
}
// Based on @erickt user comment. Thanks for the idea !
// Remove all keys whose values are null from given value (changed in place)
pub fn remove_json_null_values(value: &mut Value) {
match *value {
Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}
fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> {
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values {
let confidence = strsim::jaro_winkler(v, pv);
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
}
pub enum CallType {
Upload(UploadProtocol),
Standard,
}
arg_enum!{
pub enum UploadProtocol {
Simple,
Resumable
}
}
impl AsRef<str> for UploadProtocol {
fn as_ref(&self) -> &str {
match *self {
UploadProtocol::Simple => "simple",
UploadProtocol::Resumable => "resumable",
}
}
}
impl AsRef<str> for CallType {
fn as_ref(&self) -> &str {
match *self {
CallType::Upload(ref proto) => proto.as_ref(),
CallType::Standard => "standard-request",
}
}
}
#[derive(Clone, Default)]
pub struct FieldCursor(Vec<String>);
impl ToString for FieldCursor {
fn to_string(&self) -> String {
self.0.join(".")
}
}
impl From<&'static str> for FieldCursor {
fn from(value: &'static str) -> FieldCursor {
let mut res = FieldCursor::default();
res.set(value).unwrap();
res
}
}
fn assure_entry<'a, 'b>(m: &'a mut json::Map<String, Value>, k: &'b String) -> &'a mut Value {
if m.contains_key(k) {
return m.get_mut(k).expect("value to exist");
}
m.insert(k.to_owned(), Value::Object(Default::default()));
m.get_mut(k).expect("value to exist")
}
impl FieldCursor {
pub fn set(&mut self, value: &str) -> Result<(), CLIError> {
if value.len() == 0 {
return Err(CLIError::Field(FieldError::Empty));
}
let mut first_is_field_sep = false;
let mut char_count: usize = 0;
let mut last_c = FIELD_SEP;
let mut num_conscutive_field_seps = 0;
let mut field = String::new();
let mut fields = self.0.clone();
let push_field = |fs: &mut Vec<String>, f: &mut String| {
if f.len() > 0 {
fs.push(f.clone());
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
char_count += 1;
if c == FIELD_SEP {
if cid == 0 {
first_is_field_sep = true;
}
num_conscutive_field_seps += 1;
if cid > 0 && last_c == FIELD_SEP {
if fields.pop().is_none() {
return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string())));
}
} else {
push_field(&mut fields, &mut field);
}
} else {
num_conscutive_field_seps = 0;
if cid == 1 {
if first_is_field_sep {
fields.truncate(0);
}
}
field.push(c);
}
last_c = c;
}
push_field(&mut fields, &mut field);
if char_count == 1 && first_is_field_sep {
fields.truncate(0);
}
if char_count > 1 && num_conscutive_field_seps == 1 {
return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string())));
}
self.0 = fields;
Ok(())
}
pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option<String> {
if value.len() == 0 {
return None;
}
let mut last_c = FIELD_SEP;
let mut field = String::new();
let mut output = String::new();
let push_field = |fs: &mut String, f: &mut String| {
if f.len() > 0 {
fs.push_str(match did_you_mean(&f, possible_values) {
Some(candidate) => candidate,
None => &f,
});
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
if c == FIELD_SEP {
if last_c != FIELD_SEP {
push_field(&mut output, &mut field);
}
output.push(c);
} else {
field.push(c);
}
last_c = c;
}
push_field(&mut output, &mut field);
if &output == value {
None
} else {
Some(output)
}
}
pub fn set_json_value(&self,
mut object: &mut Value,
value: &str,
type_info: JsonTypeInfo,
err: &mut InvalidOptionsError,
orig_cursor: &FieldCursor) {
assert!(self.0.len() > 0);
for field in &self.0[..self.0.len() - 1] {
let tmp = object;
object = match *tmp {
Value::Object(ref mut mapping) => {
assure_entry(mapping, &field)
}
_ => panic!("We don't expect non-object Values here ..."),
};
}
match *object {
Value::Object(ref mut mapping) => {
let field = &self.0[self.0.len() - 1];
let to_jval = |value: &str,
jtype: JsonType,
err: &mut InvalidOptionsError|
-> Value {
match jtype {
JsonType::Boolean =>
Value::Bool(arg_from_str(value, err, &field, "boolean")),
JsonType::Int =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"int"))
.expect("valid f64")),
JsonType::Uint =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"uint"))
.expect("valid f64")),
JsonType::Float =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"float"))
.expect("valid f64")),
JsonType::String => Value::String(value.to_owned()),
}
};
match type_info.ctype {
ComplexType::Pod => {
if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err))
.is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
ComplexType::Vec => {
match *assure_entry(mapping, field) {
Value::Array(ref mut values) =>
values.push(to_jval(value, type_info.jtype, err)),
_ => unreachable!(),
}
}
ComplexType::Map => {
let (key, value) = parse_kv_arg(value, err, true);
let jval = to_jval(value.unwrap_or(""), type_info.jtype, err);
match *assure_entry(mapping, &field) {
Value::Object(ref mut value_map) => {
if value_map.insert(key.to_owned(), jval).is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
_ => unreachable!(),
}
}
}
}
_ => unreachable!(),
}
}
pub fn num_fields(&self) -> usize {
self.0.len()
}
}
pub fn parse_kv_arg<'a>(kv: &'a str,
err: &mut InvalidOptionsError,
for_hashmap: bool)
-> (&'a str, Option<&'a str>) {
let mut add_err = || {
err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(), for_hashmap))
};
match kv.find('=') {
None => {
add_err();
return (kv, None);
}
Some(pos) => {
let key = &kv[..pos];
if kv.len() <= pos + 1 {
add_err();
return (key, Some(""));
}
(key, Some(&kv[pos + 1..]))
}
}
}
pub fn calltype_from_str(name: &str,
valid_protocols: Vec<String>,
err: &mut InvalidOptionsError)
-> CallType {
CallType::Upload(match UploadProtocol::from_str(name) {
Ok(up) => up,
Err(msg) => {
err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols));
UploadProtocol::Simple
}
})
}
pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option<fs::File> {
match fs::File::open(file_path) {
Ok(f) => Some(f),
Err(io_err) => {
err.issues.push(CLIError::Input(InputError::Io((file_path.to_string(), io_err))));
None
}
}
}
pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option<Mime> {
match mime.parse() {
Ok(m) => Some(m),
Err(_) => {
err.issues.push(CLIError::Input(InputError::Mime(mime.to_string())));
None
}
}
}
pub fn writer_from_opts(arg: Option<&str>) -> Result<Box<Write>, io::Error> {
let f = arg.unwrap_or("-");
match f {
"-" => Ok(Box::new(stdout())),
_ => match fs::OpenOptions::new().create(true).write(true).open(f) {
Ok(f) => Ok(Box::new(f)),
Err(io_err) => Err(io_err),
},
}
}
pub fn arg_from_str<'a, T>(arg: &str,
err: &mut InvalidOptionsError,
arg_name: &'a str,
arg_type: &'a str)
-> T
where T: FromStr + Default,
<T as FromStr>::Err: fmt::Display
{
match FromStr::from_str(arg) {
Err(perr) => {
err.issues.push(CLIError::ParseError(arg_name.to_owned(),
arg_type.to_owned(),
arg.to_string(),
format!("{}", perr)));
Default::default()
}
Ok(v) => v,
}
}
pub struct JsonTokenStorage {
pub program_name: &'static str,
pub db_dir: String,
}
impl JsonTokenStorage {
fn path(&self, scope_hash: u64) -> PathBuf {
Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash))
}
}
#[derive(Debug)]
pub enum TokenStorageError {
Json(json::Error),
Io(io::Error),
}
impl fmt::Display for TokenStorageError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
TokenStorageError::Json(ref err) => writeln!(f, "Could not serialize secrets: {}", err),
TokenStorageError::Io(ref err) => writeln!(f, "Failed to write secret token: {}", err),
}
}
}
impl StdError for TokenStorageError {
fn description(&self) -> &str {
"Failure when getting or setting the token storage"
}
}
impl TokenStorage for JsonTokenStorage {
type Error = TokenStorageError;
// NOTE: logging might be interesting, currently we swallow all errors
fn set(&mut self,
scope_hash: u64,
_: &Vec<&str>,
token: Option<Token>)
-> Result<(), TokenStorageError> {
match token {
None => {
match fs::remove_file(self.path(scope_hash)) {
Err(err) => match err.kind() {
io::ErrorKind::NotFound => Ok(()),
_ => Err(TokenStorageError::Io(err)),
},
Ok(_) => Ok(()),
}
}
Some(token) => {
match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) {
Ok(mut f) => {
match json::to_writer_pretty(&mut f, &token) {
Ok(_) => Ok(()),
Err(serde_err) => Err(TokenStorageError::Json(serde_err)),
}
}
Err(io_err) => Err(TokenStorageError::Io(io_err)),
}
}
}
}
fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result<Option<Token>, TokenStorageError> {
match fs::File::open(&self.path(scope_hash)) {
Ok(f) => {
match json::de::from_reader(f) {
Ok(token) => Ok(Some(token)),
Err(err) => Err(TokenStorageError::Json(err)),
}
}
Err(io_err) => {
match io_err.kind() {
io::ErrorKind::NotFound => Ok(None),
_ => Err(TokenStorageError::Io(io_err)),
}
}
}
}
}
#[derive(Debug)]
pub enum ApplicationSecretError {
DecoderError((String, json::Error)),
FormatError(String),
}
impl fmt::Display for ApplicationSecretError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ApplicationSecretError::DecoderError((ref path, ref err)) =>
writeln!(f,
"Could not decode file at '{}' with error: {}.",
path,
err),
ApplicationSecretError::FormatError(ref path) =>
writeln!(f,
"'installed' field is unset in secret file at '{}'.",
path),
}
}
}
#[derive(Debug)]
pub enum ConfigurationError {
DirectoryCreationFailed((String, io::Error)),
DirectoryUnset,
HomeExpansionFailed(String),
Secret(ApplicationSecretError),
Io((String, io::Error)),
}
impl fmt::Display for ConfigurationError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) =>
writeln!(f,
"Directory '{}' could not be created with error: {}.",
dir,
err),
ConfigurationError::DirectoryUnset => writeln!(f, "--config-dir was unset or empty."),
ConfigurationError::HomeExpansionFailed(ref dir) =>
writeln!(f,
"Couldn't find HOME directory of current user, failed to expand '{}'.",
dir),
ConfigurationError::Secret(ref err) => writeln!(f, "Secret -> {}", err),
ConfigurationError::Io((ref path, ref err)) =>
writeln!(f,
"IO operation failed on path '{}' with error: {}.",
path,
err),
}
}
}
#[derive(Debug)]
pub enum InputError {
Io((String, io::Error)),
Mime(String),
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
InputError::Io((ref file_path, ref io_err)) =>
writeln!(f,
"Failed to open '{}' for reading with error: {}.",
file_path,
io_err),
InputError::Mime(ref mime) => writeln!(f, "'{}' is not a known mime-type.", mime),
}
}
}
#[derive(Debug)]
pub enum FieldError {
PopOnEmpty(String),
TrailingFieldSep(String),
Unknown(String, Option<String>, Option<String>),
Duplicate(String),
Empty,
}
impl fmt::Display for FieldError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
FieldError::PopOnEmpty(ref field) =>
writeln!(f, "'{}': Cannot move up on empty field cursor.", field),
FieldError::TrailingFieldSep(ref field) =>
writeln!(f,
"'{}': Single field separator may not be last character.",
field),
FieldError::Unknown(ref field, ref suggestion, ref value) => {
let suffix = match *suggestion {
Some(ref s) => {
let kv = match *value {
Some(ref v) => format!("{}={}", s, v),
None => s.clone(),
};
format!(" Did you mean '{}' ?", kv)
}
None => String::new(),
};
writeln!(f, "Field '{}' does not exist.{}", field, suffix)
}
FieldError::Duplicate(ref cursor) =>
writeln!(f, "Value at '{}' was already set", cursor),
FieldError::Empty => writeln!(f, "Field names must not be empty."),
}
}
}
#[derive(Debug)]
pub enum CLIError {
Configuration(ConfigurationError),
ParseError(String, String, String, String),
UnknownParameter(String, Vec<&'static str>),
InvalidUploadProtocol(String, Vec<String>),
InvalidKeyValueSyntax(String, bool),
Input(InputError),
Field(FieldError),
MissingCommandError,
MissingMethodError(String),
}
impl fmt::Display for CLIError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err),
CLIError::Input(ref err) => write!(f, "Input -> {}", err),
CLIError::Field(ref err) => write!(f, "Field -> {}", err),
CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) =>
writeln!(f,
"'{}' is not a valid upload protocol. Choose from one of {}.",
proto_name,
valid_names.join(", ")),
CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) =>
writeln!(f,
"Failed to parse argument '{}' with value '{}' as {} with error: {}.",
arg_name,
value,
type_name,
err_desc),
CLIError::UnknownParameter(ref param_name, ref possible_values) => {
let suffix = match did_you_mean(param_name, &possible_values) {
Some(v) => format!(" Did you mean '{}' ?", v),
None => String::new(),
};
write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix)
}
CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => {
let hashmap_info = if is_hashmap {
"hashmap "
} else {
""
};
writeln!(f,
"'{}' does not match {}pattern <key>=<value>.",
kv,
hashmap_info)
}
CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."),
CLIError::MissingMethodError(ref cmd) =>
writeln!(f,
"Please specify the method to call on the '{}' command.",
cmd),
}
}
}
#[derive(Debug)]
pub struct InvalidOptionsError {
pub issues: Vec<CLIError>,
pub exit_code: i32,
}
impl fmt::Display for InvalidOptionsError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for issue in &self.issues {
try!(issue.fmt(f));
}
Ok(())
}
}
impl InvalidOptionsError {
pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError {
InvalidOptionsError {
issues: vec![err],
exit_code: exit_code,
}
}
pub fn new() -> InvalidOptionsError {
InvalidOptionsError {
issues: Vec::new(),
exit_code: 1,
}
}
}
pub fn assure_config_dir_exists(dir: &str) -> Result<String, CLIError> {
let trdir = dir.trim();
if trdir.len() == 0 {
return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset));
}
let expanded_config_dir = if trdir.as_bytes()[0] == b'~' {
match env::var("HOME").ok().or(env::var("UserProfile").ok()) {
None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))),
Some(mut user) => {
user.push_str(&trdir[1..]);
user
}
}
} else {
trdir.to_string()
};
if let Err(err) = fs::create_dir(&expanded_config_dir) {
if err.kind() != io::ErrorKind::AlreadyExists {
return Err(CLIError::Configuration(
ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err))));
}
}
Ok(expanded_config_dir)
}
pub fn application_secret_from_directory(dir: &str,
secret_basename: &str,
json_console_secret: &str)
-> Result<ApplicationSecret, CLIError> {
let secret_path = Path::new(dir).join(secret_basename);
let secret_str = || secret_path.as_path().to_str().unwrap().to_string();
let secret_io_error = |io_err: io::Error| {
Err(CLIError::Configuration(ConfigurationError::Io((secret_str(), io_err))))
};
for _ in 0..2 {
match fs::File::open(&secret_path) {
Err(mut err) => {
if err.kind() == io::ErrorKind::NotFound {
// Write our built-in one - user may adjust the written file at will
err = match fs::OpenOptions::new()
.create(true)
.write(true)
.open(&secret_path) {
Err(cfe) => cfe,
Ok(mut f) => {
// Assure we convert 'ugly' json string into pretty one
let console_secret: ConsoleApplicationSecret =
json::from_str(json_console_secret).unwrap();
match json::to_writer_pretty(&mut f, &console_secret) {
Err(serde_err) =>
panic!("Unexpected serde error: {:#?}", serde_err),
Ok(_) => continue,
}
}
};
// fall through to IO error handling
}
return secret_io_error(err);
}
Ok(f) => {
match json::de::from_reader::<_, ConsoleApplicationSecret>(f) {
Err(json_err) =>
return Err(CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::DecoderError(
(secret_str(), json_err)
)))),
Ok(console_secret) => match console_secret.installed {
Some(secret) => return Ok(secret),
None => return Err(
CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::FormatError(secret_str())
))),
},
}
}
}
}
unreachable!();
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,31 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-cloudbuild1"
version = "1.0.7+20171205"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with Cloud Build (protocol v1)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudbuild1"
homepage = "https://cloud.google.com/container-builder/docs/"
documentation = "https://docs.rs/google-cloudbuild1/1.0.7+20171205"
license = "MIT"
keywords = ["cloudbuild", "google", "protocol", "web", "api"]
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
url = "= 0.5"
[features]

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

184
gen/cloudbuild1/README.md Normal file
View File

@@ -0,0 +1,184 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/api/README.md.mako'
DO NOT EDIT !
-->
The `google-cloudbuild1` library allows access to all features of the *Google Cloud Build* service.
This documentation was generated from *Cloud Build* crate version *1.0.7+20171205*, where *20171205* is the exact revision of the *cloudbuild:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.7*.
Everything else about the *Cloud Build* *v1* API can be found at the
[official documentation site](https://cloud.google.com/container-builder/docs/).
# Features
Handle the following *Resources* with ease from the central [hub](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.CloudBuild.html) ...
* [operations](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.Operation.html)
* [*cancel*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.OperationCancelCall.html), [*get*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.OperationGetCall.html) and [*list*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.OperationListCall.html)
* projects
* [*builds cancel*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.ProjectBuildCancelCall.html), [*builds create*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.ProjectBuildCreateCall.html), [*builds get*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.ProjectBuildGetCall.html), [*builds list*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.ProjectBuildListCall.html), [*builds retry*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.ProjectBuildRetryCall.html), [*triggers create*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.ProjectTriggerCreateCall.html), [*triggers delete*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.ProjectTriggerDeleteCall.html), [*triggers get*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.ProjectTriggerGetCall.html), [*triggers list*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.ProjectTriggerListCall.html), [*triggers patch*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.ProjectTriggerPatchCall.html) and [*triggers run*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.ProjectTriggerRunCall.html)
# Structure of this Library
The API is structured into the following primary items:
* **[Hub](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/struct.CloudBuild.html)**
* a central object to maintain state and allow accessing all *Activities*
* creates [*Method Builders*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.MethodsBuilder.html) which in turn
allow access to individual [*Call Builders*](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.CallBuilder.html)
* **[Resources](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.Resource.html)**
* primary types that you can apply *Activities* to
* a collection of properties and *Parts*
* **[Parts](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.Part.html)**
* a collection of properties
* never directly used in *Activities*
* **[Activities](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.CallBuilder.html)**
* operations to apply to *Resources*
All *structures* are marked with applicable traits to further categorize them and ease browsing.
Generally speaking, you can invoke *Activities* like this:
```Rust,ignore
let r = hub.resource().activity(...).doit()
```
Or specifically ...
```ignore
let r = hub.operations().cancel(...).doit()
let r = hub.projects().triggers_run(...).doit()
let r = hub.projects().builds_create(...).doit()
let r = hub.operations().list(...).doit()
let r = hub.operations().get(...).doit()
let r = hub.projects().builds_retry(...).doit()
```
The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
The `doit()` method performs the actual communication with the server and returns the respective result.
# Usage
## Setting up your Project
To use this library, you would put the following lines into your `Cargo.toml` file:
```toml
[dependencies]
google-cloudbuild1 = "*"
```
## A complete example
```Rust
extern crate hyper;
extern crate hyper_rustls;
extern crate yup_oauth2 as oauth2;
extern crate google_cloudbuild1 as cloudbuild1;
use cloudbuild1::{Result, Error};
use std::default::Default;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
use cloudbuild1::CloudBuild;
// Get an ApplicationSecret instance by some means. It contains the `client_id` and
// `client_secret`, among other things.
let secret: ApplicationSecret = Default::default();
// Instantiate the authenticator. It will choose a suitable authentication flow for you,
// unless you replace `None` with the desired Flow.
// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
// retrieve them from storage.
let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
<MemoryStorage as Default>::default(), None);
let mut hub = CloudBuild::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
// You can configure optional parameters by calling the respective setters at will, and
// execute the final call using `doit()`.
// Values shown here are possibly random and not representative !
let result = hub.operations().list("name")
.page_token("sit")
.page_size(-65)
.filter("sed")
.doit();
match result {
Err(e) => match e {
// The Error enum provides details about what exactly happened.
// You can also just use its `Debug`, `Display` or `Error` traits
Error::HttpError(_)
|Error::MissingAPIKey
|Error::MissingToken(_)
|Error::Cancelled
|Error::UploadSizeLimitExceeded(_, _)
|Error::Failure(_)
|Error::BadRequest(_)
|Error::FieldClash(_)
|Error::JsonDecodeError(_, _) => println!("{}", e),
},
Ok(res) => println!("Success: {:?}", res),
}
```
## Handling Errors
All errors produced by the system are provided either as [Result](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/enum.Result.html) enumeration as return value of
the doit() methods, or handed as possibly intermediate results to either the
[Hub Delegate](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.Delegate.html), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html).
When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
makes the system potentially resilient to all kinds of errors.
## Uploads and Downloads
If a method supports downloads, the response body, which is part of the [Result](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/enum.Result.html), should be
read by you to obtain the media.
If such a method also supports a [Response Result](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.ResponseResult.html), it will return that by default.
You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
this call: `.param("alt", "media")`.
Methods supporting uploads can do so using up to 2 different protocols:
*simple* and *resumable*. The distinctiveness of each is represented by customized
`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
## Customization and Callbacks
You may alter the way an `doit()` method is called by providing a [delegate](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.Delegate.html) to the
[Method Builder](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.CallBuilder.html) before making the final `doit()` call.
Respective methods will be called to provide progress information, as well as determine whether the system should
retry on failure.
The [delegate trait](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
## Optional Parts in Server-Requests
All structures provided by this library are made to be [enocodable](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.RequestValue.html) and
[decodable](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
are valid.
Most optionals are are considered [Parts](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.Part.html) which are identifiable by name, which will be sent to
the server to indicate either the set parts of the request or the desired parts in the response.
## Builder Arguments
Using [method builders](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods.
These will always take a single argument, for which the following statements are true.
* [PODs][wiki-pod] are handed by copy
* strings are passed as `&str`
* [request values](https://docs.rs/google-cloudbuild1/1.0.7+20171205/google_cloudbuild1/trait.RequestValue.html) are moved
Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
[google-go-api]: https://github.com/google/google-api-go-client
# License
The **cloudbuild1** library was generated by Sebastian Thiel, and is placed
under the *MIT* license.
You can read the full text at the repository's [license file][repo-license].
[repo-license]: https://github.com/Byron/google-apis-rsblob/master/LICENSE.md

753
gen/cloudbuild1/src/cmn.rs Normal file
View File

@@ -0,0 +1,753 @@
// COPY OF 'src/rust/api/cmn.rs'
// DO NOT EDIT
use std::io::{self, Read, Seek, Cursor, Write, SeekFrom};
use std;
use std::fmt::{self, Display};
use std::str::FromStr;
use std::error;
use std::thread::sleep;
use std::time::Duration;
use mime::{Mime, TopLevel, SubLevel, Attr, Value};
use oauth2::{TokenType, Retry, self};
use hyper;
use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header,
HeaderFormat, Bearer};
use hyper::http::h1::LINE_ENDING;
use hyper::method::Method;
use hyper::status::StatusCode;
use serde_json as json;
/// Identifies the Hub. There is only one per library, this trait is supposed
/// to make intended use more explicit.
/// The hub allows to access all resource methods more easily.
pub trait Hub {}
/// Identifies types for building methods of a particular resource type
pub trait MethodsBuilder {}
/// Identifies types which represent builders for a particular resource method
pub trait CallBuilder {}
/// Identifies types which can be inserted and deleted.
/// Types with this trait are most commonly used by clients of this API.
pub trait Resource {}
/// Identifies types which are used in API responses.
pub trait ResponseResult {}
/// Identifies types which are used in API requests.
pub trait RequestValue {}
/// Identifies types which are not actually used by the API
/// This might be a bug within the google API schema.
pub trait UnusedType {}
/// Identifies types which are only used as part of other types, which
/// usually are carrying the `Resource` trait.
pub trait Part {}
/// Identifies types which are only used by other types internally.
/// They have no special meaning, this trait just marks them for completeness.
pub trait NestedType {}
/// A utility to specify reader types which provide seeking capabilities too
pub trait ReadSeek: Seek + Read {}
impl<T: Seek + Read> ReadSeek for T {}
/// A trait for all types that can convert themselves into a *parts* string
pub trait ToParts {
fn to_parts(&self) -> String;
}
/// A utility type which can decode a server response that indicates error
#[derive(Deserialize)]
pub struct JsonServerError {
pub error: String,
pub error_description: Option<String>
}
/// A utility to represent detailed errors we might see in case there are BadRequests.
/// The latter happen if the sent parameters or request structures are unsound
#[derive(Deserialize, Serialize, Debug)]
pub struct ErrorResponse {
error: ServerError,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerError {
errors: Vec<ServerMessage>,
code: u16,
message: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerMessage {
domain: String,
reason: String,
message: String,
#[serde(rename="locationType")]
location_type: Option<String>,
location: Option<String>
}
#[derive(Copy, Clone)]
pub struct DummyNetworkStream;
impl Read for DummyNetworkStream {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl Write for DummyNetworkStream {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl hyper::net::NetworkStream for DummyNetworkStream {
fn peer_addr(&mut self) -> io::Result<std::net::SocketAddr> {
Ok("127.0.0.1:1337".parse().unwrap())
}
fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
}
/// A trait specifying functionality to help controlling any request performed by the API.
/// The trait has a conservative default implementation.
///
/// It contains methods to deal with all common issues, as well with the ones related to
/// uploading media
pub trait Delegate {
/// Called at the beginning of any API request. The delegate should store the method
/// information if he is interesting in knowing more context when further calls to it
/// are made.
/// The matching `finished()` call will always be made, no matter whether or not the API
/// request was successful. That way, the delegate may easily maintain a clean state
/// between various API calls.
fn begin(&mut self, MethodInfo) {}
/// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
///
/// Return retry information.
fn http_error(&mut self, &hyper::Error) -> Retry {
Retry::Abort
}
/// Called whenever there is the need for your applications API key after
/// the official authenticator implementation didn't provide one, for some reason.
/// If this method returns None as well, the underlying operation will fail
fn api_key(&mut self) -> Option<String> {
None
}
/// Called whenever the Authenticator didn't yield a token. The delegate
/// may attempt to provide one, or just take it as a general information about the
/// impending failure.
/// The given Error provides information about why the token couldn't be acquired in the
/// first place
fn token(&mut self, err: &error::Error) -> Option<oauth2::Token> {
let _ = err;
None
}
/// Called during resumable uploads to provide a URL for the impending upload.
/// It was saved after a previous call to `store_upload_url(...)`, and if not None,
/// will be used instead of asking the server for a new upload URL.
/// This is useful in case a previous resumable upload was aborted/canceled, but should now
/// be resumed.
/// The returned URL will be used exactly once - if it fails again and the delegate allows
/// to retry, we will ask the server for a new upload URL.
fn upload_url(&mut self) -> Option<String> {
None
}
/// Called after we have retrieved a new upload URL for a resumable upload to store it
/// in case we fail or cancel. That way, we can attempt to resume the upload later,
/// see `upload_url()`.
/// It will also be called with None after a successful upload, which allows the delegate
/// to forget the URL. That way, we will not attempt to resume an upload that has already
/// finished.
fn store_upload_url(&mut self, url: Option<&str>) {
let _ = url;
}
/// Called whenever a server response could not be decoded from json.
/// It's for informational purposes only, the caller will return with an error
/// accordingly.
///
/// # Arguments
///
/// * `json_encoded_value` - The json-encoded value which failed to decode.
/// * `json_decode_error` - The decoder error
fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &json::Error) {
let _ = json_encoded_value;
let _ = json_decode_error;
}
/// Called whenever the http request returns with a non-success status code.
/// This can involve authentication issues, or anything else that very much
/// depends on the used API method.
/// The delegate should check the status, header and decoded json error to decide
/// whether to retry or not. In the latter case, the underlying call will fail.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
fn http_failure(&mut self, _: &hyper::client::Response, Option<JsonServerError>, _: Option<ServerError>) -> Retry {
Retry::Abort
}
/// Called prior to sending the main request of the given method. It can be used to time
/// the call or to print progress information.
/// It's also useful as you can be sure that a request will definitely be made.
fn pre_request(&mut self) { }
/// Return the size of each chunk of a resumable upload.
/// Must be a power of two, with 1<<18 being the smallest allowed chunk size.
/// Will be called once before starting any resumable upload.
fn chunk_size(&mut self) -> u64 {
1 << 23
}
/// Called before the given chunk is uploaded to the server.
/// If true is returned, the upload will be interrupted.
/// However, it may be resumable if you stored the upload URL in a previous call
/// to `store_upload_url()`
fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool {
let _ = chunk;
false
}
/// Called before the API request method returns, in every case. It can be used to clean up
/// internal state between calls to the API.
/// This call always has a matching call to `begin(...)`.
///
/// # Arguments
///
/// * `is_success` - a true value indicates the operation was successful. If false, you should
/// discard all values stored during `store_upload_url`.
fn finished(&mut self, is_success: bool) {
let _ = is_success;
}
}
/// A delegate with a conservative default implementation, which is used if no other delegate is
/// set.
#[derive(Default)]
pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}
#[derive(Debug)]
pub enum Error {
/// The http connection failed
HttpError(hyper::Error),
/// An attempt was made to upload a resource with size stored in field `.0`
/// even though the maximum upload size is what is stored in field `.1`.
UploadSizeLimitExceeded(u64, u64),
/// Represents information about a request that was not understood by the server.
/// Details are included.
BadRequest(ErrorResponse),
/// We needed an API key for authentication, but didn't obtain one.
/// Neither through the authenticator, nor through the Delegate.
MissingAPIKey,
/// We required a Token, but didn't get one from the Authenticator
MissingToken(Box<error::Error>),
/// The delgate instructed to cancel the operation
Cancelled,
/// An additional, free form field clashed with one of the built-in optional ones
FieldClash(&'static str),
/// Shows that we failed to decode the server response.
/// This can happen if the protocol changes in conjunction with strict json decoding.
JsonDecodeError(String, json::Error),
/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref err) => err.fmt(f),
Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) =>
writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}"
, resource_size, max_size),
Error::MissingAPIKey => {
(writeln!(f, "The application's API key was not found in the configuration")).ok();
writeln!(f, "It is used as there are no Scopes defined for this method.")
},
Error::BadRequest(ref err) => {
try!(writeln!(f, "Bad Request ({}): {}", err.error.code, err.error.message));
for err in err.error.errors.iter() {
try!(writeln!(f, " {}: {}, {}{}",
err.domain,
err.message,
err.reason,
match &err.location {
&Some(ref loc) => format!("@{}", loc),
&None => String::new(),
}));
}
Ok(())
},
Error::MissingToken(ref err) =>
writeln!(f, "Token retrieval failed with error: {}", err),
Error::Cancelled =>
writeln!(f, "Operation cancelled by delegate"),
Error::FieldClash(field) =>
writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field),
Error::JsonDecodeError(ref json_str, ref err)
=> writeln!(f, "{}: {}", err, json_str),
Error::Failure(ref response) =>
writeln!(f, "Http status indicates failure: {:?}", response),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::HttpError(ref err) => err.description(),
Error::JsonDecodeError(_, ref err) => err.description(),
_ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead"
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::HttpError(ref err) => err.cause(),
Error::JsonDecodeError(_, ref err) => err.cause(),
_ => None
}
}
}
/// A universal result type used as return for all calls.
pub type Result<T> = std::result::Result<T, Error>;
/// Contains information about an API request.
pub struct MethodInfo {
pub id: &'static str,
pub http_method: Method,
}
const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d";
/// Provides a `Read` interface that converts multiple parts into the protocol
/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387).
/// **Note**: This implementation is just as rich as it needs to be to perform uploads
/// to google APIs, and might not be a fully-featured implementation.
#[derive(Default)]
pub struct MultiPartReader<'a> {
raw_parts: Vec<(Headers, &'a mut Read)>,
current_part: Option<(Cursor<Vec<u8>>, &'a mut Read)>,
last_part_boundary: Option<Cursor<Vec<u8>>>,
}
impl<'a> MultiPartReader<'a> {
/// Reserve memory for exactly the given amount of parts
pub fn reserve_exact(&mut self, cap: usize) {
self.raw_parts.reserve_exact(cap);
}
/// Add a new part to the queue of parts to be read on the first `read` call.
///
/// # Arguments
///
/// `headers` - identifying the body of the part. It's similar to the header
/// in an ordinary single-part call, and should thus contain the
/// same information.
/// `reader` - a reader providing the part's body
/// `size` - the amount of bytes provided by the reader. It will be put onto the header as
/// content-size.
/// `mime` - It will be put onto the content type
pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> {
let mut headers = Headers::new();
headers.set(ContentType(mime_type));
headers.set(ContentLength(size));
self.raw_parts.push((headers, reader));
self
}
/// Returns the mime-type representing our multi-part message.
/// Use it with the ContentType header.
pub fn mime_type(&self) -> Mime {
Mime(
TopLevel::Multipart,
SubLevel::Ext("Related".to_string()),
vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))],
)
}
/// Returns true if we are totally used
fn is_depleted(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none()
}
/// Returns true if we are handling our last part
fn is_last_part(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_some()
}
}
impl<'a> Read for MultiPartReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.raw_parts.len(),
self.current_part.is_none(),
self.last_part_boundary.is_none()) {
(_, _, false) => {
let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0);
if br < buf.len() {
self.last_part_boundary = None;
}
return Ok(br)
},
(0, true, true) => return Ok(0),
(n, true, _) if n > 0 => {
let (headers, reader) = self.raw_parts.remove(0);
let mut c = Cursor::new(Vec::<u8>::new());
(write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING,
headers, LINE_ENDING)).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
self.current_part = Some((c, reader));
}
_ => {},
}
// read headers as long as possible
let (hb, rr) = {
let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap();
let b = c.read(buf).unwrap_or(0);
(b, reader.read(&mut buf[b..]))
};
match rr {
Ok(bytes_read) => {
if hb < buf.len() && bytes_read == 0 {
if self.is_last_part() {
// before clearing the last part, we will add the boundary that
// will be written last
self.last_part_boundary = Some(Cursor::new(
format!("{}--{}--", LINE_ENDING, BOUNDARY).into_bytes()))
}
// We are depleted - this can trigger the next part to come in
self.current_part = None;
}
let mut total_bytes_read = hb + bytes_read;
while total_bytes_read < buf.len() && !self.is_depleted() {
match self.read(&mut buf[total_bytes_read ..]) {
Ok(br) => total_bytes_read += br,
Err(err) => return Err(err),
}
}
Ok(total_bytes_read)
}
Err(err) => {
// fail permanently
self.current_part = None;
self.last_part_boundary = None;
self.raw_parts.clear();
Err(err)
}
}
}
}
/// The `X-Upload-Content-Type` header.
///
/// Generated via rustc --pretty expanded -Z unstable-options, and manually
/// processed to be more readable.
#[derive(PartialEq, Debug, Clone)]
pub struct XUploadContentType(pub Mime);
impl ::std::ops::Deref for XUploadContentType {
type Target = Mime;
fn deref<'a>(&'a self) -> &'a Mime { &self.0 }
}
impl ::std::ops::DerefMut for XUploadContentType {
fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 }
}
impl Header for XUploadContentType {
fn header_name() -> &'static str { "X-Upload-Content-Type" }
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType)
}
}
impl HeaderFormat for XUploadContentType {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&**self, f)
}
}
impl Display for XUploadContentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chunk {
pub first: u64,
pub last: u64
}
impl fmt::Display for Chunk {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(write!(fmt, "{}-{}", self.first, self.last)).ok();
Ok(())
}
}
impl FromStr for Chunk {
type Err = &'static str;
/// NOTE: only implements `%i-%i`, not `*`
fn from_str(s: &str) -> std::result::Result<Chunk, &'static str> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 2 {
return Err("Expected two parts: %i-%i")
}
Ok(
Chunk {
first: match FromStr::from_str(parts[0]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'first' as digit")
},
last: match FromStr::from_str(parts[1]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'last' as digit")
}
}
)
}
}
/// Implements the Content-Range header, for serialization only
#[derive(Clone, PartialEq, Debug)]
pub struct ContentRange {
pub range: Option<Chunk>,
pub total_length: u64,
}
impl Header for ContentRange {
fn header_name() -> &'static str {
"Content-Range"
}
/// We are not parsable, as parsing is done by the `Range` header
fn parse_header(_: &[Vec<u8>]) -> hyper::error::Result<Self> {
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for ContentRange {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("bytes "));
match self.range {
Some(ref c) => try!(c.fmt(fmt)),
None => try!(fmt.write_str("*"))
}
(write!(fmt, "/{}", self.total_length)).ok();
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct RangeResponseHeader(pub Chunk);
impl Header for RangeResponseHeader {
fn header_name() -> &'static str {
"Range"
}
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
if raw.len() > 0 {
let v = &raw[0];
if let Ok(s) = std::str::from_utf8(v) {
const PREFIX: &'static str = "bytes ";
if s.starts_with(PREFIX) {
if let Ok(c) = <Chunk as FromStr>::from_str(&s[PREFIX.len()..]) {
return Ok(RangeResponseHeader(c))
}
}
}
}
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for RangeResponseHeader {
/// No implmentation necessary, we just need to parse
fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
/// A utility type to perform a resumable upload from start to end.
pub struct ResumableUploadHelper<'a, A: 'a> {
pub client: &'a mut hyper::client::Client,
pub delegate: &'a mut Delegate,
pub start_at: Option<u64>,
pub auth: &'a mut A,
pub user_agent: &'a str,
pub auth_header: Authorization<Bearer>,
pub url: &'a str,
pub reader: &'a mut ReadSeek,
pub media_type: Mime,
pub content_length: u64
}
impl<'a, A> ResumableUploadHelper<'a, A>
where A: oauth2::GetToken {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::Result<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
.header(ContentRange { range: None, total_length: self.content_length })
.header(self.auth_header.clone())
.send() {
Ok(r) => {
// 308 = resume-incomplete == PermanentRedirect
let headers = r.headers.clone();
let h: &RangeResponseHeader = match headers.get() {
Some(hh) if r.status == StatusCode::PermanentRedirect => hh,
None|Some(_) => {
if let Retry::After(d) = self.delegate.http_failure(&r, None, None) {
sleep(d);
continue;
}
return Err(Ok(r))
}
};
return Ok(h.0.last)
}
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Err(Err(err))
}
}
}
}
/// returns None if operation was cancelled by delegate, or the HttpResult.
/// It can be that we return the result just because we didn't understand the status code -
/// caller should check for status himself before assuming it's OK to use
pub fn upload(&mut self) -> Option<hyper::Result<hyper::client::Response>> {
let mut start = match self.start_at {
Some(s) => s,
None => match self.query_transfer_status() {
Ok(s) => s,
Err(result) => return Some(result)
}
};
const MIN_CHUNK_SIZE: u64 = 1 << 18;
let chunk_size = match self.delegate.chunk_size() {
cs if cs > MIN_CHUNK_SIZE => cs,
_ => MIN_CHUNK_SIZE
};
self.reader.seek(SeekFrom::Start(start)).unwrap();
loop {
let request_size = match self.content_length - start {
rs if rs > chunk_size => chunk_size,
rs => rs
};
let mut section_reader = self.reader.take(request_size);
let range_header = ContentRange {
range: Some(Chunk {first: start, last: start + request_size - 1}),
total_length: self.content_length
};
start += request_size;
if self.delegate.cancel_chunk_upload(&range_header) {
return None
}
let res = self.client.post(self.url)
.header(range_header)
.header(ContentType(self.media_type.clone()))
.header(UserAgent(self.user_agent.to_string()))
.body(&mut section_reader)
.send();
match res {
Ok(mut res) => {
if res.status == StatusCode::PermanentRedirect {
continue
}
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let Retry::After(d) = self.delegate.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
}
return Some(Ok(res))
},
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Some(Err(err))
}
}
}
}
}
// Copy of src/rust/cli/cmn.rs
// TODO(ST): Allow sharing common code between program types
pub fn remove_json_null_values(value: &mut json::value::Value) {
match *value {
json::value::Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}

5467
gen/cloudbuild1/src/lib.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-clouderrorreporting1_beta1-cli"
version = "1.0.7+20171201"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with Clouderrorreporting (protocol v1beta1)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/clouderrorreporting1_beta1-cli"
homepage = "https://cloud.google.com/error-reporting/"
documentation = "http://byron.github.io/google-apis-rs/google_clouderrorreporting1_beta1_cli"
license = "MIT"
keywords = ["clouderrorreporting", "google", "cli"]
[[bin]]
name = "clouderrorreporting1-beta1"
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
strsim = "^0.5"
hyper-rustls = "^0.6"
yup-hyper-mock = "^2.0"
clap = "^2.0"
[features]
[dependencies.google-clouderrorreporting1_beta1]
path = "../clouderrorreporting1_beta1"
version = "1.0.7+20171201"

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,119 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/cli/README.md.mako'
DO NOT EDIT !
-->
The `clouderrorreporting1-beta1` command-line interface *(CLI)* allows to use most features of the *Google Clouderrorreporting* service from the comfort of your terminal.
By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's
capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero.
If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools.
Everything else about the *Clouderrorreporting* API can be found at the
[official documentation site](https://cloud.google.com/error-reporting/).
# Installation and Source Code
Install the command-line interface with cargo using:
```bash
cargo install google-clouderrorreporting1_beta1-cli
```
Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/clouderrorreporting1_beta1-cli).
# Usage
This documentation was generated from the *Clouderrorreporting* API at revision *20171201*. The CLI is at version *1.0.7*.
```bash
clouderrorreporting1-beta1 [options]
projects
delete-events <project-name> [-p <v>]... [-o <out>]
events-list <project-name> [-p <v>]... [-o <out>]
events-report <project-name> (-r <kv>)... [-p <v>]... [-o <out>]
group-stats-list <project-name> [-p <v>]... [-o <out>]
groups-get <group-name> [-p <v>]... [-o <out>]
groups-update <name> (-r <kv>)... [-p <v>]... [-o <out>]
clouderrorreporting1-beta1 --help
Configuration:
[--scope <url>]...
Specify the authentication a method should be executed in. Each scope
requires the user to grant this application permission to use it.
If unset, it defaults to the shortest scope url for a particular method.
--config-dir <folder>
A directory into which we will store our persistent data. Defaults to
a user-writable directory that we will create during the first invocation.
[default: ~/.google-service-cli]
--debug
Output all server communication to standard error. `tx` and `rx` are placed
into the same stream.
--debug-auth
Output all communication related to authentication to standard error. `tx`
and `rx` are placed into the same stream.
```
# Configuration
The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `clouderrorreporting1-beta1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis.
More information about the various kinds of persistent data are given in the following paragraphs.
# Authentication
Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the
set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*.
If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a
method that is read-only, it will ask only for a read-only scope.
You may use the `--scope` flag to specify a scope directly.
All applicable scopes are documented in the respective method's CLI documentation.
The first time a scope is used, the user is asked for permission. Follow the instructions given
by the CLI to grant permissions, or to decline.
If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration
directory, e.g. `~/.google-service-cli/clouderrorreporting1-beta1-token-<scope-hash>.json`. No manual management of these tokens
is necessary.
To revoke granted authentication, please refer to the [official documentation][revoke-access].
# Application Secrets
In order to allow any application to use Google services, it will need to be registered using the
[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it
one by one. Most APIs can be used for free and have a daily quota.
To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI
comes with a default application secret that is configured accordingly. This also means that heavy usage
all around the world may deplete the daily quota.
You can workaround this limitation by putting your own secrets file at this location:
`~/.google-service-cli/clouderrorreporting1-beta1-secret.json`, assuming that the required *clouderrorreporting* API
was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at
*APIs & auth -> Credentials -> Download JSON* and used as is.
Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new].
# Debugging
Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know
what exactly led to a particular issue. This is done by allowing all client-server communication to be
output to standard error *as-is*.
The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag
will cause all communication related to authentication to standard error.
If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the
issue at hand.
You may consider redirecting standard error into a file for ease of use, e.g. `clouderrorreporting1-beta1 --debug <resource> <method> [options] 2>debug.txt`.
[scopes]: https://developers.google.com/+/api/oauth#scopes
[revoke-access]: http://webapps.stackexchange.com/a/30849
[google-dev-console]: https://console.developers.google.com/
[google-project-new]: https://developers.google.com/console/help/new/

View File

@@ -0,0 +1,22 @@
site_name: Clouderrorreporting v1.0.7+20171201
site_url: http://byron.github.io/google-apis-rs/google-clouderrorreporting1_beta1-cli
site_description: A complete library to interact with Clouderrorreporting (protocol v1beta1)
repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/clouderrorreporting1_beta1-cli
docs_dir: docs
site_dir: build_html
pages:
- ['index.md', 'Home']
- ['projects_delete-events.md', 'Projects', 'Delete Events']
- ['projects_events-list.md', 'Projects', 'Events List']
- ['projects_events-report.md', 'Projects', 'Events Report']
- ['projects_group-stats-list.md', 'Projects', 'Group Stats List']
- ['projects_groups-get.md', 'Projects', 'Groups Get']
- ['projects_groups-update.md', 'Projects', 'Groups Update']
theme: readthedocs
copyright: Copyright &copy; 2015-2016, `Sebastian Thiel`

View File

@@ -0,0 +1,799 @@
// COPY OF 'src/rust/cli/cmn.rs'
// DO NOT EDIT
use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token};
use serde_json as json;
use serde_json::value::Value;
use mime::Mime;
use clap::{App, SubCommand};
use strsim;
use std::fs;
use std::env;
use std::io;
use std::error::Error as StdError;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
use std::io::{Write, Read, stdout};
use std::default::Default;
const FIELD_SEP: char = '.';
pub enum ComplexType {
Pod,
Vec,
Map,
}
// Null,
// Bool(bool),
// I64(i64),
// U64(u64),
// F64(f64),
// String(String),
pub enum JsonType {
Boolean,
Int,
Uint,
Float,
String,
}
pub struct JsonTypeInfo {
pub jtype: JsonType,
pub ctype: ComplexType,
}
// Based on @erickt user comment. Thanks for the idea !
// Remove all keys whose values are null from given value (changed in place)
pub fn remove_json_null_values(value: &mut Value) {
match *value {
Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}
fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> {
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values {
let confidence = strsim::jaro_winkler(v, pv);
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
}
pub enum CallType {
Upload(UploadProtocol),
Standard,
}
arg_enum!{
pub enum UploadProtocol {
Simple,
Resumable
}
}
impl AsRef<str> for UploadProtocol {
fn as_ref(&self) -> &str {
match *self {
UploadProtocol::Simple => "simple",
UploadProtocol::Resumable => "resumable",
}
}
}
impl AsRef<str> for CallType {
fn as_ref(&self) -> &str {
match *self {
CallType::Upload(ref proto) => proto.as_ref(),
CallType::Standard => "standard-request",
}
}
}
#[derive(Clone, Default)]
pub struct FieldCursor(Vec<String>);
impl ToString for FieldCursor {
fn to_string(&self) -> String {
self.0.join(".")
}
}
impl From<&'static str> for FieldCursor {
fn from(value: &'static str) -> FieldCursor {
let mut res = FieldCursor::default();
res.set(value).unwrap();
res
}
}
fn assure_entry<'a, 'b>(m: &'a mut json::Map<String, Value>, k: &'b String) -> &'a mut Value {
if m.contains_key(k) {
return m.get_mut(k).expect("value to exist");
}
m.insert(k.to_owned(), Value::Object(Default::default()));
m.get_mut(k).expect("value to exist")
}
impl FieldCursor {
pub fn set(&mut self, value: &str) -> Result<(), CLIError> {
if value.len() == 0 {
return Err(CLIError::Field(FieldError::Empty));
}
let mut first_is_field_sep = false;
let mut char_count: usize = 0;
let mut last_c = FIELD_SEP;
let mut num_conscutive_field_seps = 0;
let mut field = String::new();
let mut fields = self.0.clone();
let push_field = |fs: &mut Vec<String>, f: &mut String| {
if f.len() > 0 {
fs.push(f.clone());
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
char_count += 1;
if c == FIELD_SEP {
if cid == 0 {
first_is_field_sep = true;
}
num_conscutive_field_seps += 1;
if cid > 0 && last_c == FIELD_SEP {
if fields.pop().is_none() {
return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string())));
}
} else {
push_field(&mut fields, &mut field);
}
} else {
num_conscutive_field_seps = 0;
if cid == 1 {
if first_is_field_sep {
fields.truncate(0);
}
}
field.push(c);
}
last_c = c;
}
push_field(&mut fields, &mut field);
if char_count == 1 && first_is_field_sep {
fields.truncate(0);
}
if char_count > 1 && num_conscutive_field_seps == 1 {
return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string())));
}
self.0 = fields;
Ok(())
}
pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option<String> {
if value.len() == 0 {
return None;
}
let mut last_c = FIELD_SEP;
let mut field = String::new();
let mut output = String::new();
let push_field = |fs: &mut String, f: &mut String| {
if f.len() > 0 {
fs.push_str(match did_you_mean(&f, possible_values) {
Some(candidate) => candidate,
None => &f,
});
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
if c == FIELD_SEP {
if last_c != FIELD_SEP {
push_field(&mut output, &mut field);
}
output.push(c);
} else {
field.push(c);
}
last_c = c;
}
push_field(&mut output, &mut field);
if &output == value {
None
} else {
Some(output)
}
}
pub fn set_json_value(&self,
mut object: &mut Value,
value: &str,
type_info: JsonTypeInfo,
err: &mut InvalidOptionsError,
orig_cursor: &FieldCursor) {
assert!(self.0.len() > 0);
for field in &self.0[..self.0.len() - 1] {
let tmp = object;
object = match *tmp {
Value::Object(ref mut mapping) => {
assure_entry(mapping, &field)
}
_ => panic!("We don't expect non-object Values here ..."),
};
}
match *object {
Value::Object(ref mut mapping) => {
let field = &self.0[self.0.len() - 1];
let to_jval = |value: &str,
jtype: JsonType,
err: &mut InvalidOptionsError|
-> Value {
match jtype {
JsonType::Boolean =>
Value::Bool(arg_from_str(value, err, &field, "boolean")),
JsonType::Int =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"int"))
.expect("valid f64")),
JsonType::Uint =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"uint"))
.expect("valid f64")),
JsonType::Float =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"float"))
.expect("valid f64")),
JsonType::String => Value::String(value.to_owned()),
}
};
match type_info.ctype {
ComplexType::Pod => {
if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err))
.is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
ComplexType::Vec => {
match *assure_entry(mapping, field) {
Value::Array(ref mut values) =>
values.push(to_jval(value, type_info.jtype, err)),
_ => unreachable!(),
}
}
ComplexType::Map => {
let (key, value) = parse_kv_arg(value, err, true);
let jval = to_jval(value.unwrap_or(""), type_info.jtype, err);
match *assure_entry(mapping, &field) {
Value::Object(ref mut value_map) => {
if value_map.insert(key.to_owned(), jval).is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
_ => unreachable!(),
}
}
}
}
_ => unreachable!(),
}
}
pub fn num_fields(&self) -> usize {
self.0.len()
}
}
pub fn parse_kv_arg<'a>(kv: &'a str,
err: &mut InvalidOptionsError,
for_hashmap: bool)
-> (&'a str, Option<&'a str>) {
let mut add_err = || {
err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(), for_hashmap))
};
match kv.find('=') {
None => {
add_err();
return (kv, None);
}
Some(pos) => {
let key = &kv[..pos];
if kv.len() <= pos + 1 {
add_err();
return (key, Some(""));
}
(key, Some(&kv[pos + 1..]))
}
}
}
pub fn calltype_from_str(name: &str,
valid_protocols: Vec<String>,
err: &mut InvalidOptionsError)
-> CallType {
CallType::Upload(match UploadProtocol::from_str(name) {
Ok(up) => up,
Err(msg) => {
err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols));
UploadProtocol::Simple
}
})
}
pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option<fs::File> {
match fs::File::open(file_path) {
Ok(f) => Some(f),
Err(io_err) => {
err.issues.push(CLIError::Input(InputError::Io((file_path.to_string(), io_err))));
None
}
}
}
pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option<Mime> {
match mime.parse() {
Ok(m) => Some(m),
Err(_) => {
err.issues.push(CLIError::Input(InputError::Mime(mime.to_string())));
None
}
}
}
pub fn writer_from_opts(arg: Option<&str>) -> Result<Box<Write>, io::Error> {
let f = arg.unwrap_or("-");
match f {
"-" => Ok(Box::new(stdout())),
_ => match fs::OpenOptions::new().create(true).write(true).open(f) {
Ok(f) => Ok(Box::new(f)),
Err(io_err) => Err(io_err),
},
}
}
pub fn arg_from_str<'a, T>(arg: &str,
err: &mut InvalidOptionsError,
arg_name: &'a str,
arg_type: &'a str)
-> T
where T: FromStr + Default,
<T as FromStr>::Err: fmt::Display
{
match FromStr::from_str(arg) {
Err(perr) => {
err.issues.push(CLIError::ParseError(arg_name.to_owned(),
arg_type.to_owned(),
arg.to_string(),
format!("{}", perr)));
Default::default()
}
Ok(v) => v,
}
}
pub struct JsonTokenStorage {
pub program_name: &'static str,
pub db_dir: String,
}
impl JsonTokenStorage {
fn path(&self, scope_hash: u64) -> PathBuf {
Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash))
}
}
#[derive(Debug)]
pub enum TokenStorageError {
Json(json::Error),
Io(io::Error),
}
impl fmt::Display for TokenStorageError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
TokenStorageError::Json(ref err) => writeln!(f, "Could not serialize secrets: {}", err),
TokenStorageError::Io(ref err) => writeln!(f, "Failed to write secret token: {}", err),
}
}
}
impl StdError for TokenStorageError {
fn description(&self) -> &str {
"Failure when getting or setting the token storage"
}
}
impl TokenStorage for JsonTokenStorage {
type Error = TokenStorageError;
// NOTE: logging might be interesting, currently we swallow all errors
fn set(&mut self,
scope_hash: u64,
_: &Vec<&str>,
token: Option<Token>)
-> Result<(), TokenStorageError> {
match token {
None => {
match fs::remove_file(self.path(scope_hash)) {
Err(err) => match err.kind() {
io::ErrorKind::NotFound => Ok(()),
_ => Err(TokenStorageError::Io(err)),
},
Ok(_) => Ok(()),
}
}
Some(token) => {
match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) {
Ok(mut f) => {
match json::to_writer_pretty(&mut f, &token) {
Ok(_) => Ok(()),
Err(serde_err) => Err(TokenStorageError::Json(serde_err)),
}
}
Err(io_err) => Err(TokenStorageError::Io(io_err)),
}
}
}
}
fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result<Option<Token>, TokenStorageError> {
match fs::File::open(&self.path(scope_hash)) {
Ok(f) => {
match json::de::from_reader(f) {
Ok(token) => Ok(Some(token)),
Err(err) => Err(TokenStorageError::Json(err)),
}
}
Err(io_err) => {
match io_err.kind() {
io::ErrorKind::NotFound => Ok(None),
_ => Err(TokenStorageError::Io(io_err)),
}
}
}
}
}
#[derive(Debug)]
pub enum ApplicationSecretError {
DecoderError((String, json::Error)),
FormatError(String),
}
impl fmt::Display for ApplicationSecretError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ApplicationSecretError::DecoderError((ref path, ref err)) =>
writeln!(f,
"Could not decode file at '{}' with error: {}.",
path,
err),
ApplicationSecretError::FormatError(ref path) =>
writeln!(f,
"'installed' field is unset in secret file at '{}'.",
path),
}
}
}
#[derive(Debug)]
pub enum ConfigurationError {
DirectoryCreationFailed((String, io::Error)),
DirectoryUnset,
HomeExpansionFailed(String),
Secret(ApplicationSecretError),
Io((String, io::Error)),
}
impl fmt::Display for ConfigurationError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) =>
writeln!(f,
"Directory '{}' could not be created with error: {}.",
dir,
err),
ConfigurationError::DirectoryUnset => writeln!(f, "--config-dir was unset or empty."),
ConfigurationError::HomeExpansionFailed(ref dir) =>
writeln!(f,
"Couldn't find HOME directory of current user, failed to expand '{}'.",
dir),
ConfigurationError::Secret(ref err) => writeln!(f, "Secret -> {}", err),
ConfigurationError::Io((ref path, ref err)) =>
writeln!(f,
"IO operation failed on path '{}' with error: {}.",
path,
err),
}
}
}
#[derive(Debug)]
pub enum InputError {
Io((String, io::Error)),
Mime(String),
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
InputError::Io((ref file_path, ref io_err)) =>
writeln!(f,
"Failed to open '{}' for reading with error: {}.",
file_path,
io_err),
InputError::Mime(ref mime) => writeln!(f, "'{}' is not a known mime-type.", mime),
}
}
}
#[derive(Debug)]
pub enum FieldError {
PopOnEmpty(String),
TrailingFieldSep(String),
Unknown(String, Option<String>, Option<String>),
Duplicate(String),
Empty,
}
impl fmt::Display for FieldError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
FieldError::PopOnEmpty(ref field) =>
writeln!(f, "'{}': Cannot move up on empty field cursor.", field),
FieldError::TrailingFieldSep(ref field) =>
writeln!(f,
"'{}': Single field separator may not be last character.",
field),
FieldError::Unknown(ref field, ref suggestion, ref value) => {
let suffix = match *suggestion {
Some(ref s) => {
let kv = match *value {
Some(ref v) => format!("{}={}", s, v),
None => s.clone(),
};
format!(" Did you mean '{}' ?", kv)
}
None => String::new(),
};
writeln!(f, "Field '{}' does not exist.{}", field, suffix)
}
FieldError::Duplicate(ref cursor) =>
writeln!(f, "Value at '{}' was already set", cursor),
FieldError::Empty => writeln!(f, "Field names must not be empty."),
}
}
}
#[derive(Debug)]
pub enum CLIError {
Configuration(ConfigurationError),
ParseError(String, String, String, String),
UnknownParameter(String, Vec<&'static str>),
InvalidUploadProtocol(String, Vec<String>),
InvalidKeyValueSyntax(String, bool),
Input(InputError),
Field(FieldError),
MissingCommandError,
MissingMethodError(String),
}
impl fmt::Display for CLIError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err),
CLIError::Input(ref err) => write!(f, "Input -> {}", err),
CLIError::Field(ref err) => write!(f, "Field -> {}", err),
CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) =>
writeln!(f,
"'{}' is not a valid upload protocol. Choose from one of {}.",
proto_name,
valid_names.join(", ")),
CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) =>
writeln!(f,
"Failed to parse argument '{}' with value '{}' as {} with error: {}.",
arg_name,
value,
type_name,
err_desc),
CLIError::UnknownParameter(ref param_name, ref possible_values) => {
let suffix = match did_you_mean(param_name, &possible_values) {
Some(v) => format!(" Did you mean '{}' ?", v),
None => String::new(),
};
write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix)
}
CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => {
let hashmap_info = if is_hashmap {
"hashmap "
} else {
""
};
writeln!(f,
"'{}' does not match {}pattern <key>=<value>.",
kv,
hashmap_info)
}
CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."),
CLIError::MissingMethodError(ref cmd) =>
writeln!(f,
"Please specify the method to call on the '{}' command.",
cmd),
}
}
}
#[derive(Debug)]
pub struct InvalidOptionsError {
pub issues: Vec<CLIError>,
pub exit_code: i32,
}
impl fmt::Display for InvalidOptionsError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for issue in &self.issues {
try!(issue.fmt(f));
}
Ok(())
}
}
impl InvalidOptionsError {
pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError {
InvalidOptionsError {
issues: vec![err],
exit_code: exit_code,
}
}
pub fn new() -> InvalidOptionsError {
InvalidOptionsError {
issues: Vec::new(),
exit_code: 1,
}
}
}
pub fn assure_config_dir_exists(dir: &str) -> Result<String, CLIError> {
let trdir = dir.trim();
if trdir.len() == 0 {
return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset));
}
let expanded_config_dir = if trdir.as_bytes()[0] == b'~' {
match env::var("HOME").ok().or(env::var("UserProfile").ok()) {
None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))),
Some(mut user) => {
user.push_str(&trdir[1..]);
user
}
}
} else {
trdir.to_string()
};
if let Err(err) = fs::create_dir(&expanded_config_dir) {
if err.kind() != io::ErrorKind::AlreadyExists {
return Err(CLIError::Configuration(
ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err))));
}
}
Ok(expanded_config_dir)
}
pub fn application_secret_from_directory(dir: &str,
secret_basename: &str,
json_console_secret: &str)
-> Result<ApplicationSecret, CLIError> {
let secret_path = Path::new(dir).join(secret_basename);
let secret_str = || secret_path.as_path().to_str().unwrap().to_string();
let secret_io_error = |io_err: io::Error| {
Err(CLIError::Configuration(ConfigurationError::Io((secret_str(), io_err))))
};
for _ in 0..2 {
match fs::File::open(&secret_path) {
Err(mut err) => {
if err.kind() == io::ErrorKind::NotFound {
// Write our built-in one - user may adjust the written file at will
err = match fs::OpenOptions::new()
.create(true)
.write(true)
.open(&secret_path) {
Err(cfe) => cfe,
Ok(mut f) => {
// Assure we convert 'ugly' json string into pretty one
let console_secret: ConsoleApplicationSecret =
json::from_str(json_console_secret).unwrap();
match json::to_writer_pretty(&mut f, &console_secret) {
Err(serde_err) =>
panic!("Unexpected serde error: {:#?}", serde_err),
Ok(_) => continue,
}
}
};
// fall through to IO error handling
}
return secret_io_error(err);
}
Ok(f) => {
match json::de::from_reader::<_, ConsoleApplicationSecret>(f) {
Err(json_err) =>
return Err(CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::DecoderError(
(secret_str(), json_err)
)))),
Ok(console_secret) => match console_secret.installed {
Some(secret) => return Ok(secret),
None => return Err(
CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::FormatError(secret_str())
))),
},
}
}
}
}
unreachable!();
}

View File

@@ -0,0 +1,892 @@
// DO NOT EDIT !
// This file was generated automatically from 'src/mako/cli/main.rs.mako'
// DO NOT EDIT !
#![allow(unused_variables, unused_imports, dead_code, unused_mut)]
#[macro_use]
extern crate clap;
extern crate yup_oauth2 as oauth2;
extern crate yup_hyper_mock as mock;
extern crate hyper_rustls;
extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate mime;
extern crate strsim;
extern crate google_clouderrorreporting1_beta1 as api;
use std::env;
use std::io::{self, Write};
use clap::{App, SubCommand, Arg};
mod cmn;
use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg,
input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol,
calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo};
use std::default::Default;
use std::str::FromStr;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, FlowType};
use serde_json as json;
use clap::ArgMatches;
enum DoitError {
IoError(String, io::Error),
ApiError(api::Error),
}
struct Engine<'n> {
opt: ArgMatches<'n>,
hub: api::Clouderrorreporting<hyper::Client, Authenticator<DefaultAuthenticatorDelegate, JsonTokenStorage, hyper::Client>>,
gp: Vec<&'static str>,
gpm: Vec<(&'static str, &'static str)>,
}
impl<'n> Engine<'n> {
fn _projects_delete_events(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.projects().delete_events(opt.value_of("project-name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _projects_events_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.projects().events_list(opt.value_of("project-name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"time-range-period" => {
call = call.time_range_period(value.unwrap_or(""));
},
"service-filter-version" => {
call = call.service_filter_version(value.unwrap_or(""));
},
"service-filter-service" => {
call = call.service_filter_service(value.unwrap_or(""));
},
"service-filter-resource-type" => {
call = call.service_filter_resource_type(value.unwrap_or(""));
},
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"page-size" => {
call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer"));
},
"group-id" => {
call = call.group_id(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["service-filter-resource-type", "time-range-period", "page-size", "service-filter-service", "page-token", "service-filter-version", "group-id"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _projects_events_report(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"service-context.resource-type" => Some(("serviceContext.resourceType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"service-context.version" => Some(("serviceContext.version", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"service-context.service" => Some(("serviceContext.service", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"message" => Some(("message", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"event-time" => Some(("eventTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"context.http-request.response-status-code" => Some(("context.httpRequest.responseStatusCode", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"context.http-request.url" => Some(("context.httpRequest.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"context.http-request.referrer" => Some(("context.httpRequest.referrer", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"context.http-request.remote-ip" => Some(("context.httpRequest.remoteIp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"context.http-request.user-agent" => Some(("context.httpRequest.userAgent", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"context.http-request.method" => Some(("context.httpRequest.method", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"context.user" => Some(("context.user", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"context.report-location.line-number" => Some(("context.reportLocation.lineNumber", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"context.report-location.function-name" => Some(("context.reportLocation.functionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"context.report-location.file-path" => Some(("context.reportLocation.filePath", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["context", "event-time", "file-path", "function-name", "http-request", "line-number", "message", "method", "referrer", "remote-ip", "report-location", "resource-type", "response-status-code", "service", "service-context", "url", "user", "user-agent", "version"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::ReportedErrorEvent = json::value::from_value(object).unwrap();
let mut call = self.hub.projects().events_report(request, opt.value_of("project-name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _projects_group_stats_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.projects().group_stats_list(opt.value_of("project-name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"timed-count-duration" => {
call = call.timed_count_duration(arg_from_str(value.unwrap_or("-0"), err, "timed-count-duration", "int64"));
},
"time-range-period" => {
call = call.time_range_period(value.unwrap_or(""));
},
"service-filter-version" => {
call = call.service_filter_version(value.unwrap_or(""));
},
"service-filter-service" => {
call = call.service_filter_service(value.unwrap_or(""));
},
"service-filter-resource-type" => {
call = call.service_filter_resource_type(value.unwrap_or(""));
},
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"page-size" => {
call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer"));
},
"order" => {
call = call.order(value.unwrap_or(""));
},
"group-id" => {
call = call.add_group_id(value.unwrap_or(""));
},
"alignment-time" => {
call = call.alignment_time(value.unwrap_or(""));
},
"alignment" => {
call = call.alignment(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["service-filter-resource-type", "time-range-period", "timed-count-duration", "page-size", "alignment-time", "service-filter-service", "group-id", "page-token", "service-filter-version", "order", "alignment"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _projects_groups_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.projects().groups_get(opt.value_of("group-name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _projects_groups_update(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"group-id" => Some(("groupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["group-id", "name"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::ErrorGroup = json::value::from_value(object).unwrap();
let mut call = self.hub.projects().groups_update(request, opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _doit(&self, dry_run: bool) -> Result<Result<(), DoitError>, Option<InvalidOptionsError>> {
let mut err = InvalidOptionsError::new();
let mut call_result: Result<(), DoitError> = Ok(());
let mut err_opt: Option<InvalidOptionsError> = None;
match self.opt.subcommand() {
("projects", Some(opt)) => {
match opt.subcommand() {
("delete-events", Some(opt)) => {
call_result = self._projects_delete_events(opt, dry_run, &mut err);
},
("events-list", Some(opt)) => {
call_result = self._projects_events_list(opt, dry_run, &mut err);
},
("events-report", Some(opt)) => {
call_result = self._projects_events_report(opt, dry_run, &mut err);
},
("group-stats-list", Some(opt)) => {
call_result = self._projects_group_stats_list(opt, dry_run, &mut err);
},
("groups-get", Some(opt)) => {
call_result = self._projects_groups_get(opt, dry_run, &mut err);
},
("groups-update", Some(opt)) => {
call_result = self._projects_groups_update(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("projects".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
_ => {
err.issues.push(CLIError::MissingCommandError);
writeln!(io::stderr(), "{}\n", self.opt.usage()).ok();
}
}
if dry_run {
if err.issues.len() > 0 {
err_opt = Some(err);
}
Err(err_opt)
} else {
Ok(call_result)
}
}
// Please note that this call will fail if any part of the opt can't be handled
fn new(opt: ArgMatches<'n>) -> Result<Engine<'n>, InvalidOptionsError> {
let (config_dir, secret) = {
let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) {
Err(e) => return Err(InvalidOptionsError::single(e, 3)),
Ok(p) => p,
};
match cmn::application_secret_from_directory(&config_dir, "clouderrorreporting1-beta1-secret.json",
"{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") {
Ok(secret) => (config_dir, secret),
Err(e) => return Err(InvalidOptionsError::single(e, 4))
}
};
let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate,
if opt.is_present("debug-auth") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
},
JsonTokenStorage {
program_name: "clouderrorreporting1-beta1",
db_dir: config_dir.clone(),
}, Some(FlowType::InstalledRedirect(54324)));
let client =
if opt.is_present("debug") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
};
let engine = Engine {
opt: opt,
hub: api::Clouderrorreporting::new(client, auth),
gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"],
gpm: vec![
("$-xgafv", "$.xgafv"),
("access-token", "access_token"),
("bearer-token", "bearer_token"),
("oauth-token", "oauth_token"),
("pretty-print", "prettyPrint"),
("quota-user", "quotaUser"),
("upload-type", "uploadType"),
("upload-protocol", "upload_protocol"),
]
};
match engine._doit(true) {
Err(Some(err)) => Err(err),
Err(None) => Ok(engine),
Ok(_) => unreachable!(),
}
}
fn doit(&self) -> Result<(), DoitError> {
match self._doit(false) {
Ok(res) => res,
Err(_) => unreachable!(),
}
}
}
fn main() {
let mut exit_status = 0i32;
let arg_data = [
("projects", "methods: 'delete-events', 'events-list', 'events-report', 'group-stats-list', 'groups-get' and 'groups-update'", vec![
("delete-events",
Some(r##"Deletes all error events of a given project."##),
"Details at http://byron.github.io/google-apis-rs/google_clouderrorreporting1_beta1_cli/projects_delete-events",
vec![
(Some(r##"project-name"##),
None,
Some(r##"[Required] The resource name of the Google Cloud Platform project. Written
as `projects/` plus the
[Google Cloud Platform project
ID](https://support.google.com/cloud/answer/6158840).
Example: `projects/my-project-123`."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("events-list",
Some(r##"Lists the specified events."##),
"Details at http://byron.github.io/google-apis-rs/google_clouderrorreporting1_beta1_cli/projects_events-list",
vec![
(Some(r##"project-name"##),
None,
Some(r##"[Required] The resource name of the Google Cloud Platform project. Written
as `projects/` plus the
[Google Cloud Platform project
ID](https://support.google.com/cloud/answer/6158840).
Example: `projects/my-project-123`."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("events-report",
Some(r##"Report an individual error event.
This endpoint accepts <strong>either</strong> an OAuth token,
<strong>or</strong> an
<a href="https://support.google.com/cloud/answer/6158862">API key</a>
for authentication. To use an API key, append it to the URL as the value of
a `key` parameter. For example:
<pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre>"##),
"Details at http://byron.github.io/google-apis-rs/google_clouderrorreporting1_beta1_cli/projects_events-report",
vec![
(Some(r##"project-name"##),
None,
Some(r##"[Required] The resource name of the Google Cloud Platform project. Written
as `projects/` plus the
[Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840).
Example: `projects/my-project-123`."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("group-stats-list",
Some(r##"Lists the specified groups."##),
"Details at http://byron.github.io/google-apis-rs/google_clouderrorreporting1_beta1_cli/projects_group-stats-list",
vec![
(Some(r##"project-name"##),
None,
Some(r##"[Required] The resource name of the Google Cloud Platform project. Written
as <code>projects/</code> plus the
<a href="https://support.google.com/cloud/answer/6158840">Google Cloud
Platform project ID</a>.
Example: <code>projects/my-project-123</code>."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("groups-get",
Some(r##"Get the specified group."##),
"Details at http://byron.github.io/google-apis-rs/google_clouderrorreporting1_beta1_cli/projects_groups-get",
vec![
(Some(r##"group-name"##),
None,
Some(r##"[Required] The group resource name. Written as
<code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
Call
<a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list">
<code>groupStats.list</code></a> to return a list of groups belonging to
this project.
Example: <code>projects/my-project-123/groups/my-group</code>"##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("groups-update",
Some(r##"Replace the data for the specified group.
Fails if the group does not exist."##),
"Details at http://byron.github.io/google-apis-rs/google_clouderrorreporting1_beta1_cli/projects_groups-update",
vec![
(Some(r##"name"##),
None,
Some(r##"The group resource name.
Example: <code>projects/my-project-123/groups/my-groupid</code>"##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
];
let mut app = App::new("clouderrorreporting1-beta1")
.author("Sebastian Thiel <byronimo@gmail.com>")
.version("1.0.7+20171201")
.about("Groups and counts similar errors from cloud services and applications, reports new errors, and provides access to error groups and their associated errors.
")
.after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_clouderrorreporting1_beta1_cli")
.arg(Arg::with_name("url")
.long("scope")
.help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.")
.multiple(true)
.takes_value(true))
.arg(Arg::with_name("folder")
.long("config-dir")
.help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli")
.multiple(false)
.takes_value(true))
.arg(Arg::with_name("debug")
.long("debug")
.help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false))
.arg(Arg::with_name("debug-auth")
.long("debug-auth")
.help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false));
for &(main_command_name, about, ref subcommands) in arg_data.iter() {
let mut mcmd = SubCommand::with_name(main_command_name).about(about);
for &(sub_command_name, ref desc, url_info, ref args) in subcommands {
let mut scmd = SubCommand::with_name(sub_command_name);
if let &Some(desc) = desc {
scmd = scmd.about(desc);
}
scmd = scmd.after_help(url_info);
for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args {
let arg_name_str =
match (arg_name, flag) {
(&Some(an), _ ) => an,
(_ , &Some(f)) => f,
_ => unreachable!(),
};
let mut arg = Arg::with_name(arg_name_str)
.empty_values(false);
if let &Some(short_flag) = flag {
arg = arg.short(short_flag);
}
if let &Some(desc) = desc {
arg = arg.help(desc);
}
if arg_name.is_some() && flag.is_some() {
arg = arg.takes_value(true);
}
if let &Some(required) = required {
arg = arg.required(required);
}
if let &Some(multi) = multi {
arg = arg.multiple(multi);
}
scmd = scmd.arg(arg);
}
mcmd = mcmd.subcommand(scmd);
}
app = app.subcommand(mcmd);
}
let matches = app.get_matches();
let debug = matches.is_present("debug");
match Engine::new(matches) {
Err(err) => {
exit_status = err.exit_code;
writeln!(io::stderr(), "{}", err).ok();
},
Ok(engine) => {
if let Err(doit_err) = engine.doit() {
exit_status = 1;
match doit_err {
DoitError::IoError(path, err) => {
writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok();
},
DoitError::ApiError(err) => {
if debug {
writeln!(io::stderr(), "{:#?}", err).ok();
} else {
writeln!(io::stderr(), "{}", err).ok();
}
}
}
}
}
}
std::process::exit(exit_status);
}

View File

@@ -0,0 +1,31 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-clouderrorreporting1_beta1"
version = "1.0.7+20171201"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with Clouderrorreporting (protocol v1beta1)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/clouderrorreporting1_beta1"
homepage = "https://cloud.google.com/error-reporting/"
documentation = "https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201"
license = "MIT"
keywords = ["clouderrorreporting", "google", "protocol", "web", "api"]
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
url = "= 0.5"
[features]

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,181 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/api/README.md.mako'
DO NOT EDIT !
-->
The `google-clouderrorreporting1_beta1` library allows access to all features of the *Google Clouderrorreporting* service.
This documentation was generated from *Clouderrorreporting* crate version *1.0.7+20171201*, where *20171201* is the exact revision of the *clouderrorreporting:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.7*.
Everything else about the *Clouderrorreporting* *v1_beta1* API can be found at the
[official documentation site](https://cloud.google.com/error-reporting/).
# Features
Handle the following *Resources* with ease from the central [hub](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/struct.Clouderrorreporting.html) ...
* projects
* [*delete events*](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/struct.ProjectDeleteEventCall.html), [*events list*](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/struct.ProjectEventListCall.html), [*events report*](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/struct.ProjectEventReportCall.html), [*group stats list*](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/struct.ProjectGroupStatListCall.html), [*groups get*](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/struct.ProjectGroupGetCall.html) and [*groups update*](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/struct.ProjectGroupUpdateCall.html)
# Structure of this Library
The API is structured into the following primary items:
* **[Hub](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/struct.Clouderrorreporting.html)**
* a central object to maintain state and allow accessing all *Activities*
* creates [*Method Builders*](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.MethodsBuilder.html) which in turn
allow access to individual [*Call Builders*](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.CallBuilder.html)
* **[Resources](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.Resource.html)**
* primary types that you can apply *Activities* to
* a collection of properties and *Parts*
* **[Parts](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.Part.html)**
* a collection of properties
* never directly used in *Activities*
* **[Activities](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.CallBuilder.html)**
* operations to apply to *Resources*
All *structures* are marked with applicable traits to further categorize them and ease browsing.
Generally speaking, you can invoke *Activities* like this:
```Rust,ignore
let r = hub.resource().activity(...).doit()
```
Or specifically ...
```ignore
let r = hub.projects().groups_get(...).doit()
let r = hub.projects().groups_update(...).doit()
```
The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
The `doit()` method performs the actual communication with the server and returns the respective result.
# Usage
## Setting up your Project
To use this library, you would put the following lines into your `Cargo.toml` file:
```toml
[dependencies]
google-clouderrorreporting1_beta1 = "*"
```
## A complete example
```Rust
extern crate hyper;
extern crate hyper_rustls;
extern crate yup_oauth2 as oauth2;
extern crate google_clouderrorreporting1_beta1 as clouderrorreporting1_beta1;
use clouderrorreporting1_beta1::ErrorGroup;
use clouderrorreporting1_beta1::{Result, Error};
use std::default::Default;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
use clouderrorreporting1_beta1::Clouderrorreporting;
// Get an ApplicationSecret instance by some means. It contains the `client_id` and
// `client_secret`, among other things.
let secret: ApplicationSecret = Default::default();
// Instantiate the authenticator. It will choose a suitable authentication flow for you,
// unless you replace `None` with the desired Flow.
// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
// retrieve them from storage.
let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
<MemoryStorage as Default>::default(), None);
let mut hub = Clouderrorreporting::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
// As the method needs a request, you would usually fill it with the desired information
// into the respective structure. Some of the parts shown here might not be applicable !
// Values shown here are possibly random and not representative !
let mut req = ErrorGroup::default();
// You can configure optional parameters by calling the respective setters at will, and
// execute the final call using `doit()`.
// Values shown here are possibly random and not representative !
let result = hub.projects().groups_update(req, "name")
.doit();
match result {
Err(e) => match e {
// The Error enum provides details about what exactly happened.
// You can also just use its `Debug`, `Display` or `Error` traits
Error::HttpError(_)
|Error::MissingAPIKey
|Error::MissingToken(_)
|Error::Cancelled
|Error::UploadSizeLimitExceeded(_, _)
|Error::Failure(_)
|Error::BadRequest(_)
|Error::FieldClash(_)
|Error::JsonDecodeError(_, _) => println!("{}", e),
},
Ok(res) => println!("Success: {:?}", res),
}
```
## Handling Errors
All errors produced by the system are provided either as [Result](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/enum.Result.html) enumeration as return value of
the doit() methods, or handed as possibly intermediate results to either the
[Hub Delegate](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.Delegate.html), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html).
When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
makes the system potentially resilient to all kinds of errors.
## Uploads and Downloads
If a method supports downloads, the response body, which is part of the [Result](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/enum.Result.html), should be
read by you to obtain the media.
If such a method also supports a [Response Result](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.ResponseResult.html), it will return that by default.
You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
this call: `.param("alt", "media")`.
Methods supporting uploads can do so using up to 2 different protocols:
*simple* and *resumable*. The distinctiveness of each is represented by customized
`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
## Customization and Callbacks
You may alter the way an `doit()` method is called by providing a [delegate](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.Delegate.html) to the
[Method Builder](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.CallBuilder.html) before making the final `doit()` call.
Respective methods will be called to provide progress information, as well as determine whether the system should
retry on failure.
The [delegate trait](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
## Optional Parts in Server-Requests
All structures provided by this library are made to be [enocodable](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.RequestValue.html) and
[decodable](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
are valid.
Most optionals are are considered [Parts](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.Part.html) which are identifiable by name, which will be sent to
the server to indicate either the set parts of the request or the desired parts in the response.
## Builder Arguments
Using [method builders](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods.
These will always take a single argument, for which the following statements are true.
* [PODs][wiki-pod] are handed by copy
* strings are passed as `&str`
* [request values](https://docs.rs/google-clouderrorreporting1_beta1/1.0.7+20171201/google_clouderrorreporting1_beta1/trait.RequestValue.html) are moved
Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
[google-go-api]: https://github.com/google/google-api-go-client
# License
The **clouderrorreporting1_beta1** library was generated by Sebastian Thiel, and is placed
under the *MIT* license.
You can read the full text at the repository's [license file][repo-license].
[repo-license]: https://github.com/Byron/google-apis-rsblob/master/LICENSE.md

View File

@@ -0,0 +1,753 @@
// COPY OF 'src/rust/api/cmn.rs'
// DO NOT EDIT
use std::io::{self, Read, Seek, Cursor, Write, SeekFrom};
use std;
use std::fmt::{self, Display};
use std::str::FromStr;
use std::error;
use std::thread::sleep;
use std::time::Duration;
use mime::{Mime, TopLevel, SubLevel, Attr, Value};
use oauth2::{TokenType, Retry, self};
use hyper;
use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header,
HeaderFormat, Bearer};
use hyper::http::h1::LINE_ENDING;
use hyper::method::Method;
use hyper::status::StatusCode;
use serde_json as json;
/// Identifies the Hub. There is only one per library, this trait is supposed
/// to make intended use more explicit.
/// The hub allows to access all resource methods more easily.
pub trait Hub {}
/// Identifies types for building methods of a particular resource type
pub trait MethodsBuilder {}
/// Identifies types which represent builders for a particular resource method
pub trait CallBuilder {}
/// Identifies types which can be inserted and deleted.
/// Types with this trait are most commonly used by clients of this API.
pub trait Resource {}
/// Identifies types which are used in API responses.
pub trait ResponseResult {}
/// Identifies types which are used in API requests.
pub trait RequestValue {}
/// Identifies types which are not actually used by the API
/// This might be a bug within the google API schema.
pub trait UnusedType {}
/// Identifies types which are only used as part of other types, which
/// usually are carrying the `Resource` trait.
pub trait Part {}
/// Identifies types which are only used by other types internally.
/// They have no special meaning, this trait just marks them for completeness.
pub trait NestedType {}
/// A utility to specify reader types which provide seeking capabilities too
pub trait ReadSeek: Seek + Read {}
impl<T: Seek + Read> ReadSeek for T {}
/// A trait for all types that can convert themselves into a *parts* string
pub trait ToParts {
fn to_parts(&self) -> String;
}
/// A utility type which can decode a server response that indicates error
#[derive(Deserialize)]
pub struct JsonServerError {
pub error: String,
pub error_description: Option<String>
}
/// A utility to represent detailed errors we might see in case there are BadRequests.
/// The latter happen if the sent parameters or request structures are unsound
#[derive(Deserialize, Serialize, Debug)]
pub struct ErrorResponse {
error: ServerError,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerError {
errors: Vec<ServerMessage>,
code: u16,
message: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerMessage {
domain: String,
reason: String,
message: String,
#[serde(rename="locationType")]
location_type: Option<String>,
location: Option<String>
}
#[derive(Copy, Clone)]
pub struct DummyNetworkStream;
impl Read for DummyNetworkStream {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl Write for DummyNetworkStream {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl hyper::net::NetworkStream for DummyNetworkStream {
fn peer_addr(&mut self) -> io::Result<std::net::SocketAddr> {
Ok("127.0.0.1:1337".parse().unwrap())
}
fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
}
/// A trait specifying functionality to help controlling any request performed by the API.
/// The trait has a conservative default implementation.
///
/// It contains methods to deal with all common issues, as well with the ones related to
/// uploading media
pub trait Delegate {
/// Called at the beginning of any API request. The delegate should store the method
/// information if he is interesting in knowing more context when further calls to it
/// are made.
/// The matching `finished()` call will always be made, no matter whether or not the API
/// request was successful. That way, the delegate may easily maintain a clean state
/// between various API calls.
fn begin(&mut self, MethodInfo) {}
/// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
///
/// Return retry information.
fn http_error(&mut self, &hyper::Error) -> Retry {
Retry::Abort
}
/// Called whenever there is the need for your applications API key after
/// the official authenticator implementation didn't provide one, for some reason.
/// If this method returns None as well, the underlying operation will fail
fn api_key(&mut self) -> Option<String> {
None
}
/// Called whenever the Authenticator didn't yield a token. The delegate
/// may attempt to provide one, or just take it as a general information about the
/// impending failure.
/// The given Error provides information about why the token couldn't be acquired in the
/// first place
fn token(&mut self, err: &error::Error) -> Option<oauth2::Token> {
let _ = err;
None
}
/// Called during resumable uploads to provide a URL for the impending upload.
/// It was saved after a previous call to `store_upload_url(...)`, and if not None,
/// will be used instead of asking the server for a new upload URL.
/// This is useful in case a previous resumable upload was aborted/canceled, but should now
/// be resumed.
/// The returned URL will be used exactly once - if it fails again and the delegate allows
/// to retry, we will ask the server for a new upload URL.
fn upload_url(&mut self) -> Option<String> {
None
}
/// Called after we have retrieved a new upload URL for a resumable upload to store it
/// in case we fail or cancel. That way, we can attempt to resume the upload later,
/// see `upload_url()`.
/// It will also be called with None after a successful upload, which allows the delegate
/// to forget the URL. That way, we will not attempt to resume an upload that has already
/// finished.
fn store_upload_url(&mut self, url: Option<&str>) {
let _ = url;
}
/// Called whenever a server response could not be decoded from json.
/// It's for informational purposes only, the caller will return with an error
/// accordingly.
///
/// # Arguments
///
/// * `json_encoded_value` - The json-encoded value which failed to decode.
/// * `json_decode_error` - The decoder error
fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &json::Error) {
let _ = json_encoded_value;
let _ = json_decode_error;
}
/// Called whenever the http request returns with a non-success status code.
/// This can involve authentication issues, or anything else that very much
/// depends on the used API method.
/// The delegate should check the status, header and decoded json error to decide
/// whether to retry or not. In the latter case, the underlying call will fail.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
fn http_failure(&mut self, _: &hyper::client::Response, Option<JsonServerError>, _: Option<ServerError>) -> Retry {
Retry::Abort
}
/// Called prior to sending the main request of the given method. It can be used to time
/// the call or to print progress information.
/// It's also useful as you can be sure that a request will definitely be made.
fn pre_request(&mut self) { }
/// Return the size of each chunk of a resumable upload.
/// Must be a power of two, with 1<<18 being the smallest allowed chunk size.
/// Will be called once before starting any resumable upload.
fn chunk_size(&mut self) -> u64 {
1 << 23
}
/// Called before the given chunk is uploaded to the server.
/// If true is returned, the upload will be interrupted.
/// However, it may be resumable if you stored the upload URL in a previous call
/// to `store_upload_url()`
fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool {
let _ = chunk;
false
}
/// Called before the API request method returns, in every case. It can be used to clean up
/// internal state between calls to the API.
/// This call always has a matching call to `begin(...)`.
///
/// # Arguments
///
/// * `is_success` - a true value indicates the operation was successful. If false, you should
/// discard all values stored during `store_upload_url`.
fn finished(&mut self, is_success: bool) {
let _ = is_success;
}
}
/// A delegate with a conservative default implementation, which is used if no other delegate is
/// set.
#[derive(Default)]
pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}
#[derive(Debug)]
pub enum Error {
/// The http connection failed
HttpError(hyper::Error),
/// An attempt was made to upload a resource with size stored in field `.0`
/// even though the maximum upload size is what is stored in field `.1`.
UploadSizeLimitExceeded(u64, u64),
/// Represents information about a request that was not understood by the server.
/// Details are included.
BadRequest(ErrorResponse),
/// We needed an API key for authentication, but didn't obtain one.
/// Neither through the authenticator, nor through the Delegate.
MissingAPIKey,
/// We required a Token, but didn't get one from the Authenticator
MissingToken(Box<error::Error>),
/// The delgate instructed to cancel the operation
Cancelled,
/// An additional, free form field clashed with one of the built-in optional ones
FieldClash(&'static str),
/// Shows that we failed to decode the server response.
/// This can happen if the protocol changes in conjunction with strict json decoding.
JsonDecodeError(String, json::Error),
/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref err) => err.fmt(f),
Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) =>
writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}"
, resource_size, max_size),
Error::MissingAPIKey => {
(writeln!(f, "The application's API key was not found in the configuration")).ok();
writeln!(f, "It is used as there are no Scopes defined for this method.")
},
Error::BadRequest(ref err) => {
try!(writeln!(f, "Bad Request ({}): {}", err.error.code, err.error.message));
for err in err.error.errors.iter() {
try!(writeln!(f, " {}: {}, {}{}",
err.domain,
err.message,
err.reason,
match &err.location {
&Some(ref loc) => format!("@{}", loc),
&None => String::new(),
}));
}
Ok(())
},
Error::MissingToken(ref err) =>
writeln!(f, "Token retrieval failed with error: {}", err),
Error::Cancelled =>
writeln!(f, "Operation cancelled by delegate"),
Error::FieldClash(field) =>
writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field),
Error::JsonDecodeError(ref json_str, ref err)
=> writeln!(f, "{}: {}", err, json_str),
Error::Failure(ref response) =>
writeln!(f, "Http status indicates failure: {:?}", response),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::HttpError(ref err) => err.description(),
Error::JsonDecodeError(_, ref err) => err.description(),
_ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead"
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::HttpError(ref err) => err.cause(),
Error::JsonDecodeError(_, ref err) => err.cause(),
_ => None
}
}
}
/// A universal result type used as return for all calls.
pub type Result<T> = std::result::Result<T, Error>;
/// Contains information about an API request.
pub struct MethodInfo {
pub id: &'static str,
pub http_method: Method,
}
const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d";
/// Provides a `Read` interface that converts multiple parts into the protocol
/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387).
/// **Note**: This implementation is just as rich as it needs to be to perform uploads
/// to google APIs, and might not be a fully-featured implementation.
#[derive(Default)]
pub struct MultiPartReader<'a> {
raw_parts: Vec<(Headers, &'a mut Read)>,
current_part: Option<(Cursor<Vec<u8>>, &'a mut Read)>,
last_part_boundary: Option<Cursor<Vec<u8>>>,
}
impl<'a> MultiPartReader<'a> {
/// Reserve memory for exactly the given amount of parts
pub fn reserve_exact(&mut self, cap: usize) {
self.raw_parts.reserve_exact(cap);
}
/// Add a new part to the queue of parts to be read on the first `read` call.
///
/// # Arguments
///
/// `headers` - identifying the body of the part. It's similar to the header
/// in an ordinary single-part call, and should thus contain the
/// same information.
/// `reader` - a reader providing the part's body
/// `size` - the amount of bytes provided by the reader. It will be put onto the header as
/// content-size.
/// `mime` - It will be put onto the content type
pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> {
let mut headers = Headers::new();
headers.set(ContentType(mime_type));
headers.set(ContentLength(size));
self.raw_parts.push((headers, reader));
self
}
/// Returns the mime-type representing our multi-part message.
/// Use it with the ContentType header.
pub fn mime_type(&self) -> Mime {
Mime(
TopLevel::Multipart,
SubLevel::Ext("Related".to_string()),
vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))],
)
}
/// Returns true if we are totally used
fn is_depleted(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none()
}
/// Returns true if we are handling our last part
fn is_last_part(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_some()
}
}
impl<'a> Read for MultiPartReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.raw_parts.len(),
self.current_part.is_none(),
self.last_part_boundary.is_none()) {
(_, _, false) => {
let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0);
if br < buf.len() {
self.last_part_boundary = None;
}
return Ok(br)
},
(0, true, true) => return Ok(0),
(n, true, _) if n > 0 => {
let (headers, reader) = self.raw_parts.remove(0);
let mut c = Cursor::new(Vec::<u8>::new());
(write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING,
headers, LINE_ENDING)).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
self.current_part = Some((c, reader));
}
_ => {},
}
// read headers as long as possible
let (hb, rr) = {
let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap();
let b = c.read(buf).unwrap_or(0);
(b, reader.read(&mut buf[b..]))
};
match rr {
Ok(bytes_read) => {
if hb < buf.len() && bytes_read == 0 {
if self.is_last_part() {
// before clearing the last part, we will add the boundary that
// will be written last
self.last_part_boundary = Some(Cursor::new(
format!("{}--{}--", LINE_ENDING, BOUNDARY).into_bytes()))
}
// We are depleted - this can trigger the next part to come in
self.current_part = None;
}
let mut total_bytes_read = hb + bytes_read;
while total_bytes_read < buf.len() && !self.is_depleted() {
match self.read(&mut buf[total_bytes_read ..]) {
Ok(br) => total_bytes_read += br,
Err(err) => return Err(err),
}
}
Ok(total_bytes_read)
}
Err(err) => {
// fail permanently
self.current_part = None;
self.last_part_boundary = None;
self.raw_parts.clear();
Err(err)
}
}
}
}
/// The `X-Upload-Content-Type` header.
///
/// Generated via rustc --pretty expanded -Z unstable-options, and manually
/// processed to be more readable.
#[derive(PartialEq, Debug, Clone)]
pub struct XUploadContentType(pub Mime);
impl ::std::ops::Deref for XUploadContentType {
type Target = Mime;
fn deref<'a>(&'a self) -> &'a Mime { &self.0 }
}
impl ::std::ops::DerefMut for XUploadContentType {
fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 }
}
impl Header for XUploadContentType {
fn header_name() -> &'static str { "X-Upload-Content-Type" }
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType)
}
}
impl HeaderFormat for XUploadContentType {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&**self, f)
}
}
impl Display for XUploadContentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chunk {
pub first: u64,
pub last: u64
}
impl fmt::Display for Chunk {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(write!(fmt, "{}-{}", self.first, self.last)).ok();
Ok(())
}
}
impl FromStr for Chunk {
type Err = &'static str;
/// NOTE: only implements `%i-%i`, not `*`
fn from_str(s: &str) -> std::result::Result<Chunk, &'static str> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 2 {
return Err("Expected two parts: %i-%i")
}
Ok(
Chunk {
first: match FromStr::from_str(parts[0]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'first' as digit")
},
last: match FromStr::from_str(parts[1]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'last' as digit")
}
}
)
}
}
/// Implements the Content-Range header, for serialization only
#[derive(Clone, PartialEq, Debug)]
pub struct ContentRange {
pub range: Option<Chunk>,
pub total_length: u64,
}
impl Header for ContentRange {
fn header_name() -> &'static str {
"Content-Range"
}
/// We are not parsable, as parsing is done by the `Range` header
fn parse_header(_: &[Vec<u8>]) -> hyper::error::Result<Self> {
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for ContentRange {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("bytes "));
match self.range {
Some(ref c) => try!(c.fmt(fmt)),
None => try!(fmt.write_str("*"))
}
(write!(fmt, "/{}", self.total_length)).ok();
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct RangeResponseHeader(pub Chunk);
impl Header for RangeResponseHeader {
fn header_name() -> &'static str {
"Range"
}
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
if raw.len() > 0 {
let v = &raw[0];
if let Ok(s) = std::str::from_utf8(v) {
const PREFIX: &'static str = "bytes ";
if s.starts_with(PREFIX) {
if let Ok(c) = <Chunk as FromStr>::from_str(&s[PREFIX.len()..]) {
return Ok(RangeResponseHeader(c))
}
}
}
}
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for RangeResponseHeader {
/// No implmentation necessary, we just need to parse
fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
/// A utility type to perform a resumable upload from start to end.
pub struct ResumableUploadHelper<'a, A: 'a> {
pub client: &'a mut hyper::client::Client,
pub delegate: &'a mut Delegate,
pub start_at: Option<u64>,
pub auth: &'a mut A,
pub user_agent: &'a str,
pub auth_header: Authorization<Bearer>,
pub url: &'a str,
pub reader: &'a mut ReadSeek,
pub media_type: Mime,
pub content_length: u64
}
impl<'a, A> ResumableUploadHelper<'a, A>
where A: oauth2::GetToken {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::Result<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
.header(ContentRange { range: None, total_length: self.content_length })
.header(self.auth_header.clone())
.send() {
Ok(r) => {
// 308 = resume-incomplete == PermanentRedirect
let headers = r.headers.clone();
let h: &RangeResponseHeader = match headers.get() {
Some(hh) if r.status == StatusCode::PermanentRedirect => hh,
None|Some(_) => {
if let Retry::After(d) = self.delegate.http_failure(&r, None, None) {
sleep(d);
continue;
}
return Err(Ok(r))
}
};
return Ok(h.0.last)
}
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Err(Err(err))
}
}
}
}
/// returns None if operation was cancelled by delegate, or the HttpResult.
/// It can be that we return the result just because we didn't understand the status code -
/// caller should check for status himself before assuming it's OK to use
pub fn upload(&mut self) -> Option<hyper::Result<hyper::client::Response>> {
let mut start = match self.start_at {
Some(s) => s,
None => match self.query_transfer_status() {
Ok(s) => s,
Err(result) => return Some(result)
}
};
const MIN_CHUNK_SIZE: u64 = 1 << 18;
let chunk_size = match self.delegate.chunk_size() {
cs if cs > MIN_CHUNK_SIZE => cs,
_ => MIN_CHUNK_SIZE
};
self.reader.seek(SeekFrom::Start(start)).unwrap();
loop {
let request_size = match self.content_length - start {
rs if rs > chunk_size => chunk_size,
rs => rs
};
let mut section_reader = self.reader.take(request_size);
let range_header = ContentRange {
range: Some(Chunk {first: start, last: start + request_size - 1}),
total_length: self.content_length
};
start += request_size;
if self.delegate.cancel_chunk_upload(&range_header) {
return None
}
let res = self.client.post(self.url)
.header(range_header)
.header(ContentType(self.media_type.clone()))
.header(UserAgent(self.user_agent.to_string()))
.body(&mut section_reader)
.send();
match res {
Ok(mut res) => {
if res.status == StatusCode::PermanentRedirect {
continue
}
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let Retry::After(d) = self.delegate.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
}
return Some(Ok(res))
},
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Some(Err(err))
}
}
}
}
}
// Copy of src/rust/cli/cmn.rs
// TODO(ST): Allow sharing common code between program types
pub fn remove_json_null_values(value: &mut json::value::Value) {
match *value {
json::value::Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-cloudtrace1-cli"
version = "1.0.7+20171202"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with Cloud Trace (protocol v1)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace1-cli"
homepage = "https://cloud.google.com/trace"
documentation = "http://byron.github.io/google-apis-rs/google_cloudtrace1_cli"
license = "MIT"
keywords = ["cloudtrace", "google", "cli"]
[[bin]]
name = "cloudtrace1"
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
strsim = "^0.5"
hyper-rustls = "^0.6"
yup-hyper-mock = "^2.0"
clap = "^2.0"
[features]
[dependencies.google-cloudtrace1]
path = "../cloudtrace1"
version = "1.0.7+20171202"

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,116 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/cli/README.md.mako'
DO NOT EDIT !
-->
The `cloudtrace1` command-line interface *(CLI)* allows to use most features of the *Google Cloud Trace* service from the comfort of your terminal.
By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's
capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero.
If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools.
Everything else about the *Cloud Trace* API can be found at the
[official documentation site](https://cloud.google.com/trace).
# Installation and Source Code
Install the command-line interface with cargo using:
```bash
cargo install google-cloudtrace1-cli
```
Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace1-cli).
# Usage
This documentation was generated from the *Cloud Trace* API at revision *20171202*. The CLI is at version *1.0.7*.
```bash
cloudtrace1 [options]
projects
patch-traces <project-id> (-r <kv>)... [-p <v>]... [-o <out>]
traces-get <project-id> <trace-id> [-p <v>]... [-o <out>]
traces-list <project-id> [-p <v>]... [-o <out>]
cloudtrace1 --help
Configuration:
[--scope <url>]...
Specify the authentication a method should be executed in. Each scope
requires the user to grant this application permission to use it.
If unset, it defaults to the shortest scope url for a particular method.
--config-dir <folder>
A directory into which we will store our persistent data. Defaults to
a user-writable directory that we will create during the first invocation.
[default: ~/.google-service-cli]
--debug
Output all server communication to standard error. `tx` and `rx` are placed
into the same stream.
--debug-auth
Output all communication related to authentication to standard error. `tx`
and `rx` are placed into the same stream.
```
# Configuration
The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `cloudtrace1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis.
More information about the various kinds of persistent data are given in the following paragraphs.
# Authentication
Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the
set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*.
If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a
method that is read-only, it will ask only for a read-only scope.
You may use the `--scope` flag to specify a scope directly.
All applicable scopes are documented in the respective method's CLI documentation.
The first time a scope is used, the user is asked for permission. Follow the instructions given
by the CLI to grant permissions, or to decline.
If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration
directory, e.g. `~/.google-service-cli/cloudtrace1-token-<scope-hash>.json`. No manual management of these tokens
is necessary.
To revoke granted authentication, please refer to the [official documentation][revoke-access].
# Application Secrets
In order to allow any application to use Google services, it will need to be registered using the
[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it
one by one. Most APIs can be used for free and have a daily quota.
To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI
comes with a default application secret that is configured accordingly. This also means that heavy usage
all around the world may deplete the daily quota.
You can workaround this limitation by putting your own secrets file at this location:
`~/.google-service-cli/cloudtrace1-secret.json`, assuming that the required *cloudtrace* API
was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at
*APIs & auth -> Credentials -> Download JSON* and used as is.
Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new].
# Debugging
Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know
what exactly led to a particular issue. This is done by allowing all client-server communication to be
output to standard error *as-is*.
The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag
will cause all communication related to authentication to standard error.
If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the
issue at hand.
You may consider redirecting standard error into a file for ease of use, e.g. `cloudtrace1 --debug <resource> <method> [options] 2>debug.txt`.
[scopes]: https://developers.google.com/+/api/oauth#scopes
[revoke-access]: http://webapps.stackexchange.com/a/30849
[google-dev-console]: https://console.developers.google.com/
[google-project-new]: https://developers.google.com/console/help/new/

View File

@@ -0,0 +1,19 @@
site_name: Cloud Trace v1.0.7+20171202
site_url: http://byron.github.io/google-apis-rs/google-cloudtrace1-cli
site_description: A complete library to interact with Cloud Trace (protocol v1)
repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace1-cli
docs_dir: docs
site_dir: build_html
pages:
- ['index.md', 'Home']
- ['projects_patch-traces.md', 'Projects', 'Patch Traces']
- ['projects_traces-get.md', 'Projects', 'Traces Get']
- ['projects_traces-list.md', 'Projects', 'Traces List']
theme: readthedocs
copyright: Copyright &copy; 2015-2016, `Sebastian Thiel`

View File

@@ -0,0 +1,799 @@
// COPY OF 'src/rust/cli/cmn.rs'
// DO NOT EDIT
use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token};
use serde_json as json;
use serde_json::value::Value;
use mime::Mime;
use clap::{App, SubCommand};
use strsim;
use std::fs;
use std::env;
use std::io;
use std::error::Error as StdError;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
use std::io::{Write, Read, stdout};
use std::default::Default;
const FIELD_SEP: char = '.';
pub enum ComplexType {
Pod,
Vec,
Map,
}
// Null,
// Bool(bool),
// I64(i64),
// U64(u64),
// F64(f64),
// String(String),
pub enum JsonType {
Boolean,
Int,
Uint,
Float,
String,
}
pub struct JsonTypeInfo {
pub jtype: JsonType,
pub ctype: ComplexType,
}
// Based on @erickt user comment. Thanks for the idea !
// Remove all keys whose values are null from given value (changed in place)
pub fn remove_json_null_values(value: &mut Value) {
match *value {
Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}
fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> {
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values {
let confidence = strsim::jaro_winkler(v, pv);
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
}
pub enum CallType {
Upload(UploadProtocol),
Standard,
}
arg_enum!{
pub enum UploadProtocol {
Simple,
Resumable
}
}
impl AsRef<str> for UploadProtocol {
fn as_ref(&self) -> &str {
match *self {
UploadProtocol::Simple => "simple",
UploadProtocol::Resumable => "resumable",
}
}
}
impl AsRef<str> for CallType {
fn as_ref(&self) -> &str {
match *self {
CallType::Upload(ref proto) => proto.as_ref(),
CallType::Standard => "standard-request",
}
}
}
#[derive(Clone, Default)]
pub struct FieldCursor(Vec<String>);
impl ToString for FieldCursor {
fn to_string(&self) -> String {
self.0.join(".")
}
}
impl From<&'static str> for FieldCursor {
fn from(value: &'static str) -> FieldCursor {
let mut res = FieldCursor::default();
res.set(value).unwrap();
res
}
}
fn assure_entry<'a, 'b>(m: &'a mut json::Map<String, Value>, k: &'b String) -> &'a mut Value {
if m.contains_key(k) {
return m.get_mut(k).expect("value to exist");
}
m.insert(k.to_owned(), Value::Object(Default::default()));
m.get_mut(k).expect("value to exist")
}
impl FieldCursor {
pub fn set(&mut self, value: &str) -> Result<(), CLIError> {
if value.len() == 0 {
return Err(CLIError::Field(FieldError::Empty));
}
let mut first_is_field_sep = false;
let mut char_count: usize = 0;
let mut last_c = FIELD_SEP;
let mut num_conscutive_field_seps = 0;
let mut field = String::new();
let mut fields = self.0.clone();
let push_field = |fs: &mut Vec<String>, f: &mut String| {
if f.len() > 0 {
fs.push(f.clone());
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
char_count += 1;
if c == FIELD_SEP {
if cid == 0 {
first_is_field_sep = true;
}
num_conscutive_field_seps += 1;
if cid > 0 && last_c == FIELD_SEP {
if fields.pop().is_none() {
return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string())));
}
} else {
push_field(&mut fields, &mut field);
}
} else {
num_conscutive_field_seps = 0;
if cid == 1 {
if first_is_field_sep {
fields.truncate(0);
}
}
field.push(c);
}
last_c = c;
}
push_field(&mut fields, &mut field);
if char_count == 1 && first_is_field_sep {
fields.truncate(0);
}
if char_count > 1 && num_conscutive_field_seps == 1 {
return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string())));
}
self.0 = fields;
Ok(())
}
pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option<String> {
if value.len() == 0 {
return None;
}
let mut last_c = FIELD_SEP;
let mut field = String::new();
let mut output = String::new();
let push_field = |fs: &mut String, f: &mut String| {
if f.len() > 0 {
fs.push_str(match did_you_mean(&f, possible_values) {
Some(candidate) => candidate,
None => &f,
});
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
if c == FIELD_SEP {
if last_c != FIELD_SEP {
push_field(&mut output, &mut field);
}
output.push(c);
} else {
field.push(c);
}
last_c = c;
}
push_field(&mut output, &mut field);
if &output == value {
None
} else {
Some(output)
}
}
pub fn set_json_value(&self,
mut object: &mut Value,
value: &str,
type_info: JsonTypeInfo,
err: &mut InvalidOptionsError,
orig_cursor: &FieldCursor) {
assert!(self.0.len() > 0);
for field in &self.0[..self.0.len() - 1] {
let tmp = object;
object = match *tmp {
Value::Object(ref mut mapping) => {
assure_entry(mapping, &field)
}
_ => panic!("We don't expect non-object Values here ..."),
};
}
match *object {
Value::Object(ref mut mapping) => {
let field = &self.0[self.0.len() - 1];
let to_jval = |value: &str,
jtype: JsonType,
err: &mut InvalidOptionsError|
-> Value {
match jtype {
JsonType::Boolean =>
Value::Bool(arg_from_str(value, err, &field, "boolean")),
JsonType::Int =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"int"))
.expect("valid f64")),
JsonType::Uint =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"uint"))
.expect("valid f64")),
JsonType::Float =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"float"))
.expect("valid f64")),
JsonType::String => Value::String(value.to_owned()),
}
};
match type_info.ctype {
ComplexType::Pod => {
if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err))
.is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
ComplexType::Vec => {
match *assure_entry(mapping, field) {
Value::Array(ref mut values) =>
values.push(to_jval(value, type_info.jtype, err)),
_ => unreachable!(),
}
}
ComplexType::Map => {
let (key, value) = parse_kv_arg(value, err, true);
let jval = to_jval(value.unwrap_or(""), type_info.jtype, err);
match *assure_entry(mapping, &field) {
Value::Object(ref mut value_map) => {
if value_map.insert(key.to_owned(), jval).is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
_ => unreachable!(),
}
}
}
}
_ => unreachable!(),
}
}
pub fn num_fields(&self) -> usize {
self.0.len()
}
}
pub fn parse_kv_arg<'a>(kv: &'a str,
err: &mut InvalidOptionsError,
for_hashmap: bool)
-> (&'a str, Option<&'a str>) {
let mut add_err = || {
err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(), for_hashmap))
};
match kv.find('=') {
None => {
add_err();
return (kv, None);
}
Some(pos) => {
let key = &kv[..pos];
if kv.len() <= pos + 1 {
add_err();
return (key, Some(""));
}
(key, Some(&kv[pos + 1..]))
}
}
}
pub fn calltype_from_str(name: &str,
valid_protocols: Vec<String>,
err: &mut InvalidOptionsError)
-> CallType {
CallType::Upload(match UploadProtocol::from_str(name) {
Ok(up) => up,
Err(msg) => {
err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols));
UploadProtocol::Simple
}
})
}
pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option<fs::File> {
match fs::File::open(file_path) {
Ok(f) => Some(f),
Err(io_err) => {
err.issues.push(CLIError::Input(InputError::Io((file_path.to_string(), io_err))));
None
}
}
}
pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option<Mime> {
match mime.parse() {
Ok(m) => Some(m),
Err(_) => {
err.issues.push(CLIError::Input(InputError::Mime(mime.to_string())));
None
}
}
}
pub fn writer_from_opts(arg: Option<&str>) -> Result<Box<Write>, io::Error> {
let f = arg.unwrap_or("-");
match f {
"-" => Ok(Box::new(stdout())),
_ => match fs::OpenOptions::new().create(true).write(true).open(f) {
Ok(f) => Ok(Box::new(f)),
Err(io_err) => Err(io_err),
},
}
}
pub fn arg_from_str<'a, T>(arg: &str,
err: &mut InvalidOptionsError,
arg_name: &'a str,
arg_type: &'a str)
-> T
where T: FromStr + Default,
<T as FromStr>::Err: fmt::Display
{
match FromStr::from_str(arg) {
Err(perr) => {
err.issues.push(CLIError::ParseError(arg_name.to_owned(),
arg_type.to_owned(),
arg.to_string(),
format!("{}", perr)));
Default::default()
}
Ok(v) => v,
}
}
pub struct JsonTokenStorage {
pub program_name: &'static str,
pub db_dir: String,
}
impl JsonTokenStorage {
fn path(&self, scope_hash: u64) -> PathBuf {
Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash))
}
}
#[derive(Debug)]
pub enum TokenStorageError {
Json(json::Error),
Io(io::Error),
}
impl fmt::Display for TokenStorageError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
TokenStorageError::Json(ref err) => writeln!(f, "Could not serialize secrets: {}", err),
TokenStorageError::Io(ref err) => writeln!(f, "Failed to write secret token: {}", err),
}
}
}
impl StdError for TokenStorageError {
fn description(&self) -> &str {
"Failure when getting or setting the token storage"
}
}
impl TokenStorage for JsonTokenStorage {
type Error = TokenStorageError;
// NOTE: logging might be interesting, currently we swallow all errors
fn set(&mut self,
scope_hash: u64,
_: &Vec<&str>,
token: Option<Token>)
-> Result<(), TokenStorageError> {
match token {
None => {
match fs::remove_file(self.path(scope_hash)) {
Err(err) => match err.kind() {
io::ErrorKind::NotFound => Ok(()),
_ => Err(TokenStorageError::Io(err)),
},
Ok(_) => Ok(()),
}
}
Some(token) => {
match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) {
Ok(mut f) => {
match json::to_writer_pretty(&mut f, &token) {
Ok(_) => Ok(()),
Err(serde_err) => Err(TokenStorageError::Json(serde_err)),
}
}
Err(io_err) => Err(TokenStorageError::Io(io_err)),
}
}
}
}
fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result<Option<Token>, TokenStorageError> {
match fs::File::open(&self.path(scope_hash)) {
Ok(f) => {
match json::de::from_reader(f) {
Ok(token) => Ok(Some(token)),
Err(err) => Err(TokenStorageError::Json(err)),
}
}
Err(io_err) => {
match io_err.kind() {
io::ErrorKind::NotFound => Ok(None),
_ => Err(TokenStorageError::Io(io_err)),
}
}
}
}
}
#[derive(Debug)]
pub enum ApplicationSecretError {
DecoderError((String, json::Error)),
FormatError(String),
}
impl fmt::Display for ApplicationSecretError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ApplicationSecretError::DecoderError((ref path, ref err)) =>
writeln!(f,
"Could not decode file at '{}' with error: {}.",
path,
err),
ApplicationSecretError::FormatError(ref path) =>
writeln!(f,
"'installed' field is unset in secret file at '{}'.",
path),
}
}
}
#[derive(Debug)]
pub enum ConfigurationError {
DirectoryCreationFailed((String, io::Error)),
DirectoryUnset,
HomeExpansionFailed(String),
Secret(ApplicationSecretError),
Io((String, io::Error)),
}
impl fmt::Display for ConfigurationError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) =>
writeln!(f,
"Directory '{}' could not be created with error: {}.",
dir,
err),
ConfigurationError::DirectoryUnset => writeln!(f, "--config-dir was unset or empty."),
ConfigurationError::HomeExpansionFailed(ref dir) =>
writeln!(f,
"Couldn't find HOME directory of current user, failed to expand '{}'.",
dir),
ConfigurationError::Secret(ref err) => writeln!(f, "Secret -> {}", err),
ConfigurationError::Io((ref path, ref err)) =>
writeln!(f,
"IO operation failed on path '{}' with error: {}.",
path,
err),
}
}
}
#[derive(Debug)]
pub enum InputError {
Io((String, io::Error)),
Mime(String),
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
InputError::Io((ref file_path, ref io_err)) =>
writeln!(f,
"Failed to open '{}' for reading with error: {}.",
file_path,
io_err),
InputError::Mime(ref mime) => writeln!(f, "'{}' is not a known mime-type.", mime),
}
}
}
#[derive(Debug)]
pub enum FieldError {
PopOnEmpty(String),
TrailingFieldSep(String),
Unknown(String, Option<String>, Option<String>),
Duplicate(String),
Empty,
}
impl fmt::Display for FieldError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
FieldError::PopOnEmpty(ref field) =>
writeln!(f, "'{}': Cannot move up on empty field cursor.", field),
FieldError::TrailingFieldSep(ref field) =>
writeln!(f,
"'{}': Single field separator may not be last character.",
field),
FieldError::Unknown(ref field, ref suggestion, ref value) => {
let suffix = match *suggestion {
Some(ref s) => {
let kv = match *value {
Some(ref v) => format!("{}={}", s, v),
None => s.clone(),
};
format!(" Did you mean '{}' ?", kv)
}
None => String::new(),
};
writeln!(f, "Field '{}' does not exist.{}", field, suffix)
}
FieldError::Duplicate(ref cursor) =>
writeln!(f, "Value at '{}' was already set", cursor),
FieldError::Empty => writeln!(f, "Field names must not be empty."),
}
}
}
#[derive(Debug)]
pub enum CLIError {
Configuration(ConfigurationError),
ParseError(String, String, String, String),
UnknownParameter(String, Vec<&'static str>),
InvalidUploadProtocol(String, Vec<String>),
InvalidKeyValueSyntax(String, bool),
Input(InputError),
Field(FieldError),
MissingCommandError,
MissingMethodError(String),
}
impl fmt::Display for CLIError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err),
CLIError::Input(ref err) => write!(f, "Input -> {}", err),
CLIError::Field(ref err) => write!(f, "Field -> {}", err),
CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) =>
writeln!(f,
"'{}' is not a valid upload protocol. Choose from one of {}.",
proto_name,
valid_names.join(", ")),
CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) =>
writeln!(f,
"Failed to parse argument '{}' with value '{}' as {} with error: {}.",
arg_name,
value,
type_name,
err_desc),
CLIError::UnknownParameter(ref param_name, ref possible_values) => {
let suffix = match did_you_mean(param_name, &possible_values) {
Some(v) => format!(" Did you mean '{}' ?", v),
None => String::new(),
};
write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix)
}
CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => {
let hashmap_info = if is_hashmap {
"hashmap "
} else {
""
};
writeln!(f,
"'{}' does not match {}pattern <key>=<value>.",
kv,
hashmap_info)
}
CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."),
CLIError::MissingMethodError(ref cmd) =>
writeln!(f,
"Please specify the method to call on the '{}' command.",
cmd),
}
}
}
#[derive(Debug)]
pub struct InvalidOptionsError {
pub issues: Vec<CLIError>,
pub exit_code: i32,
}
impl fmt::Display for InvalidOptionsError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for issue in &self.issues {
try!(issue.fmt(f));
}
Ok(())
}
}
impl InvalidOptionsError {
pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError {
InvalidOptionsError {
issues: vec![err],
exit_code: exit_code,
}
}
pub fn new() -> InvalidOptionsError {
InvalidOptionsError {
issues: Vec::new(),
exit_code: 1,
}
}
}
pub fn assure_config_dir_exists(dir: &str) -> Result<String, CLIError> {
let trdir = dir.trim();
if trdir.len() == 0 {
return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset));
}
let expanded_config_dir = if trdir.as_bytes()[0] == b'~' {
match env::var("HOME").ok().or(env::var("UserProfile").ok()) {
None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))),
Some(mut user) => {
user.push_str(&trdir[1..]);
user
}
}
} else {
trdir.to_string()
};
if let Err(err) = fs::create_dir(&expanded_config_dir) {
if err.kind() != io::ErrorKind::AlreadyExists {
return Err(CLIError::Configuration(
ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err))));
}
}
Ok(expanded_config_dir)
}
pub fn application_secret_from_directory(dir: &str,
secret_basename: &str,
json_console_secret: &str)
-> Result<ApplicationSecret, CLIError> {
let secret_path = Path::new(dir).join(secret_basename);
let secret_str = || secret_path.as_path().to_str().unwrap().to_string();
let secret_io_error = |io_err: io::Error| {
Err(CLIError::Configuration(ConfigurationError::Io((secret_str(), io_err))))
};
for _ in 0..2 {
match fs::File::open(&secret_path) {
Err(mut err) => {
if err.kind() == io::ErrorKind::NotFound {
// Write our built-in one - user may adjust the written file at will
err = match fs::OpenOptions::new()
.create(true)
.write(true)
.open(&secret_path) {
Err(cfe) => cfe,
Ok(mut f) => {
// Assure we convert 'ugly' json string into pretty one
let console_secret: ConsoleApplicationSecret =
json::from_str(json_console_secret).unwrap();
match json::to_writer_pretty(&mut f, &console_secret) {
Err(serde_err) =>
panic!("Unexpected serde error: {:#?}", serde_err),
Ok(_) => continue,
}
}
};
// fall through to IO error handling
}
return secret_io_error(err);
}
Ok(f) => {
match json::de::from_reader::<_, ConsoleApplicationSecret>(f) {
Err(json_err) =>
return Err(CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::DecoderError(
(secret_str(), json_err)
)))),
Ok(console_secret) => match console_secret.installed {
Some(secret) => return Ok(secret),
None => return Err(
CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::FormatError(secret_str())
))),
},
}
}
}
}
unreachable!();
}

View File

@@ -0,0 +1,550 @@
// DO NOT EDIT !
// This file was generated automatically from 'src/mako/cli/main.rs.mako'
// DO NOT EDIT !
#![allow(unused_variables, unused_imports, dead_code, unused_mut)]
#[macro_use]
extern crate clap;
extern crate yup_oauth2 as oauth2;
extern crate yup_hyper_mock as mock;
extern crate hyper_rustls;
extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate mime;
extern crate strsim;
extern crate google_cloudtrace1 as api;
use std::env;
use std::io::{self, Write};
use clap::{App, SubCommand, Arg};
mod cmn;
use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg,
input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol,
calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo};
use std::default::Default;
use std::str::FromStr;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, FlowType};
use serde_json as json;
use clap::ArgMatches;
enum DoitError {
IoError(String, io::Error),
ApiError(api::Error),
}
struct Engine<'n> {
opt: ArgMatches<'n>,
hub: api::CloudTrace<hyper::Client, Authenticator<DefaultAuthenticatorDelegate, JsonTokenStorage, hyper::Client>>,
gp: Vec<&'static str>,
gpm: Vec<(&'static str, &'static str)>,
}
impl<'n> Engine<'n> {
fn _projects_patch_traces(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec![]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::Traces = json::value::from_value(object).unwrap();
let mut call = self.hub.projects().patch_traces(request, opt.value_of("project-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _projects_traces_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.projects().traces_get(opt.value_of("project-id").unwrap_or(""), opt.value_of("trace-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _projects_traces_list(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.projects().traces_list(opt.value_of("project-id").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"view" => {
call = call.view(value.unwrap_or(""));
},
"start-time" => {
call = call.start_time(value.unwrap_or(""));
},
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"page-size" => {
call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer"));
},
"order-by" => {
call = call.order_by(value.unwrap_or(""));
},
"filter" => {
call = call.filter(value.unwrap_or(""));
},
"end-time" => {
call = call.end_time(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["order-by", "page-size", "filter", "page-token", "start-time", "end-time", "view"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _doit(&self, dry_run: bool) -> Result<Result<(), DoitError>, Option<InvalidOptionsError>> {
let mut err = InvalidOptionsError::new();
let mut call_result: Result<(), DoitError> = Ok(());
let mut err_opt: Option<InvalidOptionsError> = None;
match self.opt.subcommand() {
("projects", Some(opt)) => {
match opt.subcommand() {
("patch-traces", Some(opt)) => {
call_result = self._projects_patch_traces(opt, dry_run, &mut err);
},
("traces-get", Some(opt)) => {
call_result = self._projects_traces_get(opt, dry_run, &mut err);
},
("traces-list", Some(opt)) => {
call_result = self._projects_traces_list(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("projects".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
_ => {
err.issues.push(CLIError::MissingCommandError);
writeln!(io::stderr(), "{}\n", self.opt.usage()).ok();
}
}
if dry_run {
if err.issues.len() > 0 {
err_opt = Some(err);
}
Err(err_opt)
} else {
Ok(call_result)
}
}
// Please note that this call will fail if any part of the opt can't be handled
fn new(opt: ArgMatches<'n>) -> Result<Engine<'n>, InvalidOptionsError> {
let (config_dir, secret) = {
let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) {
Err(e) => return Err(InvalidOptionsError::single(e, 3)),
Ok(p) => p,
};
match cmn::application_secret_from_directory(&config_dir, "cloudtrace1-secret.json",
"{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") {
Ok(secret) => (config_dir, secret),
Err(e) => return Err(InvalidOptionsError::single(e, 4))
}
};
let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate,
if opt.is_present("debug-auth") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
},
JsonTokenStorage {
program_name: "cloudtrace1",
db_dir: config_dir.clone(),
}, Some(FlowType::InstalledRedirect(54324)));
let client =
if opt.is_present("debug") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
};
let engine = Engine {
opt: opt,
hub: api::CloudTrace::new(client, auth),
gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"],
gpm: vec![
("$-xgafv", "$.xgafv"),
("access-token", "access_token"),
("bearer-token", "bearer_token"),
("oauth-token", "oauth_token"),
("pretty-print", "prettyPrint"),
("quota-user", "quotaUser"),
("upload-type", "uploadType"),
("upload-protocol", "upload_protocol"),
]
};
match engine._doit(true) {
Err(Some(err)) => Err(err),
Err(None) => Ok(engine),
Ok(_) => unreachable!(),
}
}
fn doit(&self) -> Result<(), DoitError> {
match self._doit(false) {
Ok(res) => res,
Err(_) => unreachable!(),
}
}
}
fn main() {
let mut exit_status = 0i32;
let arg_data = [
("projects", "methods: 'patch-traces', 'traces-get' and 'traces-list'", vec![
("patch-traces",
Some(r##"Sends new traces to Stackdriver Trace or updates existing traces. If the ID
of a trace that you send matches that of an existing trace, any fields
in the existing trace and its spans are overwritten by the provided values,
and any new fields provided are merged with the existing trace data. If the
ID does not match, a new trace is created."##),
"Details at http://byron.github.io/google-apis-rs/google_cloudtrace1_cli/projects_patch-traces",
vec![
(Some(r##"project-id"##),
None,
Some(r##"ID of the Cloud project where the trace data is stored."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("traces-get",
Some(r##"Gets a single trace by its ID."##),
"Details at http://byron.github.io/google-apis-rs/google_cloudtrace1_cli/projects_traces-get",
vec![
(Some(r##"project-id"##),
None,
Some(r##"ID of the Cloud project where the trace data is stored."##),
Some(true),
Some(false)),
(Some(r##"trace-id"##),
None,
Some(r##"ID of the trace to return."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("traces-list",
Some(r##"Returns of a list of traces that match the specified filter conditions."##),
"Details at http://byron.github.io/google-apis-rs/google_cloudtrace1_cli/projects_traces-list",
vec![
(Some(r##"project-id"##),
None,
Some(r##"ID of the Cloud project where the trace data is stored."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
];
let mut app = App::new("cloudtrace1")
.author("Sebastian Thiel <byronimo@gmail.com>")
.version("1.0.7+20171202")
.about("Sends application trace data to Stackdriver Trace for viewing. Trace data is collected for all App Engine applications by default. Trace data from other applications can be provided using this API.
")
.after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_cloudtrace1_cli")
.arg(Arg::with_name("url")
.long("scope")
.help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.")
.multiple(true)
.takes_value(true))
.arg(Arg::with_name("folder")
.long("config-dir")
.help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli")
.multiple(false)
.takes_value(true))
.arg(Arg::with_name("debug")
.long("debug")
.help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false))
.arg(Arg::with_name("debug-auth")
.long("debug-auth")
.help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false));
for &(main_command_name, about, ref subcommands) in arg_data.iter() {
let mut mcmd = SubCommand::with_name(main_command_name).about(about);
for &(sub_command_name, ref desc, url_info, ref args) in subcommands {
let mut scmd = SubCommand::with_name(sub_command_name);
if let &Some(desc) = desc {
scmd = scmd.about(desc);
}
scmd = scmd.after_help(url_info);
for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args {
let arg_name_str =
match (arg_name, flag) {
(&Some(an), _ ) => an,
(_ , &Some(f)) => f,
_ => unreachable!(),
};
let mut arg = Arg::with_name(arg_name_str)
.empty_values(false);
if let &Some(short_flag) = flag {
arg = arg.short(short_flag);
}
if let &Some(desc) = desc {
arg = arg.help(desc);
}
if arg_name.is_some() && flag.is_some() {
arg = arg.takes_value(true);
}
if let &Some(required) = required {
arg = arg.required(required);
}
if let &Some(multi) = multi {
arg = arg.multiple(multi);
}
scmd = scmd.arg(arg);
}
mcmd = mcmd.subcommand(scmd);
}
app = app.subcommand(mcmd);
}
let matches = app.get_matches();
let debug = matches.is_present("debug");
match Engine::new(matches) {
Err(err) => {
exit_status = err.exit_code;
writeln!(io::stderr(), "{}", err).ok();
},
Ok(engine) => {
if let Err(doit_err) = engine.doit() {
exit_status = 1;
match doit_err {
DoitError::IoError(path, err) => {
writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok();
},
DoitError::ApiError(err) => {
if debug {
writeln!(io::stderr(), "{:#?}", err).ok();
} else {
writeln!(io::stderr(), "{}", err).ok();
}
}
}
}
}
}
std::process::exit(exit_status);
}

View File

@@ -0,0 +1,31 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-cloudtrace1"
version = "1.0.7+20171202"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with Cloud Trace (protocol v1)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace1"
homepage = "https://cloud.google.com/trace"
documentation = "https://docs.rs/google-cloudtrace1/1.0.7+20171202"
license = "MIT"
keywords = ["cloudtrace", "google", "protocol", "web", "api"]
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
url = "= 0.5"
[features]

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

174
gen/cloudtrace1/README.md Normal file
View File

@@ -0,0 +1,174 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/api/README.md.mako'
DO NOT EDIT !
-->
The `google-cloudtrace1` library allows access to all features of the *Google Cloud Trace* service.
This documentation was generated from *Cloud Trace* crate version *1.0.7+20171202*, where *20171202* is the exact revision of the *cloudtrace:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.7*.
Everything else about the *Cloud Trace* *v1* API can be found at the
[official documentation site](https://cloud.google.com/trace).
# Features
Handle the following *Resources* with ease from the central [hub](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/struct.CloudTrace.html) ...
* projects
* [*patch traces*](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/struct.ProjectPatchTraceCall.html), [*traces get*](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/struct.ProjectTraceGetCall.html) and [*traces list*](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/struct.ProjectTraceListCall.html)
# Structure of this Library
The API is structured into the following primary items:
* **[Hub](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/struct.CloudTrace.html)**
* a central object to maintain state and allow accessing all *Activities*
* creates [*Method Builders*](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.MethodsBuilder.html) which in turn
allow access to individual [*Call Builders*](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.CallBuilder.html)
* **[Resources](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.Resource.html)**
* primary types that you can apply *Activities* to
* a collection of properties and *Parts*
* **[Parts](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.Part.html)**
* a collection of properties
* never directly used in *Activities*
* **[Activities](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.CallBuilder.html)**
* operations to apply to *Resources*
All *structures* are marked with applicable traits to further categorize them and ease browsing.
Generally speaking, you can invoke *Activities* like this:
```Rust,ignore
let r = hub.resource().activity(...).doit()
```
Or specifically ...
```ignore
let r = hub.projects().traces_get(...).doit()
```
The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
The `doit()` method performs the actual communication with the server and returns the respective result.
# Usage
## Setting up your Project
To use this library, you would put the following lines into your `Cargo.toml` file:
```toml
[dependencies]
google-cloudtrace1 = "*"
```
## A complete example
```Rust
extern crate hyper;
extern crate hyper_rustls;
extern crate yup_oauth2 as oauth2;
extern crate google_cloudtrace1 as cloudtrace1;
use cloudtrace1::{Result, Error};
use std::default::Default;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
use cloudtrace1::CloudTrace;
// Get an ApplicationSecret instance by some means. It contains the `client_id` and
// `client_secret`, among other things.
let secret: ApplicationSecret = Default::default();
// Instantiate the authenticator. It will choose a suitable authentication flow for you,
// unless you replace `None` with the desired Flow.
// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
// retrieve them from storage.
let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
<MemoryStorage as Default>::default(), None);
let mut hub = CloudTrace::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
// You can configure optional parameters by calling the respective setters at will, and
// execute the final call using `doit()`.
// Values shown here are possibly random and not representative !
let result = hub.projects().traces_get("projectId", "traceId")
.doit();
match result {
Err(e) => match e {
// The Error enum provides details about what exactly happened.
// You can also just use its `Debug`, `Display` or `Error` traits
Error::HttpError(_)
|Error::MissingAPIKey
|Error::MissingToken(_)
|Error::Cancelled
|Error::UploadSizeLimitExceeded(_, _)
|Error::Failure(_)
|Error::BadRequest(_)
|Error::FieldClash(_)
|Error::JsonDecodeError(_, _) => println!("{}", e),
},
Ok(res) => println!("Success: {:?}", res),
}
```
## Handling Errors
All errors produced by the system are provided either as [Result](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/enum.Result.html) enumeration as return value of
the doit() methods, or handed as possibly intermediate results to either the
[Hub Delegate](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.Delegate.html), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html).
When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
makes the system potentially resilient to all kinds of errors.
## Uploads and Downloads
If a method supports downloads, the response body, which is part of the [Result](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/enum.Result.html), should be
read by you to obtain the media.
If such a method also supports a [Response Result](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.ResponseResult.html), it will return that by default.
You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
this call: `.param("alt", "media")`.
Methods supporting uploads can do so using up to 2 different protocols:
*simple* and *resumable*. The distinctiveness of each is represented by customized
`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
## Customization and Callbacks
You may alter the way an `doit()` method is called by providing a [delegate](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.Delegate.html) to the
[Method Builder](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.CallBuilder.html) before making the final `doit()` call.
Respective methods will be called to provide progress information, as well as determine whether the system should
retry on failure.
The [delegate trait](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
## Optional Parts in Server-Requests
All structures provided by this library are made to be [enocodable](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.RequestValue.html) and
[decodable](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
are valid.
Most optionals are are considered [Parts](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.Part.html) which are identifiable by name, which will be sent to
the server to indicate either the set parts of the request or the desired parts in the response.
## Builder Arguments
Using [method builders](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods.
These will always take a single argument, for which the following statements are true.
* [PODs][wiki-pod] are handed by copy
* strings are passed as `&str`
* [request values](https://docs.rs/google-cloudtrace1/1.0.7+20171202/google_cloudtrace1/trait.RequestValue.html) are moved
Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
[google-go-api]: https://github.com/google/google-api-go-client
# License
The **cloudtrace1** library was generated by Sebastian Thiel, and is placed
under the *MIT* license.
You can read the full text at the repository's [license file][repo-license].
[repo-license]: https://github.com/Byron/google-apis-rsblob/master/LICENSE.md

753
gen/cloudtrace1/src/cmn.rs Normal file
View File

@@ -0,0 +1,753 @@
// COPY OF 'src/rust/api/cmn.rs'
// DO NOT EDIT
use std::io::{self, Read, Seek, Cursor, Write, SeekFrom};
use std;
use std::fmt::{self, Display};
use std::str::FromStr;
use std::error;
use std::thread::sleep;
use std::time::Duration;
use mime::{Mime, TopLevel, SubLevel, Attr, Value};
use oauth2::{TokenType, Retry, self};
use hyper;
use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header,
HeaderFormat, Bearer};
use hyper::http::h1::LINE_ENDING;
use hyper::method::Method;
use hyper::status::StatusCode;
use serde_json as json;
/// Identifies the Hub. There is only one per library, this trait is supposed
/// to make intended use more explicit.
/// The hub allows to access all resource methods more easily.
pub trait Hub {}
/// Identifies types for building methods of a particular resource type
pub trait MethodsBuilder {}
/// Identifies types which represent builders for a particular resource method
pub trait CallBuilder {}
/// Identifies types which can be inserted and deleted.
/// Types with this trait are most commonly used by clients of this API.
pub trait Resource {}
/// Identifies types which are used in API responses.
pub trait ResponseResult {}
/// Identifies types which are used in API requests.
pub trait RequestValue {}
/// Identifies types which are not actually used by the API
/// This might be a bug within the google API schema.
pub trait UnusedType {}
/// Identifies types which are only used as part of other types, which
/// usually are carrying the `Resource` trait.
pub trait Part {}
/// Identifies types which are only used by other types internally.
/// They have no special meaning, this trait just marks them for completeness.
pub trait NestedType {}
/// A utility to specify reader types which provide seeking capabilities too
pub trait ReadSeek: Seek + Read {}
impl<T: Seek + Read> ReadSeek for T {}
/// A trait for all types that can convert themselves into a *parts* string
pub trait ToParts {
fn to_parts(&self) -> String;
}
/// A utility type which can decode a server response that indicates error
#[derive(Deserialize)]
pub struct JsonServerError {
pub error: String,
pub error_description: Option<String>
}
/// A utility to represent detailed errors we might see in case there are BadRequests.
/// The latter happen if the sent parameters or request structures are unsound
#[derive(Deserialize, Serialize, Debug)]
pub struct ErrorResponse {
error: ServerError,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerError {
errors: Vec<ServerMessage>,
code: u16,
message: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerMessage {
domain: String,
reason: String,
message: String,
#[serde(rename="locationType")]
location_type: Option<String>,
location: Option<String>
}
#[derive(Copy, Clone)]
pub struct DummyNetworkStream;
impl Read for DummyNetworkStream {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl Write for DummyNetworkStream {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl hyper::net::NetworkStream for DummyNetworkStream {
fn peer_addr(&mut self) -> io::Result<std::net::SocketAddr> {
Ok("127.0.0.1:1337".parse().unwrap())
}
fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
}
/// A trait specifying functionality to help controlling any request performed by the API.
/// The trait has a conservative default implementation.
///
/// It contains methods to deal with all common issues, as well with the ones related to
/// uploading media
pub trait Delegate {
/// Called at the beginning of any API request. The delegate should store the method
/// information if he is interesting in knowing more context when further calls to it
/// are made.
/// The matching `finished()` call will always be made, no matter whether or not the API
/// request was successful. That way, the delegate may easily maintain a clean state
/// between various API calls.
fn begin(&mut self, MethodInfo) {}
/// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
///
/// Return retry information.
fn http_error(&mut self, &hyper::Error) -> Retry {
Retry::Abort
}
/// Called whenever there is the need for your applications API key after
/// the official authenticator implementation didn't provide one, for some reason.
/// If this method returns None as well, the underlying operation will fail
fn api_key(&mut self) -> Option<String> {
None
}
/// Called whenever the Authenticator didn't yield a token. The delegate
/// may attempt to provide one, or just take it as a general information about the
/// impending failure.
/// The given Error provides information about why the token couldn't be acquired in the
/// first place
fn token(&mut self, err: &error::Error) -> Option<oauth2::Token> {
let _ = err;
None
}
/// Called during resumable uploads to provide a URL for the impending upload.
/// It was saved after a previous call to `store_upload_url(...)`, and if not None,
/// will be used instead of asking the server for a new upload URL.
/// This is useful in case a previous resumable upload was aborted/canceled, but should now
/// be resumed.
/// The returned URL will be used exactly once - if it fails again and the delegate allows
/// to retry, we will ask the server for a new upload URL.
fn upload_url(&mut self) -> Option<String> {
None
}
/// Called after we have retrieved a new upload URL for a resumable upload to store it
/// in case we fail or cancel. That way, we can attempt to resume the upload later,
/// see `upload_url()`.
/// It will also be called with None after a successful upload, which allows the delegate
/// to forget the URL. That way, we will not attempt to resume an upload that has already
/// finished.
fn store_upload_url(&mut self, url: Option<&str>) {
let _ = url;
}
/// Called whenever a server response could not be decoded from json.
/// It's for informational purposes only, the caller will return with an error
/// accordingly.
///
/// # Arguments
///
/// * `json_encoded_value` - The json-encoded value which failed to decode.
/// * `json_decode_error` - The decoder error
fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &json::Error) {
let _ = json_encoded_value;
let _ = json_decode_error;
}
/// Called whenever the http request returns with a non-success status code.
/// This can involve authentication issues, or anything else that very much
/// depends on the used API method.
/// The delegate should check the status, header and decoded json error to decide
/// whether to retry or not. In the latter case, the underlying call will fail.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
fn http_failure(&mut self, _: &hyper::client::Response, Option<JsonServerError>, _: Option<ServerError>) -> Retry {
Retry::Abort
}
/// Called prior to sending the main request of the given method. It can be used to time
/// the call or to print progress information.
/// It's also useful as you can be sure that a request will definitely be made.
fn pre_request(&mut self) { }
/// Return the size of each chunk of a resumable upload.
/// Must be a power of two, with 1<<18 being the smallest allowed chunk size.
/// Will be called once before starting any resumable upload.
fn chunk_size(&mut self) -> u64 {
1 << 23
}
/// Called before the given chunk is uploaded to the server.
/// If true is returned, the upload will be interrupted.
/// However, it may be resumable if you stored the upload URL in a previous call
/// to `store_upload_url()`
fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool {
let _ = chunk;
false
}
/// Called before the API request method returns, in every case. It can be used to clean up
/// internal state between calls to the API.
/// This call always has a matching call to `begin(...)`.
///
/// # Arguments
///
/// * `is_success` - a true value indicates the operation was successful. If false, you should
/// discard all values stored during `store_upload_url`.
fn finished(&mut self, is_success: bool) {
let _ = is_success;
}
}
/// A delegate with a conservative default implementation, which is used if no other delegate is
/// set.
#[derive(Default)]
pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}
#[derive(Debug)]
pub enum Error {
/// The http connection failed
HttpError(hyper::Error),
/// An attempt was made to upload a resource with size stored in field `.0`
/// even though the maximum upload size is what is stored in field `.1`.
UploadSizeLimitExceeded(u64, u64),
/// Represents information about a request that was not understood by the server.
/// Details are included.
BadRequest(ErrorResponse),
/// We needed an API key for authentication, but didn't obtain one.
/// Neither through the authenticator, nor through the Delegate.
MissingAPIKey,
/// We required a Token, but didn't get one from the Authenticator
MissingToken(Box<error::Error>),
/// The delgate instructed to cancel the operation
Cancelled,
/// An additional, free form field clashed with one of the built-in optional ones
FieldClash(&'static str),
/// Shows that we failed to decode the server response.
/// This can happen if the protocol changes in conjunction with strict json decoding.
JsonDecodeError(String, json::Error),
/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref err) => err.fmt(f),
Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) =>
writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}"
, resource_size, max_size),
Error::MissingAPIKey => {
(writeln!(f, "The application's API key was not found in the configuration")).ok();
writeln!(f, "It is used as there are no Scopes defined for this method.")
},
Error::BadRequest(ref err) => {
try!(writeln!(f, "Bad Request ({}): {}", err.error.code, err.error.message));
for err in err.error.errors.iter() {
try!(writeln!(f, " {}: {}, {}{}",
err.domain,
err.message,
err.reason,
match &err.location {
&Some(ref loc) => format!("@{}", loc),
&None => String::new(),
}));
}
Ok(())
},
Error::MissingToken(ref err) =>
writeln!(f, "Token retrieval failed with error: {}", err),
Error::Cancelled =>
writeln!(f, "Operation cancelled by delegate"),
Error::FieldClash(field) =>
writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field),
Error::JsonDecodeError(ref json_str, ref err)
=> writeln!(f, "{}: {}", err, json_str),
Error::Failure(ref response) =>
writeln!(f, "Http status indicates failure: {:?}", response),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::HttpError(ref err) => err.description(),
Error::JsonDecodeError(_, ref err) => err.description(),
_ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead"
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::HttpError(ref err) => err.cause(),
Error::JsonDecodeError(_, ref err) => err.cause(),
_ => None
}
}
}
/// A universal result type used as return for all calls.
pub type Result<T> = std::result::Result<T, Error>;
/// Contains information about an API request.
pub struct MethodInfo {
pub id: &'static str,
pub http_method: Method,
}
const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d";
/// Provides a `Read` interface that converts multiple parts into the protocol
/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387).
/// **Note**: This implementation is just as rich as it needs to be to perform uploads
/// to google APIs, and might not be a fully-featured implementation.
#[derive(Default)]
pub struct MultiPartReader<'a> {
raw_parts: Vec<(Headers, &'a mut Read)>,
current_part: Option<(Cursor<Vec<u8>>, &'a mut Read)>,
last_part_boundary: Option<Cursor<Vec<u8>>>,
}
impl<'a> MultiPartReader<'a> {
/// Reserve memory for exactly the given amount of parts
pub fn reserve_exact(&mut self, cap: usize) {
self.raw_parts.reserve_exact(cap);
}
/// Add a new part to the queue of parts to be read on the first `read` call.
///
/// # Arguments
///
/// `headers` - identifying the body of the part. It's similar to the header
/// in an ordinary single-part call, and should thus contain the
/// same information.
/// `reader` - a reader providing the part's body
/// `size` - the amount of bytes provided by the reader. It will be put onto the header as
/// content-size.
/// `mime` - It will be put onto the content type
pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> {
let mut headers = Headers::new();
headers.set(ContentType(mime_type));
headers.set(ContentLength(size));
self.raw_parts.push((headers, reader));
self
}
/// Returns the mime-type representing our multi-part message.
/// Use it with the ContentType header.
pub fn mime_type(&self) -> Mime {
Mime(
TopLevel::Multipart,
SubLevel::Ext("Related".to_string()),
vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))],
)
}
/// Returns true if we are totally used
fn is_depleted(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none()
}
/// Returns true if we are handling our last part
fn is_last_part(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_some()
}
}
impl<'a> Read for MultiPartReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.raw_parts.len(),
self.current_part.is_none(),
self.last_part_boundary.is_none()) {
(_, _, false) => {
let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0);
if br < buf.len() {
self.last_part_boundary = None;
}
return Ok(br)
},
(0, true, true) => return Ok(0),
(n, true, _) if n > 0 => {
let (headers, reader) = self.raw_parts.remove(0);
let mut c = Cursor::new(Vec::<u8>::new());
(write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING,
headers, LINE_ENDING)).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
self.current_part = Some((c, reader));
}
_ => {},
}
// read headers as long as possible
let (hb, rr) = {
let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap();
let b = c.read(buf).unwrap_or(0);
(b, reader.read(&mut buf[b..]))
};
match rr {
Ok(bytes_read) => {
if hb < buf.len() && bytes_read == 0 {
if self.is_last_part() {
// before clearing the last part, we will add the boundary that
// will be written last
self.last_part_boundary = Some(Cursor::new(
format!("{}--{}--", LINE_ENDING, BOUNDARY).into_bytes()))
}
// We are depleted - this can trigger the next part to come in
self.current_part = None;
}
let mut total_bytes_read = hb + bytes_read;
while total_bytes_read < buf.len() && !self.is_depleted() {
match self.read(&mut buf[total_bytes_read ..]) {
Ok(br) => total_bytes_read += br,
Err(err) => return Err(err),
}
}
Ok(total_bytes_read)
}
Err(err) => {
// fail permanently
self.current_part = None;
self.last_part_boundary = None;
self.raw_parts.clear();
Err(err)
}
}
}
}
/// The `X-Upload-Content-Type` header.
///
/// Generated via rustc --pretty expanded -Z unstable-options, and manually
/// processed to be more readable.
#[derive(PartialEq, Debug, Clone)]
pub struct XUploadContentType(pub Mime);
impl ::std::ops::Deref for XUploadContentType {
type Target = Mime;
fn deref<'a>(&'a self) -> &'a Mime { &self.0 }
}
impl ::std::ops::DerefMut for XUploadContentType {
fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 }
}
impl Header for XUploadContentType {
fn header_name() -> &'static str { "X-Upload-Content-Type" }
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType)
}
}
impl HeaderFormat for XUploadContentType {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&**self, f)
}
}
impl Display for XUploadContentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chunk {
pub first: u64,
pub last: u64
}
impl fmt::Display for Chunk {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(write!(fmt, "{}-{}", self.first, self.last)).ok();
Ok(())
}
}
impl FromStr for Chunk {
type Err = &'static str;
/// NOTE: only implements `%i-%i`, not `*`
fn from_str(s: &str) -> std::result::Result<Chunk, &'static str> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 2 {
return Err("Expected two parts: %i-%i")
}
Ok(
Chunk {
first: match FromStr::from_str(parts[0]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'first' as digit")
},
last: match FromStr::from_str(parts[1]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'last' as digit")
}
}
)
}
}
/// Implements the Content-Range header, for serialization only
#[derive(Clone, PartialEq, Debug)]
pub struct ContentRange {
pub range: Option<Chunk>,
pub total_length: u64,
}
impl Header for ContentRange {
fn header_name() -> &'static str {
"Content-Range"
}
/// We are not parsable, as parsing is done by the `Range` header
fn parse_header(_: &[Vec<u8>]) -> hyper::error::Result<Self> {
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for ContentRange {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("bytes "));
match self.range {
Some(ref c) => try!(c.fmt(fmt)),
None => try!(fmt.write_str("*"))
}
(write!(fmt, "/{}", self.total_length)).ok();
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct RangeResponseHeader(pub Chunk);
impl Header for RangeResponseHeader {
fn header_name() -> &'static str {
"Range"
}
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
if raw.len() > 0 {
let v = &raw[0];
if let Ok(s) = std::str::from_utf8(v) {
const PREFIX: &'static str = "bytes ";
if s.starts_with(PREFIX) {
if let Ok(c) = <Chunk as FromStr>::from_str(&s[PREFIX.len()..]) {
return Ok(RangeResponseHeader(c))
}
}
}
}
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for RangeResponseHeader {
/// No implmentation necessary, we just need to parse
fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
/// A utility type to perform a resumable upload from start to end.
pub struct ResumableUploadHelper<'a, A: 'a> {
pub client: &'a mut hyper::client::Client,
pub delegate: &'a mut Delegate,
pub start_at: Option<u64>,
pub auth: &'a mut A,
pub user_agent: &'a str,
pub auth_header: Authorization<Bearer>,
pub url: &'a str,
pub reader: &'a mut ReadSeek,
pub media_type: Mime,
pub content_length: u64
}
impl<'a, A> ResumableUploadHelper<'a, A>
where A: oauth2::GetToken {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::Result<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
.header(ContentRange { range: None, total_length: self.content_length })
.header(self.auth_header.clone())
.send() {
Ok(r) => {
// 308 = resume-incomplete == PermanentRedirect
let headers = r.headers.clone();
let h: &RangeResponseHeader = match headers.get() {
Some(hh) if r.status == StatusCode::PermanentRedirect => hh,
None|Some(_) => {
if let Retry::After(d) = self.delegate.http_failure(&r, None, None) {
sleep(d);
continue;
}
return Err(Ok(r))
}
};
return Ok(h.0.last)
}
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Err(Err(err))
}
}
}
}
/// returns None if operation was cancelled by delegate, or the HttpResult.
/// It can be that we return the result just because we didn't understand the status code -
/// caller should check for status himself before assuming it's OK to use
pub fn upload(&mut self) -> Option<hyper::Result<hyper::client::Response>> {
let mut start = match self.start_at {
Some(s) => s,
None => match self.query_transfer_status() {
Ok(s) => s,
Err(result) => return Some(result)
}
};
const MIN_CHUNK_SIZE: u64 = 1 << 18;
let chunk_size = match self.delegate.chunk_size() {
cs if cs > MIN_CHUNK_SIZE => cs,
_ => MIN_CHUNK_SIZE
};
self.reader.seek(SeekFrom::Start(start)).unwrap();
loop {
let request_size = match self.content_length - start {
rs if rs > chunk_size => chunk_size,
rs => rs
};
let mut section_reader = self.reader.take(request_size);
let range_header = ContentRange {
range: Some(Chunk {first: start, last: start + request_size - 1}),
total_length: self.content_length
};
start += request_size;
if self.delegate.cancel_chunk_upload(&range_header) {
return None
}
let res = self.client.post(self.url)
.header(range_header)
.header(ContentType(self.media_type.clone()))
.header(UserAgent(self.user_agent.to_string()))
.body(&mut section_reader)
.send();
match res {
Ok(mut res) => {
if res.status == StatusCode::PermanentRedirect {
continue
}
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let Retry::After(d) = self.delegate.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
}
return Some(Ok(res))
},
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Some(Err(err))
}
}
}
}
}
// Copy of src/rust/cli/cmn.rs
// TODO(ST): Allow sharing common code between program types
pub fn remove_json_null_values(value: &mut json::value::Value) {
match *value {
json::value::Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}

1569
gen/cloudtrace1/src/lib.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-cloudtrace2-cli"
version = "1.0.7+20171202"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with Cloud Trace (protocol v2)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace2-cli"
homepage = "https://cloud.google.com/trace"
documentation = "http://byron.github.io/google-apis-rs/google_cloudtrace2_cli"
license = "MIT"
keywords = ["cloudtrace", "google", "cli"]
[[bin]]
name = "cloudtrace2"
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
strsim = "^0.5"
hyper-rustls = "^0.6"
yup-hyper-mock = "^2.0"
clap = "^2.0"
[features]
[dependencies.google-cloudtrace2]
path = "../cloudtrace2"
version = "1.0.7+20171202"

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,115 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/cli/README.md.mako'
DO NOT EDIT !
-->
The `cloudtrace2` command-line interface *(CLI)* allows to use most features of the *Google Cloud Trace* service from the comfort of your terminal.
By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's
capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero.
If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools.
Everything else about the *Cloud Trace* API can be found at the
[official documentation site](https://cloud.google.com/trace).
# Installation and Source Code
Install the command-line interface with cargo using:
```bash
cargo install google-cloudtrace2-cli
```
Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace2-cli).
# Usage
This documentation was generated from the *Cloud Trace* API at revision *20171202*. The CLI is at version *1.0.7*.
```bash
cloudtrace2 [options]
projects
traces-batch-write <name> (-r <kv>)... [-p <v>]... [-o <out>]
traces-spans-create <name> (-r <kv>)... [-p <v>]... [-o <out>]
cloudtrace2 --help
Configuration:
[--scope <url>]...
Specify the authentication a method should be executed in. Each scope
requires the user to grant this application permission to use it.
If unset, it defaults to the shortest scope url for a particular method.
--config-dir <folder>
A directory into which we will store our persistent data. Defaults to
a user-writable directory that we will create during the first invocation.
[default: ~/.google-service-cli]
--debug
Output all server communication to standard error. `tx` and `rx` are placed
into the same stream.
--debug-auth
Output all communication related to authentication to standard error. `tx`
and `rx` are placed into the same stream.
```
# Configuration
The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `cloudtrace2-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis.
More information about the various kinds of persistent data are given in the following paragraphs.
# Authentication
Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the
set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*.
If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a
method that is read-only, it will ask only for a read-only scope.
You may use the `--scope` flag to specify a scope directly.
All applicable scopes are documented in the respective method's CLI documentation.
The first time a scope is used, the user is asked for permission. Follow the instructions given
by the CLI to grant permissions, or to decline.
If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration
directory, e.g. `~/.google-service-cli/cloudtrace2-token-<scope-hash>.json`. No manual management of these tokens
is necessary.
To revoke granted authentication, please refer to the [official documentation][revoke-access].
# Application Secrets
In order to allow any application to use Google services, it will need to be registered using the
[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it
one by one. Most APIs can be used for free and have a daily quota.
To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI
comes with a default application secret that is configured accordingly. This also means that heavy usage
all around the world may deplete the daily quota.
You can workaround this limitation by putting your own secrets file at this location:
`~/.google-service-cli/cloudtrace2-secret.json`, assuming that the required *cloudtrace* API
was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at
*APIs & auth -> Credentials -> Download JSON* and used as is.
Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new].
# Debugging
Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know
what exactly led to a particular issue. This is done by allowing all client-server communication to be
output to standard error *as-is*.
The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag
will cause all communication related to authentication to standard error.
If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the
issue at hand.
You may consider redirecting standard error into a file for ease of use, e.g. `cloudtrace2 --debug <resource> <method> [options] 2>debug.txt`.
[scopes]: https://developers.google.com/+/api/oauth#scopes
[revoke-access]: http://webapps.stackexchange.com/a/30849
[google-dev-console]: https://console.developers.google.com/
[google-project-new]: https://developers.google.com/console/help/new/

View File

@@ -0,0 +1,18 @@
site_name: Cloud Trace v1.0.7+20171202
site_url: http://byron.github.io/google-apis-rs/google-cloudtrace2-cli
site_description: A complete library to interact with Cloud Trace (protocol v2)
repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace2-cli
docs_dir: docs
site_dir: build_html
pages:
- ['index.md', 'Home']
- ['projects_traces-batch-write.md', 'Projects', 'Traces Batch Write']
- ['projects_traces-spans-create.md', 'Projects', 'Traces Spans Create']
theme: readthedocs
copyright: Copyright &copy; 2015-2016, `Sebastian Thiel`

View File

@@ -0,0 +1,799 @@
// COPY OF 'src/rust/cli/cmn.rs'
// DO NOT EDIT
use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token};
use serde_json as json;
use serde_json::value::Value;
use mime::Mime;
use clap::{App, SubCommand};
use strsim;
use std::fs;
use std::env;
use std::io;
use std::error::Error as StdError;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
use std::io::{Write, Read, stdout};
use std::default::Default;
const FIELD_SEP: char = '.';
pub enum ComplexType {
Pod,
Vec,
Map,
}
// Null,
// Bool(bool),
// I64(i64),
// U64(u64),
// F64(f64),
// String(String),
pub enum JsonType {
Boolean,
Int,
Uint,
Float,
String,
}
pub struct JsonTypeInfo {
pub jtype: JsonType,
pub ctype: ComplexType,
}
// Based on @erickt user comment. Thanks for the idea !
// Remove all keys whose values are null from given value (changed in place)
pub fn remove_json_null_values(value: &mut Value) {
match *value {
Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}
fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> {
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values {
let confidence = strsim::jaro_winkler(v, pv);
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
}
pub enum CallType {
Upload(UploadProtocol),
Standard,
}
arg_enum!{
pub enum UploadProtocol {
Simple,
Resumable
}
}
impl AsRef<str> for UploadProtocol {
fn as_ref(&self) -> &str {
match *self {
UploadProtocol::Simple => "simple",
UploadProtocol::Resumable => "resumable",
}
}
}
impl AsRef<str> for CallType {
fn as_ref(&self) -> &str {
match *self {
CallType::Upload(ref proto) => proto.as_ref(),
CallType::Standard => "standard-request",
}
}
}
#[derive(Clone, Default)]
pub struct FieldCursor(Vec<String>);
impl ToString for FieldCursor {
fn to_string(&self) -> String {
self.0.join(".")
}
}
impl From<&'static str> for FieldCursor {
fn from(value: &'static str) -> FieldCursor {
let mut res = FieldCursor::default();
res.set(value).unwrap();
res
}
}
fn assure_entry<'a, 'b>(m: &'a mut json::Map<String, Value>, k: &'b String) -> &'a mut Value {
if m.contains_key(k) {
return m.get_mut(k).expect("value to exist");
}
m.insert(k.to_owned(), Value::Object(Default::default()));
m.get_mut(k).expect("value to exist")
}
impl FieldCursor {
pub fn set(&mut self, value: &str) -> Result<(), CLIError> {
if value.len() == 0 {
return Err(CLIError::Field(FieldError::Empty));
}
let mut first_is_field_sep = false;
let mut char_count: usize = 0;
let mut last_c = FIELD_SEP;
let mut num_conscutive_field_seps = 0;
let mut field = String::new();
let mut fields = self.0.clone();
let push_field = |fs: &mut Vec<String>, f: &mut String| {
if f.len() > 0 {
fs.push(f.clone());
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
char_count += 1;
if c == FIELD_SEP {
if cid == 0 {
first_is_field_sep = true;
}
num_conscutive_field_seps += 1;
if cid > 0 && last_c == FIELD_SEP {
if fields.pop().is_none() {
return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string())));
}
} else {
push_field(&mut fields, &mut field);
}
} else {
num_conscutive_field_seps = 0;
if cid == 1 {
if first_is_field_sep {
fields.truncate(0);
}
}
field.push(c);
}
last_c = c;
}
push_field(&mut fields, &mut field);
if char_count == 1 && first_is_field_sep {
fields.truncate(0);
}
if char_count > 1 && num_conscutive_field_seps == 1 {
return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string())));
}
self.0 = fields;
Ok(())
}
pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option<String> {
if value.len() == 0 {
return None;
}
let mut last_c = FIELD_SEP;
let mut field = String::new();
let mut output = String::new();
let push_field = |fs: &mut String, f: &mut String| {
if f.len() > 0 {
fs.push_str(match did_you_mean(&f, possible_values) {
Some(candidate) => candidate,
None => &f,
});
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
if c == FIELD_SEP {
if last_c != FIELD_SEP {
push_field(&mut output, &mut field);
}
output.push(c);
} else {
field.push(c);
}
last_c = c;
}
push_field(&mut output, &mut field);
if &output == value {
None
} else {
Some(output)
}
}
pub fn set_json_value(&self,
mut object: &mut Value,
value: &str,
type_info: JsonTypeInfo,
err: &mut InvalidOptionsError,
orig_cursor: &FieldCursor) {
assert!(self.0.len() > 0);
for field in &self.0[..self.0.len() - 1] {
let tmp = object;
object = match *tmp {
Value::Object(ref mut mapping) => {
assure_entry(mapping, &field)
}
_ => panic!("We don't expect non-object Values here ..."),
};
}
match *object {
Value::Object(ref mut mapping) => {
let field = &self.0[self.0.len() - 1];
let to_jval = |value: &str,
jtype: JsonType,
err: &mut InvalidOptionsError|
-> Value {
match jtype {
JsonType::Boolean =>
Value::Bool(arg_from_str(value, err, &field, "boolean")),
JsonType::Int =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"int"))
.expect("valid f64")),
JsonType::Uint =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"uint"))
.expect("valid f64")),
JsonType::Float =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"float"))
.expect("valid f64")),
JsonType::String => Value::String(value.to_owned()),
}
};
match type_info.ctype {
ComplexType::Pod => {
if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err))
.is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
ComplexType::Vec => {
match *assure_entry(mapping, field) {
Value::Array(ref mut values) =>
values.push(to_jval(value, type_info.jtype, err)),
_ => unreachable!(),
}
}
ComplexType::Map => {
let (key, value) = parse_kv_arg(value, err, true);
let jval = to_jval(value.unwrap_or(""), type_info.jtype, err);
match *assure_entry(mapping, &field) {
Value::Object(ref mut value_map) => {
if value_map.insert(key.to_owned(), jval).is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
_ => unreachable!(),
}
}
}
}
_ => unreachable!(),
}
}
pub fn num_fields(&self) -> usize {
self.0.len()
}
}
pub fn parse_kv_arg<'a>(kv: &'a str,
err: &mut InvalidOptionsError,
for_hashmap: bool)
-> (&'a str, Option<&'a str>) {
let mut add_err = || {
err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(), for_hashmap))
};
match kv.find('=') {
None => {
add_err();
return (kv, None);
}
Some(pos) => {
let key = &kv[..pos];
if kv.len() <= pos + 1 {
add_err();
return (key, Some(""));
}
(key, Some(&kv[pos + 1..]))
}
}
}
pub fn calltype_from_str(name: &str,
valid_protocols: Vec<String>,
err: &mut InvalidOptionsError)
-> CallType {
CallType::Upload(match UploadProtocol::from_str(name) {
Ok(up) => up,
Err(msg) => {
err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols));
UploadProtocol::Simple
}
})
}
pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option<fs::File> {
match fs::File::open(file_path) {
Ok(f) => Some(f),
Err(io_err) => {
err.issues.push(CLIError::Input(InputError::Io((file_path.to_string(), io_err))));
None
}
}
}
pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option<Mime> {
match mime.parse() {
Ok(m) => Some(m),
Err(_) => {
err.issues.push(CLIError::Input(InputError::Mime(mime.to_string())));
None
}
}
}
pub fn writer_from_opts(arg: Option<&str>) -> Result<Box<Write>, io::Error> {
let f = arg.unwrap_or("-");
match f {
"-" => Ok(Box::new(stdout())),
_ => match fs::OpenOptions::new().create(true).write(true).open(f) {
Ok(f) => Ok(Box::new(f)),
Err(io_err) => Err(io_err),
},
}
}
pub fn arg_from_str<'a, T>(arg: &str,
err: &mut InvalidOptionsError,
arg_name: &'a str,
arg_type: &'a str)
-> T
where T: FromStr + Default,
<T as FromStr>::Err: fmt::Display
{
match FromStr::from_str(arg) {
Err(perr) => {
err.issues.push(CLIError::ParseError(arg_name.to_owned(),
arg_type.to_owned(),
arg.to_string(),
format!("{}", perr)));
Default::default()
}
Ok(v) => v,
}
}
pub struct JsonTokenStorage {
pub program_name: &'static str,
pub db_dir: String,
}
impl JsonTokenStorage {
fn path(&self, scope_hash: u64) -> PathBuf {
Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash))
}
}
#[derive(Debug)]
pub enum TokenStorageError {
Json(json::Error),
Io(io::Error),
}
impl fmt::Display for TokenStorageError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
TokenStorageError::Json(ref err) => writeln!(f, "Could not serialize secrets: {}", err),
TokenStorageError::Io(ref err) => writeln!(f, "Failed to write secret token: {}", err),
}
}
}
impl StdError for TokenStorageError {
fn description(&self) -> &str {
"Failure when getting or setting the token storage"
}
}
impl TokenStorage for JsonTokenStorage {
type Error = TokenStorageError;
// NOTE: logging might be interesting, currently we swallow all errors
fn set(&mut self,
scope_hash: u64,
_: &Vec<&str>,
token: Option<Token>)
-> Result<(), TokenStorageError> {
match token {
None => {
match fs::remove_file(self.path(scope_hash)) {
Err(err) => match err.kind() {
io::ErrorKind::NotFound => Ok(()),
_ => Err(TokenStorageError::Io(err)),
},
Ok(_) => Ok(()),
}
}
Some(token) => {
match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) {
Ok(mut f) => {
match json::to_writer_pretty(&mut f, &token) {
Ok(_) => Ok(()),
Err(serde_err) => Err(TokenStorageError::Json(serde_err)),
}
}
Err(io_err) => Err(TokenStorageError::Io(io_err)),
}
}
}
}
fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result<Option<Token>, TokenStorageError> {
match fs::File::open(&self.path(scope_hash)) {
Ok(f) => {
match json::de::from_reader(f) {
Ok(token) => Ok(Some(token)),
Err(err) => Err(TokenStorageError::Json(err)),
}
}
Err(io_err) => {
match io_err.kind() {
io::ErrorKind::NotFound => Ok(None),
_ => Err(TokenStorageError::Io(io_err)),
}
}
}
}
}
#[derive(Debug)]
pub enum ApplicationSecretError {
DecoderError((String, json::Error)),
FormatError(String),
}
impl fmt::Display for ApplicationSecretError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ApplicationSecretError::DecoderError((ref path, ref err)) =>
writeln!(f,
"Could not decode file at '{}' with error: {}.",
path,
err),
ApplicationSecretError::FormatError(ref path) =>
writeln!(f,
"'installed' field is unset in secret file at '{}'.",
path),
}
}
}
#[derive(Debug)]
pub enum ConfigurationError {
DirectoryCreationFailed((String, io::Error)),
DirectoryUnset,
HomeExpansionFailed(String),
Secret(ApplicationSecretError),
Io((String, io::Error)),
}
impl fmt::Display for ConfigurationError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) =>
writeln!(f,
"Directory '{}' could not be created with error: {}.",
dir,
err),
ConfigurationError::DirectoryUnset => writeln!(f, "--config-dir was unset or empty."),
ConfigurationError::HomeExpansionFailed(ref dir) =>
writeln!(f,
"Couldn't find HOME directory of current user, failed to expand '{}'.",
dir),
ConfigurationError::Secret(ref err) => writeln!(f, "Secret -> {}", err),
ConfigurationError::Io((ref path, ref err)) =>
writeln!(f,
"IO operation failed on path '{}' with error: {}.",
path,
err),
}
}
}
#[derive(Debug)]
pub enum InputError {
Io((String, io::Error)),
Mime(String),
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
InputError::Io((ref file_path, ref io_err)) =>
writeln!(f,
"Failed to open '{}' for reading with error: {}.",
file_path,
io_err),
InputError::Mime(ref mime) => writeln!(f, "'{}' is not a known mime-type.", mime),
}
}
}
#[derive(Debug)]
pub enum FieldError {
PopOnEmpty(String),
TrailingFieldSep(String),
Unknown(String, Option<String>, Option<String>),
Duplicate(String),
Empty,
}
impl fmt::Display for FieldError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
FieldError::PopOnEmpty(ref field) =>
writeln!(f, "'{}': Cannot move up on empty field cursor.", field),
FieldError::TrailingFieldSep(ref field) =>
writeln!(f,
"'{}': Single field separator may not be last character.",
field),
FieldError::Unknown(ref field, ref suggestion, ref value) => {
let suffix = match *suggestion {
Some(ref s) => {
let kv = match *value {
Some(ref v) => format!("{}={}", s, v),
None => s.clone(),
};
format!(" Did you mean '{}' ?", kv)
}
None => String::new(),
};
writeln!(f, "Field '{}' does not exist.{}", field, suffix)
}
FieldError::Duplicate(ref cursor) =>
writeln!(f, "Value at '{}' was already set", cursor),
FieldError::Empty => writeln!(f, "Field names must not be empty."),
}
}
}
#[derive(Debug)]
pub enum CLIError {
Configuration(ConfigurationError),
ParseError(String, String, String, String),
UnknownParameter(String, Vec<&'static str>),
InvalidUploadProtocol(String, Vec<String>),
InvalidKeyValueSyntax(String, bool),
Input(InputError),
Field(FieldError),
MissingCommandError,
MissingMethodError(String),
}
impl fmt::Display for CLIError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err),
CLIError::Input(ref err) => write!(f, "Input -> {}", err),
CLIError::Field(ref err) => write!(f, "Field -> {}", err),
CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) =>
writeln!(f,
"'{}' is not a valid upload protocol. Choose from one of {}.",
proto_name,
valid_names.join(", ")),
CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) =>
writeln!(f,
"Failed to parse argument '{}' with value '{}' as {} with error: {}.",
arg_name,
value,
type_name,
err_desc),
CLIError::UnknownParameter(ref param_name, ref possible_values) => {
let suffix = match did_you_mean(param_name, &possible_values) {
Some(v) => format!(" Did you mean '{}' ?", v),
None => String::new(),
};
write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix)
}
CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => {
let hashmap_info = if is_hashmap {
"hashmap "
} else {
""
};
writeln!(f,
"'{}' does not match {}pattern <key>=<value>.",
kv,
hashmap_info)
}
CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."),
CLIError::MissingMethodError(ref cmd) =>
writeln!(f,
"Please specify the method to call on the '{}' command.",
cmd),
}
}
}
#[derive(Debug)]
pub struct InvalidOptionsError {
pub issues: Vec<CLIError>,
pub exit_code: i32,
}
impl fmt::Display for InvalidOptionsError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for issue in &self.issues {
try!(issue.fmt(f));
}
Ok(())
}
}
impl InvalidOptionsError {
pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError {
InvalidOptionsError {
issues: vec![err],
exit_code: exit_code,
}
}
pub fn new() -> InvalidOptionsError {
InvalidOptionsError {
issues: Vec::new(),
exit_code: 1,
}
}
}
pub fn assure_config_dir_exists(dir: &str) -> Result<String, CLIError> {
let trdir = dir.trim();
if trdir.len() == 0 {
return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset));
}
let expanded_config_dir = if trdir.as_bytes()[0] == b'~' {
match env::var("HOME").ok().or(env::var("UserProfile").ok()) {
None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))),
Some(mut user) => {
user.push_str(&trdir[1..]);
user
}
}
} else {
trdir.to_string()
};
if let Err(err) = fs::create_dir(&expanded_config_dir) {
if err.kind() != io::ErrorKind::AlreadyExists {
return Err(CLIError::Configuration(
ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err))));
}
}
Ok(expanded_config_dir)
}
pub fn application_secret_from_directory(dir: &str,
secret_basename: &str,
json_console_secret: &str)
-> Result<ApplicationSecret, CLIError> {
let secret_path = Path::new(dir).join(secret_basename);
let secret_str = || secret_path.as_path().to_str().unwrap().to_string();
let secret_io_error = |io_err: io::Error| {
Err(CLIError::Configuration(ConfigurationError::Io((secret_str(), io_err))))
};
for _ in 0..2 {
match fs::File::open(&secret_path) {
Err(mut err) => {
if err.kind() == io::ErrorKind::NotFound {
// Write our built-in one - user may adjust the written file at will
err = match fs::OpenOptions::new()
.create(true)
.write(true)
.open(&secret_path) {
Err(cfe) => cfe,
Ok(mut f) => {
// Assure we convert 'ugly' json string into pretty one
let console_secret: ConsoleApplicationSecret =
json::from_str(json_console_secret).unwrap();
match json::to_writer_pretty(&mut f, &console_secret) {
Err(serde_err) =>
panic!("Unexpected serde error: {:#?}", serde_err),
Ok(_) => continue,
}
}
};
// fall through to IO error handling
}
return secret_io_error(err);
}
Ok(f) => {
match json::de::from_reader::<_, ConsoleApplicationSecret>(f) {
Err(json_err) =>
return Err(CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::DecoderError(
(secret_str(), json_err)
)))),
Ok(console_secret) => match console_secret.installed {
Some(secret) => return Ok(secret),
None => return Err(
CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::FormatError(secret_str())
))),
},
}
}
}
}
unreachable!();
}

View File

@@ -0,0 +1,504 @@
// DO NOT EDIT !
// This file was generated automatically from 'src/mako/cli/main.rs.mako'
// DO NOT EDIT !
#![allow(unused_variables, unused_imports, dead_code, unused_mut)]
#[macro_use]
extern crate clap;
extern crate yup_oauth2 as oauth2;
extern crate yup_hyper_mock as mock;
extern crate hyper_rustls;
extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate mime;
extern crate strsim;
extern crate google_cloudtrace2 as api;
use std::env;
use std::io::{self, Write};
use clap::{App, SubCommand, Arg};
mod cmn;
use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg,
input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol,
calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo};
use std::default::Default;
use std::str::FromStr;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, FlowType};
use serde_json as json;
use clap::ArgMatches;
enum DoitError {
IoError(String, io::Error),
ApiError(api::Error),
}
struct Engine<'n> {
opt: ArgMatches<'n>,
hub: api::CloudTrace<hyper::Client, Authenticator<DefaultAuthenticatorDelegate, JsonTokenStorage, hyper::Client>>,
gp: Vec<&'static str>,
gpm: Vec<(&'static str, &'static str)>,
}
impl<'n> Engine<'n> {
fn _projects_traces_batch_write(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec![]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::BatchWriteSpansRequest = json::value::from_value(object).unwrap();
let mut call = self.hub.projects().traces_batch_write(request, opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _projects_traces_spans_create(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"status.message" => Some(("status.message", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"status.code" => Some(("status.code", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"child-span-count" => Some(("childSpanCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"display-name.value" => Some(("displayName.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"display-name.truncated-byte-count" => Some(("displayName.truncatedByteCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"links.dropped-links-count" => Some(("links.droppedLinksCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"stack-trace.stack-trace-hash-id" => Some(("stackTrace.stackTraceHashId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"stack-trace.stack-frames.dropped-frames-count" => Some(("stackTrace.stackFrames.droppedFramesCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"parent-span-id" => Some(("parentSpanId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"start-time" => Some(("startTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"span-id" => Some(("spanId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"attributes.dropped-attributes-count" => Some(("attributes.droppedAttributesCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"time-events.dropped-message-events-count" => Some(("timeEvents.droppedMessageEventsCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"time-events.dropped-annotations-count" => Some(("timeEvents.droppedAnnotationsCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"end-time" => Some(("endTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"same-process-as-parent-span" => Some(("sameProcessAsParentSpan", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["attributes", "child-span-count", "code", "display-name", "dropped-annotations-count", "dropped-attributes-count", "dropped-frames-count", "dropped-links-count", "dropped-message-events-count", "end-time", "links", "message", "name", "parent-span-id", "same-process-as-parent-span", "span-id", "stack-frames", "stack-trace", "stack-trace-hash-id", "start-time", "status", "time-events", "truncated-byte-count", "value"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::Span = json::value::from_value(object).unwrap();
let mut call = self.hub.projects().traces_spans_create(request, opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _doit(&self, dry_run: bool) -> Result<Result<(), DoitError>, Option<InvalidOptionsError>> {
let mut err = InvalidOptionsError::new();
let mut call_result: Result<(), DoitError> = Ok(());
let mut err_opt: Option<InvalidOptionsError> = None;
match self.opt.subcommand() {
("projects", Some(opt)) => {
match opt.subcommand() {
("traces-batch-write", Some(opt)) => {
call_result = self._projects_traces_batch_write(opt, dry_run, &mut err);
},
("traces-spans-create", Some(opt)) => {
call_result = self._projects_traces_spans_create(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("projects".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
_ => {
err.issues.push(CLIError::MissingCommandError);
writeln!(io::stderr(), "{}\n", self.opt.usage()).ok();
}
}
if dry_run {
if err.issues.len() > 0 {
err_opt = Some(err);
}
Err(err_opt)
} else {
Ok(call_result)
}
}
// Please note that this call will fail if any part of the opt can't be handled
fn new(opt: ArgMatches<'n>) -> Result<Engine<'n>, InvalidOptionsError> {
let (config_dir, secret) = {
let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) {
Err(e) => return Err(InvalidOptionsError::single(e, 3)),
Ok(p) => p,
};
match cmn::application_secret_from_directory(&config_dir, "cloudtrace2-secret.json",
"{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") {
Ok(secret) => (config_dir, secret),
Err(e) => return Err(InvalidOptionsError::single(e, 4))
}
};
let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate,
if opt.is_present("debug-auth") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
},
JsonTokenStorage {
program_name: "cloudtrace2",
db_dir: config_dir.clone(),
}, Some(FlowType::InstalledRedirect(54324)));
let client =
if opt.is_present("debug") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
};
let engine = Engine {
opt: opt,
hub: api::CloudTrace::new(client, auth),
gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"],
gpm: vec![
("$-xgafv", "$.xgafv"),
("access-token", "access_token"),
("bearer-token", "bearer_token"),
("oauth-token", "oauth_token"),
("pretty-print", "prettyPrint"),
("quota-user", "quotaUser"),
("upload-type", "uploadType"),
("upload-protocol", "upload_protocol"),
]
};
match engine._doit(true) {
Err(Some(err)) => Err(err),
Err(None) => Ok(engine),
Ok(_) => unreachable!(),
}
}
fn doit(&self) -> Result<(), DoitError> {
match self._doit(false) {
Ok(res) => res,
Err(_) => unreachable!(),
}
}
}
fn main() {
let mut exit_status = 0i32;
let arg_data = [
("projects", "methods: 'traces-batch-write' and 'traces-spans-create'", vec![
("traces-batch-write",
Some(r##"Sends new spans to new or existing traces. You cannot update
existing spans."##),
"Details at http://byron.github.io/google-apis-rs/google_cloudtrace2_cli/projects_traces-batch-write",
vec![
(Some(r##"name"##),
None,
Some(r##"Required. The name of the project where the spans belong. The format is
`projects/[PROJECT_ID]`."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("traces-spans-create",
Some(r##"Creates a new span."##),
"Details at http://byron.github.io/google-apis-rs/google_cloudtrace2_cli/projects_traces-spans-create",
vec![
(Some(r##"name"##),
None,
Some(r##"The resource name of the span in the following format:
projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/SPAN_ID is a unique identifier for a trace within a project;
it is a 32-character hexadecimal encoding of a 16-byte array.
[SPAN_ID] is a unique identifier for a span within a trace; it
is a 16-character hexadecimal encoding of an 8-byte array."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
];
let mut app = App::new("cloudtrace2")
.author("Sebastian Thiel <byronimo@gmail.com>")
.version("1.0.7+20171202")
.about("Sends application trace data to Stackdriver Trace for viewing. Trace data is collected for all App Engine applications by default. Trace data from other applications can be provided using this API.
")
.after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_cloudtrace2_cli")
.arg(Arg::with_name("url")
.long("scope")
.help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.")
.multiple(true)
.takes_value(true))
.arg(Arg::with_name("folder")
.long("config-dir")
.help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli")
.multiple(false)
.takes_value(true))
.arg(Arg::with_name("debug")
.long("debug")
.help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false))
.arg(Arg::with_name("debug-auth")
.long("debug-auth")
.help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false));
for &(main_command_name, about, ref subcommands) in arg_data.iter() {
let mut mcmd = SubCommand::with_name(main_command_name).about(about);
for &(sub_command_name, ref desc, url_info, ref args) in subcommands {
let mut scmd = SubCommand::with_name(sub_command_name);
if let &Some(desc) = desc {
scmd = scmd.about(desc);
}
scmd = scmd.after_help(url_info);
for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args {
let arg_name_str =
match (arg_name, flag) {
(&Some(an), _ ) => an,
(_ , &Some(f)) => f,
_ => unreachable!(),
};
let mut arg = Arg::with_name(arg_name_str)
.empty_values(false);
if let &Some(short_flag) = flag {
arg = arg.short(short_flag);
}
if let &Some(desc) = desc {
arg = arg.help(desc);
}
if arg_name.is_some() && flag.is_some() {
arg = arg.takes_value(true);
}
if let &Some(required) = required {
arg = arg.required(required);
}
if let &Some(multi) = multi {
arg = arg.multiple(multi);
}
scmd = scmd.arg(arg);
}
mcmd = mcmd.subcommand(scmd);
}
app = app.subcommand(mcmd);
}
let matches = app.get_matches();
let debug = matches.is_present("debug");
match Engine::new(matches) {
Err(err) => {
exit_status = err.exit_code;
writeln!(io::stderr(), "{}", err).ok();
},
Ok(engine) => {
if let Err(doit_err) = engine.doit() {
exit_status = 1;
match doit_err {
DoitError::IoError(path, err) => {
writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok();
},
DoitError::ApiError(err) => {
if debug {
writeln!(io::stderr(), "{:#?}", err).ok();
} else {
writeln!(io::stderr(), "{}", err).ok();
}
}
}
}
}
}
std::process::exit(exit_status);
}

View File

@@ -0,0 +1,31 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-cloudtrace2"
version = "1.0.7+20171202"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with Cloud Trace (protocol v2)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace2"
homepage = "https://cloud.google.com/trace"
documentation = "https://docs.rs/google-cloudtrace2/1.0.7+20171202"
license = "MIT"
keywords = ["cloudtrace", "google", "protocol", "web", "api"]
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
url = "= 0.5"
[features]

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

180
gen/cloudtrace2/README.md Normal file
View File

@@ -0,0 +1,180 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/api/README.md.mako'
DO NOT EDIT !
-->
The `google-cloudtrace2` library allows access to all features of the *Google Cloud Trace* service.
This documentation was generated from *Cloud Trace* crate version *1.0.7+20171202*, where *20171202* is the exact revision of the *cloudtrace:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.7*.
Everything else about the *Cloud Trace* *v2* API can be found at the
[official documentation site](https://cloud.google.com/trace).
# Features
Handle the following *Resources* with ease from the central [hub](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/struct.CloudTrace.html) ...
* projects
* [*traces batch write*](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/struct.ProjectTraceBatchWriteCall.html) and [*traces spans create*](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/struct.ProjectTraceSpanCreateCall.html)
# Structure of this Library
The API is structured into the following primary items:
* **[Hub](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/struct.CloudTrace.html)**
* a central object to maintain state and allow accessing all *Activities*
* creates [*Method Builders*](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.MethodsBuilder.html) which in turn
allow access to individual [*Call Builders*](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.CallBuilder.html)
* **[Resources](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.Resource.html)**
* primary types that you can apply *Activities* to
* a collection of properties and *Parts*
* **[Parts](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.Part.html)**
* a collection of properties
* never directly used in *Activities*
* **[Activities](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.CallBuilder.html)**
* operations to apply to *Resources*
All *structures* are marked with applicable traits to further categorize them and ease browsing.
Generally speaking, you can invoke *Activities* like this:
```Rust,ignore
let r = hub.resource().activity(...).doit()
```
Or specifically ...
```ignore
let r = hub.projects().traces_spans_create(...).doit()
```
The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
The `doit()` method performs the actual communication with the server and returns the respective result.
# Usage
## Setting up your Project
To use this library, you would put the following lines into your `Cargo.toml` file:
```toml
[dependencies]
google-cloudtrace2 = "*"
```
## A complete example
```Rust
extern crate hyper;
extern crate hyper_rustls;
extern crate yup_oauth2 as oauth2;
extern crate google_cloudtrace2 as cloudtrace2;
use cloudtrace2::Span;
use cloudtrace2::{Result, Error};
use std::default::Default;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
use cloudtrace2::CloudTrace;
// Get an ApplicationSecret instance by some means. It contains the `client_id` and
// `client_secret`, among other things.
let secret: ApplicationSecret = Default::default();
// Instantiate the authenticator. It will choose a suitable authentication flow for you,
// unless you replace `None` with the desired Flow.
// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
// retrieve them from storage.
let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
<MemoryStorage as Default>::default(), None);
let mut hub = CloudTrace::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
// As the method needs a request, you would usually fill it with the desired information
// into the respective structure. Some of the parts shown here might not be applicable !
// Values shown here are possibly random and not representative !
let mut req = Span::default();
// You can configure optional parameters by calling the respective setters at will, and
// execute the final call using `doit()`.
// Values shown here are possibly random and not representative !
let result = hub.projects().traces_spans_create(req, "name")
.doit();
match result {
Err(e) => match e {
// The Error enum provides details about what exactly happened.
// You can also just use its `Debug`, `Display` or `Error` traits
Error::HttpError(_)
|Error::MissingAPIKey
|Error::MissingToken(_)
|Error::Cancelled
|Error::UploadSizeLimitExceeded(_, _)
|Error::Failure(_)
|Error::BadRequest(_)
|Error::FieldClash(_)
|Error::JsonDecodeError(_, _) => println!("{}", e),
},
Ok(res) => println!("Success: {:?}", res),
}
```
## Handling Errors
All errors produced by the system are provided either as [Result](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/enum.Result.html) enumeration as return value of
the doit() methods, or handed as possibly intermediate results to either the
[Hub Delegate](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.Delegate.html), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html).
When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
makes the system potentially resilient to all kinds of errors.
## Uploads and Downloads
If a method supports downloads, the response body, which is part of the [Result](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/enum.Result.html), should be
read by you to obtain the media.
If such a method also supports a [Response Result](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.ResponseResult.html), it will return that by default.
You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
this call: `.param("alt", "media")`.
Methods supporting uploads can do so using up to 2 different protocols:
*simple* and *resumable*. The distinctiveness of each is represented by customized
`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
## Customization and Callbacks
You may alter the way an `doit()` method is called by providing a [delegate](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.Delegate.html) to the
[Method Builder](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.CallBuilder.html) before making the final `doit()` call.
Respective methods will be called to provide progress information, as well as determine whether the system should
retry on failure.
The [delegate trait](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
## Optional Parts in Server-Requests
All structures provided by this library are made to be [enocodable](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.RequestValue.html) and
[decodable](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
are valid.
Most optionals are are considered [Parts](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.Part.html) which are identifiable by name, which will be sent to
the server to indicate either the set parts of the request or the desired parts in the response.
## Builder Arguments
Using [method builders](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods.
These will always take a single argument, for which the following statements are true.
* [PODs][wiki-pod] are handed by copy
* strings are passed as `&str`
* [request values](https://docs.rs/google-cloudtrace2/1.0.7+20171202/google_cloudtrace2/trait.RequestValue.html) are moved
Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
[google-go-api]: https://github.com/google/google-api-go-client
# License
The **cloudtrace2** library was generated by Sebastian Thiel, and is placed
under the *MIT* license.
You can read the full text at the repository's [license file][repo-license].
[repo-license]: https://github.com/Byron/google-apis-rsblob/master/LICENSE.md

753
gen/cloudtrace2/src/cmn.rs Normal file
View File

@@ -0,0 +1,753 @@
// COPY OF 'src/rust/api/cmn.rs'
// DO NOT EDIT
use std::io::{self, Read, Seek, Cursor, Write, SeekFrom};
use std;
use std::fmt::{self, Display};
use std::str::FromStr;
use std::error;
use std::thread::sleep;
use std::time::Duration;
use mime::{Mime, TopLevel, SubLevel, Attr, Value};
use oauth2::{TokenType, Retry, self};
use hyper;
use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header,
HeaderFormat, Bearer};
use hyper::http::h1::LINE_ENDING;
use hyper::method::Method;
use hyper::status::StatusCode;
use serde_json as json;
/// Identifies the Hub. There is only one per library, this trait is supposed
/// to make intended use more explicit.
/// The hub allows to access all resource methods more easily.
pub trait Hub {}
/// Identifies types for building methods of a particular resource type
pub trait MethodsBuilder {}
/// Identifies types which represent builders for a particular resource method
pub trait CallBuilder {}
/// Identifies types which can be inserted and deleted.
/// Types with this trait are most commonly used by clients of this API.
pub trait Resource {}
/// Identifies types which are used in API responses.
pub trait ResponseResult {}
/// Identifies types which are used in API requests.
pub trait RequestValue {}
/// Identifies types which are not actually used by the API
/// This might be a bug within the google API schema.
pub trait UnusedType {}
/// Identifies types which are only used as part of other types, which
/// usually are carrying the `Resource` trait.
pub trait Part {}
/// Identifies types which are only used by other types internally.
/// They have no special meaning, this trait just marks them for completeness.
pub trait NestedType {}
/// A utility to specify reader types which provide seeking capabilities too
pub trait ReadSeek: Seek + Read {}
impl<T: Seek + Read> ReadSeek for T {}
/// A trait for all types that can convert themselves into a *parts* string
pub trait ToParts {
fn to_parts(&self) -> String;
}
/// A utility type which can decode a server response that indicates error
#[derive(Deserialize)]
pub struct JsonServerError {
pub error: String,
pub error_description: Option<String>
}
/// A utility to represent detailed errors we might see in case there are BadRequests.
/// The latter happen if the sent parameters or request structures are unsound
#[derive(Deserialize, Serialize, Debug)]
pub struct ErrorResponse {
error: ServerError,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerError {
errors: Vec<ServerMessage>,
code: u16,
message: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerMessage {
domain: String,
reason: String,
message: String,
#[serde(rename="locationType")]
location_type: Option<String>,
location: Option<String>
}
#[derive(Copy, Clone)]
pub struct DummyNetworkStream;
impl Read for DummyNetworkStream {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl Write for DummyNetworkStream {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl hyper::net::NetworkStream for DummyNetworkStream {
fn peer_addr(&mut self) -> io::Result<std::net::SocketAddr> {
Ok("127.0.0.1:1337".parse().unwrap())
}
fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
}
/// A trait specifying functionality to help controlling any request performed by the API.
/// The trait has a conservative default implementation.
///
/// It contains methods to deal with all common issues, as well with the ones related to
/// uploading media
pub trait Delegate {
/// Called at the beginning of any API request. The delegate should store the method
/// information if he is interesting in knowing more context when further calls to it
/// are made.
/// The matching `finished()` call will always be made, no matter whether or not the API
/// request was successful. That way, the delegate may easily maintain a clean state
/// between various API calls.
fn begin(&mut self, MethodInfo) {}
/// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
///
/// Return retry information.
fn http_error(&mut self, &hyper::Error) -> Retry {
Retry::Abort
}
/// Called whenever there is the need for your applications API key after
/// the official authenticator implementation didn't provide one, for some reason.
/// If this method returns None as well, the underlying operation will fail
fn api_key(&mut self) -> Option<String> {
None
}
/// Called whenever the Authenticator didn't yield a token. The delegate
/// may attempt to provide one, or just take it as a general information about the
/// impending failure.
/// The given Error provides information about why the token couldn't be acquired in the
/// first place
fn token(&mut self, err: &error::Error) -> Option<oauth2::Token> {
let _ = err;
None
}
/// Called during resumable uploads to provide a URL for the impending upload.
/// It was saved after a previous call to `store_upload_url(...)`, and if not None,
/// will be used instead of asking the server for a new upload URL.
/// This is useful in case a previous resumable upload was aborted/canceled, but should now
/// be resumed.
/// The returned URL will be used exactly once - if it fails again and the delegate allows
/// to retry, we will ask the server for a new upload URL.
fn upload_url(&mut self) -> Option<String> {
None
}
/// Called after we have retrieved a new upload URL for a resumable upload to store it
/// in case we fail or cancel. That way, we can attempt to resume the upload later,
/// see `upload_url()`.
/// It will also be called with None after a successful upload, which allows the delegate
/// to forget the URL. That way, we will not attempt to resume an upload that has already
/// finished.
fn store_upload_url(&mut self, url: Option<&str>) {
let _ = url;
}
/// Called whenever a server response could not be decoded from json.
/// It's for informational purposes only, the caller will return with an error
/// accordingly.
///
/// # Arguments
///
/// * `json_encoded_value` - The json-encoded value which failed to decode.
/// * `json_decode_error` - The decoder error
fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &json::Error) {
let _ = json_encoded_value;
let _ = json_decode_error;
}
/// Called whenever the http request returns with a non-success status code.
/// This can involve authentication issues, or anything else that very much
/// depends on the used API method.
/// The delegate should check the status, header and decoded json error to decide
/// whether to retry or not. In the latter case, the underlying call will fail.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
fn http_failure(&mut self, _: &hyper::client::Response, Option<JsonServerError>, _: Option<ServerError>) -> Retry {
Retry::Abort
}
/// Called prior to sending the main request of the given method. It can be used to time
/// the call or to print progress information.
/// It's also useful as you can be sure that a request will definitely be made.
fn pre_request(&mut self) { }
/// Return the size of each chunk of a resumable upload.
/// Must be a power of two, with 1<<18 being the smallest allowed chunk size.
/// Will be called once before starting any resumable upload.
fn chunk_size(&mut self) -> u64 {
1 << 23
}
/// Called before the given chunk is uploaded to the server.
/// If true is returned, the upload will be interrupted.
/// However, it may be resumable if you stored the upload URL in a previous call
/// to `store_upload_url()`
fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool {
let _ = chunk;
false
}
/// Called before the API request method returns, in every case. It can be used to clean up
/// internal state between calls to the API.
/// This call always has a matching call to `begin(...)`.
///
/// # Arguments
///
/// * `is_success` - a true value indicates the operation was successful. If false, you should
/// discard all values stored during `store_upload_url`.
fn finished(&mut self, is_success: bool) {
let _ = is_success;
}
}
/// A delegate with a conservative default implementation, which is used if no other delegate is
/// set.
#[derive(Default)]
pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}
#[derive(Debug)]
pub enum Error {
/// The http connection failed
HttpError(hyper::Error),
/// An attempt was made to upload a resource with size stored in field `.0`
/// even though the maximum upload size is what is stored in field `.1`.
UploadSizeLimitExceeded(u64, u64),
/// Represents information about a request that was not understood by the server.
/// Details are included.
BadRequest(ErrorResponse),
/// We needed an API key for authentication, but didn't obtain one.
/// Neither through the authenticator, nor through the Delegate.
MissingAPIKey,
/// We required a Token, but didn't get one from the Authenticator
MissingToken(Box<error::Error>),
/// The delgate instructed to cancel the operation
Cancelled,
/// An additional, free form field clashed with one of the built-in optional ones
FieldClash(&'static str),
/// Shows that we failed to decode the server response.
/// This can happen if the protocol changes in conjunction with strict json decoding.
JsonDecodeError(String, json::Error),
/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref err) => err.fmt(f),
Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) =>
writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}"
, resource_size, max_size),
Error::MissingAPIKey => {
(writeln!(f, "The application's API key was not found in the configuration")).ok();
writeln!(f, "It is used as there are no Scopes defined for this method.")
},
Error::BadRequest(ref err) => {
try!(writeln!(f, "Bad Request ({}): {}", err.error.code, err.error.message));
for err in err.error.errors.iter() {
try!(writeln!(f, " {}: {}, {}{}",
err.domain,
err.message,
err.reason,
match &err.location {
&Some(ref loc) => format!("@{}", loc),
&None => String::new(),
}));
}
Ok(())
},
Error::MissingToken(ref err) =>
writeln!(f, "Token retrieval failed with error: {}", err),
Error::Cancelled =>
writeln!(f, "Operation cancelled by delegate"),
Error::FieldClash(field) =>
writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field),
Error::JsonDecodeError(ref json_str, ref err)
=> writeln!(f, "{}: {}", err, json_str),
Error::Failure(ref response) =>
writeln!(f, "Http status indicates failure: {:?}", response),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::HttpError(ref err) => err.description(),
Error::JsonDecodeError(_, ref err) => err.description(),
_ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead"
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::HttpError(ref err) => err.cause(),
Error::JsonDecodeError(_, ref err) => err.cause(),
_ => None
}
}
}
/// A universal result type used as return for all calls.
pub type Result<T> = std::result::Result<T, Error>;
/// Contains information about an API request.
pub struct MethodInfo {
pub id: &'static str,
pub http_method: Method,
}
const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d";
/// Provides a `Read` interface that converts multiple parts into the protocol
/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387).
/// **Note**: This implementation is just as rich as it needs to be to perform uploads
/// to google APIs, and might not be a fully-featured implementation.
#[derive(Default)]
pub struct MultiPartReader<'a> {
raw_parts: Vec<(Headers, &'a mut Read)>,
current_part: Option<(Cursor<Vec<u8>>, &'a mut Read)>,
last_part_boundary: Option<Cursor<Vec<u8>>>,
}
impl<'a> MultiPartReader<'a> {
/// Reserve memory for exactly the given amount of parts
pub fn reserve_exact(&mut self, cap: usize) {
self.raw_parts.reserve_exact(cap);
}
/// Add a new part to the queue of parts to be read on the first `read` call.
///
/// # Arguments
///
/// `headers` - identifying the body of the part. It's similar to the header
/// in an ordinary single-part call, and should thus contain the
/// same information.
/// `reader` - a reader providing the part's body
/// `size` - the amount of bytes provided by the reader. It will be put onto the header as
/// content-size.
/// `mime` - It will be put onto the content type
pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> {
let mut headers = Headers::new();
headers.set(ContentType(mime_type));
headers.set(ContentLength(size));
self.raw_parts.push((headers, reader));
self
}
/// Returns the mime-type representing our multi-part message.
/// Use it with the ContentType header.
pub fn mime_type(&self) -> Mime {
Mime(
TopLevel::Multipart,
SubLevel::Ext("Related".to_string()),
vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))],
)
}
/// Returns true if we are totally used
fn is_depleted(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none()
}
/// Returns true if we are handling our last part
fn is_last_part(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_some()
}
}
impl<'a> Read for MultiPartReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.raw_parts.len(),
self.current_part.is_none(),
self.last_part_boundary.is_none()) {
(_, _, false) => {
let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0);
if br < buf.len() {
self.last_part_boundary = None;
}
return Ok(br)
},
(0, true, true) => return Ok(0),
(n, true, _) if n > 0 => {
let (headers, reader) = self.raw_parts.remove(0);
let mut c = Cursor::new(Vec::<u8>::new());
(write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING,
headers, LINE_ENDING)).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
self.current_part = Some((c, reader));
}
_ => {},
}
// read headers as long as possible
let (hb, rr) = {
let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap();
let b = c.read(buf).unwrap_or(0);
(b, reader.read(&mut buf[b..]))
};
match rr {
Ok(bytes_read) => {
if hb < buf.len() && bytes_read == 0 {
if self.is_last_part() {
// before clearing the last part, we will add the boundary that
// will be written last
self.last_part_boundary = Some(Cursor::new(
format!("{}--{}--", LINE_ENDING, BOUNDARY).into_bytes()))
}
// We are depleted - this can trigger the next part to come in
self.current_part = None;
}
let mut total_bytes_read = hb + bytes_read;
while total_bytes_read < buf.len() && !self.is_depleted() {
match self.read(&mut buf[total_bytes_read ..]) {
Ok(br) => total_bytes_read += br,
Err(err) => return Err(err),
}
}
Ok(total_bytes_read)
}
Err(err) => {
// fail permanently
self.current_part = None;
self.last_part_boundary = None;
self.raw_parts.clear();
Err(err)
}
}
}
}
/// The `X-Upload-Content-Type` header.
///
/// Generated via rustc --pretty expanded -Z unstable-options, and manually
/// processed to be more readable.
#[derive(PartialEq, Debug, Clone)]
pub struct XUploadContentType(pub Mime);
impl ::std::ops::Deref for XUploadContentType {
type Target = Mime;
fn deref<'a>(&'a self) -> &'a Mime { &self.0 }
}
impl ::std::ops::DerefMut for XUploadContentType {
fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 }
}
impl Header for XUploadContentType {
fn header_name() -> &'static str { "X-Upload-Content-Type" }
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType)
}
}
impl HeaderFormat for XUploadContentType {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&**self, f)
}
}
impl Display for XUploadContentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chunk {
pub first: u64,
pub last: u64
}
impl fmt::Display for Chunk {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(write!(fmt, "{}-{}", self.first, self.last)).ok();
Ok(())
}
}
impl FromStr for Chunk {
type Err = &'static str;
/// NOTE: only implements `%i-%i`, not `*`
fn from_str(s: &str) -> std::result::Result<Chunk, &'static str> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 2 {
return Err("Expected two parts: %i-%i")
}
Ok(
Chunk {
first: match FromStr::from_str(parts[0]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'first' as digit")
},
last: match FromStr::from_str(parts[1]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'last' as digit")
}
}
)
}
}
/// Implements the Content-Range header, for serialization only
#[derive(Clone, PartialEq, Debug)]
pub struct ContentRange {
pub range: Option<Chunk>,
pub total_length: u64,
}
impl Header for ContentRange {
fn header_name() -> &'static str {
"Content-Range"
}
/// We are not parsable, as parsing is done by the `Range` header
fn parse_header(_: &[Vec<u8>]) -> hyper::error::Result<Self> {
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for ContentRange {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("bytes "));
match self.range {
Some(ref c) => try!(c.fmt(fmt)),
None => try!(fmt.write_str("*"))
}
(write!(fmt, "/{}", self.total_length)).ok();
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct RangeResponseHeader(pub Chunk);
impl Header for RangeResponseHeader {
fn header_name() -> &'static str {
"Range"
}
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
if raw.len() > 0 {
let v = &raw[0];
if let Ok(s) = std::str::from_utf8(v) {
const PREFIX: &'static str = "bytes ";
if s.starts_with(PREFIX) {
if let Ok(c) = <Chunk as FromStr>::from_str(&s[PREFIX.len()..]) {
return Ok(RangeResponseHeader(c))
}
}
}
}
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for RangeResponseHeader {
/// No implmentation necessary, we just need to parse
fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
/// A utility type to perform a resumable upload from start to end.
pub struct ResumableUploadHelper<'a, A: 'a> {
pub client: &'a mut hyper::client::Client,
pub delegate: &'a mut Delegate,
pub start_at: Option<u64>,
pub auth: &'a mut A,
pub user_agent: &'a str,
pub auth_header: Authorization<Bearer>,
pub url: &'a str,
pub reader: &'a mut ReadSeek,
pub media_type: Mime,
pub content_length: u64
}
impl<'a, A> ResumableUploadHelper<'a, A>
where A: oauth2::GetToken {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::Result<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
.header(ContentRange { range: None, total_length: self.content_length })
.header(self.auth_header.clone())
.send() {
Ok(r) => {
// 308 = resume-incomplete == PermanentRedirect
let headers = r.headers.clone();
let h: &RangeResponseHeader = match headers.get() {
Some(hh) if r.status == StatusCode::PermanentRedirect => hh,
None|Some(_) => {
if let Retry::After(d) = self.delegate.http_failure(&r, None, None) {
sleep(d);
continue;
}
return Err(Ok(r))
}
};
return Ok(h.0.last)
}
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Err(Err(err))
}
}
}
}
/// returns None if operation was cancelled by delegate, or the HttpResult.
/// It can be that we return the result just because we didn't understand the status code -
/// caller should check for status himself before assuming it's OK to use
pub fn upload(&mut self) -> Option<hyper::Result<hyper::client::Response>> {
let mut start = match self.start_at {
Some(s) => s,
None => match self.query_transfer_status() {
Ok(s) => s,
Err(result) => return Some(result)
}
};
const MIN_CHUNK_SIZE: u64 = 1 << 18;
let chunk_size = match self.delegate.chunk_size() {
cs if cs > MIN_CHUNK_SIZE => cs,
_ => MIN_CHUNK_SIZE
};
self.reader.seek(SeekFrom::Start(start)).unwrap();
loop {
let request_size = match self.content_length - start {
rs if rs > chunk_size => chunk_size,
rs => rs
};
let mut section_reader = self.reader.take(request_size);
let range_header = ContentRange {
range: Some(Chunk {first: start, last: start + request_size - 1}),
total_length: self.content_length
};
start += request_size;
if self.delegate.cancel_chunk_upload(&range_header) {
return None
}
let res = self.client.post(self.url)
.header(range_header)
.header(ContentType(self.media_type.clone()))
.header(UserAgent(self.user_agent.to_string()))
.body(&mut section_reader)
.send();
match res {
Ok(mut res) => {
if res.status == StatusCode::PermanentRedirect {
continue
}
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let Retry::After(d) = self.delegate.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
}
return Some(Ok(res))
},
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Some(Err(err))
}
}
}
}
}
// Copy of src/rust/cli/cmn.rs
// TODO(ST): Allow sharing common code between program types
pub fn remove_json_null_values(value: &mut json::value::Value) {
match *value {
json::value::Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}

1530
gen/cloudtrace2/src/lib.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-consumersurveys2-cli"
version = "1.0.7+20170407"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with Consumer Surveys (protocol v2)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/consumersurveys2-cli"
documentation = "http://byron.github.io/google-apis-rs/google_consumersurveys2_cli"
license = "MIT"
keywords = ["consumersurveys", "google", "cli"]
[[bin]]
name = "consumersurveys2"
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
strsim = "^0.5"
hyper-rustls = "^0.6"
yup-hyper-mock = "^2.0"
clap = "^2.0"
[features]
[dependencies.google-consumersurveys2]
path = "../consumersurveys2"
version = "1.0.7+20170407"

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,123 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/cli/README.md.mako'
DO NOT EDIT !
-->
The `consumersurveys2` command-line interface *(CLI)* allows to use most features of the *Google Consumer Surveys* service from the comfort of your terminal.
By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's
capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero.
If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools.
# Installation and Source Code
Install the command-line interface with cargo using:
```bash
cargo install google-consumersurveys2-cli
```
Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/consumersurveys2-cli).
# Usage
This documentation was generated from the *Consumer Surveys* API at revision *20170407*. The CLI is at version *1.0.7*.
```bash
consumersurveys2 [options]
mobileapppanels
get <panel-id> [-p <v>]... [-o <out>]
list [-p <v>]... [-o <out>]
update <panel-id> (-r <kv>)... [-p <v>]... [-o <out>]
results
get <survey-url-id> (-r <kv>)... [-p <v>]... [-o <out>]
surveys
delete <survey-url-id> [-p <v>]... [-o <out>]
get <survey-url-id> [-p <v>]... [-o <out>]
insert (-r <kv>)... [-p <v>]... [-o <out>]
list [-p <v>]... [-o <out>]
start <resource-id> (-r <kv>)... [-p <v>]... [-o <out>]
stop <resource-id> [-p <v>]... [-o <out>]
update <survey-url-id> (-r <kv>)... [-p <v>]... [-o <out>]
consumersurveys2 --help
Configuration:
[--scope <url>]...
Specify the authentication a method should be executed in. Each scope
requires the user to grant this application permission to use it.
If unset, it defaults to the shortest scope url for a particular method.
--config-dir <folder>
A directory into which we will store our persistent data. Defaults to
a user-writable directory that we will create during the first invocation.
[default: ~/.google-service-cli]
--debug
Output all server communication to standard error. `tx` and `rx` are placed
into the same stream.
--debug-auth
Output all communication related to authentication to standard error. `tx`
and `rx` are placed into the same stream.
```
# Configuration
The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `consumersurveys2-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis.
More information about the various kinds of persistent data are given in the following paragraphs.
# Authentication
Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the
set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*.
If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a
method that is read-only, it will ask only for a read-only scope.
You may use the `--scope` flag to specify a scope directly.
All applicable scopes are documented in the respective method's CLI documentation.
The first time a scope is used, the user is asked for permission. Follow the instructions given
by the CLI to grant permissions, or to decline.
If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration
directory, e.g. `~/.google-service-cli/consumersurveys2-token-<scope-hash>.json`. No manual management of these tokens
is necessary.
To revoke granted authentication, please refer to the [official documentation][revoke-access].
# Application Secrets
In order to allow any application to use Google services, it will need to be registered using the
[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it
one by one. Most APIs can be used for free and have a daily quota.
To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI
comes with a default application secret that is configured accordingly. This also means that heavy usage
all around the world may deplete the daily quota.
You can workaround this limitation by putting your own secrets file at this location:
`~/.google-service-cli/consumersurveys2-secret.json`, assuming that the required *consumersurveys* API
was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at
*APIs & auth -> Credentials -> Download JSON* and used as is.
Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new].
# Debugging
Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know
what exactly led to a particular issue. This is done by allowing all client-server communication to be
output to standard error *as-is*.
The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag
will cause all communication related to authentication to standard error.
If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the
issue at hand.
You may consider redirecting standard error into a file for ease of use, e.g. `consumersurveys2 --debug <resource> <method> [options] 2>debug.txt`.
[scopes]: https://developers.google.com/+/api/oauth#scopes
[revoke-access]: http://webapps.stackexchange.com/a/30849
[google-dev-console]: https://console.developers.google.com/
[google-project-new]: https://developers.google.com/console/help/new/

View File

@@ -0,0 +1,27 @@
site_name: Consumer Surveys v1.0.7+20170407
site_url: http://byron.github.io/google-apis-rs/google-consumersurveys2-cli
site_description: A complete library to interact with Consumer Surveys (protocol v2)
repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/consumersurveys2-cli
docs_dir: docs
site_dir: build_html
pages:
- ['index.md', 'Home']
- ['mobileapppanels_get.md', 'Mobileapppanels', 'Get']
- ['mobileapppanels_list.md', 'Mobileapppanels', 'List']
- ['mobileapppanels_update.md', 'Mobileapppanels', 'Update']
- ['results_get.md', 'Results', 'Get']
- ['surveys_delete.md', 'Surveys', 'Delete']
- ['surveys_get.md', 'Surveys', 'Get']
- ['surveys_insert.md', 'Surveys', 'Insert']
- ['surveys_list.md', 'Surveys', 'List']
- ['surveys_start.md', 'Surveys', 'Start']
- ['surveys_stop.md', 'Surveys', 'Stop']
- ['surveys_update.md', 'Surveys', 'Update']
theme: readthedocs
copyright: Copyright &copy; 2015-2016, `Sebastian Thiel`

View File

@@ -0,0 +1,799 @@
// COPY OF 'src/rust/cli/cmn.rs'
// DO NOT EDIT
use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token};
use serde_json as json;
use serde_json::value::Value;
use mime::Mime;
use clap::{App, SubCommand};
use strsim;
use std::fs;
use std::env;
use std::io;
use std::error::Error as StdError;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
use std::io::{Write, Read, stdout};
use std::default::Default;
const FIELD_SEP: char = '.';
pub enum ComplexType {
Pod,
Vec,
Map,
}
// Null,
// Bool(bool),
// I64(i64),
// U64(u64),
// F64(f64),
// String(String),
pub enum JsonType {
Boolean,
Int,
Uint,
Float,
String,
}
pub struct JsonTypeInfo {
pub jtype: JsonType,
pub ctype: ComplexType,
}
// Based on @erickt user comment. Thanks for the idea !
// Remove all keys whose values are null from given value (changed in place)
pub fn remove_json_null_values(value: &mut Value) {
match *value {
Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}
fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> {
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values {
let confidence = strsim::jaro_winkler(v, pv);
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
}
pub enum CallType {
Upload(UploadProtocol),
Standard,
}
arg_enum!{
pub enum UploadProtocol {
Simple,
Resumable
}
}
impl AsRef<str> for UploadProtocol {
fn as_ref(&self) -> &str {
match *self {
UploadProtocol::Simple => "simple",
UploadProtocol::Resumable => "resumable",
}
}
}
impl AsRef<str> for CallType {
fn as_ref(&self) -> &str {
match *self {
CallType::Upload(ref proto) => proto.as_ref(),
CallType::Standard => "standard-request",
}
}
}
#[derive(Clone, Default)]
pub struct FieldCursor(Vec<String>);
impl ToString for FieldCursor {
fn to_string(&self) -> String {
self.0.join(".")
}
}
impl From<&'static str> for FieldCursor {
fn from(value: &'static str) -> FieldCursor {
let mut res = FieldCursor::default();
res.set(value).unwrap();
res
}
}
fn assure_entry<'a, 'b>(m: &'a mut json::Map<String, Value>, k: &'b String) -> &'a mut Value {
if m.contains_key(k) {
return m.get_mut(k).expect("value to exist");
}
m.insert(k.to_owned(), Value::Object(Default::default()));
m.get_mut(k).expect("value to exist")
}
impl FieldCursor {
pub fn set(&mut self, value: &str) -> Result<(), CLIError> {
if value.len() == 0 {
return Err(CLIError::Field(FieldError::Empty));
}
let mut first_is_field_sep = false;
let mut char_count: usize = 0;
let mut last_c = FIELD_SEP;
let mut num_conscutive_field_seps = 0;
let mut field = String::new();
let mut fields = self.0.clone();
let push_field = |fs: &mut Vec<String>, f: &mut String| {
if f.len() > 0 {
fs.push(f.clone());
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
char_count += 1;
if c == FIELD_SEP {
if cid == 0 {
first_is_field_sep = true;
}
num_conscutive_field_seps += 1;
if cid > 0 && last_c == FIELD_SEP {
if fields.pop().is_none() {
return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string())));
}
} else {
push_field(&mut fields, &mut field);
}
} else {
num_conscutive_field_seps = 0;
if cid == 1 {
if first_is_field_sep {
fields.truncate(0);
}
}
field.push(c);
}
last_c = c;
}
push_field(&mut fields, &mut field);
if char_count == 1 && first_is_field_sep {
fields.truncate(0);
}
if char_count > 1 && num_conscutive_field_seps == 1 {
return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string())));
}
self.0 = fields;
Ok(())
}
pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option<String> {
if value.len() == 0 {
return None;
}
let mut last_c = FIELD_SEP;
let mut field = String::new();
let mut output = String::new();
let push_field = |fs: &mut String, f: &mut String| {
if f.len() > 0 {
fs.push_str(match did_you_mean(&f, possible_values) {
Some(candidate) => candidate,
None => &f,
});
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
if c == FIELD_SEP {
if last_c != FIELD_SEP {
push_field(&mut output, &mut field);
}
output.push(c);
} else {
field.push(c);
}
last_c = c;
}
push_field(&mut output, &mut field);
if &output == value {
None
} else {
Some(output)
}
}
pub fn set_json_value(&self,
mut object: &mut Value,
value: &str,
type_info: JsonTypeInfo,
err: &mut InvalidOptionsError,
orig_cursor: &FieldCursor) {
assert!(self.0.len() > 0);
for field in &self.0[..self.0.len() - 1] {
let tmp = object;
object = match *tmp {
Value::Object(ref mut mapping) => {
assure_entry(mapping, &field)
}
_ => panic!("We don't expect non-object Values here ..."),
};
}
match *object {
Value::Object(ref mut mapping) => {
let field = &self.0[self.0.len() - 1];
let to_jval = |value: &str,
jtype: JsonType,
err: &mut InvalidOptionsError|
-> Value {
match jtype {
JsonType::Boolean =>
Value::Bool(arg_from_str(value, err, &field, "boolean")),
JsonType::Int =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"int"))
.expect("valid f64")),
JsonType::Uint =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"uint"))
.expect("valid f64")),
JsonType::Float =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"float"))
.expect("valid f64")),
JsonType::String => Value::String(value.to_owned()),
}
};
match type_info.ctype {
ComplexType::Pod => {
if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err))
.is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
ComplexType::Vec => {
match *assure_entry(mapping, field) {
Value::Array(ref mut values) =>
values.push(to_jval(value, type_info.jtype, err)),
_ => unreachable!(),
}
}
ComplexType::Map => {
let (key, value) = parse_kv_arg(value, err, true);
let jval = to_jval(value.unwrap_or(""), type_info.jtype, err);
match *assure_entry(mapping, &field) {
Value::Object(ref mut value_map) => {
if value_map.insert(key.to_owned(), jval).is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
_ => unreachable!(),
}
}
}
}
_ => unreachable!(),
}
}
pub fn num_fields(&self) -> usize {
self.0.len()
}
}
pub fn parse_kv_arg<'a>(kv: &'a str,
err: &mut InvalidOptionsError,
for_hashmap: bool)
-> (&'a str, Option<&'a str>) {
let mut add_err = || {
err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(), for_hashmap))
};
match kv.find('=') {
None => {
add_err();
return (kv, None);
}
Some(pos) => {
let key = &kv[..pos];
if kv.len() <= pos + 1 {
add_err();
return (key, Some(""));
}
(key, Some(&kv[pos + 1..]))
}
}
}
pub fn calltype_from_str(name: &str,
valid_protocols: Vec<String>,
err: &mut InvalidOptionsError)
-> CallType {
CallType::Upload(match UploadProtocol::from_str(name) {
Ok(up) => up,
Err(msg) => {
err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols));
UploadProtocol::Simple
}
})
}
pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option<fs::File> {
match fs::File::open(file_path) {
Ok(f) => Some(f),
Err(io_err) => {
err.issues.push(CLIError::Input(InputError::Io((file_path.to_string(), io_err))));
None
}
}
}
pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option<Mime> {
match mime.parse() {
Ok(m) => Some(m),
Err(_) => {
err.issues.push(CLIError::Input(InputError::Mime(mime.to_string())));
None
}
}
}
pub fn writer_from_opts(arg: Option<&str>) -> Result<Box<Write>, io::Error> {
let f = arg.unwrap_or("-");
match f {
"-" => Ok(Box::new(stdout())),
_ => match fs::OpenOptions::new().create(true).write(true).open(f) {
Ok(f) => Ok(Box::new(f)),
Err(io_err) => Err(io_err),
},
}
}
pub fn arg_from_str<'a, T>(arg: &str,
err: &mut InvalidOptionsError,
arg_name: &'a str,
arg_type: &'a str)
-> T
where T: FromStr + Default,
<T as FromStr>::Err: fmt::Display
{
match FromStr::from_str(arg) {
Err(perr) => {
err.issues.push(CLIError::ParseError(arg_name.to_owned(),
arg_type.to_owned(),
arg.to_string(),
format!("{}", perr)));
Default::default()
}
Ok(v) => v,
}
}
pub struct JsonTokenStorage {
pub program_name: &'static str,
pub db_dir: String,
}
impl JsonTokenStorage {
fn path(&self, scope_hash: u64) -> PathBuf {
Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash))
}
}
#[derive(Debug)]
pub enum TokenStorageError {
Json(json::Error),
Io(io::Error),
}
impl fmt::Display for TokenStorageError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
TokenStorageError::Json(ref err) => writeln!(f, "Could not serialize secrets: {}", err),
TokenStorageError::Io(ref err) => writeln!(f, "Failed to write secret token: {}", err),
}
}
}
impl StdError for TokenStorageError {
fn description(&self) -> &str {
"Failure when getting or setting the token storage"
}
}
impl TokenStorage for JsonTokenStorage {
type Error = TokenStorageError;
// NOTE: logging might be interesting, currently we swallow all errors
fn set(&mut self,
scope_hash: u64,
_: &Vec<&str>,
token: Option<Token>)
-> Result<(), TokenStorageError> {
match token {
None => {
match fs::remove_file(self.path(scope_hash)) {
Err(err) => match err.kind() {
io::ErrorKind::NotFound => Ok(()),
_ => Err(TokenStorageError::Io(err)),
},
Ok(_) => Ok(()),
}
}
Some(token) => {
match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) {
Ok(mut f) => {
match json::to_writer_pretty(&mut f, &token) {
Ok(_) => Ok(()),
Err(serde_err) => Err(TokenStorageError::Json(serde_err)),
}
}
Err(io_err) => Err(TokenStorageError::Io(io_err)),
}
}
}
}
fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result<Option<Token>, TokenStorageError> {
match fs::File::open(&self.path(scope_hash)) {
Ok(f) => {
match json::de::from_reader(f) {
Ok(token) => Ok(Some(token)),
Err(err) => Err(TokenStorageError::Json(err)),
}
}
Err(io_err) => {
match io_err.kind() {
io::ErrorKind::NotFound => Ok(None),
_ => Err(TokenStorageError::Io(io_err)),
}
}
}
}
}
#[derive(Debug)]
pub enum ApplicationSecretError {
DecoderError((String, json::Error)),
FormatError(String),
}
impl fmt::Display for ApplicationSecretError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ApplicationSecretError::DecoderError((ref path, ref err)) =>
writeln!(f,
"Could not decode file at '{}' with error: {}.",
path,
err),
ApplicationSecretError::FormatError(ref path) =>
writeln!(f,
"'installed' field is unset in secret file at '{}'.",
path),
}
}
}
#[derive(Debug)]
pub enum ConfigurationError {
DirectoryCreationFailed((String, io::Error)),
DirectoryUnset,
HomeExpansionFailed(String),
Secret(ApplicationSecretError),
Io((String, io::Error)),
}
impl fmt::Display for ConfigurationError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) =>
writeln!(f,
"Directory '{}' could not be created with error: {}.",
dir,
err),
ConfigurationError::DirectoryUnset => writeln!(f, "--config-dir was unset or empty."),
ConfigurationError::HomeExpansionFailed(ref dir) =>
writeln!(f,
"Couldn't find HOME directory of current user, failed to expand '{}'.",
dir),
ConfigurationError::Secret(ref err) => writeln!(f, "Secret -> {}", err),
ConfigurationError::Io((ref path, ref err)) =>
writeln!(f,
"IO operation failed on path '{}' with error: {}.",
path,
err),
}
}
}
#[derive(Debug)]
pub enum InputError {
Io((String, io::Error)),
Mime(String),
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
InputError::Io((ref file_path, ref io_err)) =>
writeln!(f,
"Failed to open '{}' for reading with error: {}.",
file_path,
io_err),
InputError::Mime(ref mime) => writeln!(f, "'{}' is not a known mime-type.", mime),
}
}
}
#[derive(Debug)]
pub enum FieldError {
PopOnEmpty(String),
TrailingFieldSep(String),
Unknown(String, Option<String>, Option<String>),
Duplicate(String),
Empty,
}
impl fmt::Display for FieldError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
FieldError::PopOnEmpty(ref field) =>
writeln!(f, "'{}': Cannot move up on empty field cursor.", field),
FieldError::TrailingFieldSep(ref field) =>
writeln!(f,
"'{}': Single field separator may not be last character.",
field),
FieldError::Unknown(ref field, ref suggestion, ref value) => {
let suffix = match *suggestion {
Some(ref s) => {
let kv = match *value {
Some(ref v) => format!("{}={}", s, v),
None => s.clone(),
};
format!(" Did you mean '{}' ?", kv)
}
None => String::new(),
};
writeln!(f, "Field '{}' does not exist.{}", field, suffix)
}
FieldError::Duplicate(ref cursor) =>
writeln!(f, "Value at '{}' was already set", cursor),
FieldError::Empty => writeln!(f, "Field names must not be empty."),
}
}
}
#[derive(Debug)]
pub enum CLIError {
Configuration(ConfigurationError),
ParseError(String, String, String, String),
UnknownParameter(String, Vec<&'static str>),
InvalidUploadProtocol(String, Vec<String>),
InvalidKeyValueSyntax(String, bool),
Input(InputError),
Field(FieldError),
MissingCommandError,
MissingMethodError(String),
}
impl fmt::Display for CLIError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err),
CLIError::Input(ref err) => write!(f, "Input -> {}", err),
CLIError::Field(ref err) => write!(f, "Field -> {}", err),
CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) =>
writeln!(f,
"'{}' is not a valid upload protocol. Choose from one of {}.",
proto_name,
valid_names.join(", ")),
CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) =>
writeln!(f,
"Failed to parse argument '{}' with value '{}' as {} with error: {}.",
arg_name,
value,
type_name,
err_desc),
CLIError::UnknownParameter(ref param_name, ref possible_values) => {
let suffix = match did_you_mean(param_name, &possible_values) {
Some(v) => format!(" Did you mean '{}' ?", v),
None => String::new(),
};
write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix)
}
CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => {
let hashmap_info = if is_hashmap {
"hashmap "
} else {
""
};
writeln!(f,
"'{}' does not match {}pattern <key>=<value>.",
kv,
hashmap_info)
}
CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."),
CLIError::MissingMethodError(ref cmd) =>
writeln!(f,
"Please specify the method to call on the '{}' command.",
cmd),
}
}
}
#[derive(Debug)]
pub struct InvalidOptionsError {
pub issues: Vec<CLIError>,
pub exit_code: i32,
}
impl fmt::Display for InvalidOptionsError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for issue in &self.issues {
try!(issue.fmt(f));
}
Ok(())
}
}
impl InvalidOptionsError {
pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError {
InvalidOptionsError {
issues: vec![err],
exit_code: exit_code,
}
}
pub fn new() -> InvalidOptionsError {
InvalidOptionsError {
issues: Vec::new(),
exit_code: 1,
}
}
}
pub fn assure_config_dir_exists(dir: &str) -> Result<String, CLIError> {
let trdir = dir.trim();
if trdir.len() == 0 {
return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset));
}
let expanded_config_dir = if trdir.as_bytes()[0] == b'~' {
match env::var("HOME").ok().or(env::var("UserProfile").ok()) {
None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))),
Some(mut user) => {
user.push_str(&trdir[1..]);
user
}
}
} else {
trdir.to_string()
};
if let Err(err) = fs::create_dir(&expanded_config_dir) {
if err.kind() != io::ErrorKind::AlreadyExists {
return Err(CLIError::Configuration(
ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err))));
}
}
Ok(expanded_config_dir)
}
pub fn application_secret_from_directory(dir: &str,
secret_basename: &str,
json_console_secret: &str)
-> Result<ApplicationSecret, CLIError> {
let secret_path = Path::new(dir).join(secret_basename);
let secret_str = || secret_path.as_path().to_str().unwrap().to_string();
let secret_io_error = |io_err: io::Error| {
Err(CLIError::Configuration(ConfigurationError::Io((secret_str(), io_err))))
};
for _ in 0..2 {
match fs::File::open(&secret_path) {
Err(mut err) => {
if err.kind() == io::ErrorKind::NotFound {
// Write our built-in one - user may adjust the written file at will
err = match fs::OpenOptions::new()
.create(true)
.write(true)
.open(&secret_path) {
Err(cfe) => cfe,
Ok(mut f) => {
// Assure we convert 'ugly' json string into pretty one
let console_secret: ConsoleApplicationSecret =
json::from_str(json_console_secret).unwrap();
match json::to_writer_pretty(&mut f, &console_secret) {
Err(serde_err) =>
panic!("Unexpected serde error: {:#?}", serde_err),
Ok(_) => continue,
}
}
};
// fall through to IO error handling
}
return secret_io_error(err);
}
Ok(f) => {
match json::de::from_reader::<_, ConsoleApplicationSecret>(f) {
Err(json_err) =>
return Err(CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::DecoderError(
(secret_str(), json_err)
)))),
Ok(console_secret) => match console_secret.installed {
Some(secret) => return Ok(secret),
None => return Err(
CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::FormatError(secret_str())
))),
},
}
}
}
}
unreachable!();
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,30 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-consumersurveys2"
version = "1.0.7+20170407"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with Consumer Surveys (protocol v2)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/consumersurveys2"
documentation = "https://docs.rs/google-consumersurveys2/1.0.7+20170407"
license = "MIT"
keywords = ["consumersurveys", "google", "protocol", "web", "api"]
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
url = "= 0.5"
[features]

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,188 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/api/README.md.mako'
DO NOT EDIT !
-->
The `google-consumersurveys2` library allows access to all features of the *Google Consumer Surveys* service.
This documentation was generated from *Consumer Surveys* crate version *1.0.7+20170407*, where *20170407* is the exact revision of the *consumersurveys:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.7*.
# Features
Handle the following *Resources* with ease from the central [hub](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.ConsumerSurveys.html) ...
* mobileapppanels
* [*get*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.MobileapppanelGetCall.html), [*list*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.MobileapppanelListCall.html) and [*update*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.MobileapppanelUpdateCall.html)
* results
* [*get*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.ResultGetCall.html)
* [surveys](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.Survey.html)
* [*delete*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.SurveyDeleteCall.html), [*get*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.SurveyGetCall.html), [*insert*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.SurveyInsertCall.html), [*list*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.SurveyListCall.html), [*start*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.SurveyStartCall.html), [*stop*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.SurveyStopCall.html) and [*update*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.SurveyUpdateCall.html)
Download supported by ...
* [*get results*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.ResultGetCall.html)
# Structure of this Library
The API is structured into the following primary items:
* **[Hub](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/struct.ConsumerSurveys.html)**
* a central object to maintain state and allow accessing all *Activities*
* creates [*Method Builders*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.MethodsBuilder.html) which in turn
allow access to individual [*Call Builders*](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.CallBuilder.html)
* **[Resources](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.Resource.html)**
* primary types that you can apply *Activities* to
* a collection of properties and *Parts*
* **[Parts](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.Part.html)**
* a collection of properties
* never directly used in *Activities*
* **[Activities](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.CallBuilder.html)**
* operations to apply to *Resources*
All *structures* are marked with applicable traits to further categorize them and ease browsing.
Generally speaking, you can invoke *Activities* like this:
```Rust,ignore
let r = hub.resource().activity(...).doit()
```
Or specifically ...
```ignore
let r = hub.surveys().delete(...).doit()
let r = hub.surveys().insert(...).doit()
let r = hub.surveys().list(...).doit()
let r = hub.surveys().update(...).doit()
let r = hub.surveys().get(...).doit()
let r = hub.surveys().stop(...).doit()
let r = hub.surveys().start(...).doit()
```
The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
The `doit()` method performs the actual communication with the server and returns the respective result.
# Usage
## Setting up your Project
To use this library, you would put the following lines into your `Cargo.toml` file:
```toml
[dependencies]
google-consumersurveys2 = "*"
```
## A complete example
```Rust
extern crate hyper;
extern crate hyper_rustls;
extern crate yup_oauth2 as oauth2;
extern crate google_consumersurveys2 as consumersurveys2;
use consumersurveys2::{Result, Error};
use std::default::Default;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
use consumersurveys2::ConsumerSurveys;
// Get an ApplicationSecret instance by some means. It contains the `client_id` and
// `client_secret`, among other things.
let secret: ApplicationSecret = Default::default();
// Instantiate the authenticator. It will choose a suitable authentication flow for you,
// unless you replace `None` with the desired Flow.
// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
// retrieve them from storage.
let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
<MemoryStorage as Default>::default(), None);
let mut hub = ConsumerSurveys::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
// You can configure optional parameters by calling the respective setters at will, and
// execute the final call using `doit()`.
// Values shown here are possibly random and not representative !
let result = hub.surveys().list()
.token("eirmod")
.start_index(53)
.max_results(36)
.doit();
match result {
Err(e) => match e {
// The Error enum provides details about what exactly happened.
// You can also just use its `Debug`, `Display` or `Error` traits
Error::HttpError(_)
|Error::MissingAPIKey
|Error::MissingToken(_)
|Error::Cancelled
|Error::UploadSizeLimitExceeded(_, _)
|Error::Failure(_)
|Error::BadRequest(_)
|Error::FieldClash(_)
|Error::JsonDecodeError(_, _) => println!("{}", e),
},
Ok(res) => println!("Success: {:?}", res),
}
```
## Handling Errors
All errors produced by the system are provided either as [Result](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/enum.Result.html) enumeration as return value of
the doit() methods, or handed as possibly intermediate results to either the
[Hub Delegate](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.Delegate.html), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html).
When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
makes the system potentially resilient to all kinds of errors.
## Uploads and Downloads
If a method supports downloads, the response body, which is part of the [Result](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/enum.Result.html), should be
read by you to obtain the media.
If such a method also supports a [Response Result](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.ResponseResult.html), it will return that by default.
You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
this call: `.param("alt", "media")`.
Methods supporting uploads can do so using up to 2 different protocols:
*simple* and *resumable*. The distinctiveness of each is represented by customized
`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
## Customization and Callbacks
You may alter the way an `doit()` method is called by providing a [delegate](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.Delegate.html) to the
[Method Builder](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.CallBuilder.html) before making the final `doit()` call.
Respective methods will be called to provide progress information, as well as determine whether the system should
retry on failure.
The [delegate trait](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
## Optional Parts in Server-Requests
All structures provided by this library are made to be [enocodable](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.RequestValue.html) and
[decodable](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
are valid.
Most optionals are are considered [Parts](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.Part.html) which are identifiable by name, which will be sent to
the server to indicate either the set parts of the request or the desired parts in the response.
## Builder Arguments
Using [method builders](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods.
These will always take a single argument, for which the following statements are true.
* [PODs][wiki-pod] are handed by copy
* strings are passed as `&str`
* [request values](https://docs.rs/google-consumersurveys2/1.0.7+20170407/google_consumersurveys2/trait.RequestValue.html) are moved
Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
[google-go-api]: https://github.com/google/google-api-go-client
# License
The **consumersurveys2** library was generated by Sebastian Thiel, and is placed
under the *MIT* license.
You can read the full text at the repository's [license file][repo-license].
[repo-license]: https://github.com/Byron/google-apis-rsblob/master/LICENSE.md

View File

@@ -0,0 +1,753 @@
// COPY OF 'src/rust/api/cmn.rs'
// DO NOT EDIT
use std::io::{self, Read, Seek, Cursor, Write, SeekFrom};
use std;
use std::fmt::{self, Display};
use std::str::FromStr;
use std::error;
use std::thread::sleep;
use std::time::Duration;
use mime::{Mime, TopLevel, SubLevel, Attr, Value};
use oauth2::{TokenType, Retry, self};
use hyper;
use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header,
HeaderFormat, Bearer};
use hyper::http::h1::LINE_ENDING;
use hyper::method::Method;
use hyper::status::StatusCode;
use serde_json as json;
/// Identifies the Hub. There is only one per library, this trait is supposed
/// to make intended use more explicit.
/// The hub allows to access all resource methods more easily.
pub trait Hub {}
/// Identifies types for building methods of a particular resource type
pub trait MethodsBuilder {}
/// Identifies types which represent builders for a particular resource method
pub trait CallBuilder {}
/// Identifies types which can be inserted and deleted.
/// Types with this trait are most commonly used by clients of this API.
pub trait Resource {}
/// Identifies types which are used in API responses.
pub trait ResponseResult {}
/// Identifies types which are used in API requests.
pub trait RequestValue {}
/// Identifies types which are not actually used by the API
/// This might be a bug within the google API schema.
pub trait UnusedType {}
/// Identifies types which are only used as part of other types, which
/// usually are carrying the `Resource` trait.
pub trait Part {}
/// Identifies types which are only used by other types internally.
/// They have no special meaning, this trait just marks them for completeness.
pub trait NestedType {}
/// A utility to specify reader types which provide seeking capabilities too
pub trait ReadSeek: Seek + Read {}
impl<T: Seek + Read> ReadSeek for T {}
/// A trait for all types that can convert themselves into a *parts* string
pub trait ToParts {
fn to_parts(&self) -> String;
}
/// A utility type which can decode a server response that indicates error
#[derive(Deserialize)]
pub struct JsonServerError {
pub error: String,
pub error_description: Option<String>
}
/// A utility to represent detailed errors we might see in case there are BadRequests.
/// The latter happen if the sent parameters or request structures are unsound
#[derive(Deserialize, Serialize, Debug)]
pub struct ErrorResponse {
error: ServerError,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerError {
errors: Vec<ServerMessage>,
code: u16,
message: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerMessage {
domain: String,
reason: String,
message: String,
#[serde(rename="locationType")]
location_type: Option<String>,
location: Option<String>
}
#[derive(Copy, Clone)]
pub struct DummyNetworkStream;
impl Read for DummyNetworkStream {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl Write for DummyNetworkStream {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl hyper::net::NetworkStream for DummyNetworkStream {
fn peer_addr(&mut self) -> io::Result<std::net::SocketAddr> {
Ok("127.0.0.1:1337".parse().unwrap())
}
fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
}
/// A trait specifying functionality to help controlling any request performed by the API.
/// The trait has a conservative default implementation.
///
/// It contains methods to deal with all common issues, as well with the ones related to
/// uploading media
pub trait Delegate {
/// Called at the beginning of any API request. The delegate should store the method
/// information if he is interesting in knowing more context when further calls to it
/// are made.
/// The matching `finished()` call will always be made, no matter whether or not the API
/// request was successful. That way, the delegate may easily maintain a clean state
/// between various API calls.
fn begin(&mut self, MethodInfo) {}
/// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
///
/// Return retry information.
fn http_error(&mut self, &hyper::Error) -> Retry {
Retry::Abort
}
/// Called whenever there is the need for your applications API key after
/// the official authenticator implementation didn't provide one, for some reason.
/// If this method returns None as well, the underlying operation will fail
fn api_key(&mut self) -> Option<String> {
None
}
/// Called whenever the Authenticator didn't yield a token. The delegate
/// may attempt to provide one, or just take it as a general information about the
/// impending failure.
/// The given Error provides information about why the token couldn't be acquired in the
/// first place
fn token(&mut self, err: &error::Error) -> Option<oauth2::Token> {
let _ = err;
None
}
/// Called during resumable uploads to provide a URL for the impending upload.
/// It was saved after a previous call to `store_upload_url(...)`, and if not None,
/// will be used instead of asking the server for a new upload URL.
/// This is useful in case a previous resumable upload was aborted/canceled, but should now
/// be resumed.
/// The returned URL will be used exactly once - if it fails again and the delegate allows
/// to retry, we will ask the server for a new upload URL.
fn upload_url(&mut self) -> Option<String> {
None
}
/// Called after we have retrieved a new upload URL for a resumable upload to store it
/// in case we fail or cancel. That way, we can attempt to resume the upload later,
/// see `upload_url()`.
/// It will also be called with None after a successful upload, which allows the delegate
/// to forget the URL. That way, we will not attempt to resume an upload that has already
/// finished.
fn store_upload_url(&mut self, url: Option<&str>) {
let _ = url;
}
/// Called whenever a server response could not be decoded from json.
/// It's for informational purposes only, the caller will return with an error
/// accordingly.
///
/// # Arguments
///
/// * `json_encoded_value` - The json-encoded value which failed to decode.
/// * `json_decode_error` - The decoder error
fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &json::Error) {
let _ = json_encoded_value;
let _ = json_decode_error;
}
/// Called whenever the http request returns with a non-success status code.
/// This can involve authentication issues, or anything else that very much
/// depends on the used API method.
/// The delegate should check the status, header and decoded json error to decide
/// whether to retry or not. In the latter case, the underlying call will fail.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
fn http_failure(&mut self, _: &hyper::client::Response, Option<JsonServerError>, _: Option<ServerError>) -> Retry {
Retry::Abort
}
/// Called prior to sending the main request of the given method. It can be used to time
/// the call or to print progress information.
/// It's also useful as you can be sure that a request will definitely be made.
fn pre_request(&mut self) { }
/// Return the size of each chunk of a resumable upload.
/// Must be a power of two, with 1<<18 being the smallest allowed chunk size.
/// Will be called once before starting any resumable upload.
fn chunk_size(&mut self) -> u64 {
1 << 23
}
/// Called before the given chunk is uploaded to the server.
/// If true is returned, the upload will be interrupted.
/// However, it may be resumable if you stored the upload URL in a previous call
/// to `store_upload_url()`
fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool {
let _ = chunk;
false
}
/// Called before the API request method returns, in every case. It can be used to clean up
/// internal state between calls to the API.
/// This call always has a matching call to `begin(...)`.
///
/// # Arguments
///
/// * `is_success` - a true value indicates the operation was successful. If false, you should
/// discard all values stored during `store_upload_url`.
fn finished(&mut self, is_success: bool) {
let _ = is_success;
}
}
/// A delegate with a conservative default implementation, which is used if no other delegate is
/// set.
#[derive(Default)]
pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}
#[derive(Debug)]
pub enum Error {
/// The http connection failed
HttpError(hyper::Error),
/// An attempt was made to upload a resource with size stored in field `.0`
/// even though the maximum upload size is what is stored in field `.1`.
UploadSizeLimitExceeded(u64, u64),
/// Represents information about a request that was not understood by the server.
/// Details are included.
BadRequest(ErrorResponse),
/// We needed an API key for authentication, but didn't obtain one.
/// Neither through the authenticator, nor through the Delegate.
MissingAPIKey,
/// We required a Token, but didn't get one from the Authenticator
MissingToken(Box<error::Error>),
/// The delgate instructed to cancel the operation
Cancelled,
/// An additional, free form field clashed with one of the built-in optional ones
FieldClash(&'static str),
/// Shows that we failed to decode the server response.
/// This can happen if the protocol changes in conjunction with strict json decoding.
JsonDecodeError(String, json::Error),
/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref err) => err.fmt(f),
Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) =>
writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}"
, resource_size, max_size),
Error::MissingAPIKey => {
(writeln!(f, "The application's API key was not found in the configuration")).ok();
writeln!(f, "It is used as there are no Scopes defined for this method.")
},
Error::BadRequest(ref err) => {
try!(writeln!(f, "Bad Request ({}): {}", err.error.code, err.error.message));
for err in err.error.errors.iter() {
try!(writeln!(f, " {}: {}, {}{}",
err.domain,
err.message,
err.reason,
match &err.location {
&Some(ref loc) => format!("@{}", loc),
&None => String::new(),
}));
}
Ok(())
},
Error::MissingToken(ref err) =>
writeln!(f, "Token retrieval failed with error: {}", err),
Error::Cancelled =>
writeln!(f, "Operation cancelled by delegate"),
Error::FieldClash(field) =>
writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field),
Error::JsonDecodeError(ref json_str, ref err)
=> writeln!(f, "{}: {}", err, json_str),
Error::Failure(ref response) =>
writeln!(f, "Http status indicates failure: {:?}", response),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::HttpError(ref err) => err.description(),
Error::JsonDecodeError(_, ref err) => err.description(),
_ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead"
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::HttpError(ref err) => err.cause(),
Error::JsonDecodeError(_, ref err) => err.cause(),
_ => None
}
}
}
/// A universal result type used as return for all calls.
pub type Result<T> = std::result::Result<T, Error>;
/// Contains information about an API request.
pub struct MethodInfo {
pub id: &'static str,
pub http_method: Method,
}
const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d";
/// Provides a `Read` interface that converts multiple parts into the protocol
/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387).
/// **Note**: This implementation is just as rich as it needs to be to perform uploads
/// to google APIs, and might not be a fully-featured implementation.
#[derive(Default)]
pub struct MultiPartReader<'a> {
raw_parts: Vec<(Headers, &'a mut Read)>,
current_part: Option<(Cursor<Vec<u8>>, &'a mut Read)>,
last_part_boundary: Option<Cursor<Vec<u8>>>,
}
impl<'a> MultiPartReader<'a> {
/// Reserve memory for exactly the given amount of parts
pub fn reserve_exact(&mut self, cap: usize) {
self.raw_parts.reserve_exact(cap);
}
/// Add a new part to the queue of parts to be read on the first `read` call.
///
/// # Arguments
///
/// `headers` - identifying the body of the part. It's similar to the header
/// in an ordinary single-part call, and should thus contain the
/// same information.
/// `reader` - a reader providing the part's body
/// `size` - the amount of bytes provided by the reader. It will be put onto the header as
/// content-size.
/// `mime` - It will be put onto the content type
pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> {
let mut headers = Headers::new();
headers.set(ContentType(mime_type));
headers.set(ContentLength(size));
self.raw_parts.push((headers, reader));
self
}
/// Returns the mime-type representing our multi-part message.
/// Use it with the ContentType header.
pub fn mime_type(&self) -> Mime {
Mime(
TopLevel::Multipart,
SubLevel::Ext("Related".to_string()),
vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))],
)
}
/// Returns true if we are totally used
fn is_depleted(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none()
}
/// Returns true if we are handling our last part
fn is_last_part(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_some()
}
}
impl<'a> Read for MultiPartReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.raw_parts.len(),
self.current_part.is_none(),
self.last_part_boundary.is_none()) {
(_, _, false) => {
let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0);
if br < buf.len() {
self.last_part_boundary = None;
}
return Ok(br)
},
(0, true, true) => return Ok(0),
(n, true, _) if n > 0 => {
let (headers, reader) = self.raw_parts.remove(0);
let mut c = Cursor::new(Vec::<u8>::new());
(write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING,
headers, LINE_ENDING)).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
self.current_part = Some((c, reader));
}
_ => {},
}
// read headers as long as possible
let (hb, rr) = {
let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap();
let b = c.read(buf).unwrap_or(0);
(b, reader.read(&mut buf[b..]))
};
match rr {
Ok(bytes_read) => {
if hb < buf.len() && bytes_read == 0 {
if self.is_last_part() {
// before clearing the last part, we will add the boundary that
// will be written last
self.last_part_boundary = Some(Cursor::new(
format!("{}--{}--", LINE_ENDING, BOUNDARY).into_bytes()))
}
// We are depleted - this can trigger the next part to come in
self.current_part = None;
}
let mut total_bytes_read = hb + bytes_read;
while total_bytes_read < buf.len() && !self.is_depleted() {
match self.read(&mut buf[total_bytes_read ..]) {
Ok(br) => total_bytes_read += br,
Err(err) => return Err(err),
}
}
Ok(total_bytes_read)
}
Err(err) => {
// fail permanently
self.current_part = None;
self.last_part_boundary = None;
self.raw_parts.clear();
Err(err)
}
}
}
}
/// The `X-Upload-Content-Type` header.
///
/// Generated via rustc --pretty expanded -Z unstable-options, and manually
/// processed to be more readable.
#[derive(PartialEq, Debug, Clone)]
pub struct XUploadContentType(pub Mime);
impl ::std::ops::Deref for XUploadContentType {
type Target = Mime;
fn deref<'a>(&'a self) -> &'a Mime { &self.0 }
}
impl ::std::ops::DerefMut for XUploadContentType {
fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 }
}
impl Header for XUploadContentType {
fn header_name() -> &'static str { "X-Upload-Content-Type" }
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType)
}
}
impl HeaderFormat for XUploadContentType {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&**self, f)
}
}
impl Display for XUploadContentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chunk {
pub first: u64,
pub last: u64
}
impl fmt::Display for Chunk {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(write!(fmt, "{}-{}", self.first, self.last)).ok();
Ok(())
}
}
impl FromStr for Chunk {
type Err = &'static str;
/// NOTE: only implements `%i-%i`, not `*`
fn from_str(s: &str) -> std::result::Result<Chunk, &'static str> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 2 {
return Err("Expected two parts: %i-%i")
}
Ok(
Chunk {
first: match FromStr::from_str(parts[0]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'first' as digit")
},
last: match FromStr::from_str(parts[1]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'last' as digit")
}
}
)
}
}
/// Implements the Content-Range header, for serialization only
#[derive(Clone, PartialEq, Debug)]
pub struct ContentRange {
pub range: Option<Chunk>,
pub total_length: u64,
}
impl Header for ContentRange {
fn header_name() -> &'static str {
"Content-Range"
}
/// We are not parsable, as parsing is done by the `Range` header
fn parse_header(_: &[Vec<u8>]) -> hyper::error::Result<Self> {
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for ContentRange {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("bytes "));
match self.range {
Some(ref c) => try!(c.fmt(fmt)),
None => try!(fmt.write_str("*"))
}
(write!(fmt, "/{}", self.total_length)).ok();
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct RangeResponseHeader(pub Chunk);
impl Header for RangeResponseHeader {
fn header_name() -> &'static str {
"Range"
}
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
if raw.len() > 0 {
let v = &raw[0];
if let Ok(s) = std::str::from_utf8(v) {
const PREFIX: &'static str = "bytes ";
if s.starts_with(PREFIX) {
if let Ok(c) = <Chunk as FromStr>::from_str(&s[PREFIX.len()..]) {
return Ok(RangeResponseHeader(c))
}
}
}
}
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for RangeResponseHeader {
/// No implmentation necessary, we just need to parse
fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
/// A utility type to perform a resumable upload from start to end.
pub struct ResumableUploadHelper<'a, A: 'a> {
pub client: &'a mut hyper::client::Client,
pub delegate: &'a mut Delegate,
pub start_at: Option<u64>,
pub auth: &'a mut A,
pub user_agent: &'a str,
pub auth_header: Authorization<Bearer>,
pub url: &'a str,
pub reader: &'a mut ReadSeek,
pub media_type: Mime,
pub content_length: u64
}
impl<'a, A> ResumableUploadHelper<'a, A>
where A: oauth2::GetToken {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::Result<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
.header(ContentRange { range: None, total_length: self.content_length })
.header(self.auth_header.clone())
.send() {
Ok(r) => {
// 308 = resume-incomplete == PermanentRedirect
let headers = r.headers.clone();
let h: &RangeResponseHeader = match headers.get() {
Some(hh) if r.status == StatusCode::PermanentRedirect => hh,
None|Some(_) => {
if let Retry::After(d) = self.delegate.http_failure(&r, None, None) {
sleep(d);
continue;
}
return Err(Ok(r))
}
};
return Ok(h.0.last)
}
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Err(Err(err))
}
}
}
}
/// returns None if operation was cancelled by delegate, or the HttpResult.
/// It can be that we return the result just because we didn't understand the status code -
/// caller should check for status himself before assuming it's OK to use
pub fn upload(&mut self) -> Option<hyper::Result<hyper::client::Response>> {
let mut start = match self.start_at {
Some(s) => s,
None => match self.query_transfer_status() {
Ok(s) => s,
Err(result) => return Some(result)
}
};
const MIN_CHUNK_SIZE: u64 = 1 << 18;
let chunk_size = match self.delegate.chunk_size() {
cs if cs > MIN_CHUNK_SIZE => cs,
_ => MIN_CHUNK_SIZE
};
self.reader.seek(SeekFrom::Start(start)).unwrap();
loop {
let request_size = match self.content_length - start {
rs if rs > chunk_size => chunk_size,
rs => rs
};
let mut section_reader = self.reader.take(request_size);
let range_header = ContentRange {
range: Some(Chunk {first: start, last: start + request_size - 1}),
total_length: self.content_length
};
start += request_size;
if self.delegate.cancel_chunk_upload(&range_header) {
return None
}
let res = self.client.post(self.url)
.header(range_header)
.header(ContentType(self.media_type.clone()))
.header(UserAgent(self.user_agent.to_string()))
.body(&mut section_reader)
.send();
match res {
Ok(mut res) => {
if res.status == StatusCode::PermanentRedirect {
continue
}
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let Retry::After(d) = self.delegate.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
}
return Some(Ok(res))
},
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Some(Err(err))
}
}
}
}
}
// Copy of src/rust/cli/cmn.rs
// TODO(ST): Allow sharing common code between program types
pub fn remove_json_null_values(value: &mut json::value::Value) {
match *value {
json::value::Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-datastore1-cli"
version = "1.0.7+20171205"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with datastore (protocol v1)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/datastore1-cli"
homepage = "https://cloud.google.com/datastore/"
documentation = "http://byron.github.io/google-apis-rs/google_datastore1_cli"
license = "MIT"
keywords = ["datastore", "google", "cli"]
[[bin]]
name = "datastore1"
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
strsim = "^0.5"
hyper-rustls = "^0.6"
yup-hyper-mock = "^2.0"
clap = "^2.0"
[features]
[dependencies.google-datastore1]
path = "../datastore1"
version = "1.0.7+20171205"

View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,124 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/cli/README.md.mako'
DO NOT EDIT !
-->
The `datastore1` command-line interface *(CLI)* allows to use most features of the *Google datastore* service from the comfort of your terminal.
By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's
capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero.
If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools.
Everything else about the *datastore* API can be found at the
[official documentation site](https://cloud.google.com/datastore/).
# Installation and Source Code
Install the command-line interface with cargo using:
```bash
cargo install google-datastore1-cli
```
Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/datastore1-cli).
# Usage
This documentation was generated from the *datastore* API at revision *20171205*. The CLI is at version *1.0.7*.
```bash
datastore1 [options]
projects
allocate-ids <project-id> (-r <kv>)... [-p <v>]... [-o <out>]
begin-transaction <project-id> (-r <kv>)... [-p <v>]... [-o <out>]
commit <project-id> (-r <kv>)... [-p <v>]... [-o <out>]
lookup <project-id> (-r <kv>)... [-p <v>]... [-o <out>]
operations-cancel <name> [-p <v>]... [-o <out>]
operations-delete <name> [-p <v>]... [-o <out>]
operations-get <name> [-p <v>]... [-o <out>]
operations-list <name> [-p <v>]... [-o <out>]
reserve-ids <project-id> (-r <kv>)... [-p <v>]... [-o <out>]
rollback <project-id> (-r <kv>)... [-p <v>]... [-o <out>]
run-query <project-id> (-r <kv>)... [-p <v>]... [-o <out>]
datastore1 --help
Configuration:
[--scope <url>]...
Specify the authentication a method should be executed in. Each scope
requires the user to grant this application permission to use it.
If unset, it defaults to the shortest scope url for a particular method.
--config-dir <folder>
A directory into which we will store our persistent data. Defaults to
a user-writable directory that we will create during the first invocation.
[default: ~/.google-service-cli]
--debug
Output all server communication to standard error. `tx` and `rx` are placed
into the same stream.
--debug-auth
Output all communication related to authentication to standard error. `tx`
and `rx` are placed into the same stream.
```
# Configuration
The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `datastore1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis.
More information about the various kinds of persistent data are given in the following paragraphs.
# Authentication
Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the
set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*.
If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a
method that is read-only, it will ask only for a read-only scope.
You may use the `--scope` flag to specify a scope directly.
All applicable scopes are documented in the respective method's CLI documentation.
The first time a scope is used, the user is asked for permission. Follow the instructions given
by the CLI to grant permissions, or to decline.
If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration
directory, e.g. `~/.google-service-cli/datastore1-token-<scope-hash>.json`. No manual management of these tokens
is necessary.
To revoke granted authentication, please refer to the [official documentation][revoke-access].
# Application Secrets
In order to allow any application to use Google services, it will need to be registered using the
[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it
one by one. Most APIs can be used for free and have a daily quota.
To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI
comes with a default application secret that is configured accordingly. This also means that heavy usage
all around the world may deplete the daily quota.
You can workaround this limitation by putting your own secrets file at this location:
`~/.google-service-cli/datastore1-secret.json`, assuming that the required *datastore* API
was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at
*APIs & auth -> Credentials -> Download JSON* and used as is.
Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new].
# Debugging
Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know
what exactly led to a particular issue. This is done by allowing all client-server communication to be
output to standard error *as-is*.
The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag
will cause all communication related to authentication to standard error.
If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the
issue at hand.
You may consider redirecting standard error into a file for ease of use, e.g. `datastore1 --debug <resource> <method> [options] 2>debug.txt`.
[scopes]: https://developers.google.com/+/api/oauth#scopes
[revoke-access]: http://webapps.stackexchange.com/a/30849
[google-dev-console]: https://console.developers.google.com/
[google-project-new]: https://developers.google.com/console/help/new/

View File

@@ -0,0 +1,27 @@
site_name: datastore v1.0.7+20171205
site_url: http://byron.github.io/google-apis-rs/google-datastore1-cli
site_description: A complete library to interact with datastore (protocol v1)
repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/datastore1-cli
docs_dir: docs
site_dir: build_html
pages:
- ['index.md', 'Home']
- ['projects_allocate-ids.md', 'Projects', 'Allocate Ids']
- ['projects_begin-transaction.md', 'Projects', 'Begin Transaction']
- ['projects_commit.md', 'Projects', 'Commit']
- ['projects_lookup.md', 'Projects', 'Lookup']
- ['projects_operations-cancel.md', 'Projects', 'Operations Cancel']
- ['projects_operations-delete.md', 'Projects', 'Operations Delete']
- ['projects_operations-get.md', 'Projects', 'Operations Get']
- ['projects_operations-list.md', 'Projects', 'Operations List']
- ['projects_reserve-ids.md', 'Projects', 'Reserve Ids']
- ['projects_rollback.md', 'Projects', 'Rollback']
- ['projects_run-query.md', 'Projects', 'Run Query']
theme: readthedocs
copyright: Copyright &copy; 2015-2016, `Sebastian Thiel`

View File

@@ -0,0 +1,799 @@
// COPY OF 'src/rust/cli/cmn.rs'
// DO NOT EDIT
use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token};
use serde_json as json;
use serde_json::value::Value;
use mime::Mime;
use clap::{App, SubCommand};
use strsim;
use std::fs;
use std::env;
use std::io;
use std::error::Error as StdError;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
use std::io::{Write, Read, stdout};
use std::default::Default;
const FIELD_SEP: char = '.';
pub enum ComplexType {
Pod,
Vec,
Map,
}
// Null,
// Bool(bool),
// I64(i64),
// U64(u64),
// F64(f64),
// String(String),
pub enum JsonType {
Boolean,
Int,
Uint,
Float,
String,
}
pub struct JsonTypeInfo {
pub jtype: JsonType,
pub ctype: ComplexType,
}
// Based on @erickt user comment. Thanks for the idea !
// Remove all keys whose values are null from given value (changed in place)
pub fn remove_json_null_values(value: &mut Value) {
match *value {
Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}
fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> {
let mut candidate: Option<(f64, &str)> = None;
for pv in possible_values {
let confidence = strsim::jaro_winkler(v, pv);
if confidence > 0.8 &&
(candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) {
candidate = Some((confidence, pv));
}
}
match candidate {
None => None,
Some((_, candidate)) => Some(candidate),
}
}
pub enum CallType {
Upload(UploadProtocol),
Standard,
}
arg_enum!{
pub enum UploadProtocol {
Simple,
Resumable
}
}
impl AsRef<str> for UploadProtocol {
fn as_ref(&self) -> &str {
match *self {
UploadProtocol::Simple => "simple",
UploadProtocol::Resumable => "resumable",
}
}
}
impl AsRef<str> for CallType {
fn as_ref(&self) -> &str {
match *self {
CallType::Upload(ref proto) => proto.as_ref(),
CallType::Standard => "standard-request",
}
}
}
#[derive(Clone, Default)]
pub struct FieldCursor(Vec<String>);
impl ToString for FieldCursor {
fn to_string(&self) -> String {
self.0.join(".")
}
}
impl From<&'static str> for FieldCursor {
fn from(value: &'static str) -> FieldCursor {
let mut res = FieldCursor::default();
res.set(value).unwrap();
res
}
}
fn assure_entry<'a, 'b>(m: &'a mut json::Map<String, Value>, k: &'b String) -> &'a mut Value {
if m.contains_key(k) {
return m.get_mut(k).expect("value to exist");
}
m.insert(k.to_owned(), Value::Object(Default::default()));
m.get_mut(k).expect("value to exist")
}
impl FieldCursor {
pub fn set(&mut self, value: &str) -> Result<(), CLIError> {
if value.len() == 0 {
return Err(CLIError::Field(FieldError::Empty));
}
let mut first_is_field_sep = false;
let mut char_count: usize = 0;
let mut last_c = FIELD_SEP;
let mut num_conscutive_field_seps = 0;
let mut field = String::new();
let mut fields = self.0.clone();
let push_field = |fs: &mut Vec<String>, f: &mut String| {
if f.len() > 0 {
fs.push(f.clone());
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
char_count += 1;
if c == FIELD_SEP {
if cid == 0 {
first_is_field_sep = true;
}
num_conscutive_field_seps += 1;
if cid > 0 && last_c == FIELD_SEP {
if fields.pop().is_none() {
return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string())));
}
} else {
push_field(&mut fields, &mut field);
}
} else {
num_conscutive_field_seps = 0;
if cid == 1 {
if first_is_field_sep {
fields.truncate(0);
}
}
field.push(c);
}
last_c = c;
}
push_field(&mut fields, &mut field);
if char_count == 1 && first_is_field_sep {
fields.truncate(0);
}
if char_count > 1 && num_conscutive_field_seps == 1 {
return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string())));
}
self.0 = fields;
Ok(())
}
pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option<String> {
if value.len() == 0 {
return None;
}
let mut last_c = FIELD_SEP;
let mut field = String::new();
let mut output = String::new();
let push_field = |fs: &mut String, f: &mut String| {
if f.len() > 0 {
fs.push_str(match did_you_mean(&f, possible_values) {
Some(candidate) => candidate,
None => &f,
});
f.truncate(0);
}
};
for (cid, c) in value.chars().enumerate() {
if c == FIELD_SEP {
if last_c != FIELD_SEP {
push_field(&mut output, &mut field);
}
output.push(c);
} else {
field.push(c);
}
last_c = c;
}
push_field(&mut output, &mut field);
if &output == value {
None
} else {
Some(output)
}
}
pub fn set_json_value(&self,
mut object: &mut Value,
value: &str,
type_info: JsonTypeInfo,
err: &mut InvalidOptionsError,
orig_cursor: &FieldCursor) {
assert!(self.0.len() > 0);
for field in &self.0[..self.0.len() - 1] {
let tmp = object;
object = match *tmp {
Value::Object(ref mut mapping) => {
assure_entry(mapping, &field)
}
_ => panic!("We don't expect non-object Values here ..."),
};
}
match *object {
Value::Object(ref mut mapping) => {
let field = &self.0[self.0.len() - 1];
let to_jval = |value: &str,
jtype: JsonType,
err: &mut InvalidOptionsError|
-> Value {
match jtype {
JsonType::Boolean =>
Value::Bool(arg_from_str(value, err, &field, "boolean")),
JsonType::Int =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"int"))
.expect("valid f64")),
JsonType::Uint =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"uint"))
.expect("valid f64")),
JsonType::Float =>
Value::Number(json::Number::from_f64(arg_from_str(value,
err,
&field,
"float"))
.expect("valid f64")),
JsonType::String => Value::String(value.to_owned()),
}
};
match type_info.ctype {
ComplexType::Pod => {
if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err))
.is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
ComplexType::Vec => {
match *assure_entry(mapping, field) {
Value::Array(ref mut values) =>
values.push(to_jval(value, type_info.jtype, err)),
_ => unreachable!(),
}
}
ComplexType::Map => {
let (key, value) = parse_kv_arg(value, err, true);
let jval = to_jval(value.unwrap_or(""), type_info.jtype, err);
match *assure_entry(mapping, &field) {
Value::Object(ref mut value_map) => {
if value_map.insert(key.to_owned(), jval).is_some() {
err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string())));
}
}
_ => unreachable!(),
}
}
}
}
_ => unreachable!(),
}
}
pub fn num_fields(&self) -> usize {
self.0.len()
}
}
pub fn parse_kv_arg<'a>(kv: &'a str,
err: &mut InvalidOptionsError,
for_hashmap: bool)
-> (&'a str, Option<&'a str>) {
let mut add_err = || {
err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(), for_hashmap))
};
match kv.find('=') {
None => {
add_err();
return (kv, None);
}
Some(pos) => {
let key = &kv[..pos];
if kv.len() <= pos + 1 {
add_err();
return (key, Some(""));
}
(key, Some(&kv[pos + 1..]))
}
}
}
pub fn calltype_from_str(name: &str,
valid_protocols: Vec<String>,
err: &mut InvalidOptionsError)
-> CallType {
CallType::Upload(match UploadProtocol::from_str(name) {
Ok(up) => up,
Err(msg) => {
err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols));
UploadProtocol::Simple
}
})
}
pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option<fs::File> {
match fs::File::open(file_path) {
Ok(f) => Some(f),
Err(io_err) => {
err.issues.push(CLIError::Input(InputError::Io((file_path.to_string(), io_err))));
None
}
}
}
pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option<Mime> {
match mime.parse() {
Ok(m) => Some(m),
Err(_) => {
err.issues.push(CLIError::Input(InputError::Mime(mime.to_string())));
None
}
}
}
pub fn writer_from_opts(arg: Option<&str>) -> Result<Box<Write>, io::Error> {
let f = arg.unwrap_or("-");
match f {
"-" => Ok(Box::new(stdout())),
_ => match fs::OpenOptions::new().create(true).write(true).open(f) {
Ok(f) => Ok(Box::new(f)),
Err(io_err) => Err(io_err),
},
}
}
pub fn arg_from_str<'a, T>(arg: &str,
err: &mut InvalidOptionsError,
arg_name: &'a str,
arg_type: &'a str)
-> T
where T: FromStr + Default,
<T as FromStr>::Err: fmt::Display
{
match FromStr::from_str(arg) {
Err(perr) => {
err.issues.push(CLIError::ParseError(arg_name.to_owned(),
arg_type.to_owned(),
arg.to_string(),
format!("{}", perr)));
Default::default()
}
Ok(v) => v,
}
}
pub struct JsonTokenStorage {
pub program_name: &'static str,
pub db_dir: String,
}
impl JsonTokenStorage {
fn path(&self, scope_hash: u64) -> PathBuf {
Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash))
}
}
#[derive(Debug)]
pub enum TokenStorageError {
Json(json::Error),
Io(io::Error),
}
impl fmt::Display for TokenStorageError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
TokenStorageError::Json(ref err) => writeln!(f, "Could not serialize secrets: {}", err),
TokenStorageError::Io(ref err) => writeln!(f, "Failed to write secret token: {}", err),
}
}
}
impl StdError for TokenStorageError {
fn description(&self) -> &str {
"Failure when getting or setting the token storage"
}
}
impl TokenStorage for JsonTokenStorage {
type Error = TokenStorageError;
// NOTE: logging might be interesting, currently we swallow all errors
fn set(&mut self,
scope_hash: u64,
_: &Vec<&str>,
token: Option<Token>)
-> Result<(), TokenStorageError> {
match token {
None => {
match fs::remove_file(self.path(scope_hash)) {
Err(err) => match err.kind() {
io::ErrorKind::NotFound => Ok(()),
_ => Err(TokenStorageError::Io(err)),
},
Ok(_) => Ok(()),
}
}
Some(token) => {
match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) {
Ok(mut f) => {
match json::to_writer_pretty(&mut f, &token) {
Ok(_) => Ok(()),
Err(serde_err) => Err(TokenStorageError::Json(serde_err)),
}
}
Err(io_err) => Err(TokenStorageError::Io(io_err)),
}
}
}
}
fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result<Option<Token>, TokenStorageError> {
match fs::File::open(&self.path(scope_hash)) {
Ok(f) => {
match json::de::from_reader(f) {
Ok(token) => Ok(Some(token)),
Err(err) => Err(TokenStorageError::Json(err)),
}
}
Err(io_err) => {
match io_err.kind() {
io::ErrorKind::NotFound => Ok(None),
_ => Err(TokenStorageError::Io(io_err)),
}
}
}
}
}
#[derive(Debug)]
pub enum ApplicationSecretError {
DecoderError((String, json::Error)),
FormatError(String),
}
impl fmt::Display for ApplicationSecretError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ApplicationSecretError::DecoderError((ref path, ref err)) =>
writeln!(f,
"Could not decode file at '{}' with error: {}.",
path,
err),
ApplicationSecretError::FormatError(ref path) =>
writeln!(f,
"'installed' field is unset in secret file at '{}'.",
path),
}
}
}
#[derive(Debug)]
pub enum ConfigurationError {
DirectoryCreationFailed((String, io::Error)),
DirectoryUnset,
HomeExpansionFailed(String),
Secret(ApplicationSecretError),
Io((String, io::Error)),
}
impl fmt::Display for ConfigurationError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) =>
writeln!(f,
"Directory '{}' could not be created with error: {}.",
dir,
err),
ConfigurationError::DirectoryUnset => writeln!(f, "--config-dir was unset or empty."),
ConfigurationError::HomeExpansionFailed(ref dir) =>
writeln!(f,
"Couldn't find HOME directory of current user, failed to expand '{}'.",
dir),
ConfigurationError::Secret(ref err) => writeln!(f, "Secret -> {}", err),
ConfigurationError::Io((ref path, ref err)) =>
writeln!(f,
"IO operation failed on path '{}' with error: {}.",
path,
err),
}
}
}
#[derive(Debug)]
pub enum InputError {
Io((String, io::Error)),
Mime(String),
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
InputError::Io((ref file_path, ref io_err)) =>
writeln!(f,
"Failed to open '{}' for reading with error: {}.",
file_path,
io_err),
InputError::Mime(ref mime) => writeln!(f, "'{}' is not a known mime-type.", mime),
}
}
}
#[derive(Debug)]
pub enum FieldError {
PopOnEmpty(String),
TrailingFieldSep(String),
Unknown(String, Option<String>, Option<String>),
Duplicate(String),
Empty,
}
impl fmt::Display for FieldError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
FieldError::PopOnEmpty(ref field) =>
writeln!(f, "'{}': Cannot move up on empty field cursor.", field),
FieldError::TrailingFieldSep(ref field) =>
writeln!(f,
"'{}': Single field separator may not be last character.",
field),
FieldError::Unknown(ref field, ref suggestion, ref value) => {
let suffix = match *suggestion {
Some(ref s) => {
let kv = match *value {
Some(ref v) => format!("{}={}", s, v),
None => s.clone(),
};
format!(" Did you mean '{}' ?", kv)
}
None => String::new(),
};
writeln!(f, "Field '{}' does not exist.{}", field, suffix)
}
FieldError::Duplicate(ref cursor) =>
writeln!(f, "Value at '{}' was already set", cursor),
FieldError::Empty => writeln!(f, "Field names must not be empty."),
}
}
}
#[derive(Debug)]
pub enum CLIError {
Configuration(ConfigurationError),
ParseError(String, String, String, String),
UnknownParameter(String, Vec<&'static str>),
InvalidUploadProtocol(String, Vec<String>),
InvalidKeyValueSyntax(String, bool),
Input(InputError),
Field(FieldError),
MissingCommandError,
MissingMethodError(String),
}
impl fmt::Display for CLIError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err),
CLIError::Input(ref err) => write!(f, "Input -> {}", err),
CLIError::Field(ref err) => write!(f, "Field -> {}", err),
CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) =>
writeln!(f,
"'{}' is not a valid upload protocol. Choose from one of {}.",
proto_name,
valid_names.join(", ")),
CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) =>
writeln!(f,
"Failed to parse argument '{}' with value '{}' as {} with error: {}.",
arg_name,
value,
type_name,
err_desc),
CLIError::UnknownParameter(ref param_name, ref possible_values) => {
let suffix = match did_you_mean(param_name, &possible_values) {
Some(v) => format!(" Did you mean '{}' ?", v),
None => String::new(),
};
write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix)
}
CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => {
let hashmap_info = if is_hashmap {
"hashmap "
} else {
""
};
writeln!(f,
"'{}' does not match {}pattern <key>=<value>.",
kv,
hashmap_info)
}
CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."),
CLIError::MissingMethodError(ref cmd) =>
writeln!(f,
"Please specify the method to call on the '{}' command.",
cmd),
}
}
}
#[derive(Debug)]
pub struct InvalidOptionsError {
pub issues: Vec<CLIError>,
pub exit_code: i32,
}
impl fmt::Display for InvalidOptionsError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
for issue in &self.issues {
try!(issue.fmt(f));
}
Ok(())
}
}
impl InvalidOptionsError {
pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError {
InvalidOptionsError {
issues: vec![err],
exit_code: exit_code,
}
}
pub fn new() -> InvalidOptionsError {
InvalidOptionsError {
issues: Vec::new(),
exit_code: 1,
}
}
}
pub fn assure_config_dir_exists(dir: &str) -> Result<String, CLIError> {
let trdir = dir.trim();
if trdir.len() == 0 {
return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset));
}
let expanded_config_dir = if trdir.as_bytes()[0] == b'~' {
match env::var("HOME").ok().or(env::var("UserProfile").ok()) {
None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))),
Some(mut user) => {
user.push_str(&trdir[1..]);
user
}
}
} else {
trdir.to_string()
};
if let Err(err) = fs::create_dir(&expanded_config_dir) {
if err.kind() != io::ErrorKind::AlreadyExists {
return Err(CLIError::Configuration(
ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err))));
}
}
Ok(expanded_config_dir)
}
pub fn application_secret_from_directory(dir: &str,
secret_basename: &str,
json_console_secret: &str)
-> Result<ApplicationSecret, CLIError> {
let secret_path = Path::new(dir).join(secret_basename);
let secret_str = || secret_path.as_path().to_str().unwrap().to_string();
let secret_io_error = |io_err: io::Error| {
Err(CLIError::Configuration(ConfigurationError::Io((secret_str(), io_err))))
};
for _ in 0..2 {
match fs::File::open(&secret_path) {
Err(mut err) => {
if err.kind() == io::ErrorKind::NotFound {
// Write our built-in one - user may adjust the written file at will
err = match fs::OpenOptions::new()
.create(true)
.write(true)
.open(&secret_path) {
Err(cfe) => cfe,
Ok(mut f) => {
// Assure we convert 'ugly' json string into pretty one
let console_secret: ConsoleApplicationSecret =
json::from_str(json_console_secret).unwrap();
match json::to_writer_pretty(&mut f, &console_secret) {
Err(serde_err) =>
panic!("Unexpected serde error: {:#?}", serde_err),
Ok(_) => continue,
}
}
};
// fall through to IO error handling
}
return secret_io_error(err);
}
Ok(f) => {
match json::de::from_reader::<_, ConsoleApplicationSecret>(f) {
Err(json_err) =>
return Err(CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::DecoderError(
(secret_str(), json_err)
)))),
Ok(console_secret) => match console_secret.installed {
Some(secret) => return Ok(secret),
None => return Err(
CLIError::Configuration(
ConfigurationError::Secret(
ApplicationSecretError::FormatError(secret_str())
))),
},
}
}
}
}
unreachable!();
}

File diff suppressed because it is too large Load Diff

31
gen/datastore1/Cargo.toml Normal file
View File

@@ -0,0 +1,31 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-datastore1"
version = "1.0.7+20171205"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with datastore (protocol v1)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/datastore1"
homepage = "https://cloud.google.com/datastore/"
documentation = "https://docs.rs/google-datastore1/1.0.7+20171205"
license = "MIT"
keywords = ["datastore", "google", "protocol", "web", "api"]
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
url = "= 0.5"
[features]

30
gen/datastore1/LICENSE.md Normal file
View File

@@ -0,0 +1,30 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/LICENSE.md.mako'
DO NOT EDIT !
-->
The MIT License (MIT)
=====================
Copyright © `2015-2016` `Sebastian Thiel`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

175
gen/datastore1/README.md Normal file
View File

@@ -0,0 +1,175 @@
<!---
DO NOT EDIT !
This file was generated automatically from 'src/mako/api/README.md.mako'
DO NOT EDIT !
-->
The `google-datastore1` library allows access to all features of the *Google datastore* service.
This documentation was generated from *datastore* crate version *1.0.7+20171205*, where *20171205* is the exact revision of the *datastore:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.7*.
Everything else about the *datastore* *v1* API can be found at the
[official documentation site](https://cloud.google.com/datastore/).
# Features
Handle the following *Resources* with ease from the central [hub](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.Datastore.html) ...
* projects
* [*allocate ids*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.ProjectAllocateIdCall.html), [*begin transaction*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.ProjectBeginTransactionCall.html), [*commit*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.ProjectCommitCall.html), [*lookup*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.ProjectLookupCall.html), [*operations cancel*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.ProjectOperationCancelCall.html), [*operations delete*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.ProjectOperationDeleteCall.html), [*operations get*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.ProjectOperationGetCall.html), [*operations list*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.ProjectOperationListCall.html), [*reserve ids*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.ProjectReserveIdCall.html), [*rollback*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.ProjectRollbackCall.html) and [*run query*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.ProjectRunQueryCall.html)
# Structure of this Library
The API is structured into the following primary items:
* **[Hub](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/struct.Datastore.html)**
* a central object to maintain state and allow accessing all *Activities*
* creates [*Method Builders*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.MethodsBuilder.html) which in turn
allow access to individual [*Call Builders*](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.CallBuilder.html)
* **[Resources](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.Resource.html)**
* primary types that you can apply *Activities* to
* a collection of properties and *Parts*
* **[Parts](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.Part.html)**
* a collection of properties
* never directly used in *Activities*
* **[Activities](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.CallBuilder.html)**
* operations to apply to *Resources*
All *structures* are marked with applicable traits to further categorize them and ease browsing.
Generally speaking, you can invoke *Activities* like this:
```Rust,ignore
let r = hub.resource().activity(...).doit()
```
Or specifically ...
```ignore
let r = hub.projects().operations_delete(...).doit()
let r = hub.projects().operations_cancel(...).doit()
```
The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
The `doit()` method performs the actual communication with the server and returns the respective result.
# Usage
## Setting up your Project
To use this library, you would put the following lines into your `Cargo.toml` file:
```toml
[dependencies]
google-datastore1 = "*"
```
## A complete example
```Rust
extern crate hyper;
extern crate hyper_rustls;
extern crate yup_oauth2 as oauth2;
extern crate google_datastore1 as datastore1;
use datastore1::{Result, Error};
use std::default::Default;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
use datastore1::Datastore;
// Get an ApplicationSecret instance by some means. It contains the `client_id` and
// `client_secret`, among other things.
let secret: ApplicationSecret = Default::default();
// Instantiate the authenticator. It will choose a suitable authentication flow for you,
// unless you replace `None` with the desired Flow.
// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
// retrieve them from storage.
let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
<MemoryStorage as Default>::default(), None);
let mut hub = Datastore::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
// You can configure optional parameters by calling the respective setters at will, and
// execute the final call using `doit()`.
// Values shown here are possibly random and not representative !
let result = hub.projects().operations_delete("name")
.doit();
match result {
Err(e) => match e {
// The Error enum provides details about what exactly happened.
// You can also just use its `Debug`, `Display` or `Error` traits
Error::HttpError(_)
|Error::MissingAPIKey
|Error::MissingToken(_)
|Error::Cancelled
|Error::UploadSizeLimitExceeded(_, _)
|Error::Failure(_)
|Error::BadRequest(_)
|Error::FieldClash(_)
|Error::JsonDecodeError(_, _) => println!("{}", e),
},
Ok(res) => println!("Success: {:?}", res),
}
```
## Handling Errors
All errors produced by the system are provided either as [Result](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/enum.Result.html) enumeration as return value of
the doit() methods, or handed as possibly intermediate results to either the
[Hub Delegate](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.Delegate.html), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html).
When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
makes the system potentially resilient to all kinds of errors.
## Uploads and Downloads
If a method supports downloads, the response body, which is part of the [Result](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/enum.Result.html), should be
read by you to obtain the media.
If such a method also supports a [Response Result](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.ResponseResult.html), it will return that by default.
You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
this call: `.param("alt", "media")`.
Methods supporting uploads can do so using up to 2 different protocols:
*simple* and *resumable*. The distinctiveness of each is represented by customized
`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
## Customization and Callbacks
You may alter the way an `doit()` method is called by providing a [delegate](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.Delegate.html) to the
[Method Builder](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.CallBuilder.html) before making the final `doit()` call.
Respective methods will be called to provide progress information, as well as determine whether the system should
retry on failure.
The [delegate trait](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
## Optional Parts in Server-Requests
All structures provided by this library are made to be [enocodable](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.RequestValue.html) and
[decodable](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
are valid.
Most optionals are are considered [Parts](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.Part.html) which are identifiable by name, which will be sent to
the server to indicate either the set parts of the request or the desired parts in the response.
## Builder Arguments
Using [method builders](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods.
These will always take a single argument, for which the following statements are true.
* [PODs][wiki-pod] are handed by copy
* strings are passed as `&str`
* [request values](https://docs.rs/google-datastore1/1.0.7+20171205/google_datastore1/trait.RequestValue.html) are moved
Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
[google-go-api]: https://github.com/google/google-api-go-client
# License
The **datastore1** library was generated by Sebastian Thiel, and is placed
under the *MIT* license.
You can read the full text at the repository's [license file][repo-license].
[repo-license]: https://github.com/Byron/google-apis-rsblob/master/LICENSE.md

753
gen/datastore1/src/cmn.rs Normal file
View File

@@ -0,0 +1,753 @@
// COPY OF 'src/rust/api/cmn.rs'
// DO NOT EDIT
use std::io::{self, Read, Seek, Cursor, Write, SeekFrom};
use std;
use std::fmt::{self, Display};
use std::str::FromStr;
use std::error;
use std::thread::sleep;
use std::time::Duration;
use mime::{Mime, TopLevel, SubLevel, Attr, Value};
use oauth2::{TokenType, Retry, self};
use hyper;
use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header,
HeaderFormat, Bearer};
use hyper::http::h1::LINE_ENDING;
use hyper::method::Method;
use hyper::status::StatusCode;
use serde_json as json;
/// Identifies the Hub. There is only one per library, this trait is supposed
/// to make intended use more explicit.
/// The hub allows to access all resource methods more easily.
pub trait Hub {}
/// Identifies types for building methods of a particular resource type
pub trait MethodsBuilder {}
/// Identifies types which represent builders for a particular resource method
pub trait CallBuilder {}
/// Identifies types which can be inserted and deleted.
/// Types with this trait are most commonly used by clients of this API.
pub trait Resource {}
/// Identifies types which are used in API responses.
pub trait ResponseResult {}
/// Identifies types which are used in API requests.
pub trait RequestValue {}
/// Identifies types which are not actually used by the API
/// This might be a bug within the google API schema.
pub trait UnusedType {}
/// Identifies types which are only used as part of other types, which
/// usually are carrying the `Resource` trait.
pub trait Part {}
/// Identifies types which are only used by other types internally.
/// They have no special meaning, this trait just marks them for completeness.
pub trait NestedType {}
/// A utility to specify reader types which provide seeking capabilities too
pub trait ReadSeek: Seek + Read {}
impl<T: Seek + Read> ReadSeek for T {}
/// A trait for all types that can convert themselves into a *parts* string
pub trait ToParts {
fn to_parts(&self) -> String;
}
/// A utility type which can decode a server response that indicates error
#[derive(Deserialize)]
pub struct JsonServerError {
pub error: String,
pub error_description: Option<String>
}
/// A utility to represent detailed errors we might see in case there are BadRequests.
/// The latter happen if the sent parameters or request structures are unsound
#[derive(Deserialize, Serialize, Debug)]
pub struct ErrorResponse {
error: ServerError,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerError {
errors: Vec<ServerMessage>,
code: u16,
message: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct ServerMessage {
domain: String,
reason: String,
message: String,
#[serde(rename="locationType")]
location_type: Option<String>,
location: Option<String>
}
#[derive(Copy, Clone)]
pub struct DummyNetworkStream;
impl Read for DummyNetworkStream {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl Write for DummyNetworkStream {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl hyper::net::NetworkStream for DummyNetworkStream {
fn peer_addr(&mut self) -> io::Result<std::net::SocketAddr> {
Ok("127.0.0.1:1337".parse().unwrap())
}
fn set_read_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
fn set_write_timeout(&self, _dur: Option<Duration>) -> io::Result<()> {
Ok(())
}
}
/// A trait specifying functionality to help controlling any request performed by the API.
/// The trait has a conservative default implementation.
///
/// It contains methods to deal with all common issues, as well with the ones related to
/// uploading media
pub trait Delegate {
/// Called at the beginning of any API request. The delegate should store the method
/// information if he is interesting in knowing more context when further calls to it
/// are made.
/// The matching `finished()` call will always be made, no matter whether or not the API
/// request was successful. That way, the delegate may easily maintain a clean state
/// between various API calls.
fn begin(&mut self, MethodInfo) {}
/// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
///
/// Return retry information.
fn http_error(&mut self, &hyper::Error) -> Retry {
Retry::Abort
}
/// Called whenever there is the need for your applications API key after
/// the official authenticator implementation didn't provide one, for some reason.
/// If this method returns None as well, the underlying operation will fail
fn api_key(&mut self) -> Option<String> {
None
}
/// Called whenever the Authenticator didn't yield a token. The delegate
/// may attempt to provide one, or just take it as a general information about the
/// impending failure.
/// The given Error provides information about why the token couldn't be acquired in the
/// first place
fn token(&mut self, err: &error::Error) -> Option<oauth2::Token> {
let _ = err;
None
}
/// Called during resumable uploads to provide a URL for the impending upload.
/// It was saved after a previous call to `store_upload_url(...)`, and if not None,
/// will be used instead of asking the server for a new upload URL.
/// This is useful in case a previous resumable upload was aborted/canceled, but should now
/// be resumed.
/// The returned URL will be used exactly once - if it fails again and the delegate allows
/// to retry, we will ask the server for a new upload URL.
fn upload_url(&mut self) -> Option<String> {
None
}
/// Called after we have retrieved a new upload URL for a resumable upload to store it
/// in case we fail or cancel. That way, we can attempt to resume the upload later,
/// see `upload_url()`.
/// It will also be called with None after a successful upload, which allows the delegate
/// to forget the URL. That way, we will not attempt to resume an upload that has already
/// finished.
fn store_upload_url(&mut self, url: Option<&str>) {
let _ = url;
}
/// Called whenever a server response could not be decoded from json.
/// It's for informational purposes only, the caller will return with an error
/// accordingly.
///
/// # Arguments
///
/// * `json_encoded_value` - The json-encoded value which failed to decode.
/// * `json_decode_error` - The decoder error
fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &json::Error) {
let _ = json_encoded_value;
let _ = json_decode_error;
}
/// Called whenever the http request returns with a non-success status code.
/// This can involve authentication issues, or anything else that very much
/// depends on the used API method.
/// The delegate should check the status, header and decoded json error to decide
/// whether to retry or not. In the latter case, the underlying call will fail.
///
/// If you choose to retry after a duration, the duration should be chosen using the
/// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff).
fn http_failure(&mut self, _: &hyper::client::Response, Option<JsonServerError>, _: Option<ServerError>) -> Retry {
Retry::Abort
}
/// Called prior to sending the main request of the given method. It can be used to time
/// the call or to print progress information.
/// It's also useful as you can be sure that a request will definitely be made.
fn pre_request(&mut self) { }
/// Return the size of each chunk of a resumable upload.
/// Must be a power of two, with 1<<18 being the smallest allowed chunk size.
/// Will be called once before starting any resumable upload.
fn chunk_size(&mut self) -> u64 {
1 << 23
}
/// Called before the given chunk is uploaded to the server.
/// If true is returned, the upload will be interrupted.
/// However, it may be resumable if you stored the upload URL in a previous call
/// to `store_upload_url()`
fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool {
let _ = chunk;
false
}
/// Called before the API request method returns, in every case. It can be used to clean up
/// internal state between calls to the API.
/// This call always has a matching call to `begin(...)`.
///
/// # Arguments
///
/// * `is_success` - a true value indicates the operation was successful. If false, you should
/// discard all values stored during `store_upload_url`.
fn finished(&mut self, is_success: bool) {
let _ = is_success;
}
}
/// A delegate with a conservative default implementation, which is used if no other delegate is
/// set.
#[derive(Default)]
pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}
#[derive(Debug)]
pub enum Error {
/// The http connection failed
HttpError(hyper::Error),
/// An attempt was made to upload a resource with size stored in field `.0`
/// even though the maximum upload size is what is stored in field `.1`.
UploadSizeLimitExceeded(u64, u64),
/// Represents information about a request that was not understood by the server.
/// Details are included.
BadRequest(ErrorResponse),
/// We needed an API key for authentication, but didn't obtain one.
/// Neither through the authenticator, nor through the Delegate.
MissingAPIKey,
/// We required a Token, but didn't get one from the Authenticator
MissingToken(Box<error::Error>),
/// The delgate instructed to cancel the operation
Cancelled,
/// An additional, free form field clashed with one of the built-in optional ones
FieldClash(&'static str),
/// Shows that we failed to decode the server response.
/// This can happen if the protocol changes in conjunction with strict json decoding.
JsonDecodeError(String, json::Error),
/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::HttpError(ref err) => err.fmt(f),
Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) =>
writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}"
, resource_size, max_size),
Error::MissingAPIKey => {
(writeln!(f, "The application's API key was not found in the configuration")).ok();
writeln!(f, "It is used as there are no Scopes defined for this method.")
},
Error::BadRequest(ref err) => {
try!(writeln!(f, "Bad Request ({}): {}", err.error.code, err.error.message));
for err in err.error.errors.iter() {
try!(writeln!(f, " {}: {}, {}{}",
err.domain,
err.message,
err.reason,
match &err.location {
&Some(ref loc) => format!("@{}", loc),
&None => String::new(),
}));
}
Ok(())
},
Error::MissingToken(ref err) =>
writeln!(f, "Token retrieval failed with error: {}", err),
Error::Cancelled =>
writeln!(f, "Operation cancelled by delegate"),
Error::FieldClash(field) =>
writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field),
Error::JsonDecodeError(ref json_str, ref err)
=> writeln!(f, "{}: {}", err, json_str),
Error::Failure(ref response) =>
writeln!(f, "Http status indicates failure: {:?}", response),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::HttpError(ref err) => err.description(),
Error::JsonDecodeError(_, ref err) => err.description(),
_ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead"
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::HttpError(ref err) => err.cause(),
Error::JsonDecodeError(_, ref err) => err.cause(),
_ => None
}
}
}
/// A universal result type used as return for all calls.
pub type Result<T> = std::result::Result<T, Error>;
/// Contains information about an API request.
pub struct MethodInfo {
pub id: &'static str,
pub http_method: Method,
}
const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d";
/// Provides a `Read` interface that converts multiple parts into the protocol
/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387).
/// **Note**: This implementation is just as rich as it needs to be to perform uploads
/// to google APIs, and might not be a fully-featured implementation.
#[derive(Default)]
pub struct MultiPartReader<'a> {
raw_parts: Vec<(Headers, &'a mut Read)>,
current_part: Option<(Cursor<Vec<u8>>, &'a mut Read)>,
last_part_boundary: Option<Cursor<Vec<u8>>>,
}
impl<'a> MultiPartReader<'a> {
/// Reserve memory for exactly the given amount of parts
pub fn reserve_exact(&mut self, cap: usize) {
self.raw_parts.reserve_exact(cap);
}
/// Add a new part to the queue of parts to be read on the first `read` call.
///
/// # Arguments
///
/// `headers` - identifying the body of the part. It's similar to the header
/// in an ordinary single-part call, and should thus contain the
/// same information.
/// `reader` - a reader providing the part's body
/// `size` - the amount of bytes provided by the reader. It will be put onto the header as
/// content-size.
/// `mime` - It will be put onto the content type
pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> {
let mut headers = Headers::new();
headers.set(ContentType(mime_type));
headers.set(ContentLength(size));
self.raw_parts.push((headers, reader));
self
}
/// Returns the mime-type representing our multi-part message.
/// Use it with the ContentType header.
pub fn mime_type(&self) -> Mime {
Mime(
TopLevel::Multipart,
SubLevel::Ext("Related".to_string()),
vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))],
)
}
/// Returns true if we are totally used
fn is_depleted(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none()
}
/// Returns true if we are handling our last part
fn is_last_part(&self) -> bool {
self.raw_parts.len() == 0 && self.current_part.is_some()
}
}
impl<'a> Read for MultiPartReader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.raw_parts.len(),
self.current_part.is_none(),
self.last_part_boundary.is_none()) {
(_, _, false) => {
let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0);
if br < buf.len() {
self.last_part_boundary = None;
}
return Ok(br)
},
(0, true, true) => return Ok(0),
(n, true, _) if n > 0 => {
let (headers, reader) = self.raw_parts.remove(0);
let mut c = Cursor::new(Vec::<u8>::new());
(write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING,
headers, LINE_ENDING)).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
self.current_part = Some((c, reader));
}
_ => {},
}
// read headers as long as possible
let (hb, rr) = {
let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap();
let b = c.read(buf).unwrap_or(0);
(b, reader.read(&mut buf[b..]))
};
match rr {
Ok(bytes_read) => {
if hb < buf.len() && bytes_read == 0 {
if self.is_last_part() {
// before clearing the last part, we will add the boundary that
// will be written last
self.last_part_boundary = Some(Cursor::new(
format!("{}--{}--", LINE_ENDING, BOUNDARY).into_bytes()))
}
// We are depleted - this can trigger the next part to come in
self.current_part = None;
}
let mut total_bytes_read = hb + bytes_read;
while total_bytes_read < buf.len() && !self.is_depleted() {
match self.read(&mut buf[total_bytes_read ..]) {
Ok(br) => total_bytes_read += br,
Err(err) => return Err(err),
}
}
Ok(total_bytes_read)
}
Err(err) => {
// fail permanently
self.current_part = None;
self.last_part_boundary = None;
self.raw_parts.clear();
Err(err)
}
}
}
}
/// The `X-Upload-Content-Type` header.
///
/// Generated via rustc --pretty expanded -Z unstable-options, and manually
/// processed to be more readable.
#[derive(PartialEq, Debug, Clone)]
pub struct XUploadContentType(pub Mime);
impl ::std::ops::Deref for XUploadContentType {
type Target = Mime;
fn deref<'a>(&'a self) -> &'a Mime { &self.0 }
}
impl ::std::ops::DerefMut for XUploadContentType {
fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 }
}
impl Header for XUploadContentType {
fn header_name() -> &'static str { "X-Upload-Content-Type" }
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType)
}
}
impl HeaderFormat for XUploadContentType {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&**self, f)
}
}
impl Display for XUploadContentType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Chunk {
pub first: u64,
pub last: u64
}
impl fmt::Display for Chunk {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(write!(fmt, "{}-{}", self.first, self.last)).ok();
Ok(())
}
}
impl FromStr for Chunk {
type Err = &'static str;
/// NOTE: only implements `%i-%i`, not `*`
fn from_str(s: &str) -> std::result::Result<Chunk, &'static str> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 2 {
return Err("Expected two parts: %i-%i")
}
Ok(
Chunk {
first: match FromStr::from_str(parts[0]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'first' as digit")
},
last: match FromStr::from_str(parts[1]) {
Ok(d) => d,
_ => return Err("Couldn't parse 'last' as digit")
}
}
)
}
}
/// Implements the Content-Range header, for serialization only
#[derive(Clone, PartialEq, Debug)]
pub struct ContentRange {
pub range: Option<Chunk>,
pub total_length: u64,
}
impl Header for ContentRange {
fn header_name() -> &'static str {
"Content-Range"
}
/// We are not parsable, as parsing is done by the `Range` header
fn parse_header(_: &[Vec<u8>]) -> hyper::error::Result<Self> {
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for ContentRange {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("bytes "));
match self.range {
Some(ref c) => try!(c.fmt(fmt)),
None => try!(fmt.write_str("*"))
}
(write!(fmt, "/{}", self.total_length)).ok();
Ok(())
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct RangeResponseHeader(pub Chunk);
impl Header for RangeResponseHeader {
fn header_name() -> &'static str {
"Range"
}
fn parse_header(raw: &[Vec<u8>]) -> hyper::error::Result<Self> {
if raw.len() > 0 {
let v = &raw[0];
if let Ok(s) = std::str::from_utf8(v) {
const PREFIX: &'static str = "bytes ";
if s.starts_with(PREFIX) {
if let Ok(c) = <Chunk as FromStr>::from_str(&s[PREFIX.len()..]) {
return Ok(RangeResponseHeader(c))
}
}
}
}
Err(hyper::error::Error::Method)
}
}
impl HeaderFormat for RangeResponseHeader {
/// No implmentation necessary, we just need to parse
fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
/// A utility type to perform a resumable upload from start to end.
pub struct ResumableUploadHelper<'a, A: 'a> {
pub client: &'a mut hyper::client::Client,
pub delegate: &'a mut Delegate,
pub start_at: Option<u64>,
pub auth: &'a mut A,
pub user_agent: &'a str,
pub auth_header: Authorization<Bearer>,
pub url: &'a str,
pub reader: &'a mut ReadSeek,
pub media_type: Mime,
pub content_length: u64
}
impl<'a, A> ResumableUploadHelper<'a, A>
where A: oauth2::GetToken {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::Result<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
.header(ContentRange { range: None, total_length: self.content_length })
.header(self.auth_header.clone())
.send() {
Ok(r) => {
// 308 = resume-incomplete == PermanentRedirect
let headers = r.headers.clone();
let h: &RangeResponseHeader = match headers.get() {
Some(hh) if r.status == StatusCode::PermanentRedirect => hh,
None|Some(_) => {
if let Retry::After(d) = self.delegate.http_failure(&r, None, None) {
sleep(d);
continue;
}
return Err(Ok(r))
}
};
return Ok(h.0.last)
}
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Err(Err(err))
}
}
}
}
/// returns None if operation was cancelled by delegate, or the HttpResult.
/// It can be that we return the result just because we didn't understand the status code -
/// caller should check for status himself before assuming it's OK to use
pub fn upload(&mut self) -> Option<hyper::Result<hyper::client::Response>> {
let mut start = match self.start_at {
Some(s) => s,
None => match self.query_transfer_status() {
Ok(s) => s,
Err(result) => return Some(result)
}
};
const MIN_CHUNK_SIZE: u64 = 1 << 18;
let chunk_size = match self.delegate.chunk_size() {
cs if cs > MIN_CHUNK_SIZE => cs,
_ => MIN_CHUNK_SIZE
};
self.reader.seek(SeekFrom::Start(start)).unwrap();
loop {
let request_size = match self.content_length - start {
rs if rs > chunk_size => chunk_size,
rs => rs
};
let mut section_reader = self.reader.take(request_size);
let range_header = ContentRange {
range: Some(Chunk {first: start, last: start + request_size - 1}),
total_length: self.content_length
};
start += request_size;
if self.delegate.cancel_chunk_upload(&range_header) {
return None
}
let res = self.client.post(self.url)
.header(range_header)
.header(ContentType(self.media_type.clone()))
.header(UserAgent(self.user_agent.to_string()))
.body(&mut section_reader)
.send();
match res {
Ok(mut res) => {
if res.status == StatusCode::PermanentRedirect {
continue
}
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let Retry::After(d) = self.delegate.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
}
return Some(Ok(res))
},
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return Some(Err(err))
}
}
}
}
}
// Copy of src/rust/cli/cmn.rs
// TODO(ST): Allow sharing common code between program types
pub fn remove_json_null_values(value: &mut json::value::Value) {
match *value {
json::value::Value::Object(ref mut map) => {
let mut for_removal = Vec::new();
for (key, mut value) in map.iter_mut() {
if value.is_null() {
for_removal.push(key.clone());
} else {
remove_json_null_values(&mut value);
}
}
for key in &for_removal {
map.remove(key);
}
}
_ => {}
}
}

4745
gen/datastore1/src/lib.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
# DO NOT EDIT !
# This file was generated automatically from 'src/mako/Cargo.toml.mako'
# DO NOT EDIT !
[package]
name = "google-datastore1_beta3-cli"
version = "1.0.7+20171205"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
description = "A complete library to interact with datastore (protocol v1beta3)"
repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/datastore1_beta3-cli"
homepage = "https://cloud.google.com/datastore/"
documentation = "http://byron.github.io/google-apis-rs/google_datastore1_beta3_cli"
license = "MIT"
keywords = ["datastore", "google", "cli"]
[[bin]]
name = "datastore1-beta3"
[dev-dependencies]
hyper-rustls = "^0.6"
[dependencies]
hyper = "^ 0.10"
mime = "^ 0.2.0"
serde = "^ 1.0"
serde_json = "^ 1.0"
serde_derive = "^ 1.0"
yup-oauth2 = "^ 1.0"
strsim = "^0.5"
hyper-rustls = "^0.6"
yup-hyper-mock = "^2.0"
clap = "^2.0"
[features]
[dependencies.google-datastore1_beta3]
path = "../datastore1_beta3"
version = "1.0.7+20171205"

Some files were not shown because too many files have changed in this diff Show More