Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strip dependencies of bat-as-a-library #899

Merged
merged 4 commits into from
Mar 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 27 additions & 10 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,41 @@ exclude = [
build = "build.rs"
edition = '2018'

[features]
default = ["application"]
# Feature required for bat the application. Should be disabled when depending on
# bat as a library.
application = [
"atty",
"clap",
"dirs",
"git",
"lazy_static",
"liquid",
"paging",
"wild",
]
git = ["git2"] # Support indicating git modifications
paging = ["shell-words"] # Support applying a pager on the output

[dependencies]
atty = "0.2.14"
atty = { version = "0.2.14", optional = true }
ansi_term = "^0.12.1"
ansi_colours = "^1.0"
console = "0.10"
dirs = "2.0"
lazy_static = "1.4"
wild = "2.0"
dirs = { version = "2.0", optional = true }
lazy_static = { version = "1.4", optional = true }
wild = { version = "2.0", optional = true }
content_inspector = "0.2.4"
encoding = "0.2"
shell-words = "0.1.0"
shell-words = { version = "0.1.0", optional = true }
unicode-width = "0.1.7"
globset = "0.4"

[dependencies.git2]
version = "0.13"
optional = true
default-features = false
features = []

[dependencies.syntect]
version = "3.3.0"
Expand All @@ -41,22 +58,22 @@ features = ["parsing", "yaml-load", "dump-load", "dump-create"]

[dependencies.clap]
version = "2.33"
optional = true
default-features = false
features = ["suggestions", "color", "wrap_help"]

[dependencies.error-chain]
version = "0.12"
default-features = false
features = []

[dev-dependencies]
tempdir = "0.3"
assert_cmd = "0.12.0"

[build-dependencies]
clap = "2.33"
liquid = "0.20"
lazy_static = "1.4"
clap = { version = "2.33", optional = true }
liquid = { version = "0.20", optional = true }
lazy_static = { version = "1.4", optional = true }

[profile.release]
lto = true
66 changes: 35 additions & 31 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,42 @@
// TODO: Re-enable generation of shell completion files (below) when clap 3 is out.
// For more details, see https://github.com/sharkdp/bat/issues/372

#[macro_use]
extern crate lazy_static;
extern crate liquid;

use std::error::Error;
use std::fs;
use std::path::Path;

// Read environment variables.
lazy_static! {
pub static ref PROJECT_NAME: &'static str = option_env!("PROJECT_NAME").unwrap_or("bat");
pub static ref PROJECT_VERSION: &'static str = option_env!("CARGO_PKG_VERSION").unwrap();
pub static ref EXECUTABLE_NAME: &'static str = option_env!("PROJECT_EXECUTABLE")
.or(option_env!("PROJECT_NAME"))
.unwrap_or("bat");
}

/// Generates a file from a liquid template.
fn template(
variables: &liquid::Object,
in_file: &str,
out_file: impl AsRef<Path>,
) -> Result<(), Box<dyn Error>> {
let template = liquid::ParserBuilder::with_stdlib()
.build()?
.parse(&fs::read_to_string(in_file)?)?;

fs::write(out_file, template.render(variables)?)?;
Ok(())
}
// For bat-as-a-library, no build script is required. The build script is for
// the manpage and completions, which are only relevant to the bat application.
#[cfg(not(feature = "application"))]
fn main() {}

#[cfg(feature = "application")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
use std::error::Error;
use std::fs;
use std::path::Path;

use lazy_static::lazy_static;

// Read environment variables.
lazy_static! {
static ref PROJECT_NAME: &'static str = option_env!("PROJECT_NAME").unwrap_or("bat");
static ref PROJECT_VERSION: &'static str = option_env!("CARGO_PKG_VERSION").unwrap();
static ref EXECUTABLE_NAME: &'static str = option_env!("PROJECT_EXECUTABLE")
.or(option_env!("PROJECT_NAME"))
.unwrap_or("bat");
}

/// Generates a file from a liquid template.
fn template(
variables: &liquid::Object,
in_file: &str,
out_file: impl AsRef<Path>,
) -> Result<(), Box<dyn Error>> {
let template = liquid::ParserBuilder::with_stdlib()
.build()?
.parse(&fs::read_to_string(in_file)?)?;

fs::write(out_file, template.render(variables)?)?;
Ok(())
}

fn main() -> Result<(), Box<dyn Error>> {
let variables = liquid::object!({
"PROJECT_NAME": PROJECT_NAME.to_owned(),
"PROJECT_EXECUTABLE": EXECUTABLE_NAME.to_owned(),
Expand Down
6 changes: 6 additions & 0 deletions ci/script.bash
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,9 @@ if [[ $TARGET != arm-unknown-linux-gnueabihf ]] && [[ $TARGET != aarch64-unknown
# Run 'bat' on its own source code and the README
cargo run --target "$TARGET" -- src/bin/bat/main.rs README.md --paging=never
fi

# Check bat-as-a-library, which has a smaller set of dependencies
cargo check --target "$TARGET" --verbose --lib --no-default-features
cargo check --target "$TARGET" --verbose --lib --no-default-features --features git
cargo check --target "$TARGET" --verbose --lib --no-default-features --features paging
sharkdp marked this conversation as resolved.
Show resolved Hide resolved
cargo check --target "$TARGET" --verbose --lib --no-default-features --features git,paging
4 changes: 0 additions & 4 deletions src/bin/bat/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,9 @@ use crate::{
config::{get_args_from_config_file, get_args_from_env_var},
};
use clap::ArgMatches;
use wild;

use console::Term;

#[cfg(windows)]
use ansi_term;

use bat::{
config::{
Config, HighlightedLineRanges, InputFile, LineRange, LineRanges, MappingTarget, OutputWrap,
Expand Down
2 changes: 1 addition & 1 deletion src/bin/bat/clap_app.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use clap::{App as ClapApp, AppSettings, Arg, ArgGroup, SubCommand};
use clap::{crate_name, crate_version, App as ClapApp, AppSettings, Arg, ArgGroup, SubCommand};
use std::path::Path;

pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
Expand Down
2 changes: 0 additions & 2 deletions src/bin/bat/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ use std::fs;
use std::io::{self, Write};
use std::path::PathBuf;

use shell_words;

use crate::directories::PROJECT_DIRS;

pub fn config_file() -> PathBuf {
Expand Down
1 change: 0 additions & 1 deletion src/bin/bat/directories.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::env;
use std::path::{Path, PathBuf};

use dirs;
use lazy_static::lazy_static;

/// Wrapper for 'dirs' that treats MacOS more like Linux, by following the XDG specification.
Expand Down
5 changes: 0 additions & 5 deletions src/bin/bat/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]

#[macro_use]
extern crate clap;

extern crate dirs as dirs_rs;

mod app;
mod assets;
mod clap_app;
Expand Down
3 changes: 3 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ pub use crate::syntax_mapping::{MappingTarget, SyntaxMapping};
pub use crate::wrap::OutputWrap;

#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg(feature = "paging")]
pub enum PagingMode {
Always,
QuitIfOneScreen,
Never,
}
sharkdp marked this conversation as resolved.
Show resolved Hide resolved

#[cfg(feature = "paging")]
impl Default for PagingMode {
fn default() -> Self {
PagingMode::Never
Expand Down Expand Up @@ -51,6 +53,7 @@ pub struct Config<'a> {
pub output_wrap: OutputWrap,

/// Pager or STDOUT
#[cfg(feature = "paging")]
pub paging_mode: PagingMode,

/// Specifies the lines that should be printed
Expand Down
41 changes: 27 additions & 14 deletions src/controller.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use std::io::{self, Write};
use std::path::Path;

use crate::assets::HighlightingAssets;
use crate::config::{Config, PagingMode};
use crate::config::Config;
#[cfg(feature = "paging")]
use crate::config::PagingMode;
use crate::errors::*;
use crate::inputfile::{InputFile, InputFileReader};
use crate::line_range::{LineRanges, RangeCheckResult};
Expand All @@ -24,22 +25,34 @@ impl<'b> Controller<'b> {
}

pub fn run_with_error_handler(&self, handle_error: impl Fn(&Error)) -> Result<bool> {
// Do not launch the pager if NONE of the input files exist
let mut paging_mode = self.config.paging_mode;
if self.config.paging_mode != PagingMode::Never {
let call_pager = self.config.files.iter().any(|file| {
if let InputFile::Ordinary(path) = file {
return Path::new(path).exists();
} else {
return true;
let mut output_type;

#[cfg(feature = "paging")]
{
use std::path::Path;

// Do not launch the pager if NONE of the input files exist
let mut paging_mode = self.config.paging_mode;
if self.config.paging_mode != PagingMode::Never {
let call_pager = self.config.files.iter().any(|file| {
if let InputFile::Ordinary(path) = file {
return Path::new(path).exists();
} else {
return true;
}
});
if !call_pager {
paging_mode = PagingMode::Never;
}
});
if !call_pager {
paging_mode = PagingMode::Never;
}
output_type = OutputType::from_mode(paging_mode, self.config.pager)?;
}

#[cfg(not(feature = "paging"))]
{
output_type = OutputType::stdout();
}

let mut output_type = OutputType::from_mode(paging_mode, self.config.pager)?;
let writer = output_type.handle()?;
let mut no_errors: bool = true;

Expand Down
4 changes: 4 additions & 0 deletions src/decorations.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#[cfg(feature = "git")]
use crate::diff::LineChange;
use crate::printer::{Colors, InteractivePrinter};
use ansi_term::Style;
Expand Down Expand Up @@ -68,6 +69,7 @@ impl Decoration for LineNumberDecoration {
}
}

#[cfg(feature = "git")]
pub struct LineChangesDecoration {
cached_none: DecorationText,
cached_added: DecorationText,
Expand All @@ -76,6 +78,7 @@ pub struct LineChangesDecoration {
cached_modified: DecorationText,
}

#[cfg(feature = "git")]
impl LineChangesDecoration {
#[inline]
fn generate_cached(style: Style, text: &str) -> DecorationText {
Expand All @@ -96,6 +99,7 @@ impl LineChangesDecoration {
}
}

#[cfg(feature = "git")]
impl Decoration for LineChangesDecoration {
fn generate(
&self,
Expand Down
2 changes: 2 additions & 0 deletions src/diff.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![cfg(feature = "git")]

use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
Expand Down
2 changes: 1 addition & 1 deletion src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use error_chain::error_chain;

error_chain! {
foreign_links {
Clap(::clap::Error);
Clap(::clap::Error) #[cfg(feature = "application")];
Io(::std::io::Error);
SyntectError(::syntect::LoadingError);
ParseIntError(::std::num::ParseIntError);
Expand Down
2 changes: 2 additions & 0 deletions src/less.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![cfg(feature = "paging")]

use std::process::Command;

pub fn retrieve_less_version() -> Option<usize> {
Expand Down
11 changes: 0 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,6 @@
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]

extern crate ansi_term;
extern crate atty;
extern crate console;
extern crate content_inspector;
extern crate dirs as dirs_rs;
extern crate encoding;
extern crate git2;
extern crate shell_words;
extern crate syntect;
extern crate wild;

pub(crate) mod assets;
pub mod config;
pub(crate) mod controller;
Expand Down
Loading