From 1ebb99f1647b4452810aaa9127d87d904b758663 Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Wed, 12 Feb 2025 13:05:16 +0100 Subject: [PATCH 01/14] init --- .gitignore | 3 +++ Cargo.toml | 8 +++++++ src/lib.rs | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0c98f0d --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/target +/.idea +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..d32ea4f --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "tracing-build-script" +version = "0.1.0" +edition = "2021" + +[dependencies] +tracing = "^0.1" +tracing-subscriber = "^0.3" diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..a349c23 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,61 @@ +use std::io; +use tracing::{Level, Metadata}; +use tracing_subscriber::fmt::MakeWriter; + +enum BuildScriptWriterInner { + Informational(io::Stderr), + ErrorsAndWarnings { first_write: bool, writer: io::Stdout }, +} + +pub struct BuildScriptWriter(BuildScriptWriterInner); + +impl BuildScriptWriter { + pub fn informational() -> Self { + Self(BuildScriptWriterInner::Informational(io::stderr())) + } + + pub fn errors_and_warnings() -> Self { + Self(BuildScriptWriterInner::ErrorsAndWarnings { first_write: true, writer: io::stdout() }) + } +} + +impl io::Write for BuildScriptWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + match &mut self.0 { + BuildScriptWriterInner::Informational(writer) => writer.write(buf), + BuildScriptWriterInner::ErrorsAndWarnings { first_write, writer } => { + if *first_write { + writer.write(b"cargo::warning=")?; + *first_write = false; + } + + writer.write(buf) + }, + } + } + + fn flush(&mut self) -> io::Result<()> { + match &mut self.0 { + BuildScriptWriterInner::Informational(writer) => writer.flush(), + BuildScriptWriterInner::ErrorsAndWarnings { writer, first_write: _ } => writer.flush(), + } + } +} + +pub struct BuildScriptMakeWriter; + +impl<'a> MakeWriter<'a> for BuildScriptMakeWriter { + type Writer = BuildScriptWriter; + + fn make_writer(&'a self) -> Self::Writer { + BuildScriptWriter::informational() + } + + fn make_writer_for(&'a self, meta: &Metadata) -> Self::Writer { + if meta.level() == &Level::ERROR || meta.level() == &Level::WARN { + BuildScriptWriter::errors_and_warnings() + } else { + BuildScriptWriter::informational() + } + } +} From 7215a209520efcc4b33a82af11075acade09b401 Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Wed, 12 Feb 2025 15:15:50 +0100 Subject: [PATCH 02/14] comments --- README.md | 3 +++ src/lib.rs | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/README.md b/README.md index e69de29..23c3a67 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,3 @@ +# tracing-build-script + +A [`tracing-subscriber`](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/) compatible writer for logging events in build scripts. diff --git a/src/lib.rs b/src/lib.rs index a349c23..65d3d72 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,13 +7,34 @@ enum BuildScriptWriterInner { ErrorsAndWarnings { first_write: bool, writer: io::Stdout }, } +/// A writer intended to support the [output capturing of build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script). +/// `BuildScriptWriter` can be used by [`tracing_subscriber::fmt::Subscriber`](tracing_subscriber::fmt::Subscriber) or [`tracing_subscriber::fmt::Layer`](tracing_subscriber::fmt::Layer) +/// to enable capturing output in build scripts. +/// +/// # Logging Behaviour +/// Events for Levels Error and Warn are printed to stdout with [`cargo::warning=`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-warning) prepended. +/// All other levels are sent to stderr, where they are only visible when running with verbose build output (`cargo build -vv`). +/// +/// Note: this writer explicitly does **not** use the [`cargo::error=`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-error) instruction +/// because it aborts the build with an error, which is not always desired. +/// +/// # Example +/// ``` +/// tracing_subscriber::fmt() +/// .with_writer(tracing_build_script::BuildScriptMakeWriter) +/// .init(); +/// ``` pub struct BuildScriptWriter(BuildScriptWriterInner); impl BuildScriptWriter { + /// Create a writer for informational events. + /// Events will be written to stderr. pub fn informational() -> Self { Self(BuildScriptWriterInner::Informational(io::stderr())) } + /// Create a writer for warning and error events. + /// Events will be written to stdout after having `cargo::warning=` prepended. pub fn errors_and_warnings() -> Self { Self(BuildScriptWriterInner::ErrorsAndWarnings { first_write: true, writer: io::stdout() }) } From e3cdefdf35c65f776773080a9f9b8ec6f2f69bfd Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Wed, 12 Feb 2025 15:24:44 +0100 Subject: [PATCH 03/14] manifest --- Cargo.toml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index d32ea4f..ef27c82 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,18 @@ [package] name = "tracing-build-script" version = "0.1.0" +authors = ["Liss Heidrich "] +license = "MIT" +readme = "README.md" +homepage = "https://github.com/dice-group/tracing-build-script" +description = """ +Provides a tracing-subscriber compatible writer for use in build scripts. +""" +categories = [ + "development-tools::debugging", + "development-tools::build-utils", +] +keywords = ["logging", "tracing", "build-script"] edition = "2021" [dependencies] From ef4413f0e4c2573c5c197126823a30add5d4e9b6 Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Wed, 12 Feb 2025 15:26:08 +0100 Subject: [PATCH 04/14] Create LICENSE-MIT --- LICENSE-MIT | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE-MIT diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..8541ef4 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Data Science Group at UPB + +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. From 2a41e88c500152493322734b3637ce5fbffcb739 Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Wed, 12 Feb 2025 15:27:05 +0100 Subject: [PATCH 05/14] Create LICENSE-APACHE --- LICENSE-APACHE | 201 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 LICENSE-APACHE diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + 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. From 30efd68c39369339d9f11ea75ee1a155ce54efba Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Wed, 12 Feb 2025 15:27:16 +0100 Subject: [PATCH 06/14] license --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index ef27c82..867cbda 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "tracing-build-script" version = "0.1.0" authors = ["Liss Heidrich "] -license = "MIT" +license = "MIT OR Apache-2.0" readme = "README.md" homepage = "https://github.com/dice-group/tracing-build-script" description = """ From 4fb12edad7c821cc3434319d9bd4b3c6f920871f Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Wed, 12 Feb 2025 15:30:06 +0100 Subject: [PATCH 07/14] fix comment --- src/lib.rs | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 65d3d72..69317db 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,20 +10,6 @@ enum BuildScriptWriterInner { /// A writer intended to support the [output capturing of build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script). /// `BuildScriptWriter` can be used by [`tracing_subscriber::fmt::Subscriber`](tracing_subscriber::fmt::Subscriber) or [`tracing_subscriber::fmt::Layer`](tracing_subscriber::fmt::Layer) /// to enable capturing output in build scripts. -/// -/// # Logging Behaviour -/// Events for Levels Error and Warn are printed to stdout with [`cargo::warning=`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-warning) prepended. -/// All other levels are sent to stderr, where they are only visible when running with verbose build output (`cargo build -vv`). -/// -/// Note: this writer explicitly does **not** use the [`cargo::error=`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-error) instruction -/// because it aborts the build with an error, which is not always desired. -/// -/// # Example -/// ``` -/// tracing_subscriber::fmt() -/// .with_writer(tracing_build_script::BuildScriptMakeWriter) -/// .init(); -/// ``` pub struct BuildScriptWriter(BuildScriptWriterInner); impl BuildScriptWriter { @@ -63,6 +49,21 @@ impl io::Write for BuildScriptWriter { } } +/// [`MakeWriter`](tracing_subscriber::fmt::MakeWriter) implementation for [`BuildScriptWriter`](BuildScriptWriter) +/// +/// # Behaviour +/// Events for Levels Error and Warn are printed to stdout with [`cargo::warning=`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-warning) prepended. +/// All other levels are sent to stderr, where they are only visible when running with verbose build output (`cargo build -vv`). +/// +/// Note: this writer explicitly does **not** use the [`cargo::error=`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-error) instruction +/// because it aborts the build with an error, which is not always desired. +/// +/// # Example +/// ``` +/// tracing_subscriber::fmt() +/// .with_writer(tracing_build_script::BuildScriptMakeWriter) +/// .init(); +/// ``` pub struct BuildScriptMakeWriter; impl<'a> MakeWriter<'a> for BuildScriptMakeWriter { From 33c89f75f4fd2c610637d5e8acee9ee105dd305d Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Wed, 12 Feb 2025 15:59:49 +0100 Subject: [PATCH 08/14] quickstart --- README.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/README.md b/README.md index 23c3a67..76e100e 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,26 @@ # tracing-build-script A [`tracing-subscriber`](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/) compatible writer for logging events in build scripts. + +## Getting Started +### How to install +Add `tracing-build-script` to your dependencies + +```toml +[dependencies] +# ... +tracing-build-script = "0.1.0" +tracing-subscriber = "0.3.19" +``` + +### Quickstart +> build.rs +> ```rust +> fn main() { +> tracing_subscriber::fmt() +> .with_writer(tracing_build_script::BuildScriptMakeWriter) +> .init(); +> +> ... +> } +> ``` From 6ea98c362c48366308e6adf318268b43052df9fe Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Wed, 12 Feb 2025 16:01:33 +0100 Subject: [PATCH 09/14] fix --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 76e100e..88605e5 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,11 @@ A [`tracing-subscriber`](https://docs.rs/tracing-subscriber/latest/tracing_subsc Add `tracing-build-script` to your dependencies ```toml -[dependencies] +[package] +# ... +build = "build.rs" + +[build-dependencies] # ... tracing-build-script = "0.1.0" tracing-subscriber = "0.3.19" From 551c055ebce3a2b4a32b6a878622cb49b9b00f7a Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Thu, 13 Feb 2025 12:11:39 +0100 Subject: [PATCH 10/14] fix bugs related to special chars in log messages and add tests via separate crate in workspace --- Cargo.toml | 24 +--- src/lib.rs | 83 ----------- tracing-build-script-tests/Cargo.toml | 9 ++ tracing-build-script-tests/build.rs | 25 ++++ tracing-build-script-tests/src/lib.rs | 55 ++++++++ tracing-build-script/Cargo.toml | 20 +++ tracing-build-script/src/lib.rs | 196 ++++++++++++++++++++++++++ 7 files changed, 310 insertions(+), 102 deletions(-) delete mode 100644 src/lib.rs create mode 100644 tracing-build-script-tests/Cargo.toml create mode 100644 tracing-build-script-tests/build.rs create mode 100644 tracing-build-script-tests/src/lib.rs create mode 100644 tracing-build-script/Cargo.toml create mode 100644 tracing-build-script/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index 867cbda..e6c983e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,20 +1,6 @@ -[package] -name = "tracing-build-script" -version = "0.1.0" -authors = ["Liss Heidrich "] -license = "MIT OR Apache-2.0" -readme = "README.md" -homepage = "https://github.com/dice-group/tracing-build-script" -description = """ -Provides a tracing-subscriber compatible writer for use in build scripts. -""" -categories = [ - "development-tools::debugging", - "development-tools::build-utils", +[workspace] +resolver = "2" +members = [ + "tracing-build-script", + "tracing-build-script-tests", ] -keywords = ["logging", "tracing", "build-script"] -edition = "2021" - -[dependencies] -tracing = "^0.1" -tracing-subscriber = "^0.3" diff --git a/src/lib.rs b/src/lib.rs deleted file mode 100644 index 69317db..0000000 --- a/src/lib.rs +++ /dev/null @@ -1,83 +0,0 @@ -use std::io; -use tracing::{Level, Metadata}; -use tracing_subscriber::fmt::MakeWriter; - -enum BuildScriptWriterInner { - Informational(io::Stderr), - ErrorsAndWarnings { first_write: bool, writer: io::Stdout }, -} - -/// A writer intended to support the [output capturing of build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script). -/// `BuildScriptWriter` can be used by [`tracing_subscriber::fmt::Subscriber`](tracing_subscriber::fmt::Subscriber) or [`tracing_subscriber::fmt::Layer`](tracing_subscriber::fmt::Layer) -/// to enable capturing output in build scripts. -pub struct BuildScriptWriter(BuildScriptWriterInner); - -impl BuildScriptWriter { - /// Create a writer for informational events. - /// Events will be written to stderr. - pub fn informational() -> Self { - Self(BuildScriptWriterInner::Informational(io::stderr())) - } - - /// Create a writer for warning and error events. - /// Events will be written to stdout after having `cargo::warning=` prepended. - pub fn errors_and_warnings() -> Self { - Self(BuildScriptWriterInner::ErrorsAndWarnings { first_write: true, writer: io::stdout() }) - } -} - -impl io::Write for BuildScriptWriter { - fn write(&mut self, buf: &[u8]) -> io::Result { - match &mut self.0 { - BuildScriptWriterInner::Informational(writer) => writer.write(buf), - BuildScriptWriterInner::ErrorsAndWarnings { first_write, writer } => { - if *first_write { - writer.write(b"cargo::warning=")?; - *first_write = false; - } - - writer.write(buf) - }, - } - } - - fn flush(&mut self) -> io::Result<()> { - match &mut self.0 { - BuildScriptWriterInner::Informational(writer) => writer.flush(), - BuildScriptWriterInner::ErrorsAndWarnings { writer, first_write: _ } => writer.flush(), - } - } -} - -/// [`MakeWriter`](tracing_subscriber::fmt::MakeWriter) implementation for [`BuildScriptWriter`](BuildScriptWriter) -/// -/// # Behaviour -/// Events for Levels Error and Warn are printed to stdout with [`cargo::warning=`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-warning) prepended. -/// All other levels are sent to stderr, where they are only visible when running with verbose build output (`cargo build -vv`). -/// -/// Note: this writer explicitly does **not** use the [`cargo::error=`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-error) instruction -/// because it aborts the build with an error, which is not always desired. -/// -/// # Example -/// ``` -/// tracing_subscriber::fmt() -/// .with_writer(tracing_build_script::BuildScriptMakeWriter) -/// .init(); -/// ``` -pub struct BuildScriptMakeWriter; - -impl<'a> MakeWriter<'a> for BuildScriptMakeWriter { - type Writer = BuildScriptWriter; - - fn make_writer(&'a self) -> Self::Writer { - BuildScriptWriter::informational() - } - - fn make_writer_for(&'a self, meta: &Metadata) -> Self::Writer { - if meta.level() == &Level::ERROR || meta.level() == &Level::WARN { - BuildScriptWriter::errors_and_warnings() - } else { - BuildScriptWriter::informational() - } - } -} diff --git a/tracing-build-script-tests/Cargo.toml b/tracing-build-script-tests/Cargo.toml new file mode 100644 index 0000000..6872bbc --- /dev/null +++ b/tracing-build-script-tests/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "tracing-build-script-tests" +build = "build.rs" +edition = "2021" + +[build-dependencies] +tracing = "0.1.41" +tracing-subscriber = "0.3.19" +tracing-build-script = { path = "../tracing-build-script" } diff --git a/tracing-build-script-tests/build.rs b/tracing-build-script-tests/build.rs new file mode 100644 index 0000000..1c87f27 --- /dev/null +++ b/tracing-build-script-tests/build.rs @@ -0,0 +1,25 @@ +use tracing::metadata::LevelFilter; + +fn write_message(msg: &str) { + tracing::trace!("{msg}"); + tracing::debug!("{msg}"); + tracing::info!("{msg}"); + tracing::warn!("{msg}"); + tracing::error!("{msg}"); +} + +fn main() { + tracing_subscriber::fmt() + .with_writer(tracing_build_script::BuildScriptMakeWriter) + .with_ansi(false) + .without_time() + .with_max_level(LevelFilter::TRACE) + .init(); + + write_message("simple message"); + write_message("with\nnew\nline"); + write_message("with\nnew\nlineend\n"); + write_message("\nwith\nnew\nlinestart"); + write_message("two\n\nnewlines"); + write_message("other\rspecial\tchar\0a\tb\"c\\"); +} diff --git a/tracing-build-script-tests/src/lib.rs b/tracing-build-script-tests/src/lib.rs new file mode 100644 index 0000000..09d660b --- /dev/null +++ b/tracing-build-script-tests/src/lib.rs @@ -0,0 +1,55 @@ +#![cfg(test)] + +use std::path::Path; + +#[test] +fn test_warn_and_error_output() { + let out_dir = Path::new(env!("OUT_DIR")); + let warn_output_file = out_dir.join("../output"); + let warn_output = std::fs::read_to_string(warn_output_file).unwrap(); + + assert_eq!( + warn_output, + "cargo::warning= WARN build_script_build: simple message\n\ + cargo::warning=ERROR build_script_build: simple message\n\ + cargo::warning= WARN build_script_build: with\\nnew\\nline\n\ + cargo::warning=ERROR build_script_build: with\\nnew\\nline\n\ + cargo::warning= WARN build_script_build: with\\nnew\\nlineend\\n\n\ + cargo::warning=ERROR build_script_build: with\\nnew\\nlineend\\n\n\ + cargo::warning= WARN build_script_build: \\nwith\\nnew\\nlinestart\n\ + cargo::warning=ERROR build_script_build: \\nwith\\nnew\\nlinestart\n\ + cargo::warning= WARN build_script_build: two\\n\\nnewlines\n\ + cargo::warning=ERROR build_script_build: two\\n\\nnewlines\n\ + cargo::warning= WARN build_script_build: other\\rspecial\tchar\0a\tb\"c\\\n\ + cargo::warning=ERROR build_script_build: other\\rspecial\tchar\0a\tb\"c\\\n" + ); +} + +#[test] +fn test_informational_output() { + let out_dir = Path::new(env!("OUT_DIR")); + let info_output_file = out_dir.join("../stderr"); + let info_output = std::fs::read_to_string(info_output_file).unwrap(); + + assert_eq!( + info_output, + "TRACE build_script_build: simple message\n\ + DEBUG build_script_build: simple message\n \ + INFO build_script_build: simple message\n\ + TRACE build_script_build: with\nnew\nline\n\ + DEBUG build_script_build: with\nnew\nline\n \ + INFO build_script_build: with\nnew\nline\n\ + TRACE build_script_build: with\nnew\nlineend\n\n\ + DEBUG build_script_build: with\nnew\nlineend\n\n \ + INFO build_script_build: with\nnew\nlineend\n\n\ + TRACE build_script_build: \nwith\nnew\nlinestart\n\ + DEBUG build_script_build: \nwith\nnew\nlinestart\n \ + INFO build_script_build: \nwith\nnew\nlinestart\n\ + TRACE build_script_build: two\n\nnewlines\n\ + DEBUG build_script_build: two\n\nnewlines\n \ + INFO build_script_build: two\n\nnewlines\n\ + TRACE build_script_build: other\rspecial\tchar\0a\tb\"c\\\n\ + DEBUG build_script_build: other\rspecial\tchar\0a\tb\"c\\\n \ + INFO build_script_build: other\rspecial\tchar\0a\tb\"c\\\n" + ); +} diff --git a/tracing-build-script/Cargo.toml b/tracing-build-script/Cargo.toml new file mode 100644 index 0000000..fc2672f --- /dev/null +++ b/tracing-build-script/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "tracing-build-script" +version = "0.1.0" +authors = ["Liss Heidrich "] +license = "MIT OR Apache-2.0" +readme = "../README.md" +homepage = "https://github.com/dice-group/tracing-build-script" +description = """ +Provides a tracing-subscriber compatible writer for use in build scripts. +""" +categories = [ + "development-tools::debugging", + "development-tools::build-utils", +] +keywords = ["logging", "tracing", "build-script"] +edition = "2021" + +[dependencies] +tracing = "^0.1" +tracing-subscriber = "^0.3" diff --git a/tracing-build-script/src/lib.rs b/tracing-build-script/src/lib.rs new file mode 100644 index 0000000..434fcb5 --- /dev/null +++ b/tracing-build-script/src/lib.rs @@ -0,0 +1,196 @@ +use std::{io, io::Write}; +use tracing::{Level, Metadata}; +use tracing_subscriber::fmt::MakeWriter; + +enum ErrorAndWarnState { + /// Initial state, no output has been written yet + /// cargo::warning= needs to be written next + Init, + /// Normal operation, cargo::warning= was already written + /// and user input did not end with newline + Normal, + /// Normal operation, cargo::warning= was already written + /// but user input ended with a newline or another char that needs escaping. + /// This either means the log message is done, or there just happens to be a newline at the end of this write + /// request + LastCharWasSpecial(u8), +} + +fn char_is_special(ch: u8) -> bool { + ch == b'\n' || ch == b'\r' +} + +fn escape_special(ch: u8) -> &'static [u8] { + match ch { + b'\n' => b"\\n", + b'\r' => b"\\r", + _ => unreachable!(), + } +} + +enum BuildScriptWriterInner { + Informational(io::Stderr), + ErrorsAndWarnings { + state: ErrorAndWarnState, + writer: io::Stdout, + }, +} + +/// A writer intended to support the [output capturing of build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script). +/// `BuildScriptWriter` can be used by [`tracing_subscriber::fmt::Subscriber`](tracing_subscriber::fmt::Subscriber) or [`tracing_subscriber::fmt::Layer`](tracing_subscriber::fmt::Layer) +/// to enable capturing output in build scripts. +pub struct BuildScriptWriter(BuildScriptWriterInner); + +impl BuildScriptWriter { + /// Create a writer for informational events. + /// Events will be written to stderr. + pub fn informational() -> Self { + Self(BuildScriptWriterInner::Informational(io::stderr())) + } + + /// Create a writer for warning and error events. + /// Events will be written to stdout after having `cargo::warning=` prepended. + pub fn errors_and_warnings() -> Self { + Self(BuildScriptWriterInner::ErrorsAndWarnings { state: ErrorAndWarnState::Init, writer: io::stdout() }) + } +} + +impl Drop for BuildScriptWriter { + fn drop(&mut self) { + if let BuildScriptWriterInner::ErrorsAndWarnings { state: ErrorAndWarnState::LastCharWasSpecial(ch), writer } = + &mut self.0 + { + let _ = writer.write(&[*ch]); + } + } +} + +impl Write for BuildScriptWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.write_all(buf)?; + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + match &mut self.0 { + BuildScriptWriterInner::Informational(writer) => writer.flush(), + BuildScriptWriterInner::ErrorsAndWarnings { writer, state: _ } => writer.flush(), + } + } + + fn write_all(&mut self, mut buf: &[u8]) -> io::Result<()> { + match &mut self.0 { + BuildScriptWriterInner::Informational(writer) => writer.write_all(buf), + BuildScriptWriterInner::ErrorsAndWarnings { state, writer } => { + // We will need to issue multiple write calls to the writer (to avoid heap allocation) + // so we need to lock it to prevent other threads from clobbering our output. + let mut writer = writer.lock(); + + match *state { + ErrorAndWarnState::Init => { + writer.write_all(b"cargo::warning=")?; + }, + ErrorAndWarnState::LastCharWasSpecial(ch) => { + writer.write_all(escape_special(ch))?; + }, + ErrorAndWarnState::Normal => {}, + } + + // If the last char is a newline we need to remember that but cannot immediately + // write it out. This is because we cannot know yet if its needs to be escaped, there are two cases: + // + // 1. this call to write is not actually the last call to write that will happen it just happens to end with a newline + // => we need to escape the newline + // + // 2. this call to write is actually the last call to write that will happen, and it ends with a newline + // => we need to keep the newline as is, because it is the newline terminator of the log message + // (tracing automatically appends a newline at the end of each message, like println!) + // + // Since we cannot decide which of these cases we are in at the moment, we need to delay writing the last character (if it is a newline) until we know that. + // We know which case we are in + // either when we enter this function the next time (case 1) + // or the next time or when we enter the destructor (case 2). + let last_char = buf.last().copied(); + + match last_char { + Some(ch) if char_is_special(ch) => { + // we strip the special char at the end so that the call to split + // does not yield an empty slice in the end + buf = &buf[..buf.len() - 1]; + *state = ErrorAndWarnState::LastCharWasSpecial(ch); + }, + _ => { + *state = ErrorAndWarnState::Normal; + }, + } + + let mut last_special_char = match buf.iter().position(|ch| char_is_special(*ch)) { + Some(pos) => { + writer.write_all(&buf[..pos])?; + + let ret = buf[pos]; + buf = &buf[pos + 1..]; + ret + }, + None => { + // fast path for messages without any special chars + writer.write_all(buf)?; + return Ok(()); + }, + }; + + loop { + writer.write_all(escape_special(last_special_char))?; + + match buf.iter().position(|ch| char_is_special(*ch)) { + Some(pos) => { + writer.write_all(&buf[..pos])?; + + last_special_char = buf[pos]; + buf = &buf[pos + 1..]; + }, + None => { + writer.write_all(buf)?; + break; + }, + } + } + + Ok(()) + }, + } + } +} + +/// [`MakeWriter`](tracing_subscriber::fmt::MakeWriter) implementation for [`BuildScriptWriter`](BuildScriptWriter) +/// +/// # Behaviour +/// Events for Levels Error and Warn are printed to stdout with [`cargo::warning=`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-warning) prepended. +/// All other levels are sent to stderr, where they are only visible when running with verbose build output (`cargo build -vv`). +/// +/// Note: this writer explicitly does **not** use the [`cargo::error=`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-error) instruction +/// because it aborts the build with an error, which is not always desired. +/// +/// # Example +/// ``` +/// tracing_subscriber::fmt() +/// .with_writer(tracing_build_script::BuildScriptMakeWriter) +/// .init(); +/// ``` +pub struct BuildScriptMakeWriter; + +impl<'a> MakeWriter<'a> for BuildScriptMakeWriter { + type Writer = BuildScriptWriter; + + fn make_writer(&'a self) -> Self::Writer { + BuildScriptWriter::informational() + } + + fn make_writer_for(&'a self, meta: &Metadata) -> Self::Writer { + if meta.level() == &Level::ERROR || meta.level() == &Level::WARN { + BuildScriptWriter::errors_and_warnings() + } else { + BuildScriptWriter::informational() + } + } +} From c10930aa7bc86d50bef2c526c38407c62bfe162a Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Thu, 13 Feb 2025 12:13:16 +0100 Subject: [PATCH 11/14] comment --- tracing-build-script/src/lib.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tracing-build-script/src/lib.rs b/tracing-build-script/src/lib.rs index 434fcb5..474cfc4 100644 --- a/tracing-build-script/src/lib.rs +++ b/tracing-build-script/src/lib.rs @@ -86,6 +86,7 @@ impl Write for BuildScriptWriter { // so we need to lock it to prevent other threads from clobbering our output. let mut writer = writer.lock(); + // depending on the current state we may need to prefix the output match *state { ErrorAndWarnState::Init => { writer.write_all(b"cargo::warning=")?; @@ -110,9 +111,7 @@ impl Write for BuildScriptWriter { // We know which case we are in // either when we enter this function the next time (case 1) // or the next time or when we enter the destructor (case 2). - let last_char = buf.last().copied(); - - match last_char { + match buf.last().copied() { Some(ch) if char_is_special(ch) => { // we strip the special char at the end so that the call to split // does not yield an empty slice in the end From 9bec623c9964a6a0defb130e042dc88958e1d69c Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Thu, 13 Feb 2025 12:15:09 +0100 Subject: [PATCH 12/14] add ci --- .github/workflows/cargo-test.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .github/workflows/cargo-test.yml diff --git a/.github/workflows/cargo-test.yml b/.github/workflows/cargo-test.yml new file mode 100644 index 0000000..3a4e024 --- /dev/null +++ b/.github/workflows/cargo-test.yml @@ -0,0 +1,12 @@ +name: Cargo Test +on: push + +jobs: + cargo-test: + runs-on: ubuntu-22.04 + steps: + - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions/checkout@v4 + - name: Run Unittests + run: | + cargo test From ba15a3c3c948d6493e9c3ca4e1fba65d90a33fe4 Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Thu, 13 Feb 2025 12:19:17 +0100 Subject: [PATCH 13/14] fix --- tracing-build-script/src/lib.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/tracing-build-script/src/lib.rs b/tracing-build-script/src/lib.rs index 474cfc4..90ed1c3 100644 --- a/tracing-build-script/src/lib.rs +++ b/tracing-build-script/src/lib.rs @@ -113,8 +113,6 @@ impl Write for BuildScriptWriter { // or the next time or when we enter the destructor (case 2). match buf.last().copied() { Some(ch) if char_is_special(ch) => { - // we strip the special char at the end so that the call to split - // does not yield an empty slice in the end buf = &buf[..buf.len() - 1]; *state = ErrorAndWarnState::LastCharWasSpecial(ch); }, From 5f7d293475d1c5ce77d9bec43c2b8d020c670b69 Mon Sep 17 00:00:00 2001 From: Liss Heidrich <31625940+liss-h@users.noreply.github.com> Date: Fri, 14 Feb 2025 11:32:30 +0100 Subject: [PATCH 14/14] add test for double newline at end --- tracing-build-script-tests/build.rs | 1 + tracing-build-script-tests/src/lib.rs | 9 +++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/tracing-build-script-tests/build.rs b/tracing-build-script-tests/build.rs index 1c87f27..be48501 100644 --- a/tracing-build-script-tests/build.rs +++ b/tracing-build-script-tests/build.rs @@ -22,4 +22,5 @@ fn main() { write_message("\nwith\nnew\nlinestart"); write_message("two\n\nnewlines"); write_message("other\rspecial\tchar\0a\tb\"c\\"); + write_message("two\nnewlines\natend\n\n"); } diff --git a/tracing-build-script-tests/src/lib.rs b/tracing-build-script-tests/src/lib.rs index 09d660b..b13c671 100644 --- a/tracing-build-script-tests/src/lib.rs +++ b/tracing-build-script-tests/src/lib.rs @@ -21,7 +21,9 @@ fn test_warn_and_error_output() { cargo::warning= WARN build_script_build: two\\n\\nnewlines\n\ cargo::warning=ERROR build_script_build: two\\n\\nnewlines\n\ cargo::warning= WARN build_script_build: other\\rspecial\tchar\0a\tb\"c\\\n\ - cargo::warning=ERROR build_script_build: other\\rspecial\tchar\0a\tb\"c\\\n" + cargo::warning=ERROR build_script_build: other\\rspecial\tchar\0a\tb\"c\\\n\ + cargo::warning= WARN build_script_build: two\\nnewlines\\natend\\n\\n\n\ + cargo::warning=ERROR build_script_build: two\\nnewlines\\natend\\n\\n\n" ); } @@ -50,6 +52,9 @@ fn test_informational_output() { INFO build_script_build: two\n\nnewlines\n\ TRACE build_script_build: other\rspecial\tchar\0a\tb\"c\\\n\ DEBUG build_script_build: other\rspecial\tchar\0a\tb\"c\\\n \ - INFO build_script_build: other\rspecial\tchar\0a\tb\"c\\\n" + INFO build_script_build: other\rspecial\tchar\0a\tb\"c\\\n\ + TRACE build_script_build: two\nnewlines\natend\n\n\n\ + DEBUG build_script_build: two\nnewlines\natend\n\n\n \ + INFO build_script_build: two\nnewlines\natend\n\n\n" ); }