From e4b09c0c0fa76b7767e0890635a145b65a22e2d3 Mon Sep 17 00:00:00 2001 From: Edouard Oger Date: Tue, 11 Dec 2018 13:27:40 -0500 Subject: [PATCH 1/9] Convert sync15-adapter to Rust 2018 --- sync15-adapter/Cargo.toml | 1 + sync15-adapter/src/bso_record.rs | 12 +++++--- sync15-adapter/src/changeset.rs | 14 ++++----- sync15-adapter/src/client.rs | 27 ++++++++-------- sync15-adapter/src/collection_keys.rs | 11 ++++--- sync15-adapter/src/error.rs | 5 --- sync15-adapter/src/key_bundle.rs | 6 ++-- sync15-adapter/src/lib.rs | 44 ++++++--------------------- sync15-adapter/src/record_types.rs | 1 + sync15-adapter/src/request.rs | 13 ++++---- sync15-adapter/src/state.rs | 21 +++++++------ sync15-adapter/src/sync.rs | 14 ++++----- sync15-adapter/src/sync_multiple.rs | 12 ++++---- sync15-adapter/src/token.rs | 8 ++--- sync15-adapter/src/util.rs | 3 +- 15 files changed, 83 insertions(+), 109 deletions(-) diff --git a/sync15-adapter/Cargo.toml b/sync15-adapter/Cargo.toml index 3035736963..8e456fc76e 100644 --- a/sync15-adapter/Cargo.toml +++ b/sync15-adapter/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "sync15-adapter" +edition = "2018" version = "0.1.0" authors = ["Thom Chiovoloni "] diff --git a/sync15-adapter/src/bso_record.rs b/sync15-adapter/src/bso_record.rs index 139ecdc50b..ea941d07c2 100644 --- a/sync15-adapter/src/bso_record.rs +++ b/sync15-adapter/src/bso_record.rs @@ -2,15 +2,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use base64; -use error; -use key_bundle::KeyBundle; +use crate::error; +use crate::key_bundle::KeyBundle; +use crate::util::ServerTimestamp; +use lazy_static::lazy_static; +use log::*; use serde::de::{Deserialize, DeserializeOwned}; use serde::ser::Serialize; +use serde_derive::*; use serde_json::{self, Map, Value as JsonValue}; use std::convert::From; use std::ops::{Deref, DerefMut}; -use util::ServerTimestamp; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct BsoRecord { @@ -313,7 +315,6 @@ pub type CleartextBso = BsoRecord; mod as_json { use serde::de::{self, Deserialize, DeserializeOwned, Deserializer}; use serde::ser::{self, Serialize, Serializer}; - use serde_json; pub fn serialize(t: &T, serializer: S) -> Result where @@ -412,6 +413,7 @@ impl CleartextBso { #[cfg(test)] mod tests { use super::*; + use serde_json::json; #[test] fn test_deserialize_enc() { diff --git a/sync15-adapter/src/changeset.rs b/sync15-adapter/src/changeset.rs index c194c323be..702a096d5d 100644 --- a/sync15-adapter/src/changeset.rs +++ b/sync15-adapter/src/changeset.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use bso_record::{EncryptedBso, Payload}; -use client::Sync15StorageClient; -use error::{self, ErrorKind, Result}; -use key_bundle::KeyBundle; -use request::{CollectionRequest, NormalResponseHandler, UploadInfo}; -use state::GlobalState; -use util::ServerTimestamp; +use crate::bso_record::{EncryptedBso, Payload}; +use crate::client::Sync15StorageClient; +use crate::error::{self, ErrorKind, Result}; +use crate::key_bundle::KeyBundle; +use crate::request::{CollectionRequest, NormalResponseHandler, UploadInfo}; +use crate::state::GlobalState; +use crate::util::ServerTimestamp; #[derive(Debug, Clone)] pub struct RecordChangeset { diff --git a/sync15-adapter/src/client.rs b/sync15-adapter/src/client.rs index 2f17a4dbb8..cb1868aac2 100644 --- a/sync15-adapter/src/client.rs +++ b/sync15-adapter/src/client.rs @@ -2,27 +2,24 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use std::cell::Cell; -use std::time::Duration; - +use crate::bso_record::{BsoRecord, EncryptedBso}; +use crate::error::{self, ErrorKind}; +use crate::record_types::MetaGlobalRecord; +use crate::request::{ + BatchPoster, CollectionRequest, InfoCollections, InfoConfiguration, PostQueue, PostResponse, + PostResponseHandler, X_IF_UNMODIFIED_SINCE, X_WEAVE_TIMESTAMP, +}; +use crate::token; +use crate::util::ServerTimestamp; use hyper::Method; +use log::*; use reqwest::{ header::{self, HeaderValue, ACCEPT, AUTHORIZATION}, Client, Request, Response, Url, }; -use serde; -use serde_json; - -use bso_record::{BsoRecord, EncryptedBso}; -use error::{self, ErrorKind}; -use record_types::MetaGlobalRecord; -use request::{ - BatchPoster, CollectionRequest, InfoCollections, InfoConfiguration, PostQueue, PostResponse, - PostResponseHandler, X_IF_UNMODIFIED_SINCE, X_WEAVE_TIMESTAMP, -}; +use std::cell::Cell; use std::str::FromStr; -use token; -use util::ServerTimestamp; +use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Sync15StorageClientInit { diff --git a/sync15-adapter/src/collection_keys.rs b/sync15-adapter/src/collection_keys.rs index dfbfa415d4..79962149d1 100644 --- a/sync15-adapter/src/collection_keys.rs +++ b/sync15-adapter/src/collection_keys.rs @@ -2,12 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use bso_record::{EncryptedBso, Payload}; -use error::Result; -use key_bundle::KeyBundle; -use record_types::CryptoKeysRecord; +use crate::bso_record::{EncryptedBso, Payload}; +use crate::error::Result; +use crate::key_bundle::KeyBundle; +use crate::record_types::CryptoKeysRecord; +use crate::util::ServerTimestamp; +use serde_derive::*; use std::collections::HashMap; -use util::ServerTimestamp; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionKeys { diff --git a/sync15-adapter/src/error.rs b/sync15-adapter/src/error.rs index 5a17e7c1ff..a48415919e 100644 --- a/sync15-adapter/src/error.rs +++ b/sync15-adapter/src/error.rs @@ -2,12 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use base64; use failure::{self, Backtrace, Context, Fail, SyncFailure}; -use hawk; -use openssl; -use reqwest; -use serde_json; use std::boxed::Box; use std::time::SystemTime; use std::{fmt, result, string}; diff --git a/sync15-adapter/src/key_bundle.rs b/sync15-adapter/src/key_bundle.rs index beebb952ae..0e1e1ab3e3 100644 --- a/sync15-adapter/src/key_bundle.rs +++ b/sync15-adapter/src/key_bundle.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use base16; -use base64; -use error::{ErrorKind, Result}; +use crate::error::{ErrorKind, Result}; +use log::*; use openssl::hash::MessageDigest; use openssl::pkey::PKey; use openssl::sign::Signer; use openssl::{self, symm}; +use serde_derive::*; #[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)] pub struct KeyBundle { diff --git a/sync15-adapter/src/lib.rs b/sync15-adapter/src/lib.rs index 44dbc88741..f08eca3210 100644 --- a/sync15-adapter/src/lib.rs +++ b/sync15-adapter/src/lib.rs @@ -2,30 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -extern crate base64; -extern crate hawk; -extern crate hyper; -extern crate openssl; -extern crate reqwest; -extern crate serde; - -extern crate failure; - -#[macro_use] -extern crate lazy_static; - -#[macro_use] -extern crate serde_derive; - -#[macro_use] -extern crate log; - -#[cfg_attr(test, macro_use)] -extern crate serde_json; - -extern crate base16; -extern crate url; - // TODO: Some of these don't need to be pub... pub mod bso_record; pub mod changeset; @@ -42,13 +18,13 @@ pub mod token; pub mod util; // Re-export some of the types callers are likely to want for convenience. -pub use bso_record::{BsoRecord, CleartextBso, EncryptedBso, Payload}; -pub use changeset::{IncomingChangeset, OutgoingChangeset, RecordChangeset}; -pub use client::{Sync15StorageClient, Sync15StorageClientInit}; -pub use error::{Error, ErrorKind, Result}; -pub use key_bundle::KeyBundle; -pub use request::CollectionRequest; -pub use state::{GlobalState, SetupStateMachine}; -pub use sync::{synchronize, Store}; -pub use sync_multiple::{sync_multiple, ClientInfo}; -pub use util::{ServerTimestamp, SERVER_EPOCH}; +pub use crate::bso_record::{BsoRecord, CleartextBso, EncryptedBso, Payload}; +pub use crate::changeset::{IncomingChangeset, OutgoingChangeset, RecordChangeset}; +pub use crate::client::{Sync15StorageClient, Sync15StorageClientInit}; +pub use crate::error::{Error, ErrorKind, Result}; +pub use crate::key_bundle::KeyBundle; +pub use crate::request::CollectionRequest; +pub use crate::state::{GlobalState, SetupStateMachine}; +pub use crate::sync::{synchronize, Store}; +pub use crate::sync_multiple::{sync_multiple, ClientInfo}; +pub use crate::util::{ServerTimestamp, SERVER_EPOCH}; diff --git a/sync15-adapter/src/record_types.rs b/sync15-adapter/src/record_types.rs index ad6e356e3c..231d0d3942 100644 --- a/sync15-adapter/src/record_types.rs +++ b/sync15-adapter/src/record_types.rs @@ -2,6 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use serde_derive::*; use std::collections::HashMap; // Known record formats. diff --git a/sync15-adapter/src/request.rs b/sync15-adapter/src/request.rs index cd05039c7f..b4fda57acc 100644 --- a/sync15-adapter/src/request.rs +++ b/sync15-adapter/src/request.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use bso_record::EncryptedBso; -use util::ServerTimestamp; - -use error::{self, ErrorKind, Result}; +use crate::bso_record::EncryptedBso; +use crate::error::{self, ErrorKind, Result}; +use crate::util::ServerTimestamp; use hyper::StatusCode; +use log::*; use reqwest::Response; -use serde_json; +use serde_derive::*; use std::collections::HashMap; use std::default::Default; use std::fmt; @@ -671,7 +671,8 @@ impl PostQueue { #[cfg(test)] mod test { use super::*; - use bso_record::{BsoRecord, EncryptedPayload}; + use crate::bso_record::{BsoRecord, EncryptedPayload}; + use lazy_static::lazy_static; use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; diff --git a/sync15-adapter/src/state.rs b/sync15-adapter/src/state.rs index 358cdf9904..f0850776aa 100644 --- a/sync15-adapter/src/state.rs +++ b/sync15-adapter/src/state.rs @@ -4,15 +4,16 @@ use std::collections::{HashMap, HashSet}; -use bso_record::BsoRecord; -use client::SetupStorageClient; -use collection_keys::CollectionKeys; -use error::{self, ErrorKind}; -use key_bundle::KeyBundle; -use record_types::{MetaGlobalEngine, MetaGlobalRecord}; -use request::{InfoCollections, InfoConfiguration}; -use serde_json; -use util::{random_guid, ServerTimestamp, SERVER_EPOCH}; +use crate::bso_record::BsoRecord; +use crate::client::SetupStorageClient; +use crate::collection_keys::CollectionKeys; +use crate::error::{self, ErrorKind}; +use crate::key_bundle::KeyBundle; +use crate::record_types::{MetaGlobalEngine, MetaGlobalRecord}; +use crate::request::{InfoCollections, InfoConfiguration}; +use crate::util::{random_guid, ServerTimestamp, SERVER_EPOCH}; +use lazy_static::lazy_static; +use serde_derive::*; use self::SetupState::*; @@ -625,7 +626,7 @@ pub enum EngineStateChange { mod tests { use super::*; - use bso_record::{BsoRecord, EncryptedBso, EncryptedPayload}; + use crate::bso_record::{BsoRecord, EncryptedBso, EncryptedPayload}; struct InMemoryClient { info_configuration: error::Result, diff --git a/sync15-adapter/src/sync.rs b/sync15-adapter/src/sync.rs index 0896f83c00..37fb4bd391 100644 --- a/sync15-adapter/src/sync.rs +++ b/sync15-adapter/src/sync.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use changeset::{CollectionUpdate, IncomingChangeset, OutgoingChangeset}; -use client::Sync15StorageClient; -use error::Error; -use failure; -use request::CollectionRequest; -use state::GlobalState; -use util::ServerTimestamp; +use crate::changeset::{CollectionUpdate, IncomingChangeset, OutgoingChangeset}; +use crate::client::Sync15StorageClient; +use crate::error::Error; +use crate::request::CollectionRequest; +use crate::state::GlobalState; +use crate::util::ServerTimestamp; +use log::*; /// Low-level store functionality. Stores that need custom reconciliation logic should use this. /// diff --git a/sync15-adapter/src/sync_multiple.rs b/sync15-adapter/src/sync_multiple.rs index 0e4aee7219..d422552c52 100644 --- a/sync15-adapter/src/sync_multiple.rs +++ b/sync15-adapter/src/sync_multiple.rs @@ -5,15 +5,15 @@ // This helps you perform a sync of multiple stores and helps you manage // global and local state between syncs. -use client::{Sync15StorageClient, Sync15StorageClientInit}; -use error::Error; -use key_bundle::KeyBundle; -use serde_json; -use state::{GlobalState, SetupStateMachine}; +use crate::client::{Sync15StorageClient, Sync15StorageClientInit}; +use crate::error::Error; +use crate::key_bundle::KeyBundle; +use crate::state::{GlobalState, SetupStateMachine}; +use crate::sync::{self, Store}; +use log::*; use std::cell::Cell; use std::collections::HashMap; use std::result; -use sync::{self, Store}; /// Info stored in memory about the client to use. We reuse the client unless /// we discover the client_init has changed, in which case we re-create one. diff --git a/sync15-adapter/src/token.rs b/sync15-adapter/src/token.rs index 02b16f367c..81606370a7 100644 --- a/sync15-adapter/src/token.rs +++ b/sync15-adapter/src/token.rs @@ -2,17 +2,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use hawk; - -use error::{self, ErrorKind, Result}; +use crate::error::{self, ErrorKind, Result}; +use crate::util::ServerTimestamp; use hyper::header::AUTHORIZATION; +use log::*; use reqwest::{Client, Request, Url}; +use serde_derive::*; use std::borrow::{Borrow, Cow}; use std::cell::RefCell; use std::fmt; use std::str::FromStr; use std::time::{Duration, SystemTime}; -use util::ServerTimestamp; /// Tokenserver's timestamp is X-Timestamp and not X-Weave-Timestamp. const RETRY_AFTER: &str = "Retry-After"; diff --git a/sync15-adapter/src/util.rs b/sync15-adapter/src/util.rs index 1a8c8595d1..75d6aa9261 100644 --- a/sync15-adapter/src/util.rs +++ b/sync15-adapter/src/util.rs @@ -2,8 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use base64; -use openssl; +use serde_derive::*; use std::convert::From; use std::str::FromStr; use std::time::Duration; From 340723b173a875e85b3a4df5fbd905dc15161358 Mon Sep 17 00:00:00 2001 From: Edouard Oger Date: Tue, 11 Dec 2018 13:47:38 -0500 Subject: [PATCH 2/9] Convert sandvich/desktop to Rust 2018 --- sandvich/desktop/Cargo.toml | 1 + sandvich/desktop/src/main.rs | 6 +----- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/sandvich/desktop/Cargo.toml b/sandvich/desktop/Cargo.toml index ae2fded5b0..9d3a3ba375 100644 --- a/sandvich/desktop/Cargo.toml +++ b/sandvich/desktop/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "sandvich-desktop" +edition = "2018" version = "0.1.0" authors = ["Edouard Oger "] diff --git a/sandvich/desktop/src/main.rs b/sandvich/desktop/src/main.rs index cc04292e86..8e464aebcf 100644 --- a/sandvich/desktop/src/main.rs +++ b/sandvich/desktop/src/main.rs @@ -1,10 +1,6 @@ -extern crate fxa_client; -#[macro_use] -extern crate text_io; -extern crate url; - use fxa_client::FirefoxAccount; use std::collections::HashMap; +use text_io::*; use url::Url; static CONTENT_SERVER: &'static str = "http://127.0.0.1:3030"; From ca1572a6dd737d136db1895f658bf360ea606b5e Mon Sep 17 00:00:00 2001 From: Edouard Oger Date: Tue, 11 Dec 2018 13:49:11 -0500 Subject: [PATCH 3/9] Convert logins-sql to Rust 2018 --- logins-sql/Cargo.toml | 1 + logins-sql/examples/sync_pass_sql.rs | 28 +++------------------ logins-sql/ffi/Cargo.toml | 1 + logins-sql/ffi/src/lib.rs | 24 +++++------------- logins-sql/src/db.rs | 19 +++++++------- logins-sql/src/engine.rs | 12 ++++----- logins-sql/src/error.rs | 5 +--- logins-sql/src/ffi.rs | 8 +++--- logins-sql/src/lib.rs | 37 +++------------------------- logins-sql/src/login.rs | 8 +++--- logins-sql/src/schema.rs | 6 +++-- logins-sql/src/update_plan.rs | 10 ++++---- logins-sql/src/util.rs | 3 +-- 13 files changed, 52 insertions(+), 110 deletions(-) diff --git a/logins-sql/Cargo.toml b/logins-sql/Cargo.toml index 207ef2ac91..6144d79f9c 100644 --- a/logins-sql/Cargo.toml +++ b/logins-sql/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "logins-sql" +edition = "2018" version = "0.1.0" authors = ["Thom Chiovoloni "] diff --git a/logins-sql/examples/sync_pass_sql.rs b/logins-sql/examples/sync_pass_sql.rs index 255f17bbf4..583c67ec1b 100644 --- a/logins-sql/examples/sync_pass_sql.rs +++ b/logins-sql/examples/sync_pass_sql.rs @@ -4,39 +4,19 @@ #![recursion_limit = "4096"] -extern crate fxa_client; -extern crate logins_sql; -extern crate sync15_adapter as sync; -extern crate url; -#[macro_use] -extern crate prettytable; - -extern crate serde; -#[macro_use] -extern crate serde_derive; -extern crate serde_json; - -extern crate rusqlite; - -extern crate clap; -extern crate webbrowser; - -#[macro_use] -extern crate log; -extern crate chrono; -extern crate env_logger; -extern crate failure; - use failure::Fail; +use crate::sync::{KeyBundle, Sync15StorageClientInit}; use fxa_client::{AccessTokenInfo, Config, FirefoxAccount}; +use log::*; use logins_sql::{Login, PasswordEngine}; +use prettytable::*; use std::collections::HashMap; use std::{ fs, io::{self, Read, Write}, }; -use sync::{KeyBundle, Sync15StorageClientInit}; +use sync15_adapter as sync; const CLIENT_ID: &str = "98adfa37698f255b"; const REDIRECT_URI: &str = "https://lockbox.firefox.com/fxa/ios-redirect.html"; diff --git a/logins-sql/ffi/Cargo.toml b/logins-sql/ffi/Cargo.toml index b3976d0e6f..3a122a1db5 100644 --- a/logins-sql/ffi/Cargo.toml +++ b/logins-sql/ffi/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "loginsql_ffi" +edition = "2018" version = "0.1.0" authors = ["Thom Chiovoloni "] diff --git a/logins-sql/ffi/src/lib.rs b/logins-sql/ffi/src/lib.rs index 0fe316cae0..e5c55d4248 100644 --- a/logins-sql/ffi/src/lib.rs +++ b/logins-sql/ffi/src/lib.rs @@ -2,25 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -extern crate logins_sql; -extern crate rusqlite; -extern crate serde_json; -extern crate sync15_adapter; -extern crate url; - -#[macro_use] -extern crate ffi_support; -#[macro_use] -extern crate log; - -#[cfg(target_os = "android")] -extern crate android_logger; - -use std::os::raw::c_char; - -use ffi_support::{call_with_result, rust_str_from_c, rust_string_from_c, ExternError}; - +use ffi_support::{ + call_with_result, define_box_destructor, define_string_destructor, rust_str_from_c, + rust_string_from_c, ExternError, +}; +use log::*; use logins_sql::{Login, PasswordEngine, Result}; +use std::os::raw::c_char; fn logging_init() { #[cfg(target_os = "android")] diff --git a/logins-sql/src/db.rs b/logins-sql/src/db.rs index bd33c62eef..5c6ed90123 100644 --- a/logins-sql/src/db.rs +++ b/logins-sql/src/db.rs @@ -2,25 +2,26 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use error::*; -use failure; -use login::{LocalLogin, Login, MirrorLogin, SyncLoginData, SyncStatus}; +use crate::error::*; +use crate::login::{LocalLogin, Login, MirrorLogin, SyncLoginData, SyncStatus}; +use crate::schema; +use crate::sync::{ + self, CollectionRequest, IncomingChangeset, OutgoingChangeset, Payload, ServerTimestamp, Store, +}; +use crate::update_plan::UpdatePlan; +use crate::util; +use lazy_static::lazy_static; +use log::*; use rusqlite::{ types::{FromSql, ToSql}, Connection, }; -use schema; use sql_support::{self, ConnExt}; use std::collections::HashSet; use std::ops::Deref; use std::path::Path; use std::result; use std::time::SystemTime; -use sync::{ - self, CollectionRequest, IncomingChangeset, OutgoingChangeset, Payload, ServerTimestamp, Store, -}; -use update_plan::UpdatePlan; -use util; pub struct LoginDb { pub db: Connection, diff --git a/logins-sql/src/engine.rs b/logins-sql/src/engine.rs index 7e05de35fb..aa2c17faa9 100644 --- a/logins-sql/src/engine.rs +++ b/logins-sql/src/engine.rs @@ -1,13 +1,12 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use db::LoginDb; -use error::*; -use login::Login; -use rusqlite; +use crate::db::LoginDb; +use crate::error::*; +use crate::login::Login; +use crate::sync::{sync_multiple, ClientInfo, KeyBundle, Sync15StorageClientInit}; use std::cell::Cell; use std::path::Path; -use sync::{sync_multiple, ClientInfo, KeyBundle, Sync15StorageClientInit}; // This isn't really an engine in the firefox sync15 desktop sense -- it's // really a bundle of state that contains the sync storage client, the sync @@ -105,8 +104,9 @@ impl PasswordEngine { #[cfg(test)] mod test { use super::*; + use crate::util; + use more_asserts::*; use std::time::SystemTime; - use util; // Doesn't check metadata fields fn assert_logins_equiv(a: &Login, b: &Login) { assert_eq!(b.id, a.id); diff --git a/logins-sql/src/error.rs b/logins-sql/src/error.rs index 37019c5369..1091fd5ef9 100644 --- a/logins-sql/src/error.rs +++ b/logins-sql/src/error.rs @@ -2,13 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use crate::sync; use failure::{Backtrace, Context, Fail}; -use rusqlite; -use serde_json; use std::boxed::Box; use std::{self, fmt}; -use sync; -use url; pub type Result = std::result::Result; diff --git a/logins-sql/src/ffi.rs b/logins-sql/src/ffi.rs index 615015878a..211ba462e1 100644 --- a/logins-sql/src/ffi.rs +++ b/logins-sql/src/ffi.rs @@ -6,10 +6,12 @@ // This module implement the traits that make the FFI code easier to manage. -use ffi_support::{ErrorCode, ExternError}; -use rusqlite; +use crate::{Error, ErrorKind, Login, PasswordEngine}; +use ffi_support::{ + implement_into_ffi_by_json, implement_into_ffi_by_pointer, ErrorCode, ExternError, +}; +use log::*; use sync::ErrorKind as Sync15ErrorKind; -use {Error, ErrorKind, Login, PasswordEngine}; pub mod error_codes { /// An unexpected error occurred which likely cannot be meaningfully handled diff --git a/logins-sql/src/lib.rs b/logins-sql/src/lib.rs index 9fdda910af..c8c10ec48d 100644 --- a/logins-sql/src/lib.rs +++ b/logins-sql/src/lib.rs @@ -4,37 +4,6 @@ extern crate sync15_adapter as sync; -#[macro_use] -extern crate log; - -#[cfg(test)] -extern crate env_logger; - -#[macro_use] -extern crate lazy_static; - -extern crate failure; - -#[cfg(test)] -#[macro_use] -extern crate more_asserts; - -extern crate url; - -extern crate rusqlite; - -extern crate serde; -extern crate serde_json; - -#[macro_use] -extern crate serde_derive; - -extern crate sql_support; - -#[cfg(feature = "ffi")] -#[macro_use] -extern crate ffi_support; - #[macro_use] mod error; mod login; @@ -48,6 +17,6 @@ mod util; #[cfg(feature = "ffi")] mod ffi; -pub use engine::*; -pub use error::*; -pub use login::*; +pub use crate::engine::*; +pub use crate::error::*; +pub use crate::login::*; diff --git a/logins-sql/src/login.rs b/logins-sql/src/login.rs index fe80eb98f6..082ec34ffe 100644 --- a/logins-sql/src/login.rs +++ b/logins-sql/src/login.rs @@ -2,11 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use error::*; +use crate::error::*; +use crate::sync::{self, ServerTimestamp}; +use crate::util; +use log::*; use rusqlite::Row; +use serde_derive::*; use std::time::{self, SystemTime}; -use sync::{self, ServerTimestamp}; -use util; #[derive(Debug, Clone, Hash, PartialEq, Serialize, Deserialize, Default)] #[serde(rename_all = "camelCase")] diff --git a/logins-sql/src/schema.rs b/logins-sql/src/schema.rs index 4731f50805..258a7b11e1 100644 --- a/logins-sql/src/schema.rs +++ b/logins-sql/src/schema.rs @@ -88,8 +88,10 @@ //! JSON. //! -use db; -use error::*; +use crate::db; +use crate::error::*; +use lazy_static::lazy_static; +use log::*; use sql_support::ConnExt; /// Note that firefox-ios is currently on version 3. Version 4 is this version, diff --git a/logins-sql/src/update_plan.rs b/logins-sql/src/update_plan.rs index 237639ddfb..bddcc83fe4 100644 --- a/logins-sql/src/update_plan.rs +++ b/logins-sql/src/update_plan.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use error::*; -use login::{LocalLogin, Login, MirrorLogin, SyncStatus}; +use crate::error::*; +use crate::login::{LocalLogin, Login, MirrorLogin, SyncStatus}; +use crate::sync::ServerTimestamp; +use crate::util; +use log::*; use rusqlite::{types::ToSql, Connection}; -use sql_support; use std::time::SystemTime; -use sync::ServerTimestamp; -use util; #[derive(Default, Debug, Clone)] pub(crate) struct UpdatePlan { diff --git a/logins-sql/src/util.rs b/logins-sql/src/util.rs index 24fae758bb..542d25c6df 100644 --- a/logins-sql/src/util.rs +++ b/logins-sql/src/util.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use error::*; +use crate::error::*; use rusqlite::Row; use std::time; use url::Url; @@ -35,7 +35,6 @@ pub fn system_time_ms_i64(t: time::SystemTime) -> i64 { // Unfortunately, there's not a better way to turn on logging in tests AFAICT #[cfg(test)] pub(crate) fn init_test_logging() { - use env_logger; use std::sync::{Once, ONCE_INIT}; static INIT_LOGGING: Once = ONCE_INIT; INIT_LOGGING.call_once(|| { From 23289c0f40b94129ff2d059f01b1a355a57918ed Mon Sep 17 00:00:00 2001 From: Edouard Oger Date: Tue, 11 Dec 2018 14:00:46 -0500 Subject: [PATCH 4/9] Convert composite crates to Rust 2018 --- composites/lockbox/Cargo.toml | 1 + composites/reference-browser/Cargo.toml | 1 + 2 files changed, 2 insertions(+) diff --git a/composites/lockbox/Cargo.toml b/composites/lockbox/Cargo.toml index 80034f7699..f744c16ebc 100644 --- a/composites/lockbox/Cargo.toml +++ b/composites/lockbox/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "lockbox" +edition = "2018" version = "0.1.0" authors = ["application-services "] diff --git a/composites/reference-browser/Cargo.toml b/composites/reference-browser/Cargo.toml index 00c87ebfa2..809faa9950 100644 --- a/composites/reference-browser/Cargo.toml +++ b/composites/reference-browser/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "reference-browser" +edition = "2018" version = "0.1.0" authors = ["application-services "] From d8f775f94f542a9e6f161fb2546de0b5690273d7 Mon Sep 17 00:00:00 2001 From: Edouard Oger Date: Tue, 11 Dec 2018 14:01:35 -0500 Subject: [PATCH 5/9] Convert components/places to Rust 2018 --- components/places/Cargo.toml | 1 + components/places/examples/autocomplete.rs | 40 ++++------------ components/places/examples/sync_history.rs | 22 +-------- components/places/ffi/Cargo.toml | 1 + components/places/ffi/src/lib.rs | 21 ++------- components/places/src/api/history.rs | 12 ++--- components/places/src/api/matcher.rs | 15 +++--- components/places/src/api/mod.rs | 8 ++-- components/places/src/db/db.rs | 8 ++-- components/places/src/db/mod.rs | 2 +- components/places/src/db/schema.rs | 11 +++-- components/places/src/error.rs | 4 -- components/places/src/ffi.rs | 11 +++-- components/places/src/frecency.rs | 4 +- components/places/src/history_sync/mod.rs | 3 +- components/places/src/history_sync/plan.rs | 45 ++++++++---------- components/places/src/history_sync/record.rs | 6 +-- components/places/src/history_sync/store.rs | 6 +-- components/places/src/lib.rs | 49 +++----------------- components/places/src/match_impl.rs | 3 +- components/places/src/observation.rs | 4 +- components/places/src/storage.rs | 29 ++++++------ components/places/src/types.rs | 8 ++-- 23 files changed, 107 insertions(+), 206 deletions(-) diff --git a/components/places/Cargo.toml b/components/places/Cargo.toml index e1b77265f4..253629e6b1 100644 --- a/components/places/Cargo.toml +++ b/components/places/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "places" +edition = "2018" version = "0.1.0" authors = [] diff --git a/components/places/examples/autocomplete.rs b/components/places/examples/autocomplete.rs index d1cfb4baed..63ba1b0c9c 100644 --- a/components/places/examples/autocomplete.rs +++ b/components/places/examples/autocomplete.rs @@ -2,42 +2,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -extern crate places; - -#[macro_use] -extern crate log; -extern crate env_logger; -#[macro_use] -extern crate failure; -extern crate rusqlite; - -extern crate serde; -#[macro_use] -extern crate serde_derive; -extern crate serde_json; -extern crate url; -#[macro_use] -extern crate clap; -extern crate find_places_db; -extern crate sql_support; -extern crate tempfile; +use clap::value_t; +use failure::bail; +use log::*; +use places::{VisitObservation, VisitTransition}; +use serde_derive::*; use sql_support::ConnExt; - -#[cfg(not(windows))] -extern crate termion; - -extern crate rand; - use std::io::prelude::*; - -use url::Url; - -use places::{VisitObservation, VisitTransition}; - use std::{ fs, path::{Path, PathBuf}, }; +use url::Url; type Result = std::result::Result; @@ -619,11 +595,11 @@ mod autocomplete { } } Key::Ctrl('a') | Key::Home => { - write!(stdout, "{}", Goto(3, 2)); + write!(stdout, "{}", Goto(3, 2))?; cursor_idx = 0; } Key::Ctrl('e') | Key::End => { - write!(stdout, "{}", Goto(3 + query_str.len() as u16, 2)); + write!(stdout, "{}", Goto(3 + query_str.len() as u16, 2))?; cursor_idx = query_str.len(); } Key::Ctrl('u') => { diff --git a/components/places/examples/sync_history.rs b/components/places/examples/sync_history.rs index 3a1eb96e98..7de1f512a1 100644 --- a/components/places/examples/sync_history.rs +++ b/components/places/examples/sync_history.rs @@ -2,29 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -extern crate fxa_client; -extern crate sync15_adapter; -extern crate url; - -extern crate serde; -#[macro_use] -extern crate serde_derive; -extern crate serde_json; - -extern crate rusqlite; - -extern crate clap; - -#[macro_use] -extern crate log; -extern crate env_logger; -extern crate failure; - -extern crate places; - use failure::Fail; - use fxa_client::{AccessTokenInfo, Config, FirefoxAccount}; +use log::*; use places::history_sync::store::HistoryStore; use places::PlacesDb; use std::{fs, io::Read}; diff --git a/components/places/ffi/Cargo.toml b/components/places/ffi/Cargo.toml index 8d39cafe26..b09ffba171 100644 --- a/components/places/ffi/Cargo.toml +++ b/components/places/ffi/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "places-ffi" +edition = "2018" version = "0.1.0" authors = ["Thom Chiovoloni "] diff --git a/components/places/ffi/src/lib.rs b/components/places/ffi/src/lib.rs index cc2c22c347..bdbfdefac8 100644 --- a/components/places/ffi/src/lib.rs +++ b/components/places/ffi/src/lib.rs @@ -2,22 +2,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -extern crate places; -extern crate rusqlite; -extern crate serde_json; -extern crate sync15_adapter; -extern crate url; - -#[macro_use] -extern crate log; - -#[cfg(target_os = "android")] -extern crate android_logger; - -#[macro_use] -extern crate ffi_support; - -use ffi_support::{call_with_result, rust_str_from_c, rust_string_from_c, ExternError}; +use ffi_support::{ + call_with_result, define_box_destructor, define_string_destructor, rust_str_from_c, + rust_string_from_c, ExternError, +}; +use log::*; use places::history_sync::store::HistoryStore; use places::{storage, PlacesDb}; use std::os::raw::c_char; diff --git a/components/places/src/api/history.rs b/components/places/src/api/history.rs index 2fc00c3854..c1f0c90e7d 100644 --- a/components/places/src/api/history.rs +++ b/components/places/src/api/history.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use url::Url; - use super::apply_observation; -use db::PlacesDb; -use error::*; -use observation::VisitObservation; -use types::*; +use crate::db::PlacesDb; +use crate::error::*; +use crate::observation::VisitObservation; +use crate::types::*; +use log::*; +use url::Url; // This module can become, roughly: PlacesUtils.history() diff --git a/components/places/src/api/matcher.rs b/components/places/src/api/matcher.rs index 75181fca24..7800dd2f06 100644 --- a/components/places/src/api/matcher.rs +++ b/components/places/src/api/matcher.rs @@ -2,13 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use db::PlacesDb; -use error::Result; -use rusqlite; +use crate::db::PlacesDb; +use crate::error::Result; +use serde_derive::*; use url::Url; -use url_serde; -pub use match_impl::{MatchBehavior, SearchBehavior}; +pub use crate::match_impl::{MatchBehavior, SearchBehavior}; #[derive(Debug, Clone)] pub struct SearchParams { @@ -519,9 +518,9 @@ impl<'query, 'conn> Suggestions<'query, 'conn> { #[cfg(test)] mod tests { use super::*; - use observation::VisitObservation; - use storage::apply_observation; - use types::{Timestamp, VisitTransition}; + use crate::observation::VisitObservation; + use crate::storage::apply_observation; + use crate::types::{Timestamp, VisitTransition}; #[test] fn split() { diff --git a/components/places/src/api/mod.rs b/components/places/src/api/mod.rs index 0508addc80..63f5f9a542 100644 --- a/components/places/src/api/mod.rs +++ b/components/places/src/api/mod.rs @@ -4,10 +4,10 @@ pub mod history; pub mod matcher; -use db::PlacesDb; -use error::Result; -use observation::VisitObservation; -use storage; +use crate::db::PlacesDb; +use crate::error::Result; +use crate::observation::VisitObservation; +use crate::storage; pub fn apply_observation(conn: &mut PlacesDb, visit_obs: VisitObservation) -> Result<()> { storage::apply_observation(conn, visit_obs)?; diff --git a/components/places/src/db/db.rs b/components/places/src/db/db.rs index 78d517c6b4..afb93fdc83 100644 --- a/components/places/src/db/db.rs +++ b/components/places/src/db/db.rs @@ -7,15 +7,15 @@ // We should work out how to split this into a library we can reuse. use super::schema; -use error::*; -use hash; +use crate::error::*; +use crate::hash; use rusqlite::{self, Connection}; use sql_support::{self, ConnExt}; use std::ops::Deref; use std::path::Path; -use api::matcher::{split_after_host_and_port, split_after_prefix}; -use match_impl::{AutocompleteMatch, MatchBehavior, SearchBehavior}; +use crate::api::matcher::{split_after_host_and_port, split_after_prefix}; +use crate::match_impl::{AutocompleteMatch, MatchBehavior, SearchBehavior}; pub const MAX_VARIABLE_NUMBER: usize = 999; diff --git a/components/places/src/db/mod.rs b/components/places/src/db/mod.rs index 69e8394de9..e2a3944446 100644 --- a/components/places/src/db/mod.rs +++ b/components/places/src/db/mod.rs @@ -4,6 +4,6 @@ // We don't want 'db.rs' as a sub-module. We could move the contents here? Or something else? pub mod db; -pub use db::db::PlacesDb; +pub use crate::db::db::PlacesDb; mod schema; diff --git a/components/places/src/db/schema.rs b/components/places/src/db/schema.rs index bc62b4fd0a..9443d7e98f 100644 --- a/components/places/src/db/schema.rs +++ b/components/places/src/db/schema.rs @@ -7,11 +7,12 @@ // We should work out how to turn this into something that can use a shared // db.rs. -use db::PlacesDb; +use crate::db::PlacesDb; +use crate::error::*; +use lazy_static::lazy_static; +use log::*; use sql_support::ConnExt; -use error::*; - const VERSION: i64 = 2; const CREATE_TABLE_PLACES_SQL: &str = @@ -297,9 +298,9 @@ pub fn create(db: &PlacesDb) -> Result<()> { #[cfg(test)] mod tests { use super::*; - use db::PlacesDb; + use crate::db::PlacesDb; + use crate::types::SyncStatus; use sync15_adapter::util::random_guid; - use types::SyncStatus; use url::Url; fn has_tombstone(conn: &PlacesDb, guid: &str) -> bool { diff --git a/components/places/src/error.rs b/components/places/src/error.rs index de9e8893df..4b4256f890 100644 --- a/components/places/src/error.rs +++ b/components/places/src/error.rs @@ -5,12 +5,8 @@ // XXX - more copy-pasta from logins-sql. use failure::{Backtrace, Context, Fail}; -use rusqlite; -use serde_json; use std::boxed::Box; use std::{self, fmt}; -use sync15_adapter; -use url; pub type Result = std::result::Result; diff --git a/components/places/src/ffi.rs b/components/places/src/ffi.rs index 1a637d4a01..804d7e2a91 100644 --- a/components/places/src/ffi.rs +++ b/components/places/src/ffi.rs @@ -6,10 +6,13 @@ // This module implement the traits that make the FFI code easier to manage. -use api::matcher::SearchResult; -use db::PlacesDb; -use error::{Error, ErrorKind}; -use ffi_support::{ErrorCode, ExternError}; +use crate::api::matcher::SearchResult; +use crate::db::PlacesDb; +use crate::error::{Error, ErrorKind}; +use ffi_support::{ + implement_into_ffi_by_json, implement_into_ffi_by_pointer, ErrorCode, ExternError, +}; +use log::*; pub mod error_codes { // Note: 0 (success) and -1 (panic) are reserved by ffi_support diff --git a/components/places/src/frecency.rs b/components/places/src/frecency.rs index 02e3a4bf0d..2134cb10f0 100644 --- a/components/places/src/frecency.rs +++ b/components/places/src/frecency.rs @@ -2,9 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use error::*; +use crate::error::*; +use crate::types::VisitTransition; use rusqlite::Connection; -use types::VisitTransition; #[derive(Debug, Clone, Copy, PartialEq)] enum RedirectBonus { diff --git a/components/places/src/history_sync/mod.rs b/components/places/src/history_sync/mod.rs index 5b2a0f457c..c7708c6fb8 100644 --- a/components/places/src/history_sync/mod.rs +++ b/components/places/src/history_sync/mod.rs @@ -2,9 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use crate::types::Timestamp; +use serde_derive::*; use std::fmt; use std::time::{SystemTime, UNIX_EPOCH}; -use types::Timestamp; mod plan; pub mod record; diff --git a/components/places/src/history_sync/plan.rs b/components/places/src/history_sync/plan.rs index 903d424f3d..cef5cedd07 100644 --- a/components/places/src/history_sync/plan.rs +++ b/components/places/src/history_sync/plan.rs @@ -2,26 +2,23 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use std::collections::HashSet; -use std::time::{SystemTime, UNIX_EPOCH}; - -use rusqlite::Connection; -use sql_support::ConnExt; -use url::Url; - use super::record::{HistoryRecord, HistoryRecordVisit, HistorySyncRecord}; use super::{HISTORY_TTL, MAX_OUTGOING_PLACES, MAX_VISITS}; -use storage::history_sync::{ +use crate::api::history::can_add_url; +use crate::error::*; +use crate::storage::history_sync::{ apply_synced_deletion, apply_synced_reconciliation, apply_synced_visits, fetch_outgoing, fetch_visits, finish_outgoing, FetchedVisit, FetchedVisitPage, OutgoingInfo, }; -use types::{SyncGuid, Timestamp, VisitTransition}; -use valid_guid::is_valid_places_guid; - -use api::history::can_add_url; -use error::*; - +use crate::types::{SyncGuid, Timestamp, VisitTransition}; +use crate::valid_guid::is_valid_places_guid; +use log::*; +use rusqlite::Connection; +use sql_support::ConnExt; +use std::collections::HashSet; +use std::time::{SystemTime, UNIX_EPOCH}; use sync15_adapter::{IncomingChangeset, OutgoingChangeset, Payload}; +use url::Url; // In desktop sync, bookmarks are clamped to Jan 23, 1993 (which is 727747200000) // There's no good reason history records could be older than that, so we do @@ -290,19 +287,17 @@ pub fn finish_plan(conn: &Connection) -> Result<()> { #[cfg(test)] mod tests { use super::*; - use api::matcher::{search_frecent, SearchParams}; - use db::PlacesDb; - use history_sync::ServerVisitTimestamp; - use observation::VisitObservation; - use std::time::Duration; - use storage::apply_observation; - use storage::history_sync::fetch_visits; - use types::{SyncStatus, Timestamp}; - + use crate::api::matcher::{search_frecent, SearchParams}; + use crate::db::PlacesDb; + use crate::history_sync::ServerVisitTimestamp; + use crate::observation::VisitObservation; + use crate::storage::apply_observation; + use crate::storage::history_sync::fetch_visits; + use crate::types::{SyncStatus, Timestamp}; + use serde_json::json; use sql_support::ConnExt; + use std::time::Duration; use sync15_adapter::util::random_guid; - - use env_logger; use sync15_adapter::{IncomingChangeset, ServerTimestamp}; use url::Url; diff --git a/components/places/src/history_sync/record.rs b/components/places/src/history_sync/record.rs index 1b183c70df..9a422cd8da 100644 --- a/components/places/src/history_sync/record.rs +++ b/components/places/src/history_sync/record.rs @@ -3,9 +3,9 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use super::ServerVisitTimestamp; -use error::*; -use sync15_adapter; -use types::SyncGuid; +use crate::error::*; +use crate::types::SyncGuid; +use serde_derive::*; #[derive(Debug, Clone, Hash, PartialEq, Serialize, Deserialize, Default)] #[serde(rename_all = "camelCase")] diff --git a/components/places/src/history_sync/store.rs b/components/places/src/history_sync/store.rs index f18d1271d9..f58e716342 100644 --- a/components/places/src/history_sync/store.rs +++ b/components/places/src/history_sync/store.rs @@ -2,15 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use error::*; -use failure; +use crate::error::*; +use crate::storage::history_sync::reset_storage; +use log::*; use rusqlite::types::{FromSql, ToSql}; use rusqlite::Connection; use sql_support::ConnExt; use std::cell::Cell; use std::ops::Deref; use std::result; -use storage::history_sync::reset_storage; use sync15_adapter::request::CollectionRequest; use sync15_adapter::{ sync_multiple, ClientInfo, IncomingChangeset, KeyBundle, OutgoingChangeset, ServerTimestamp, diff --git a/components/places/src/lib.rs b/components/places/src/lib.rs index 60bf046c8b..18d984c484 100644 --- a/components/places/src/lib.rs +++ b/components/places/src/lib.rs @@ -2,43 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -extern crate sync15_adapter; - -#[macro_use] -extern crate log; - -#[cfg(test)] -extern crate env_logger; - -extern crate failure; - -extern crate unicode_segmentation; - -extern crate url; - -extern crate rusqlite; - -extern crate serde; -#[cfg_attr(test, macro_use)] -extern crate serde_json; - -#[macro_use] -extern crate serde_derive; - -extern crate caseless; -extern crate sql_support; -extern crate unicode_normalization; -extern crate url_serde; -#[macro_use] -extern crate bitflags; - -#[cfg(feature = "ffi")] -#[macro_use] -extern crate ffi_support; - -#[macro_use] -extern crate lazy_static; - pub mod api; pub mod error; pub mod types; @@ -55,9 +18,9 @@ pub mod storage; mod util; mod valid_guid; -pub use api::apply_observation; -pub use db::PlacesDb; -pub use error::*; -pub use observation::VisitObservation; -pub use storage::{PageInfo, RowId}; -pub use types::*; +pub use crate::api::apply_observation; +pub use crate::db::PlacesDb; +pub use crate::error::*; +pub use crate::observation::VisitObservation; +pub use crate::storage::{PageInfo, RowId}; +pub use crate::types::*; diff --git a/components/places/src/match_impl.rs b/components/places/src/match_impl.rs index 1bceddc156..55127b006b 100644 --- a/components/places/src/match_impl.rs +++ b/components/places/src/match_impl.rs @@ -2,6 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use crate::util; +use bitflags::bitflags; use caseless::Caseless; use rusqlite::{ self, @@ -9,7 +11,6 @@ use rusqlite::{ }; use std::borrow::Cow; use url::percent_encoding; -use util; const MAX_CHARS_TO_SEARCH_THROUGH: usize = 255; diff --git a/components/places/src/observation.rs b/components/places/src/observation.rs index 358d8f97b0..cca1779af3 100644 --- a/components/places/src/observation.rs +++ b/components/places/src/observation.rs @@ -2,9 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use types::*; +use crate::types::*; +use serde_derive::*; use url::Url; -use url_serde; /// An "observation" based model for updating history. /// You create a VisitObservation, call functions on it which correspond diff --git a/components/places/src/storage.rs b/components/places/src/storage.rs index 50a71c6954..c8d88f2c31 100644 --- a/components/places/src/storage.rs +++ b/components/places/src/storage.rs @@ -6,22 +6,20 @@ // API and the database. // This should probably be a sub-directory -use error::Result; -use frecency; -use observation::VisitObservation; -use std::fmt; -use types::{SyncGuid, SyncStatus, Timestamp, VisitTransition}; -use url::Url; - -use sync15_adapter; - +use crate::db::PlacesDb; +use crate::error::Result; +use crate::frecency; +use crate::hash; +use crate::observation::VisitObservation; +use crate::types::{SyncGuid, SyncStatus, Timestamp, VisitTransition}; +use log::*; use rusqlite::types::{FromSql, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; use rusqlite::Result as RusqliteResult; use rusqlite::{Connection, Row}; - -use db::PlacesDb; -use hash; +use serde_derive::*; use sql_support::{self, ConnExt}; +use std::fmt; +use url::Url; // Typesafe way to manage RowIds. Does it make sense? A better way? #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Deserialize, Serialize, Default)] @@ -309,8 +307,8 @@ fn add_visit( // Support for Sync - in its own module to try and keep a delineation pub mod history_sync { use super::*; - use history_sync::record::{HistoryRecord, HistoryRecordVisit}; - use history_sync::HISTORY_TTL; + use crate::history_sync::record::{HistoryRecord, HistoryRecordVisit}; + use crate::history_sync::HISTORY_TTL; use std::collections::HashMap; #[derive(Debug)] @@ -771,8 +769,7 @@ pub fn get_visited_urls( mod tests { use super::history_sync::*; use super::*; - use env_logger; - use history_sync::record::HistoryRecord; + use crate::history_sync::record::HistoryRecord; use std::time::{Duration, SystemTime}; struct Origin { diff --git a/components/places/src/types.rs b/components/places/src/types.rs index bbb9d1f68c..052c6eb5ad 100644 --- a/components/places/src/types.rs +++ b/components/places/src/types.rs @@ -2,13 +2,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use std::fmt; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - use rusqlite::types::{FromSql, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; use rusqlite::Result as RusqliteResult; - -use serde; +use serde_derive::*; +use std::fmt; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; // XXX - copied from logins - surprised it's not in `sync` #[derive(PartialEq, Eq, Hash, Clone, Debug, Serialize, Deserialize)] From c717f91b59537391e9f67dcb2e4eb38bf29fa0eb Mon Sep 17 00:00:00 2001 From: Edouard Oger Date: Tue, 11 Dec 2018 14:12:43 -0500 Subject: [PATCH 6/9] Convert components/support to Rust 2018 --- components/support/ffi/Cargo.toml | 1 + components/support/ffi/src/error.rs | 2 +- components/support/ffi/src/into_ffi.rs | 4 +-- components/support/ffi/src/lib.rs | 34 +++++++++--------------- components/support/ffi/src/macros.rs | 8 +++--- components/support/ffi/src/string.rs | 1 + components/support/sql/Cargo.toml | 1 + components/support/sql/src/conn_ext.rs | 3 ++- components/support/sql/src/each_chunk.rs | 1 + components/support/sql/src/lib.rs | 16 +++-------- 10 files changed, 27 insertions(+), 44 deletions(-) diff --git a/components/support/ffi/Cargo.toml b/components/support/ffi/Cargo.toml index 253e1b4b69..ae05e801e2 100644 --- a/components/support/ffi/Cargo.toml +++ b/components/support/ffi/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "ffi-support" +edition = "2018" version = "0.1.1" authors = ["Thom Chiovoloni "] description = "A crate to help expose Rust functions over the FFI." diff --git a/components/support/ffi/src/error.rs b/components/support/ffi/src/error.rs index 736331fe87..bfc5dd6451 100644 --- a/components/support/ffi/src/error.rs +++ b/components/support/ffi/src/error.rs @@ -2,9 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use crate::string::{destroy_c_string, rust_str_from_c, rust_string_to_c}; use std::os::raw::c_char; use std::{self, ptr}; -use string::{destroy_c_string, rust_str_from_c, rust_string_to_c}; /// Represents an error that occured within rust, storing both an error code, and additional data /// that may be used by the caller. diff --git a/components/support/ffi/src/into_ffi.rs b/components/support/ffi/src/into_ffi.rs index b9531f1433..8d3a5a92bf 100644 --- a/components/support/ffi/src/into_ffi.rs +++ b/components/support/ffi/src/into_ffi.rs @@ -2,11 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use serde; -use serde_json; +use crate::string::*; use std::os::raw::c_char; use std::ptr; -use string::*; /// This trait is used to return types over the FFI. It essentially is a mapping between a type and /// version of that type we can pass back to C (`IntoFfi::Value`). diff --git a/components/support/ffi/src/lib.rs b/components/support/ffi/src/lib.rs index c4c01294a5..f714058928 100644 --- a/components/support/ffi/src/lib.rs +++ b/components/support/ffi/src/lib.rs @@ -90,34 +90,18 @@ //! [`opt_rust_string_from_c`], etc. //! -// TODO: it would be nice if this was an optional dep. -extern crate serde; -extern crate serde_json; - -#[macro_use] -extern crate log; - +use log::*; use std::{panic, thread}; -// We could use failure for failure::Backtrace (and we enable RUST_BACKTRACE -// to opt-in to backtraces on failure errors if possible), however: -// - we don't already have a failure dependency (one is likely inevitable, -// and all our clients do, so this doesn't matter) -// - `failure` only checks the RUST_BACKTRACE variable once, and we could have errors -// before this. So we just use the backtrace crate directly. -#[cfg(feature = "log_backtraces")] -extern crate backtrace; - -#[macro_use] -mod macros; mod error; mod into_ffi; +mod macros; mod string; -pub use error::*; -pub use into_ffi::*; -pub use macros::*; -pub use string::*; +pub use crate::error::*; +pub use crate::into_ffi::*; +pub use crate::macros::*; +pub use crate::string::*; /// Call a callback that returns a `Result` while: /// @@ -342,6 +326,12 @@ fn init_backtraces_once() { ("", 0) }; error!("### Rust `panic!` hit at file '{}', line {}", file, line); + // We could use failure for failure::Backtrace (and we enable RUST_BACKTRACE + // to opt-in to backtraces on failure errors if possible), however: + // - we don't already have a failure dependency (one is likely inevitable, + // and all our clients do, so this doesn't matter) + // - `failure` only checks the RUST_BACKTRACE variable once, and we could have errors + // before this. So we just use the backtrace crate directly. error!(" Complete stack trace:\n{:?}", backtrace::Backtrace::new()); })); }); diff --git a/components/support/ffi/src/macros.rs b/components/support/ffi/src/macros.rs index 8230b8494a..be8ebb5a03 100644 --- a/components/support/ffi/src/macros.rs +++ b/components/support/ffi/src/macros.rs @@ -2,10 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use serde; -use serde_json; +use crate::string::rust_string_to_c; use std::os::raw::c_char; -use string::rust_string_to_c; /// Implements [`IntoFfi`] for the provided types (more than one may be passed in) by allocating /// `$T` on the heap as an opaque pointer. @@ -97,7 +95,7 @@ macro_rules! implement_into_ffi_by_json { /// ## Example /// /// ```rust -/// # #[macro_use] extern crate ffi_support; +/// # use ffi_support::define_string_destructor; /// define_string_destructor!(mylib_destroy_string); /// ``` #[macro_export] @@ -128,7 +126,7 @@ macro_rules! define_string_destructor { /// ## Example /// /// ```rust -/// # #[macro_use] extern crate ffi_support; +/// # use ffi_support::define_box_destructor; /// struct CoolType(Vec); /// /// define_box_destructor!(CoolType, mylib_destroy_cooltype); diff --git a/components/support/ffi/src/string.rs b/components/support/ffi/src/string.rs index c074d08d4f..20fecd73a7 100644 --- a/components/support/ffi/src/string.rs +++ b/components/support/ffi/src/string.rs @@ -2,6 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use log::*; use std::ffi::{CStr, CString}; use std::os::raw::c_char; use std::ptr; diff --git a/components/support/sql/Cargo.toml b/components/support/sql/Cargo.toml index 038063435d..ffb748cce0 100644 --- a/components/support/sql/Cargo.toml +++ b/components/support/sql/Cargo.toml @@ -1,5 +1,6 @@ [package] name = "sql-support" +edition = "2018" version = "0.1.0" authors = ["Thom Chiovoloni "] diff --git a/components/support/sql/src/conn_ext.rs b/components/support/sql/src/conn_ext.rs index f3c371a309..0a60c4f547 100644 --- a/components/support/sql/src/conn_ext.rs +++ b/components/support/sql/src/conn_ext.rs @@ -2,6 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use log::*; use rusqlite::{ self, types::{FromSql, ToSql}, @@ -10,7 +11,7 @@ use rusqlite::{ use std::ops::Deref; use std::time::Instant; -use maybe_cached::MaybeCached; +use crate::maybe_cached::MaybeCached; /// This trait exists so that we can use these helpers on `rusqlite::{Transaction, Connection}`. /// Note that you must import ConnExt in order to call these methods on anything. diff --git a/components/support/sql/src/each_chunk.rs b/components/support/sql/src/each_chunk.rs index 09a8ac6970..58ef64aa69 100644 --- a/components/support/sql/src/each_chunk.rs +++ b/components/support/sql/src/each_chunk.rs @@ -2,6 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use lazy_static::lazy_static; use rusqlite::{self, limits::Limit, types::ToSql}; /// Returns SQLITE_LIMIT_VARIABLE_NUMBER as read from an in-memory connection and cached. diff --git a/components/support/sql/src/lib.rs b/components/support/sql/src/lib.rs index abb32d0c87..d5b48dcf3c 100644 --- a/components/support/sql/src/lib.rs +++ b/components/support/sql/src/lib.rs @@ -2,23 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#[macro_use] -extern crate log; - -extern crate rusqlite; - -#[macro_use] -extern crate lazy_static; - mod conn_ext; mod each_chunk; mod maybe_cached; mod repeat; -pub use conn_ext::*; -pub use each_chunk::*; -pub use maybe_cached::*; -pub use repeat::*; +pub use crate::conn_ext::*; +pub use crate::each_chunk::*; +pub use crate::maybe_cached::*; +pub use crate::repeat::*; /// In PRAGMA foo='bar', `'bar'` must be a constant string (it cannot be a /// bound parameter), so we need to escape manually. According to From e77da88aa35ff6c4ffd6a49018d8ebe1a71d58c4 Mon Sep 17 00:00:00 2001 From: Edouard Oger Date: Tue, 11 Dec 2018 14:21:19 -0500 Subject: [PATCH 7/9] Remove extern crate statement in fxa-client --- fxa-client/ffi/src/lib.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/fxa-client/ffi/src/lib.rs b/fxa-client/ffi/src/lib.rs index fea4750885..0c81697c43 100644 --- a/fxa-client/ffi/src/lib.rs +++ b/fxa-client/ffi/src/lib.rs @@ -2,8 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -extern crate fxa_client; - use ffi_support::{ call_with_output, call_with_result, define_box_destructor, define_string_destructor, rust_str_from_c, ExternError, From 14abecddccbfbf6043029f3f0f872187c6233b84 Mon Sep 17 00:00:00 2001 From: Edouard Oger Date: Tue, 11 Dec 2018 19:29:20 -0500 Subject: [PATCH 8/9] Use prefixed log macros --- components/places/examples/autocomplete.rs | 22 +++---- components/places/examples/sync_history.rs | 18 ++--- components/places/ffi/src/lib.rs | 15 ++--- components/places/src/api/history.rs | 3 +- components/places/src/db/schema.rs | 12 ++-- components/places/src/ffi.rs | 9 ++- components/places/src/history_sync/plan.rs | 28 ++++---- components/places/src/history_sync/store.rs | 7 +- components/places/src/storage.rs | 15 ++--- components/support/ffi/src/lib.rs | 7 +- components/support/ffi/src/string.rs | 3 +- components/support/sql/src/conn_ext.rs | 5 +- fxa-client/src/ffi.rs | 5 +- fxa-client/src/lib.rs | 11 ++-- fxa-client/src/login_sm.rs | 37 +++++------ logins-sql/examples/sync_pass_sql.rs | 73 +++++++++++---------- logins-sql/ffi/src/lib.rs | 23 ++++--- logins-sql/src/db.rs | 30 ++++----- logins-sql/src/ffi.rs | 13 ++-- logins-sql/src/login.rs | 3 +- logins-sql/src/schema.rs | 12 ++-- logins-sql/src/update_plan.rs | 15 ++--- sync15-adapter/src/bso_record.rs | 11 ++-- sync15-adapter/src/client.rs | 11 ++-- sync15-adapter/src/key_bundle.rs | 11 ++-- sync15-adapter/src/request.rs | 21 +++--- sync15-adapter/src/sync.rs | 11 ++-- sync15-adapter/src/sync_multiple.rs | 17 +++-- sync15-adapter/src/token.rs | 12 ++-- 29 files changed, 223 insertions(+), 237 deletions(-) diff --git a/components/places/examples/autocomplete.rs b/components/places/examples/autocomplete.rs index 63ba1b0c9c..2fbe291e43 100644 --- a/components/places/examples/autocomplete.rs +++ b/components/places/examples/autocomplete.rs @@ -4,7 +4,6 @@ use clap::value_t; use failure::bail; -use log::*; use places::{VisitObservation, VisitTransition}; use serde_derive::*; use sql_support::ConnExt; @@ -157,9 +156,10 @@ fn import_places( (ps, vs) }; - info!( + log::info!( "Importing {} visits across {} places!", - place_count, visit_count + place_count, + visit_count ); let mut stmt = old.prepare( " @@ -231,7 +231,7 @@ fn import_places( println!("Finished processing records"); println!("Committing...."); tx.commit()?; - info!("Finished import!"); + log::info!("Finished import!"); Ok(()) } @@ -345,7 +345,7 @@ mod autocomplete { } Err(e) => { // TODO: this is likely not to go very well since we're in raw mode... - error!("Got error doing autocomplete: {:?}", e); + log::error!("Got error doing autocomplete: {:?}", e); panic!("Got error doing autocomplete: {:?}", e); // return Err(e.into()); } @@ -808,14 +808,14 @@ fn main() -> Result<()> { .unwrap_or(0.1), }; let import_source = if import_places_arg == "auto" { - info!("Automatically locating largest places DB in your profile(s)"); + log::info!("Automatically locating largest places DB in your profile(s)"); let profile_info = if let Some(info) = find_places_db::get_largest_places_db()? { info } else { - error!("Failed to locate your firefox profile!"); + log::error!("Failed to locate your firefox profile!"); bail!("--import-places=auto specified, but couldn't find a `places.sqlite`"); }; - info!( + log::info!( "Using a {} places.sqlite from profile '{}' (places path = {:?})", profile_info.friendly_db_size(), profile_info.profile_name, @@ -848,17 +848,17 @@ fn main() -> Result<()> { } if let Some(observations_json) = matches.value_of("import_observations") { - info!("Importing observations from {}", observations_json); + log::info!("Importing observations from {}", observations_json); let observations: Vec = read_json_file(observations_json)?; let num_observations = observations.len(); - info!("Found {} observations", num_observations); + log::info!("Found {} observations", num_observations); let mut counter = 0; for obs in observations { let visit = obs.into_visit()?; places::apply_observation(&mut conn, visit)?; counter += 1; if (counter % 1000) == 0 { - trace!("Importing observations {} / {}", counter, num_observations); + log::trace!("Importing observations {} / {}", counter, num_observations); } } } diff --git a/components/places/examples/sync_history.rs b/components/places/examples/sync_history.rs index 7de1f512a1..fd83a313cf 100644 --- a/components/places/examples/sync_history.rs +++ b/components/places/examples/sync_history.rs @@ -4,7 +4,6 @@ use failure::Fail; use fxa_client::{AccessTokenInfo, Config, FirefoxAccount}; -use log::*; use places::history_sync::store::HistoryStore; use places::PlacesDb; use std::{fs, io::Read}; @@ -87,9 +86,10 @@ fn main() -> Result<()> { .expect("Encryption key is not optional"); // Lets not log the encryption key, it's just not a good habit to be in. - debug!( + log::debug!( "Using credential file = {:?}, db = {:?}", - cred_file, db_path + cred_file, + db_path ); // TODO: allow users to use stage/etc. @@ -117,22 +117,22 @@ fn main() -> Result<()> { let store = HistoryStore::new(&db); if matches.is_present("wipe-remote") { - info!("Wiping remote"); + log::info!("Wiping remote"); let client = Sync15StorageClient::new(client_init.clone())?; client.wipe_all_remote()?; } if matches.is_present("reset") { - info!("Resetting"); + log::info!("Resetting"); store.reset()?; } - info!("Syncing!"); + log::info!("Syncing!"); if let Err(e) = store.sync(&client_init, &root_sync_key) { - warn!("Sync failed! {}", e); - warn!("BT: {:?}", e.backtrace()); + log::warn!("Sync failed! {}", e); + log::warn!("BT: {:?}", e.backtrace()); } else { - info!("Sync was successful!"); + log::info!("Sync was successful!"); } println!("Exiting (bye!)"); Ok(()) diff --git a/components/places/ffi/src/lib.rs b/components/places/ffi/src/lib.rs index bdbfdefac8..6b3cc763cd 100644 --- a/components/places/ffi/src/lib.rs +++ b/components/places/ffi/src/lib.rs @@ -6,7 +6,6 @@ use ffi_support::{ call_with_result, define_box_destructor, define_string_destructor, rust_str_from_c, rust_string_from_c, ExternError, }; -use log::*; use places::history_sync::store::HistoryStore; use places::{storage, PlacesDb}; use std::os::raw::c_char; @@ -25,7 +24,7 @@ fn logging_init() { android_logger::Filter::default().with_min_level(log::Level::Trace), Some("libplaces_ffi"), ); - debug!("Android logging should be hooked up!") + log::debug!("Android logging should be hooked up!") } } @@ -40,7 +39,7 @@ pub unsafe extern "C" fn places_connection_new( encryption_key: *const c_char, error: &mut ExternError, ) -> *mut PlacesDb { - trace!("places_connection_new"); + log::trace!("places_connection_new"); logging_init(); call_with_result(error, || { let path = ffi_support::rust_string_from_c(db_path); @@ -57,7 +56,7 @@ pub unsafe extern "C" fn places_note_observation( json_observation: *const c_char, error: &mut ExternError, ) { - trace!("places_note_observation"); + log::trace!("places_note_observation"); call_with_result(error, || { let json = ffi_support::rust_str_from_c(json_observation); let visit: places::VisitObservation = serde_json::from_str(&json)?; @@ -74,7 +73,7 @@ pub unsafe extern "C" fn places_query_autocomplete( limit: u32, error: &mut ExternError, ) -> *mut c_char { - trace!("places_query_autocomplete"); + log::trace!("places_query_autocomplete"); call_with_result(error, || { search_frecent( conn, @@ -92,7 +91,7 @@ pub unsafe extern "C" fn places_get_visited( urls_json: *const c_char, error: &mut ExternError, ) -> *mut c_char { - trace!("places_get_visited"); + log::trace!("places_get_visited"); // This function has a dumb amount of overhead and copying... call_with_result(error, || -> places::Result { let json = ffi_support::rust_str_from_c(urls_json); @@ -116,7 +115,7 @@ pub extern "C" fn places_get_visited_urls_in_range( include_remote: u8, // JNA has issues with bools... error: &mut ExternError, ) -> *mut c_char { - trace!("places_get_visited_in_range"); + log::trace!("places_get_visited_in_range"); call_with_result(error, || -> places::Result { let visited = storage::get_visited_urls( conn, @@ -138,7 +137,7 @@ pub unsafe extern "C" fn sync15_history_sync( tokenserver_url: *const c_char, error: &mut ExternError, ) { - trace!("sync15_history_sync"); + log::trace!("sync15_history_sync"); call_with_result(error, || -> places::Result<()> { // XXX - this is wrong - we kinda want this to be long-lived - the "Db" // should own the store, but it's not part of the db. diff --git a/components/places/src/api/history.rs b/components/places/src/api/history.rs index c1f0c90e7d..43bc784cd1 100644 --- a/components/places/src/api/history.rs +++ b/components/places/src/api/history.rs @@ -7,7 +7,6 @@ use crate::db::PlacesDb; use crate::error::*; use crate::observation::VisitObservation; use crate::types::*; -use log::*; use url::Url; // This module can become, roughly: PlacesUtils.history() @@ -182,7 +181,7 @@ pub fn visit_uri( // EMBED visits are session-persistent and should not go through the database. // They exist only to keep track of isVisited status during the session. if transition == VisitTransition::Embed { - warn!("Embed visit, but in-memory storage of these isn't done yet"); + log::warn!("Embed visit, but in-memory storage of these isn't done yet"); return Ok(()); } diff --git a/components/places/src/db/schema.rs b/components/places/src/db/schema.rs index 9443d7e98f..e23fb8dca5 100644 --- a/components/places/src/db/schema.rs +++ b/components/places/src/db/schema.rs @@ -10,7 +10,6 @@ use crate::db::PlacesDb; use crate::error::*; use lazy_static::lazy_static; -use log::*; use sql_support::ConnExt; const VERSION: i64 = 2; @@ -236,10 +235,11 @@ pub fn init(db: &PlacesDb) -> Result<()> { if user_version < VERSION { upgrade(db, user_version)?; } else { - warn!( + log::warn!( "Loaded future schema version {} (we only understand version {}). \ Optimisitically ", - user_version, VERSION + user_version, + VERSION ) } } @@ -248,7 +248,7 @@ pub fn init(db: &PlacesDb) -> Result<()> { // https://github.com/mozilla-mobile/firefox-ios/blob/master/Storage/SQL/LoginsSchema.swift#L100 fn upgrade(_db: &PlacesDb, from: i64) -> Result<()> { - debug!("Upgrading schema from {} to {}", from, VERSION); + log::debug!("Upgrading schema from {} to {}", from, VERSION); if from == VERSION { return Ok(()); } @@ -258,7 +258,7 @@ fn upgrade(_db: &PlacesDb, from: i64) -> Result<()> { } pub fn create(db: &PlacesDb) -> Result<()> { - debug!("Creating schema"); + log::debug!("Creating schema"); db.execute_all(&[ CREATE_TABLE_PLACES_SQL, CREATE_TABLE_PLACES_TOMBSTONES_SQL, @@ -283,7 +283,7 @@ pub fn create(db: &PlacesDb) -> Result<()> { &format!("PRAGMA user_version = {version}", version = VERSION), ])?; - debug!("Creating temp tables and triggers"); + log::debug!("Creating temp tables and triggers"); db.execute_all(&[ CREATE_TRIGGER_AFTER_INSERT_ON_PLACES, &CREATE_TRIGGER_HISTORYVISITS_AFTERINSERT, diff --git a/components/places/src/ffi.rs b/components/places/src/ffi.rs index 804d7e2a91..6e50b4916a 100644 --- a/components/places/src/ffi.rs +++ b/components/places/src/ffi.rs @@ -12,7 +12,6 @@ use crate::error::{Error, ErrorKind}; use ffi_support::{ implement_into_ffi_by_json, implement_into_ffi_by_pointer, ErrorCode, ExternError, }; -use log::*; pub mod error_codes { // Note: 0 (success) and -1 (panic) are reserved by ffi_support @@ -36,11 +35,11 @@ pub mod error_codes { fn get_code(err: &Error) -> ErrorCode { match err.kind() { ErrorKind::InvalidPlaceInfo(info) => { - error!("Invalid place info: {}", info); + log::error!("Invalid place info: {}", info); ErrorCode::new(error_codes::INVALID_PLACE_INFO) } ErrorKind::UrlParseError(e) => { - error!("URL parse error: {}", e); + log::error!("URL parse error: {}", e); ErrorCode::new(error_codes::URL_PARSE_ERROR) } // Can't pattern match on `err` without adding a dep on the sqlite3-sys crate, @@ -48,11 +47,11 @@ fn get_code(err: &Error) -> ErrorCode { ErrorKind::SqlError(rusqlite::Error::SqliteFailure(err, msg)) if err.code == rusqlite::ErrorCode::DatabaseBusy => { - error!("Database busy: {:?} {:?}", err, msg); + log::error!("Database busy: {:?} {:?}", err, msg); ErrorCode::new(error_codes::DATABASE_BUSY) } err => { - error!("Unexpected error: {:?}", err); + log::error!("Unexpected error: {:?}", err); ErrorCode::new(error_codes::UNEXPECTED) } } diff --git a/components/places/src/history_sync/plan.rs b/components/places/src/history_sync/plan.rs index cef5cedd07..4f7e1f2661 100644 --- a/components/places/src/history_sync/plan.rs +++ b/components/places/src/history_sync/plan.rs @@ -12,7 +12,6 @@ use crate::storage::history_sync::{ }; use crate::types::{SyncGuid, Timestamp, VisitTransition}; use crate::valid_guid::is_valid_places_guid; -use log::*; use rusqlite::Connection; use sql_support::ConnExt; use std::collections::HashSet; @@ -184,7 +183,7 @@ pub fn apply_plan(conn: &Connection, inbound: IncomingChangeset) -> Result { // We can't push IncomingPlan::Invalid into plans as we don't // know the guid - just skip it. - warn!("Error deserializing incoming record: {}", e); + log::warn!("Error deserializing incoming record: {}", e); continue; } }; @@ -205,19 +204,20 @@ pub fn apply_plan(conn: &Connection, inbound: IncomingChangeset) -> Result { - trace!("incoming: skipping item {:?}", guid); + log::trace!("incoming: skipping item {:?}", guid); } IncomingPlan::Invalid(err) => { - warn!( + log::warn!( "incoming: record {:?} skipped because it is invalid: {}", - guid, err + guid, + err ); } IncomingPlan::Failed(err) => { - error!("incoming: record {:?} failed to apply: {}", guid, err); + log::error!("incoming: record {:?} failed to apply: {}", guid, err); } IncomingPlan::Delete => { - trace!("incoming: deleting {:?}", guid); + log::trace!("incoming: deleting {:?}", guid); num_deleted += 1; apply_synced_deletion(&conn, &guid)?; } @@ -228,7 +228,7 @@ pub fn apply_plan(conn: &Connection, inbound: IncomingChangeset) -> Result { num_applied += 1; - trace!( + log::trace!( "incoming: will apply {:?}: url={:?}, title={:?}, to_add={:?}", guid, url, @@ -249,7 +249,7 @@ pub fn apply_plan(conn: &Connection, inbound: IncomingChangeset) -> Result { num_reconciled += 1; - trace!("incoming: reconciled {:?}", guid); + log::trace!("incoming: reconciled {:?}", guid); apply_synced_reconciliation(&conn, &guid)?; } }; @@ -263,14 +263,16 @@ pub fn apply_plan(conn: &Connection, inbound: IncomingChangeset) -> Result Payload::from_record(record)?, OutgoingInfo::Tombstone => Payload::new_tombstone_with_ttl(guid.0.clone(), HISTORY_TTL), }; - trace!("outgoing {:?}", payload); + log::trace!("outgoing {:?}", payload); outgoing.changes.push(payload); } tx.commit()?; - info!( + log::info!( "incoming: applied {}, deleted {}, reconciled {}", - num_applied, num_deleted, num_reconciled + num_applied, + num_deleted, + num_reconciled ); Ok(outgoing) @@ -279,7 +281,7 @@ pub fn apply_plan(conn: &Connection, inbound: IncomingChangeset) -> Result Result<()> { let tx = conn.unchecked_transaction()?; finish_outgoing(conn)?; - trace!("Committing final sync plan"); + log::trace!("Committing final sync plan"); tx.commit()?; Ok(()) } diff --git a/components/places/src/history_sync/store.rs b/components/places/src/history_sync/store.rs index f58e716342..04e6662b16 100644 --- a/components/places/src/history_sync/store.rs +++ b/components/places/src/history_sync/store.rs @@ -4,7 +4,6 @@ use crate::error::*; use crate::storage::history_sync::reset_storage; -use log::*; use rusqlite::types::{FromSql, ToSql}; use rusqlite::Connection; use sql_support::ConnExt; @@ -68,7 +67,7 @@ impl<'a> HistoryStore<'a> { new_timestamp: ServerTimestamp, records_synced: &[String], ) -> Result<()> { - info!( + log::info!( "sync completed after uploading {} records", records_synced.len() ); @@ -81,7 +80,7 @@ impl<'a> HistoryStore<'a> { } fn do_reset(&self) -> Result<()> { - info!("Resetting history store"); + log::info!("Resetting history store"); reset_storage(self.db)?; self.put_meta(LAST_SYNC_META_KEY, &0)?; Ok(()) @@ -178,7 +177,7 @@ impl<'a> Store for HistoryStore<'a> { } fn wipe(&self) -> result::Result<(), failure::Error> { - warn!("not implemented"); + log::warn!("not implemented"); Ok(()) } } diff --git a/components/places/src/storage.rs b/components/places/src/storage.rs index c8d88f2c31..de8e480721 100644 --- a/components/places/src/storage.rs +++ b/components/places/src/storage.rs @@ -12,7 +12,6 @@ use crate::frecency; use crate::hash; use crate::observation::VisitObservation; use crate::types::{SyncGuid, SyncStatus, Timestamp, VisitTransition}; -use log::*; use rusqlite::types::{FromSql, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; use rusqlite::Result as RusqliteResult; use rusqlite::{Connection, Row}; @@ -539,7 +538,7 @@ pub mod history_sync { })?; for r in ts_rows { let guid = r?; - trace!("outgoing tombstone {:?}", &guid); + log::trace!("outgoing tombstone {:?}", &guid); result.insert(guid, OutgoingInfo::Tombstone); } @@ -581,17 +580,17 @@ pub mod history_sync { let visits = visit_rows.collect::>>()?; if result.contains_key(&page.guid) { // should be impossible! - warn!("Found {:?} in both tombstones and live records", &page.guid); + log::warn!("Found {:?} in both tombstones and live records", &page.guid); continue; } if visits.len() == 0 { - info!( + log::info!( "Page {:?} is flagged to be uploaded, but has no visits - skipping", &page.guid ); continue; } - trace!("outgoing record {:?}", &page.guid); + log::trace!("outgoing record {:?}", &page.guid); ids_to_update.push(page.row_id); db.execute_named_cached( insert_meta_sql, @@ -645,7 +644,7 @@ pub mod history_sync { // we can't do chunking and building a literal string with the ids seems // wrong and likely to hit max sql length limits. // So we use a temp table. - trace!("Updating all synced rows"); + log::trace!("Updating all synced rows"); // XXX - is there a better way to express this SQL? Multi-selects // doesn't seem ideal... db.conn().execute_cached( @@ -658,7 +657,7 @@ pub mod history_sync { &[], )?; - trace!("Updating all non-synced rows"); + log::trace!("Updating all non-synced rows"); db.execute_all(&[ &format!( "UPDATE moz_places @@ -669,7 +668,7 @@ pub mod history_sync { "DELETE FROM temp_sync_updated_meta", ])?; - trace!("Removing local tombstones"); + log::trace!("Removing local tombstones"); db.conn() .execute_cached("DELETE from moz_places_tombstones", &[])?; diff --git a/components/support/ffi/src/lib.rs b/components/support/ffi/src/lib.rs index f714058928..0038cef19a 100644 --- a/components/support/ffi/src/lib.rs +++ b/components/support/ffi/src/lib.rs @@ -90,7 +90,6 @@ //! [`opt_rust_string_from_c`], etc. //! -use log::*; use std::{panic, thread}; mod error; @@ -263,7 +262,7 @@ where o } Err(e) => { - error!("Caught a panic calling rust code: {:?}", e); + log::error!("Caught a panic calling rust code: {:?}", e); if abort_on_panic { std::process::abort(); } @@ -325,14 +324,14 @@ fn init_backtraces_once() { // in the future. ("", 0) }; - error!("### Rust `panic!` hit at file '{}', line {}", file, line); + log::error!("### Rust `panic!` hit at file '{}', line {}", file, line); // We could use failure for failure::Backtrace (and we enable RUST_BACKTRACE // to opt-in to backtraces on failure errors if possible), however: // - we don't already have a failure dependency (one is likely inevitable, // and all our clients do, so this doesn't matter) // - `failure` only checks the RUST_BACKTRACE variable once, and we could have errors // before this. So we just use the backtrace crate directly. - error!(" Complete stack trace:\n{:?}", backtrace::Backtrace::new()); + log::error!(" Complete stack trace:\n{:?}", backtrace::Backtrace::new()); })); }); } diff --git a/components/support/ffi/src/string.rs b/components/support/ffi/src/string.rs index 20fecd73a7..365fd66da6 100644 --- a/components/support/ffi/src/string.rs +++ b/components/support/ffi/src/string.rs @@ -2,7 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use log::*; use std::ffi::{CStr, CString}; use std::os::raw::c_char; use std::ptr; @@ -111,7 +110,7 @@ pub unsafe fn opt_rust_str_from_c<'a>(c_string: *const c_char) -> Option<&'a str Err(e) => { // Currently I think this is impossible, so I'd like to know if it can happen // (Java/Swift shouldn't pass us invalid UTF-8... right?). - error!( + log::error!( "[Bug] Invalid UTF-8 was passed to rust! Report this! {:?}", e ); diff --git a/components/support/sql/src/conn_ext.rs b/components/support/sql/src/conn_ext.rs index 0a60c4f547..ce142653f9 100644 --- a/components/support/sql/src/conn_ext.rs +++ b/components/support/sql/src/conn_ext.rs @@ -2,7 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use log::*; use rusqlite::{ self, types::{FromSql, ToSql}, @@ -165,7 +164,7 @@ impl<'conn> UncheckedTransaction<'conn> { /// Consumes and commits an unchecked transaction. pub fn commit(self) -> SqlResult<()> { self.conn.execute_batch("COMMIT")?; - trace!("Transaction commited after {:?}", self.started_at.elapsed()); + log::trace!("Transaction commited after {:?}", self.started_at.elapsed()); Ok(()) } @@ -199,7 +198,7 @@ impl<'conn> Deref for UncheckedTransaction<'conn> { impl<'conn> Drop for UncheckedTransaction<'conn> { fn drop(&mut self) { if let Err(e) = self.finish_() { - warn!("Error dropping an unchecked transaction: {}", e); + log::warn!("Error dropping an unchecked transaction: {}", e); } } } diff --git a/fxa-client/src/ffi.rs b/fxa-client/src/ffi.rs index 9972980d41..c5cc641df7 100644 --- a/fxa-client/src/ffi.rs +++ b/fxa-client/src/ffi.rs @@ -19,7 +19,6 @@ use ffi_support::{ destroy_c_string, implement_into_ffi_by_pointer, opt_rust_string_to_c, rust_string_to_c, ErrorCode, ExternError, IntoFfi, }; -use log::*; use std::os::raw::c_char; pub mod error_codes { @@ -38,11 +37,11 @@ fn get_code(err: &Error) -> ErrorCode { ErrorKind::RemoteError { code: 401, .. } | ErrorKind::NotMarried | ErrorKind::NoCachedToken(_) => { - warn!("Authentication error: {:?}", err); + log::warn!("Authentication error: {:?}", err); ErrorCode::new(error_codes::AUTHENTICATION) } _ => { - warn!("Unexpected error: {:?}", err); + log::warn!("Unexpected error: {:?}", err); ErrorCode::new(error_codes::OTHER) } } diff --git a/fxa-client/src/lib.rs b/fxa-client/src/lib.rs index 2d596a904f..19b0d3cb2d 100644 --- a/fxa-client/src/lib.rs +++ b/fxa-client/src/lib.rs @@ -5,7 +5,6 @@ pub use crate::{config::Config, http_client::ProfileResponse as Profile}; use crate::{errors::*, http_client::Client, scoped_keys::ScopedKeysFlow, util::now}; use lazy_static::lazy_static; -use log::*; use ring::{ digest, rand::{SecureRandom, SystemRandom}, @@ -343,7 +342,7 @@ impl FirefoxAccount { } None => { if oauth_flow.scoped_keys_flow.is_some() { - error!("Expected to get keys back alongside the token but the server didn't send them."); + log::error!("Expected to get keys back alongside the token but the server didn't send them."); return Err(ErrorKind::TokenWithoutKeys.into()); } } @@ -353,7 +352,7 @@ impl FirefoxAccount { // don't want to return an over-scoped access token. // Let's be good citizens and destroy this access token. if let Err(err) = client.destroy_oauth_token(&resp.access_token) { - warn!("Access token destruction failure: {:?}", err); + log::warn!("Access token destruction failure: {:?}", err); } let refresh_token = match resp.refresh_token { Some(ref refresh_token) => refresh_token.clone(), @@ -363,7 +362,7 @@ impl FirefoxAccount { // we also destroy the existing refresh token. if let Some(ref old_refresh_token) = self.state.refresh_token { if let Err(err) = client.destroy_oauth_token(&old_refresh_token.token) { - warn!("Refresh token destruction failure: {:?}", err); + log::warn!("Refresh token destruction failure: {:?}", err); } } self.state.refresh_token = Some(RefreshToken { @@ -434,7 +433,7 @@ impl FirefoxAccount { None => match self.profile_cache { Some(ref cached_profile) => Ok(cached_profile.response.clone()), None => { - error!("Insane state! We got a 304 without having a cached response."); + log::error!("Insane state! We got a 304 without having a cached response."); Err(ErrorKind::UnrecoverableServerError.into()) } }, @@ -498,7 +497,7 @@ impl FirefoxAccount { let json = match self.to_json() { Ok(json) => json, Err(_) => { - error!("Error with to_json in persist_callback"); + log::error!("Error with to_json in persist_callback"); return; } }; diff --git a/fxa-client/src/login_sm.rs b/fxa-client/src/login_sm.rs index 0eaaeb1152..d1b4b26316 100644 --- a/fxa-client/src/login_sm.rs +++ b/fxa-client/src/login_sm.rs @@ -7,7 +7,6 @@ use crate::{ http_client::{browser_id::rsa::RSABrowserIDKeyPair, *}, util::{now, Xorable}, }; -use log::*; use serde_derive::*; pub struct LoginStateMachine<'a> { @@ -34,34 +33,34 @@ impl<'a> LoginStateMachine<'a> { } fn advance_one(&self, from: LoginState) -> LoginState { - info!("advancing from state {:?}", from); + log::info!("advancing from state {:?}", from); match from { LoginState::Married(state) => { let now = now(); - debug!("Checking key pair and certificate freshness."); + log::debug!("Checking key pair and certificate freshness."); if now > state.token_keys_and_key_pair.key_pair_expires_at { - info!("Key pair has expired. Transitioning to CohabitingBeforeKeyPair."); + log::info!("Key pair has expired. Transitioning to CohabitingBeforeKeyPair."); LoginState::CohabitingBeforeKeyPair( state.token_keys_and_key_pair.token_and_keys, ) } else if now > state.certificate_expires_at { - info!("Certificate has expired. Transitioning to CohabitingAfterKeyPair."); + log::info!("Certificate has expired. Transitioning to CohabitingAfterKeyPair."); LoginState::CohabitingAfterKeyPair(state.token_keys_and_key_pair) } else { - info!("Key pair and certificate are fresh; staying Married."); + log::info!("Key pair and certificate are fresh; staying Married."); LoginState::Married(state) // same } } LoginState::CohabitingBeforeKeyPair(state) => { - debug!("Generating key pair."); + log::debug!("Generating key pair."); let key_pair = match Client::key_pair(2048) { Ok(key_pair) => key_pair, Err(_) => { - error!("Failed to generate key pair! Transitioning to Separated."); + log::error!("Failed to generate key pair! Transitioning to Separated."); return LoginState::Separated(state.base); } }; - info!("Key pair generated! Transitioning to CohabitingAfterKeyPairState."); + log::info!("Key pair generated! Transitioning to CohabitingAfterKeyPairState."); let new_state = CohabitingAfterKeyPairState { token_and_keys: state, key_pair, @@ -70,13 +69,13 @@ impl<'a> LoginStateMachine<'a> { LoginState::CohabitingAfterKeyPair(new_state) } LoginState::CohabitingAfterKeyPair(state) => { - debug!("Signing public key."); + log::debug!("Signing public key."); let resp = self .client .sign(&state.token_and_keys.session_token, &state.key_pair); match resp { Ok(resp) => { - info!("Signed public key! Transitioning to Married."); + log::info!("Signed public key! Transitioning to Married."); let new_state = MarriedState { token_keys_and_key_pair: state, certificate: resp.certificate, @@ -86,10 +85,10 @@ impl<'a> LoginStateMachine<'a> { } Err(e) => { if let ErrorKind::RemoteError { .. } = e.kind() { - error!("Server error: {:?}. Transitioning to Separated.", e); + log::error!("Server error: {:?}. Transitioning to Separated.", e); LoginState::Separated(state.token_and_keys.base) } else { - error!( + log::error!( "Unknown error: ({:?}). Assuming transient, not transitioning.", e ); @@ -114,18 +113,18 @@ impl<'a> LoginStateMachine<'a> { same: F, state: ReadyForKeysState, ) -> LoginState { - debug!("Fetching keys."); + log::debug!("Fetching keys."); let resp = self.client.keys(&state.key_fetch_token); match resp { Ok(resp) => { let kb = match resp.wrap_kb.xored_with(&state.unwrap_kb) { Ok(kb) => kb, Err(_) => { - error!("Failed to unwrap keys response! Transitioning to Separated."); + log::error!("Failed to unwrap keys response! Transitioning to Separated."); return same(state); } }; - info!("Unwrapped keys response. Transition to CohabitingBeforeKeyPair."); + log::info!("Unwrapped keys response. Transition to CohabitingBeforeKeyPair."); let sync_key = Client::derive_sync_key(&kb); let xcs = Client::compute_client_state(&kb); LoginState::CohabitingBeforeKeyPair(TokenAndKeysState { @@ -137,15 +136,15 @@ impl<'a> LoginStateMachine<'a> { } Err(e) => match e.kind() { ErrorKind::RemoteError { errno: 104, .. } => { - warn!("Account not yet verified, not transitioning."); + log::warn!("Account not yet verified, not transitioning."); same(state) } ErrorKind::RemoteError { .. } => { - error!("Server error: {:?}. Transitioning to Separated.", e); + log::error!("Server error: {:?}. Transitioning to Separated.", e); LoginState::Separated(state.base) } _ => { - error!( + log::error!( "Unknown error: ({:?}). Assuming transient, not transitioning.", e ); diff --git a/logins-sql/examples/sync_pass_sql.rs b/logins-sql/examples/sync_pass_sql.rs index 583c67ec1b..c005e33ea7 100644 --- a/logins-sql/examples/sync_pass_sql.rs +++ b/logins-sql/examples/sync_pass_sql.rs @@ -8,7 +8,6 @@ use failure::Fail; use crate::sync::{KeyBundle, Sync15StorageClientInit}; use fxa_client::{AccessTokenInfo, Config, FirefoxAccount}; -use log::*; use logins_sql::{Login, PasswordEngine}; use prettytable::*; use std::collections::HashMap; @@ -35,9 +34,10 @@ fn load_fxa_creds(path: &str) -> Result { fn load_or_create_fxa_creds(path: &str, cfg: Config) -> Result { load_fxa_creds(path).or_else(|e| { - info!( + log::info!( "Failed to load existing FxA credentials from {:?} (error: {}), launching OAuth flow", - path, e + path, + e ); create_fxa_creds(path, cfg) }) @@ -48,7 +48,7 @@ fn create_fxa_creds(path: &str, cfg: Config) -> Result { let oauth_uri = acct.begin_oauth_flow(&[SYNC_SCOPE], true)?; if let Err(_) = webbrowser::open(&oauth_uri.as_ref()) { - warn!("Failed to open a web browser D:"); + log::warn!("Failed to open a web browser D:"); println!("Please visit this URL, sign in, and then copy-paste the final URL below."); println!("\n {}\n", oauth_uri); } else { @@ -123,7 +123,7 @@ fn read_login() -> Login { }; if let Err(e) = record.check_valid() { - warn!("Warning: produced invalid record: {}", e); + log::warn!("Warning: produced invalid record: {}", e); } record } @@ -181,7 +181,7 @@ fn update_login(record: &mut Login) { } if let Err(e) = record.check_valid() { - warn!("Warning: produced invalid record: {}", e); + log::warn!("Warning: produced invalid record: {}", e); } } @@ -308,7 +308,7 @@ fn prompt_record_id(e: &PasswordEngine, action: &str) -> Result> return Ok(None); }; if input >= index_to_id.len() { - info!("No such index"); + log::info!("No such index"); return Ok(None); } Ok(Some(index_to_id[input].clone())) @@ -365,9 +365,10 @@ fn main() -> Result<()> { .expect("Encryption key is not optional"); // Lets not log the encryption key, it's just not a good habit to be in. - debug!( + log::debug!( "Using credential file = {:?}, db = {:?}", - cred_file, db_path + cred_file, + db_path ); // TODO: allow users to use stage/etc. @@ -380,7 +381,7 @@ fn main() -> Result<()> { Ok(t) => t, Err(_) => { // The cached credentials did not have appropriate scope, sign in again. - warn!("Credentials do not have appropriate scope, launching OAuth flow."); + log::warn!("Credentials do not have appropriate scope, launching OAuth flow."); acct = create_fxa_creds(cred_file, cfg.clone())?; acct.get_access_token(SYNC_SCOPE)? } @@ -396,106 +397,106 @@ fn main() -> Result<()> { let engine = PasswordEngine::new(db_path, Some(encryption_key))?; - info!("Engine has {} passwords", engine.list()?.len()); + log::info!("Engine has {} passwords", engine.list()?.len()); if let Err(e) = show_all(&engine) { - warn!("Failed to show initial login data! {}", e); + log::warn!("Failed to show initial login data! {}", e); } loop { match prompt_chars("[A]dd, [D]elete, [U]pdate, [S]ync, [V]iew, [R]eset, [W]ipe, [T]ouch, E[x]ecute SQL Query, or [Q]uit").unwrap_or('?') { 'A' | 'a' => { - info!("Adding new record"); + log::info!("Adding new record"); let record = read_login(); if let Err(e) = engine.add(record) { - warn!("Failed to create record! {}", e); + log::warn!("Failed to create record! {}", e); } } 'D' | 'd' => { - info!("Deleting record"); + log::info!("Deleting record"); match prompt_record_id(&engine, "delete") { Ok(Some(id)) => { if let Err(e) = engine.delete(&id) { - warn!("Failed to delete record! {}", e); + log::warn!("Failed to delete record! {}", e); } } Err(e) => { - warn!("Failed to get record ID! {}", e); + log::warn!("Failed to get record ID! {}", e); } _ => {} } } 'U' | 'u' => { - info!("Updating record fields"); + log::info!("Updating record fields"); match prompt_record_id(&engine, "update") { Err(e) => { - warn!("Failed to get record ID! {}", e); + log::warn!("Failed to get record ID! {}", e); } Ok(Some(id)) => { let mut login = match engine.get(&id) { Ok(Some(login)) => login, Ok(None) => { - warn!("No such login!"); + log::warn!("No such login!"); continue } Err(e) => { - warn!("Failed to update record (get failed) {}", e); + log::warn!("Failed to update record (get failed) {}", e); continue; } }; update_login(&mut login); if let Err(e) = engine.update(login) { - warn!("Failed to update record! {}", e); + log::warn!("Failed to update record! {}", e); } } _ => {} } } 'R' | 'r' => { - info!("Resetting client."); + log::info!("Resetting client."); if let Err(e) = engine.db.reset() { - warn!("Failed to reset! {}", e); + log::warn!("Failed to reset! {}", e); } } 'W' | 'w' => { - info!("Wiping all data from client!"); + log::info!("Wiping all data from client!"); if let Err(e) = engine.db.wipe() { - warn!("Failed to wipe! {}", e); + log::warn!("Failed to wipe! {}", e); } } 'S' | 's' => { - info!("Syncing!"); + log::info!("Syncing!"); if let Err(e) = engine.sync(&client_init, &root_sync_key) { - warn!("Sync failed! {}", e); - warn!("BT: {:?}", e.backtrace()); + log::warn!("Sync failed! {}", e); + log::warn!("BT: {:?}", e.backtrace()); } else { - info!("Sync was successful!"); + log::info!("Sync was successful!"); } } 'V' | 'v' => { if let Err(e) = show_all(&engine) { - warn!("Failed to dump passwords? This is probably bad! {}", e); + log::warn!("Failed to dump passwords? This is probably bad! {}", e); } } 'T' | 't' => { - info!("Touching (bumping use count) for a record"); + log::info!("Touching (bumping use count) for a record"); match prompt_record_id(&engine, "update") { Err(e) => { - warn!("Failed to get record ID! {}", e); + log::warn!("Failed to get record ID! {}", e); } Ok(Some(id)) => { if let Err(e) = engine.touch(&id) { - warn!("Failed to touch record! {}", e); + log::warn!("Failed to touch record! {}", e); } } _ => {} } } 'x' | 'X' => { - info!("Running arbitrary SQL, there's no way this could go wrong!"); + log::info!("Running arbitrary SQL, there's no way this could go wrong!"); if let Some(sql) = prompt_string("SQL (one line only, press enter when done):\n") { if let Err(e) = show_sql(&engine, &sql) { - warn!("Failed to run sql query: {}", e); + log::warn!("Failed to run sql query: {}", e); } } } diff --git a/logins-sql/ffi/src/lib.rs b/logins-sql/ffi/src/lib.rs index e5c55d4248..74bb150874 100644 --- a/logins-sql/ffi/src/lib.rs +++ b/logins-sql/ffi/src/lib.rs @@ -6,7 +6,6 @@ use ffi_support::{ call_with_result, define_box_destructor, define_string_destructor, rust_str_from_c, rust_string_from_c, ExternError, }; -use log::*; use logins_sql::{Login, PasswordEngine, Result}; use std::os::raw::c_char; @@ -17,7 +16,7 @@ fn logging_init() { android_logger::Filter::default().with_min_level(log::Level::Trace), Some("liblogins_ffi"), ); - debug!("Android logging should be hooked up!") + log::debug!("Android logging should be hooked up!") } } @@ -28,7 +27,7 @@ pub unsafe extern "C" fn sync15_passwords_state_new( error: &mut ExternError, ) -> *mut PasswordEngine { logging_init(); - trace!("sync15_passwords_state_new"); + log::trace!("sync15_passwords_state_new"); call_with_result(error, || { let path = rust_str_from_c(db_path); let key = rust_str_from_c(encryption_key); @@ -50,7 +49,7 @@ pub unsafe extern "C" fn sync15_passwords_sync( tokenserver_url: *const c_char, error: &mut ExternError, ) { - trace!("sync15_passwords_sync"); + log::trace!("sync15_passwords_sync"); call_with_result(error, || -> Result<()> { state.sync( &sync15_adapter::Sync15StorageClientInit { @@ -69,7 +68,7 @@ pub unsafe extern "C" fn sync15_passwords_touch( id: *const c_char, error: &mut ExternError, ) { - trace!("sync15_passwords_touch"); + log::trace!("sync15_passwords_touch"); call_with_result(error, || state.touch(rust_str_from_c(id))) } @@ -79,19 +78,19 @@ pub unsafe extern "C" fn sync15_passwords_delete( id: *const c_char, error: &mut ExternError, ) -> u8 { - trace!("sync15_passwords_delete"); + log::trace!("sync15_passwords_delete"); call_with_result(error, || state.delete(rust_str_from_c(id))) } #[no_mangle] pub unsafe extern "C" fn sync15_passwords_wipe(state: &PasswordEngine, error: &mut ExternError) { - trace!("sync15_passwords_wipe"); + log::trace!("sync15_passwords_wipe"); call_with_result(error, || state.wipe()) } #[no_mangle] pub extern "C" fn sync15_passwords_reset(state: &PasswordEngine, error: &mut ExternError) { - trace!("sync15_passwords_reset"); + log::trace!("sync15_passwords_reset"); call_with_result(error, || state.reset()) } @@ -100,7 +99,7 @@ pub extern "C" fn sync15_passwords_get_all( state: &PasswordEngine, error: &mut ExternError, ) -> *mut c_char { - trace!("sync15_passwords_get_all"); + log::trace!("sync15_passwords_get_all"); call_with_result(error, || -> Result { let all_passwords = state.list()?; let result = serde_json::to_string(&all_passwords)?; @@ -114,7 +113,7 @@ pub unsafe extern "C" fn sync15_passwords_get_by_id( id: *const c_char, error: &mut ExternError, ) -> *mut c_char { - trace!("sync15_passwords_get_by_id"); + log::trace!("sync15_passwords_get_by_id"); call_with_result(error, || state.get(rust_str_from_c(id))) } @@ -124,7 +123,7 @@ pub unsafe extern "C" fn sync15_passwords_add( record_json: *const c_char, error: &mut ExternError, ) -> *mut c_char { - trace!("sync15_passwords_add"); + log::trace!("sync15_passwords_add"); call_with_result(error, || { let mut parsed: serde_json::Value = serde_json::from_str(rust_str_from_c(record_json))?; if parsed.get("id").is_none() { @@ -142,7 +141,7 @@ pub unsafe extern "C" fn sync15_passwords_update( record_json: *const c_char, error: &mut ExternError, ) { - trace!("sync15_passwords_update"); + log::trace!("sync15_passwords_update"); call_with_result(error, || { let parsed: Login = serde_json::from_str(rust_str_from_c(record_json))?; state.update(parsed) diff --git a/logins-sql/src/db.rs b/logins-sql/src/db.rs index 5c6ed90123..b547fce7d9 100644 --- a/logins-sql/src/db.rs +++ b/logins-sql/src/db.rs @@ -11,7 +11,6 @@ use crate::sync::{ use crate::update_plan::UpdatePlan; use crate::util; use lazy_static::lazy_static; -use log::*; use rusqlite::{ types::{FromSql, ToSql}, Connection, @@ -375,7 +374,7 @@ impl LoginDb { ], )?; if rows_changed == 0 { - error!( + log::error!( "Record {:?} already exists (use `update` to update records, not add)", login.id ); @@ -528,10 +527,10 @@ impl LoginDb { return Ok(()); } - debug!("No overlay; cloning one for {:?}.", guid); + log::debug!("No overlay; cloning one for {:?}.", guid); let changed = self.clone_mirror_to_overlay(guid)?; if changed == 0 { - error!("Failed to create local overlay for GUID {:?}.", guid); + log::error!("Failed to create local overlay for GUID {:?}.", guid); throw!(ErrorKind::NoSuchRecord(guid.to_owned())); } Ok(()) @@ -542,7 +541,7 @@ impl LoginDb { } pub fn reset(&self) -> Result<()> { - info!("Executing reset on password store!"); + log::info!("Executing reset on password store!"); self.execute_all(&[ &*CLONE_ENTIRE_MIRROR_SQL, "DELETE FROM loginsM", @@ -554,7 +553,7 @@ impl LoginDb { } pub fn wipe(&self) -> Result<()> { - info!("Executing wipe on password store!"); + log::info!("Executing wipe on password store!"); let now_ms = util::system_time_ms_i64(SystemTime::now()); self.execute( &format!( @@ -601,37 +600,38 @@ impl LoginDb { let mut plan = UpdatePlan::default(); for mut record in records { - debug!("Processing remote change {}", record.guid()); + log::debug!("Processing remote change {}", record.guid()); let upstream = if let Some(inbound) = record.inbound.0.take() { inbound } else { - debug!("Processing inbound deletion (always prefer)"); + log::debug!("Processing inbound deletion (always prefer)"); plan.plan_delete(record.guid.clone()); continue; }; let upstream_time = record.inbound.1; match (record.mirror.take(), record.local.take()) { (Some(mirror), Some(local)) => { - debug!(" Conflict between remote and local, Resolving with 3WM"); + log::debug!(" Conflict between remote and local, Resolving with 3WM"); plan.plan_three_way_merge(local, mirror, upstream, upstream_time, server_now); } (Some(_mirror), None) => { - debug!(" Forwarding mirror to remote"); + log::debug!(" Forwarding mirror to remote"); plan.plan_mirror_update(upstream, upstream_time); } (None, Some(local)) => { - debug!(" Conflicting record without shared parent, using newer"); + log::debug!(" Conflicting record without shared parent, using newer"); plan.plan_two_way_merge(&local.login, (upstream, upstream_time)); } (None, None) => { if let Some(dupe) = self.find_dupe(&upstream)? { - debug!( + log::debug!( " Incoming recordĀ {} was is a dupe of local record {}", - upstream.id, dupe.id + upstream.id, + dupe.id ); plan.plan_two_way_merge(&dupe, (upstream, upstream_time)); } else { - debug!(" No dupe found, inserting into mirror"); + log::debug!(" No dupe found, inserting into mirror"); plan.plan_mirror_insert(upstream, upstream_time, false); } } @@ -696,7 +696,7 @@ impl LoginDb { } fn set_last_sync(&self, last_sync: ServerTimestamp) -> Result<()> { - debug!("Updating last sync to {}", last_sync); + log::debug!("Updating last sync to {}", last_sync); let last_sync_millis = last_sync.as_millis() as i64; self.put_meta(schema::LAST_SYNC_META_KEY, &last_sync_millis) } diff --git a/logins-sql/src/ffi.rs b/logins-sql/src/ffi.rs index 211ba462e1..01806b8dac 100644 --- a/logins-sql/src/ffi.rs +++ b/logins-sql/src/ffi.rs @@ -10,7 +10,6 @@ use crate::{Error, ErrorKind, Login, PasswordEngine}; use ffi_support::{ implement_into_ffi_by_json, implement_into_ffi_by_pointer, ErrorCode, ExternError, }; -use log::*; use sync::ErrorKind as Sync15ErrorKind; pub mod error_codes { @@ -44,7 +43,7 @@ pub mod error_codes { fn get_code(err: &Error) -> ErrorCode { match err.kind() { ErrorKind::SyncAdapterError(e) => { - error!("Sync error {:?}", e); + log::error!("Sync error {:?}", e); match e.kind() { Sync15ErrorKind::TokenserverHttpError(401) => { ErrorCode::new(error_codes::AUTH_INVALID) @@ -54,15 +53,15 @@ fn get_code(err: &Error) -> ErrorCode { } } ErrorKind::DuplicateGuid(id) => { - error!("Guid already exists: {}", id); + log::error!("Guid already exists: {}", id); ErrorCode::new(error_codes::DUPLICATE_GUID) } ErrorKind::NoSuchRecord(id) => { - error!("No record exists with id {}", id); + log::error!("No record exists with id {}", id); ErrorCode::new(error_codes::NO_SUCH_RECORD) } ErrorKind::InvalidLogin(desc) => { - error!("Invalid login: {}", desc); + log::error!("Invalid login: {}", desc); ErrorCode::new(error_codes::INVALID_LOGIN) } // We can't destructure `err` without bringing in the libsqlite3_sys crate @@ -70,11 +69,11 @@ fn get_code(err: &Error) -> ErrorCode { ErrorKind::SqlError(rusqlite::Error::SqliteFailure(err, _)) if err.code == rusqlite::ErrorCode::NotADatabase => { - error!("Not a database / invalid key error"); + log::error!("Not a database / invalid key error"); ErrorCode::new(error_codes::INVALID_KEY) } err => { - error!("Unexpected error: {:?}", err); + log::error!("Unexpected error: {:?}", err); ErrorCode::new(error_codes::UNEXPECTED) } } diff --git a/logins-sql/src/login.rs b/logins-sql/src/login.rs index 082ec34ffe..6d4e898ec0 100644 --- a/logins-sql/src/login.rs +++ b/logins-sql/src/login.rs @@ -5,7 +5,6 @@ use crate::error::*; use crate::sync::{self, ServerTimestamp}; use crate::util; -use log::*; use rusqlite::Row; use serde_derive::*; use std::time::{self, SystemTime}; @@ -326,7 +325,7 @@ macro_rules! merge_field { ($merged:ident, $b:ident, $prefer_b:expr, $field:ident) => { if let Some($field) = $b.$field.take() { if $merged.$field.is_some() { - warn!("Collision merging login field {}", stringify!($field)); + log::warn!("Collision merging login field {}", stringify!($field)); if $prefer_b { $merged.$field = Some($field); } diff --git a/logins-sql/src/schema.rs b/logins-sql/src/schema.rs index 258a7b11e1..ef7854ed64 100644 --- a/logins-sql/src/schema.rs +++ b/logins-sql/src/schema.rs @@ -91,7 +91,6 @@ use crate::db; use crate::error::*; use lazy_static::lazy_static; -use log::*; use sql_support::ConnExt; /// Note that firefox-ios is currently on version 3. Version 4 is this version, @@ -239,10 +238,11 @@ pub(crate) fn init(db: &db::LoginDb) -> Result<()> { if user_version < VERSION { upgrade(db, user_version)?; } else { - warn!( + log::warn!( "Loaded future schema version {} (we only understand version {}). \ Optimisitically ", - user_version, VERSION + user_version, + VERSION ) } } @@ -251,7 +251,7 @@ pub(crate) fn init(db: &db::LoginDb) -> Result<()> { // https://github.com/mozilla-mobile/firefox-ios/blob/master/Storage/SQL/LoginsSchema.swift#L100 fn upgrade(db: &db::LoginDb, from: i64) -> Result<()> { - debug!("Upgrading schema from {} to {}", from, VERSION); + log::debug!("Upgrading schema from {} to {}", from, VERSION); if from == VERSION { return Ok(()); } @@ -282,7 +282,7 @@ fn upgrade(db: &db::LoginDb, from: i64) -> Result<()> { } pub(crate) fn create(db: &db::LoginDb) -> Result<()> { - debug!("Creating schema"); + log::debug!("Creating schema"); db.execute_all(&[ &*CREATE_LOCAL_TABLE_SQL, &*CREATE_MIRROR_TABLE_SQL, @@ -295,7 +295,7 @@ pub(crate) fn create(db: &db::LoginDb) -> Result<()> { } pub(crate) fn drop(db: &db::LoginDb) -> Result<()> { - debug!("Dropping schema"); + log::debug!("Dropping schema"); db.execute_all(&[ "DROP TABLE IF EXISTS loginsM", "DROP TABLE IF EXISTS loginsL", diff --git a/logins-sql/src/update_plan.rs b/logins-sql/src/update_plan.rs index bddcc83fe4..ca94f633cc 100644 --- a/logins-sql/src/update_plan.rs +++ b/logins-sql/src/update_plan.rs @@ -6,7 +6,6 @@ use crate::error::*; use crate::login::{LocalLogin, Login, MirrorLogin, SyncStatus}; use crate::sync::ServerTimestamp; use crate::util; -use log::*; use rusqlite::{types::ToSql, Connection}; use std::time::SystemTime; @@ -117,7 +116,7 @@ impl UpdatePlan { "; let mut stmt = conn.prepare_cached(sql)?; for (login, timestamp) in &self.mirror_updates { - trace!("Updating mirror {:?}", login.guid_str()); + log::trace!("Updating mirror {:?}", login.guid_str()); stmt.execute_named(&[ (":server_modified", timestamp as &ToSql), (":http_realm", &login.http_realm as &ToSql), @@ -182,7 +181,7 @@ impl UpdatePlan { let mut stmt = conn.prepare_cached(&sql)?; for (login, timestamp, is_overridden) in &self.mirror_inserts { - trace!("Inserting mirror {:?}", login.guid_str()); + log::trace!("Inserting mirror {:?}", login.guid_str()); stmt.execute_named(&[ (":is_overridden", is_overridden as &ToSql), (":server_modified", timestamp as &ToSql), @@ -229,7 +228,7 @@ impl UpdatePlan { // XXX OutgoingChangeset should no longer have timestamp. let local_ms: i64 = util::system_time_ms_i64(SystemTime::now()); for l in &self.local_updates { - trace!("Updating local {:?}", l.guid_str()); + log::trace!("Updating local {:?}", l.guid_str()); stmt.execute_named(&[ (":local_modified", &local_ms as &ToSql), (":http_realm", &l.login.http_realm as &ToSql), @@ -252,13 +251,13 @@ impl UpdatePlan { } pub fn execute(&self, conn: &Connection) -> Result<()> { - debug!("UpdatePlan: deleting records..."); + log::debug!("UpdatePlan: deleting records..."); self.perform_deletes(conn)?; - debug!("UpdatePlan: Updating existing mirror records..."); + log::debug!("UpdatePlan: Updating existing mirror records..."); self.perform_mirror_updates(conn)?; - debug!("UpdatePlan: Inserting new mirror records..."); + log::debug!("UpdatePlan: Inserting new mirror records..."); self.perform_mirror_inserts(conn)?; - debug!("UpdatePlan: Updating reconciled local records..."); + log::debug!("UpdatePlan: Updating reconciled local records..."); self.perform_local_updates(conn)?; Ok(()) } diff --git a/sync15-adapter/src/bso_record.rs b/sync15-adapter/src/bso_record.rs index ea941d07c2..d9ff19a6e0 100644 --- a/sync15-adapter/src/bso_record.rs +++ b/sync15-adapter/src/bso_record.rs @@ -6,7 +6,6 @@ use crate::error; use crate::key_bundle::KeyBundle; use crate::util::ServerTimestamp; use lazy_static::lazy_static; -use log::*; use serde::de::{Deserialize, DeserializeOwned}; use serde::ser::Serialize; use serde_derive::*; @@ -261,10 +260,11 @@ impl Payload { // This is a little dubious, but it seems like if we have a e.g. `sortindex` field on the payload // it's going to be a bug if we use it instead of the "real" sort index. if self.data.contains_key(name) { - warn!( + log::warn!( "Payload for record {} already contains 'automatic' field \"{}\"? \ Overwriting with 'real' value", - self.id, name + self.id, + name ); } @@ -283,9 +283,10 @@ impl Payload { match serde_json::from_value(v) { Ok(v) => Some(v), Err(e) => { - error!( + log::error!( "Automatic field {} exists on payload, but cannot be deserialized: {}", - name, e + name, + e ); None } diff --git a/sync15-adapter/src/client.rs b/sync15-adapter/src/client.rs index cb1868aac2..b51a478298 100644 --- a/sync15-adapter/src/client.rs +++ b/sync15-adapter/src/client.rs @@ -12,7 +12,6 @@ use crate::request::{ use crate::token; use crate::util::ServerTimestamp; use hyper::Method; -use log::*; use reqwest::{ header::{self, HeaderValue, ACCEPT, AUTHORIZATION}, Client, Request, Response, Url, @@ -68,7 +67,7 @@ impl SetupStorageClient for Sync15StorageClient { }?; // Note: meta/global is not encrypted! let meta_global: BsoRecord = resp.json()?; - info!("Meta global: {:?}", meta_global.payload); + log::info!("Meta global: {:?}", meta_global.payload); Ok(meta_global) } @@ -166,14 +165,14 @@ impl Sync15StorageClient { } fn exec_request(&self, req: Request, require_success: bool) -> error::Result { - trace!("request: {} {}", req.method(), req.url().path()); + log::trace!("request: {} {}", req.method(), req.url().path()); let resp = self.http_client.execute(req)?; - trace!("response: {}", resp.status()); + log::trace!("response: {}", resp.status()); self.update_timestamp(resp.headers()); if require_success && !resp.status().is_success() { - warn!( + log::warn!( "HTTP error {} ({}) during storage request to {}", resp.status().as_u16(), resp.status(), @@ -219,7 +218,7 @@ impl Sync15StorageClient { self.timestamp.set(ts); } else { // Should we complain more here? - warn!("No X-Weave-Timestamp from storage server!"); + log::warn!("No X-Weave-Timestamp from storage server!"); } } diff --git a/sync15-adapter/src/key_bundle.rs b/sync15-adapter/src/key_bundle.rs index 0e1e1ab3e3..716d601096 100644 --- a/sync15-adapter/src/key_bundle.rs +++ b/sync15-adapter/src/key_bundle.rs @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::error::{ErrorKind, Result}; -use log::*; use openssl::hash::MessageDigest; use openssl::pkey::PKey; use openssl::sign::Signer; @@ -21,11 +20,11 @@ impl KeyBundle { /// Panics (asserts) if they aren't both 32 bytes. pub fn new(enc: Vec, mac: Vec) -> Result { if enc.len() != 32 { - error!("Bad key length (enc_key): {} != 32", enc.len()); + log::error!("Bad key length (enc_key): {} != 32", enc.len()); return Err(ErrorKind::BadKeyLength("enc_key", enc.len(), 32).into()); } if mac.len() != 32 { - error!("Bad key length (mac_key): {} != 32", mac.len()); + log::error!("Bad key length (mac_key): {} != 32", mac.len()); return Err(ErrorKind::BadKeyLength("mac_key", mac.len(), 32).into()); } Ok(KeyBundle { @@ -42,7 +41,7 @@ impl KeyBundle { pub fn from_ksync_bytes(ksync: &[u8]) -> Result { if ksync.len() != 64 { - error!("Bad key length (kSync): {} != 64", ksync.len()); + log::error!("Bad key length (kSync): {} != 64", ksync.len()); return Err(ErrorKind::BadKeyLength("kSync", ksync.len(), 64).into()); } Ok(KeyBundle { @@ -110,7 +109,7 @@ impl KeyBundle { // Note: openssl::memcmp::eq panics if the sizes aren't the same. Desktop returns that it // was a verification failure, so we will too. if expected_hmac.len() != 64 { - warn!("Garbage HMAC verification string: Wrong length"); + log::warn!("Garbage HMAC verification string: Wrong length"); return Ok(false); } // Decode the expected_hmac into bytes to avoid issues if a client happens to encode @@ -119,7 +118,7 @@ impl KeyBundle { let mut decoded_hmac = [0u8; 32]; if let Err(_) = base16::decode_slice(expected_hmac, &mut decoded_hmac) { - warn!("Garbage HMAC verification string: contained non base16 characters"); + log::warn!("Garbage HMAC verification string: contained non base16 characters"); return Ok(false); } diff --git a/sync15-adapter/src/request.rs b/sync15-adapter/src/request.rs index b4fda57acc..f0be824dc7 100644 --- a/sync15-adapter/src/request.rs +++ b/sync15-adapter/src/request.rs @@ -6,7 +6,6 @@ use crate::bso_record::EncryptedBso; use crate::error::{self, ErrorKind, Result}; use crate::util::ServerTimestamp; use hyper::StatusCode; -use log::*; use reqwest::Response; use serde_derive::*; use std::collections::HashMap; @@ -383,7 +382,7 @@ impl NormalResponseHandler { impl PostResponseHandler for NormalResponseHandler { fn handle_response(&mut self, r: PostResponse, mid_batch: bool) -> error::Result<()> { if !r.status.is_success() { - warn!("Got failure status from server while posting: {}", r.status); + log::warn!("Got failure status from server while posting: {}", r.status); if r.status == StatusCode::PRECONDITION_FAILED { return Err(ErrorKind::BatchInterrupted.into()); } else { @@ -450,7 +449,7 @@ where || self.batch_limits.can_never_add(payload_length) || payload_length >= self.max_payload_bytes { - warn!( + log::warn!( "Single record too large to submit to server ({} b)", payload_length ); @@ -487,7 +486,7 @@ where if item_len >= self.max_request_bytes { self.queued.truncate(item_start); - warn!( + log::warn!( "Single record too large to submit to server ({} b)", item_len ); @@ -499,9 +498,11 @@ where let can_send_record = self.queued.len() < self.max_request_bytes; if !can_post_record || !can_send_record || !can_batch_record { - debug!( + log::debug!( "PostQueue flushing! (can_post = {}, can_send = {}, can_batch = {})", - can_post_record, can_send_record, can_batch_record + can_post_record, + can_send_record, + can_batch_record ); // "unwrite" the record. self.queued.truncate(item_start); @@ -539,7 +540,7 @@ where &BatchState::InBatch(ref s) => Some(s.clone()), }; - info!( + log::info!( "Posting {} records of {} bytes", self.post_limits.cur_records, self.queued.len() @@ -563,7 +564,7 @@ where if !resp.status.is_success() { let code = resp.status.as_u16(); self.on_response.handle_response(resp, !want_commit)?; - error!("Bug: expected OnResponse to have bailed out!"); + log::error!("Bug: expected OnResponse to have bailed out!"); // Should we assert here instead? return Err(ErrorKind::StorageHttpError { code, @@ -577,7 +578,7 @@ where } if want_commit { - debug!("Committed batch {:?}", self.batch); + log::debug!("Committed batch {:?}", self.batch); self.batch = BatchState::NoBatch; self.on_response.handle_response(resp, false)?; return Ok(()); @@ -608,7 +609,7 @@ where match &self.batch { &BatchState::Unsupported => { - warn!("Server changed it's mind about supporting batching mid-batch..."); + log::warn!("Server changed it's mind about supporting batching mid-batch..."); } &BatchState::InBatch(ref cur_id) => { diff --git a/sync15-adapter/src/sync.rs b/sync15-adapter/src/sync.rs index 37fb4bd391..3fc6eacb40 100644 --- a/sync15-adapter/src/sync.rs +++ b/sync15-adapter/src/sync.rs @@ -8,7 +8,6 @@ use crate::error::Error; use crate::request::CollectionRequest; use crate::state::GlobalState; use crate::util::ServerTimestamp; -use log::*; /// Low-level store functionality. Stores that need custom reconciliation logic should use this. /// @@ -47,13 +46,13 @@ pub fn synchronize( fully_atomic: bool, ) -> Result<(), Error> { let collection = store.collection_name(); - info!("Syncing collection {}", collection); + log::info!("Syncing collection {}", collection); let collection_request = store.get_collection_request()?; let incoming_changes = IncomingChangeset::fetch(client, state, collection.into(), &collection_request)?; let last_changed_remote = incoming_changes.timestamp; - info!( + log::info!( "Downloaded {} remote changes", incoming_changes.changes.len() ); @@ -61,11 +60,11 @@ pub fn synchronize( outgoing.timestamp = last_changed_remote; - info!("Uploading {} outgoing changes", outgoing.changes.len()); + log::info!("Uploading {} outgoing changes", outgoing.changes.len()); let upload_info = CollectionUpdate::new_from_changeset(client, state, outgoing, fully_atomic)?.upload()?; - info!( + log::info!( "Upload success ({} records success, {} records failed)", upload_info.successful_ids.len(), upload_info.failed_ids.len() @@ -73,6 +72,6 @@ pub fn synchronize( store.sync_finished(upload_info.modified_timestamp, &upload_info.successful_ids)?; - info!("Sync finished!"); + log::info!("Sync finished!"); Ok(()) } diff --git a/sync15-adapter/src/sync_multiple.rs b/sync15-adapter/src/sync_multiple.rs index d422552c52..d836c8d63e 100644 --- a/sync15-adapter/src/sync_multiple.rs +++ b/sync15-adapter/src/sync_multiple.rs @@ -10,7 +10,6 @@ use crate::error::Error; use crate::key_bundle::KeyBundle; use crate::state::{GlobalState, SetupStateMachine}; use crate::sync::{self, Store}; -use log::*; use std::cell::Cell; use std::collections::HashMap; use std::result; @@ -61,7 +60,7 @@ pub fn sync_multiple( _ => { // Don't log the error since it might contain sensitive // info like keys (the JSON does, after all). - error!("Failed to parse GlobalState from JSON! Falling back to default"); + log::error!("Failed to parse GlobalState from JSON! Falling back to default"); None } } @@ -72,7 +71,7 @@ pub fn sync_multiple( let mut global_state = match maybe_global { Some(g) => g, None => { - info!("First time through since unlock. Creating default global state."); + log::info!("First time through since unlock. Creating default global state."); last_client_info.replace(None); GlobalState::default() } @@ -104,7 +103,7 @@ pub fn sync_multiple( // Scope borrow of `sync_info.client` let mut state_machine = SetupStateMachine::for_full_sync(&client_info.client, &root_sync_key); - info!("Advancing state machine to ready (full)"); + log::info!("Advancing state machine to ready (full)"); global_state = state_machine.to_ready(global_state)?; } @@ -114,7 +113,7 @@ pub fn sync_multiple( .engines_that_need_local_reset() .contains(store.collection_name()) { - info!( + log::info!( "{} sync ID changed; engine needs local reset", store.collection_name() ); @@ -125,20 +124,20 @@ pub fn sync_multiple( let mut failures: HashMap = HashMap::new(); for store in stores { let name = store.collection_name(); - info!("Syncing {} engine!", name); + log::info!("Syncing {} engine!", name); let result = sync::synchronize(&client_info.client, &global_state, *store, true); match result { - Ok(()) => info!("Sync of {} was successful!", name), + Ok(()) => log::info!("Sync of {} was successful!", name), Err(e) => { - warn!("Sync of {} failed! {:?}", name, e); + log::warn!("Sync of {} failed! {:?}", name, e); failures.insert(name.into(), e.into()); } } } - info!("Updating persisted global state"); + log::info!("Updating persisted global state"); persisted_global_state.replace(Some(global_state.to_persistable_string())); last_client_info.replace(Some(client_info)); diff --git a/sync15-adapter/src/token.rs b/sync15-adapter/src/token.rs index 81606370a7..2109628fb9 100644 --- a/sync15-adapter/src/token.rs +++ b/sync15-adapter/src/token.rs @@ -5,7 +5,6 @@ use crate::error::{self, ErrorKind, Result}; use crate::util::ServerTimestamp; use hyper::header::AUTHORIZATION; -use log::*; use reqwest::{Client, Request, Url}; use serde_derive::*; use std::borrow::{Borrow, Cow}; @@ -81,9 +80,9 @@ impl TokenFetcher for TokenServerFetcher { .send()?; if !resp.status().is_success() { - warn!("Non-success status when fetching token: {}", resp.status()); + log::warn!("Non-success status when fetching token: {}", resp.status()); // TODO: the body should be JSON and contain a status parameter we might need? - debug!( + log::debug!( " Response body {}", resp.text().unwrap_or_else(|_| "???".into()) ); @@ -265,9 +264,10 @@ impl TokenProviderImpl { if prev == tc.token.api_endpoint { TokenState::Token(tc) } else { - warn!( + log::warn!( "api_endpoint changed from {} to {}", - prev, tc.token.api_endpoint + prev, + tc.token.api_endpoint ); TokenState::NodeReassigned } @@ -311,7 +311,7 @@ impl TokenProviderImpl { } TokenState::Backoff(ref until, ref existing_endpoint) => { if let Ok(remaining) = until.duration_since(self.fetcher.now()) { - debug!("enforcing existing backoff - {:?} remains", remaining); + log::debug!("enforcing existing backoff - {:?} remains", remaining); None } else { // backoff period is over From 906c2b952ea92807490a9588a71fb2b29e4233f1 Mon Sep 17 00:00:00 2001 From: Edouard Oger Date: Tue, 11 Dec 2018 19:30:31 -0500 Subject: [PATCH 9/9] Bump ffi-support version --- components/support/ffi/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/support/ffi/Cargo.toml b/components/support/ffi/Cargo.toml index ae05e801e2..6c710184ae 100644 --- a/components/support/ffi/Cargo.toml +++ b/components/support/ffi/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "ffi-support" edition = "2018" -version = "0.1.1" +version = "0.1.2" authors = ["Thom Chiovoloni "] description = "A crate to help expose Rust functions over the FFI." repository = "https://github.com/mozilla/application-services"