Skip to content

Commit

Permalink
Check formatting in CI (typedb#26)
Browse files Browse the repository at this point in the history
## What is the goal of this PR?

We add a check to the Factory CI configuration that ensures that all
Rust code has been formatted properly.

## What are the changes implemented in this PR?

We add rustfmt configuration, reformat the project, and ensure that
rustfmt had been run in CI.

Closes typedb#10.
  • Loading branch information
dmitrii-ubskii authored Nov 29, 2022
1 parent ca26db6 commit 11dbed3
Show file tree
Hide file tree
Showing 18 changed files with 925 additions and 455 deletions.
1 change: 1 addition & 0 deletions .factory/automation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ build:
bazel build //...
bazel run @vaticle_dependencies//tool/checkstyle:test-coverage
bazel test $(bazel query 'kind(checkstyle_test, //...)') --test_output=errors
bazel test $(bazel query 'kind(rustfmt_test, //...)') --@rules_rust//:rustfmt.toml=//:rustfmt_config
deploy-crate-snapshot:
filter:
owner: vaticle
Expand Down
9 changes: 8 additions & 1 deletion BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

package(default_visibility = ["//visibility:public"])

load("@rules_rust//rust:defs.bzl", "rust_library")
load("@rules_rust//rust:defs.bzl", "rust_library", "rustfmt_test")
load("@vaticle_bazel_distribution//crates:rules.bzl", "assemble_crate", "deploy_crate")
load("@vaticle_bazel_distribution//github:rules.bzl", "deploy_github")
load("@vaticle_dependencies//distribution:deployment.bzl", "deployment")
Expand All @@ -48,6 +48,13 @@ rust_library(
],
)

filegroup(
name = "rustfmt_config",
srcs = ["rustfmt.toml"],
)

rustfmt_test(name = "client_rustfmt_test", targets = ["typedb_client"])

assemble_crate(
name = "assemble_crate",
target = "typedb_client",
Expand Down
24 changes: 24 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#
# Copyright (C) 2022 Vaticle
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#

imports_granularity = "Crate"
use_small_heuristics = "Max"
15 changes: 9 additions & 6 deletions src/answer/concept_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@
* under the License.
*/

use std::collections::{hash_map, HashMap};
use std::ops::Index;
use crate::common::Result;
use crate::concept::Concept;
use crate::{common::Result, concept::Concept};
use std::{
collections::{hash_map, HashMap},
ops::Index,
};

#[derive(Debug)]
pub struct ConceptMap {
pub map: HashMap<String, Concept>
pub map: HashMap<String, Concept>,
}

impl ConceptMap {
Expand Down Expand Up @@ -54,7 +55,9 @@ impl ConceptMap {
impl Clone for ConceptMap {
fn clone(&self) -> Self {
let mut map = HashMap::with_capacity(self.map.len());
for (k, v) in &self.map { map.insert(k.clone(), v.clone()); }
for (k, v) in &self.map {
map.insert(k.clone(), v.clone());
}
Self { map }
}
}
Expand Down
20 changes: 14 additions & 6 deletions src/answer/numeric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
* under the License.
*/

use typedb_protocol::numeric::Value;
use crate::common::Error;
use typedb_protocol::numeric::Value;

#[derive(Clone, Debug)]
pub enum Numeric {
Expand All @@ -31,11 +31,19 @@ pub enum Numeric {

impl Numeric {
pub fn into_i64(self) -> i64 {
if let Self::Long(value) = self { value } else { panic!() }
if let Self::Long(value) = self {
value
} else {
panic!()
}
}

pub fn into_f64(self) -> f64 {
if let Self::Double(value) = self { value } else { panic!() }
if let Self::Double(value) = self {
value
} else {
panic!()
}
}
}

Expand All @@ -44,9 +52,9 @@ impl TryFrom<typedb_protocol::Numeric> for Numeric {

fn try_from(value: typedb_protocol::Numeric) -> std::result::Result<Self, Self::Error> {
match value.value.unwrap() {
Value::LongValue(long) => { Ok(Numeric::Long(long)) }
Value::DoubleValue(double) => { Ok(Numeric::Double(double)) }
Value::Nan(_) => { Ok(Numeric::NaN) }
Value::LongValue(long) => Ok(Numeric::Long(long)),
Value::DoubleValue(double) => Ok(Numeric::Double(double)),
Value::Nan(_) => Ok(Numeric::NaN),
}
}
}
Expand Down
48 changes: 31 additions & 17 deletions src/common/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@
*/

// use grpc::{Error as GrpcError, GrpcMessageError, GrpcStatus};
use std::error::Error as StdError;
use std::fmt::{Debug, Display, Formatter};
use std::{
error::Error as StdError,
fmt::{Debug, Display, Formatter},
};
use tonic::Status;

// TODO: try refactoring out the lifetime by storing String instead of &str
Expand All @@ -32,10 +34,7 @@ struct MessageTemplate<'a> {

impl MessageTemplate<'_> {
const fn new<'a>(code_prefix: &'a str, msg_prefix: &'a str) -> MessageTemplate<'a> {
MessageTemplate {
code_prefix,
msg_prefix
}
MessageTemplate { code_prefix, msg_prefix }
}
}

Expand All @@ -44,27 +43,40 @@ pub struct Message<'a> {
code_prefix: &'a str,
code_number: u8,
msg_prefix: &'a str,
msg_body: &'a str
msg_body: &'a str,
}

impl Message<'_> {
const fn new<'a>(template: MessageTemplate<'a>, code_number: u8, msg_body: &'a str) -> Message<'a> {
const fn new<'a>(
template: MessageTemplate<'a>,
code_number: u8,
msg_body: &'a str,
) -> Message<'a> {
Message {
code_prefix: template.code_prefix,
code_number,
msg_prefix: template.msg_prefix,
msg_body
msg_body,
}
}

fn format(&self, args: Vec<&str>) -> String {
let expected_arg_count = self.msg_body.matches("{}").count();
assert_eq!(
expected_arg_count, args.len(),
expected_arg_count,
args.len(),
"Message template `{}` takes `{}` args but `{}` were provided",
self.msg_body, expected_arg_count, args.len()
self.msg_body,
expected_arg_count,
args.len()
);
format!("[{}{:0>2}] {}: {}", self.code_prefix, self.code_number, self.msg_prefix, self.expand_msg(args))
format!(
"[{}{:0>2}] {}: {}",
self.code_prefix,
self.code_number,
self.msg_prefix,
self.expand_msg(args)
)
}

pub(crate) fn to_err(&self, args: Vec<&str>) -> Error {
Expand All @@ -77,7 +89,9 @@ impl Message<'_> {
let mut formatted_msg = String::new();
for (idx, fragment) in msg_split_indexed {
formatted_msg.push_str(fragment);
if idx < arg_count { formatted_msg.push_str(args[idx]) }
if idx < arg_count {
formatted_msg.push_str(args[idx])
}
}
formatted_msg
}
Expand All @@ -92,14 +106,14 @@ impl From<Message<'_>> for String {

struct MessageTemplates<'a> {
client: MessageTemplate<'a>,
concept: MessageTemplate<'a>
concept: MessageTemplate<'a>,
}

impl MessageTemplates<'_> {
const fn new() -> MessageTemplates<'static> {
MessageTemplates {
client: MessageTemplate::new("CLI", "Client Error"),
concept: MessageTemplate::new("CON", "Concept Error")
concept: MessageTemplate::new("CON", "Concept Error"),
}
}
}
Expand Down Expand Up @@ -192,7 +206,7 @@ impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let message = match self {
// Error::GrpcError(msg, _) => msg,
Error::Other(msg) => msg
Error::Other(msg) => msg,
};
write!(f, "{}", message)
}
Expand All @@ -202,7 +216,7 @@ impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
// Error::GrpcError(_, source) => Some(source),
Error::Other(_) => None
Error::Other(_) => None,
}
}
}
Expand Down
Loading

0 comments on commit 11dbed3

Please sign in to comment.