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 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..e6c983e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] +resolver = "2" +members = [ + "tracing-build-script", + "tracing-build-script-tests", +] 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. 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. diff --git a/README.md b/README.md index e69de29..88605e5 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,30 @@ +# 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 +[package] +# ... +build = "build.rs" + +[build-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(); +> +> ... +> } +> ``` 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..be48501 --- /dev/null +++ b/tracing-build-script-tests/build.rs @@ -0,0 +1,26 @@ +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\\"); + 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 new file mode 100644 index 0000000..b13c671 --- /dev/null +++ b/tracing-build-script-tests/src/lib.rs @@ -0,0 +1,60 @@ +#![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\ + cargo::warning= WARN build_script_build: two\\nnewlines\\natend\\n\\n\n\ + cargo::warning=ERROR build_script_build: two\\nnewlines\\natend\\n\\n\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\ + 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" + ); +} 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..90ed1c3 --- /dev/null +++ b/tracing-build-script/src/lib.rs @@ -0,0 +1,193 @@ +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(); + + // depending on the current state we may need to prefix the output + 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). + match buf.last().copied() { + Some(ch) if char_is_special(ch) => { + 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() + } + } +}