Bug 1677073 - Update in-tree version of env_logger. r=janerik

Also update plist to avoid pulling a duplicate humantime version.

Differential Revision: https://phabricator.services.mozilla.com/D96995
This commit is contained in:
Emilio Cobos Álvarez 2020-11-19 14:03:43 +00:00
parent 47e3ae93eb
commit 5716498fbd
61 changed files with 331 additions and 4361 deletions

38
Cargo.lock generated
View File

@ -217,7 +217,7 @@ dependencies = [
"bindgen",
"cranelift-codegen",
"cranelift-wasm",
"env_logger 0.6.2",
"env_logger",
"log",
"smallvec",
]
@ -1297,9 +1297,9 @@ dependencies = [
[[package]]
name = "env_logger"
version = "0.6.2"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aafcde04e90a5226a6443b7aabdb016ba2f8307c847d524724bd9b346dd1a2d3"
checksum = "f26ecb66b4bdca6c1409b40fb255eefc2bd4f6d135dab3c3124f80ffa2a9661e"
dependencies = [
"atty",
"humantime",
@ -1308,15 +1308,6 @@ dependencies = [
"termcolor",
]
[[package]]
name = "env_logger"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54532e3223c5af90a6a757c90b5c5521564b07e5e7a958681bcd2afad421cdcd"
dependencies = [
"log",
]
[[package]]
name = "error-chain"
version = "0.11.0"
@ -1748,7 +1739,7 @@ name = "gecko_logger"
version = "0.1.0"
dependencies = [
"app_services_logger",
"env_logger 0.6.2",
"env_logger",
"lazy_static",
"log",
]
@ -2342,12 +2333,9 @@ checksum = "e8734b0cfd3bc3e101ec59100e101c2eecd19282202e87808b3037b442777a83"
[[package]]
name = "humantime"
version = "1.3.0"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f"
dependencies = [
"quick-error",
]
checksum = "3c1ad908cc71012b7bea4d0c53ba96a8cba9962f048fa68d143376143d863b7a"
[[package]]
name = "hyper"
@ -2528,7 +2516,7 @@ version = "0.1.4"
dependencies = [
"bindgen",
"cmake",
"env_logger 0.6.2",
"env_logger",
"glob",
"lazy_static",
"libc",
@ -3326,7 +3314,7 @@ version = "0.4.16"
source = "git+https://github.com/mozilla/neqo?tag=v0.4.16#1b0664a1e2b3ac59a5c919d32ddc284dc57634e6"
dependencies = [
"chrono",
"env_logger 0.8.1",
"env_logger",
"lazy_static",
"log",
"qlog",
@ -3642,7 +3630,7 @@ version = "0.1.4"
dependencies = [
"byteorder",
"core-foundation",
"env_logger 0.6.2",
"env_logger",
"lazy_static",
"libloading 0.5.2",
"log",
@ -3886,9 +3874,9 @@ dependencies = [
[[package]]
name = "plist"
version = "0.5.1"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31850d149352e2b75f0e4b206045ee3775076c422892328343beca48a2b5cf17"
checksum = "50ce7c785e06e3a9e6f546c1a30d3d59111a31a21bc294fb1496241a572c9a00"
dependencies = [
"base64 0.10.1",
"humantime",
@ -4732,7 +4720,7 @@ name = "smoosh"
version = "0.1.0"
dependencies = [
"bumpalo",
"env_logger 0.6.2",
"env_logger",
"jsparagus",
"log",
]
@ -4932,7 +4920,7 @@ dependencies = [
"atomic_refcell",
"cssparser",
"cstr",
"env_logger 0.6.2",
"env_logger",
"geckoservo",
"libc",
"log",

View File

@ -6,7 +6,7 @@ build = "build.rs"
license = "MPL-2.0"
[build-dependencies]
env_logger = {version = "0.6", default-features = false} # disable `regex` to reduce code size
env_logger = {version = "0.8", default-features = false} # disable `regex` to reduce code size
bindgen = {version = "0.53", default-features = false, features = ["runtime"]} # disable `logging` to reduce code size
cmake = "0.1"
glob = "0.3"

View File

@ -10,7 +10,7 @@ bumpalo = "3.4.0"
log = "0.4"
# Setup RUST_LOG logging.
# Disable regex feature for code size.
env_logger = {version = "0.6", default-features = false}
env_logger = {version = "0.8", default-features = false}
# For non-jsparagus developers.
jsparagus = { git = "https://github.com/mozilla-spidermonkey/jsparagus", rev = "1dc60327164a3f64f87180147b1f3a2a9cc74276" }
# For local development, replace above with

View File

@ -16,7 +16,7 @@ name = "baldrdash"
cranelift-codegen = { version = "0.67.0", default-features = false }
cranelift-wasm = { version = "0.67.0" }
log = { version = "0.4.6", default-features = false, features = ["release_max_level_info"] }
env_logger = "0.6"
env_logger = "0.8"
smallvec = "1.0"
[build-dependencies]

View File

@ -9,7 +9,7 @@ license = "MPL-2.0"
[dependencies]
byteorder = "1.3"
env_logger = {version = "0.6", default-features = false } # disable `regex` to reduce code size
env_logger = {version = "0.8", default-features = false } # disable `regex` to reduce code size
lazy_static = "1"
log = "0.4"
pkcs11 = "0.4"

View File

@ -13,7 +13,7 @@ doctest = false
atomic_refcell = "0.1"
cssparser = "0.27"
cstr = "0.1.2"
env_logger = { version = "0.6", default-features = false }
env_logger = { version = "0.8", default-features = false }
geckoservo = {path = "../../../ports/geckolib"}
libc = "0.2"
log = {version = "0.4", features = ["release_max_level_info"]}

View File

@ -1 +0,0 @@
{"files":{"CHANGELOG.md":"7c044d74477515ab39287a4caff27eb96daebaed8b9f9b6a1d1c081a7b42d4a7","Cargo.lock":"132c1f881b80a79314567a6993141c6204495fec144cdcec1729f2a3e0fec18b","Cargo.toml":"b60137f1fd54001ca4d8be1d0bbec154225a44c8f4fa3576078bdad55216d357","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"0e231c1c4ad51ff0239062297bdaa69aeb34a8692e3f814188ce1e0ade8583d5","examples/custom_default_format.rs":"799c439f61cb711078f8aa584db537a5758c25b90d44767849dae2ad3822885c","examples/custom_format.rs":"ac8323e2febf8b8ff7238bd254fbbbfb3183da5af84f7f3a261fd9ad892c9ab6","examples/custom_logger.rs":"99fb3c9761ad4c5fe73f4ec2a2bd44b4acf6d1f7b7cfaa16bf0373665d3e2a4b","examples/default.rs":"ac96427611784d310704f738c7a29ebddd7930c8a70ad3c464c4d3eae4cf74a3","examples/direct_logger.rs":"549f6a10e0903d06aca2cc7ba82415b07a23392676101c9bc7aa72b4a9b0b9e2","examples/filters_from_code.rs":"84bd82803683d19ae96f85edcf4ee38cda028c2dbde923dddecc8563453b18e2","src/filter/mod.rs":"de471579c5db400c5ed11b9d7c9fc62686068b42798c58f7165806319ab7ec09","src/filter/regex.rs":"5fff47d1d4d0aa3f2bab90636127d3e72aebf800c3b78faba99637220ffdf865","src/filter/string.rs":"52bbd047c31a1afdb3cd1c11629b956f21b3f47bf22e06421baf3d693a045e59","src/fmt/humantime/extern_impl.rs":"cd2538e7a03fd3ad6c843af3c3d4016ca96cadaefee32cf9b37329c4787e6552","src/fmt/humantime/mod.rs":"408496eb21344c654b9e06da2a2df86de56e427147bb7f7b47851e0da976c003","src/fmt/humantime/shim_impl.rs":"7c2fdf4031f5568b716df14842b0d32bc03ff398763f4849960df7f9632a5bb2","src/fmt/mod.rs":"5104dad2fd14bc18ab6ab46e7c2bc5752b509d9fc934fb99f0ebc126728f8f04","src/fmt/writer/atty.rs":"3e9fd61d291d0919f7aa7119a26dd15d920df8783b4ae57bcf2c3cb6f3ff06b5","src/fmt/writer/mod.rs":"583f6616e0cf21955a530baa332fb7a99bf4fcd418a2367bbd1e733a06a22318","src/fmt/writer/termcolor/extern_impl.rs":"15e048be128568abcdd0ce99dafffe296df26131d4aa05921585761d31c11db5","src/fmt/writer/termcolor/mod.rs":"a3cf956aec030e0f940e4eaefe58d7703857eb900022286e328e05e5f61de183","src/fmt/writer/termcolor/shim_impl.rs":"bdd479c4e933b14ba02a3c1a9fe30eb51bcdf600e23cebd044d68683fdaad037","src/lib.rs":"2c5ab92ee141022f3e657b0f81e84e5ee4e7fad9fb648204e00ed4fb03d4166f","tests/init-twice-retains-filter.rs":"00524ce0f6779981b695bad1fdd244f87b76c126aeccd8b4ff77ef9e6325478b","tests/log-in-log.rs":"41126910998adfbac771c2a1237fecbc5437344f8e4dfc2f93235bab764a087e","tests/regexp_filter.rs":"44aa6c39de894be090e37083601e501cfffb15e3c0cd36209c48abdf3e2cb120"},"package":"aafcde04e90a5226a6443b7aabdb016ba2f8307c847d524724bd9b346dd1a2d3"}

View File

@ -1,3 +0,0 @@
Changes to this crate are tracked via [GitHub Releases][releases].
[releases]: https://github.com/sebasmagri/env_logger/releases

View File

@ -1,212 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "aho-corasick"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"memchr 2.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "atty"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.40 (registry+https://github.com/rust-lang/crates.io-index)",
"termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "cfg-if"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "env_logger"
version = "0.6.2"
dependencies = [
"atty 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"humantime 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"termcolor 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "humantime"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "lazy_static"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "libc"
version = "0.2.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "log"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "memchr"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.40 (registry+https://github.com/rust-lang/crates.io-index)",
"version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "quick-error"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "redox_syscall"
version = "0.1.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "redox_termios"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"redox_syscall 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "regex"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"aho-corasick 0.6.9 (registry+https://github.com/rust-lang/crates.io-index)",
"memchr 2.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"regex-syntax 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
"thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
"utf8-ranges 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "regex-syntax"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"ucd-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "termcolor"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"wincolor 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "termion"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.40 (registry+https://github.com/rust-lang/crates.io-index)",
"redox_syscall 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)",
"redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "thread_local"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ucd-util"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "utf8-ranges"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "version_check"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "winapi"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "winapi-util"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"winapi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "wincolor"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"winapi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[metadata]
"checksum aho-corasick 0.6.9 (registry+https://github.com/rust-lang/crates.io-index)" = "1e9a933f4e58658d7b12defcf96dc5c720f20832deebe3e0a19efd3b6aaeeb9e"
"checksum atty 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "af80143d6f7608d746df1520709e5d141c96f240b0e62b0aa41bdfb53374d9d4"
"checksum cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "082bb9b28e00d3c9d39cc03e64ce4cea0f1bb9b3fde493f0cbc008472d22bdf4"
"checksum humantime 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3ca7e5f2e110db35f93b837c81797f3714500b81d517bf20c431b16d3ca4f114"
"checksum lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c8f31047daa365f19be14b47c29df4f7c3b581832407daabe6ae77397619237d"
"checksum libc 0.2.40 (registry+https://github.com/rust-lang/crates.io-index)" = "6fd41f331ac7c5b8ac259b8bf82c75c0fb2e469bbf37d2becbba9a6a2221965b"
"checksum log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c84ec4b527950aa83a329754b01dbe3f58361d1c5efacd1f6d68c494d08a17c6"
"checksum memchr 2.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0a3eb002f0535929f1199681417029ebea04aadc0c7a4224b46be99c7f5d6a16"
"checksum quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0"
"checksum redox_syscall 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)" = "0d92eecebad22b767915e4d529f89f28ee96dbbf5a4810d2b844373f136417fd"
"checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76"
"checksum regex 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "37e7cbbd370869ce2e8dff25c7018702d10b21a20ef7135316f8daecd6c25b7f"
"checksum regex-syntax 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "8c2f35eedad5295fdf00a63d7d4b238135723f92b434ec06774dad15c7ab0861"
"checksum termcolor 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "4096add70612622289f2fdcdbd5086dc81c1e2675e6ae58d6c4f62a16c6d7f2f"
"checksum termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "689a3bdfaab439fd92bc87df5c4c78417d3cbe537487274e9b0b2dce76e92096"
"checksum thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b"
"checksum ucd-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fd2be2d6639d0f8fe6cdda291ad456e23629558d466e2789d2c3e9892bda285d"
"checksum utf8-ranges 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "796f7e48bef87609f7ade7e06495a87d5cd06c7866e6a5cbfceffc558a243737"
"checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd"
"checksum winapi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "04e3bd221fcbe8a271359c04f21a76db7d0c6028862d1bb5512d85e1e2eb5bb3"
"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
"checksum winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7168bab6e1daee33b4557efd0e95d5ca70a03706d39fa5f3fe7a236f584b03c9"
"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
"checksum wincolor 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "561ed901ae465d6185fa7864d63fbd5720d0ef718366c9a4dc83cf6170d7e9ba"

View File

@ -1,57 +0,0 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies
#
# If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
# editing this file be aware that the upstream Cargo.toml
# will likely look very different (and much more reasonable)
[package]
name = "env_logger"
version = "0.6.2"
authors = ["The Rust Project Developers"]
description = "A logging implementation for `log` which is configured via an environment\nvariable.\n"
documentation = "https://docs.rs/env_logger"
readme = "README.md"
keywords = ["logging", "log", "logger"]
categories = ["development-tools::debugging"]
license = "MIT/Apache-2.0"
repository = "https://github.com/sebasmagri/env_logger/"
[[test]]
name = "regexp_filter"
harness = false
[[test]]
name = "log-in-log"
harness = false
[[test]]
name = "init-twice-retains-filter"
harness = false
[dependencies.atty]
version = "0.2.5"
optional = true
[dependencies.humantime]
version = "1.1"
optional = true
[dependencies.log]
version = "0.4"
features = ["std"]
[dependencies.regex]
version = "1.0.3"
optional = true
[dependencies.termcolor]
version = "1.0.2"
optional = true
[features]
default = ["termcolor", "atty", "humantime", "regex"]

View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,25 +0,0 @@
Copyright (c) 2014 The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@ -1,152 +0,0 @@
env_logger [![Build Status](https://travis-ci.org/sebasmagri/env_logger.svg?branch=master)](https://travis-ci.org/sebasmagri/env_logger) [![Maintenance](https://img.shields.io/badge/maintenance-actively%20maintained-brightgreen.svg)](https://github.com/sebasmagri/env_logger) [![crates.io](https://img.shields.io/crates/v/env_logger.svg)](https://crates.io/crates/env_logger) [![Documentation](https://img.shields.io/badge/docs-current-blue.svg)](https://docs.rs/env_logger)
==========
Implements a logger that can be configured via environment variables.
## Usage
### In libraries
`env_logger` makes sense when used in executables (binary projects). Libraries should use the [`log`](https://doc.rust-lang.org/log) crate instead.
### In executables
It must be added along with `log` to the project dependencies:
```toml
[dependencies]
log = "0.4.0"
env_logger = "0.6.2"
```
`env_logger` must be initialized as early as possible in the project. After it's initialized, you can use the `log` macros to do actual logging.
```rust
#[macro_use]
extern crate log;
extern crate env_logger;
fn main() {
env_logger::init();
info!("starting up");
// ...
}
```
Then when running the executable, specify a value for the `RUST_LOG`
environment variable that corresponds with the log messages you want to show.
```bash
$ RUST_LOG=info ./main
[2018-11-03T06:09:06Z INFO default] starting up
```
`env_logger` can be configured in other ways besides an environment variable. See [the examples](https://github.com/sebasmagri/env_logger/tree/master/examples) for more approaches.
### In tests
Tests can use the `env_logger` crate to see log messages generated during that test:
```toml
[dependencies]
log = "0.4.0"
[dev-dependencies]
env_logger = "0.6.2"
```
```rust
#[macro_use]
extern crate log;
fn add_one(num: i32) -> i32 {
info!("add_one called with {}", num);
num + 1
}
#[cfg(test)]
mod tests {
use super::*;
extern crate env_logger;
fn init() {
let _ = env_logger::builder().is_test(true).try_init();
}
#[test]
fn it_adds_one() {
init();
info!("can log from the test too");
assert_eq!(3, add_one(2));
}
#[test]
fn it_handles_negative_numbers() {
init();
info!("logging from another test");
assert_eq!(-7, add_one(-8));
}
}
```
Assuming the module under test is called `my_lib`, running the tests with the
`RUST_LOG` filtering to info messages from this module looks like:
```bash
$ RUST_LOG=my_lib=info cargo test
Running target/debug/my_lib-...
running 2 tests
[INFO my_lib::tests] logging from another test
[INFO my_lib] add_one called with -8
test tests::it_handles_negative_numbers ... ok
[INFO my_lib::tests] can log from the test too
[INFO my_lib] add_one called with 2
test tests::it_adds_one ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured
```
Note that `env_logger::try_init()` needs to be called in each test in which you
want to enable logging. Additionally, the default behavior of tests to
run in parallel means that logging output may be interleaved with test output.
Either run tests in a single thread by specifying `RUST_TEST_THREADS=1` or by
running one test by specifying its name as an argument to the test binaries as
directed by the `cargo test` help docs:
```bash
$ RUST_LOG=my_lib=info cargo test it_adds_one
Running target/debug/my_lib-...
running 1 test
[INFO my_lib::tests] can log from the test too
[INFO my_lib] add_one called with 2
test tests::it_adds_one ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
```
## Configuring log target
By default, `env_logger` logs to stderr. If you want to log to stdout instead,
you can use the `Builder` to change the log target:
```rust
use std::env;
use env_logger::{Builder, Target};
let mut builder = Builder::from_default_env();
builder.target(Target::Stdout);
builder.init();
```
## Stability of the default format
The default format won't optimise for long-term stability, and explicitly makes no guarantees about the stability of its output across major, minor or patch version bumps during `0.x`.
If you want to capture or interpret the output of `env_logger` programmatically then you should use a custom format.

View File

@ -1,44 +0,0 @@
/*!
Disabling parts of the default format.
Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`:
```no_run,shell
$ export MY_LOG_LEVEL='info'
```
Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors
or `auto` to enable them:
```no_run,shell
$ export MY_LOG_STYLE=never
```
If you want to control the logging output completely, see the `custom_logger` example.
*/
#[macro_use]
extern crate log;
extern crate env_logger;
use env_logger::{Env, Builder};
fn init_logger() {
let env = Env::default()
.filter("MY_LOG_LEVEL")
.write_style("MY_LOG_STYLE");
let mut builder = Builder::from_env(env);
builder
.default_format_level(false)
.default_format_timestamp_nanos(true);
builder.init();
}
fn main() {
init_logger();
info!("a log from `MyLogger`");
}

View File

@ -1,54 +0,0 @@
/*!
Changing the default logging format.
Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`:
```no_run,shell
$ export MY_LOG_LEVEL='info'
```
Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors
or `auto` to enable them:
```no_run,shell
$ export MY_LOG_STYLE=never
```
If you want to control the logging output completely, see the `custom_logger` example.
*/
#[macro_use]
extern crate log;
extern crate env_logger;
use std::io::Write;
use env_logger::{Env, Builder, fmt};
fn init_logger() {
let env = Env::default()
.filter("MY_LOG_LEVEL")
.write_style("MY_LOG_STYLE");
let mut builder = Builder::from_env(env);
// Use a different format for writing log records
// The colors are only available when the `termcolor` dependency is (which it is by default)
#[cfg(feature = "termcolor")]
builder.format(|buf, record| {
let mut style = buf.style();
style.set_bg(fmt::Color::Yellow).set_bold(true);
let timestamp = buf.timestamp();
writeln!(buf, "My formatted log ({}): {}", timestamp, style.value(record.args()))
});
builder.init();
}
fn main() {
init_logger();
info!("a log from `MyLogger`");
}

View File

@ -1,60 +0,0 @@
/*!
Using `env_logger` to drive a custom logger.
Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`:
```no_run,shell
$ export MY_LOG_LEVEL='info'
```
If you only want to change the way logs are formatted, look at the `custom_format` example.
*/
#[macro_use]
extern crate log;
extern crate env_logger;
use env_logger::filter::Filter;
use log::{Log, Metadata, Record, SetLoggerError};
struct MyLogger {
inner: Filter
}
impl MyLogger {
fn new() -> MyLogger {
use env_logger::filter::Builder;
let mut builder = Builder::from_env("MY_LOG_LEVEL");
MyLogger {
inner: builder.build()
}
}
fn init() -> Result<(), SetLoggerError> {
let logger = Self::new();
log::set_max_level(logger.inner.filter());
log::set_boxed_logger(Box::new(logger))
}
}
impl Log for MyLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
self.inner.enabled(metadata)
}
fn log(&self, record: &Record) {
// Check if the record is matched by the logger before logging
if self.inner.matches(record) {
println!("{} - {}", record.level(), record.args());
}
}
fn flush(&self) { }
}
fn main() {
MyLogger::init().unwrap();
info!("a log from `MyLogger`");
}

View File

@ -1,39 +0,0 @@
/*!
Using `env_logger`.
Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`:
```no_run,shell
$ export MY_LOG_LEVEL='info'
```
Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors
or `auto` to enable them:
```no_run,shell
$ export MY_LOG_STYLE=never
```
*/
#[macro_use]
extern crate log;
extern crate env_logger;
use env_logger::Env;
fn main() {
// The `Env` lets us tweak what the environment
// variables to read are and what the default
// value is if they're missing
let env = Env::default()
.filter_or("MY_LOG_LEVEL", "trace")
.write_style_or("MY_LOG_STYLE", "always");
env_logger::init_from_env(env);
trace!("some trace log");
debug!("some debug log");
info!("some information log");
warn!("some warning log");
error!("some error log");
}

View File

@ -1,40 +0,0 @@
/*!
Using `env_logger::Logger` and the `log::Log` trait directly.
This example doesn't rely on environment variables, or having a static logger installed.
*/
extern crate log;
extern crate env_logger;
fn record() -> log::Record<'static> {
let error_metadata = log::MetadataBuilder::new()
.target("myApp")
.level(log::Level::Error)
.build();
log::Record::builder()
.metadata(error_metadata)
.args(format_args!("Error!"))
.line(Some(433))
.file(Some("app.rs"))
.module_path(Some("server"))
.build()
}
fn main() {
use log::Log;
let stylish_logger = env_logger::Builder::new()
.filter(None, log::LevelFilter::Error)
.write_style(env_logger::WriteStyle::Always)
.build();
let unstylish_logger = env_logger::Builder::new()
.filter(None, log::LevelFilter::Error)
.write_style(env_logger::WriteStyle::Never)
.build();
stylish_logger.log(&record());
unstylish_logger.log(&record());
}

View File

@ -1,19 +0,0 @@
/*!
Specify logging filters in code instead of using an environment variable.
*/
#[macro_use]
extern crate log;
extern crate env_logger;
fn main() {
env_logger::builder()
.filter_level(log::LevelFilter::Trace)
.init();
trace!("some trace log");
debug!("some debug log");
info!("some information log");
warn!("some warning log");
error!("some error log");
}

View File

@ -1,579 +0,0 @@
//! Filtering for log records.
//!
//! This module contains the log filtering used by `env_logger` to match records.
//! You can use the `Filter` type in your own logger implementation to use the same
//! filter parsing and matching as `env_logger`. For more details about the format
//! for directive strings see [Enabling Logging].
//!
//! ## Using `env_logger` in your own logger
//!
//! You can use `env_logger`'s filtering functionality with your own logger.
//! Call [`Builder::parse`] to parse directives from a string when constructing
//! your logger. Call [`Filter::matches`] to check whether a record should be
//! logged based on the parsed filters when log records are received.
//!
//! ```
//! extern crate log;
//! extern crate env_logger;
//! use env_logger::filter::Filter;
//! use log::{Log, Metadata, Record};
//!
//! struct MyLogger {
//! filter: Filter
//! }
//!
//! impl MyLogger {
//! fn new() -> MyLogger {
//! use env_logger::filter::Builder;
//! let mut builder = Builder::new();
//!
//! // Parse a directives string from an environment variable
//! if let Ok(ref filter) = std::env::var("MY_LOG_LEVEL") {
//! builder.parse(filter);
//! }
//!
//! MyLogger {
//! filter: builder.build()
//! }
//! }
//! }
//!
//! impl Log for MyLogger {
//! fn enabled(&self, metadata: &Metadata) -> bool {
//! self.filter.enabled(metadata)
//! }
//!
//! fn log(&self, record: &Record) {
//! // Check if the record is matched by the filter
//! if self.filter.matches(record) {
//! println!("{:?}", record);
//! }
//! }
//!
//! fn flush(&self) {}
//! }
//! # fn main() {}
//! ```
//!
//! [Enabling Logging]: ../index.html#enabling-logging
//! [`Builder::parse`]: struct.Builder.html#method.parse
//! [`Filter::matches`]: struct.Filter.html#method.matches
use std::env;
use std::mem;
use std::fmt;
use log::{Level, LevelFilter, Record, Metadata};
#[cfg(feature = "regex")]
#[path = "regex.rs"]
mod inner;
#[cfg(not(feature = "regex"))]
#[path = "string.rs"]
mod inner;
/// A log filter.
///
/// This struct can be used to determine whether or not a log record
/// should be written to the output.
/// Use the [`Builder`] type to parse and construct a `Filter`.
///
/// [`Builder`]: struct.Builder.html
pub struct Filter {
directives: Vec<Directive>,
filter: Option<inner::Filter>,
}
/// A builder for a log filter.
///
/// It can be used to parse a set of directives from a string before building
/// a [`Filter`] instance.
///
/// ## Example
///
/// ```
/// #[macro_use]
/// extern crate log;
/// extern crate env_logger;
///
/// use std::env;
/// use std::io;
/// use env_logger::filter::Builder;
///
/// fn main() {
/// let mut builder = Builder::new();
///
/// // Parse a logging filter from an environment variable.
/// if let Ok(rust_log) = env::var("RUST_LOG") {
/// builder.parse(&rust_log);
/// }
///
/// let filter = builder.build();
/// }
/// ```
///
/// [`Filter`]: struct.Filter.html
pub struct Builder {
directives: Vec<Directive>,
filter: Option<inner::Filter>,
built: bool,
}
#[derive(Debug)]
struct Directive {
name: Option<String>,
level: LevelFilter,
}
impl Filter {
/// Returns the maximum `LevelFilter` that this filter instance is
/// configured to output.
///
/// # Example
///
/// ```rust
/// extern crate log;
/// extern crate env_logger;
///
/// use log::LevelFilter;
/// use env_logger::filter::Builder;
///
/// fn main() {
/// let mut builder = Builder::new();
/// builder.filter(Some("module1"), LevelFilter::Info);
/// builder.filter(Some("module2"), LevelFilter::Error);
///
/// let filter = builder.build();
/// assert_eq!(filter.filter(), LevelFilter::Info);
/// }
/// ```
pub fn filter(&self) -> LevelFilter {
self.directives.iter()
.map(|d| d.level)
.max()
.unwrap_or(LevelFilter::Off)
}
/// Checks if this record matches the configured filter.
pub fn matches(&self, record: &Record) -> bool {
if !self.enabled(record.metadata()) {
return false;
}
if let Some(filter) = self.filter.as_ref() {
if !filter.is_match(&*record.args().to_string()) {
return false;
}
}
true
}
/// Determines if a log message with the specified metadata would be logged.
pub fn enabled(&self, metadata: &Metadata) -> bool {
let level = metadata.level();
let target = metadata.target();
enabled(&self.directives, level, target)
}
}
impl Builder {
/// Initializes the filter builder with defaults.
pub fn new() -> Builder {
Builder {
directives: Vec::new(),
filter: None,
built: false,
}
}
/// Initializes the filter builder from an environment.
pub fn from_env(env: &str) -> Builder {
let mut builder = Builder::new();
if let Ok(s) = env::var(env) {
builder.parse(&s);
}
builder
}
/// Adds a directive to the filter for a specific module.
pub fn filter_module(&mut self, module: &str, level: LevelFilter) -> &mut Self {
self.filter(Some(module), level)
}
/// Adds a directive to the filter for all modules.
pub fn filter_level(&mut self, level: LevelFilter) -> &mut Self {
self.filter(None, level)
}
/// Adds a directive to the filter.
///
/// The given module (if any) will log at most the specified level provided.
/// If no module is provided then the filter will apply to all log messages.
pub fn filter(&mut self,
module: Option<&str>,
level: LevelFilter) -> &mut Self {
self.directives.push(Directive {
name: module.map(|s| s.to_string()),
level,
});
self
}
/// Parses the directives string.
///
/// See the [Enabling Logging] section for more details.
///
/// [Enabling Logging]: ../index.html#enabling-logging
pub fn parse(&mut self, filters: &str) -> &mut Self {
let (directives, filter) = parse_spec(filters);
self.filter = filter;
for directive in directives {
self.directives.push(directive);
}
self
}
/// Build a log filter.
pub fn build(&mut self) -> Filter {
assert!(!self.built, "attempt to re-use consumed builder");
self.built = true;
if self.directives.is_empty() {
// Adds the default filter if none exist
self.directives.push(Directive {
name: None,
level: LevelFilter::Error,
});
} else {
// Sort the directives by length of their name, this allows a
// little more efficient lookup at runtime.
self.directives.sort_by(|a, b| {
let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0);
let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0);
alen.cmp(&blen)
});
}
Filter {
directives: mem::replace(&mut self.directives, Vec::new()),
filter: mem::replace(&mut self.filter, None),
}
}
}
impl Default for Builder {
fn default() -> Self {
Builder::new()
}
}
impl fmt::Debug for Filter {
fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result {
f.debug_struct("Filter")
.field("filter", &self.filter)
.field("directives", &self.directives)
.finish()
}
}
impl fmt::Debug for Builder {
fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result {
if self.built {
f.debug_struct("Filter")
.field("built", &true)
.finish()
} else {
f.debug_struct("Filter")
.field("filter", &self.filter)
.field("directives", &self.directives)
.finish()
}
}
}
/// Parse a logging specification string (e.g: "crate1,crate2::mod3,crate3::x=error/foo")
/// and return a vector with log directives.
fn parse_spec(spec: &str) -> (Vec<Directive>, Option<inner::Filter>) {
let mut dirs = Vec::new();
let mut parts = spec.split('/');
let mods = parts.next();
let filter = parts.next();
if parts.next().is_some() {
eprintln!("warning: invalid logging spec '{}', \
ignoring it (too many '/'s)", spec);
return (dirs, None);
}
mods.map(|m| { for s in m.split(',') {
if s.len() == 0 { continue }
let mut parts = s.split('=');
let (log_level, name) = match (parts.next(), parts.next().map(|s| s.trim()), parts.next()) {
(Some(part0), None, None) => {
// if the single argument is a log-level string or number,
// treat that as a global fallback
match part0.parse() {
Ok(num) => (num, None),
Err(_) => (LevelFilter::max(), Some(part0)),
}
}
(Some(part0), Some(""), None) => (LevelFilter::max(), Some(part0)),
(Some(part0), Some(part1), None) => {
match part1.parse() {
Ok(num) => (num, Some(part0)),
_ => {
eprintln!("warning: invalid logging spec '{}', \
ignoring it", part1);
continue
}
}
},
_ => {
eprintln!("warning: invalid logging spec '{}', \
ignoring it", s);
continue
}
};
dirs.push(Directive {
name: name.map(|s| s.to_string()),
level: log_level,
});
}});
let filter = filter.map_or(None, |filter| {
match inner::Filter::new(filter) {
Ok(re) => Some(re),
Err(e) => {
eprintln!("warning: invalid regex filter - {}", e);
None
}
}
});
return (dirs, filter);
}
// Check whether a level and target are enabled by the set of directives.
fn enabled(directives: &[Directive], level: Level, target: &str) -> bool {
// Search for the longest match, the vector is assumed to be pre-sorted.
for directive in directives.iter().rev() {
match directive.name {
Some(ref name) if !target.starts_with(&**name) => {},
Some(..) | None => {
return level <= directive.level
}
}
}
false
}
#[cfg(test)]
mod tests {
use log::{Level, LevelFilter};
use super::{Builder, Filter, Directive, parse_spec, enabled};
fn make_logger_filter(dirs: Vec<Directive>) -> Filter {
let mut logger = Builder::new().build();
logger.directives = dirs;
logger
}
#[test]
fn filter_info() {
let logger = Builder::new().filter(None, LevelFilter::Info).build();
assert!(enabled(&logger.directives, Level::Info, "crate1"));
assert!(!enabled(&logger.directives, Level::Debug, "crate1"));
}
#[test]
fn filter_beginning_longest_match() {
let logger = Builder::new()
.filter(Some("crate2"), LevelFilter::Info)
.filter(Some("crate2::mod"), LevelFilter::Debug)
.filter(Some("crate1::mod1"), LevelFilter::Warn)
.build();
assert!(enabled(&logger.directives, Level::Debug, "crate2::mod1"));
assert!(!enabled(&logger.directives, Level::Debug, "crate2"));
}
#[test]
fn parse_default() {
let logger = Builder::new().parse("info,crate1::mod1=warn").build();
assert!(enabled(&logger.directives, Level::Warn, "crate1::mod1"));
assert!(enabled(&logger.directives, Level::Info, "crate2::mod2"));
}
#[test]
fn match_full_path() {
let logger = make_logger_filter(vec![
Directive {
name: Some("crate2".to_string()),
level: LevelFilter::Info
},
Directive {
name: Some("crate1::mod1".to_string()),
level: LevelFilter::Warn
}
]);
assert!(enabled(&logger.directives, Level::Warn, "crate1::mod1"));
assert!(!enabled(&logger.directives, Level::Info, "crate1::mod1"));
assert!(enabled(&logger.directives, Level::Info, "crate2"));
assert!(!enabled(&logger.directives, Level::Debug, "crate2"));
}
#[test]
fn no_match() {
let logger = make_logger_filter(vec![
Directive { name: Some("crate2".to_string()), level: LevelFilter::Info },
Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
]);
assert!(!enabled(&logger.directives, Level::Warn, "crate3"));
}
#[test]
fn match_beginning() {
let logger = make_logger_filter(vec![
Directive { name: Some("crate2".to_string()), level: LevelFilter::Info },
Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
]);
assert!(enabled(&logger.directives, Level::Info, "crate2::mod1"));
}
#[test]
fn match_beginning_longest_match() {
let logger = make_logger_filter(vec![
Directive { name: Some("crate2".to_string()), level: LevelFilter::Info },
Directive { name: Some("crate2::mod".to_string()), level: LevelFilter::Debug },
Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
]);
assert!(enabled(&logger.directives, Level::Debug, "crate2::mod1"));
assert!(!enabled(&logger.directives, Level::Debug, "crate2"));
}
#[test]
fn match_default() {
let logger = make_logger_filter(vec![
Directive { name: None, level: LevelFilter::Info },
Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn }
]);
assert!(enabled(&logger.directives, Level::Warn, "crate1::mod1"));
assert!(enabled(&logger.directives, Level::Info, "crate2::mod2"));
}
#[test]
fn zero_level() {
let logger = make_logger_filter(vec![
Directive { name: None, level: LevelFilter::Info },
Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Off }
]);
assert!(!enabled(&logger.directives, Level::Error, "crate1::mod1"));
assert!(enabled(&logger.directives, Level::Info, "crate2::mod2"));
}
#[test]
fn parse_spec_valid() {
let (dirs, filter) = parse_spec("crate1::mod1=error,crate1::mod2,crate2=debug");
assert_eq!(dirs.len(), 3);
assert_eq!(dirs[0].name, Some("crate1::mod1".to_string()));
assert_eq!(dirs[0].level, LevelFilter::Error);
assert_eq!(dirs[1].name, Some("crate1::mod2".to_string()));
assert_eq!(dirs[1].level, LevelFilter::max());
assert_eq!(dirs[2].name, Some("crate2".to_string()));
assert_eq!(dirs[2].level, LevelFilter::Debug);
assert!(filter.is_none());
}
#[test]
fn parse_spec_invalid_crate() {
// test parse_spec with multiple = in specification
let (dirs, filter) = parse_spec("crate1::mod1=warn=info,crate2=debug");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
assert_eq!(dirs[0].level, LevelFilter::Debug);
assert!(filter.is_none());
}
#[test]
fn parse_spec_invalid_level() {
// test parse_spec with 'noNumber' as log level
let (dirs, filter) = parse_spec("crate1::mod1=noNumber,crate2=debug");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
assert_eq!(dirs[0].level, LevelFilter::Debug);
assert!(filter.is_none());
}
#[test]
fn parse_spec_string_level() {
// test parse_spec with 'warn' as log level
let (dirs, filter) = parse_spec("crate1::mod1=wrong,crate2=warn");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
assert_eq!(dirs[0].level, LevelFilter::Warn);
assert!(filter.is_none());
}
#[test]
fn parse_spec_empty_level() {
// test parse_spec with '' as log level
let (dirs, filter) = parse_spec("crate1::mod1=wrong,crate2=");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
assert_eq!(dirs[0].level, LevelFilter::max());
assert!(filter.is_none());
}
#[test]
fn parse_spec_global() {
// test parse_spec with no crate
let (dirs, filter) = parse_spec("warn,crate2=debug");
assert_eq!(dirs.len(), 2);
assert_eq!(dirs[0].name, None);
assert_eq!(dirs[0].level, LevelFilter::Warn);
assert_eq!(dirs[1].name, Some("crate2".to_string()));
assert_eq!(dirs[1].level, LevelFilter::Debug);
assert!(filter.is_none());
}
#[test]
fn parse_spec_valid_filter() {
let (dirs, filter) = parse_spec("crate1::mod1=error,crate1::mod2,crate2=debug/abc");
assert_eq!(dirs.len(), 3);
assert_eq!(dirs[0].name, Some("crate1::mod1".to_string()));
assert_eq!(dirs[0].level, LevelFilter::Error);
assert_eq!(dirs[1].name, Some("crate1::mod2".to_string()));
assert_eq!(dirs[1].level, LevelFilter::max());
assert_eq!(dirs[2].name, Some("crate2".to_string()));
assert_eq!(dirs[2].level, LevelFilter::Debug);
assert!(filter.is_some() && filter.unwrap().to_string() == "abc");
}
#[test]
fn parse_spec_invalid_crate_filter() {
let (dirs, filter) = parse_spec("crate1::mod1=error=warn,crate2=debug/a.c");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate2".to_string()));
assert_eq!(dirs[0].level, LevelFilter::Debug);
assert!(filter.is_some() && filter.unwrap().to_string() == "a.c");
}
#[test]
fn parse_spec_empty_with_filter() {
let (dirs, filter) = parse_spec("crate1/a*c");
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0].name, Some("crate1".to_string()));
assert_eq!(dirs[0].level, LevelFilter::max());
assert!(filter.is_some() && filter.unwrap().to_string() == "a*c");
}
}

View File

@ -1,29 +0,0 @@
extern crate regex;
use std::fmt;
use self::regex::Regex;
#[derive(Debug)]
pub struct Filter {
inner: Regex,
}
impl Filter {
pub fn new(spec: &str) -> Result<Filter, String> {
match Regex::new(spec){
Ok(r) => Ok(Filter { inner: r }),
Err(e) => Err(e.to_string()),
}
}
pub fn is_match(&self, s: &str) -> bool {
self.inner.is_match(s)
}
}
impl fmt::Display for Filter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.inner.fmt(f)
}
}

View File

@ -1,22 +0,0 @@
use std::fmt;
#[derive(Debug)]
pub struct Filter {
inner: String,
}
impl Filter {
pub fn new(spec: &str) -> Result<Filter, String> {
Ok(Filter { inner: spec.to_string() })
}
pub fn is_match(&self, s: &str) -> bool {
s.contains(&self.inner)
}
}
impl fmt::Display for Filter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.inner.fmt(f)
}
}

View File

@ -1,84 +0,0 @@
use std::fmt;
use std::time::SystemTime;
use humantime::{format_rfc3339_nanos, format_rfc3339_seconds};
use ::fmt::Formatter;
pub(in ::fmt) mod glob {
pub use super::*;
}
impl Formatter {
/// Get a [`Timestamp`] for the current date and time in UTC.
///
/// # Examples
///
/// Include the current timestamp with the log record:
///
/// ```
/// use std::io::Write;
///
/// let mut builder = env_logger::Builder::new();
///
/// builder.format(|buf, record| {
/// let ts = buf.timestamp();
///
/// writeln!(buf, "{}: {}: {}", ts, record.level(), record.args())
/// });
/// ```
///
/// [`Timestamp`]: struct.Timestamp.html
pub fn timestamp(&self) -> Timestamp {
Timestamp(SystemTime::now())
}
/// Get a [`PreciseTimestamp`] for the current date and time in UTC with nanos.
pub fn precise_timestamp(&self) -> PreciseTimestamp {
PreciseTimestamp(SystemTime::now())
}
}
/// An [RFC3339] formatted timestamp.
///
/// The timestamp implements [`Display`] and can be written to a [`Formatter`].
///
/// [RFC3339]: https://www.ietf.org/rfc/rfc3339.txt
/// [`Display`]: https://doc.rust-lang.org/stable/std/fmt/trait.Display.html
/// [`Formatter`]: struct.Formatter.html
pub struct Timestamp(SystemTime);
/// An [RFC3339] formatted timestamp with nanos.
///
/// [RFC3339]: https://www.ietf.org/rfc/rfc3339.txt
#[derive(Debug)]
pub struct PreciseTimestamp(SystemTime);
impl fmt::Debug for Timestamp {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// A `Debug` wrapper for `Timestamp` that uses the `Display` implementation.
struct TimestampValue<'a>(&'a Timestamp);
impl<'a> fmt::Debug for TimestampValue<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
f.debug_tuple("Timestamp")
.field(&TimestampValue(&self))
.finish()
}
}
impl fmt::Display for Timestamp {
fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result {
format_rfc3339_seconds(self.0).fmt(f)
}
}
impl fmt::Display for PreciseTimestamp {
fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result {
format_rfc3339_nanos(self.0).fmt(f)
}
}

View File

@ -1,11 +0,0 @@
/*
This internal module contains the timestamp implementation.
Its public API is available when the `humantime` crate is available.
*/
#[cfg_attr(feature = "humantime", path = "extern_impl.rs")]
#[cfg_attr(not(feature = "humantime"), path = "shim_impl.rs")]
mod imp;
pub(in ::fmt) use self::imp::*;

View File

@ -1,7 +0,0 @@
/*
Timestamps aren't available when we don't have a `humantime` dependency.
*/
pub(in ::fmt) mod glob {
}

View File

@ -1,358 +0,0 @@
//! Formatting for log records.
//!
//! This module contains a [`Formatter`] that can be used to format log records
//! into without needing temporary allocations. Usually you won't need to worry
//! about the contents of this module and can use the `Formatter` like an ordinary
//! [`Write`].
//!
//! # Formatting log records
//!
//! The format used to print log records can be customised using the [`Builder::format`]
//! method.
//! Custom formats can apply different color and weight to printed values using
//! [`Style`] builders.
//!
//! ```
//! use std::io::Write;
//!
//! let mut builder = env_logger::Builder::new();
//!
//! builder.format(|buf, record| {
//! writeln!(buf, "{}: {}",
//! record.level(),
//! record.args())
//! });
//! ```
//!
//! [`Formatter`]: struct.Formatter.html
//! [`Style`]: struct.Style.html
//! [`Builder::format`]: ../struct.Builder.html#method.format
//! [`Write`]: https://doc.rust-lang.org/stable/std/io/trait.Write.html
use std::io::prelude::*;
use std::{io, fmt, mem};
use std::rc::Rc;
use std::cell::RefCell;
use std::fmt::Display;
use log::Record;
pub(crate) mod writer;
mod humantime;
pub use self::humantime::glob::*;
pub use self::writer::glob::*;
use self::writer::{Writer, Buffer};
pub(crate) mod glob {
pub use super::{Target, WriteStyle};
}
/// A formatter to write logs into.
///
/// `Formatter` implements the standard [`Write`] trait for writing log records.
/// It also supports terminal colors, through the [`style`] method.
///
/// # Examples
///
/// Use the [`writeln`] macro to format a log record.
/// An instance of a `Formatter` is passed to an `env_logger` format as `buf`:
///
/// ```
/// use std::io::Write;
///
/// let mut builder = env_logger::Builder::new();
///
/// builder.format(|buf, record| writeln!(buf, "{}: {}", record.level(), record.args()));
/// ```
///
/// [`Write`]: https://doc.rust-lang.org/stable/std/io/trait.Write.html
/// [`writeln`]: https://doc.rust-lang.org/stable/std/macro.writeln.html
/// [`style`]: #method.style
pub struct Formatter {
buf: Rc<RefCell<Buffer>>,
write_style: WriteStyle,
}
impl Formatter {
pub(crate) fn new(writer: &Writer) -> Self {
Formatter {
buf: Rc::new(RefCell::new(writer.buffer())),
write_style: writer.write_style(),
}
}
pub(crate) fn write_style(&self) -> WriteStyle {
self.write_style
}
pub(crate) fn print(&self, writer: &Writer) -> io::Result<()> {
writer.print(&self.buf.borrow())
}
pub(crate) fn clear(&mut self) {
self.buf.borrow_mut().clear()
}
}
impl Write for Formatter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.buf.borrow_mut().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.buf.borrow_mut().flush()
}
}
impl fmt::Debug for Formatter {
fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result {
f.debug_struct("Formatter").finish()
}
}
pub(crate) struct Builder {
pub default_format_timestamp: bool,
pub default_format_timestamp_nanos: bool,
pub default_format_module_path: bool,
pub default_format_level: bool,
#[allow(unknown_lints, bare_trait_objects)]
pub custom_format: Option<Box<Fn(&mut Formatter, &Record) -> io::Result<()> + Sync + Send>>,
built: bool,
}
impl Default for Builder {
fn default() -> Self {
Builder {
default_format_timestamp: true,
default_format_timestamp_nanos: false,
default_format_module_path: true,
default_format_level: true,
custom_format: None,
built: false,
}
}
}
impl Builder {
/// Convert the format into a callable function.
///
/// If the `custom_format` is `Some`, then any `default_format` switches are ignored.
/// If the `custom_format` is `None`, then a default format is returned.
/// Any `default_format` switches set to `false` won't be written by the format.
#[allow(unknown_lints, bare_trait_objects)]
pub fn build(&mut self) -> Box<Fn(&mut Formatter, &Record) -> io::Result<()> + Sync + Send> {
assert!(!self.built, "attempt to re-use consumed builder");
let built = mem::replace(self, Builder {
built: true,
..Default::default()
});
if let Some(fmt) = built.custom_format {
fmt
}
else {
Box::new(move |buf, record| {
let fmt = DefaultFormat {
timestamp: built.default_format_timestamp,
timestamp_nanos: built.default_format_timestamp_nanos,
module_path: built.default_format_module_path,
level: built.default_format_level,
written_header_value: false,
buf,
};
fmt.write(record)
})
}
}
}
#[cfg(feature = "termcolor")]
type SubtleStyle = StyledValue<'static, &'static str>;
#[cfg(not(feature = "termcolor"))]
type SubtleStyle = &'static str;
/// The default format.
///
/// This format needs to work with any combination of crate features.
struct DefaultFormat<'a> {
timestamp: bool,
module_path: bool,
level: bool,
timestamp_nanos: bool,
written_header_value: bool,
buf: &'a mut Formatter,
}
impl<'a> DefaultFormat<'a> {
fn write(mut self, record: &Record) -> io::Result<()> {
self.write_timestamp()?;
self.write_level(record)?;
self.write_module_path(record)?;
self.finish_header()?;
self.write_args(record)
}
fn subtle_style(&self, text: &'static str) -> SubtleStyle {
#[cfg(feature = "termcolor")]
{
self.buf.style()
.set_color(Color::Black)
.set_intense(true)
.into_value(text)
}
#[cfg(not(feature = "termcolor"))]
{
text
}
}
fn write_header_value<T>(&mut self, value: T) -> io::Result<()>
where
T: Display,
{
if !self.written_header_value {
self.written_header_value = true;
let open_brace = self.subtle_style("[");
write!(self.buf, "{}{}", open_brace, value)
} else {
write!(self.buf, " {}", value)
}
}
fn write_level(&mut self, record: &Record) -> io::Result<()> {
if !self.level {
return Ok(())
}
let level = {
#[cfg(feature = "termcolor")]
{
self.buf.default_styled_level(record.level())
}
#[cfg(not(feature = "termcolor"))]
{
record.level()
}
};
self.write_header_value(format_args!("{:<5}", level))
}
fn write_timestamp(&mut self) -> io::Result<()> {
#[cfg(feature = "humantime")]
{
if !self.timestamp {
return Ok(())
}
if self.timestamp_nanos {
let ts_nanos = self.buf.precise_timestamp();
self.write_header_value(ts_nanos)
} else {
let ts = self.buf.timestamp();
self.write_header_value(ts)
}
}
#[cfg(not(feature = "humantime"))]
{
let _ = self.timestamp;
let _ = self.timestamp_nanos;
Ok(())
}
}
fn write_module_path(&mut self, record: &Record) -> io::Result<()> {
if !self.module_path {
return Ok(())
}
if let Some(module_path) = record.module_path() {
self.write_header_value(module_path)
} else {
Ok(())
}
}
fn finish_header(&mut self) -> io::Result<()> {
if self.written_header_value {
let close_brace = self.subtle_style("]");
write!(self.buf, "{} ", close_brace)
} else {
Ok(())
}
}
fn write_args(&mut self, record: &Record) -> io::Result<()> {
writeln!(self.buf, "{}", record.args())
}
}
#[cfg(test)]
mod tests {
use super::*;
use log::{Level, Record};
fn write(fmt: DefaultFormat) -> String {
let buf = fmt.buf.buf.clone();
let record = Record::builder()
.args(format_args!("log message"))
.level(Level::Info)
.file(Some("test.rs"))
.line(Some(144))
.module_path(Some("test::path"))
.build();
fmt.write(&record).expect("failed to write record");
let buf = buf.borrow();
String::from_utf8(buf.bytes().to_vec()).expect("failed to read record")
}
#[test]
fn default_format_with_header() {
let writer = writer::Builder::new()
.write_style(WriteStyle::Never)
.build();
let mut f = Formatter::new(&writer);
let written = write(DefaultFormat {
timestamp: false,
timestamp_nanos: false,
module_path: true,
level: true,
written_header_value: false,
buf: &mut f,
});
assert_eq!("[INFO test::path] log message\n", written);
}
#[test]
fn default_format_no_header() {
let writer = writer::Builder::new()
.write_style(WriteStyle::Never)
.build();
let mut f = Formatter::new(&writer);
let written = write(DefaultFormat {
timestamp: false,
timestamp_nanos: false,
module_path: false,
level: false,
written_header_value: false,
buf: &mut f,
});
assert_eq!("log message\n", written);
}
}

View File

@ -1,34 +0,0 @@
/*
This internal module contains the terminal detection implementation.
If the `atty` crate is available then we use it to detect whether we're
attached to a particular TTY. If the `atty` crate is not available we
assume we're not attached to anything. This effectively prevents styles
from being printed.
*/
#[cfg(feature = "atty")]
mod imp {
use atty;
pub(in ::fmt) fn is_stdout() -> bool {
atty::is(atty::Stream::Stdout)
}
pub(in ::fmt) fn is_stderr() -> bool {
atty::is(atty::Stream::Stderr)
}
}
#[cfg(not(feature = "atty"))]
mod imp {
pub(in ::fmt) fn is_stdout() -> bool {
false
}
pub(in ::fmt) fn is_stderr() -> bool {
false
}
}
pub(in ::fmt) use self::imp::*;

View File

@ -1,206 +0,0 @@
mod termcolor;
mod atty;
use std::{fmt, io};
use self::termcolor::BufferWriter;
use self::atty::{is_stdout, is_stderr};
pub(in ::fmt) mod glob {
pub use super::termcolor::glob::*;
pub use super::*;
}
pub(in ::fmt) use self::termcolor::Buffer;
/// Log target, either `stdout` or `stderr`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Target {
/// Logs will be sent to standard output.
Stdout,
/// Logs will be sent to standard error.
Stderr,
}
impl Default for Target {
fn default() -> Self {
Target::Stderr
}
}
/// Whether or not to print styles to the target.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum WriteStyle {
/// Try to print styles, but don't force the issue.
Auto,
/// Try very hard to print styles.
Always,
/// Never print styles.
Never,
}
impl Default for WriteStyle {
fn default() -> Self {
WriteStyle::Auto
}
}
/// A terminal target with color awareness.
pub(crate) struct Writer {
inner: BufferWriter,
write_style: WriteStyle,
}
impl Writer {
pub fn write_style(&self) -> WriteStyle {
self.write_style
}
pub(in ::fmt) fn buffer(&self) -> Buffer {
self.inner.buffer()
}
pub(in ::fmt) fn print(&self, buf: &Buffer) -> io::Result<()> {
self.inner.print(buf)
}
}
/// A builder for a terminal writer.
///
/// The target and style choice can be configured before building.
pub(crate) struct Builder {
target: Target,
write_style: WriteStyle,
is_test: bool,
built: bool,
}
impl Builder {
/// Initialize the writer builder with defaults.
pub(crate) fn new() -> Self {
Builder {
target: Default::default(),
write_style: Default::default(),
is_test: false,
built: false,
}
}
/// Set the target to write to.
pub(crate) fn target(&mut self, target: Target) -> &mut Self {
self.target = target;
self
}
/// Parses a style choice string.
///
/// See the [Disabling colors] section for more details.
///
/// [Disabling colors]: ../index.html#disabling-colors
pub(crate) fn parse_write_style(&mut self, write_style: &str) -> &mut Self {
self.write_style(parse_write_style(write_style))
}
/// Whether or not to print style characters when writing.
pub(crate) fn write_style(&mut self, write_style: WriteStyle) -> &mut Self {
self.write_style = write_style;
self
}
/// Whether or not to capture logs for `cargo test`.
pub(crate) fn is_test(&mut self, is_test: bool) -> &mut Self {
self.is_test = is_test;
self
}
/// Build a terminal writer.
pub(crate) fn build(&mut self) -> Writer {
assert!(!self.built, "attempt to re-use consumed builder");
self.built = true;
let color_choice = match self.write_style {
WriteStyle::Auto => {
if match self.target {
Target::Stderr => is_stderr(),
Target::Stdout => is_stdout(),
} {
WriteStyle::Auto
} else {
WriteStyle::Never
}
},
color_choice => color_choice,
};
let writer = match self.target {
Target::Stderr => BufferWriter::stderr(self.is_test, color_choice),
Target::Stdout => BufferWriter::stdout(self.is_test, color_choice),
};
Writer {
inner: writer,
write_style: self.write_style,
}
}
}
impl Default for Builder {
fn default() -> Self {
Builder::new()
}
}
impl fmt::Debug for Builder {
fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result {
f.debug_struct("Logger")
.field("target", &self.target)
.field("write_style", &self.write_style)
.finish()
}
}
impl fmt::Debug for Writer {
fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result {
f.debug_struct("Writer").finish()
}
}
fn parse_write_style(spec: &str) -> WriteStyle {
match spec {
"auto" => WriteStyle::Auto,
"always" => WriteStyle::Always,
"never" => WriteStyle::Never,
_ => Default::default(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_write_style_valid() {
let inputs = vec![
("auto", WriteStyle::Auto),
("always", WriteStyle::Always),
("never", WriteStyle::Never),
];
for (input, expected) in inputs {
assert_eq!(expected, parse_write_style(input));
}
}
#[test]
fn parse_write_style_invalid() {
let inputs = vec![
"",
"true",
"false",
"NEVER!!"
];
for input in inputs {
assert_eq!(WriteStyle::Auto, parse_write_style(input));
}
}
}

View File

@ -1,490 +0,0 @@
use std::borrow::Cow;
use std::fmt;
use std::io::{self, Write};
use std::cell::RefCell;
use std::rc::Rc;
use log::Level;
use termcolor::{self, ColorChoice, ColorSpec, WriteColor};
use ::WriteStyle;
use ::fmt::{Formatter, Target};
pub(in ::fmt::writer) mod glob {
pub use super::*;
}
impl Formatter {
/// Begin a new [`Style`].
///
/// # Examples
///
/// Create a bold, red colored style and use it to print the log level:
///
/// ```
/// use std::io::Write;
/// use env_logger::fmt::Color;
///
/// let mut builder = env_logger::Builder::new();
///
/// builder.format(|buf, record| {
/// let mut level_style = buf.style();
///
/// level_style.set_color(Color::Red).set_bold(true);
///
/// writeln!(buf, "{}: {}",
/// level_style.value(record.level()),
/// record.args())
/// });
/// ```
///
/// [`Style`]: struct.Style.html
pub fn style(&self) -> Style {
Style {
buf: self.buf.clone(),
spec: ColorSpec::new(),
}
}
/// Get the default [`Style`] for the given level.
///
/// The style can be used to print other values besides the level.
pub fn default_level_style(&self, level: Level) -> Style {
let mut level_style = self.style();
match level {
Level::Trace => level_style.set_color(Color::Black).set_intense(true),
Level::Debug => level_style.set_color(Color::White),
Level::Info => level_style.set_color(Color::Green),
Level::Warn => level_style.set_color(Color::Yellow),
Level::Error => level_style.set_color(Color::Red).set_bold(true),
};
level_style
}
/// Get a printable [`Style`] for the given level.
///
/// The style can only be used to print the level.
pub fn default_styled_level(&self, level: Level) -> StyledValue<'static, Level> {
self.default_level_style(level).into_value(level)
}
}
pub(in ::fmt::writer) struct BufferWriter {
inner: termcolor::BufferWriter,
test_target: Option<Target>,
}
pub(in ::fmt) struct Buffer {
inner: termcolor::Buffer,
test_target: Option<Target>,
}
impl BufferWriter {
pub(in ::fmt::writer) fn stderr(is_test: bool, write_style: WriteStyle) -> Self {
BufferWriter {
inner: termcolor::BufferWriter::stderr(write_style.into_color_choice()),
test_target: if is_test {
Some(Target::Stderr)
} else {
None
},
}
}
pub(in ::fmt::writer) fn stdout(is_test: bool, write_style: WriteStyle) -> Self {
BufferWriter {
inner: termcolor::BufferWriter::stdout(write_style.into_color_choice()),
test_target: if is_test {
Some(Target::Stdout)
} else {
None
},
}
}
pub(in ::fmt::writer) fn buffer(&self) -> Buffer {
Buffer {
inner: self.inner.buffer(),
test_target: self.test_target,
}
}
pub(in ::fmt::writer) fn print(&self, buf: &Buffer) -> io::Result<()> {
if let Some(target) = self.test_target {
// This impl uses the `eprint` and `print` macros
// instead of `termcolor`'s buffer.
// This is so their output can be captured by `cargo test`
let log = String::from_utf8_lossy(buf.bytes());
match target {
Target::Stderr => eprint!("{}", log),
Target::Stdout => print!("{}", log),
}
Ok(())
} else {
self.inner.print(&buf.inner)
}
}
}
impl Buffer {
pub(in ::fmt) fn clear(&mut self) {
self.inner.clear()
}
pub(in ::fmt) fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.inner.write(buf)
}
pub(in ::fmt) fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
pub(in ::fmt) fn bytes(&self) -> &[u8] {
self.inner.as_slice()
}
fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {
// Ignore styles for test captured logs because they can't be printed
if self.test_target.is_none() {
self.inner.set_color(spec)
} else {
Ok(())
}
}
fn reset(&mut self) -> io::Result<()> {
// Ignore styles for test captured logs because they can't be printed
if self.test_target.is_none() {
self.inner.reset()
} else {
Ok(())
}
}
}
impl WriteStyle {
fn into_color_choice(self) -> ColorChoice {
match self {
WriteStyle::Always => ColorChoice::Always,
WriteStyle::Auto => ColorChoice::Auto,
WriteStyle::Never => ColorChoice::Never,
}
}
}
/// A set of styles to apply to the terminal output.
///
/// Call [`Formatter::style`] to get a `Style` and use the builder methods to
/// set styling properties, like [color] and [weight].
/// To print a value using the style, wrap it in a call to [`value`] when the log
/// record is formatted.
///
/// # Examples
///
/// Create a bold, red colored style and use it to print the log level:
///
/// ```
/// use std::io::Write;
/// use env_logger::fmt::Color;
///
/// let mut builder = env_logger::Builder::new();
///
/// builder.format(|buf, record| {
/// let mut level_style = buf.style();
///
/// level_style.set_color(Color::Red).set_bold(true);
///
/// writeln!(buf, "{}: {}",
/// level_style.value(record.level()),
/// record.args())
/// });
/// ```
///
/// Styles can be re-used to output multiple values:
///
/// ```
/// use std::io::Write;
/// use env_logger::fmt::Color;
///
/// let mut builder = env_logger::Builder::new();
///
/// builder.format(|buf, record| {
/// let mut bold = buf.style();
///
/// bold.set_bold(true);
///
/// writeln!(buf, "{}: {} {}",
/// bold.value(record.level()),
/// bold.value("some bold text"),
/// record.args())
/// });
/// ```
///
/// [`Formatter::style`]: struct.Formatter.html#method.style
/// [color]: #method.set_color
/// [weight]: #method.set_bold
/// [`value`]: #method.value
#[derive(Clone)]
pub struct Style {
buf: Rc<RefCell<Buffer>>,
spec: ColorSpec,
}
/// A value that can be printed using the given styles.
///
/// It is the result of calling [`Style::value`].
///
/// [`Style::value`]: struct.Style.html#method.value
pub struct StyledValue<'a, T> {
style: Cow<'a, Style>,
value: T,
}
impl Style {
/// Set the text color.
///
/// # Examples
///
/// Create a style with red text:
///
/// ```
/// use std::io::Write;
/// use env_logger::fmt::Color;
///
/// let mut builder = env_logger::Builder::new();
///
/// builder.format(|buf, record| {
/// let mut style = buf.style();
///
/// style.set_color(Color::Red);
///
/// writeln!(buf, "{}", style.value(record.args()))
/// });
/// ```
pub fn set_color(&mut self, color: Color) -> &mut Style {
self.spec.set_fg(color.into_termcolor());
self
}
/// Set the text weight.
///
/// If `yes` is true then text will be written in bold.
/// If `yes` is false then text will be written in the default weight.
///
/// # Examples
///
/// Create a style with bold text:
///
/// ```
/// use std::io::Write;
///
/// let mut builder = env_logger::Builder::new();
///
/// builder.format(|buf, record| {
/// let mut style = buf.style();
///
/// style.set_bold(true);
///
/// writeln!(buf, "{}", style.value(record.args()))
/// });
/// ```
pub fn set_bold(&mut self, yes: bool) -> &mut Style {
self.spec.set_bold(yes);
self
}
/// Set the text intensity.
///
/// If `yes` is true then text will be written in a brighter color.
/// If `yes` is false then text will be written in the default color.
///
/// # Examples
///
/// Create a style with intense text:
///
/// ```
/// use std::io::Write;
///
/// let mut builder = env_logger::Builder::new();
///
/// builder.format(|buf, record| {
/// let mut style = buf.style();
///
/// style.set_intense(true);
///
/// writeln!(buf, "{}", style.value(record.args()))
/// });
/// ```
pub fn set_intense(&mut self, yes: bool) -> &mut Style {
self.spec.set_intense(yes);
self
}
/// Set the background color.
///
/// # Examples
///
/// Create a style with a yellow background:
///
/// ```
/// use std::io::Write;
/// use env_logger::fmt::Color;
///
/// let mut builder = env_logger::Builder::new();
///
/// builder.format(|buf, record| {
/// let mut style = buf.style();
///
/// style.set_bg(Color::Yellow);
///
/// writeln!(buf, "{}", style.value(record.args()))
/// });
/// ```
pub fn set_bg(&mut self, color: Color) -> &mut Style {
self.spec.set_bg(color.into_termcolor());
self
}
/// Wrap a value in the style.
///
/// The same `Style` can be used to print multiple different values.
///
/// # Examples
///
/// Create a bold, red colored style and use it to print the log level:
///
/// ```
/// use std::io::Write;
/// use env_logger::fmt::Color;
///
/// let mut builder = env_logger::Builder::new();
///
/// builder.format(|buf, record| {
/// let mut style = buf.style();
///
/// style.set_color(Color::Red).set_bold(true);
///
/// writeln!(buf, "{}: {}",
/// style.value(record.level()),
/// record.args())
/// });
/// ```
pub fn value<T>(&self, value: T) -> StyledValue<T> {
StyledValue {
style: Cow::Borrowed(self),
value
}
}
/// Wrap a value in the style by taking ownership of it.
pub(crate) fn into_value<T>(&mut self, value: T) -> StyledValue<'static, T> {
StyledValue {
style: Cow::Owned(self.clone()),
value
}
}
}
impl<'a, T> StyledValue<'a, T> {
fn write_fmt<F>(&self, f: F) -> fmt::Result
where
F: FnOnce() -> fmt::Result,
{
self.style.buf.borrow_mut().set_color(&self.style.spec).map_err(|_| fmt::Error)?;
// Always try to reset the terminal style, even if writing failed
let write = f();
let reset = self.style.buf.borrow_mut().reset().map_err(|_| fmt::Error);
write.and(reset)
}
}
impl fmt::Debug for Style {
fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result {
f.debug_struct("Style").field("spec", &self.spec).finish()
}
}
macro_rules! impl_styled_value_fmt {
($($fmt_trait:path),*) => {
$(
impl<'a, T: $fmt_trait> $fmt_trait for StyledValue<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result {
self.write_fmt(|| T::fmt(&self.value, f))
}
}
)*
};
}
impl_styled_value_fmt!(
fmt::Debug,
fmt::Display,
fmt::Pointer,
fmt::Octal,
fmt::Binary,
fmt::UpperHex,
fmt::LowerHex,
fmt::UpperExp,
fmt::LowerExp);
// The `Color` type is copied from https://github.com/BurntSushi/ripgrep/tree/master/termcolor
/// The set of available colors for the terminal foreground/background.
///
/// The `Ansi256` and `Rgb` colors will only output the correct codes when
/// paired with the `Ansi` `WriteColor` implementation.
///
/// The `Ansi256` and `Rgb` color types are not supported when writing colors
/// on Windows using the console. If they are used on Windows, then they are
/// silently ignored and no colors will be emitted.
///
/// This set may expand over time.
///
/// This type has a `FromStr` impl that can parse colors from their human
/// readable form. The format is as follows:
///
/// 1. Any of the explicitly listed colors in English. They are matched
/// case insensitively.
/// 2. A single 8-bit integer, in either decimal or hexadecimal format.
/// 3. A triple of 8-bit integers separated by a comma, where each integer is
/// in decimal or hexadecimal format.
///
/// Hexadecimal numbers are written with a `0x` prefix.
#[allow(missing_docs)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Color {
Black,
Blue,
Green,
Red,
Cyan,
Magenta,
Yellow,
White,
Ansi256(u8),
Rgb(u8, u8, u8),
#[doc(hidden)]
__Nonexhaustive,
}
impl Color {
fn into_termcolor(self) -> Option<termcolor::Color> {
match self {
Color::Black => Some(termcolor::Color::Black),
Color::Blue => Some(termcolor::Color::Blue),
Color::Green => Some(termcolor::Color::Green),
Color::Red => Some(termcolor::Color::Red),
Color::Cyan => Some(termcolor::Color::Cyan),
Color::Magenta => Some(termcolor::Color::Magenta),
Color::Yellow => Some(termcolor::Color::Yellow),
Color::White => Some(termcolor::Color::White),
Color::Ansi256(value) => Some(termcolor::Color::Ansi256(value)),
Color::Rgb(r, g, b) => Some(termcolor::Color::Rgb(r, g, b)),
_ => None,
}
}
}

View File

@ -1,12 +0,0 @@
/*
This internal module contains the style and terminal writing implementation.
Its public API is available when the `termcolor` crate is available.
The terminal printing is shimmed when the `termcolor` crate is not available.
*/
#[cfg_attr(feature = "termcolor", path = "extern_impl.rs")]
#[cfg_attr(not(feature = "termcolor"), path = "shim_impl.rs")]
mod imp;
pub(in ::fmt) use self::imp::*;

View File

@ -1,65 +0,0 @@
use std::io;
use fmt::{WriteStyle, Target};
pub(in ::fmt::writer) mod glob {
}
pub(in ::fmt::writer) struct BufferWriter {
target: Target,
}
pub(in ::fmt) struct Buffer(Vec<u8>);
impl BufferWriter {
pub(in ::fmt::writer) fn stderr(_is_test: bool, _write_style: WriteStyle) -> Self {
BufferWriter {
target: Target::Stderr,
}
}
pub(in ::fmt::writer) fn stdout(_is_test: bool, _write_style: WriteStyle) -> Self {
BufferWriter {
target: Target::Stdout,
}
}
pub(in ::fmt::writer) fn buffer(&self) -> Buffer {
Buffer(Vec::new())
}
pub(in ::fmt::writer) fn print(&self, buf: &Buffer) -> io::Result<()> {
// This impl uses the `eprint` and `print` macros
// instead of using the streams directly.
// This is so their output can be captured by `cargo test`
let log = String::from_utf8_lossy(&buf.0);
match self.target {
Target::Stderr => eprint!("{}", log),
Target::Stdout => print!("{}", log),
}
Ok(())
}
}
impl Buffer {
pub(in ::fmt) fn clear(&mut self) {
self.0.clear();
}
pub(in ::fmt) fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.extend(buf);
Ok(buf.len())
}
pub(in ::fmt) fn flush(&mut self) -> io::Result<()> {
Ok(())
}
#[cfg(test)]
pub(in ::fmt) fn bytes(&self) -> &[u8] {
&self.0
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,40 +0,0 @@
extern crate log;
extern crate env_logger;
use std::process;
use std::env;
use std::str;
fn main() {
if env::var("YOU_ARE_TESTING_NOW").is_ok() {
// Init from the env (which should set the max level to `Debug`)
env_logger::init();
assert_eq!(log::LevelFilter::Debug, log::max_level());
// Init again using a different max level
// This shouldn't clobber the level that was previously set
env_logger::Builder::new()
.parse_filters("info")
.try_init()
.unwrap_err();
assert_eq!(log::LevelFilter::Debug, log::max_level());
return
}
let exe = env::current_exe().unwrap();
let out = process::Command::new(exe)
.env("YOU_ARE_TESTING_NOW", "1")
.env("RUST_LOG", "debug")
.output()
.unwrap_or_else(|e| panic!("Unable to start child process: {}", e));
if out.status.success() {
return
}
println!("test failed: {}", out.status);
println!("--- stdout\n{}", str::from_utf8(&out.stdout).unwrap());
println!("--- stderr\n{}", str::from_utf8(&out.stderr).unwrap());
process::exit(1);
}

View File

@ -1,38 +0,0 @@
#[macro_use] extern crate log;
extern crate env_logger;
use std::process;
use std::fmt;
use std::env;
use std::str;
struct Foo;
impl fmt::Display for Foo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
info!("test");
f.write_str("bar")
}
}
fn main() {
env_logger::init();
if env::var("YOU_ARE_TESTING_NOW").is_ok() {
return info!("{}", Foo);
}
let exe = env::current_exe().unwrap();
let out = process::Command::new(exe)
.env("YOU_ARE_TESTING_NOW", "1")
.env("RUST_LOG", "debug")
.output()
.unwrap_or_else(|e| panic!("Unable to start child process: {}", e));
if out.status.success() {
return
}
println!("test failed: {}", out.status);
println!("--- stdout\n{}", str::from_utf8(&out.stdout).unwrap());
println!("--- stderr\n{}", str::from_utf8(&out.stderr).unwrap());
process::exit(1);
}

View File

@ -1,51 +0,0 @@
#[macro_use] extern crate log;
extern crate env_logger;
use std::process;
use std::env;
use std::str;
fn main() {
if env::var("LOG_REGEXP_TEST").ok() == Some(String::from("1")) {
child_main();
} else {
parent_main()
}
}
fn child_main() {
env_logger::init();
info!("XYZ Message");
}
fn run_child(rust_log: String) -> bool {
let exe = env::current_exe().unwrap();
let out = process::Command::new(exe)
.env("LOG_REGEXP_TEST", "1")
.env("RUST_LOG", rust_log)
.output()
.unwrap_or_else(|e| panic!("Unable to start child process: {}", e));
str::from_utf8(out.stderr.as_ref()).unwrap().contains("XYZ Message")
}
fn assert_message_printed(rust_log: &str) {
if !run_child(rust_log.to_string()) {
panic!("RUST_LOG={} should allow the test log message", rust_log)
}
}
fn assert_message_not_printed(rust_log: &str) {
if run_child(rust_log.to_string()) {
panic!("RUST_LOG={} should not allow the test log message", rust_log)
}
}
fn parent_main() {
// test normal log severity levels
assert_message_printed("info");
assert_message_not_printed("warn");
// test of regular expression filters
assert_message_printed("info/XYZ");
assert_message_not_printed("info/XXX");
}

View File

@ -1 +1 @@
{"files":{"CHANGELOG.md":"34c3abc5bfaeb865e9b901c245f7e41f02a96b6be50beef5302458bff548ef3c","Cargo.lock":"c4f7bc54617e5f7c9d3e3597dbf736ccbd0ecbf6bd2594ffa280cff38c5b34d7","Cargo.toml":"1b0382f9c8b4fb862d4e5ce67a05b33891edca607a69a730bfd03f6d94e4e1da","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"7de7e137a0f9f1eb565355c060939a159f687959e50a78fc6e52e7e41f379d15","examples/custom_default_format.rs":"a6fe2b9255248a19e2cac58033ac80ff1fbf78af9786a7331efcbafe469815a2","examples/custom_format.rs":"58ab6ea92b857abe0743757d94c2d21ea4717c03e096fdd9aa0b54c59a8f4875","examples/custom_logger.rs":"723b145a50d6a88efd9d345f0d041a2d326794d19539f9a507f63bd25a2e03a2","examples/default.rs":"7ed1c6a8a8fe457a86676bd3a75c07d4ec7fb54147cf2825c9d299a5878a24cd","examples/direct_logger.rs":"5ae565fab0583c06de4cc3554fb4c8dc64cee8e2e1337b9aafff44e1bfb94e43","examples/filters_from_code.rs":"57edd53e811873c67b3069b4ea8fac619a0d5a507f6462ea4d0682bdf5d84a56","examples/in_tests.rs":"0b714146ab6f38d23394bfa5a5383fca2262a184a7628b8182d57b267e0917e7","examples/syslog_friendly_format.rs":"4269a86f549253bad54c7e8aae03d5ab09959a5c9d798d3fc6c4745cd5d96cd9","rust-toolchain":"d2ec7870533c64024a4f44f3315711f9f809230c2ae70d4a16100b14664d9fe1","src/filter/mod.rs":"80f29ae9395982a488682770fbeb545f8d6a23d1c8e6cdfb1113cab5c15bc2d2","src/filter/regex.rs":"bdf875bac25e089e1e462f5dd01a88678067c24118ecd6268561c6a6af39747d","src/filter/string.rs":"fac54d51189fc0b5d2bff334b7a7e465177b431e3428299e345e1f90062d832e","src/fmt/humantime/extern_impl.rs":"f3087b29eedb8b4d5573621ad206e48a2eac72a77277be3b0e631d7dc9fb7a2e","src/fmt/humantime/mod.rs":"f4111c26cf2ffb85c1d639bd7674d55af7e1736e7e98c52f7be3070046a3253f","src/fmt/humantime/shim_impl.rs":"cce9a252abd5952fa109a72b1dfb85a593d237e22606b2b608a32c69184560e9","src/fmt/mod.rs":"dff0e4613985f7a392182d9b1c1a68d148367d8b9622e37051b5367b5d6f9d04","src/fmt/writer/atty.rs":"09d14097dee61492828daaabdbde9f43251e2cb32e79d66c1c0e63f317761704","src/fmt/writer/mod.rs":"1e0feb4dee3ee86c4c24f49566673e99ec85765869105a07a2fc7436d7640cfe","src/fmt/writer/termcolor/extern_impl.rs":"e743201e9c428cda2df12a50611ccb33407a14f9726f6635a577937bafd5d108","src/fmt/writer/termcolor/mod.rs":"a790f9391a50cd52be6823e3e55942de13a8d12e23d63765342ae9e8dd6d091c","src/fmt/writer/termcolor/shim_impl.rs":"d93786671d6a89fc2912f77f04b8cb0b82d67277d255d15ac31bfc1bc4464e30","src/lib.rs":"fabde9b654547962aded95b0c473abfcb3dec5183b85942b015e3777c0e7fdcb","tests/init-twice-retains-filter.rs":"be5cd2132342d89ede1f5c4266173bb3c4d51cc22a1847f133d299a1c5430ccb","tests/log-in-log.rs":"29fecc65c1e0d1c22d79c97e7ca843ad44a91f27934148d7a05c48899a3f39d8","tests/log_tls_dtors.rs":"7320667d774a9b05037f7bf273fb2574dec0705707692a9cd2f46f4cd5bc68dd","tests/regexp_filter.rs":"a84263c995b534b6479a1d0abadf63f4f0264958ff86d9173d6b2139b82c4dc5"},"package":"54532e3223c5af90a6a757c90b5c5521564b07e5e7a958681bcd2afad421cdcd"}
{"files":{"CHANGELOG.md":"34c3abc5bfaeb865e9b901c245f7e41f02a96b6be50beef5302458bff548ef3c","Cargo.lock":"d71d249c813d01822d617294c433ed958c33389e339ca5c860b9ad81b6c509a6","Cargo.toml":"43aac950cc279366126613c1adb7ddfb4e126c7359d4ccf049fa13808e7ffc17","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"d8f5429aea4c3503ea036548ef0eaa30329f5bcc948c002af3d943df3cd87ef6","examples/custom_default_format.rs":"a6fe2b9255248a19e2cac58033ac80ff1fbf78af9786a7331efcbafe469815a2","examples/custom_format.rs":"58ab6ea92b857abe0743757d94c2d21ea4717c03e096fdd9aa0b54c59a8f4875","examples/custom_logger.rs":"723b145a50d6a88efd9d345f0d041a2d326794d19539f9a507f63bd25a2e03a2","examples/default.rs":"7ed1c6a8a8fe457a86676bd3a75c07d4ec7fb54147cf2825c9d299a5878a24cd","examples/direct_logger.rs":"5ae565fab0583c06de4cc3554fb4c8dc64cee8e2e1337b9aafff44e1bfb94e43","examples/filters_from_code.rs":"57edd53e811873c67b3069b4ea8fac619a0d5a507f6462ea4d0682bdf5d84a56","examples/in_tests.rs":"0b714146ab6f38d23394bfa5a5383fca2262a184a7628b8182d57b267e0917e7","examples/syslog_friendly_format.rs":"4269a86f549253bad54c7e8aae03d5ab09959a5c9d798d3fc6c4745cd5d96cd9","rust-toolchain":"d2ec7870533c64024a4f44f3315711f9f809230c2ae70d4a16100b14664d9fe1","src/filter/mod.rs":"80f29ae9395982a488682770fbeb545f8d6a23d1c8e6cdfb1113cab5c15bc2d2","src/filter/regex.rs":"bdf875bac25e089e1e462f5dd01a88678067c24118ecd6268561c6a6af39747d","src/filter/string.rs":"fac54d51189fc0b5d2bff334b7a7e465177b431e3428299e345e1f90062d832e","src/fmt/humantime/extern_impl.rs":"f3087b29eedb8b4d5573621ad206e48a2eac72a77277be3b0e631d7dc9fb7a2e","src/fmt/humantime/mod.rs":"f4111c26cf2ffb85c1d639bd7674d55af7e1736e7e98c52f7be3070046a3253f","src/fmt/humantime/shim_impl.rs":"cce9a252abd5952fa109a72b1dfb85a593d237e22606b2b608a32c69184560e9","src/fmt/mod.rs":"dff0e4613985f7a392182d9b1c1a68d148367d8b9622e37051b5367b5d6f9d04","src/fmt/writer/atty.rs":"09d14097dee61492828daaabdbde9f43251e2cb32e79d66c1c0e63f317761704","src/fmt/writer/mod.rs":"1e0feb4dee3ee86c4c24f49566673e99ec85765869105a07a2fc7436d7640cfe","src/fmt/writer/termcolor/extern_impl.rs":"e743201e9c428cda2df12a50611ccb33407a14f9726f6635a577937bafd5d108","src/fmt/writer/termcolor/mod.rs":"a790f9391a50cd52be6823e3e55942de13a8d12e23d63765342ae9e8dd6d091c","src/fmt/writer/termcolor/shim_impl.rs":"d93786671d6a89fc2912f77f04b8cb0b82d67277d255d15ac31bfc1bc4464e30","src/lib.rs":"1bd27a89c54366b3e35ad49845e81bbea36cf883382fcf902fbeb6f68c6a7a24","tests/init-twice-retains-filter.rs":"be5cd2132342d89ede1f5c4266173bb3c4d51cc22a1847f133d299a1c5430ccb","tests/log-in-log.rs":"29fecc65c1e0d1c22d79c97e7ca843ad44a91f27934148d7a05c48899a3f39d8","tests/log_tls_dtors.rs":"7320667d774a9b05037f7bf273fb2574dec0705707692a9cd2f46f4cd5bc68dd","tests/regexp_filter.rs":"a84263c995b534b6479a1d0abadf63f4f0264958ff86d9173d6b2139b82c4dc5"},"package":"f26ecb66b4bdca6c1409b40fb255eefc2bd4f6d135dab3c3124f80ffa2a9661e"}

View File

@ -2,9 +2,9 @@
# It is not intended for manual editing.
[[package]]
name = "aho-corasick"
version = "0.7.14"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b476ce7103678b0c6d3d395dbbae31d48ff910bd28be979ba5d48c6351131d0d"
checksum = "7404febffaa47dac81aa44dba71523c9d069b1bdc50a77db41195149e17f68e5"
dependencies = [
"memchr",
]
@ -28,7 +28,7 @@ checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[package]]
name = "env_logger"
version = "0.8.1"
version = "0.8.2"
dependencies = [
"atty",
"humantime",
@ -60,9 +60,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.79"
version = "0.2.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2448f6066e80e3bfc792e9c98bf705b4b0fc6e8ef5b43e5889aff0eaa9c58743"
checksum = "4d58d1b70b004888f764dfbf6a26a3b0342a1632d33968e4a179d8011c760614"
[[package]]
name = "log"
@ -75,15 +75,15 @@ dependencies = [
[[package]]
name = "memchr"
version = "2.3.3"
version = "2.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400"
checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525"
[[package]]
name = "regex"
version = "1.4.1"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8963b85b8ce3074fecffde43b4b0dded83ce2f367dc8d363afc56679f3ee820b"
checksum = "38cf2c13ed4745de91a5eb834e11c00bcc3709e773173b2ce4c56c9fbde04b9c"
dependencies = [
"aho-corasick",
"memchr",
@ -93,9 +93,9 @@ dependencies = [
[[package]]
name = "regex-syntax"
version = "0.6.20"
version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8cab7a364d15cde1e505267766a2d3c4e22a843e1a601f0fa7564c0f82ced11c"
checksum = "3b181ba2dcf07aaccad5448e8ead58db5b742cf85dfe035e2227f137a539a189"
[[package]]
name = "termcolor"

View File

@ -13,7 +13,7 @@
[package]
edition = "2018"
name = "env_logger"
version = "0.8.1"
version = "0.8.2"
authors = ["The Rust Project Developers"]
description = "A logging implementation for `log` which is configured via an environment\nvariable.\n"
documentation = "https://docs.rs/env_logger"

View File

@ -22,7 +22,7 @@ It must be added along with `log` to the project dependencies:
```toml
[dependencies]
log = "0.4.0"
env_logger = "0.8.1"
env_logger = "0.8.2"
```
`env_logger` must be initialized as early as possible in the project. After it's initialized, you can use the `log` macros to do actual logging.
@ -59,7 +59,7 @@ Tests can use the `env_logger` crate to see log messages generated during that t
log = "0.4.0"
[dev-dependencies]
env_logger = "0.8.1"
env_logger = "0.8.2"
```
```rust

View File

@ -232,7 +232,7 @@
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/static/images/favicon.ico",
html_root_url = "https://docs.rs/env_logger/0.8.1"
html_root_url = "https://docs.rs/env_logger/0.8.2"
)]
#![cfg_attr(test, deny(warnings))]
// When compiled for the rustc compiler itself we want to make sure that this is

View File

@ -1 +1 @@
{"files":{"Cargo.toml":"ae7f884d13f5d849afd58b5db15510396832df7f648b0095e43bfdfa600b2ba3","LICENSE-APACHE":"c6596eb7be8581c18be736c846fb9173b69eccf6ef94c5135893ec56bd92ba08","LICENSE-MIT":"f6deca8261a8f4a3403dc74c725c46051157fd36c27cd4b100277eb1f303ad11","README.md":"e4bb65f28ddffb11d7eb337e9585947651f2fc11a5e4290f0ca126e21c582c1e","benches/datetime_format.rs":"a44c7ffb3c9515e92828564df8f91a86470343a2fa7e1a08bc2bc7397ba2591c","benches/datetime_parse.rs":"336a241755ccfa546d1840e56a40218c4f98f22d7d274829c5102ec280f2d963","bulk.yaml":"17c2548388e0cd3a63473021a2f1e4ddedee082d79d9167cb31ad06a1890d3fc","src/date.rs":"ea9924869a2484e333df2a845009593dd0062bb3b3e1a5ef9cefc05ec0a41196","src/duration.rs":"a5d4756451f495a3d5df0c872caa6304dd81ae075f0e204c8145c11c7c8f698b","src/lib.rs":"59dcc8a1ed89ecde199d59a7f71e550b461f87858b4becffb0a183994bafdd7c","src/wrapper.rs":"5bbdaf43256b445a8ca3a6b3eded9dd4fa8fb4dadf3683a5bac9648d91117396","vagga.yaml":"59761e5138a3015ef5654fec095ac8f1587cd23529b37822dd540b866fe4cd5b"},"package":"df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f"}
{"files":{"Cargo.toml":"74afb84b99fa5ba0f58b483df1ef0749821d4c2b5c5a9df299cb1cc0002c236f","LICENSE-APACHE":"c6596eb7be8581c18be736c846fb9173b69eccf6ef94c5135893ec56bd92ba08","LICENSE-MIT":"f6deca8261a8f4a3403dc74c725c46051157fd36c27cd4b100277eb1f303ad11","README.md":"e4bb65f28ddffb11d7eb337e9585947651f2fc11a5e4290f0ca126e21c582c1e","benches/datetime_format.rs":"ffe2e459e9b48e8fdbfb3686f6297257d66b29369ecd6750ae9fbba527ccc681","benches/datetime_parse.rs":"8039c4bd5f1795dbb54e1e39da5988f1d2df6c86c42d8fd378094fc78074d31e","bulk.yaml":"17c2548388e0cd3a63473021a2f1e4ddedee082d79d9167cb31ad06a1890d3fc","src/date.rs":"3f21e426f449e434e5973db9bd06a09d3f0cd6aa77708dbf0e3230bce7e48f44","src/duration.rs":"5a91e6e94c9ca2078ede527a4c159ddfc1cd67ade0d75a1c1db5474b40d2916f","src/lib.rs":"ad4dbed28080d9a64ef0100c96b20ff4988d9dde908f56e28ece7252f5932990","src/wrapper.rs":"badc640e77379a42b2fcb728337d60a764b7f00a1b5b1d50c7372ddc20941967","vagga.yaml":"8396fe1510117c1c7bc3e896b62290dcf2dd300346071297018b0077ad9e45ce"},"package":"3c1ad908cc71012b7bea4d0c53ba96a8cba9962f048fa68d143376143d863b7a"}

View File

@ -11,8 +11,9 @@
# will likely look very different (and much more reasonable)
[package]
edition = "2018"
name = "humantime"
version = "1.3.0"
version = "2.0.1"
authors = ["Paul Colomiets <paul@colomiets.name>"]
description = " A parser and formatter for std::time::{Duration, SystemTime}\n"
homepage = "https://github.com/tailhook/humantime"
@ -21,17 +22,16 @@ readme = "README.md"
keywords = ["time", "human", "human-friendly", "parser", "duration"]
categories = ["date-and-time"]
license = "MIT/Apache-2.0"
repository = "https://github.com/tailhook/humantime"
[lib]
name = "humantime"
path = "src/lib.rs"
[dependencies.quick-error]
version = "1.0.0"
[dev-dependencies.chrono]
version = "0.4.0"
version = "0.4"
[dev-dependencies.rand]
version = "0.4.2"
version = "0.6"
[dev-dependencies.time]
version = "0.1.39"
version = "0.1"

View File

@ -1,16 +1,14 @@
#![feature(test)]
extern crate chrono;
extern crate humantime;
extern crate test;
use std::io::Write;
use std::time::{Duration, UNIX_EPOCH};
use humantime::format_rfc3339;
use humantime::format_rfc3339;
#[bench]
fn rfc3339_humantime_seconds(b: &mut test::Bencher) {
let time = UNIX_EPOCH + Duration::new(1483228799, 0);
let time = UNIX_EPOCH + Duration::new(1_483_228_799, 0);
let mut buf = Vec::with_capacity(100);
b.iter(|| {
buf.truncate(0);
@ -28,11 +26,11 @@ fn rfc3339_chrono(b: &mut test::Bencher) {
use chrono::format::Pad::*;
let time = DateTime::<Utc>::from_utc(
NaiveDateTime::from_timestamp(1483228799, 0), Utc);
NaiveDateTime::from_timestamp(1_483_228_799, 0), Utc);
let mut buf = Vec::with_capacity(100);
// formatting code from env_logger
const ITEMS: &'static [Item<'static>] = {
const ITEMS: &[Item<'static>] = {
&[
Numeric(Year, Zero),
Literal("-"),

View File

@ -1,12 +1,9 @@
#![feature(test)]
extern crate chrono;
extern crate humantime;
extern crate test;
use chrono::{DateTime};
use humantime::parse_rfc3339;
#[bench]
fn rfc3339_humantime_seconds(b: &mut test::Bencher) {
b.iter(|| {

View File

@ -1,3 +1,4 @@
use std::error::Error as StdError;
use std::fmt;
use std::str;
use std::time::{SystemTime, Duration, UNIX_EPOCH};
@ -26,26 +27,30 @@ mod max {
all(target_arch="wasm32", not(target_os="emscripten")),
))]
mod max {
pub const SECONDS: u64 = 253402300800-1; // last second of year 9999
pub const SECONDS: u64 = 253_402_300_800-1; // last second of year 9999
#[allow(unused)]
pub const TIMESTAMP: &'static str = "9999-12-31T23:59:59Z";
pub const TIMESTAMP: &str = "9999-12-31T23:59:59Z";
}
quick_error! {
/// Error parsing datetime (timestamp)
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Error {
/// Numeric component is out of range
OutOfRange {
display("numeric component is out of range")
}
/// Bad character where digit is expected
InvalidDigit {
display("bad character where digit is expected")
}
/// Other formatting errors
InvalidFormat {
display("timestamp format is invalid")
/// Error parsing datetime (timestamp)
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Error {
/// Numeric component is out of range
OutOfRange,
/// Bad character where digit is expected
InvalidDigit,
/// Other formatting errors
InvalidFormat,
}
impl StdError for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::OutOfRange => write!(f, "numeric component is out of range"),
Error::InvalidDigit => write!(f, "bad character where digit is expected"),
Error::InvalidFormat => write!(f, "timestamp format is invalid"),
}
}
}
@ -85,7 +90,7 @@ pub fn parse_rfc3339(s: &str) -> Result<SystemTime, Error> {
if b[10] != b'T' || b[b.len()-1] != b'Z' {
return Err(Error::InvalidFormat);
}
return parse_rfc3339_weak(s);
parse_rfc3339_weak(s)
}
/// Parse RFC3339-like timestamp `2018-02-14 00:28:07`
@ -172,10 +177,8 @@ pub fn parse_rfc3339_weak(s: &str) -> Result<SystemTime, Error> {
nanos += mult * (b[idx] - b'0') as u32;
mult /= 10;
}
} else {
if b.len() != 19 && (b.len() > 20 || b[19] != b'Z') {
return Err(Error::InvalidFormat);
}
} else if b.len() != 19 && (b.len() > 20 || b[19] != b'Z') {
return Err(Error::InvalidFormat);
}
let total_seconds = time + days * 86400;
@ -183,11 +186,11 @@ pub fn parse_rfc3339_weak(s: &str) -> Result<SystemTime, Error> {
return Err(Error::OutOfRange);
}
return Ok(UNIX_EPOCH + Duration::new(total_seconds, nanos));
Ok(UNIX_EPOCH + Duration::new(total_seconds, nanos))
}
fn is_leap_year(y: u64) -> bool {
y % 4 == 0 && (!(y % 100 == 0) || y % 400 == 0)
y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)
}
/// Format an RFC3339 timestamp `2018-02-14T00:28:07Z`
@ -198,7 +201,7 @@ fn is_leap_year(y: u64) -> bool {
///
/// The value is always UTC and ignores system timezone.
pub fn format_rfc3339(system_time: SystemTime) -> Rfc3339Timestamp {
return Rfc3339Timestamp(system_time, Precision::Smart);
Rfc3339Timestamp(system_time, Precision::Smart)
}
/// Format an RFC3339 timestamp `2018-02-14T00:28:07Z`
@ -207,7 +210,7 @@ pub fn format_rfc3339(system_time: SystemTime) -> Rfc3339Timestamp {
///
/// The value is always UTC and ignores system timezone.
pub fn format_rfc3339_seconds(system_time: SystemTime) -> Rfc3339Timestamp {
return Rfc3339Timestamp(system_time, Precision::Seconds);
Rfc3339Timestamp(system_time, Precision::Seconds)
}
/// Format an RFC3339 timestamp `2018-02-14T00:28:07.000Z`
@ -216,7 +219,7 @@ pub fn format_rfc3339_seconds(system_time: SystemTime) -> Rfc3339Timestamp {
///
/// The value is always UTC and ignores system timezone.
pub fn format_rfc3339_millis(system_time: SystemTime) -> Rfc3339Timestamp {
return Rfc3339Timestamp(system_time, Precision::Millis);
Rfc3339Timestamp(system_time, Precision::Millis)
}
/// Format an RFC3339 timestamp `2018-02-14T00:28:07.000000Z`
@ -225,7 +228,7 @@ pub fn format_rfc3339_millis(system_time: SystemTime) -> Rfc3339Timestamp {
///
/// The value is always UTC and ignores system timezone.
pub fn format_rfc3339_micros(system_time: SystemTime) -> Rfc3339Timestamp {
return Rfc3339Timestamp(system_time, Precision::Micros);
Rfc3339Timestamp(system_time, Precision::Micros)
}
/// Format an RFC3339 timestamp `2018-02-14T00:28:07.000000000Z`
@ -234,7 +237,7 @@ pub fn format_rfc3339_micros(system_time: SystemTime) -> Rfc3339Timestamp {
///
/// The value is always UTC and ignores system timezone.
pub fn format_rfc3339_nanos(system_time: SystemTime) -> Rfc3339Timestamp {
return Rfc3339Timestamp(system_time, Precision::Nanos);
Rfc3339Timestamp(system_time, Precision::Nanos)
}
impl fmt::Display for Rfc3339Timestamp {
@ -246,7 +249,7 @@ impl fmt::Display for Rfc3339Timestamp {
let secs_since_epoch = dur.as_secs();
let nanos = dur.subsec_nanos();
if secs_since_epoch >= 253402300800 { // year 9999
if secs_since_epoch >= 253_402_300_800 { // year 9999
return Err(fmt::Error);
}
@ -353,18 +356,17 @@ impl fmt::Display for Rfc3339Timestamp {
};
// we know our chars are all ascii
f.write_str(unsafe { str::from_utf8_unchecked(&buf[..offset+1]) })
f.write_str(str::from_utf8(&buf[..=offset]).expect("Conversion to utf8 failed"))
}
}
#[cfg(test)]
mod test {
extern crate time;
extern crate rand;
use std::str::from_utf8;
use self::rand::Rng;
use std::time::{UNIX_EPOCH, SystemTime, Duration};
use rand::Rng;
use super::{parse_rfc3339, parse_rfc3339_weak, format_rfc3339};
use super::{format_rfc3339_millis, format_rfc3339_micros};
use super::{format_rfc3339_nanos};
@ -374,7 +376,7 @@ mod test {
let s = time::at_utc(time::Timespec { sec: sec as i64, nsec: 0 })
.rfc3339().to_string();
let time = UNIX_EPOCH + Duration::new(sec, 0);
return (s, time)
(s, time)
}
#[test]
@ -394,9 +396,9 @@ mod test {
assert_eq!(parse_rfc3339("1970-01-01T00:00:01Z").unwrap(),
UNIX_EPOCH + Duration::new(1, 0));
assert_eq!(parse_rfc3339("2018-02-13T23:08:32Z").unwrap(),
UNIX_EPOCH + Duration::new(1518563312, 0));
UNIX_EPOCH + Duration::new(1_518_563_312, 0));
assert_eq!(parse_rfc3339("2012-01-01T00:00:00Z").unwrap(),
UNIX_EPOCH + Duration::new(1325376000, 0));
UNIX_EPOCH + Duration::new(1_325_376_000, 0));
}
#[test]
@ -408,10 +410,10 @@ mod test {
format_rfc3339(UNIX_EPOCH + Duration::new(1, 0)).to_string(),
"1970-01-01T00:00:01Z");
assert_eq!(
format_rfc3339(UNIX_EPOCH + Duration::new(1518563312, 0)).to_string(),
format_rfc3339(UNIX_EPOCH + Duration::new(1_518_563_312, 0)).to_string(),
"2018-02-13T23:08:32Z");
assert_eq!(
format_rfc3339(UNIX_EPOCH + Duration::new(1325376000, 0)).to_string(),
format_rfc3339(UNIX_EPOCH + Duration::new(1_325_376_000, 0)).to_string(),
"2012-01-01T00:00:00Z");
}
@ -423,7 +425,7 @@ mod test {
"1970-01-01T00:00:00.000Z");
assert_eq!(
format_rfc3339_millis(UNIX_EPOCH +
Duration::new(1518563312, 123_000_000)).to_string(),
Duration::new(1_518_563_312, 123_000_000)).to_string(),
"2018-02-13T23:08:32.123Z");
}
@ -435,11 +437,11 @@ mod test {
"1970-01-01T00:00:00.000000Z");
assert_eq!(
format_rfc3339_micros(UNIX_EPOCH +
Duration::new(1518563312, 123_000_000)).to_string(),
Duration::new(1_518_563_312, 123_000_000)).to_string(),
"2018-02-13T23:08:32.123000Z");
assert_eq!(
format_rfc3339_micros(UNIX_EPOCH +
Duration::new(1518563312, 456_123_000)).to_string(),
Duration::new(1_518_563_312, 456_123_000)).to_string(),
"2018-02-13T23:08:32.456123Z");
}
@ -451,11 +453,11 @@ mod test {
"1970-01-01T00:00:00.000000000Z");
assert_eq!(
format_rfc3339_nanos(UNIX_EPOCH +
Duration::new(1518563312, 123_000_000)).to_string(),
Duration::new(1_518_563_312, 123_000_000)).to_string(),
"2018-02-13T23:08:32.123000000Z");
assert_eq!(
format_rfc3339_nanos(UNIX_EPOCH +
Duration::new(1518563312, 789_456_123)).to_string(),
Duration::new(1_518_563_312, 789_456_123)).to_string(),
"2018-02-13T23:08:32.789456123Z");
}
@ -469,13 +471,13 @@ mod test {
#[test]
fn leap_second() {
assert_eq!(parse_rfc3339("2016-12-31T23:59:60Z").unwrap(),
UNIX_EPOCH + Duration::new(1483228799, 0));
UNIX_EPOCH + Duration::new(1_483_228_799, 0));
}
#[test]
fn first_731_days() {
let year_start = 0; // 1970
for day in 0.. (365 * 2 + 1) { // scan leap year and non-leap year
for day in 0..= 365 * 2 { // scan leap year and non-leap year
let (s, time) = from_sec(year_start + day * 86400);
assert_eq!(parse_rfc3339(&s).unwrap(), time);
assert_eq!(format_rfc3339(time).to_string(), s);
@ -484,8 +486,8 @@ mod test {
#[test]
fn the_731_consecutive_days() {
let year_start = 1325376000; // 2012
for day in 0.. (365 * 2 + 1) { // scan leap year and non-leap year
let year_start = 1_325_376_000; // 2012
for day in 0..= 365 * 2 { // scan leap year and non-leap year
let (s, time) = from_sec(year_start + day * 86400);
assert_eq!(parse_rfc3339(&s).unwrap(), time);
assert_eq!(format_rfc3339(time).to_string(), s);
@ -494,7 +496,7 @@ mod test {
#[test]
fn all_86400_seconds() {
let day_start = 1325376000;
let day_start = 1_325_376_000;
for second in 0..86400 { // scan leap year and non-leap year
let (s, time) = from_sec(day_start + second);
assert_eq!(parse_rfc3339(&s).unwrap(), time);
@ -516,7 +518,7 @@ mod test {
#[test]
fn random_wide_range() {
for _ in 0..100000 {
for _ in 0..100_000 {
let sec = rand::thread_rng().gen_range(0, max::SECONDS);
let (s, time) = from_sec(sec);
assert_eq!(parse_rfc3339(&s).unwrap(), time);
@ -527,8 +529,8 @@ mod test {
#[test]
fn milliseconds() {
assert_eq!(parse_rfc3339("1970-01-01T00:00:00.123Z").unwrap(),
UNIX_EPOCH + Duration::new(0, 123000000));
assert_eq!(format_rfc3339(UNIX_EPOCH + Duration::new(0, 123000000))
UNIX_EPOCH + Duration::new(0, 123_000_000));
assert_eq!(format_rfc3339(UNIX_EPOCH + Duration::new(0, 123_000_000))
.to_string(), "1970-01-01T00:00:00.123000000Z");
}
@ -596,15 +598,15 @@ mod test {
parse_rfc3339("1970-01-01 00:00:00").unwrap_err();
assert_eq!(parse_rfc3339_weak("1970-01-01 00:00:00.000123").unwrap(),
UNIX_EPOCH + Duration::new(0, 123000));
UNIX_EPOCH + Duration::new(0, 123_000));
parse_rfc3339("1970-01-01 00:00:00.000123").unwrap_err();
assert_eq!(parse_rfc3339_weak("1970-01-01T00:00:00.000123").unwrap(),
UNIX_EPOCH + Duration::new(0, 123000));
UNIX_EPOCH + Duration::new(0, 123_000));
parse_rfc3339("1970-01-01T00:00:00.000123").unwrap_err();
assert_eq!(parse_rfc3339_weak("1970-01-01 00:00:00.000123Z").unwrap(),
UNIX_EPOCH + Duration::new(0, 123000));
UNIX_EPOCH + Duration::new(0, 123_000));
parse_rfc3339("1970-01-01 00:00:00.000123Z").unwrap_err();
assert_eq!(parse_rfc3339_weak("1970-01-01 00:00:00Z").unwrap(),

View File

@ -1,60 +1,79 @@
use std::error::Error as StdError;
use std::fmt;
use std::str::Chars;
use std::time::Duration;
use std::error::Error as StdError;
quick_error! {
/// Error parsing human-friendly duration
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Error {
/// Invalid character during parsing
///
/// More specifically anything that is not alphanumeric is prohibited
///
/// The field is an byte offset of the character in the string.
InvalidCharacter(offset: usize) {
display("invalid character at {}", offset)
description("invalid character")
}
/// Non-numeric value where number is expected
///
/// This usually means that either time unit is broken into words,
/// e.g. `m sec` instead of `msec`, or just number is omitted,
/// for example `2 hours min` instead of `2 hours 1 min`
///
/// The field is an byte offset of the errorneous character
/// in the string.
NumberExpected(offset: usize) {
display("expected number at {}", offset)
description("expected number")
}
/// Unit in the number is not one of allowed units
///
/// See documentation of `parse_duration` for the list of supported
/// time units.
///
/// The two fields are start and end (exclusive) of the slice from
/// the original string, containing errorneous value
UnknownUnit(start: usize, end: usize) {
display("unknown unit at {}-{}", start, end)
description("unknown unit")
}
/// The numeric value is too large
///
/// Usually this means value is too large to be useful. If user writes
/// data in subsecond units, then the maximum is about 3k years. When
/// using seconds, or larger units, the limit is even larger.
NumberOverflow {
display(self_) -> ("{}", self_.description())
description("number is too large")
}
/// The value was an empty string (or consists only whitespace)
Empty {
display(self_) -> ("{}", self_.description())
description("value was empty")
/// Error parsing human-friendly duration
#[derive(Debug, PartialEq, Clone)]
pub enum Error {
/// Invalid character during parsing
///
/// More specifically anything that is not alphanumeric is prohibited
///
/// The field is an byte offset of the character in the string.
InvalidCharacter(usize),
/// Non-numeric value where number is expected
///
/// This usually means that either time unit is broken into words,
/// e.g. `m sec` instead of `msec`, or just number is omitted,
/// for example `2 hours min` instead of `2 hours 1 min`
///
/// The field is an byte offset of the errorneous character
/// in the string.
NumberExpected(usize),
/// Unit in the number is not one of allowed units
///
/// See documentation of `parse_duration` for the list of supported
/// time units.
///
/// The two fields are start and end (exclusive) of the slice from
/// the original string, containing errorneous value
UnknownUnit {
/// Start of the invalid unit inside the original string
start: usize,
/// End of the invalid unit inside the original string
end: usize,
/// The unit verbatim
unit: String,
/// A number associated with the unit
value: u64,
},
/// The numeric value is too large
///
/// Usually this means value is too large to be useful. If user writes
/// data in subsecond units, then the maximum is about 3k years. When
/// using seconds, or larger units, the limit is even larger.
NumberOverflow,
/// The value was an empty string (or consists only whitespace)
Empty,
}
impl StdError for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::InvalidCharacter(offset) => write!(f, "invalid character at {}", offset),
Error::NumberExpected(offset) => write!(f, "expected number at {}", offset),
Error::UnknownUnit { unit, value, .. } if &unit == &"" => {
write!(f,
"time unit needed, for example {0}sec or {0}ms",
value,
)
}
Error::UnknownUnit { unit, .. } => {
write!(
f,
"unknown time unit {:?}, \
supported units: ns, us, ms, sec, min, hours, days, \
weeks, months, years (and few variations)",
unit
)
}
Error::NumberOverflow => write!(f, "number is too large"),
Error::Empty => write!(f, "value was empty"),
}
}
}
/// A wrapper type that allows you to Display a Duration
@ -90,7 +109,7 @@ impl<'a> Parser<'a> {
let off = self.off();
for c in self.iter.by_ref() {
match c {
'0'...'9' => {
'0'..='9' => {
return Ok(Some(c as u64 - '0' as u64));
}
c if c.is_whitespace() => continue,
@ -99,48 +118,54 @@ impl<'a> Parser<'a> {
}
}
}
return Ok(None);
Ok(None)
}
fn parse_unit(&mut self, n: u64, start: usize, end: usize)
-> Result<(), Error>
{
let (mut sec, nsec) = match &self.src[start..end] {
"nanos" | "nsec" | "ns" => (0u64, n),
"usec" | "us" => (0u64, try!(n.mul(1000))),
"millis" | "msec" | "ms" => (0u64, try!(n.mul(1000_000))),
"usec" | "us" => (0u64, n.mul(1000)?),
"millis" | "msec" | "ms" => (0u64, n.mul(1_000_000)?),
"seconds" | "second" | "secs" | "sec" | "s" => (n, 0),
"minutes" | "minute" | "min" | "mins" | "m"
=> (try!(n.mul(60)), 0),
"hours" | "hour" | "hr" | "hrs" | "h" => (try!(n.mul(3600)), 0),
"days" | "day" | "d" => (try!(n.mul(86400)), 0),
"weeks" | "week" | "w" => (try!(n.mul(86400*7)), 0),
"months" | "month" | "M" => (try!(n.mul(2630016)), 0), // 30.44d
"years" | "year" | "y" => (try!(n.mul(31557600)), 0), // 365.25d
_ => return Err(Error::UnknownUnit(start, end)),
=> (n.mul(60)?, 0),
"hours" | "hour" | "hr" | "hrs" | "h" => (n.mul(3600)?, 0),
"days" | "day" | "d" => (n.mul(86400)?, 0),
"weeks" | "week" | "w" => (n.mul(86400*7)?, 0),
"months" | "month" | "M" => (n.mul(2_630_016)?, 0), // 30.44d
"years" | "year" | "y" => (n.mul(31_557_600)?, 0), // 365.25d
_ => {
return Err(Error::UnknownUnit {
start, end,
unit: self.src[start..end].to_string(),
value: n,
});
}
};
let mut nsec = try!(self.current.1.add(nsec));
if nsec > 1000_000_000 {
sec = try!(sec.add(nsec / 1000_000_000));
nsec %= 1000_000_000;
let mut nsec = self.current.1.add(nsec)?;
if nsec > 1_000_000_000 {
sec = sec.add(nsec / 1_000_000_000)?;
nsec %= 1_000_000_000;
}
sec = try!(self.current.0.add(sec));
sec = self.current.0.add(sec)?;
self.current = (sec, nsec);
Ok(())
}
fn parse(mut self) -> Result<Duration, Error> {
let mut n = try!(try!(self.parse_first_char()).ok_or(Error::Empty));
let mut n = self.parse_first_char()?.ok_or(Error::Empty)?;
'outer: loop {
let mut off = self.off();
while let Some(c) = self.iter.next() {
match c {
'0'...'9' => {
n = try!(n.checked_mul(10)
'0'..='9' => {
n = n.checked_mul(10)
.and_then(|x| x.checked_add(c as u64 - '0' as u64))
.ok_or(Error::NumberOverflow));
.ok_or(Error::NumberOverflow)?;
}
c if c.is_whitespace() => {}
'a'...'z' | 'A'...'Z' => {
'a'..='z' | 'A'..='Z' => {
break;
}
_ => {
@ -153,21 +178,21 @@ impl<'a> Parser<'a> {
let mut off = self.off();
while let Some(c) = self.iter.next() {
match c {
'0'...'9' => {
try!(self.parse_unit(n, start, off));
'0'..='9' => {
self.parse_unit(n, start, off)?;
n = c as u64 - '0' as u64;
continue 'outer;
}
c if c.is_whitespace() => break,
'a'...'z' | 'A'...'Z' => {}
'a'..='z' | 'A'..='Z' => {}
_ => {
return Err(Error::InvalidCharacter(off));
}
}
off = self.off();
}
try!(self.parse_unit(n, start, off));
n = match try!(self.parse_first_char()) {
self.parse_unit(n, start, off)?;
n = match self.parse_first_char()? {
Some(n) => n,
None => return Ok(
Duration::new(self.current.0, self.current.1 as u32)),
@ -182,7 +207,7 @@ impl<'a> Parser<'a> {
/// The duration object is a concatenation of time spans. Where each time
/// span is an integer number and a suffix. Supported suffixes:
///
/// * `nsec`, `ns` -- microseconds
/// * `nsec`, `ns` -- nanoseconds
/// * `usec`, `us` -- microseconds
/// * `msec`, `ms` -- milliseconds
/// * `seconds`, `second`, `sec`, `s`
@ -270,10 +295,10 @@ impl fmt::Display for FormattedDuration {
return Ok(());
}
let years = secs / 31557600; // 365.25d
let ydays = secs % 31557600;
let months = ydays / 2630016; // 30.44d
let mdays = ydays % 2630016;
let years = secs / 31_557_600; // 365.25d
let ydays = secs % 31_557_600;
let months = ydays / 2_630_016; // 30.44d
let mdays = ydays % 2_630_016;
let days = mdays / 86400;
let day_secs = mdays % 86400;
let hours = day_secs / 3600;
@ -300,23 +325,24 @@ impl fmt::Display for FormattedDuration {
#[cfg(test)]
mod test {
extern crate rand;
use std::time::Duration;
use self::rand::Rng;
use rand::Rng;
use super::{parse_duration, format_duration};
use super::Error;
#[test]
#[allow(clippy::cognitive_complexity)]
fn test_units() {
assert_eq!(parse_duration("17nsec"), Ok(Duration::new(0, 17)));
assert_eq!(parse_duration("17nanos"), Ok(Duration::new(0, 17)));
assert_eq!(parse_duration("33ns"), Ok(Duration::new(0, 33)));
assert_eq!(parse_duration("3usec"), Ok(Duration::new(0, 3000)));
assert_eq!(parse_duration("78us"), Ok(Duration::new(0, 78000)));
assert_eq!(parse_duration("31msec"), Ok(Duration::new(0, 31000000)));
assert_eq!(parse_duration("31millis"), Ok(Duration::new(0, 31000000)));
assert_eq!(parse_duration("6ms"), Ok(Duration::new(0, 6000000)));
assert_eq!(parse_duration("31msec"), Ok(Duration::new(0, 31_000_000)));
assert_eq!(parse_duration("31millis"), Ok(Duration::new(0, 31_000_000)));
assert_eq!(parse_duration("6ms"), Ok(Duration::new(0, 6_000_000)));
assert_eq!(parse_duration("3000s"), Ok(Duration::new(3000, 0)));
assert_eq!(parse_duration("300sec"), Ok(Duration::new(300, 0)));
assert_eq!(parse_duration("300secs"), Ok(Duration::new(300, 0)));
@ -333,17 +359,17 @@ mod test {
assert_eq!(parse_duration("1hour"), Ok(Duration::new(3600, 0)));
assert_eq!(parse_duration("24hours"), Ok(Duration::new(86400, 0)));
assert_eq!(parse_duration("1day"), Ok(Duration::new(86400, 0)));
assert_eq!(parse_duration("2days"), Ok(Duration::new(172800, 0)));
assert_eq!(parse_duration("365d"), Ok(Duration::new(31536000, 0)));
assert_eq!(parse_duration("1week"), Ok(Duration::new(604800, 0)));
assert_eq!(parse_duration("7weeks"), Ok(Duration::new(4233600, 0)));
assert_eq!(parse_duration("52w"), Ok(Duration::new(31449600, 0)));
assert_eq!(parse_duration("1month"), Ok(Duration::new(2630016, 0)));
assert_eq!(parse_duration("3months"), Ok(Duration::new(3*2630016, 0)));
assert_eq!(parse_duration("12M"), Ok(Duration::new(31560192, 0)));
assert_eq!(parse_duration("1year"), Ok(Duration::new(31557600, 0)));
assert_eq!(parse_duration("7years"), Ok(Duration::new(7*31557600, 0)));
assert_eq!(parse_duration("17y"), Ok(Duration::new(536479200, 0)));
assert_eq!(parse_duration("2days"), Ok(Duration::new(172_800, 0)));
assert_eq!(parse_duration("365d"), Ok(Duration::new(31_536_000, 0)));
assert_eq!(parse_duration("1week"), Ok(Duration::new(604_800, 0)));
assert_eq!(parse_duration("7weeks"), Ok(Duration::new(4_233_600, 0)));
assert_eq!(parse_duration("52w"), Ok(Duration::new(31_449_600, 0)));
assert_eq!(parse_duration("1month"), Ok(Duration::new(2_630_016, 0)));
assert_eq!(parse_duration("3months"), Ok(Duration::new(3*2_630_016, 0)));
assert_eq!(parse_duration("12M"), Ok(Duration::new(31_560_192, 0)));
assert_eq!(parse_duration("1year"), Ok(Duration::new(31_557_600, 0)));
assert_eq!(parse_duration("7years"), Ok(Duration::new(7*31_557_600, 0)));
assert_eq!(parse_duration("17y"), Ok(Duration::new(536_479_200, 0)));
}
#[test]
@ -364,7 +390,7 @@ mod test {
#[test]
fn random_second() {
for _ in 0..10000 {
let sec = rand::thread_rng().gen_range(0, 253370764800);
let sec = rand::thread_rng().gen_range(0, 253_370_764_800);
let d = Duration::new(sec, 0);
assert_eq!(d,
parse_duration(&format_duration(d).to_string()).unwrap());
@ -374,7 +400,7 @@ mod test {
#[test]
fn random_any() {
for _ in 0..10000 {
let sec = rand::thread_rng().gen_range(0, 253370764800);
let sec = rand::thread_rng().gen_range(0, 253_370_764_800);
let nanos = rand::thread_rng().gen_range(0, 1_000_000_000);
let d = Duration::new(sec, nanos);
assert_eq!(d,
@ -408,4 +434,16 @@ mod test {
assert_eq!(parse_duration("10000000000000y"),
Err(Error::NumberOverflow));
}
#[test]
fn test_nice_error_message() {
assert_eq!(parse_duration("123").unwrap_err().to_string(),
"time unit needed, for example 123sec or 123ms");
assert_eq!(parse_duration("10 months 1").unwrap_err().to_string(),
"time unit needed, for example 1sec or 1ms");
assert_eq!(parse_duration("10nights").unwrap_err().to_string(),
"unknown time unit \"nights\", supported units: \
ns, us, ms, sec, min, hours, days, weeks, months, \
years (and few variations)");
}
}

View File

@ -10,24 +10,25 @@
//! Timestamp parsing/formatting is super-fast because format is basically
//! fixed.
//!
//! See [serde-humantime] for serde integration.
//! See [humantime-serde] for serde integration (previous crate [serde-humantime] looks unmaintained).
//!
//! [serde-humantime]: https://docs.rs/serde-humantime/0.1.1/serde_humantime/
//! [humantime-serde]: https://docs.rs/humantime-serde
#![forbid(unsafe_code)]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#[macro_use] extern crate quick_error;
mod duration;
mod wrapper;
mod date;
pub use duration::{parse_duration, Error as DurationError};
pub use duration::{format_duration, FormattedDuration};
pub use wrapper::{Duration, Timestamp};
pub use date::{parse_rfc3339, parse_rfc3339_weak, Error as TimestampError};
pub use date::{
pub use self::duration::{parse_duration, Error as DurationError};
pub use self::duration::{format_duration, FormattedDuration};
pub use self::wrapper::{Duration, Timestamp};
pub use self::date::{parse_rfc3339, parse_rfc3339_weak, Error as TimestampError};
pub use self::date::{
format_rfc3339, format_rfc3339_micros, format_rfc3339_millis, format_rfc3339_nanos,
format_rfc3339_seconds,
};
pub use date::{Rfc3339Timestamp};
pub use self::date::{Rfc3339Timestamp};

View File

@ -3,8 +3,8 @@ use std::ops::Deref;
use std::fmt;
use std::time::{Duration as StdDuration, SystemTime};
use duration::{self, parse_duration, format_duration};
use date::{self, parse_rfc3339_weak, format_rfc3339};
use crate::duration::{self, parse_duration, format_duration};
use crate::date::{self, parse_rfc3339_weak, format_rfc3339};
/// A wrapper for duration that has `FromStr` implementation
///

View File

@ -49,7 +49,7 @@ containers:
- !Install [ca-certificates, build-essential, vim]
- !TarInstall
url: "https://static.rust-lang.org/dist/rust-1.24.0-x86_64-unknown-linux-gnu.tar.gz"
url: "https://static.rust-lang.org/dist/rust-1.31.0-x86_64-unknown-linux-gnu.tar.gz"
script: "./install.sh --prefix=/usr \
--components=rustc,rust-std-x86_64-unknown-linux-gnu,cargo"
- &bulk !Tar
@ -70,7 +70,7 @@ containers:
- !Install [ca-certificates, build-essential, vim]
- !TarInstall
url: "https://static.rust-lang.org/dist/rust-1.24.0-i686-unknown-linux-gnu.tar.gz"
url: "https://static.rust-lang.org/dist/rust-1.31.0-i686-unknown-linux-gnu.tar.gz"
script: "./install.sh --prefix=/usr \
--components=rustc,rust-std-i686-unknown-linux-gnu,cargo"

View File

@ -1 +1 @@
{"files":{"Cargo.toml":"b86768e41158d58321bde57049f0907d2066df8815e65329d8cfbed99955c18c","LICENCE":"5b0ae40d1a35f7ae6591a28e44771240e6a88cb03a66c9189a45b9681639b466","README.md":"98860ec5d46ac8f1d3a3f33600629b942f774a35a511ddedffc9a227a3822e2c","rustfmt.toml":"9bbb759b3914c49c8060bcdeeb7786f4aec083d30bcfe236bbd48d8388d06103","src/date.rs":"6378f0919e01cd41c2862fbc4d4029915a7d48324ede584daea0b5b1324cbb51","src/de.rs":"ecdd87f5fe788b5155e68b2490cb7e97adcd0bc83fe3edf75a132fba59b772ae","src/dictionary.rs":"9b8194d3e339a300de5d0fb39529d976a5f86947f3997086594d2be2f795859b","src/error.rs":"2ed8ce5c33071847abb00b27472be352d5bceb92a6ad0b8724f630570e956430","src/integer.rs":"131f528878adc5c0f33c8ad1563c06b397cb2ae5148c2bb9318203a2477d70e0","src/lib.rs":"7535b82d51ebfccf52539ac75d3fab71832e12d776a4342ce7d6786bfc9f1b30","src/ser.rs":"ea4ed049abef09c7230b94296a3d050ade3228cfededea2c17383028b594fe10","src/serde_tests.rs":"98fc0063223ded619054caa4a1c95fbb37d8a9613e2a5bdf4f15ccf3ed3c9e8a","src/stream/binary_reader.rs":"b05968d750a9de6b5d5a26c4815164318df771532b9ec42c3dce49f5e00beaaf","src/stream/binary_writer.rs":"a8eca464ac2fd722eaae45bfdc4b7c6b3a618613ca6c14670c4da46252a32332","src/stream/mod.rs":"2482d63cd50cceaf4b4fc46ddb11119b1a7c55bf3350e69ce2546317ff3f89e2","src/stream/xml_reader.rs":"865c5e398798af85a55c79fbdb78f3061a56b7df4827c112a58ba3e444860354","src/stream/xml_writer.rs":"882040ad363e7601b94414923b03079da9b6a88fa2618aea1a6b0b8f168f0cb3","src/uid.rs":"adb51121ee251941f173d83417631cd2fdfbc7104998205c538d93e4b3c3e676","src/value.rs":"6fc16f6c5219c2c9974d25beb0a487f4b014e514c2b9e825b84784cae5825a60","tests/data/binary.plist":"6088c4e105e21920c2033c868157f3d80bae55db6f783c92a3978743b81d46b4","tests/data/binary_NSKeyedArchiver.plist":"54dc8b87acd364de6b2160ff805514bc04bf0577e4f57d08d7f3578d218362f0","tests/data/binary_circular_array.plist":"825aed6ce83a8abdbe15d4686ce35157f4eb861bd792f0ce790115fb4ec48805","tests/data/binary_zero_offset_size.plist":"020953c8211989d01b5edf42e025560f46ece3b604ceda03708819bd2587a1a1","tests/data/book.plist":"3b18050f073cab956f38f1775e89dedc88d1e56dd388bc99e277efb19e50dffd","tests/data/utf16_bplist.plist":"c0b7d33001021df98d8631c604c8471e74e4b4599bac51a8bed149ca82adbcd5","tests/data/xml.plist":"0cb818c43467adf035160b135353fcac25a2abe5eccfcf45ef03223fa6ee3235","tests/data/xml_error.plist":"3718f7dd2c716a4a6c36d1f7055b78d86c982c812c19964f85a6f62eff1589ea","tests/fuzzer.rs":"ea9e7812c936e4c1e42ce234513fa8c839277222c0746c069d62e7b77870b858"},"package":"31850d149352e2b75f0e4b206045ee3775076c422892328343beca48a2b5cf17"}
{"files":{"Cargo.toml":"5e4640942c85072981f5fe3b3777d088b7360c8e0b51207defbd52315046d3e7","LICENCE":"5b0ae40d1a35f7ae6591a28e44771240e6a88cb03a66c9189a45b9681639b466","README.md":"98860ec5d46ac8f1d3a3f33600629b942f774a35a511ddedffc9a227a3822e2c","rustfmt.toml":"9bbb759b3914c49c8060bcdeeb7786f4aec083d30bcfe236bbd48d8388d06103","src/date.rs":"6378f0919e01cd41c2862fbc4d4029915a7d48324ede584daea0b5b1324cbb51","src/de.rs":"dad0b0409227223deb2778a3f63c7d355c1b642f406fc448e59224de61882770","src/dictionary.rs":"9b8194d3e339a300de5d0fb39529d976a5f86947f3997086594d2be2f795859b","src/error.rs":"2ed8ce5c33071847abb00b27472be352d5bceb92a6ad0b8724f630570e956430","src/integer.rs":"131f528878adc5c0f33c8ad1563c06b397cb2ae5148c2bb9318203a2477d70e0","src/lib.rs":"1fa5d06242ec2731f16d244e070710476caf165eb1707a1d688357928eae2310","src/ser.rs":"ea4ed049abef09c7230b94296a3d050ade3228cfededea2c17383028b594fe10","src/serde_tests.rs":"98fc0063223ded619054caa4a1c95fbb37d8a9613e2a5bdf4f15ccf3ed3c9e8a","src/stream/binary_reader.rs":"f5a38d624d3af99f57b78837d253b72ddb8d7a08e6c117648fae4654005beef6","src/stream/binary_writer.rs":"1b10bbf287ad48be3a82c36cebbc32f7232fff42995142e09f98d2a2eb1fb628","src/stream/mod.rs":"2482d63cd50cceaf4b4fc46ddb11119b1a7c55bf3350e69ce2546317ff3f89e2","src/stream/xml_reader.rs":"629cc6b975c7c88c75fe1f0e8e39b65b41fb5442f487ce8b19f99dfa90c02cf5","src/stream/xml_writer.rs":"076a2eeb3daae3737efb514ab647673dcee00b81ce0849c968c6245f36f95d53","src/uid.rs":"adb51121ee251941f173d83417631cd2fdfbc7104998205c538d93e4b3c3e676","src/value.rs":"8fca3d563723a55be3fc6f71cd17fe7e6ad33240d83d20e6420e718033c066cd","tests/data/binary.plist":"728985bb53486a92fdcc901a3c08a904835f0225efab7b85be2734e2dcd4af83","tests/data/binary_NSKeyedArchiver.plist":"54dc8b87acd364de6b2160ff805514bc04bf0577e4f57d08d7f3578d218362f0","tests/data/binary_circular_array.plist":"825aed6ce83a8abdbe15d4686ce35157f4eb861bd792f0ce790115fb4ec48805","tests/data/binary_zero_offset_size.plist":"020953c8211989d01b5edf42e025560f46ece3b604ceda03708819bd2587a1a1","tests/data/book.plist":"3b18050f073cab956f38f1775e89dedc88d1e56dd388bc99e277efb19e50dffd","tests/data/utf16_bplist.plist":"c0b7d33001021df98d8631c604c8471e74e4b4599bac51a8bed149ca82adbcd5","tests/data/xml.plist":"9669e8ad25a661ca052d30d8d74b7495e859a0a7faf01f2aeade7fcebb2aa5b7","tests/data/xml_error.plist":"3718f7dd2c716a4a6c36d1f7055b78d86c982c812c19964f85a6f62eff1589ea","tests/fuzzer.rs":"ea9e7812c936e4c1e42ce234513fa8c839277222c0746c069d62e7b77870b858"},"package":"50ce7c785e06e3a9e6f546c1a30d3d59111a31a21bc294fb1496241a572c9a00"}

View File

@ -13,10 +13,10 @@
[package]
edition = "2018"
name = "plist"
version = "0.5.1"
version = "0.5.4"
authors = ["Ed Barnard <eabarnard@gmail.com>"]
description = "A rusty plist parser. Supports Serde serialization."
documentation = "https://docs.rs/plist/0.5.1/plist/"
documentation = "https://docs.rs/plist/0.5.4/plist/"
keywords = ["plist", "parser"]
categories = ["config", "encoding", "parser-implementations"]
license = "MIT"
@ -25,7 +25,7 @@ repository = "https://github.com/ebarnard/rust-plist/"
version = "0.10.1"
[dependencies.humantime]
version = "1.1.1"
version = "2.0.0"
[dependencies.indexmap]
version = "1.0.2"

View File

@ -2,7 +2,7 @@ use serde::de;
use std::{
fmt::Display,
fs::File,
io::{BufReader, Read, Seek},
io::{BufReader, Cursor, Read, Seek},
iter::Peekable,
mem,
path::Path,
@ -362,6 +362,12 @@ where
}
}
/// Deserializes an instance of type `T` from a byte slice.
pub fn from_bytes<T: de::DeserializeOwned>(bytes: &[u8]) -> Result<T, Error> {
let cursor = Cursor::new(bytes);
from_reader(cursor)
}
/// Deserializes an instance of type `T` from a plist file of any encoding.
pub fn from_file<P: AsRef<Path>, T: de::DeserializeOwned>(path: P) -> Result<T, Error> {
let file = File::open(path).map_err(error::from_io_without_position)?;

View File

@ -110,7 +110,7 @@ mod ser;
pub use self::{de::Deserializer, ser::Serializer};
#[cfg(feature = "serde")]
pub use self::{
de::{from_file, from_reader, from_reader_xml},
de::{from_bytes, from_file, from_reader, from_reader_xml},
ser::{to_file_binary, to_file_xml, to_writer_binary, to_writer_xml},
};

View File

@ -424,22 +424,23 @@ mod tests {
let events: Vec<Event> = streaming_parser.map(|e| e.unwrap()).collect();
let comparison = &[
StartDictionary(Some(11)),
StartDictionary(Some(13)),
String("Author".into()),
String("William Shakespeare".into()),
String("Height".into()),
Real(1.6),
String("Data".into()),
Data(vec![0, 0, 0, 190, 0, 0, 0, 3, 0, 0, 0, 30, 0, 0, 0]),
String("Birthdate".into()),
Date(parse_rfc3339_weak("1981-05-16 11:32:06").unwrap().into()),
String("BiggestNumber".into()),
Integer(18446744073709551615u64.into()),
String("SmallestNumber".into()),
Integer((-9223372036854775808i64).into()),
String("EmptyArray".into()),
StartArray(Some(0)),
EndCollection,
String("IsNotFalse".into()),
Boolean(false),
String("SmallestNumber".into()),
Integer((-9223372036854775808i64).into()),
String("EmptyDictionary".into()),
StartDictionary(Some(0)),
EndCollection,
String("Height".into()),
Real(1.6),
String("Lines".into()),
StartArray(Some(2)),
String("It is a tale told by an idiot,".into()),
@ -447,15 +448,18 @@ mod tests {
EndCollection,
String("Death".into()),
Integer(1564.into()),
String("EmptyDictionary".into()),
StartDictionary(Some(0)),
EndCollection,
String("Blank".into()),
String("".into()),
String("BiggestNumber".into()),
Integer(18446744073709551615u64.into()),
String("IsTrue".into()),
Boolean(true),
String("Data".into()),
Data(vec![0, 0, 0, 190, 0, 0, 0, 3, 0, 0, 0, 30, 0, 0, 0]),
EndCollection,
];
assert_eq!(events, comparison);
assert_eq!(events, &comparison[..]);
}
#[test]

View File

@ -335,7 +335,7 @@ impl<W: Write> BinaryWriter<W> {
trailer[6] = offset_size;
trailer[7] = ref_size;
trailer[8..16].copy_from_slice(&(self.num_objects as u64).to_be_bytes());
trailer[24..32].copy_from_slice(&offset_table_offset.to_be_bytes());
trailer[24..32].copy_from_slice(&(offset_table_offset as u64).to_be_bytes());
self.writer.write_exact(&trailer)?;
self.writer
@ -454,10 +454,10 @@ impl<W: Write> BinaryWriter<W> {
match value {
Value::Boolean(true) => {
self.writer.write_exact(&[0x08])?;
self.writer.write_exact(&[0x09])?;
}
Value::Boolean(false) => {
self.writer.write_exact(&[0x09])?;
self.writer.write_exact(&[0x08])?;
}
Value::Data(v) => {
write_plist_value_ty_and_size(&mut self.writer, 0x40, v.len())?;

View File

@ -255,6 +255,10 @@ mod tests {
Integer((-9223372036854775808i64).into()),
String("HexademicalNumber".to_owned()),
Integer(0xdead_beef_u64.into()),
String("IsTrue".into()),
Boolean(true),
String("IsNotFalse".into()),
Boolean(false),
EndCollection,
];

View File

@ -323,6 +323,10 @@ mod tests {
Event::Integer(18446744073709551615u64.into()),
Event::String("SmallestNumber".to_owned()),
Event::Integer((-9223372036854775808i64).into()),
Event::String("IsTrue".into()),
Event::Boolean(true),
Event::String("IsNotFalse".into()),
Event::Boolean(false),
Event::EndCollection,
];
@ -368,6 +372,10 @@ mod tests {
\t<integer>18446744073709551615</integer>
\t<key>SmallestNumber</key>
\t<integer>-9223372036854775808</integer>
\t<key>IsTrue</key>
\t<true />
\t<key>IsNotFalse</key>
\t<false />
</dict>
</plist>";

View File

@ -113,6 +113,19 @@ impl Value {
IntoEvents::new(self)
}
/// If the `Value` is a Array, returns the underlying `Vec`.
///
/// Returns `None` otherwise.
///
/// This method consumes the `Value`. To get a reference instead, use
/// `as_array`.
pub fn into_array(self) -> Option<Vec<Value>> {
match self {
Value::Array(dict) => Some(dict),
_ => None,
}
}
/// If the `Value` is an Array, returns the associated `Vec`.
///
/// Returns `None` otherwise.
@ -133,6 +146,19 @@ impl Value {
}
}
/// If the `Value` is a Dictionary, returns the associated `BTreeMap`.
///
/// Returns `None` otherwise.
///
/// This method consumes the `Value`. To get a reference instead, use
/// `as_dictionary`.
pub fn into_dictionary(self) -> Option<Dictionary> {
match self {
Value::Dictionary(dict) => Some(dict),
_ => None,
}
}
/// If the `Value` is a Dictionary, returns the associated `BTreeMap`.
///
/// Returns `None` otherwise.

Binary file not shown.

View File

@ -28,5 +28,9 @@
<integer>-9223372036854775808</integer>
<key>HexademicalNumber</key>
<integer>0xDEADBEEF</integer>
<key>IsTrue</key>
<true/>
<key>IsNotFalse</key>
<false/>
</dict>
</plist>

View File

@ -8,5 +8,5 @@ license = "MPL-2.0"
[dependencies]
lazy_static = "1"
log = {version = "0.4", features = ["release_max_level_info"]}
env_logger = {version = "0.6", default-features = false} # disable `regex` to reduce code size
env_logger = {version = "0.8", default-features = false} # disable `regex` to reduce code size
app_services_logger = { path = "../../../services/common/app_services_logger" }