pager-0.16.1/.cargo_vcs_info.json0000644000000001360000000000100122170ustar { "git": { "sha1": "2b7dc4d0bdd8a0c7cde19e8c7fbc2e5cd75c78b0" }, "path_in_vcs": "" }pager-0.16.1/.gitignore000064400000000000000000000000221046102023000127710ustar 00000000000000target Cargo.lock pager-0.16.1/.gitlab-ci.yml000064400000000000000000000010201046102023000134340ustar 00000000000000.cargo_test_template: &cargo_test stage: test script: - cargo test --verbose --jobs 1 stages: - test - deploy stable:cargo: image: rustdocker/rust:stable <<: *cargo_test beta:cargo: image: rustdocker/rust:beta <<: *cargo_test nightly:cargo: image: rustdocker/rust:nightly <<: *cargo_test .pages: image: rustdocker/rust:stable stage: deploy only: - master script: - cargo doc - rm -rf public - mkdir public - cp -R target/doc/* public artifacts: paths: - public pager-0.16.1/.travis.yml000064400000000000000000000001411046102023000131140ustar 00000000000000language: rust sudo: false rust: - stable - beta - nightly os: - osx - linux pager-0.16.1/CHANGELOG.md000064400000000000000000000002271046102023000126210ustar 00000000000000## 0.14.0 - 2017-12-xx - Make `.skip_on_notify()` default behaviour - Clean tests to pass on Fedora ## 0.13.0 - 2017-09-06 - Add `.skip_on_notty()` pager-0.16.1/Cargo.toml0000644000000021170000000000100102160ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "pager" version = "0.16.1" authors = ["Cyril Plisko "] description = "Helps pipe your output through an external pager" documentation = "https://docs.rs/pager" readme = "README.md" keywords = [ "pager", "less", "more", ] categories = [ "command-line-interface", "text-processing", ] license = "Apache-2.0/MIT" repository = "https://gitlab.com/imp/pager-rs.git" [dependencies.errno] version = "0.2" [dependencies.libc] version = "0.2" [features] pedantic = [] [badges.gitlab] repository = "imp/pager-rs" [badges.travis-ci] repository = "imp/pager-rs" pager-0.16.1/Cargo.toml.orig000064400000000000000000000012251046102023000136760ustar 00000000000000[package] name = "pager" version = "0.16.1" # remember to update html_root_url authors = ["Cyril Plisko "] description = "Helps pipe your output through an external pager" documentation = "https://docs.rs/pager" keywords = ["pager", "less", "more"] license = "Apache-2.0/MIT" readme = "README.md" repository = "https://gitlab.com/imp/pager-rs.git" edition = "2018" categories = ["command-line-interface", "text-processing"] [badges] travis-ci = { repository = "imp/pager-rs" } gitlab = { repository = "imp/pager-rs" } [dependencies] errno = "0.2" libc = "0.2" [features] pedantic = [] pager-0.16.1/LICENSE-APACHE000064400000000000000000000261161046102023000127410ustar 00000000000000 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 2016 Cyril Plisko 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. pager-0.16.1/LICENSE-MIT000064400000000000000000000020671046102023000124500ustar 00000000000000The MIT License (MIT) Copyright (c) 2016 Cyril Plisko 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. pager-0.16.1/README.md000064400000000000000000000052241046102023000122710ustar 00000000000000## Pager - long output best friend [![Build Status](https://gitlab.com/imp/pager-rs/badges/master/build.svg)](https://gitlab.com/imp/pager-rs/pipelines) [![Crates.io](https://img.shields.io/crates/v/pager.svg)](https://crates.io/crates/pager) [![Docs.rs](https://docs.rs/pager/badge.svg)](https://docs.rs/pager) Does all the magic to have you potentially long output piped through the external pager. Similar to what `git` does for its output. # Quick Start ```rust extern crate pager; use pager::Pager; fn main() { Pager::new().setup(); // The rest of your program goes here } ``` Under the hood this forks the current process, connects child' stdout to parent's stdin, and then replaces the parent with the pager of choice (environment variable PAGER). The child just continues as normal. If PAGER environment variable is not present `Pager` probes current PATH for `more`. If found it is used as a default pager. You can control pager to a limited degree. For example you can change the environment variable used for finding pager executable. ```rust extern crate pager; use pager::Pager; fn main() { Pager::with_env("MY_PAGER").setup(); // The rest of your program goes here } ``` Also you can set alternative default (fallback) pager to be used instead of `more`. PAGER environment variable (if set) will still have precedence. ```rust extern crate pager; use pager::Pager; fn main() { Pager::with_default_pager("pager").setup(); // The rest of your program goes here } ``` If no suitable pager found `setup()` does nothing and your executable keeps running as usual. `Pager` cleans after itself and doesn't leak resources in case of setup failure. Alternatively you can specify directly the desired pager command, exactly as it would appear in PAGER environment variable. This is useful if you need some specific pager and/or flags (like "less -r") and would like to avoid forcing your consumers into modifying their existing PAGER configuration just for your application. ```rust extern crate pager; use pager::Pager; fn main() { Pager::with_pager("less -r").setup(); // The rest of your program goes here } ``` Sometimes you may want to bypass pager if the output of you executable is not a `tty`. If this case you may use `.skip_on_notty()` to get the desirable effect. ```rust extern crate pager; use pager::Pager; fn main() { Pager::new().skip_on_notty().setup(); // The rest of your program goes here } ``` If you need to disable pager altogether set environment variable `NOPAGER` and Pager::setup() will skip initialization. The host application will continue as normal. Pager::is_on() will reflect the fact that no Pager is active. pager-0.16.1/src/lib.rs000064400000000000000000000222441046102023000127160ustar 00000000000000//! Does all the magic to have you potentially long output piped through the //! external pager. Similar to what git does for its output. //! //! # Quick Start //! //! ```rust //! extern crate pager; //! use pager::Pager; //! fn main() { //! Pager::new().setup(); //! // The rest of your program goes here //! } //! ``` //! //! Under the hood this forks the current process, connects child' stdout //! to parent's stdin, and then replaces the parent with the pager of choice //! (environment variable PAGER). The child just continues as normal. If PAGER //! environment variable is not present `Pager` probes current PATH for `more`. //! If found it is used as a default pager. //! //! You can control pager to a limited degree. For example you can change the //! environment variable used for finding pager executable. //! //! ```rust //! extern crate pager; //! use pager::Pager; //! fn main() { //! Pager::with_env("MY_PAGER").setup(); //! // The rest of your program goes here //! } //! ``` //! //! Also you can set alternative default (fallback) pager to be used instead of //! `more`. PAGER environment variable (if set) will still have precedence. //! //! ```rust //! extern crate pager; //! use pager::Pager; //! fn main() { //! Pager::with_default_pager("pager").setup(); //! // The rest of your program goes here //! } //! ``` //! Alternatively you can specify directly the desired pager command, exactly //! as it would appear in PAGER environment variable. This is useful if you //! need some specific pager and/or flags (like "less -r") and would like to //! avoid forcing your consumers into modifying their existing PAGER //! configuration just for your application. //! //! ```rust //! extern crate pager; //! use pager::Pager; //! fn main() { //! Pager::with_pager("pager -r").setup(); //! // The rest of your program goes here //! } //! ``` //! //! If no suitable pager found `setup()` does nothing and your executable keeps //! running as usual. `Pager` cleans after itself and doesn't leak resources in //! case of setup failure. //! //! Sometimes you may want to bypass pager if the output of you executable is not a `tty`. //! If this case you may use `.skip_on_notty()` to get the desirable effect. //! //! ```rust //! extern crate pager; //! use pager::Pager; //! fn main() { //! Pager::new().skip_on_notty().setup(); //! // The rest of your program goes here //! } //! ``` //! //! If you need to disable pager altogether set environment variable `NOPAGER` and `Pager::setup()` //! will skip initialization. The host application will continue as normal. `Pager::is_on()` will //! reflect the fact that no Pager is active. #![doc(html_root_url = "https://docs.rs/pager/0.16.1")] #![cfg_attr(feature = "pedantic", warn(clippy::pedantic))] #![warn(clippy::use_self)] #![warn(deprecated_in_future)] #![warn(future_incompatible)] #![warn(unreachable_pub)] #![warn(missing_debug_implementations)] #![warn(rust_2018_compatibility)] #![warn(rust_2018_idioms)] #![warn(unused)] #![deny(warnings)] mod utils; use std::env; use std::ffi::{OsStr, OsString}; /// Default pager environment variable const DEFAULT_PAGER_ENV: &str = "PAGER"; /// Environment variable to disable pager altogether const NOPAGER_ENV: &str = "NOPAGER"; /// Last resort pager. Should work everywhere. const DEFAULT_PAGER: &str = "more"; /// Keeps track of the current pager state #[derive(Debug)] pub struct Pager { default_pager: Option, pager: Option, envs: Vec, on: bool, skip_on_notty: bool, } impl Default for Pager { fn default() -> Self { Self { default_pager: None, pager: env::var_os(DEFAULT_PAGER_ENV), envs: Vec::new(), on: true, skip_on_notty: true, } } } impl Pager { /// Creates new instance of `Pager` with default settings pub fn new() -> Self { Self::default() } /// Creates new instance of pager using `env` environment variable instead of PAGER pub fn with_env(env: &str) -> Self { Self { pager: env::var_os(env), ..Self::default() } } #[deprecated(since = "0.12.0", note = "use with_env() instead")] pub fn env(env: &str) -> Self { Self::with_env(env) } /// Creates a new `Pager` instance with the specified default fallback pub fn with_default_pager(pager: S) -> Self where S: Into, { let default_pager = Some(pager.into()); Self { default_pager, ..Self::default() } } /// Creates a new `Pager` instance directly specifying the desired pager pub fn with_pager(pager: &str) -> Self { Self { pager: Some(pager.into()), ..Self::default() } } /// Launch pager with the specified environment variables pub fn pager_envs(self, envs: impl IntoIterator>) -> Self { let envs = envs.into_iter().map(|s| s.into()).collect(); Self { envs, ..self } } /// Instructs `Pager` to bypass invoking pager if output is not a `tty` #[deprecated(since = "0.14.0", note = "'skip_on_notty' is default now")] pub fn skip_on_notty(self) -> Self { Self { skip_on_notty: true, ..self } } /// Gives quick assessment of successful `Pager` setup pub fn is_on(&self) -> bool { self.on } fn pager(&self) -> Option { let fallback_pager = || Some(OsStr::new(DEFAULT_PAGER).into()); if env::var_os(NOPAGER_ENV).is_some() { None } else { self.pager .clone() .or_else(|| self.default_pager.clone()) .or_else(fallback_pager) } } /// Initiates Pager framework and sets up all the necessary environment for sending standard /// output to the activated pager. pub fn setup(&mut self) { if self.skip_on_notty && !utils::isatty(libc::STDOUT_FILENO) { self.on = false; return; } if let Some(ref pager) = self.pager() { let (pager_stdin, main_stdout) = utils::pipe(); let pid = utils::fork(); match pid { -1 => { // Fork failed utils::close(pager_stdin); utils::close(main_stdout); self.on = false } 0 => { // I am child utils::dup2(main_stdout, libc::STDOUT_FILENO); utils::close(pager_stdin); } _ => { // I am parent utils::dup2(pager_stdin, libc::STDIN_FILENO); utils::close(main_stdout); utils::execvpe(pager, &self.envs); } } } else { self.on = false; } } } #[cfg(test)] mod tests { use super::*; use std::ops::Drop; enum PagerEnv { Reinstate(OsString, OsString), Remove(OsString), } impl PagerEnv { fn new>(env: S) -> Self { let env = env.as_ref().into(); if let Some(value) = env::var_os(&env) { Self::Reinstate(env, value) } else { Self::Remove(env) } } fn set>(&self, value: S) { match self { Self::Reinstate(env, _) | Self::Remove(env) => env::set_var(env, value), } } fn remove(&self) { match self { Self::Reinstate(env, _) | Self::Remove(env) => env::remove_var(env), } } } impl Drop for PagerEnv { fn drop(&mut self) { match self { Self::Reinstate(env, value) => env::set_var(env, value), Self::Remove(env) => env::remove_var(env), } } } fn assert_pager(pager: &Pager, result: &str) { assert_eq!(pager.pager(), Some(OsStr::new(result).into())); } #[test] fn nopager() { let nopager = PagerEnv::new(NOPAGER_ENV); nopager.set(""); let pager = Pager::new(); assert!(pager.pager().is_none()); } #[test] fn fallback_uses_more() { let pager = Pager::new(); assert_pager(&pager, DEFAULT_PAGER); } #[test] fn with_default_pager_without_env() { let pagerenv = PagerEnv::new(DEFAULT_PAGER_ENV); pagerenv.remove(); let pager = Pager::with_default_pager("more_or_less"); assert_pager(&pager, "more_or_less"); } #[test] fn with_default_pager_with_env() { let pagerenv = PagerEnv::new(DEFAULT_PAGER_ENV); pagerenv.set("something_else"); let pager = Pager::with_default_pager("more_or_less"); assert_pager(&pager, "something_else"); } #[test] fn with_default_pager() { let pager = Pager::with_default_pager("more_or_less"); assert_pager(&pager, "more_or_less"); } #[test] fn with_pager() { let pager = Pager::with_pager("now_or_never"); assert_pager(&pager, "now_or_never"); } } pager-0.16.1/src/utils.rs000064400000000000000000000026101046102023000133030ustar 00000000000000use std::ffi::{CString, OsString}; use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::ptr; fn osstring2cstring(s: OsString) -> CString { unsafe { CString::from_vec_unchecked(s.into_vec()) } } fn split_string(s: &OsString) -> Vec { match s.clone().into_string() { Ok(cmd) => cmd.split_whitespace().map(OsString::from).collect(), Err(cmd) => vec![cmd], } } // Helper wrappers around libc::* API pub(crate) fn fork() -> libc::pid_t { unsafe { libc::fork() } } pub(crate) fn execvpe(cmd: &OsString, envs: &[OsString]) { let cstrings = split_string(cmd) .into_iter() .map(osstring2cstring) .collect::>(); let args = cstrings .iter() .map(|c| c.as_ptr()) .chain(Some(ptr::null())) .collect::>(); for env in envs { unsafe { libc::putenv(env.as_bytes().as_ptr() as *mut _) }; } errno::set_errno(errno::Errno(0)); unsafe { libc::execvp(args[0], args.as_ptr()) }; } pub(crate) fn dup2(fd1: i32, fd2: i32) { assert!(unsafe { libc::dup2(fd1, fd2) } > -1); } pub(crate) fn close(fd: i32) { assert_eq!(unsafe { libc::close(fd) }, 0); } pub(crate) fn pipe() -> (i32, i32) { let mut fds = [0; 2]; assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0); (fds[0], fds[1]) } pub(crate) fn isatty(fd: i32) -> bool { unsafe { libc::isatty(fd) != 0 } } pager-0.16.1/tests/pager.rs000064400000000000000000000005251046102023000136170ustar 00000000000000extern crate pager; use std::env; use pager::Pager; #[test] fn nopager() { env::set_var("NOPAGER", ""); let mut pager = Pager::new(); pager.setup(); env::remove_var("NOPAGER"); assert!(!pager.is_on()); } #[test] fn skip_on_notty() { let mut pager = Pager::new(); pager.setup(); assert!(!pager.is_on()); }