Skip to content

Commit

Permalink
fix(result): remove custom Result Enum
Browse files Browse the repository at this point in the history
Instead, we just use a customized `Result` tyoe and thus stick to
common Rust conventions.

Fixes #39
  • Loading branch information
Byron committed Mar 23, 2015
1 parent fca1b24 commit e5b013e
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 35 deletions.
2 changes: 1 addition & 1 deletion src/mako/lib.rs.mako
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ use std::io;
use std::fs;
use std::thread::sleep;

pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, Resource, JsonServerError};
pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, Resource, JsonServerError};


// ##############
Expand Down
46 changes: 24 additions & 22 deletions src/mako/lib/mbuild.mako
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ ${m.description | rust_doc_comment}
% else:
/// A builder for the *${method}* method supported by a *${singular(resource)}* resource.
% endif
/// It is not used directly, but through a `${rb_type(resource)}`.
/// It is not used directly, but through a `${rb_type(resource)}` instance.
///
% if part_desc:
${part_desc | rust_doc_comment}
Expand Down Expand Up @@ -307,7 +307,7 @@ ${capture(util.test_prelude) | hide_filter}\
use ${util.library_name()}::${request_value_type};
% endif
% if handle_result:
use ${util.library_name()}::Result;
use ${util.library_name()}::{Result, Error};
% endif
% if media_params:
use std::fs;
Expand Down Expand Up @@ -358,15 +358,17 @@ ${'.' + action_name | indent_by(13)}(${action_args});
% if handle_result:
match result {
Result::HttpError(err) => println!("HTTPERROR: {:?}", err),
Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"),
Result::MissingToken => println!("OAuth2: Missing Token"),
Result::Cancelled => println!("Operation canceled by user"),
Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size),
Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"),
Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field),
Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err),
Result::Success(_) => println!("Success (value doesn't print)"),
Err(e) => match e {
Error::HttpError(err) => println!("HTTPERROR: {:?}", err),
Error::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"),
Error::MissingToken => println!("OAuth2: Missing Token"),
Error::Cancelled => println!("Operation canceled by user"),
Error::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size),
Error::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"),
Error::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field),
Error::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err),
},
Ok(_) => println!("Success (value doesn't print)"),
}
% endif
</%block>
Expand Down Expand Up @@ -447,7 +449,7 @@ match result {
if media_params:
max_size = media_params[0].max_size
if max_size > 0:
READER_SEEK += "if size > %i {\n\treturn Result::UploadSizeLimitExceeded(size, %i)\n}" % (max_size, max_size)
READER_SEEK += "if size > %i {\n\treturn Err(Error::UploadSizeLimitExceeded(size, %i))\n}" % (max_size, max_size)
special_cases = set()
for possible_url in possible_urls:
Expand Down Expand Up @@ -527,7 +529,7 @@ match result {
for &field in [${', '.join(enclose_in('"', reserved_params + [p.name for p in field_params]))}].iter() {
if ${paddfields}.contains_key(field) {
${delegate_finish}(false);
return Result::FieldClash(field);
return Err(Error::FieldClash(field));
}
}
for (name, value) in ${paddfields}.iter() {
Expand Down Expand Up @@ -589,7 +591,7 @@ else {
Some(value) => params.push(("key", value)),
None => {
${delegate_finish}(false);
return Result::MissingAPIKey
return Err(Error::MissingAPIKey)
}
}
% else:
Expand Down Expand Up @@ -668,7 +670,7 @@ else {
}
if token.is_none() {
${delegate_finish}(false);
return Result::MissingToken
return Err(Error::MissingToken)
}
let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer,
access_token: token.unwrap().access_token });
Expand Down Expand Up @@ -757,7 +759,7 @@ else {
continue;
}
${delegate_finish}(false);
return Result::HttpError(err)
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
Expand All @@ -768,7 +770,7 @@ else {
continue;
}
${delegate_finish}(false);
return Result::Failure(res)
return Err(Error::Failure(res))
}
% if resumable_media_param:
if protocol == "${resumable_media_param.protocol}" {
Expand Down Expand Up @@ -796,12 +798,12 @@ else {
match upload_result {
None => {
${delegate_finish}(false);
return Result::Cancelled
return Err(Error::Cancelled)
}
Some(Err(err)) => {
## Do not ask the delgate again, as it was asked by the helper !
${delegate_finish}(false);
return Result::HttpError(err)
return Err(Error::HttpError(err))
}
## Now the result contains the actual resource, if any ... it will be
## decoded next
Expand All @@ -810,7 +812,7 @@ else {
if !res.status.is_success() {
## delegate was called in upload() already - don't tell him again
${delegate_finish}(false);
return Result::Failure(res)
return Err(Error::Failure(res))
}
}
}
Expand All @@ -829,7 +831,7 @@ if enable_resource_parsing \
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Result::JsonDecodeError(err);
return Err(Error::JsonDecodeError(err));
}
}
}\
Expand All @@ -842,7 +844,7 @@ if enable_resource_parsing \
% endif
${delegate_finish}(true);
return Result::Success(result_value)
return Ok(result_value)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/mako/lib/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
TO_PARTS_MARKER = 'ToParts'
UNUSED_TYPE_MARKER = 'UnusedType'

RESERVED_TYPES = set(("Result", RESOURCE_MARKER_TRAIT))
RESERVED_TYPES = set(("Result", RESOURCE_MARKER_TRAIT, "Error"))

PROTOCOL_TYPE_INFO = {
'simple' : {
Expand Down
22 changes: 11 additions & 11 deletions src/rust/cmn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,8 @@ pub struct DefaultDelegate;
impl Delegate for DefaultDelegate {}


/// A universal result type used as return for all action method results.
pub enum Result<T = ()> {

pub enum Error {
/// The http connection failed
HttpError(hyper::HttpError),

Expand All @@ -244,11 +244,11 @@ pub enum Result<T = ()> {

/// Indicates an HTTP repsonse with a non-success status code
Failure(hyper::client::Response),

/// It worked !
Success(T),
}

/// 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,
Expand Down Expand Up @@ -503,7 +503,7 @@ impl<'a, NC, A> ResumableUploadHelper<'a, NC, A>
where NC: hyper::net::NetworkConnector,
A: oauth2::GetToken {

fn query_transfer_status(&mut self) -> (Option<u64>, hyper::HttpResult<hyper::client::Response>) {
fn query_transfer_status(&mut self) -> std::result::Result<u64, hyper::HttpResult<hyper::client::Response>> {
loop {
match self.client.post(self.url)
.header(UserAgent(self.user_agent.to_string()))
Expand All @@ -520,17 +520,17 @@ impl<'a, NC, A> ResumableUploadHelper<'a, NC, A>
sleep(d);
continue;
}
return (None, Ok(r))
return Err(Ok(r))
}
};
return (Some(h.0.last), Ok(r))
return Ok(h.0.last)
}
Err(err) => {
if let Retry::After(d) = self.delegate.http_error(&err) {
sleep(d);
continue;
}
return (None, Err(err))
return Err(Err(err))
}
}
}
Expand All @@ -543,8 +543,8 @@ impl<'a, NC, A> ResumableUploadHelper<'a, NC, A>
let mut start = match self.start_at {
Some(s) => s,
None => match self.query_transfer_status() {
(Some(s), _) => s,
(_, result) => return Some(result)
Ok(s) => s,
Err(result) => return Some(result)
}
};

Expand Down

0 comments on commit e5b013e

Please sign in to comment.