repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/17_tests/tests2.rs | exercises/17_tests/tests2.rs | // Calculates the power of 2 using a bit shift.
// `1 << n` is equivalent to "2 to the power of n".
fn power_of_2(n: u8) -> u64 {
1 << n
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn you_can_assert_eq() {
// TODO: Test the function `power_of_2` with some values.
assert_eq!();
assert_eq!();
assert_eq!();
assert_eq!();
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/17_tests/tests3.rs | exercises/17_tests/tests3.rs | struct Rectangle {
width: i32,
height: i32,
}
impl Rectangle {
// Don't change this function.
fn new(width: i32, height: i32) -> Self {
if width <= 0 || height <= 0 {
// Returning a `Result` would be better here. But we want to learn
// how to test functions that can panic.
panic!("Rectangle width and height must be positive");
}
Rectangle { width, height }
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn correct_width_and_height() {
// TODO: This test should check if the rectangle has the size that we
// pass to its constructor.
let rect = Rectangle::new(10, 20);
assert_eq!(todo!(), 10); // Check width
assert_eq!(todo!(), 20); // Check height
}
// TODO: This test should check if the program panics when we try to create
// a rectangle with negative width.
#[test]
fn negative_width() {
let _rect = Rectangle::new(-10, 10);
}
// TODO: This test should check if the program panics when we try to create
// a rectangle with negative height.
#[test]
fn negative_height() {
let _rect = Rectangle::new(10, -10);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/15_traits/traits3.rs | exercises/15_traits/traits3.rs | trait Licensed {
// TODO: Add a default implementation for `licensing_info` so that
// implementors like the two structs below can share that default behavior
// without repeating the function.
// The default license information should be the string "Default license".
fn licensing_info(&self) -> String;
}
struct SomeSoftware {
version_number: i32,
}
struct OtherSoftware {
version_number: String,
}
impl Licensed for SomeSoftware {} // Don't edit this line.
impl Licensed for OtherSoftware {} // Don't edit this line.
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_licensing_info_the_same() {
let licensing_info = "Default license";
let some_software = SomeSoftware { version_number: 1 };
let other_software = OtherSoftware {
version_number: "v2.0.0".to_string(),
};
assert_eq!(some_software.licensing_info(), licensing_info);
assert_eq!(other_software.licensing_info(), licensing_info);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/15_traits/traits4.rs | exercises/15_traits/traits4.rs | trait Licensed {
fn licensing_info(&self) -> String {
"Default license".to_string()
}
}
struct SomeSoftware;
struct OtherSoftware;
impl Licensed for SomeSoftware {}
impl Licensed for OtherSoftware {}
// TODO: Fix the compiler error by only changing the signature of this function.
fn compare_license_types(software1: ???, software2: ???) -> bool {
software1.licensing_info() == software2.licensing_info()
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compare_license_information() {
assert!(compare_license_types(SomeSoftware, OtherSoftware));
}
#[test]
fn compare_license_information_backwards() {
assert!(compare_license_types(OtherSoftware, SomeSoftware));
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/15_traits/traits1.rs | exercises/15_traits/traits1.rs | // The trait `AppendBar` has only one function which appends "Bar" to any object
// implementing this trait.
trait AppendBar {
fn append_bar(self) -> Self;
}
impl AppendBar for String {
// TODO: Implement `AppendBar` for the type `String`.
}
fn main() {
let s = String::from("Foo");
let s = s.append_bar();
println!("s: {s}");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_foo_bar() {
assert_eq!(String::from("Foo").append_bar(), "FooBar");
}
#[test]
fn is_bar_bar() {
assert_eq!(String::from("").append_bar().append_bar(), "BarBar");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/15_traits/traits5.rs | exercises/15_traits/traits5.rs | trait SomeTrait {
fn some_function(&self) -> bool {
true
}
}
trait OtherTrait {
fn other_function(&self) -> bool {
true
}
}
struct SomeStruct;
impl SomeTrait for SomeStruct {}
impl OtherTrait for SomeStruct {}
struct OtherStruct;
impl SomeTrait for OtherStruct {}
impl OtherTrait for OtherStruct {}
// TODO: Fix the compiler error by only changing the signature of this function.
fn some_func(item: ???) -> bool {
item.some_function() && item.other_function()
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_some_func() {
assert!(some_func(SomeStruct));
assert!(some_func(OtherStruct));
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/15_traits/traits2.rs | exercises/15_traits/traits2.rs | trait AppendBar {
fn append_bar(self) -> Self;
}
// TODO: Implement the trait `AppendBar` for a vector of strings.
// `append_bar` should push the string "Bar" into the vector.
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_vec_pop_eq_bar() {
let mut foo = vec![String::from("Foo")].append_bar();
assert_eq!(foo.pop().unwrap(), "Bar");
assert_eq!(foo.pop().unwrap(), "Foo");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/11_hashmaps/hashmaps3.rs | exercises/11_hashmaps/hashmaps3.rs | // A list of scores (one per line) of a soccer match is given. Each line is of
// the form "<team_1_name>,<team_2_name>,<team_1_goals>,<team_2_goals>"
// Example: "England,France,4,2" (England scored 4 goals, France 2).
//
// You have to build a scores table containing the name of the team, the total
// number of goals the team scored, and the total number of goals the team
// conceded.
use std::collections::HashMap;
// A structure to store the goal details of a team.
#[derive(Default)]
struct TeamScores {
goals_scored: u8,
goals_conceded: u8,
}
fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> {
// The name of the team is the key and its associated struct is the value.
let mut scores = HashMap::<&str, TeamScores>::new();
for line in results.lines() {
let mut split_iterator = line.split(',');
// NOTE: We use `unwrap` because we didn't deal with error handling yet.
let team_1_name = split_iterator.next().unwrap();
let team_2_name = split_iterator.next().unwrap();
let team_1_score: u8 = split_iterator.next().unwrap().parse().unwrap();
let team_2_score: u8 = split_iterator.next().unwrap().parse().unwrap();
// TODO: Populate the scores table with the extracted details.
// Keep in mind that goals scored by team 1 will be the number of goals
// conceded by team 2. Similarly, goals scored by team 2 will be the
// number of goals conceded by team 1.
}
scores
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
const RESULTS: &str = "England,France,4,2
France,Italy,3,1
Poland,Spain,2,0
Germany,England,2,1
England,Spain,1,0";
#[test]
fn build_scores() {
let scores = build_scores_table(RESULTS);
assert!(["England", "France", "Germany", "Italy", "Poland", "Spain"]
.into_iter()
.all(|team_name| scores.contains_key(team_name)));
}
#[test]
fn validate_team_score_1() {
let scores = build_scores_table(RESULTS);
let team = scores.get("England").unwrap();
assert_eq!(team.goals_scored, 6);
assert_eq!(team.goals_conceded, 4);
}
#[test]
fn validate_team_score_2() {
let scores = build_scores_table(RESULTS);
let team = scores.get("Spain").unwrap();
assert_eq!(team.goals_scored, 0);
assert_eq!(team.goals_conceded, 3);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/11_hashmaps/hashmaps2.rs | exercises/11_hashmaps/hashmaps2.rs | // We're collecting different fruits to bake a delicious fruit cake. For this,
// we have a basket, which we'll represent in the form of a hash map. The key
// represents the name of each fruit we collect and the value represents how
// many of that particular fruit we have collected. Three types of fruits -
// Apple (4), Mango (2) and Lychee (5) are already in the basket hash map. You
// must add fruit to the basket so that there is at least one of each kind and
// more than 11 in total - we have a lot of mouths to feed. You are not allowed
// to insert any more of the fruits that are already in the basket (Apple,
// Mango, and Lychee).
use std::collections::HashMap;
#[derive(Hash, PartialEq, Eq, Debug)]
enum Fruit {
Apple,
Banana,
Mango,
Lychee,
Pineapple,
}
fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
let fruit_kinds = [
Fruit::Apple,
Fruit::Banana,
Fruit::Mango,
Fruit::Lychee,
Fruit::Pineapple,
];
for fruit in fruit_kinds {
// TODO: Insert new fruits if they are not already present in the
// basket. Note that you are not allowed to put any type of fruit that's
// already present!
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
// Don't modify this function!
fn get_fruit_basket() -> HashMap<Fruit, u32> {
let content = [(Fruit::Apple, 4), (Fruit::Mango, 2), (Fruit::Lychee, 5)];
HashMap::from_iter(content)
}
#[test]
fn test_given_fruits_are_not_modified() {
let mut basket = get_fruit_basket();
fruit_basket(&mut basket);
assert_eq!(*basket.get(&Fruit::Apple).unwrap(), 4);
assert_eq!(*basket.get(&Fruit::Mango).unwrap(), 2);
assert_eq!(*basket.get(&Fruit::Lychee).unwrap(), 5);
}
#[test]
fn at_least_five_types_of_fruits() {
let mut basket = get_fruit_basket();
fruit_basket(&mut basket);
let count_fruit_kinds = basket.len();
assert!(count_fruit_kinds >= 5);
}
#[test]
fn greater_than_eleven_fruits() {
let mut basket = get_fruit_basket();
fruit_basket(&mut basket);
let count = basket.values().sum::<u32>();
assert!(count > 11);
}
#[test]
fn all_fruit_types_in_basket() {
let fruit_kinds = [
Fruit::Apple,
Fruit::Banana,
Fruit::Mango,
Fruit::Lychee,
Fruit::Pineapple,
];
let mut basket = get_fruit_basket();
fruit_basket(&mut basket);
for fruit_kind in fruit_kinds {
let Some(amount) = basket.get(&fruit_kind) else {
panic!("Fruit kind {fruit_kind:?} was not found in basket");
};
assert!(*amount > 0);
}
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/11_hashmaps/hashmaps1.rs | exercises/11_hashmaps/hashmaps1.rs | // A basket of fruits in the form of a hash map needs to be defined. The key
// represents the name of the fruit and the value represents how many of that
// particular fruit is in the basket. You have to put at least 3 different
// types of fruits (e.g. apple, banana, mango) in the basket and the total count
// of all the fruits should be at least 5.
use std::collections::HashMap;
fn fruit_basket() -> HashMap<String, u32> {
// TODO: Declare the hash map.
// let mut basket =
// Two bananas are already given for you :)
basket.insert(String::from("banana"), 2);
// TODO: Put more fruits in your basket.
basket
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn at_least_three_types_of_fruits() {
let basket = fruit_basket();
assert!(basket.len() >= 3);
}
#[test]
fn at_least_five_fruits() {
let basket = fruit_basket();
assert!(basket.values().sum::<u32>() >= 5);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/08_enums/enums2.rs | exercises/08_enums/enums2.rs | #[derive(Debug)]
struct Point {
x: u64,
y: u64,
}
#[derive(Debug)]
enum Message {
// TODO: Define the different variants used below.
}
impl Message {
fn call(&self) {
println!("{self:?}");
}
}
fn main() {
let messages = [
Message::Resize {
width: 10,
height: 30,
},
Message::Move(Point { x: 10, y: 15 }),
Message::Echo(String::from("hello world")),
Message::ChangeColor(200, 255, 255),
Message::Quit,
];
for message in &messages {
message.call();
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/08_enums/enums1.rs | exercises/08_enums/enums1.rs | #[derive(Debug)]
enum Message {
// TODO: Define a few types of messages as used below.
}
fn main() {
println!("{:?}", Message::Resize);
println!("{:?}", Message::Move);
println!("{:?}", Message::Echo);
println!("{:?}", Message::ChangeColor);
println!("{:?}", Message::Quit);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/08_enums/enums3.rs | exercises/08_enums/enums3.rs | struct Point {
x: u64,
y: u64,
}
enum Message {
Resize { width: u64, height: u64 },
Move(Point),
Echo(String),
ChangeColor(u8, u8, u8),
Quit,
}
struct State {
width: u64,
height: u64,
position: Point,
message: String,
// RGB color composed of red, green and blue.
color: (u8, u8, u8),
quit: bool,
}
impl State {
fn resize(&mut self, width: u64, height: u64) {
self.width = width;
self.height = height;
}
fn move_position(&mut self, point: Point) {
self.position = point;
}
fn echo(&mut self, s: String) {
self.message = s;
}
fn change_color(&mut self, red: u8, green: u8, blue: u8) {
self.color = (red, green, blue);
}
fn quit(&mut self) {
self.quit = true;
}
fn process(&mut self, message: Message) {
// TODO: Create a match expression to process the different message
// variants using the methods defined above.
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_match_message_call() {
let mut state = State {
width: 0,
height: 0,
position: Point { x: 0, y: 0 },
message: String::from("hello world"),
color: (0, 0, 0),
quit: false,
};
state.process(Message::Resize {
width: 10,
height: 30,
});
state.process(Message::Move(Point { x: 10, y: 15 }));
state.process(Message::Echo(String::from("Hello world!")));
state.process(Message::ChangeColor(255, 0, 255));
state.process(Message::Quit);
assert_eq!(state.width, 10);
assert_eq!(state.height, 30);
assert_eq!(state.position.x, 10);
assert_eq!(state.position.y, 15);
assert_eq!(state.message, "Hello world!");
assert_eq!(state.color, (255, 0, 255));
assert!(state.quit);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/18_iterators/iterators1.rs | exercises/18_iterators/iterators1.rs | // When performing operations on elements within a collection, iterators are
// essential. This module helps you get familiar with the structure of using an
// iterator and how to go through elements within an iterable collection.
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
#[test]
fn iterators() {
let my_fav_fruits = ["banana", "custard apple", "avocado", "peach", "raspberry"];
// TODO: Create an iterator over the array.
let mut fav_fruits_iterator = todo!();
assert_eq!(fav_fruits_iterator.next(), Some(&"banana"));
assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()`
assert_eq!(fav_fruits_iterator.next(), Some(&"avocado"));
assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()`
assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry"));
assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()`
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/18_iterators/iterators4.rs | exercises/18_iterators/iterators4.rs | fn factorial(num: u64) -> u64 {
// TODO: Complete this function to return the factorial of `num` which is
// defined as `1 * 2 * 3 * … * num`.
// https://en.wikipedia.org/wiki/Factorial
//
// Do not use:
// - early returns (using the `return` keyword explicitly)
// Try not to use:
// - imperative style loops (for/while)
// - additional variables
// For an extra challenge, don't use:
// - recursion
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn factorial_of_0() {
assert_eq!(factorial(0), 1);
}
#[test]
fn factorial_of_1() {
assert_eq!(factorial(1), 1);
}
#[test]
fn factorial_of_2() {
assert_eq!(factorial(2), 2);
}
#[test]
fn factorial_of_4() {
assert_eq!(factorial(4), 24);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/18_iterators/iterators3.rs | exercises/18_iterators/iterators3.rs | #[derive(Debug, PartialEq, Eq)]
enum DivisionError {
// Example: 42 / 0
DivideByZero,
// Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1`
IntegerOverflow,
// Example: 5 / 2 = 2.5
NotDivisible,
}
// TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
// Otherwise, return a suitable error.
fn divide(a: i64, b: i64) -> Result<i64, DivisionError> {
todo!();
}
// TODO: Add the correct return type and complete the function body.
// Desired output: `Ok([1, 11, 1426, 3])`
fn result_with_list() {
let numbers = [27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27));
}
// TODO: Add the correct return type and complete the function body.
// Desired output: `[Ok(1), Ok(11), Ok(1426), Ok(3)]`
fn list_of_results() {
let numbers = [27, 297, 38502, 81];
let division_results = numbers.into_iter().map(|n| divide(n, 27));
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_success() {
assert_eq!(divide(81, 9), Ok(9));
assert_eq!(divide(81, -1), Ok(-81));
assert_eq!(divide(i64::MIN, i64::MIN), Ok(1));
}
#[test]
fn test_divide_by_0() {
assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero));
}
#[test]
fn test_integer_overflow() {
assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow));
}
#[test]
fn test_not_divisible() {
assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible));
}
#[test]
fn test_divide_0_by_something() {
assert_eq!(divide(0, 81), Ok(0));
}
#[test]
fn test_result_with_list() {
assert_eq!(result_with_list().unwrap(), [1, 11, 1426, 3]);
}
#[test]
fn test_list_of_results() {
assert_eq!(list_of_results(), [Ok(1), Ok(11), Ok(1426), Ok(3)]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/18_iterators/iterators2.rs | exercises/18_iterators/iterators2.rs | // In this exercise, you'll learn some of the unique advantages that iterators
// can offer.
// TODO: Complete the `capitalize_first` function.
// "hello" -> "Hello"
fn capitalize_first(input: &str) -> String {
let mut chars = input.chars();
match chars.next() {
None => String::new(),
Some(first) => todo!(),
}
}
// TODO: Apply the `capitalize_first` function to a slice of string slices.
// Return a vector of strings.
// ["hello", "world"] -> ["Hello", "World"]
fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
// ???
}
// TODO: Apply the `capitalize_first` function again to a slice of string
// slices. Return a single string.
// ["hello", " ", "world"] -> "Hello World"
fn capitalize_words_string(words: &[&str]) -> String {
// ???
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_success() {
assert_eq!(capitalize_first("hello"), "Hello");
}
#[test]
fn test_empty() {
assert_eq!(capitalize_first(""), "");
}
#[test]
fn test_iterate_string_vec() {
let words = vec!["hello", "world"];
assert_eq!(capitalize_words_vector(&words), ["Hello", "World"]);
}
#[test]
fn test_iterate_into_string() {
let words = vec!["hello", " ", "world"];
assert_eq!(capitalize_words_string(&words), "Hello World");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/18_iterators/iterators5.rs | exercises/18_iterators/iterators5.rs | // Let's define a simple model to track Rustlings' exercise progress. Progress
// will be modelled using a hash map. The name of the exercise is the key and
// the progress is the value. Two counting functions were created to count the
// number of exercises with a given progress. Recreate this counting
// functionality using iterators. Try to not use imperative loops (for/while).
use std::collections::HashMap;
#[derive(Clone, Copy, PartialEq, Eq)]
enum Progress {
None,
Some,
Complete,
}
fn count_for(map: &HashMap<String, Progress>, value: Progress) -> usize {
let mut count = 0;
for val in map.values() {
if *val == value {
count += 1;
}
}
count
}
// TODO: Implement the functionality of `count_for` but with an iterator instead
// of a `for` loop.
fn count_iterator(map: &HashMap<String, Progress>, value: Progress) -> usize {
// `map` is a hash map with `String` keys and `Progress` values.
// map = { "variables1": Complete, "from_str": None, … }
}
fn count_collection_for(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
let mut count = 0;
for map in collection {
for val in map.values() {
if *val == value {
count += 1;
}
}
}
count
}
// TODO: Implement the functionality of `count_collection_for` but with an
// iterator instead of a `for` loop.
fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Progress) -> usize {
// `collection` is a slice of hash maps.
// collection = [{ "variables1": Complete, "from_str": None, … },
// { "variables2": Complete, … }, … ]
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
fn get_map() -> HashMap<String, Progress> {
use Progress::*;
let mut map = HashMap::new();
map.insert(String::from("variables1"), Complete);
map.insert(String::from("functions1"), Complete);
map.insert(String::from("hashmap1"), Complete);
map.insert(String::from("arc1"), Some);
map.insert(String::from("as_ref_mut"), None);
map.insert(String::from("from_str"), None);
map
}
fn get_vec_map() -> Vec<HashMap<String, Progress>> {
use Progress::*;
let map = get_map();
let mut other = HashMap::new();
other.insert(String::from("variables2"), Complete);
other.insert(String::from("functions2"), Complete);
other.insert(String::from("if1"), Complete);
other.insert(String::from("from_into"), None);
other.insert(String::from("try_from_into"), None);
vec![map, other]
}
#[test]
fn count_complete() {
let map = get_map();
assert_eq!(count_iterator(&map, Progress::Complete), 3);
}
#[test]
fn count_some() {
let map = get_map();
assert_eq!(count_iterator(&map, Progress::Some), 1);
}
#[test]
fn count_none() {
let map = get_map();
assert_eq!(count_iterator(&map, Progress::None), 2);
}
#[test]
fn count_complete_equals_for() {
let map = get_map();
let progress_states = [Progress::Complete, Progress::Some, Progress::None];
for progress_state in progress_states {
assert_eq!(
count_for(&map, progress_state),
count_iterator(&map, progress_state),
);
}
}
#[test]
fn count_collection_complete() {
let collection = get_vec_map();
assert_eq!(
count_collection_iterator(&collection, Progress::Complete),
6,
);
}
#[test]
fn count_collection_some() {
let collection = get_vec_map();
assert_eq!(count_collection_iterator(&collection, Progress::Some), 1);
}
#[test]
fn count_collection_none() {
let collection = get_vec_map();
assert_eq!(count_collection_iterator(&collection, Progress::None), 4);
}
#[test]
fn count_collection_equals_for() {
let collection = get_vec_map();
let progress_states = [Progress::Complete, Progress::Some, Progress::None];
for progress_state in progress_states {
assert_eq!(
count_collection_for(&collection, progress_state),
count_collection_iterator(&collection, progress_state),
);
}
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/03_if/if1.rs | exercises/03_if/if1.rs | fn bigger(a: i32, b: i32) -> i32 {
// TODO: Complete this function to return the bigger number!
// If both numbers are equal, any of them can be returned.
// Do not use:
// - another function call
// - additional variables
}
fn main() {
// You can optionally experiment here.
}
// Don't mind this for now :)
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ten_is_bigger_than_eight() {
assert_eq!(10, bigger(10, 8));
}
#[test]
fn fortytwo_is_bigger_than_thirtytwo() {
assert_eq!(42, bigger(32, 42));
}
#[test]
fn equal_numbers() {
assert_eq!(42, bigger(42, 42));
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/03_if/if3.rs | exercises/03_if/if3.rs | fn animal_habitat(animal: &str) -> &str {
// TODO: Fix the compiler error in the statement below.
let identifier = if animal == "crab" {
1
} else if animal == "gopher" {
2.0
} else if animal == "snake" {
3
} else {
"Unknown"
};
// Don't change the expression below!
if identifier == 1 {
"Beach"
} else if identifier == 2 {
"Burrow"
} else if identifier == 3 {
"Desert"
} else {
"Unknown"
}
}
fn main() {
// You can optionally experiment here.
}
// Don't change the tests!
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gopher_lives_in_burrow() {
assert_eq!(animal_habitat("gopher"), "Burrow")
}
#[test]
fn snake_lives_in_desert() {
assert_eq!(animal_habitat("snake"), "Desert")
}
#[test]
fn crab_lives_on_beach() {
assert_eq!(animal_habitat("crab"), "Beach")
}
#[test]
fn unknown_animal() {
assert_eq!(animal_habitat("dinosaur"), "Unknown")
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/03_if/if2.rs | exercises/03_if/if2.rs | // TODO: Fix the compiler error on this function.
fn picky_eater(food: &str) -> &str {
if food == "strawberry" {
"Yummy!"
} else {
1
}
}
fn main() {
// You can optionally experiment here.
}
// TODO: Read the tests to understand the desired behavior.
// Make all tests pass without changing them.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn yummy_food() {
// This means that calling `picky_eater` with the argument "strawberry" should return "Yummy!".
assert_eq!(picky_eater("strawberry"), "Yummy!");
}
#[test]
fn neutral_food() {
assert_eq!(picky_eater("potato"), "I guess I can eat that.");
}
#[test]
fn default_disliked_food() {
assert_eq!(picky_eater("broccoli"), "No thanks!");
assert_eq!(picky_eater("gummy bears"), "No thanks!");
assert_eq!(picky_eater("literally anything"), "No thanks!");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/05_vecs/vecs1.rs | exercises/05_vecs/vecs1.rs | fn array_and_vec() -> ([i32; 4], Vec<i32>) {
let a = [10, 20, 30, 40]; // Array
// TODO: Create a vector called `v` which contains the exact same elements as in the array `a`.
// Use the vector macro.
// let v = ???;
(a, v)
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_array_and_vec_similarity() {
let (a, v) = array_and_vec();
assert_eq!(a, *v);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/05_vecs/vecs2.rs | exercises/05_vecs/vecs2.rs | fn vec_loop(input: &[i32]) -> Vec<i32> {
let mut output = Vec::new();
for element in input {
// TODO: Multiply each element in the `input` slice by 2 and push it to
// the `output` vector.
}
output
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_vec_loop() {
let input = [2, 4, 6, 8, 10];
let ans = vec_loop(&input);
assert_eq!(ans, [4, 8, 12, 16, 20]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/14_generics/generics2.rs | exercises/14_generics/generics2.rs | // This powerful wrapper provides the ability to store a positive integer value.
// TODO: Rewrite it using a generic so that it supports wrapping ANY type.
struct Wrapper {
value: u32,
}
// TODO: Adapt the struct's implementation to be generic over the wrapped value.
impl Wrapper {
fn new(value: u32) -> Self {
Wrapper { value }
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn store_u32_in_wrapper() {
assert_eq!(Wrapper::new(42).value, 42);
}
#[test]
fn store_str_in_wrapper() {
assert_eq!(Wrapper::new("Foo").value, "Foo");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/14_generics/generics1.rs | exercises/14_generics/generics1.rs | // `Vec<T>` is generic over the type `T`. In most cases, the compiler is able to
// infer `T`, for example after pushing a value with a concrete type to the vector.
// But in this exercise, the compiler needs some help through a type annotation.
fn main() {
// TODO: Fix the compiler error by annotating the type of the vector
// `Vec<T>`. Choose `T` as some integer type that can be created from
// `u8` and `i8`.
let mut numbers = Vec::new();
// Don't change the lines below.
let n1: u8 = 42;
numbers.push(n1.into());
let n2: i8 = -1;
numbers.push(n2.into());
println!("{numbers:?}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/10_modules/modules1.rs | exercises/10_modules/modules1.rs | // TODO: Fix the compiler error about calling a private function.
mod sausage_factory {
// Don't let anybody outside of this module see this!
fn get_secret_recipe() -> String {
String::from("Ginger")
}
fn make_sausage() {
get_secret_recipe();
println!("sausage!");
}
}
fn main() {
sausage_factory::make_sausage();
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/10_modules/modules3.rs | exercises/10_modules/modules3.rs | // You can use the `use` keyword to bring module paths from modules from
// anywhere and especially from the standard library into your scope.
// TODO: Bring `SystemTime` and `UNIX_EPOCH` from the `std::time` module into
// your scope. Bonus style points if you can do it with one line!
// use ???;
fn main() {
match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/10_modules/modules2.rs | exercises/10_modules/modules2.rs | // You can bring module paths into scopes and provide new names for them with
// the `use` and `as` keywords.
mod delicious_snacks {
// TODO: Add the following two `use` statements after fixing them.
// use self::fruits::PEAR as ???;
// use self::veggies::CUCUMBER as ???;
mod fruits {
pub const PEAR: &str = "Pear";
pub const APPLE: &str = "Apple";
}
mod veggies {
pub const CUCUMBER: &str = "Cucumber";
pub const CARROT: &str = "Carrot";
}
}
fn main() {
println!(
"favorite snacks: {} and {}",
delicious_snacks::fruit,
delicious_snacks::veggie,
);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/quizzes/quiz2.rs | exercises/quizzes/quiz2.rs | // This is a quiz for the following sections:
// - Strings
// - Vecs
// - Move semantics
// - Modules
// - Enums
//
// Let's build a little machine in the form of a function. As input, we're going
// to give a list of strings and commands. These commands determine what action
// is going to be applied to the string. It can either be:
// - Uppercase the string
// - Trim the string
// - Append "bar" to the string a specified amount of times
//
// The exact form of this will be:
// - The input is going to be a Vector of 2-length tuples,
// the first element is the string, the second one is the command.
// - The output element is going to be a vector of strings.
enum Command {
Uppercase,
Trim,
Append(usize),
}
mod my_module {
use super::Command;
// TODO: Complete the function as described above.
// pub fn transformer(input: ???) -> ??? { ??? }
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
// TODO: What do we need to import to have `transformer` in scope?
// use ???;
use super::Command;
#[test]
fn it_works() {
let input = vec![
("hello".to_string(), Command::Uppercase),
(" all roads lead to rome! ".to_string(), Command::Trim),
("foo".to_string(), Command::Append(1)),
("bar".to_string(), Command::Append(5)),
];
let output = transformer(input);
assert_eq!(
output,
[
"HELLO",
"all roads lead to rome!",
"foobar",
"barbarbarbarbarbar",
]
);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/quizzes/quiz3.rs | exercises/quizzes/quiz3.rs | // This quiz tests:
// - Generics
// - Traits
//
// An imaginary magical school has a new report card generation system written
// in Rust! Currently, the system only supports creating report cards where the
// student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the
// school also issues alphabetical grades (A+ -> F-) and needs to be able to
// print both types of report card!
//
// Make the necessary code changes in the struct `ReportCard` and the impl
// block to support alphabetical report cards in addition to numerical ones.
// TODO: Adjust the struct as described above.
struct ReportCard {
grade: f32,
student_name: String,
student_age: u8,
}
// TODO: Adjust the impl block as described above.
impl ReportCard {
fn print(&self) -> String {
format!(
"{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade,
)
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generate_numeric_report_card() {
let report_card = ReportCard {
grade: 2.1,
student_name: "Tom Wriggle".to_string(),
student_age: 12,
};
assert_eq!(
report_card.print(),
"Tom Wriggle (12) - achieved a grade of 2.1",
);
}
#[test]
fn generate_alphabetic_report_card() {
let report_card = ReportCard {
grade: "A+",
student_name: "Gary Plotter".to_string(),
student_age: 11,
};
assert_eq!(
report_card.print(),
"Gary Plotter (11) - achieved a grade of A+",
);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/quizzes/quiz1.rs | exercises/quizzes/quiz1.rs | // This is a quiz for the following sections:
// - Variables
// - Functions
// - If
//
// Mary is buying apples. The price of an apple is calculated as follows:
// - An apple costs 2 rustbucks.
// - However, if Mary buys more than 40 apples, the price of each apple in the
// entire order is reduced to only 1 rustbuck!
// TODO: Write a function that calculates the price of an order of apples given
// the quantity bought.
// fn calculate_price_of_apples(???) -> ??? { ??? }
fn main() {
// You can optionally experiment here.
}
// Don't change the tests!
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verify_test() {
assert_eq!(calculate_price_of_apples(35), 70);
assert_eq!(calculate_price_of_apples(40), 80);
assert_eq!(calculate_price_of_apples(41), 41);
assert_eq!(calculate_price_of_apples(65), 65);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/16_lifetimes/lifetimes1.rs | exercises/16_lifetimes/lifetimes1.rs | // The Rust compiler needs to know how to check whether supplied references are
// valid, so that it can let the programmer know if a reference is at risk of
// going out of scope before it is used. Remember, references are borrows and do
// not own their own data. What if their owner goes out of scope?
// TODO: Fix the compiler error by updating the function signature.
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_longest() {
assert_eq!(longest("abcd", "123"), "abcd");
assert_eq!(longest("abc", "1234"), "1234");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/16_lifetimes/lifetimes3.rs | exercises/16_lifetimes/lifetimes3.rs | // Lifetimes are also needed when structs hold references.
// TODO: Fix the compiler errors about the struct.
struct Book {
author: &str,
title: &str,
}
fn main() {
let book = Book {
author: "George Orwell",
title: "1984",
};
println!("{} by {}", book.title, book.author);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/16_lifetimes/lifetimes2.rs | exercises/16_lifetimes/lifetimes2.rs | // Don't change this function.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
// TODO: Fix the compiler error by moving one line.
let string1 = String::from("long string is long");
let result;
{
let string2 = String::from("xyz");
result = longest(&string1, &string2);
}
println!("The longest string is '{result}'");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/00_intro/intro1.rs | exercises/00_intro/intro1.rs | // TODO: We sometimes encourage you to keep trying things on a given exercise
// even after you already figured it out. If you got everything working and feel
// ready for the next exercise, enter `n` in the terminal.
//
// The exercise file will be reloaded when you change one of the lines below!
// Try adding a new `println!` and check the updated output in the terminal.
fn main() {
println!(r#" Welcome to... "#);
println!(r#" _ _ _ "#);
println!(r#" _ __ _ _ ___| |_| (_)_ __ __ _ ___ "#);
println!(r#" | '__| | | / __| __| | | '_ \ / _` / __| "#);
println!(r#" | | | |_| \__ \ |_| | | | | | (_| \__ \ "#);
println!(r#" |_| \__,_|___/\__|_|_|_| |_|\__, |___/ "#);
println!(r#" |___/ "#);
println!();
println!("This exercise compiles successfully. The remaining exercises contain a compiler");
println!("or logic error. The central concept behind Rustlings is to fix these errors and");
println!("solve the exercises. Good luck!");
println!();
println!("The file of this exercise is `exercises/00_intro/intro1.rs`. Have a look!");
println!("The current exercise path will be always shown under the progress bar.");
println!("You can click on the path to open the exercise file in your editor.");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/00_intro/intro2.rs | exercises/00_intro/intro2.rs | fn main() {
// TODO: Fix the code to print "Hello world!".
printline!("Hello world!");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/21_macros/macros4.rs | exercises/21_macros/macros4.rs | // TODO: Fix the compiler error by adding one or two characters.
#[rustfmt::skip]
macro_rules! my_macro {
() => {
println!("Check out my macro!");
}
($val:expr) => {
println!("Look at this other macro: {}", $val);
}
}
fn main() {
my_macro!();
my_macro!(7777);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/21_macros/macros2.rs | exercises/21_macros/macros2.rs | fn main() {
my_macro!();
}
// TODO: Fix the compiler error by moving the whole definition of this macro.
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/21_macros/macros1.rs | exercises/21_macros/macros1.rs | macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
fn main() {
// TODO: Fix the macro call.
my_macro();
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/21_macros/macros3.rs | exercises/21_macros/macros3.rs | // TODO: Fix the compiler error without taking the macro definition out of this
// module.
mod macros {
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
}
fn main() {
my_macro!();
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/01_variables/variables5.rs | exercises/01_variables/variables5.rs | fn main() {
let number = "T-H-R-E-E"; // Don't change this line
println!("Spell a number: {number}");
// TODO: Fix the compiler error by changing the line below without renaming the variable.
number = 3;
println!("Number plus two is: {}", number + 2);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/01_variables/variables1.rs | exercises/01_variables/variables1.rs | fn main() {
// TODO: Add the missing keyword.
x = 5;
println!("x has the value {x}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/01_variables/variables2.rs | exercises/01_variables/variables2.rs | fn main() {
// TODO: Change the line below to fix the compiler error.
let x;
if x == 10 {
println!("x is ten!");
} else {
println!("x is not ten!");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/01_variables/variables6.rs | exercises/01_variables/variables6.rs | // TODO: Change the line below to fix the compiler error.
const NUMBER = 3;
fn main() {
println!("Number: {NUMBER}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/01_variables/variables3.rs | exercises/01_variables/variables3.rs | fn main() {
// TODO: Change the line below to fix the compiler error.
let x: i32;
println!("Number {x}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/01_variables/variables4.rs | exercises/01_variables/variables4.rs | // TODO: Fix the compiler error.
fn main() {
let x = 3;
println!("Number {x}");
x = 5; // Don't change this line
println!("Number {x}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/04_primitive_types/primitive_types3.rs | exercises/04_primitive_types/primitive_types3.rs | fn main() {
// TODO: Create an array called `a` with at least 100 elements in it.
// let a = ???
if a.len() >= 100 {
println!("Wow, that's a big array!");
} else {
println!("Meh, I eat arrays like that for breakfast.");
panic!("Array not big enough, more elements needed");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/04_primitive_types/primitive_types1.rs | exercises/04_primitive_types/primitive_types1.rs | // Booleans (`bool`)
fn main() {
let is_morning = true;
if is_morning {
println!("Good morning!");
}
// TODO: Define a boolean variable with the name `is_evening` before the `if` statement below.
// The value of the variable should be the negation (opposite) of `is_morning`.
// let …
if is_evening {
println!("Good evening!");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/04_primitive_types/primitive_types6.rs | exercises/04_primitive_types/primitive_types6.rs | fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
#[test]
fn indexing_tuple() {
let numbers = (1, 2, 3);
// TODO: Use a tuple index to access the second element of `numbers`
// and assign it to a variable called `second`.
// let second = ???;
assert_eq!(second, 2, "This is not the 2nd number in the tuple!");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/04_primitive_types/primitive_types2.rs | exercises/04_primitive_types/primitive_types2.rs | // Characters (`char`)
fn main() {
// Note the _single_ quotes, these are different from the double quotes
// you've been seeing around.
let my_first_initial = 'C';
if my_first_initial.is_alphabetic() {
println!("Alphabetical!");
} else if my_first_initial.is_numeric() {
println!("Numerical!");
} else {
println!("Neither alphabetic nor numeric!");
}
// TODO: Analogous to the example before, declare a variable called `your_character`
// below with your favorite character.
// Try a letter, try a digit (in single quotes), try a special character, try a character
// from a different language than your own, try an emoji 😉
// let your_character = '';
if your_character.is_alphabetic() {
println!("Alphabetical!");
} else if your_character.is_numeric() {
println!("Numerical!");
} else {
println!("Neither alphabetic nor numeric!");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/04_primitive_types/primitive_types4.rs | exercises/04_primitive_types/primitive_types4.rs | fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
#[test]
fn slice_out_of_array() {
let a = [1, 2, 3, 4, 5];
// TODO: Get a slice called `nice_slice` out of the array `a` so that the test passes.
// let nice_slice = ???
assert_eq!([2, 3, 4], nice_slice);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/04_primitive_types/primitive_types5.rs | exercises/04_primitive_types/primitive_types5.rs | fn main() {
let cat = ("Furry McFurson", 3.5);
// TODO: Destructure the `cat` tuple in one statement so that the println works.
// let /* your pattern here */ = cat;
println!("{name} is {age} years old");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/02_functions/functions5.rs | exercises/02_functions/functions5.rs | // TODO: Fix the function body without changing the signature.
fn square(num: i32) -> i32 {
num * num;
}
fn main() {
let answer = square(3);
println!("The square of 3 is {answer}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/02_functions/functions2.rs | exercises/02_functions/functions2.rs | // TODO: Add the missing type of the argument `num` after the colon `:`.
fn call_me(num:) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
fn main() {
call_me(3);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/02_functions/functions4.rs | exercises/02_functions/functions4.rs | // This store is having a sale where if the price is an even number, you get 10
// Rustbucks off, but if it's an odd number, it's 3 Rustbucks off.
// Don't worry about the function bodies themselves, we are only interested in
// the signatures for now.
fn is_even(num: i64) -> bool {
num % 2 == 0
}
// TODO: Fix the function signature.
fn sale_price(price: i64) -> {
if is_even(price) {
price - 10
} else {
price - 3
}
}
fn main() {
let original_price = 51;
println!("Your sale price is {}", sale_price(original_price));
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/02_functions/functions1.rs | exercises/02_functions/functions1.rs | // TODO: Add some function with the name `call_me` without arguments or a return value.
fn main() {
call_me(); // Don't change this line
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/02_functions/functions3.rs | exercises/02_functions/functions3.rs | fn call_me(num: u8) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
fn main() {
// TODO: Fix the function call.
call_me();
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/12_options/options3.rs | exercises/12_options/options3.rs | #[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let optional_point = Some(Point { x: 100, y: 200 });
// TODO: Fix the compiler error by adding something to this match statement.
match optional_point {
Some(p) => println!("Coordinates are {},{}", p.x, p.y),
_ => panic!("No match!"),
}
println!("{optional_point:?}"); // Don't change this line.
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/12_options/options1.rs | exercises/12_options/options1.rs | // This function returns how much ice cream there is left in the fridge.
// If it's before 22:00 (24-hour system), then 5 scoops are left. At 22:00,
// someone eats it all, so no ice cream is left (value 0). Return `None` if
// `hour_of_day` is higher than 23.
fn maybe_ice_cream(hour_of_day: u16) -> Option<u16> {
// TODO: Complete the function body.
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn raw_value() {
// TODO: Fix this test. How do you get the value contained in the
// Option?
let ice_creams = maybe_ice_cream(12);
assert_eq!(ice_creams, 5); // Don't change this line.
}
#[test]
fn check_ice_cream() {
assert_eq!(maybe_ice_cream(0), Some(5));
assert_eq!(maybe_ice_cream(9), Some(5));
assert_eq!(maybe_ice_cream(18), Some(5));
assert_eq!(maybe_ice_cream(22), Some(0));
assert_eq!(maybe_ice_cream(23), Some(0));
assert_eq!(maybe_ice_cream(24), None);
assert_eq!(maybe_ice_cream(25), None);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/12_options/options2.rs | exercises/12_options/options2.rs | fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
#[test]
fn simple_option() {
let target = "rustlings";
let optional_target = Some(target);
// TODO: Make this an if-let statement whose value is `Some`.
word = optional_target {
assert_eq!(word, target);
}
}
#[test]
fn layered_option() {
let range = 10;
let mut optional_integers: Vec<Option<i8>> = vec![None];
for i in 1..=range {
optional_integers.push(Some(i));
}
let mut cursor = range;
// TODO: Make this a while-let statement. Remember that `Vec::pop()`
// adds another layer of `Option`. You can do nested pattern matching
// in if-let and while-let statements.
integer = optional_integers.pop() {
assert_eq!(integer, cursor);
cursor -= 1;
}
assert_eq!(cursor, 0);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/06_move_semantics/move_semantics4.rs | exercises/06_move_semantics/move_semantics4.rs | fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
// TODO: Fix the compiler errors only by reordering the lines in the test.
// Don't add, change or remove any line.
#[test]
fn move_semantics4() {
let mut x = Vec::new();
let y = &mut x;
let z = &mut x;
y.push(42);
z.push(13);
assert_eq!(x, [42, 13]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/06_move_semantics/move_semantics3.rs | exercises/06_move_semantics/move_semantics3.rs | // TODO: Fix the compiler error in the function without adding any new line.
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
vec.push(88);
vec
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn move_semantics3() {
let vec0 = vec![22, 44, 66];
let vec1 = fill_vec(vec0);
assert_eq!(vec1, [22, 44, 66, 88]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/06_move_semantics/move_semantics5.rs | exercises/06_move_semantics/move_semantics5.rs | #![allow(clippy::ptr_arg)]
// TODO: Fix the compiler errors without changing anything except adding or
// removing references (the character `&`).
// Shouldn't take ownership
fn get_char(data: String) -> char {
data.chars().last().unwrap()
}
// Should take ownership
fn string_uppercase(mut data: &String) {
data = data.to_uppercase();
println!("{data}");
}
fn main() {
let data = "Rust is great!".to_string();
get_char(data);
string_uppercase(&data);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/06_move_semantics/move_semantics2.rs | exercises/06_move_semantics/move_semantics2.rs | fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
vec.push(88);
vec
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
// TODO: Make both vectors `vec0` and `vec1` accessible at the same time to
// fix the compiler error in the test.
#[test]
fn move_semantics2() {
let vec0 = vec![22, 44, 66];
let vec1 = fill_vec(vec0);
assert_eq!(vec0, [22, 44, 66]);
assert_eq!(vec1, [22, 44, 66, 88]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/06_move_semantics/move_semantics1.rs | exercises/06_move_semantics/move_semantics1.rs | // TODO: Fix the compiler error in this function.
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let vec = vec;
vec.push(88);
vec
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn move_semantics1() {
let vec0 = vec![22, 44, 66];
let vec1 = fill_vec(vec0);
assert_eq!(vec1, vec![22, 44, 66, 88]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/rustlings-macros/src/lib.rs | rustlings-macros/src/lib.rs | use proc_macro::TokenStream;
use quote::quote;
use serde::Deserialize;
#[derive(Deserialize)]
struct ExerciseInfo {
name: String,
dir: String,
}
#[derive(Deserialize)]
struct InfoFile {
exercises: Vec<ExerciseInfo>,
}
#[proc_macro]
pub fn include_files(_: TokenStream) -> TokenStream {
let info_file = include_str!("../info.toml");
let exercises = toml::de::from_str::<InfoFile>(info_file)
.expect("Failed to parse `info.toml`")
.exercises;
let exercise_files = exercises
.iter()
.map(|exercise| format!("../exercises/{}/{}.rs", exercise.dir, exercise.name));
let solution_files = exercises
.iter()
.map(|exercise| format!("../solutions/{}/{}.rs", exercise.dir, exercise.name));
let mut dirs = Vec::with_capacity(32);
let mut dir_inds = vec![0; exercises.len()];
for (exercise, dir_ind) in exercises.iter().zip(&mut dir_inds) {
// The directory is often the last one inserted.
if let Some(ind) = dirs.iter().rev().position(|dir| *dir == exercise.dir) {
*dir_ind = dirs.len() - 1 - ind;
continue;
}
dirs.push(exercise.dir.as_str());
*dir_ind = dirs.len() - 1;
}
let readmes = dirs
.iter()
.map(|dir| format!("../exercises/{dir}/README.md"));
quote! {
EmbeddedFiles {
info_file: #info_file,
exercise_files: &[#(ExerciseFiles { exercise: include_bytes!(#exercise_files), solution: include_bytes!(#solution_files), dir_ind: #dir_inds }),*],
exercise_dirs: &[#(ExerciseDir { name: #dirs, readme: include_bytes!(#readmes) }),*]
}
}
.into()
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/paging.rs | src/paging.rs | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum PagingMode {
Always,
QuitIfOneScreen,
#[default]
Never,
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/config.rs | src/config.rs | use crate::line_range::{HighlightedLineRanges, LineRanges};
use crate::nonprintable_notation::{BinaryBehavior, NonprintableNotation};
#[cfg(feature = "paging")]
use crate::paging::PagingMode;
use crate::style::StyleComponents;
use crate::syntax_mapping::SyntaxMapping;
use crate::wrapping::WrappingMode;
use crate::StripAnsiMode;
#[derive(Debug, Clone)]
pub enum VisibleLines {
/// Show all lines which are included in the line ranges
Ranges(LineRanges),
#[cfg(feature = "git")]
/// Only show lines surrounding added/deleted/modified lines
DiffContext(usize),
}
impl VisibleLines {
pub fn diff_mode(&self) -> bool {
match self {
Self::Ranges(_) => false,
#[cfg(feature = "git")]
Self::DiffContext(_) => true,
}
}
}
impl Default for VisibleLines {
fn default() -> Self {
VisibleLines::Ranges(LineRanges::default())
}
}
#[derive(Debug, Clone, Default)]
pub struct Config<'a> {
/// The explicitly configured language, if any
pub language: Option<&'a str>,
/// Whether or not to show/replace non-printable characters like space, tab and newline.
pub show_nonprintable: bool,
/// The configured notation for non-printable characters
pub nonprintable_notation: NonprintableNotation,
/// How to treat binary content
pub binary: BinaryBehavior,
/// The character width of the terminal
pub term_width: usize,
/// The width of tab characters.
/// Currently, a value of 0 will cause tabs to be passed through without expanding them.
pub tab_width: usize,
/// Whether or not to simply loop through all input (`cat` mode)
pub loop_through: bool,
/// Whether or not the output should be colorized
pub colored_output: bool,
/// Whether or not the output terminal supports true color
pub true_color: bool,
/// Style elements (grid, line numbers, ...)
pub style_components: StyleComponents,
/// If and how text should be wrapped
pub wrapping_mode: WrappingMode,
/// Pager or STDOUT
#[cfg(feature = "paging")]
pub paging_mode: PagingMode,
/// Specifies which lines should be printed
pub visible_lines: VisibleLines,
/// The syntax highlighting theme
pub theme: String,
/// File extension/name mappings
pub syntax_mapping: SyntaxMapping<'a>,
/// Command to start the pager
pub pager: Option<&'a str>,
/// Whether or not to use ANSI italics
pub use_italic_text: bool,
/// Ranges of lines which should be highlighted with a special background color
pub highlighted_lines: HighlightedLineRanges,
/// Whether or not to allow custom assets. If this is false or if custom assets (a.k.a.
/// cached assets) are not available, assets from the binary will be used instead.
pub use_custom_assets: bool,
// Whether or not to use $LESSOPEN if set
#[cfg(feature = "lessopen")]
pub use_lessopen: bool,
// Weather or not to set terminal title when using a pager
pub set_terminal_title: bool,
/// The maximum number of consecutive empty lines to display
pub squeeze_lines: Option<usize>,
// Weather or not to set terminal title when using a pager
pub strip_ansi: StripAnsiMode,
}
#[cfg(all(feature = "minimal-application", feature = "paging"))]
pub fn get_pager_executable(config_pager: Option<&str>) -> Option<String> {
crate::pager::get_pager(config_pager)
.ok()
.flatten()
.and_then(|pager| {
if pager.kind != crate::pager::PagerKind::Builtin {
Some(pager.bin)
} else {
None
}
})
}
#[test]
fn default_config_should_include_all_lines() {
use crate::line_range::MaxBufferedLineNumber;
use crate::line_range::RangeCheckResult;
assert_eq!(
LineRanges::default().check(17, MaxBufferedLineNumber::Tentative(17)),
RangeCheckResult::InRange
);
}
#[test]
fn default_config_should_highlight_no_lines() {
use crate::line_range::MaxBufferedLineNumber;
use crate::line_range::RangeCheckResult;
assert_ne!(
Config::default()
.highlighted_lines
.0
.check(17, MaxBufferedLineNumber::Tentative(17)),
RangeCheckResult::InRange
);
}
#[cfg(all(feature = "minimal-application", feature = "paging"))]
#[test]
fn get_pager_executable_with_config_pager_less() {
let result = get_pager_executable(Some("less"));
assert_eq!(result, Some("less".to_string()));
}
#[cfg(all(feature = "minimal-application", feature = "paging"))]
#[test]
fn get_pager_executable_with_config_pager_builtin() {
let result = get_pager_executable(Some("builtin"));
assert_eq!(result, None);
}
#[cfg(all(feature = "minimal-application", feature = "paging"))]
#[test]
fn get_pager_executable_with_config_pager_more() {
let result = get_pager_executable(Some("more"));
assert_eq!(result, Some("more".to_string()));
}
#[cfg(all(feature = "minimal-application", feature = "paging"))]
#[test]
fn get_pager_executable_with_bat_pager() {
std::env::set_var("BAT_PAGER", "most");
let result = get_pager_executable(None);
assert_eq!(result, Some("most".to_string()));
std::env::remove_var("BAT_PAGER");
}
#[cfg(all(feature = "minimal-application", feature = "paging"))]
#[test]
fn get_pager_executable_with_pager_more_switches_to_less() {
std::env::set_var("PAGER", "more");
let result = get_pager_executable(None);
assert_eq!(result, Some("less".to_string()));
std::env::remove_var("PAGER");
}
#[cfg(all(feature = "minimal-application", feature = "paging"))]
#[test]
fn get_pager_executable_default() {
// Ensure no env vars
std::env::remove_var("BAT_PAGER");
std::env::remove_var("PAGER");
let result = get_pager_executable(None);
assert_eq!(result, Some("less".to_string()));
}
#[cfg(all(feature = "minimal-application", feature = "paging"))]
#[test]
fn get_pager_executable_name_ignoring_arguments() {
let result = get_pager_executable(Some("foo --bar"));
assert_eq!(result, Some("foo".to_string()));
}
#[cfg(all(feature = "minimal-application", feature = "paging"))]
#[test]
fn get_pager_executable_name_ignoring_path() {
let result = get_pager_executable(Some("/bin/foo test"));
assert_eq!(result, Some("/bin/foo".to_string()));
}
#[cfg(all(feature = "minimal-application", feature = "paging"))]
#[test]
fn get_pager_executable_invalid_command() {
let result = get_pager_executable(Some("invalid ' command"));
assert_eq!(result, None);
}
#[cfg(all(feature = "minimal-application", feature = "paging"))]
#[test]
fn get_pager_executable_empty_config() {
let result = get_pager_executable(Some(""));
assert_eq!(result, None);
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/nonprintable_notation.rs | src/nonprintable_notation.rs | /// How to print non-printable characters with
/// [crate::config::Config::show_nonprintable]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NonprintableNotation {
/// Use caret notation (^G, ^J, ^@, ..)
Caret,
/// Use unicode notation (␇, ␊, ␀, ..)
#[default]
Unicode,
}
/// How to treat binary content
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BinaryBehavior {
/// Do not print any binary content
#[default]
NoPrinting,
/// Treat binary content as normal text
AsText,
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/preprocessor.rs | src/preprocessor.rs | use std::fmt::Write;
use crate::{
nonprintable_notation::NonprintableNotation,
vscreen::{EscapeSequenceOffsets, EscapeSequenceOffsetsIterator},
};
/// Expand tabs like an ANSI-enabled expand(1).
pub fn expand_tabs(line: &str, width: usize, cursor: &mut usize) -> String {
let mut buffer = String::with_capacity(line.len() * 2);
for seq in EscapeSequenceOffsetsIterator::new(line) {
match seq {
EscapeSequenceOffsets::Text { .. } => {
let mut text = &line[seq.index_of_start()..seq.index_past_end()];
while let Some(index) = text.find('\t') {
// Add previous text.
if index > 0 {
*cursor += index;
buffer.push_str(&text[0..index]);
}
// Add tab.
let spaces = width - (*cursor % width);
*cursor += spaces;
buffer.push_str(&" ".repeat(spaces));
// Next.
text = &text[index + 1..text.len()];
}
*cursor += text.len();
buffer.push_str(text);
}
_ => {
// Copy the ANSI escape sequence.
buffer.push_str(&line[seq.index_of_start()..seq.index_past_end()])
}
}
}
buffer
}
fn try_parse_utf8_char(input: &[u8]) -> Option<(char, usize)> {
let str_from_utf8 = |seq| std::str::from_utf8(seq).ok();
let decoded = input
.get(0..1)
.and_then(str_from_utf8)
.map(|c| (c, 1))
.or_else(|| input.get(0..2).and_then(str_from_utf8).map(|c| (c, 2)))
.or_else(|| input.get(0..3).and_then(str_from_utf8).map(|c| (c, 3)))
.or_else(|| input.get(0..4).and_then(str_from_utf8).map(|c| (c, 4)));
decoded.map(|(seq, n)| (seq.chars().next().unwrap(), n))
}
pub fn replace_nonprintable(
input: &[u8],
tab_width: usize,
nonprintable_notation: NonprintableNotation,
) -> String {
let mut output = String::new();
let tab_width = if tab_width == 0 { 4 } else { tab_width };
let mut idx = 0;
let mut line_idx = 0;
let len = input.len();
while idx < len {
if let Some((chr, skip_ahead)) = try_parse_utf8_char(&input[idx..]) {
idx += skip_ahead;
line_idx += 1;
match chr {
// space
' ' => output.push('·'),
// tab
'\t' => {
let tab_stop = tab_width - ((line_idx - 1) % tab_width);
line_idx = 0;
if tab_stop == 1 {
output.push('↹');
} else {
output.push('├');
output.push_str(&"─".repeat(tab_stop - 2));
output.push('┤');
}
}
// line feed
'\x0A' => {
output.push_str(match nonprintable_notation {
NonprintableNotation::Caret => "^J\x0A",
NonprintableNotation::Unicode => "␊\x0A",
});
line_idx = 0;
}
// ASCII control characters
'\x00'..='\x1F' => {
let c = u32::from(chr);
match nonprintable_notation {
NonprintableNotation::Caret => {
let caret_character = char::from_u32(0x40 + c).unwrap();
write!(output, "^{caret_character}").ok();
}
NonprintableNotation::Unicode => {
let replacement_symbol = char::from_u32(0x2400 + c).unwrap();
output.push(replacement_symbol)
}
}
}
// delete
'\x7F' => match nonprintable_notation {
NonprintableNotation::Caret => output.push_str("^?"),
NonprintableNotation::Unicode => output.push('\u{2421}'),
},
// printable ASCII
c if c.is_ascii_alphanumeric()
|| c.is_ascii_punctuation()
|| c.is_ascii_graphic() =>
{
output.push(c)
}
// everything else
c => output.push_str(&c.escape_unicode().collect::<String>()),
}
} else {
write!(output, "\\x{:02X}", input[idx]).ok();
idx += 1;
}
}
output
}
/// Strips ANSI escape sequences from the input.
pub fn strip_ansi(line: &str) -> String {
let mut buffer = String::with_capacity(line.len());
for seq in EscapeSequenceOffsetsIterator::new(line) {
if let EscapeSequenceOffsets::Text { .. } = seq {
buffer.push_str(&line[seq.index_of_start()..seq.index_past_end()]);
}
}
buffer
}
/// Strips overstrike sequences (backspace formatting) from input.
///
/// Overstrike formatting is used by man pages and some help output:
/// - Bold: `X\x08X` (character, backspace, same character)
/// - Underline: `_\x08X` (underscore, backspace, character)
///
/// This function removes these sequences, keeping only the visible character.
/// `first_backspace` is the position of the first backspace in the line.
pub fn strip_overstrike(line: &str, first_backspace: usize) -> String {
let mut output = String::with_capacity(line.len());
output.push_str(&line[..first_backspace]);
output.pop();
let mut remaining = &line[first_backspace + 1..];
loop {
if let Some(pos) = remaining.find('\x08') {
output.push_str(&remaining[..pos]);
output.pop();
remaining = &remaining[pos + 1..];
} else {
output.push_str(remaining);
break;
}
}
output
}
#[derive(Debug, PartialEq, Clone, Copy, Default)]
pub enum StripAnsiMode {
#[default]
Never,
Always,
Auto,
}
#[test]
fn test_try_parse_utf8_char() {
assert_eq!(try_parse_utf8_char(&[0x20]), Some((' ', 1)));
assert_eq!(try_parse_utf8_char(&[0x20, 0x20]), Some((' ', 1)));
assert_eq!(try_parse_utf8_char(&[0x20, 0xef]), Some((' ', 1)));
assert_eq!(try_parse_utf8_char(&[0x00]), Some(('\x00', 1)));
assert_eq!(try_parse_utf8_char(&[0x1b]), Some(('\x1b', 1)));
assert_eq!(try_parse_utf8_char(&[0xc3, 0xa4]), Some(('ä', 2)));
assert_eq!(try_parse_utf8_char(&[0xc3, 0xa4, 0xef]), Some(('ä', 2)));
assert_eq!(try_parse_utf8_char(&[0xc3, 0xa4, 0x20]), Some(('ä', 2)));
assert_eq!(try_parse_utf8_char(&[0xe2, 0x82, 0xac]), Some(('€', 3)));
assert_eq!(
try_parse_utf8_char(&[0xe2, 0x82, 0xac, 0xef]),
Some(('€', 3))
);
assert_eq!(
try_parse_utf8_char(&[0xe2, 0x82, 0xac, 0x20]),
Some(('€', 3))
);
assert_eq!(try_parse_utf8_char(&[0xe2, 0x88, 0xb0]), Some(('∰', 3)));
assert_eq!(
try_parse_utf8_char(&[0xf0, 0x9f, 0x8c, 0x82]),
Some(('🌂', 4))
);
assert_eq!(
try_parse_utf8_char(&[0xf0, 0x9f, 0x8c, 0x82, 0xef]),
Some(('🌂', 4))
);
assert_eq!(
try_parse_utf8_char(&[0xf0, 0x9f, 0x8c, 0x82, 0x20]),
Some(('🌂', 4))
);
assert_eq!(try_parse_utf8_char(&[]), None);
assert_eq!(try_parse_utf8_char(&[0xef]), None);
assert_eq!(try_parse_utf8_char(&[0xef, 0x20]), None);
assert_eq!(try_parse_utf8_char(&[0xf0, 0xf0]), None);
}
#[test]
fn test_strip_ansi() {
// The sequence detection is covered by the tests in the vscreen module.
assert_eq!(strip_ansi("no ansi"), "no ansi");
assert_eq!(strip_ansi("\x1B[33mone"), "one");
assert_eq!(
strip_ansi("\x1B]1\x07multiple\x1B[J sequences"),
"multiple sequences"
);
}
#[test]
fn test_strip_overstrike() {
// Bold: X\x08X (same char repeated)
assert_eq!(strip_overstrike("H\x08Hello", 1), "Hello");
// Underline: _\x08X (underscore before char)
assert_eq!(strip_overstrike("_\x08Hello", 1), "Hello");
// Multiple overstrike sequences
assert_eq!(strip_overstrike("B\x08Bo\x08ol\x08ld\x08d", 1), "Bold");
// Backspace at start of line (nothing to pop)
assert_eq!(strip_overstrike("\x08Hello", 0), "Hello");
// Multiple consecutive backspaces
assert_eq!(strip_overstrike("ABC\x08\x08\x08XYZ", 3), "XYZ");
// Unicode with overstrike
assert_eq!(strip_overstrike("ä\x08äöü", 2), "äöü");
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/decorations.rs | src/decorations.rs | #[cfg(feature = "git")]
use crate::diff::LineChange;
use crate::printer::{Colors, InteractivePrinter};
use nu_ansi_term::Style;
#[derive(Debug, Clone)]
pub(crate) struct DecorationText {
pub width: usize,
pub text: String,
}
pub(crate) trait Decoration {
fn generate(
&self,
line_number: usize,
continuation: bool,
printer: &InteractivePrinter,
) -> DecorationText;
fn width(&self) -> usize;
}
pub(crate) struct LineNumberDecoration {
color: Style,
cached_wrap: DecorationText,
cached_wrap_invalid_at: usize,
}
impl LineNumberDecoration {
pub(crate) fn new(colors: &Colors) -> Self {
LineNumberDecoration {
color: colors.line_number,
cached_wrap_invalid_at: 10000,
cached_wrap: DecorationText {
text: colors.line_number.paint(" ".repeat(4)).to_string(),
width: 4,
},
}
}
}
impl Decoration for LineNumberDecoration {
fn generate(
&self,
line_number: usize,
continuation: bool,
_printer: &InteractivePrinter,
) -> DecorationText {
if continuation {
if line_number >= self.cached_wrap_invalid_at {
let new_width = self.cached_wrap.width + 1;
return DecorationText {
text: self.color.paint(" ".repeat(new_width)).to_string(),
width: new_width,
};
}
self.cached_wrap.clone()
} else {
let plain: String = format!("{line_number:4}");
DecorationText {
width: plain.len(),
text: self.color.paint(plain).to_string(),
}
}
}
fn width(&self) -> usize {
4
}
}
#[cfg(feature = "git")]
pub(crate) struct LineChangesDecoration {
cached_none: DecorationText,
cached_added: DecorationText,
cached_removed_above: DecorationText,
cached_removed_below: DecorationText,
cached_modified: DecorationText,
}
#[cfg(feature = "git")]
impl LineChangesDecoration {
#[inline]
fn generate_cached(style: Style, text: &str) -> DecorationText {
DecorationText {
text: style.paint(text).to_string(),
width: text.chars().count(),
}
}
pub(crate) fn new(colors: &Colors) -> Self {
LineChangesDecoration {
cached_none: Self::generate_cached(Style::default(), " "),
cached_added: Self::generate_cached(colors.git_added, "+"),
cached_removed_above: Self::generate_cached(colors.git_removed, "‾"),
cached_removed_below: Self::generate_cached(colors.git_removed, "_"),
cached_modified: Self::generate_cached(colors.git_modified, "~"),
}
}
}
#[cfg(feature = "git")]
impl Decoration for LineChangesDecoration {
fn generate(
&self,
line_number: usize,
continuation: bool,
printer: &InteractivePrinter,
) -> DecorationText {
if !continuation {
if let Some(ref changes) = printer.line_changes {
return match changes.get(&(line_number as u32)) {
Some(&LineChange::Added) => self.cached_added.clone(),
Some(&LineChange::RemovedAbove) => self.cached_removed_above.clone(),
Some(&LineChange::RemovedBelow) => self.cached_removed_below.clone(),
Some(&LineChange::Modified) => self.cached_modified.clone(),
_ => self.cached_none.clone(),
};
}
}
self.cached_none.clone()
}
fn width(&self) -> usize {
self.cached_none.width
}
}
pub(crate) struct GridBorderDecoration {
cached: DecorationText,
}
impl GridBorderDecoration {
pub(crate) fn new(colors: &Colors) -> Self {
GridBorderDecoration {
cached: DecorationText {
text: colors.grid.paint("│").to_string(),
width: 1,
},
}
}
}
impl Decoration for GridBorderDecoration {
fn generate(
&self,
_line_number: usize,
_continuation: bool,
_printer: &InteractivePrinter,
) -> DecorationText {
self.cached.clone()
}
fn width(&self) -> usize {
self.cached.width
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/lib.rs | src/lib.rs | //! `bat` is a library to print syntax highlighted content.
//!
//! The main struct of this crate is `PrettyPrinter` which can be used to
//! configure and run the syntax highlighting.
//!
//! If you need more control, you can also use the structs in the submodules
//! (start with `controller::Controller`), but note that the API of these
//! internal modules is much more likely to change. Some or all of these
//! modules might be removed in the future.
//!
//! "Hello world" example:
//! ```
//! use bat::PrettyPrinter;
//!
//! PrettyPrinter::new()
//! .input_from_bytes(b"<span style=\"color: #ff00cc\">Hello world!</span>\n")
//! .language("html")
//! .print()
//! .unwrap();
//! ```
#![deny(unsafe_code)]
mod macros;
pub mod assets;
pub mod assets_metadata {
pub use super::assets::assets_metadata::*;
}
pub mod config;
pub mod controller;
mod decorations;
mod diff;
pub mod error;
pub mod input;
mod less;
#[cfg(feature = "lessopen")]
mod lessopen;
pub mod line_range;
pub(crate) mod nonprintable_notation;
pub mod output;
#[cfg(feature = "paging")]
mod pager;
#[cfg(feature = "paging")]
pub(crate) mod paging;
mod preprocessor;
mod pretty_printer;
pub(crate) mod printer;
pub mod style;
pub(crate) mod syntax_mapping;
mod terminal;
pub mod theme;
mod vscreen;
pub(crate) mod wrapping;
pub use nonprintable_notation::{BinaryBehavior, NonprintableNotation};
pub use preprocessor::StripAnsiMode;
pub use pretty_printer::{Input, PrettyPrinter, Syntax};
pub use syntax_mapping::{MappingTarget, SyntaxMapping};
pub use wrapping::WrappingMode;
#[cfg(feature = "paging")]
pub use paging::PagingMode;
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/theme.rs | src/theme.rs | //! Utilities for choosing an appropriate theme for syntax highlighting.
use std::convert::Infallible;
use std::fmt;
use std::io::IsTerminal as _;
use std::str::FromStr;
/// Environment variable names.
pub mod env {
/// See [`crate::theme::ThemeOptions::theme`].
pub const BAT_THEME: &str = "BAT_THEME";
/// See [`crate::theme::ThemeOptions::theme_dark`].
pub const BAT_THEME_DARK: &str = "BAT_THEME_DARK";
/// See [`crate::theme::ThemeOptions::theme_light`].
pub const BAT_THEME_LIGHT: &str = "BAT_THEME_LIGHT";
}
/// Chooses an appropriate theme or falls back to a default theme
/// based on the user-provided options and the color scheme of the terminal.
///
/// Intentionally returns a [`ThemeResult`] instead of a simple string so
/// that downstream consumers such as `delta` can easily apply their own
/// default theme and can use the detected color scheme elsewhere.
pub fn theme(options: ThemeOptions) -> ThemeResult {
theme_impl(options, &TerminalColorSchemeDetector)
}
/// The default theme, suitable for the given color scheme.
/// Use [`theme`] if you want to automatically detect the color scheme from the terminal.
pub const fn default_theme(color_scheme: ColorScheme) -> &'static str {
match color_scheme {
ColorScheme::Dark => "Monokai Extended",
ColorScheme::Light => "Monokai Extended Light",
}
}
/// Detects the color scheme from the terminal.
pub fn color_scheme(when: DetectColorScheme) -> Option<ColorScheme> {
color_scheme_impl(when, &TerminalColorSchemeDetector)
}
/// Options for configuring the theme used for syntax highlighting.
/// Used together with [`theme`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ThemeOptions {
/// Configures how the theme is chosen. If set to a [`ThemePreference::Fixed`] value,
/// then the given theme is used regardless of the terminal's background color.
/// This corresponds with the `BAT_THEME` environment variable and the `--theme` option.
pub theme: ThemePreference,
/// The theme to use in case the terminal uses a dark background with light text.
/// This corresponds with the `BAT_THEME_DARK` environment variable and the `--theme-dark` option.
pub theme_dark: Option<ThemeName>,
/// The theme to use in case the terminal uses a light background with dark text.
/// This corresponds with the `BAT_THEME_LIGHT` environment variable and the `--theme-light` option.
pub theme_light: Option<ThemeName>,
}
/// What theme should `bat` use?
///
/// The easiest way to construct this is from a string:
/// ```
/// # use bat::theme::{ThemePreference, DetectColorScheme};
/// let preference = ThemePreference::new("auto:system");
/// assert_eq!(ThemePreference::Auto(DetectColorScheme::System), preference);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ThemePreference {
/// Choose between [`ThemeOptions::theme_dark`] and [`ThemeOptions::theme_light`]
/// based on the terminal's color scheme.
Auto(DetectColorScheme),
/// Always use the same theme regardless of the terminal's color scheme.
Fixed(ThemeName),
/// Use a dark theme.
Dark,
/// Use a light theme.
Light,
}
impl Default for ThemePreference {
fn default() -> Self {
ThemePreference::Auto(Default::default())
}
}
impl ThemePreference {
/// Creates a theme preference from a string.
pub fn new(s: impl Into<String>) -> Self {
use ThemePreference::*;
let s = s.into();
match s.as_str() {
"auto" => Auto(Default::default()),
"auto:always" => Auto(DetectColorScheme::Always),
"auto:system" => Auto(DetectColorScheme::System),
"dark" => Dark,
"light" => Light,
_ => Fixed(ThemeName::new(s)),
}
}
}
impl FromStr for ThemePreference {
type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(ThemePreference::new(s))
}
}
impl fmt::Display for ThemePreference {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use ThemePreference::*;
match self {
Auto(DetectColorScheme::Auto) => f.write_str("auto"),
Auto(DetectColorScheme::Always) => f.write_str("auto:always"),
Auto(DetectColorScheme::System) => f.write_str("auto:system"),
Fixed(theme) => theme.fmt(f),
Dark => f.write_str("dark"),
Light => f.write_str("light"),
}
}
}
/// The name of a theme or the default theme.
///
/// ```
/// # use bat::theme::ThemeName;
/// assert_eq!(ThemeName::Default, ThemeName::new("default"));
/// assert_eq!(ThemeName::Named("example".to_string()), ThemeName::new("example"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ThemeName {
Named(String),
Default,
}
impl ThemeName {
/// Creates a theme name from a string.
pub fn new(s: impl Into<String>) -> Self {
let s = s.into();
if s == "default" {
ThemeName::Default
} else {
ThemeName::Named(s)
}
}
}
impl FromStr for ThemeName {
type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(ThemeName::new(s))
}
}
impl fmt::Display for ThemeName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ThemeName::Named(t) => f.write_str(t),
ThemeName::Default => f.write_str("default"),
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DetectColorScheme {
/// Only query the terminal for its colors when appropriate (i.e. when the output is not redirected).
#[default]
Auto,
/// Always query the terminal for its colors.
Always,
/// Detect the system-wide dark/light preference (macOS only).
System,
}
/// The color scheme used to pick a fitting theme. Defaults to [`ColorScheme::Dark`].
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ColorScheme {
#[default]
Dark,
Light,
}
/// The resolved theme and the color scheme as determined from
/// the terminal, OS or fallback.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThemeResult {
/// The theme selected according to the [`ThemeOptions`].
pub theme: ThemeName,
/// Either the user's chosen color scheme, the terminal's color scheme, the OS's
/// color scheme or `None` if the color scheme was not detected because the user chose a fixed theme.
pub color_scheme: Option<ColorScheme>,
}
impl fmt::Display for ThemeResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.theme {
ThemeName::Named(name) => f.write_str(name),
ThemeName::Default => f.write_str(default_theme(self.color_scheme.unwrap_or_default())),
}
}
}
fn theme_impl(options: ThemeOptions, detector: &dyn ColorSchemeDetector) -> ThemeResult {
// Implementation note: This function is mostly pure (i.e. it has no side effects) for the sake of testing.
// All the side effects (e.g. querying the terminal for its colors) are performed in the detector.
match options.theme {
ThemePreference::Fixed(theme) => ThemeResult {
theme,
color_scheme: None,
},
ThemePreference::Dark => choose_theme_opt(Some(ColorScheme::Dark), options),
ThemePreference::Light => choose_theme_opt(Some(ColorScheme::Light), options),
ThemePreference::Auto(when) => choose_theme_opt(color_scheme_impl(when, detector), options),
}
}
fn choose_theme_opt(color_scheme: Option<ColorScheme>, options: ThemeOptions) -> ThemeResult {
ThemeResult {
color_scheme,
theme: color_scheme
.and_then(|c| choose_theme(options, c))
.unwrap_or(ThemeName::Default),
}
}
fn choose_theme(options: ThemeOptions, color_scheme: ColorScheme) -> Option<ThemeName> {
match color_scheme {
ColorScheme::Dark => options.theme_dark,
ColorScheme::Light => options.theme_light,
}
}
fn color_scheme_impl(
when: DetectColorScheme,
detector: &dyn ColorSchemeDetector,
) -> Option<ColorScheme> {
let should_detect = match when {
DetectColorScheme::Auto => detector.should_detect(),
DetectColorScheme::Always => true,
DetectColorScheme::System => return color_scheme_from_system(),
};
should_detect.then(|| detector.detect()).flatten()
}
trait ColorSchemeDetector {
fn should_detect(&self) -> bool;
fn detect(&self) -> Option<ColorScheme>;
}
struct TerminalColorSchemeDetector;
impl ColorSchemeDetector for TerminalColorSchemeDetector {
fn should_detect(&self) -> bool {
// Querying the terminal for its colors via OSC 10 / OSC 11 requires "exclusive" access
// since we read/write from the terminal and enable/disable raw mode.
// This causes race conditions with pagers such as less when they are attached to the
// same terminal as us.
//
// This is usually only an issue when the output is manually piped to a pager.
// For example: `bat Cargo.toml | less`.
// Otherwise, if we start the pager ourselves, then there's no race condition
// since the pager is started *after* the color is detected.
std::io::stdout().is_terminal()
}
fn detect(&self) -> Option<ColorScheme> {
use terminal_colorsaurus::{theme_mode, QueryOptions, ThemeMode};
match theme_mode(QueryOptions::default()).ok()? {
ThemeMode::Dark => Some(ColorScheme::Dark),
ThemeMode::Light => Some(ColorScheme::Light),
}
}
}
#[cfg(not(target_os = "macos"))]
fn color_scheme_from_system() -> Option<ColorScheme> {
crate::bat_warning!(
"Theme 'auto:system' is only supported on macOS, \
using default."
);
None
}
#[cfg(target_os = "macos")]
fn color_scheme_from_system() -> Option<ColorScheme> {
const PREFERENCES_FILE: &str = "Library/Preferences/.GlobalPreferences.plist";
const STYLE_KEY: &str = "AppleInterfaceStyle";
let preferences_file = std::env::home_dir()
.map(|home| home.join(PREFERENCES_FILE))
.expect("Could not get home directory");
match plist::Value::from_file(preferences_file).map(|file| file.into_dictionary()) {
Ok(Some(preferences)) => match preferences.get(STYLE_KEY).and_then(|val| val.as_string()) {
Some("Dark") => Some(ColorScheme::Dark),
// If the key does not exist, then light theme is currently in use.
Some(_) | None => Some(ColorScheme::Light),
},
// Unreachable, in theory. All macOS users have a home directory and preferences file setup.
Ok(None) | Err(_) => None,
}
}
#[cfg(test)]
impl ColorSchemeDetector for Option<ColorScheme> {
fn should_detect(&self) -> bool {
true
}
fn detect(&self) -> Option<ColorScheme> {
*self
}
}
#[cfg(test)]
mod tests {
use super::ColorScheme::*;
use super::*;
use std::cell::Cell;
use std::iter;
mod color_scheme_detection {
use super::*;
#[test]
fn not_called_for_dark_or_light() {
for theme in [ThemePreference::Dark, ThemePreference::Light] {
let detector = DetectorStub::should_detect(Some(Dark));
let options = ThemeOptions {
theme,
..Default::default()
};
_ = theme_impl(options, &detector);
assert!(!detector.was_called.get());
}
}
#[test]
fn called_for_always() {
let detectors = [
DetectorStub::should_detect(Some(Dark)),
DetectorStub::should_not_detect(),
];
for detector in detectors {
let options = ThemeOptions {
theme: ThemePreference::Auto(DetectColorScheme::Always),
..Default::default()
};
_ = theme_impl(options, &detector);
assert!(detector.was_called.get());
}
}
#[test]
fn called_for_auto_if_should_detect() {
let detector = DetectorStub::should_detect(Some(Dark));
_ = theme_impl(ThemeOptions::default(), &detector);
assert!(detector.was_called.get());
}
#[test]
fn not_called_for_auto_if_not_should_detect() {
let detector = DetectorStub::should_not_detect();
_ = theme_impl(ThemeOptions::default(), &detector);
assert!(!detector.was_called.get());
}
}
mod precedence {
use super::*;
#[test]
fn theme_is_preferred_over_light_or_dark_themes() {
for color_scheme in optional(color_schemes()) {
for options in [
ThemeOptions {
theme: ThemePreference::Fixed(ThemeName::Named("Theme".to_string())),
..Default::default()
},
ThemeOptions {
theme: ThemePreference::Fixed(ThemeName::Named("Theme".to_string())),
theme_dark: Some(ThemeName::Named("Dark Theme".to_string())),
theme_light: Some(ThemeName::Named("Light Theme".to_string())),
},
] {
let detector = ConstantDetector(color_scheme);
assert_eq!("Theme", theme_impl(options, &detector).to_string());
}
}
}
#[test]
fn detector_is_not_called_if_theme_is_present() {
let options = ThemeOptions {
theme: ThemePreference::Fixed(ThemeName::Named("Theme".to_string())),
..Default::default()
};
let detector = DetectorStub::should_detect(Some(Dark));
_ = theme_impl(options, &detector);
assert!(!detector.was_called.get());
}
}
mod default_theme {
use super::*;
#[test]
fn default_dark_if_unable_to_detect_color_scheme() {
let detector = ConstantDetector(None);
assert_eq!(
default_theme(ColorScheme::Dark),
theme_impl(ThemeOptions::default(), &detector).to_string()
);
}
// For backwards compatibility, if the default theme is requested
// explicitly through BAT_THEME, we always pick the default dark theme.
#[test]
fn default_dark_if_requested_explicitly_through_theme() {
for color_scheme in optional(color_schemes()) {
let options = ThemeOptions {
theme: ThemePreference::Fixed(ThemeName::Default),
..Default::default()
};
let detector = ConstantDetector(color_scheme);
assert_eq!(
default_theme(ColorScheme::Dark),
theme_impl(options, &detector).to_string()
);
}
}
#[test]
fn varies_depending_on_color_scheme() {
for color_scheme in color_schemes() {
for options in [
ThemeOptions::default(),
ThemeOptions {
theme_dark: Some(ThemeName::Default),
theme_light: Some(ThemeName::Default),
..Default::default()
},
] {
let detector = ConstantDetector(Some(color_scheme));
assert_eq!(
default_theme(color_scheme),
theme_impl(options, &detector).to_string()
);
}
}
}
}
mod choosing {
use super::*;
#[test]
fn chooses_default_theme_if_unknown() {
let options = ThemeOptions {
theme_dark: Some(ThemeName::Named("Dark".to_string())),
theme_light: Some(ThemeName::Named("Light".to_string())),
..Default::default()
};
let detector = ConstantDetector(None);
assert_eq!(
default_theme(ColorScheme::default()),
theme_impl(options, &detector).to_string()
);
}
#[test]
fn chooses_dark_theme_if_dark_or_unknown() {
let options = ThemeOptions {
theme_dark: Some(ThemeName::Named("Dark".to_string())),
theme_light: Some(ThemeName::Named("Light".to_string())),
..Default::default()
};
let detector = ConstantDetector(Some(ColorScheme::Dark));
assert_eq!("Dark", theme_impl(options, &detector).to_string());
}
#[test]
fn chooses_light_theme_if_light() {
let options = ThemeOptions {
theme_dark: Some(ThemeName::Named("Dark".to_string())),
theme_light: Some(ThemeName::Named("Light".to_string())),
..Default::default()
};
let detector = ConstantDetector(Some(ColorScheme::Light));
assert_eq!("Light", theme_impl(options, &detector).to_string());
}
}
mod theme_preference {
use super::*;
#[test]
fn values_roundtrip_via_display() {
let prefs = [
ThemePreference::Auto(DetectColorScheme::Auto),
ThemePreference::Auto(DetectColorScheme::Always),
ThemePreference::Auto(DetectColorScheme::System),
ThemePreference::Fixed(ThemeName::Default),
ThemePreference::Fixed(ThemeName::new("foo")),
ThemePreference::Dark,
ThemePreference::Light,
];
for pref in prefs {
assert_eq!(pref, ThemePreference::new(pref.to_string()));
}
}
}
struct DetectorStub {
should_detect: bool,
color_scheme: Option<ColorScheme>,
was_called: Cell<bool>,
}
impl DetectorStub {
fn should_detect(color_scheme: Option<ColorScheme>) -> Self {
DetectorStub {
should_detect: true,
color_scheme,
was_called: Cell::default(),
}
}
fn should_not_detect() -> Self {
DetectorStub {
should_detect: false,
color_scheme: None,
was_called: Cell::default(),
}
}
}
impl ColorSchemeDetector for DetectorStub {
fn should_detect(&self) -> bool {
self.should_detect
}
fn detect(&self) -> Option<ColorScheme> {
self.was_called.set(true);
self.color_scheme
}
}
struct ConstantDetector(Option<ColorScheme>);
impl ColorSchemeDetector for ConstantDetector {
fn should_detect(&self) -> bool {
true
}
fn detect(&self) -> Option<ColorScheme> {
self.0
}
}
fn optional<T>(value: impl Iterator<Item = T>) -> impl Iterator<Item = Option<T>> {
value.map(Some).chain(iter::once(None))
}
fn color_schemes() -> impl Iterator<Item = ColorScheme> {
[Dark, Light].into_iter()
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/line_range.rs | src/line_range.rs | use crate::error::*;
use itertools::{Itertools, MinMaxResult};
#[derive(Debug, Copy, Clone)]
pub struct LineRange {
lower: RangeBound,
upper: RangeBound,
}
/// Defines a boundary for a range
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub(crate) enum RangeBound {
// An absolute line number marking the boundary of a range
Absolute(usize),
// A relative (implicitly negative) offset from the end of the file as a boundary
OffsetFromEnd(usize),
}
impl Default for LineRange {
fn default() -> LineRange {
LineRange {
lower: RangeBound::Absolute(usize::MIN),
upper: RangeBound::Absolute(usize::MAX),
}
}
}
impl LineRange {
pub fn new(from: usize, to: usize) -> Self {
LineRange {
lower: RangeBound::Absolute(from),
upper: RangeBound::Absolute(to),
}
}
pub fn from(range_raw: &str) -> Result<LineRange> {
LineRange::parse_range(range_raw)
}
fn parse_range(range_raw: &str) -> Result<LineRange> {
let mut new_range = LineRange::default();
let mut raw_range_iter = range_raw.bytes();
let first_byte = raw_range_iter.next().ok_or("Empty line range")?;
if first_byte == b':' {
if raw_range_iter.next() == Some(b'-') {
// E.g. ':-3'
let value = range_raw[2..].parse()?;
new_range.upper = RangeBound::OffsetFromEnd(value);
} else {
let value = range_raw[1..].parse()?;
new_range.upper = RangeBound::Absolute(value);
}
return Ok(new_range);
} else if range_raw.bytes().last().ok_or("Empty line range")? == b':' {
if first_byte == b'-' {
// E.g. '-3:'
let value = range_raw[1..range_raw.len() - 1].parse()?;
new_range.lower = RangeBound::OffsetFromEnd(value);
} else {
let value = range_raw[..range_raw.len() - 1].parse()?;
new_range.lower = RangeBound::Absolute(value);
}
return Ok(new_range);
}
let line_numbers: Vec<&str> = range_raw.split(':').collect();
match line_numbers.len() {
1 => {
new_range.lower = RangeBound::Absolute(line_numbers[0].parse()?);
new_range.upper = new_range.lower;
Ok(new_range)
}
2 => {
let mut lower_absolute_bound: usize = line_numbers[0].parse()?;
let first_byte = line_numbers[1].bytes().next();
let upper_absolute_bound = if first_byte == Some(b'+') {
let more_lines = &line_numbers[1][1..]
.parse()
.map_err(|_| "Invalid character after +")?;
lower_absolute_bound.saturating_add(*more_lines)
} else if first_byte == Some(b'-') {
// this will prevent values like "-+5" even though "+5" is valid integer
if line_numbers[1][1..].bytes().next() == Some(b'+') {
return Err("Invalid character after -".into());
}
let prior_lines = &line_numbers[1][1..]
.parse()
.map_err(|_| "Invalid character after -")?;
let prev_lower = lower_absolute_bound;
lower_absolute_bound = lower_absolute_bound.saturating_sub(*prior_lines);
prev_lower
} else {
line_numbers[1].parse()?
};
new_range.lower = RangeBound::Absolute(lower_absolute_bound);
new_range.upper = RangeBound::Absolute(upper_absolute_bound);
Ok(new_range)
}
3 => {
// Handle context syntax: N::C or N:M:C
if line_numbers[1].is_empty() {
// Format: N::C - single line with context
let line_number: usize = line_numbers[0].parse()
.map_err(|_| "Invalid line number in N::C format")?;
let context: usize = line_numbers[2].parse()
.map_err(|_| "Invalid context number in N::C format")?;
new_range.lower = RangeBound::Absolute(line_number.saturating_sub(context));
new_range.upper = RangeBound::Absolute(line_number.saturating_add(context));
} else {
// Format: N:M:C - range with context
let start_line: usize = line_numbers[0].parse()
.map_err(|_| "Invalid start line number in N:M:C format")?;
let end_line: usize = line_numbers[1].parse()
.map_err(|_| "Invalid end line number in N:M:C format")?;
let context: usize = line_numbers[2].parse()
.map_err(|_| "Invalid context number in N:M:C format")?;
new_range.lower = RangeBound::Absolute(start_line.saturating_sub(context));
new_range.upper = RangeBound::Absolute(end_line.saturating_add(context));
}
Ok(new_range)
}
_ => Err(
"Line range contained too many ':' characters. Expected format: 'N', 'N:M', 'N::C', or 'N:M:C'"
.into(),
),
}
}
/// Checks if a line number is inside the range.
/// For ranges with relative offsets range bounds `max_buffered_line_number` is necessary
/// to convert the offset to an absolute value.
pub(crate) fn is_inside(
&self,
line: usize,
max_buffered_line_number: MaxBufferedLineNumber,
) -> bool {
match (self.lower, self.upper, max_buffered_line_number) {
(RangeBound::Absolute(lower), RangeBound::Absolute(upper), _) => {
lower <= line && line <= upper
}
(
RangeBound::Absolute(lower),
RangeBound::OffsetFromEnd(offset),
MaxBufferedLineNumber::Final(last_line_number),
) => lower <= line && line <= last_line_number.saturating_sub(offset),
(
RangeBound::Absolute(lower),
RangeBound::OffsetFromEnd(_),
MaxBufferedLineNumber::Tentative(_),
) => {
// We don't know the final line number yet, so the assumption is that the line is
// still far enough away from the upper end of the range
lower <= line
}
(
RangeBound::OffsetFromEnd(offset),
RangeBound::Absolute(upper),
MaxBufferedLineNumber::Final(last_line_number),
) => last_line_number.saturating_sub(offset) <= line && line <= upper,
(
RangeBound::OffsetFromEnd(_),
RangeBound::Absolute(_),
MaxBufferedLineNumber::Tentative(_),
) => {
// We don't know the final line number yet, so the assumption is that the line is
// still too far away from the having reached the lower end of the range
false
}
(
RangeBound::OffsetFromEnd(lower),
RangeBound::OffsetFromEnd(upper),
MaxBufferedLineNumber::Final(last_line_number),
) => {
last_line_number.saturating_sub(lower) <= line
&& line <= last_line_number.saturating_sub(upper)
}
(
RangeBound::OffsetFromEnd(_),
RangeBound::OffsetFromEnd(_),
MaxBufferedLineNumber::Tentative(_),
) => {
// We don't know the final line number yet, so the assumption is that we're still
// too far away from the having reached the lower end of the range
false
}
}
}
}
#[test]
fn test_parse_full() {
let range = LineRange::from("40:50").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(40), range.lower);
assert_eq!(RangeBound::Absolute(50), range.upper);
}
#[test]
fn test_parse_partial_min() {
let range = LineRange::from(":50").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(usize::MIN), range.lower);
assert_eq!(RangeBound::Absolute(50), range.upper);
}
#[test]
fn test_parse_partial_relative_negative_from_back() {
let range = LineRange::from(":-5").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(usize::MIN), range.lower);
assert_eq!(RangeBound::OffsetFromEnd(5), range.upper);
}
#[test]
fn test_parse_relative_negative_from_back_partial() {
let range = LineRange::from("-5:").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::OffsetFromEnd(5), range.lower);
assert_eq!(RangeBound::Absolute(usize::MAX), range.upper);
}
#[test]
fn test_parse_partial_max() {
let range = LineRange::from("40:").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(40), range.lower);
assert_eq!(RangeBound::Absolute(usize::MAX), range.upper);
}
#[test]
fn test_parse_single() {
let range = LineRange::from("40").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(40), range.lower);
assert_eq!(RangeBound::Absolute(40), range.upper);
}
#[test]
fn test_parse_fail() {
// Test 4+ colon parts should still fail
let range = LineRange::from("40:50:80:90");
assert!(range.is_err());
// Test invalid formats that should still fail
let range = LineRange::from("-2:5");
assert!(range.is_err());
let range = LineRange::from(":40:");
assert!(range.is_err());
// Test completely malformed input
let range = LineRange::from("abc:def");
assert!(range.is_err());
}
#[test]
fn test_parse_plus() {
let range = LineRange::from("40:+10").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(40), range.lower);
assert_eq!(RangeBound::Absolute(50), range.upper);
}
#[test]
fn test_parse_plus_overflow() {
let range = LineRange::from(&format!("{}:+1", usize::MAX)).expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(usize::MAX), range.lower);
assert_eq!(RangeBound::Absolute(usize::MAX), range.upper);
}
#[test]
fn test_parse_plus_fail() {
let range = LineRange::from("40:+z");
assert!(range.is_err());
let range = LineRange::from("40:+-10");
assert!(range.is_err());
let range = LineRange::from("40:+");
assert!(range.is_err());
}
#[test]
fn test_parse_minus_success() {
let range = LineRange::from("40:-10").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(30), range.lower);
assert_eq!(RangeBound::Absolute(40), range.upper);
}
#[test]
fn test_parse_minus_edge_cases_success() {
let range = LineRange::from("5:-4").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(1), range.lower);
assert_eq!(RangeBound::Absolute(5), range.upper);
let range = LineRange::from("5:-5").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(0), range.lower);
assert_eq!(RangeBound::Absolute(5), range.upper);
let range = LineRange::from("5:-100").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(0), range.lower);
assert_eq!(RangeBound::Absolute(5), range.upper);
}
#[test]
fn test_parse_minus_fail() {
let range = LineRange::from("40:-z");
assert!(range.is_err());
let range = LineRange::from("40:-+10");
assert!(range.is_err());
let range = LineRange::from("40:-");
assert!(range.is_err());
}
#[test]
fn test_parse_context_single_line() {
let range = LineRange::from("35::5").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(30), range.lower);
assert_eq!(RangeBound::Absolute(40), range.upper);
}
#[test]
fn test_parse_context_range() {
let range = LineRange::from("30:40:2").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(28), range.lower);
assert_eq!(RangeBound::Absolute(42), range.upper);
// Test the case that used to fail but should now work
let range = LineRange::from("40:50:80").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(0), range.lower); // 40 - 80 = 0 (saturated)
assert_eq!(RangeBound::Absolute(130), range.upper); // 50 + 80 = 130
}
#[test]
fn test_parse_context_edge_cases() {
// Test with small line numbers that would underflow
let range = LineRange::from("5::10").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(0), range.lower);
assert_eq!(RangeBound::Absolute(15), range.upper);
// Test with zero context
let range = LineRange::from("50::0").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(50), range.lower);
assert_eq!(RangeBound::Absolute(50), range.upper);
// Test range with zero context
let range = LineRange::from("30:40:0").expect("Shouldn't fail on test!");
assert_eq!(RangeBound::Absolute(30), range.lower);
assert_eq!(RangeBound::Absolute(40), range.upper);
}
#[test]
fn test_parse_context_fail() {
let range = LineRange::from("40::z");
assert!(range.is_err());
let range = LineRange::from("::5");
assert!(range.is_err());
let range = LineRange::from("40::");
assert!(range.is_err());
let range = LineRange::from("30:40:z");
assert!(range.is_err());
let range = LineRange::from("30::40:5");
assert!(range.is_err());
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum RangeCheckResult {
// Within one of the given ranges
InRange,
// Before the first range or within two ranges
BeforeOrBetweenRanges,
// Line number is outside of all ranges and larger than the last range.
AfterLastRange,
}
/// Represents the maximum line number in the buffer when reading a file.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub(crate) enum MaxBufferedLineNumber {
// The currently known maximum line number, may not be the final line number
Tentative(usize),
// The final line number, when EOF has been reached
Final(usize),
}
#[derive(Debug, Clone)]
pub struct LineRanges {
ranges: Vec<LineRange>,
// The largest absolute upper line number of all ranges
largest_absolute_upper_bound: usize,
// The smallest relative offset from the end of all ranges
smallest_offset_from_end: usize,
// The largest relative offset from the end of all ranges
largest_offset_from_end: usize,
}
impl LineRanges {
pub fn none() -> LineRanges {
LineRanges::from(vec![])
}
pub fn all() -> LineRanges {
LineRanges::from(vec![LineRange::default()])
}
pub fn from(ranges: Vec<LineRange>) -> LineRanges {
let largest_absolute_upper_bound = ranges
.iter()
.filter_map(|r| match r.upper {
RangeBound::Absolute(upper) => Some(upper),
_ => None,
})
.max()
.unwrap_or(usize::MAX);
let offsets_min_max = ranges
.iter()
.flat_map(|r| [r.lower, r.upper])
.filter_map(|r| match r {
RangeBound::OffsetFromEnd(offset) => Some(offset),
_ => None,
})
.minmax();
let (smallest_offset_from_end, largest_offset_from_end) = match offsets_min_max {
MinMaxResult::NoElements => (usize::MIN, usize::MIN),
MinMaxResult::OneElement(offset) => (offset, offset),
MinMaxResult::MinMax(min, max) => (min, max),
};
LineRanges {
ranges,
largest_absolute_upper_bound,
smallest_offset_from_end,
largest_offset_from_end,
}
}
pub(crate) fn check(
&self,
line: usize,
max_buffered_line_number: MaxBufferedLineNumber,
) -> RangeCheckResult {
if self
.ranges
.iter()
.any(|r| r.is_inside(line, max_buffered_line_number))
{
RangeCheckResult::InRange
} else if matches!(max_buffered_line_number, MaxBufferedLineNumber::Final(final_line_number) if line > final_line_number.saturating_sub(self.smallest_offset_from_end))
{
RangeCheckResult::AfterLastRange
} else if line < self.largest_absolute_upper_bound {
RangeCheckResult::BeforeOrBetweenRanges
} else {
RangeCheckResult::AfterLastRange
}
}
pub(crate) fn largest_offset_from_end(&self) -> usize {
self.largest_offset_from_end
}
}
impl Default for LineRanges {
fn default() -> Self {
Self::all()
}
}
#[derive(Debug, Clone)]
pub struct HighlightedLineRanges(pub LineRanges);
impl Default for HighlightedLineRanges {
fn default() -> Self {
HighlightedLineRanges(LineRanges::none())
}
}
#[cfg(test)]
fn ranges(rs: &[&str]) -> LineRanges {
LineRanges::from(rs.iter().map(|r| LineRange::from(r).unwrap()).collect())
}
#[test]
fn test_ranges_simple() {
let ranges = ranges(&["3:8"]);
assert_eq!(
RangeCheckResult::BeforeOrBetweenRanges,
ranges.check(2, MaxBufferedLineNumber::Tentative(2))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(5, MaxBufferedLineNumber::Tentative(5))
);
assert_eq!(
RangeCheckResult::AfterLastRange,
ranges.check(9, MaxBufferedLineNumber::Tentative(9))
);
}
#[test]
fn test_ranges_advanced() {
let ranges = ranges(&["3:8", "11:20", "25:30"]);
assert_eq!(
RangeCheckResult::BeforeOrBetweenRanges,
ranges.check(2, MaxBufferedLineNumber::Tentative(2))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(5, MaxBufferedLineNumber::Tentative(5))
);
assert_eq!(
RangeCheckResult::BeforeOrBetweenRanges,
ranges.check(9, MaxBufferedLineNumber::Tentative(9))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(11, MaxBufferedLineNumber::Tentative(11))
);
assert_eq!(
RangeCheckResult::BeforeOrBetweenRanges,
ranges.check(22, MaxBufferedLineNumber::Tentative(22))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(28, MaxBufferedLineNumber::Tentative(28))
);
assert_eq!(
RangeCheckResult::AfterLastRange,
ranges.check(31, MaxBufferedLineNumber::Tentative(31))
);
}
#[test]
fn test_ranges_open_low() {
let ranges = ranges(&["3:8", ":5"]);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(1, MaxBufferedLineNumber::Tentative(1))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(3, MaxBufferedLineNumber::Tentative(3))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(7, MaxBufferedLineNumber::Tentative(7))
);
assert_eq!(
RangeCheckResult::AfterLastRange,
ranges.check(9, MaxBufferedLineNumber::Tentative(9))
);
}
#[test]
fn test_ranges_open_high() {
let ranges = ranges(&["3:", "2:5"]);
assert_eq!(
RangeCheckResult::BeforeOrBetweenRanges,
ranges.check(1, MaxBufferedLineNumber::Tentative(1))
);
assert_eq!(
RangeCheckResult::BeforeOrBetweenRanges,
ranges.check(1, MaxBufferedLineNumber::Final(10))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(2, MaxBufferedLineNumber::Final(10))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(9, MaxBufferedLineNumber::Final(10))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(10, MaxBufferedLineNumber::Final(10))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(3, MaxBufferedLineNumber::Tentative(3))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(5, MaxBufferedLineNumber::Tentative(5))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(9, MaxBufferedLineNumber::Tentative(9))
);
}
#[test]
fn test_ranges_open_up_to_3_from_end() {
let ranges = ranges(&[":-3"]);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(1, MaxBufferedLineNumber::Tentative(1))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(3, MaxBufferedLineNumber::Tentative(3))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(5, MaxBufferedLineNumber::Tentative(8))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(1, MaxBufferedLineNumber::Final(6))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(2, MaxBufferedLineNumber::Final(6))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(3, MaxBufferedLineNumber::Final(6))
);
assert_eq!(
RangeCheckResult::AfterLastRange,
ranges.check(4, MaxBufferedLineNumber::Final(6))
);
assert_eq!(
RangeCheckResult::AfterLastRange,
ranges.check(5, MaxBufferedLineNumber::Final(6))
);
assert_eq!(
RangeCheckResult::AfterLastRange,
ranges.check(6, MaxBufferedLineNumber::Final(6))
);
}
#[test]
fn test_ranges_multiple_negative_from_back() {
let ranges = ranges(&[":-3", ":-9"]);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(1, MaxBufferedLineNumber::Tentative(1))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(3, MaxBufferedLineNumber::Tentative(3))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(5, MaxBufferedLineNumber::Tentative(14))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(1, MaxBufferedLineNumber::Final(16))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(7, MaxBufferedLineNumber::Final(16))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(13, MaxBufferedLineNumber::Final(16))
);
assert_eq!(
RangeCheckResult::AfterLastRange,
ranges.check(14, MaxBufferedLineNumber::Final(16))
);
assert_eq!(
RangeCheckResult::AfterLastRange,
ranges.check(16, MaxBufferedLineNumber::Final(16))
);
}
#[test]
fn test_ranges_3_from_back_up_to_end() {
let ranges = ranges(&["-3:"]);
assert_eq!(
RangeCheckResult::BeforeOrBetweenRanges,
ranges.check(1, MaxBufferedLineNumber::Tentative(1))
);
assert_eq!(
RangeCheckResult::BeforeOrBetweenRanges,
ranges.check(3, MaxBufferedLineNumber::Tentative(3))
);
assert_eq!(
RangeCheckResult::BeforeOrBetweenRanges,
ranges.check(5, MaxBufferedLineNumber::Tentative(8))
);
assert_eq!(
RangeCheckResult::BeforeOrBetweenRanges,
ranges.check(1, MaxBufferedLineNumber::Final(5))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(2, MaxBufferedLineNumber::Final(5))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(3, MaxBufferedLineNumber::Final(5))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(4, MaxBufferedLineNumber::Final(5))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(5, MaxBufferedLineNumber::Final(5))
);
}
#[test]
fn test_ranges_multiple_negative_offsets_to_end() {
let ranges = ranges(&["-3:", "-12:"]);
assert_eq!(
RangeCheckResult::BeforeOrBetweenRanges,
ranges.check(5, MaxBufferedLineNumber::Tentative(8))
);
assert_eq!(
RangeCheckResult::BeforeOrBetweenRanges,
ranges.check(5, MaxBufferedLineNumber::Tentative(17))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(8, MaxBufferedLineNumber::Final(20))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(9, MaxBufferedLineNumber::Final(20))
);
}
#[test]
fn test_ranges_absolute_bound_and_offset() {
let ranges = ranges(&["5:", ":-2"]);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(4, MaxBufferedLineNumber::Tentative(6))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(5, MaxBufferedLineNumber::Tentative(7))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(8, MaxBufferedLineNumber::Final(10))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(9, MaxBufferedLineNumber::Final(10))
);
assert_eq!(
RangeCheckResult::InRange,
ranges.check(10, MaxBufferedLineNumber::Final(10))
);
}
#[test]
fn test_ranges_all() {
let ranges = LineRanges::all();
assert_eq!(
RangeCheckResult::InRange,
ranges.check(1, MaxBufferedLineNumber::Tentative(1))
);
}
#[test]
fn test_ranges_none() {
let ranges = LineRanges::none();
assert_ne!(
RangeCheckResult::InRange,
ranges.check(1, MaxBufferedLineNumber::Tentative(1))
);
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/diff.rs | src/diff.rs | #![cfg(feature = "git")]
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use git2::{DiffOptions, IntoCString, Repository};
#[derive(Copy, Clone, Debug)]
pub enum LineChange {
Added,
RemovedAbove,
RemovedBelow,
Modified,
}
pub type LineChanges = HashMap<u32, LineChange>;
pub fn get_git_diff(filename: &Path) -> Option<LineChanges> {
let repo = Repository::discover(filename).ok()?;
let repo_path_absolute = fs::canonicalize(repo.workdir()?).ok()?;
let filepath_absolute = fs::canonicalize(filename).ok()?;
let filepath_relative_to_repo = filepath_absolute.strip_prefix(&repo_path_absolute).ok()?;
let mut diff_options = DiffOptions::new();
let pathspec = filepath_relative_to_repo.into_c_string().ok()?;
diff_options.pathspec(pathspec);
diff_options.context_lines(0);
let diff = repo
.diff_index_to_workdir(None, Some(&mut diff_options))
.ok()?;
let mut line_changes: LineChanges = HashMap::new();
let mark_section =
|line_changes: &mut LineChanges, start: u32, end: i32, change: LineChange| {
for line in start..=end as u32 {
line_changes.insert(line, change);
}
};
let _ = diff.foreach(
&mut |_, _| true,
None,
Some(&mut |delta, hunk| {
let path = delta.new_file().path().unwrap_or_else(|| Path::new(""));
if filepath_relative_to_repo != path {
return false;
}
let old_lines = hunk.old_lines();
let new_start = hunk.new_start();
let new_lines = hunk.new_lines();
let new_end = (new_start + new_lines) as i32 - 1;
if old_lines == 0 && new_lines > 0 {
mark_section(&mut line_changes, new_start, new_end, LineChange::Added);
} else if new_lines == 0 && old_lines > 0 {
if new_start == 0 {
mark_section(&mut line_changes, 1, 1, LineChange::RemovedAbove);
} else {
mark_section(
&mut line_changes,
new_start,
new_start as i32,
LineChange::RemovedBelow,
);
}
} else {
mark_section(&mut line_changes, new_start, new_end, LineChange::Modified);
}
true
}),
None,
);
Some(line_changes)
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/wrapping.rs | src/wrapping.rs | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WrappingMode {
Character,
// The bool specifies whether wrapping has been explicitly disabled by the user via --wrap=never
NoWrapping(bool),
}
impl Default for WrappingMode {
fn default() -> Self {
WrappingMode::NoWrapping(false)
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/controller.rs | src/controller.rs | use crate::assets::HighlightingAssets;
use crate::config::{Config, VisibleLines};
#[cfg(feature = "git")]
use crate::diff::{get_git_diff, LineChanges};
use crate::error::*;
use crate::input::{Input, InputReader, OpenedInput};
#[cfg(feature = "lessopen")]
use crate::lessopen::LessOpenPreprocessor;
#[cfg(feature = "git")]
use crate::line_range::LineRange;
use crate::line_range::{LineRanges, MaxBufferedLineNumber, RangeCheckResult};
use crate::output::{OutputHandle, OutputType};
#[cfg(feature = "paging")]
use crate::paging::PagingMode;
use crate::printer::{InteractivePrinter, Printer, SimplePrinter};
use std::collections::VecDeque;
use std::io::{self, BufRead, Write};
use std::mem;
use clircle::{Clircle, Identifier};
pub struct Controller<'a> {
config: &'a Config<'a>,
assets: &'a HighlightingAssets,
#[cfg(feature = "lessopen")]
preprocessor: Option<LessOpenPreprocessor>,
}
impl Controller<'_> {
pub fn new<'a>(config: &'a Config, assets: &'a HighlightingAssets) -> Controller<'a> {
Controller {
config,
assets,
#[cfg(feature = "lessopen")]
preprocessor: LessOpenPreprocessor::new().ok(),
}
}
pub fn run(
&self,
inputs: Vec<Input>,
output_handle: Option<&mut OutputHandle<'_>>,
) -> Result<bool> {
self.run_with_error_handler(inputs, output_handle, default_error_handler)
}
pub fn run_with_error_handler(
&self,
inputs: Vec<Input>,
output_handle: Option<&mut OutputHandle<'_>>,
mut handle_error: impl FnMut(&Error, &mut dyn Write),
) -> Result<bool> {
// only create our own OutputType if no output handle was provided.
#[allow(unused_mut)]
let mut output_type_opt: Option<OutputType> = None;
#[cfg(feature = "paging")]
if output_handle.is_none() {
use crate::input::InputKind;
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 = inputs.iter().any(|input| {
if let InputKind::OrdinaryFile(ref path) = input.kind {
Path::new(path).exists()
} else {
true
}
});
if !call_pager {
paging_mode = PagingMode::Never;
}
}
let wrapping_mode = self.config.wrapping_mode;
output_type_opt = Some(OutputType::from_mode(
paging_mode,
wrapping_mode,
self.config.pager,
)?);
}
#[cfg(not(feature = "paging"))]
if output_handle.is_none() {
output_type_opt = Some(OutputType::stdout());
}
let attached_to_pager = match (&output_handle, &output_type_opt) {
(Some(_), _) => true,
(None, Some(ot)) => ot.is_pager(),
(None, None) => false,
};
let stdout_identifier = if cfg!(windows) || attached_to_pager {
None
} else {
clircle::Identifier::stdout()
};
let mut writer = match (output_handle, &mut output_type_opt) {
(Some(OutputHandle::FmtWrite(w)), _) => OutputHandle::FmtWrite(w),
(Some(OutputHandle::IoWrite(w)), _) => OutputHandle::IoWrite(w),
(None, Some(ot)) => ot.handle()?,
(None, None) => unreachable!("No output handle and no output type available"),
};
let mut no_errors: bool = true;
let stderr = io::stderr();
for (index, input) in inputs.into_iter().enumerate() {
let identifier = stdout_identifier.as_ref();
let is_first = index == 0;
let result = if input.is_stdin() {
self.print_input(input, &mut writer, io::stdin().lock(), identifier, is_first)
} else {
// Use dummy stdin since stdin is actually not used (#1902)
self.print_input(input, &mut writer, io::empty(), identifier, is_first)
};
if let Err(error) = result {
match writer {
// It doesn't make much sense to send errors straight to stderr if the user
// provided their own buffer, so we just return it.
OutputHandle::FmtWrite(_) => return Err(error),
OutputHandle::IoWrite(ref mut writer) => {
if attached_to_pager {
handle_error(&error, writer);
} else {
handle_error(&error, &mut stderr.lock());
}
}
}
no_errors = false;
}
}
Ok(no_errors)
}
fn print_input<R: BufRead>(
&self,
input: Input,
writer: &mut OutputHandle,
stdin: R,
stdout_identifier: Option<&Identifier>,
is_first: bool,
) -> Result<()> {
let mut opened_input = {
#[cfg(feature = "lessopen")]
match self.preprocessor {
Some(ref preprocessor) if self.config.use_lessopen => {
preprocessor.open(input, stdin, stdout_identifier)?
}
_ => input.open(stdin, stdout_identifier)?,
}
#[cfg(not(feature = "lessopen"))]
input.open(stdin, stdout_identifier)?
};
#[cfg(feature = "git")]
let line_changes = if self.config.visible_lines.diff_mode()
|| (!self.config.loop_through && self.config.style_components.changes())
{
match opened_input.kind {
crate::input::OpenedInputKind::OrdinaryFile(ref path) => {
let diff = get_git_diff(path);
// Skip files without Git modifications
if self.config.visible_lines.diff_mode()
&& diff
.as_ref()
.map(|changes| changes.is_empty())
.unwrap_or(false)
{
return Ok(());
}
diff
}
_ if self.config.visible_lines.diff_mode() => {
// Skip non-file inputs in diff mode
return Ok(());
}
_ => None,
}
} else {
None
};
let mut printer: Box<dyn Printer> = if self.config.loop_through {
Box::new(SimplePrinter::new(self.config))
} else {
Box::new(InteractivePrinter::new(
self.config,
self.assets,
&mut opened_input,
#[cfg(feature = "git")]
&line_changes,
)?)
};
self.print_file(
&mut *printer,
writer,
&mut opened_input,
!is_first,
#[cfg(feature = "git")]
&line_changes,
)
}
fn print_file(
&self,
printer: &mut dyn Printer,
writer: &mut OutputHandle,
input: &mut OpenedInput,
add_header_padding: bool,
#[cfg(feature = "git")] line_changes: &Option<LineChanges>,
) -> Result<()> {
if !input.reader.first_line.is_empty() || self.config.style_components.header() {
printer.print_header(writer, input, add_header_padding)?;
}
if !input.reader.first_line.is_empty() {
let line_ranges = match self.config.visible_lines {
VisibleLines::Ranges(ref line_ranges) => line_ranges.clone(),
#[cfg(feature = "git")]
VisibleLines::DiffContext(context) => {
let mut line_ranges: Vec<LineRange> = vec![];
if let Some(line_changes) = line_changes {
for &line in line_changes.keys() {
let line = line as usize;
line_ranges
.push(LineRange::new(line.saturating_sub(context), line + context));
}
}
LineRanges::from(line_ranges)
}
};
self.print_file_ranges(printer, writer, &mut input.reader, &line_ranges)?;
}
printer.print_footer(writer, input)?;
Ok(())
}
fn print_file_ranges(
&self,
printer: &mut dyn Printer,
writer: &mut OutputHandle,
reader: &mut InputReader,
line_ranges: &LineRanges,
) -> Result<()> {
let mut current_line_buffer: Vec<u8> = Vec::new();
let mut current_line_number: usize = 1;
// Buffer needs to be 1 greater than the offset to have a look-ahead line for EOF
let buffer_size: usize = line_ranges.largest_offset_from_end() + 1;
// Buffers multiple line data and line number
let mut buffered_lines: VecDeque<(Vec<u8>, usize)> = VecDeque::with_capacity(buffer_size);
let mut reached_eof: bool = false;
let mut first_range: bool = true;
let mut mid_range: bool = false;
let style_snip = self.config.style_components.snip();
loop {
if reached_eof && buffered_lines.is_empty() {
// Done processing all lines
break;
}
if !reached_eof {
if reader.read_line(&mut current_line_buffer)? {
// Fill the buffer
buffered_lines
.push_back((mem::take(&mut current_line_buffer), current_line_number));
current_line_number += 1;
} else {
// No more data to read
reached_eof = true;
}
}
if buffered_lines.len() < buffer_size && !reached_eof {
// The buffer needs to be completely filled first
continue;
}
let Some((line, line_nr)) = buffered_lines.pop_front() else {
break;
};
// Determine if the last line number in the buffer is the last line of the file or
// just a line somewhere in the file
let max_buffered_line_number = buffered_lines
.back()
.map(|(_, max_line_number)| {
if reached_eof {
MaxBufferedLineNumber::Final(*max_line_number)
} else {
MaxBufferedLineNumber::Tentative(*max_line_number)
}
})
.unwrap_or(MaxBufferedLineNumber::Final(line_nr));
match line_ranges.check(line_nr, max_buffered_line_number) {
RangeCheckResult::BeforeOrBetweenRanges => {
// Call the printer in case we need to call the syntax highlighter
// for this line. However, set `out_of_range` to `true`.
printer.print_line(true, writer, line_nr, &line, max_buffered_line_number)?;
mid_range = false;
}
RangeCheckResult::InRange => {
if style_snip {
if first_range {
first_range = false;
mid_range = true;
} else if !mid_range {
mid_range = true;
printer.print_snip(writer)?;
}
}
printer.print_line(false, writer, line_nr, &line, max_buffered_line_number)?;
}
RangeCheckResult::AfterLastRange => {
break;
}
}
}
Ok(())
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/syntax_mapping.rs | src/syntax_mapping.rs | use std::{
path::Path,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
thread,
};
use globset::{Candidate, GlobBuilder, GlobMatcher};
use once_cell::sync::Lazy;
use crate::error::Result;
use builtin::BUILTIN_MAPPINGS;
use ignored_suffixes::IgnoredSuffixes;
mod builtin;
pub mod ignored_suffixes;
fn make_glob_matcher(from: &str) -> Result<GlobMatcher> {
let matcher = GlobBuilder::new(from)
.case_insensitive(true)
.literal_separator(true)
.build()?
.compile_matcher();
Ok(matcher)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MappingTarget<'a> {
/// For mapping a path to a specific syntax.
MapTo(&'a str),
/// For mapping a path (typically an extension-less file name) to an unknown
/// syntax. This typically means later using the contents of the first line
/// of the file to determine what syntax to use.
MapToUnknown,
/// For mapping a file extension (e.g. `*.conf`) to an unknown syntax. This
/// typically means later using the contents of the first line of the file
/// to determine what syntax to use. However, if a syntax handles a file
/// name that happens to have the given file extension (e.g. `resolv.conf`),
/// then that association will have higher precedence, and the mapping will
/// be ignored.
MapExtensionToUnknown,
}
#[derive(Debug, Clone, Default)]
pub struct SyntaxMapping<'a> {
/// User-defined mappings at run time.
///
/// Rules in front have precedence.
custom_mappings: Vec<(GlobMatcher, MappingTarget<'a>)>,
pub(crate) ignored_suffixes: IgnoredSuffixes<'a>,
/// A flag to halt glob matcher building, which is offloaded to another thread.
///
/// We have this so that we can signal the thread to halt early when appropriate.
halt_glob_build: Arc<AtomicBool>,
}
impl Drop for SyntaxMapping<'_> {
fn drop(&mut self) {
// signal the offload thread to halt early
self.halt_glob_build.store(true, Ordering::Relaxed);
}
}
impl<'a> SyntaxMapping<'a> {
pub fn new() -> SyntaxMapping<'a> {
Default::default()
}
/// Start a thread to build the glob matchers for all builtin mappings.
///
/// The use of this function while not necessary, is useful to speed up startup
/// times by starting this work early in parallel.
///
/// The thread halts if/when `halt_glob_build` is set to true.
pub fn start_offload_build_all(&self) {
let halt = Arc::clone(&self.halt_glob_build);
thread::spawn(move || {
for (matcher, _) in BUILTIN_MAPPINGS.iter() {
if halt.load(Ordering::Relaxed) {
break;
}
Lazy::force(matcher);
}
});
// Note that this thread is not joined upon completion because there's
// no shared resources that need synchronization to be safely dropped.
// If we later add code into this thread that requires interesting
// resources (e.g. IO), it would be a good idea to store the handle
// and join it on drop.
}
pub fn insert(&mut self, from: &str, to: MappingTarget<'a>) -> Result<()> {
let matcher = make_glob_matcher(from)?;
self.custom_mappings.push((matcher, to));
Ok(())
}
/// Returns an iterator over all mappings. User-defined mappings are listed
/// before builtin mappings; mappings in front have higher precedence.
///
/// Builtin mappings' `GlobMatcher`s are lazily compiled.
///
/// Note that this function only returns mappings that are valid under the
/// current environment. For details see [`Self::builtin_mappings`].
pub fn all_mappings(&self) -> impl Iterator<Item = (&GlobMatcher, &MappingTarget<'a>)> {
self.custom_mappings()
.iter()
.map(|(matcher, target)| (matcher, target)) // as_ref
.chain(
// we need a map with a closure to "do" the lifetime variance
// see: https://discord.com/channels/273534239310479360/1120124565591425034/1170543402870382653
// also, clippy false positive:
// see: https://github.com/rust-lang/rust-clippy/issues/9280
#[allow(clippy::map_identity)]
self.builtin_mappings().map(|rule| rule),
)
}
/// Returns an iterator over all valid builtin mappings. Mappings in front
/// have higher precedence.
///
/// The `GlabMatcher`s are lazily compiled.
///
/// Mappings that are invalid under the current environment (i.e. rule
/// requires environment variable(s) that is unset, or the joined string
/// after variable(s) replacement is not a valid glob expression) are
/// ignored.
pub fn builtin_mappings(
&self,
) -> impl Iterator<Item = (&'static GlobMatcher, &'static MappingTarget<'static>)> {
BUILTIN_MAPPINGS
.iter()
.filter_map(|(matcher, target)| matcher.as_ref().map(|glob| (glob, target)))
}
/// Returns all user-defined mappings.
pub fn custom_mappings(&self) -> &[(GlobMatcher, MappingTarget<'a>)] {
&self.custom_mappings
}
pub fn get_syntax_for(&self, path: impl AsRef<Path>) -> Option<MappingTarget<'a>> {
// Try matching on the file name as-is.
let candidate = Candidate::new(&path);
let candidate_filename = path.as_ref().file_name().map(Candidate::new);
for (glob, syntax) in self.all_mappings() {
if glob.is_match_candidate(&candidate)
|| candidate_filename
.as_ref()
.is_some_and(|filename| glob.is_match_candidate(filename))
{
return Some(*syntax);
}
}
// Try matching on the file name after removing an ignored suffix.
let file_name = path.as_ref().file_name()?;
self.ignored_suffixes
.try_with_stripped_suffix(file_name, |stripped_file_name| {
Ok(self.get_syntax_for(stripped_file_name))
})
.ok()?
}
pub fn insert_ignored_suffix(&mut self, suffix: &'a str) {
self.ignored_suffixes.add_suffix(suffix);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builtin_mappings_work() {
let map = SyntaxMapping::new();
assert_eq!(
map.get_syntax_for("/path/to/build"),
Some(MappingTarget::MapToUnknown)
);
}
#[test]
fn all_fixed_builtin_mappings_can_compile() {
let map = SyntaxMapping::new();
// collect call evaluates all lazy closures
// fixed builtin mappings will panic if they fail to compile
let _mappings = map.builtin_mappings().collect::<Vec<_>>();
}
#[test]
fn builtin_mappings_matcher_only_compile_once() {
let map = SyntaxMapping::new();
let two_iterations: Vec<_> = (0..2)
.map(|_| {
// addresses of every matcher
map.builtin_mappings()
.map(|(matcher, _)| matcher as *const _ as usize)
.collect::<Vec<_>>()
})
.collect();
// if the matchers are only compiled once, their address should remain the same
assert_eq!(two_iterations[0], two_iterations[1]);
}
#[test]
fn custom_mappings_work() {
let mut map = SyntaxMapping::new();
map.insert("/path/to/Cargo.lock", MappingTarget::MapTo("TOML"))
.ok();
map.insert("/path/to/.ignore", MappingTarget::MapTo("Git Ignore"))
.ok();
assert_eq!(
map.get_syntax_for("/path/to/Cargo.lock"),
Some(MappingTarget::MapTo("TOML"))
);
assert_eq!(map.get_syntax_for("/path/to/other.lock"), None);
assert_eq!(
map.get_syntax_for("/path/to/.ignore"),
Some(MappingTarget::MapTo("Git Ignore"))
);
}
#[test]
fn custom_mappings_override_builtin() {
let mut map = SyntaxMapping::new();
assert_eq!(
map.get_syntax_for("/path/to/httpd.conf"),
Some(MappingTarget::MapTo("Apache Conf"))
);
map.insert("httpd.conf", MappingTarget::MapTo("My Syntax"))
.ok();
assert_eq!(
map.get_syntax_for("/path/to/httpd.conf"),
Some(MappingTarget::MapTo("My Syntax"))
);
}
#[test]
fn custom_mappings_precedence() {
let mut map = SyntaxMapping::new();
map.insert("/path/to/foo", MappingTarget::MapTo("alpha"))
.ok();
map.insert("/path/to/foo", MappingTarget::MapTo("bravo"))
.ok();
assert_eq!(
map.get_syntax_for("/path/to/foo"),
Some(MappingTarget::MapTo("alpha"))
);
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/error.rs | src/error.rs | use std::io::Write;
use thiserror::Error;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Io(#[from] ::std::io::Error),
#[error(transparent)]
Fmt(#[from] ::std::fmt::Error),
#[error(transparent)]
SyntectError(#[from] ::syntect::Error),
#[error(transparent)]
SyntectLoadingError(#[from] ::syntect::LoadingError),
#[error(transparent)]
ParseIntError(#[from] ::std::num::ParseIntError),
#[error(transparent)]
GlobParsingError(#[from] ::globset::Error),
#[error(transparent)]
SerdeYamlError(#[from] ::serde_yaml::Error),
#[error("unable to detect syntax for {0}")]
UndetectedSyntax(String),
#[error("unknown syntax: '{0}'")]
UnknownSyntax(String),
#[error("Unknown style '{0}'")]
UnknownStyle(String),
#[error("Use of bat as a pager is disallowed in order to avoid infinite recursion problems")]
InvalidPagerValueBat,
#[error("{0}")]
Msg(String),
#[cfg(feature = "paging")]
#[error(transparent)]
MinusError(#[from] ::minus::MinusError),
#[cfg(feature = "lessopen")]
#[error(transparent)]
VarError(#[from] ::std::env::VarError),
#[cfg(feature = "lessopen")]
#[error(transparent)]
CommandParseError(#[from] ::shell_words::ParseError),
}
impl From<&'static str> for Error {
fn from(s: &'static str) -> Self {
Error::Msg(s.to_owned())
}
}
impl From<String> for Error {
fn from(s: String) -> Self {
Error::Msg(s)
}
}
pub type Result<T> = std::result::Result<T, Error>;
pub fn default_error_handler(error: &Error, output: &mut dyn Write) {
use nu_ansi_term::Color::Red;
match error {
Error::Io(ref io_error) if io_error.kind() == ::std::io::ErrorKind::BrokenPipe => {
::std::process::exit(0);
}
Error::SerdeYamlError(_) => {
writeln!(
output,
"{}: Error while parsing metadata.yaml file: {error}",
Red.paint("[bat error]"),
)
.ok();
}
_ => {
writeln!(
&mut std::io::stderr().lock(),
"{}: {error}",
Red.paint("[bat error]"),
)
.ok();
}
};
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/printer.rs | src/printer.rs | use std::vec::Vec;
use nu_ansi_term::Color::{Fixed, Green, Red, Yellow};
use nu_ansi_term::Style;
use bytesize::ByteSize;
use syntect::easy::HighlightLines;
use syntect::highlighting::Color;
use syntect::highlighting::FontStyle;
use syntect::highlighting::Theme;
use syntect::parsing::SyntaxSet;
use content_inspector::ContentType;
use encoding_rs::{UTF_16BE, UTF_16LE};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthChar;
use crate::assets::{HighlightingAssets, SyntaxReferenceInSet};
use crate::config::Config;
#[cfg(feature = "git")]
use crate::decorations::LineChangesDecoration;
use crate::decorations::{Decoration, GridBorderDecoration, LineNumberDecoration};
#[cfg(feature = "git")]
use crate::diff::LineChanges;
use crate::error::*;
use crate::input::OpenedInput;
use crate::line_range::{MaxBufferedLineNumber, RangeCheckResult};
use crate::output::OutputHandle;
use crate::preprocessor::{expand_tabs, replace_nonprintable, strip_ansi, strip_overstrike};
use crate::style::StyleComponent;
use crate::terminal::{as_terminal_escaped, to_ansi_color};
use crate::vscreen::{AnsiStyle, EscapeSequence, EscapeSequenceIterator};
use crate::wrapping::WrappingMode;
use crate::BinaryBehavior;
use crate::StripAnsiMode;
const ANSI_UNDERLINE_ENABLE: EscapeSequence = EscapeSequence::CSI {
raw_sequence: "\x1B[4m",
parameters: "4",
intermediates: "",
final_byte: "m",
};
const ANSI_UNDERLINE_DISABLE: EscapeSequence = EscapeSequence::CSI {
raw_sequence: "\x1B[24m",
parameters: "24",
intermediates: "",
final_byte: "m",
};
const EMPTY_SYNTECT_STYLE: syntect::highlighting::Style = syntect::highlighting::Style {
foreground: Color {
r: 127,
g: 127,
b: 127,
a: 255,
},
background: Color {
r: 127,
g: 127,
b: 127,
a: 255,
},
font_style: FontStyle::empty(),
};
pub(crate) trait Printer {
fn print_header(
&mut self,
handle: &mut OutputHandle,
input: &OpenedInput,
add_header_padding: bool,
) -> Result<()>;
fn print_footer(&mut self, handle: &mut OutputHandle, input: &OpenedInput) -> Result<()>;
fn print_snip(&mut self, handle: &mut OutputHandle) -> Result<()>;
fn print_line(
&mut self,
out_of_range: bool,
handle: &mut OutputHandle,
line_number: usize,
line_buffer: &[u8],
max_buffered_line_number: MaxBufferedLineNumber,
) -> Result<()>;
}
pub struct SimplePrinter<'a> {
config: &'a Config<'a>,
consecutive_empty_lines: usize,
}
impl<'a> SimplePrinter<'a> {
pub fn new(config: &'a Config) -> Self {
SimplePrinter {
config,
consecutive_empty_lines: 0,
}
}
}
impl Printer for SimplePrinter<'_> {
fn print_header(
&mut self,
_handle: &mut OutputHandle,
_input: &OpenedInput,
_add_header_padding: bool,
) -> Result<()> {
Ok(())
}
fn print_footer(&mut self, _handle: &mut OutputHandle, _input: &OpenedInput) -> Result<()> {
Ok(())
}
fn print_snip(&mut self, _handle: &mut OutputHandle) -> Result<()> {
Ok(())
}
fn print_line(
&mut self,
out_of_range: bool,
handle: &mut OutputHandle,
_line_number: usize,
line_buffer: &[u8],
_max_buffered_line_number: MaxBufferedLineNumber,
) -> Result<()> {
// Skip squeezed lines.
if let Some(squeeze_limit) = self.config.squeeze_lines {
if String::from_utf8_lossy(line_buffer)
.trim_end_matches(['\r', '\n'])
.is_empty()
{
self.consecutive_empty_lines += 1;
if self.consecutive_empty_lines > squeeze_limit {
return Ok(());
}
} else {
self.consecutive_empty_lines = 0;
}
}
if !out_of_range {
if self.config.show_nonprintable {
let line = replace_nonprintable(
line_buffer,
self.config.tab_width,
self.config.nonprintable_notation,
);
write!(handle, "{line}")?;
} else {
match handle {
OutputHandle::IoWrite(handle) => handle.write_all(line_buffer)?,
OutputHandle::FmtWrite(handle) => {
write!(
handle,
"{}",
std::str::from_utf8(line_buffer).map_err(|_| Error::Msg(
"encountered invalid utf8 while printing to non-io buffer"
.to_string()
))?
)?;
}
}
};
}
Ok(())
}
}
struct HighlighterFromSet<'a> {
highlighter: HighlightLines<'a>,
syntax_set: &'a SyntaxSet,
}
impl<'a> HighlighterFromSet<'a> {
fn new(syntax_in_set: SyntaxReferenceInSet<'a>, theme: &'a Theme) -> Self {
Self {
highlighter: HighlightLines::new(syntax_in_set.syntax, theme),
syntax_set: syntax_in_set.syntax_set,
}
}
}
pub(crate) struct InteractivePrinter<'a> {
colors: Colors,
config: &'a Config<'a>,
decorations: Vec<Box<dyn Decoration>>,
panel_width: usize,
ansi_style: AnsiStyle,
content_type: Option<ContentType>,
#[cfg(feature = "git")]
pub line_changes: &'a Option<LineChanges>,
highlighter_from_set: Option<HighlighterFromSet<'a>>,
background_color_highlight: Option<Color>,
consecutive_empty_lines: usize,
strip_ansi: bool,
strip_overstrike: bool,
}
impl<'a> InteractivePrinter<'a> {
pub(crate) fn new(
config: &'a Config,
assets: &'a HighlightingAssets,
input: &mut OpenedInput,
#[cfg(feature = "git")] line_changes: &'a Option<LineChanges>,
) -> Result<Self> {
let theme = assets.get_theme(&config.theme);
let background_color_highlight = theme.settings.line_highlight;
let colors = if config.colored_output {
Colors::colored(theme, config.true_color)
} else {
Colors::plain()
};
// Create decorations.
let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
if config.style_components.numbers() {
decorations.push(Box::new(LineNumberDecoration::new(&colors)));
}
#[cfg(feature = "git")]
{
if config.style_components.changes()
&& line_changes.as_ref().is_some_and(|c| !c.is_empty())
{
decorations.push(Box::new(LineChangesDecoration::new(&colors)));
}
}
let mut panel_width: usize =
decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
// The grid border decoration isn't added until after the panel_width calculation, since the
// print_horizontal_line, print_header, and print_footer functions all assume the panel
// width is without the grid border.
if config.style_components.grid() && !decorations.is_empty() {
decorations.push(Box::new(GridBorderDecoration::new(&colors)));
}
// Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
// panel showing).
if config.term_width
< (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
{
decorations.clear();
panel_width = 0;
}
// Get the highlighter for the output.
let is_printing_binary = input
.reader
.content_type
.is_some_and(|c| c.is_binary() && !config.show_nonprintable);
let needs_to_match_syntax = (!is_printing_binary
|| matches!(config.binary, BinaryBehavior::AsText))
&& (config.colored_output || config.strip_ansi == StripAnsiMode::Auto);
let (is_plain_text, strip_overstrike, highlighter_from_set) = if needs_to_match_syntax {
// Determine the type of syntax for highlighting
const PLAIN_TEXT_SYNTAX: &str = "Plain Text";
const MANPAGE_SYNTAX: &str = "Manpage";
const COMMAND_HELP_SYNTAX: &str = "Command Help";
match assets.get_syntax(config.language, input, &config.syntax_mapping) {
Ok(syntax_in_set) => (
syntax_in_set.syntax.name == PLAIN_TEXT_SYNTAX,
syntax_in_set.syntax.name == MANPAGE_SYNTAX
|| syntax_in_set.syntax.name == COMMAND_HELP_SYNTAX,
Some(HighlighterFromSet::new(syntax_in_set, theme)),
),
Err(Error::UndetectedSyntax(_)) => (
true,
false,
Some(
assets
.find_syntax_by_name(PLAIN_TEXT_SYNTAX)?
.map(|s| HighlighterFromSet::new(s, theme))
.expect("A plain text syntax is available"),
),
),
Err(e) => return Err(e),
}
} else {
(false, false, None)
};
// Determine when to strip ANSI sequences
let strip_ansi = match config.strip_ansi {
_ if config.show_nonprintable => false,
StripAnsiMode::Always => true,
StripAnsiMode::Auto if is_plain_text => false, // Plain text may already contain escape sequences.
StripAnsiMode::Auto => true,
_ => false,
};
Ok(InteractivePrinter {
panel_width,
colors,
config,
decorations,
content_type: input.reader.content_type,
ansi_style: AnsiStyle::new(),
#[cfg(feature = "git")]
line_changes,
highlighter_from_set,
background_color_highlight,
consecutive_empty_lines: 0,
strip_ansi,
strip_overstrike,
})
}
fn print_horizontal_line_term(
&mut self,
handle: &mut OutputHandle,
style: Style,
) -> Result<()> {
writeln!(
handle,
"{}",
style.paint("─".repeat(self.config.term_width))
)?;
Ok(())
}
fn print_horizontal_line(&mut self, handle: &mut OutputHandle, grid_char: char) -> Result<()> {
if self.panel_width == 0 {
self.print_horizontal_line_term(handle, self.colors.grid)?;
} else {
let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
let hline = format!("{}{grid_char}{hline}", "─".repeat(self.panel_width));
writeln!(handle, "{}", self.colors.grid.paint(hline))?;
}
Ok(())
}
fn create_fake_panel(&self, text: &str) -> String {
if self.panel_width == 0 {
return "".to_string();
}
let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
let text_filled: String = format!(
"{text_truncated}{}",
" ".repeat(self.panel_width - 1 - text_truncated.len())
);
if self.config.style_components.grid() {
format!("{text_filled} │ ")
} else {
text_filled
}
}
fn get_header_component_indent_length(&self) -> usize {
if self.config.style_components.grid() && self.panel_width > 0 {
self.panel_width + 2
} else {
self.panel_width
}
}
fn print_header_component_indent(&mut self, handle: &mut OutputHandle) -> Result<()> {
if self.config.style_components.grid() {
write!(
handle,
"{}{}",
" ".repeat(self.panel_width),
self.colors
.grid
.paint(if self.panel_width > 0 { "│ " } else { "" }),
)
} else {
write!(handle, "{}", " ".repeat(self.panel_width))
}
}
fn print_header_component_with_indent(
&mut self,
handle: &mut OutputHandle,
content: &str,
) -> Result<()> {
self.print_header_component_indent(handle)?;
writeln!(handle, "{content}")
}
fn print_header_multiline_component(
&mut self,
handle: &mut OutputHandle,
content: &str,
) -> Result<()> {
let content_width = self.config.term_width - self.get_header_component_indent_length();
if content.chars().count() <= content_width {
return self.print_header_component_with_indent(handle, content);
}
let mut content_graphemes: Vec<&str> = content.graphemes(true).collect();
while content_graphemes.len() > content_width {
let (content_line, remaining) = content_graphemes.split_at(content_width);
self.print_header_component_with_indent(handle, content_line.join("").as_str())?;
content_graphemes = remaining.to_vec();
}
self.print_header_component_with_indent(handle, content_graphemes.join("").as_str())
}
fn highlight_regions_for_line<'b>(
&mut self,
line: &'b str,
) -> Result<Vec<(syntect::highlighting::Style, &'b str)>> {
let highlighter_from_set = match self.highlighter_from_set {
Some(ref mut highlighter_from_set) => highlighter_from_set,
_ => return Ok(vec![(EMPTY_SYNTECT_STYLE, line)]),
};
// skip syntax highlighting on long lines
let too_long = line.len() > 1024 * 16;
let for_highlighting: &str = if too_long { "\n" } else { line };
let mut highlighted_line = highlighter_from_set
.highlighter
.highlight_line(for_highlighting, highlighter_from_set.syntax_set)?;
if too_long {
highlighted_line[0].1 = line;
}
Ok(highlighted_line)
}
fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
if self.config.tab_width > 0 {
return expand_tabs(text, self.config.tab_width, cursor);
}
*cursor += text.len();
text.to_string()
}
}
impl Printer for InteractivePrinter<'_> {
fn print_header(
&mut self,
handle: &mut OutputHandle,
input: &OpenedInput,
add_header_padding: bool,
) -> Result<()> {
if add_header_padding && self.config.style_components.rule() {
self.print_horizontal_line_term(handle, self.colors.rule)?;
}
if !self.config.style_components.header() {
if Some(ContentType::BINARY) == self.content_type
&& !self.config.show_nonprintable
&& !matches!(self.config.binary, BinaryBehavior::AsText)
{
writeln!(
handle,
"{}: Binary content from {} will not be printed to the terminal \
(but will be present if the output of 'bat' is piped). You can use 'bat -A' \
to show the binary file contents.",
Yellow.paint("[bat warning]"),
input.description.summary(),
)?;
} else if self.config.style_components.grid() {
self.print_horizontal_line(handle, '┬')?;
}
return Ok(());
}
let mode = match self.content_type {
Some(ContentType::BINARY) => " <BINARY>",
Some(ContentType::UTF_16LE) => " <UTF-16LE>",
Some(ContentType::UTF_16BE) => " <UTF-16BE>",
None => " <EMPTY>",
_ => "",
};
let description = &input.description;
let metadata = &input.metadata;
// We use this iterator to have a deterministic order for
// header components. HashSet has arbitrary order, but Vec is ordered.
let header_components: Vec<StyleComponent> = [
(
StyleComponent::HeaderFilename,
self.config.style_components.header_filename(),
),
(
StyleComponent::HeaderFilesize,
self.config.style_components.header_filesize(),
),
]
.iter()
.filter(|(_, is_enabled)| *is_enabled)
.map(|(component, _)| *component)
.collect();
// Print the cornering grid before the first header component
if self.config.style_components.grid() {
self.print_horizontal_line(handle, '┬')?;
} else {
// Only pad space between files, if we haven't already drawn a horizontal rule
if add_header_padding && !self.config.style_components.rule() {
writeln!(handle)?;
}
}
header_components
.iter()
.try_for_each(|component| match component {
StyleComponent::HeaderFilename => {
let header_filename = format!(
"{}{}{mode}",
description
.kind()
.map(|kind| format!("{kind}: "))
.unwrap_or_else(|| "".into()),
self.colors.header_value.paint(description.title()),
);
self.print_header_multiline_component(handle, &header_filename)
}
StyleComponent::HeaderFilesize => {
let bsize = metadata
.size
.map(|s| format!("{}", ByteSize(s)))
.unwrap_or_else(|| "-".into());
let header_filesize =
format!("Size: {}", self.colors.header_value.paint(bsize));
self.print_header_multiline_component(handle, &header_filesize)
}
_ => Ok(()),
})?;
if self.config.style_components.grid() {
if self.content_type.is_some_and(|c| c.is_text())
|| self.config.show_nonprintable
|| matches!(self.config.binary, BinaryBehavior::AsText)
{
self.print_horizontal_line(handle, '┼')?;
} else {
self.print_horizontal_line(handle, '┴')?;
}
}
Ok(())
}
fn print_footer(&mut self, handle: &mut OutputHandle, _input: &OpenedInput) -> Result<()> {
if self.config.style_components.grid()
&& (self.content_type.is_some_and(|c| c.is_text())
|| self.config.show_nonprintable
|| matches!(self.config.binary, BinaryBehavior::AsText))
{
self.print_horizontal_line(handle, '┴')
} else {
Ok(())
}
}
fn print_snip(&mut self, handle: &mut OutputHandle) -> Result<()> {
let panel = self.create_fake_panel(" ...");
let panel_count = panel.chars().count();
let title = "8<";
let title_count = title.chars().count();
let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
let snip_right =
" ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
writeln!(
handle,
"{}",
self.colors
.grid
.paint(format!("{panel}{snip_left}{title}{snip_right}"))
)?;
Ok(())
}
fn print_line(
&mut self,
out_of_range: bool,
handle: &mut OutputHandle,
line_number: usize,
line_buffer: &[u8],
max_buffered_line_number: MaxBufferedLineNumber,
) -> Result<()> {
let line = if self.config.show_nonprintable {
replace_nonprintable(
line_buffer,
self.config.tab_width,
self.config.nonprintable_notation,
)
.into()
} else {
let mut line = match self.content_type {
Some(ContentType::BINARY) | None
if !matches!(self.config.binary, BinaryBehavior::AsText) =>
{
return Ok(());
}
Some(ContentType::UTF_16LE) => UTF_16LE.decode_with_bom_removal(line_buffer).0,
Some(ContentType::UTF_16BE) => UTF_16BE.decode_with_bom_removal(line_buffer).0,
_ => {
let line = String::from_utf8_lossy(line_buffer);
if line_number == 1 {
match line.strip_prefix('\u{feff}') {
Some(stripped) => stripped.to_string().into(),
None => line,
}
} else {
line
}
}
};
if self.strip_overstrike {
if let Some(pos) = line.find('\x08') {
line = strip_overstrike(&line, pos).into();
}
}
// If ANSI escape sequences are supposed to be stripped, do it before syntax highlighting.
if self.strip_ansi {
line = strip_ansi(&line).into()
}
line
};
let regions = self.highlight_regions_for_line(&line)?;
if out_of_range {
return Ok(());
}
// Skip squeezed lines.
if let Some(squeeze_limit) = self.config.squeeze_lines {
if line.trim_end_matches(['\r', '\n']).is_empty() {
self.consecutive_empty_lines += 1;
if self.consecutive_empty_lines > squeeze_limit {
return Ok(());
}
} else {
self.consecutive_empty_lines = 0;
}
}
let mut cursor: usize = 0;
let mut cursor_max: usize = self.config.term_width;
let mut cursor_total: usize = 0;
let mut panel_wrap: Option<String> = None;
// Line highlighting
let highlight_this_line = self
.config
.highlighted_lines
.0
.check(line_number, max_buffered_line_number)
== RangeCheckResult::InRange;
if highlight_this_line && self.config.theme == "ansi" {
self.ansi_style.update(ANSI_UNDERLINE_ENABLE);
}
let background_color = self
.background_color_highlight
.filter(|_| highlight_this_line);
// Line decorations.
if self.panel_width > 0 {
let decorations = self
.decorations
.iter()
.map(|d| d.generate(line_number, false, self));
for deco in decorations {
write!(handle, "{} ", deco.text)?;
cursor_max -= deco.width + 1;
}
}
// Line contents.
if matches!(self.config.wrapping_mode, WrappingMode::NoWrapping(_)) {
let true_color = self.config.true_color;
let colored_output = self.config.colored_output;
let italics = self.config.use_italic_text;
for &(style, region) in ®ions {
let ansi_iterator = EscapeSequenceIterator::new(region);
for chunk in ansi_iterator {
match chunk {
// Regular text.
EscapeSequence::Text(text) => {
let text = self.preprocess(text, &mut cursor_total);
let text_trimmed = text.trim_end_matches(['\r', '\n']);
write!(
handle,
"{}{}",
as_terminal_escaped(
style,
&format!("{}{text_trimmed}", self.ansi_style),
true_color,
colored_output,
italics,
background_color
),
self.ansi_style.to_reset_sequence(),
)?;
// Pad the rest of the line.
if text.len() != text_trimmed.len() {
if let Some(background_color) = background_color {
let ansi_style = Style {
background: to_ansi_color(background_color, true_color),
..Default::default()
};
let width = if cursor_total <= cursor_max {
cursor_max - cursor_total + 1
} else {
0
};
write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
}
write!(handle, "{}", &text[text_trimmed.len()..])?;
}
}
// ANSI escape passthrough.
_ => {
write!(handle, "{}", chunk.raw())?;
self.ansi_style.update(chunk);
}
}
}
}
if !self.config.style_components.plain() && line.bytes().next_back() != Some(b'\n') {
writeln!(handle)?;
}
} else {
for &(style, region) in ®ions {
let ansi_iterator = EscapeSequenceIterator::new(region);
for chunk in ansi_iterator {
match chunk {
// Regular text.
EscapeSequence::Text(text) => {
let text = self
.preprocess(text.trim_end_matches(['\r', '\n']), &mut cursor_total);
let mut max_width = cursor_max - cursor;
// line buffer (avoid calling write! for every character)
let mut line_buf = String::with_capacity(max_width * 4);
// Displayed width of line_buf
let mut current_width = 0;
for c in text.chars() {
// calculate the displayed width for next character
let cw = c.width().unwrap_or(0);
current_width += cw;
// if next character cannot be printed on this line,
// flush the buffer.
if current_width > max_width {
// Generate wrap padding if not already generated.
if panel_wrap.is_none() {
panel_wrap = if self.panel_width > 0 {
Some(format!(
"{} ",
self.decorations
.iter()
.map(|d| d
.generate(line_number, true, self)
.text)
.collect::<Vec<String>>()
.join(" ")
))
} else {
Some("".to_string())
}
}
// It wraps.
write!(
handle,
"{}{}\n{}",
as_terminal_escaped(
style,
&format!("{}{line_buf}", self.ansi_style),
self.config.true_color,
self.config.colored_output,
self.config.use_italic_text,
background_color
),
self.ansi_style.to_reset_sequence(),
panel_wrap.clone().unwrap()
)?;
cursor = 0;
max_width = cursor_max;
line_buf.clear();
current_width = cw;
}
line_buf.push(c);
}
// flush the buffer
cursor += current_width;
write!(
handle,
"{}",
as_terminal_escaped(
style,
&format!("{}{line_buf}", self.ansi_style),
self.config.true_color,
self.config.colored_output,
self.config.use_italic_text,
background_color
)
)?;
}
// ANSI escape passthrough.
_ => {
write!(handle, "{}", chunk.raw())?;
self.ansi_style.update(chunk);
}
}
}
}
if let Some(background_color) = background_color {
let ansi_style = Style {
background: to_ansi_color(background_color, self.config.true_color),
..Default::default()
};
write!(
handle,
"{}",
ansi_style.paint(" ".repeat(cursor_max - cursor))
)?;
}
writeln!(handle)?;
}
if highlight_this_line && self.config.theme == "ansi" {
write!(handle, "{}", ANSI_UNDERLINE_DISABLE.raw())?;
self.ansi_style.update(ANSI_UNDERLINE_DISABLE);
}
Ok(())
}
}
const DEFAULT_GUTTER_COLOR: u8 = 238;
#[derive(Debug, Default)]
pub struct Colors {
pub grid: Style,
pub rule: Style,
pub header_value: Style,
pub git_added: Style,
pub git_removed: Style,
pub git_modified: Style,
pub line_number: Style,
}
impl Colors {
fn plain() -> Self {
Colors::default()
}
fn colored(theme: &Theme, true_color: bool) -> Self {
let gutter_style = Style {
foreground: match theme.settings.gutter_foreground {
// If the theme provides a gutter foreground color, use it.
// Note: It might be the special value #00000001, in which case
// to_ansi_color returns None and we use an empty Style
// (resulting in the terminal's default foreground color).
Some(c) => to_ansi_color(c, true_color),
// Otherwise, use a specific fallback color.
None => Some(Fixed(DEFAULT_GUTTER_COLOR)),
},
..Style::default()
};
Colors {
grid: gutter_style,
rule: gutter_style,
header_value: Style::new().bold(),
git_added: Green.normal(),
git_removed: Red.normal(),
git_modified: Yellow.normal(),
line_number: gutter_style,
}
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/pretty_printer.rs | src/pretty_printer.rs | use std::io::Read;
use std::path::Path;
use console::Term;
use crate::{
assets::HighlightingAssets,
config::{Config, VisibleLines},
controller::Controller,
error::Result,
input,
line_range::{HighlightedLineRanges, LineRange, LineRanges},
output::OutputHandle,
style::StyleComponent,
StripAnsiMode, SyntaxMapping, WrappingMode,
};
#[cfg(feature = "paging")]
use crate::paging::PagingMode;
#[derive(Default)]
struct ActiveStyleComponents {
header_filename: bool,
#[cfg(feature = "git")]
vcs_modification_markers: bool,
grid: bool,
rule: bool,
line_numbers: bool,
snip: bool,
}
#[non_exhaustive]
pub struct Syntax {
pub name: String,
pub file_extensions: Vec<String>,
}
pub struct PrettyPrinter<'a> {
inputs: Vec<Input<'a>>,
config: Config<'a>,
assets: HighlightingAssets,
highlighted_lines: Vec<LineRange>,
term_width: Option<usize>,
active_style_components: ActiveStyleComponents,
}
impl<'a> PrettyPrinter<'a> {
pub fn new() -> Self {
let config = Config {
colored_output: true,
true_color: true,
..Default::default()
};
PrettyPrinter {
inputs: vec![],
config,
assets: HighlightingAssets::from_binary(),
highlighted_lines: vec![],
term_width: None,
active_style_components: ActiveStyleComponents::default(),
}
}
/// Add an input which should be pretty-printed
pub fn input(&mut self, input: Input<'a>) -> &mut Self {
self.inputs.push(input);
self
}
/// Adds multiple inputs which should be pretty-printed
pub fn inputs(&mut self, inputs: impl IntoIterator<Item = Input<'a>>) -> &mut Self {
for input in inputs {
self.inputs.push(input);
}
self
}
/// Add a file which should be pretty-printed
pub fn input_file(&mut self, path: impl AsRef<Path>) -> &mut Self {
self.input(Input::from_file(path).kind("File"))
}
/// Add multiple files which should be pretty-printed
pub fn input_files<I, P>(&mut self, paths: I) -> &mut Self
where
I: IntoIterator<Item = P>,
P: AsRef<Path>,
{
self.inputs(paths.into_iter().map(Input::from_file))
}
/// Add STDIN as an input
pub fn input_stdin(&mut self) -> &mut Self {
self.inputs.push(Input::from_stdin());
self
}
/// Add a byte string as an input
pub fn input_from_bytes(&mut self, content: &'a [u8]) -> &mut Self {
self.input_from_reader(content)
}
/// Add a custom reader as an input
pub fn input_from_reader<R: Read + 'a>(&mut self, reader: R) -> &mut Self {
self.inputs.push(Input::from_reader(reader));
self
}
/// Specify the syntax file which should be used (default: auto-detect)
pub fn language(&mut self, language: &'a str) -> &mut Self {
self.config.language = Some(language);
self
}
/// The character width of the terminal (default: autodetect)
pub fn term_width(&mut self, width: usize) -> &mut Self {
self.term_width = Some(width);
self
}
/// The width of tab characters (default: None - do not turn tabs to spaces)
pub fn tab_width(&mut self, tab_width: Option<usize>) -> &mut Self {
self.config.tab_width = tab_width.unwrap_or(0);
self
}
/// Whether or not the output should be colorized (default: true)
pub fn colored_output(&mut self, yes: bool) -> &mut Self {
self.config.colored_output = yes;
self
}
/// Whether or not to output 24bit colors (default: true)
pub fn true_color(&mut self, yes: bool) -> &mut Self {
self.config.true_color = yes;
self
}
/// Whether to show a header with the file name
pub fn header(&mut self, yes: bool) -> &mut Self {
self.active_style_components.header_filename = yes;
self
}
/// Whether to show line numbers
pub fn line_numbers(&mut self, yes: bool) -> &mut Self {
self.active_style_components.line_numbers = yes;
self
}
/// Whether to paint a grid, separating line numbers, git changes and the code
pub fn grid(&mut self, yes: bool) -> &mut Self {
self.active_style_components.grid = yes;
self
}
/// Whether to paint a horizontal rule to delimit files
pub fn rule(&mut self, yes: bool) -> &mut Self {
self.active_style_components.rule = yes;
self
}
/// Whether to show modification markers for VCS changes. This has no effect if
/// the `git` feature is not activated.
#[cfg(feature = "git")]
pub fn vcs_modification_markers(&mut self, yes: bool) -> &mut Self {
self.active_style_components.vcs_modification_markers = yes;
self
}
/// Whether to print binary content or nonprintable characters (default: no)
pub fn show_nonprintable(&mut self, yes: bool) -> &mut Self {
self.config.show_nonprintable = yes;
self
}
/// Whether to show "snip" markers between visible line ranges (default: no)
pub fn snip(&mut self, yes: bool) -> &mut Self {
self.active_style_components.snip = yes;
self
}
/// Whether to remove ANSI escape sequences from the input (default: never)
///
/// If `Auto` is used, escape sequences will only be removed when the input
/// is not plain text.
pub fn strip_ansi(&mut self, mode: StripAnsiMode) -> &mut Self {
self.config.strip_ansi = mode;
self
}
/// Text wrapping mode (default: do not wrap)
pub fn wrapping_mode(&mut self, mode: WrappingMode) -> &mut Self {
self.config.wrapping_mode = mode;
self
}
/// Whether or not to use ANSI italics (default: off)
pub fn use_italics(&mut self, yes: bool) -> &mut Self {
self.config.use_italic_text = yes;
self
}
/// If and how to use a pager (default: no paging)
#[cfg(feature = "paging")]
pub fn paging_mode(&mut self, mode: PagingMode) -> &mut Self {
self.config.paging_mode = mode;
self
}
/// Specify the command to start the pager (default: use "less")
#[cfg(feature = "paging")]
pub fn pager(&mut self, cmd: &'a str) -> &mut Self {
self.config.pager = Some(cmd);
self
}
/// Specify the lines that should be printed (default: all)
pub fn line_ranges(&mut self, ranges: LineRanges) -> &mut Self {
self.config.visible_lines = VisibleLines::Ranges(ranges);
self
}
/// Specify a line that should be highlighted (default: none).
/// This can be called multiple times to highlight more than one
/// line. See also: highlight_range.
pub fn highlight(&mut self, line: usize) -> &mut Self {
self.highlighted_lines.push(LineRange::new(line, line));
self
}
/// Specify a range of lines that should be highlighted (default: none).
/// This can be called multiple times to highlight more than one range
/// of lines.
pub fn highlight_range(&mut self, from: usize, to: usize) -> &mut Self {
self.highlighted_lines.push(LineRange::new(from, to));
self
}
/// Specify the maximum number of consecutive empty lines to print.
pub fn squeeze_empty_lines(&mut self, maximum: Option<usize>) -> &mut Self {
self.config.squeeze_lines = maximum;
self
}
/// Specify the highlighting theme.
/// You can use [`crate::theme::theme`] to pick a theme based on user preferences
/// and the terminal's background color.
pub fn theme(&mut self, theme: impl AsRef<str>) -> &mut Self {
self.config.theme = theme.as_ref().to_owned();
self
}
/// Specify custom file extension / file name to syntax mappings
pub fn syntax_mapping(&mut self, mapping: SyntaxMapping<'a>) -> &mut Self {
self.config.syntax_mapping = mapping;
self
}
pub fn themes(&self) -> impl Iterator<Item = &str> {
self.assets.themes()
}
pub fn syntaxes(&self) -> impl Iterator<Item = Syntax> + '_ {
// We always use assets from the binary, which are guaranteed to always
// be valid, so get_syntaxes() can never fail here
self.assets
.get_syntaxes()
.unwrap()
.iter()
.filter(|s| !s.hidden)
.map(|s| Syntax {
name: s.name.clone(),
file_extensions: s.file_extensions.clone(),
})
}
/// Pretty-print all specified inputs. This method will "use" all stored inputs.
/// If you want to call 'print' multiple times, you have to call the appropriate
/// input_* methods again.
pub fn print(&mut self) -> Result<bool> {
self.print_with_writer(None::<&mut dyn std::fmt::Write>)
}
/// Pretty-print all specified inputs to a specified writer.
pub fn print_with_writer<W: std::fmt::Write>(&mut self, writer: Option<W>) -> Result<bool> {
let highlight_lines = std::mem::take(&mut self.highlighted_lines);
self.config.highlighted_lines = HighlightedLineRanges(LineRanges::from(highlight_lines));
self.config.term_width = self
.term_width
.unwrap_or_else(|| Term::stdout().size().1 as usize);
self.config.style_components.clear();
if self.active_style_components.grid {
self.config.style_components.insert(StyleComponent::Grid);
}
if self.active_style_components.rule {
self.config.style_components.insert(StyleComponent::Rule);
}
if self.active_style_components.header_filename {
self.config
.style_components
.insert(StyleComponent::HeaderFilename);
}
if self.active_style_components.line_numbers {
self.config
.style_components
.insert(StyleComponent::LineNumbers);
}
if self.active_style_components.snip {
self.config.style_components.insert(StyleComponent::Snip);
}
#[cfg(feature = "git")]
if self.active_style_components.vcs_modification_markers {
self.config.style_components.insert(StyleComponent::Changes);
}
// Collect the inputs to print
let inputs = std::mem::take(&mut self.inputs);
// Run the controller
let controller = Controller::new(&self.config, &self.assets);
// If writer is provided, pass it to the controller, otherwise pass None
if let Some(mut w) = writer {
controller.run(
inputs.into_iter().map(|i| i.into()).collect(),
Some(&mut OutputHandle::FmtWrite(&mut w)),
)
} else {
controller.run(inputs.into_iter().map(|i| i.into()).collect(), None)
}
}
}
impl Default for PrettyPrinter<'_> {
fn default() -> Self {
Self::new()
}
}
/// An input source for the pretty printer.
pub struct Input<'a> {
input: input::Input<'a>,
}
impl<'a> Input<'a> {
/// A new input from a reader.
pub fn from_reader<R: Read + 'a>(reader: R) -> Self {
input::Input::from_reader(Box::new(reader)).into()
}
/// A new input from a file.
pub fn from_file(path: impl AsRef<Path>) -> Self {
input::Input::ordinary_file(path).into()
}
/// A new input from bytes.
pub fn from_bytes(bytes: &'a [u8]) -> Self {
Input::from_reader(bytes)
}
/// A new input from STDIN.
pub fn from_stdin() -> Self {
input::Input::stdin().into()
}
/// The filename of the input.
/// This affects syntax detection and changes the default header title.
pub fn name(mut self, name: impl AsRef<Path>) -> Self {
self.input = self.input.with_name(Some(name));
self
}
/// The description for the type of input (e.g. "File")
pub fn kind(mut self, kind: impl Into<String>) -> Self {
let kind = kind.into();
self.input
.description_mut()
.set_kind(if kind.is_empty() { None } else { Some(kind) });
self
}
/// The title for the input (e.g. "Descriptive title")
/// This defaults to the file name.
pub fn title(mut self, title: impl Into<String>) -> Self {
self.input.description_mut().set_title(Some(title.into()));
self
}
}
impl<'a> From<input::Input<'a>> for Input<'a> {
fn from(input: input::Input<'a>) -> Self {
Self { input }
}
}
impl<'a> From<Input<'a>> for input::Input<'a> {
fn from(Input { input }: Input<'a>) -> Self {
input
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/terminal.rs | src/terminal.rs | use nu_ansi_term::Color::{self, Fixed, Rgb};
use nu_ansi_term::{self, Style};
use syntect::highlighting::{self, FontStyle};
pub fn to_ansi_color(color: highlighting::Color, true_color: bool) -> Option<nu_ansi_term::Color> {
if color.a == 0 {
// Themes can specify one of the user-configurable terminal colors by
// encoding them as #RRGGBBAA with AA set to 00 (transparent) and RR set
// to the 8-bit color palette number. The built-in themes ansi, base16,
// and base16-256 use this.
Some(match color.r {
// For the first 8 colors, use the Color enum to produce ANSI escape
// sequences using codes 30-37 (foreground) and 40-47 (background).
// For example, red foreground is \x1b[31m. This works on terminals
// without 256-color support.
0x00 => Color::Black,
0x01 => Color::Red,
0x02 => Color::Green,
0x03 => Color::Yellow,
0x04 => Color::Blue,
0x05 => Color::Purple,
0x06 => Color::Cyan,
0x07 => Color::White,
// For all other colors, use Fixed to produce escape sequences using
// codes 38;5 (foreground) and 48;5 (background). For example,
// bright red foreground is \x1b[38;5;9m. This only works on
// terminals with 256-color support.
//
// TODO: When ansi_term adds support for bright variants using codes
// 90-97 (foreground) and 100-107 (background), we should use those
// for values 0x08 to 0x0f and only use Fixed for 0x10 to 0xff.
n => Fixed(n),
})
} else if color.a == 1 {
// Themes can specify the terminal's default foreground/background color
// (i.e. no escape sequence) using the encoding #RRGGBBAA with AA set to
// 01. The built-in theme ansi uses this.
None
} else if true_color {
Some(Rgb(color.r, color.g, color.b))
} else {
Some(Fixed(ansi_colours::ansi256_from_rgb((
color.r, color.g, color.b,
))))
}
}
pub fn as_terminal_escaped(
style: highlighting::Style,
text: &str,
true_color: bool,
colored: bool,
italics: bool,
background_color: Option<highlighting::Color>,
) -> String {
if text.is_empty() {
return text.to_string();
}
let mut style = if !colored {
Style::default()
} else {
let mut color = Style {
foreground: to_ansi_color(style.foreground, true_color),
..Style::default()
};
if style.font_style.contains(FontStyle::BOLD) {
color = color.bold();
}
if style.font_style.contains(FontStyle::UNDERLINE) {
color = color.underline();
}
if italics && style.font_style.contains(FontStyle::ITALIC) {
color = color.italic();
}
color
};
style.background = background_color.and_then(|c| to_ansi_color(c, true_color));
style.paint(text).to_string()
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/macros.rs | src/macros.rs | #[macro_export]
macro_rules! bat_warning {
($($arg:tt)*) => ({
use nu_ansi_term::Color::Yellow;
eprintln!("{}: {}", Yellow.paint("[bat warning]"), format!($($arg)*));
})
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/style.rs | src/style.rs | use std::collections::HashSet;
use std::str::FromStr;
use crate::error::*;
#[non_exhaustive]
#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash)]
pub enum StyleComponent {
Auto,
#[cfg(feature = "git")]
Changes,
Grid,
Rule,
Header,
HeaderFilename,
HeaderFilesize,
LineNumbers,
Snip,
Full,
Default,
Plain,
}
impl StyleComponent {
pub fn components(self, interactive_terminal: bool) -> &'static [StyleComponent] {
match self {
StyleComponent::Auto => {
if interactive_terminal {
StyleComponent::Default.components(interactive_terminal)
} else {
StyleComponent::Plain.components(interactive_terminal)
}
}
#[cfg(feature = "git")]
StyleComponent::Changes => &[StyleComponent::Changes],
StyleComponent::Grid => &[StyleComponent::Grid],
StyleComponent::Rule => &[StyleComponent::Rule],
StyleComponent::Header => &[StyleComponent::HeaderFilename],
StyleComponent::HeaderFilename => &[StyleComponent::HeaderFilename],
StyleComponent::HeaderFilesize => &[StyleComponent::HeaderFilesize],
StyleComponent::LineNumbers => &[StyleComponent::LineNumbers],
StyleComponent::Snip => &[StyleComponent::Snip],
StyleComponent::Full => &[
#[cfg(feature = "git")]
StyleComponent::Changes,
StyleComponent::Grid,
StyleComponent::HeaderFilename,
StyleComponent::HeaderFilesize,
StyleComponent::LineNumbers,
StyleComponent::Snip,
],
StyleComponent::Default => &[
#[cfg(feature = "git")]
StyleComponent::Changes,
StyleComponent::Grid,
StyleComponent::HeaderFilename,
StyleComponent::LineNumbers,
StyleComponent::Snip,
],
StyleComponent::Plain => &[],
}
}
}
impl FromStr for StyleComponent {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"auto" => Ok(StyleComponent::Auto),
#[cfg(feature = "git")]
"changes" => Ok(StyleComponent::Changes),
"grid" => Ok(StyleComponent::Grid),
"rule" => Ok(StyleComponent::Rule),
"header" => Ok(StyleComponent::Header),
"header-filename" => Ok(StyleComponent::HeaderFilename),
"header-filesize" => Ok(StyleComponent::HeaderFilesize),
"numbers" => Ok(StyleComponent::LineNumbers),
"snip" => Ok(StyleComponent::Snip),
"full" => Ok(StyleComponent::Full),
"default" => Ok(StyleComponent::Default),
"plain" => Ok(StyleComponent::Plain),
_ => Err(format!("Unknown style '{s}'").into()),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct StyleComponents(pub HashSet<StyleComponent>);
impl StyleComponents {
pub fn new(components: &[StyleComponent]) -> StyleComponents {
StyleComponents(components.iter().cloned().collect())
}
#[cfg(feature = "git")]
pub fn changes(&self) -> bool {
self.0.contains(&StyleComponent::Changes)
}
pub fn grid(&self) -> bool {
self.0.contains(&StyleComponent::Grid)
}
pub fn rule(&self) -> bool {
self.0.contains(&StyleComponent::Rule)
}
pub fn header(&self) -> bool {
self.header_filename() || self.header_filesize()
}
pub fn header_filename(&self) -> bool {
self.0.contains(&StyleComponent::HeaderFilename)
}
pub fn header_filesize(&self) -> bool {
self.0.contains(&StyleComponent::HeaderFilesize)
}
pub fn numbers(&self) -> bool {
self.0.contains(&StyleComponent::LineNumbers)
}
pub fn snip(&self) -> bool {
self.0.contains(&StyleComponent::Snip)
}
pub fn plain(&self) -> bool {
self.0.iter().all(|c| c == &StyleComponent::Plain)
}
pub fn insert(&mut self, component: StyleComponent) {
self.0.insert(component);
}
pub fn clear(&mut self) {
self.0.clear();
}
}
#[derive(Debug, PartialEq)]
enum ComponentAction {
Override,
Add,
Remove,
}
impl ComponentAction {
fn extract_from_str(string: &str) -> (ComponentAction, &str) {
match string.chars().next() {
Some('-') => (ComponentAction::Remove, string.strip_prefix('-').unwrap()),
Some('+') => (ComponentAction::Add, string.strip_prefix('+').unwrap()),
_ => (ComponentAction::Override, string),
}
}
}
/// A list of [StyleComponent] that can be parsed from a string.
pub struct StyleComponentList(Vec<(ComponentAction, StyleComponent)>);
impl StyleComponentList {
fn expand_into(&self, components: &mut HashSet<StyleComponent>, interactive_terminal: bool) {
for (action, component) in self.0.iter() {
let subcomponents = component.components(interactive_terminal);
use ComponentAction::*;
match action {
Override | Add => components.extend(subcomponents),
Remove => components.retain(|c| !subcomponents.contains(c)),
}
}
}
/// Returns `true` if any component in the list was not prefixed with `+` or `-`.
fn contains_override(&self) -> bool {
self.0.iter().any(|(a, _)| *a == ComponentAction::Override)
}
/// Combines multiple [StyleComponentList]s into a single [StyleComponents] set.
///
/// ## Precedence
/// The most recent list will take precedence and override all previous lists
/// unless it only contains components prefixed with `-` or `+`. When this
/// happens, the list's components will be merged into the previous list.
///
/// ## Example
/// ```text
/// [numbers,grid] + [header,changes] -> [header,changes]
/// [numbers,grid] + [+header,-grid] -> [numbers,header]
/// ```
///
/// ## Parameters
/// - `with_default`: If true, the styles lists will build upon the StyleComponent::Auto style.
pub fn to_components(
lists: impl IntoIterator<Item = StyleComponentList>,
interactive_terminal: bool,
with_default: bool,
) -> StyleComponents {
let mut components: HashSet<StyleComponent> = HashSet::new();
if with_default {
components.extend(StyleComponent::Auto.components(interactive_terminal))
}
StyleComponents(lists.into_iter().fold(components, |mut components, list| {
if list.contains_override() {
components.clear();
}
list.expand_into(&mut components, interactive_terminal);
components
}))
}
}
impl Default for StyleComponentList {
fn default() -> Self {
StyleComponentList(vec![(ComponentAction::Override, StyleComponent::Default)])
}
}
impl FromStr for StyleComponentList {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
Ok(StyleComponentList(
s.split(",")
.map(ComponentAction::extract_from_str) // If the component starts with "-", it's meant to be removed
.map(|(a, s)| Ok((a, StyleComponent::from_str(s)?)))
.collect::<Result<Vec<(ComponentAction, StyleComponent)>>>()?,
))
}
}
#[cfg(test)]
mod test {
use std::collections::HashSet;
use std::str::FromStr;
use super::ComponentAction::*;
use super::StyleComponent;
use super::StyleComponent::*;
use super::StyleComponentList;
#[test]
pub fn style_component_list_parse() {
assert_eq!(
StyleComponentList::from_str("grid,+numbers,snip,-snip,header")
.expect("no error")
.0,
vec![
(Override, Grid),
(Add, LineNumbers),
(Override, Snip),
(Remove, Snip),
(Override, Header),
]
);
assert!(StyleComponentList::from_str("not-a-component").is_err());
assert!(StyleComponentList::from_str("grid,not-a-component").is_err());
assert!(StyleComponentList::from_str("numbers,-not-a-component").is_err());
}
#[test]
pub fn style_component_list_to_components() {
assert_eq!(
StyleComponentList::to_components(
vec![StyleComponentList::from_str("grid,numbers").expect("no error")],
false,
false
)
.0,
HashSet::from([Grid, LineNumbers])
);
}
#[test]
pub fn style_component_list_to_components_removes_negated() {
assert_eq!(
StyleComponentList::to_components(
vec![StyleComponentList::from_str("grid,numbers,-grid").expect("no error")],
false,
false
)
.0,
HashSet::from([LineNumbers])
);
}
#[test]
pub fn style_component_list_to_components_expands_subcomponents() {
assert_eq!(
StyleComponentList::to_components(
vec![StyleComponentList::from_str("full").expect("no error")],
false,
false
)
.0,
HashSet::from_iter(Full.components(true).to_owned())
);
}
#[test]
pub fn style_component_list_expand_negates_subcomponents() {
assert!(!StyleComponentList::to_components(
vec![StyleComponentList::from_str("full,-numbers").expect("no error")],
true,
false
)
.numbers());
}
#[test]
pub fn style_component_list_to_components_precedence_overrides_previous_lists() {
assert_eq!(
StyleComponentList::to_components(
vec![
StyleComponentList::from_str("grid").expect("no error"),
StyleComponentList::from_str("numbers").expect("no error"),
],
false,
false
)
.0,
HashSet::from([LineNumbers])
);
}
#[test]
pub fn style_component_list_to_components_precedence_merges_previous_lists() {
assert_eq!(
StyleComponentList::to_components(
vec![
StyleComponentList::from_str("grid,header").expect("no error"),
StyleComponentList::from_str("-grid").expect("no error"),
StyleComponentList::from_str("+numbers").expect("no error"),
],
false,
false
)
.0,
HashSet::from([HeaderFilename, LineNumbers])
);
}
#[test]
pub fn style_component_list_default_builds_on_auto() {
assert_eq!(
StyleComponentList::to_components(
vec![StyleComponentList::from_str("-numbers").expect("no error"),],
true,
true
)
.0,
{
let mut expected: HashSet<StyleComponent> = HashSet::new();
expected.extend(Auto.components(true));
expected.remove(&LineNumbers);
expected
}
);
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/vscreen.rs | src/vscreen.rs | use std::{
fmt::{Display, Formatter},
iter::Peekable,
str::CharIndices,
};
// Wrapper to avoid unnecessary branching when input doesn't have ANSI escape sequences.
pub struct AnsiStyle {
attributes: Option<Attributes>,
}
impl AnsiStyle {
pub fn new() -> Self {
AnsiStyle { attributes: None }
}
pub fn update(&mut self, sequence: EscapeSequence) -> bool {
match &mut self.attributes {
Some(a) => a.update(sequence),
None => {
self.attributes = Some(Attributes::new());
self.attributes.as_mut().unwrap().update(sequence)
}
}
}
pub fn to_reset_sequence(&self) -> String {
match self.attributes {
Some(ref a) => a.to_reset_sequence(),
None => String::new(),
}
}
}
impl Display for AnsiStyle {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self.attributes {
Some(ref a) => a.fmt(f),
None => Ok(()),
}
}
}
struct Attributes {
has_sgr_sequences: bool,
foreground: String,
background: String,
underlined: String,
/// The character set to use.
/// REGEX: `\^[()][AB0-3]`
charset: String,
/// A buffer for unknown sequences.
unknown_buffer: String,
/// ON: ^[1m
/// OFF: ^[22m
bold: String,
/// ON: ^[2m
/// OFF: ^[22m
dim: String,
/// ON: ^[4m
/// OFF: ^[24m
underline: String,
/// ON: ^[3m
/// OFF: ^[23m
italic: String,
/// ON: ^[9m
/// OFF: ^[29m
strike: String,
/// The hyperlink sequence.
/// FORMAT: \x1B]8;{ID};{URL}\e\\
///
/// `\e\\` may be replaced with BEL `\x07`.
/// Setting both {ID} and {URL} to an empty string represents no hyperlink.
hyperlink: String,
}
impl Attributes {
pub fn new() -> Self {
Attributes {
has_sgr_sequences: false,
foreground: "".to_owned(),
background: "".to_owned(),
underlined: "".to_owned(),
charset: "".to_owned(),
unknown_buffer: "".to_owned(),
bold: "".to_owned(),
dim: "".to_owned(),
underline: "".to_owned(),
italic: "".to_owned(),
strike: "".to_owned(),
hyperlink: "".to_owned(),
}
}
/// Update the attributes with an escape sequence.
/// Returns `false` if the sequence is unsupported.
pub fn update(&mut self, sequence: EscapeSequence) -> bool {
use EscapeSequence::*;
match sequence {
Text(_) => return false,
Unknown(_) => { /* defer to update_with_unsupported */ }
OSC {
raw_sequence,
command,
..
} => {
if command.starts_with("8;") {
return self.update_with_hyperlink(raw_sequence);
}
/* defer to update_with_unsupported */
}
CSI {
final_byte,
parameters,
..
} => {
match final_byte {
"m" => return self.update_with_sgr(parameters),
_ => {
// NOTE(eth-p): We might want to ignore these, since they involve cursor or buffer manipulation.
/* defer to update_with_unsupported */
}
}
}
NF { nf_sequence, .. } => {
let mut iter = nf_sequence.chars();
match iter.next() {
Some('(') => return self.update_with_charset('(', iter),
Some(')') => return self.update_with_charset(')', iter),
_ => { /* defer to update_with_unsupported */ }
}
}
}
self.update_with_unsupported(sequence.raw())
}
fn sgr_reset(&mut self) {
self.has_sgr_sequences = false;
self.foreground.clear();
self.background.clear();
self.underlined.clear();
self.bold.clear();
self.dim.clear();
self.underline.clear();
self.italic.clear();
self.strike.clear();
}
fn update_with_sgr(&mut self, parameters: &str) -> bool {
let mut iter = parameters
.split(';')
.map(|p| if p.is_empty() { "0" } else { p })
.map(|p| p.parse::<u16>())
.map(|p| p.unwrap_or(0)); // Treat errors as 0.
self.has_sgr_sequences = true;
while let Some(p) = iter.next() {
match p {
0 => self.sgr_reset(),
1 => self.bold = "\x1B[1m".to_owned(),
2 => self.dim = "\x1B[2m".to_owned(),
3 => self.italic = "\x1B[3m".to_owned(),
4 => self.underline = "\x1B[4m".to_owned(),
23 => self.italic.clear(),
24 => self.underline.clear(),
22 => {
self.bold.clear();
self.dim.clear();
}
30..=39 => self.foreground = Self::parse_color(p, &mut iter),
40..=49 => self.background = Self::parse_color(p, &mut iter),
58..=59 => self.underlined = Self::parse_color(p, &mut iter),
90..=97 => self.foreground = Self::parse_color(p, &mut iter),
100..=107 => self.background = Self::parse_color(p, &mut iter),
_ => {
// Unsupported SGR sequence.
// Be compatible and pretend one just wasn't was provided.
}
}
}
true
}
fn update_with_unsupported(&mut self, sequence: &str) -> bool {
self.unknown_buffer.push_str(sequence);
false
}
fn update_with_hyperlink(&mut self, sequence: &str) -> bool {
if sequence == "8;;" {
// Empty hyperlink ID and HREF -> end of hyperlink.
self.hyperlink.clear();
} else {
self.hyperlink.clear();
self.hyperlink.push_str(sequence);
}
true
}
fn update_with_charset(&mut self, kind: char, set: impl Iterator<Item = char>) -> bool {
self.charset = format!("\x1B{kind}{}", set.take(1).collect::<String>());
true
}
fn parse_color(color: u16, parameters: &mut dyn Iterator<Item = u16>) -> String {
match color % 10 {
8 => match parameters.next() {
Some(5) /* 256-color */ => format!("\x1B[{color};5;{}m", join(";", 1, parameters)),
Some(2) /* 24-bit color */ => format!("\x1B[{color};2;{}m", join(";", 3, parameters)),
Some(c) => format!("\x1B[{color};{c}m"),
_ => "".to_owned(),
},
9 => "".to_owned(),
_ => format!("\x1B[{color}m"),
}
}
/// Gets an ANSI escape sequence to reset all the known attributes.
pub fn to_reset_sequence(&self) -> String {
let mut buf = String::with_capacity(17);
// TODO: Enable me in a later pull request.
// if self.has_sgr_sequences {
// buf.push_str("\x1B[m");
// }
if !self.hyperlink.is_empty() {
buf.push_str("\x1B]8;;\x1B\\"); // Disable hyperlink.
}
// TODO: Enable me in a later pull request.
// if !self.charset.is_empty() {
// // https://espterm.github.io/docs/VT100%20escape%20codes.html
// buf.push_str("\x1B(B\x1B)B"); // setusg0 and setusg1
// }
buf
}
}
impl Display for Attributes {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}{}{}{}{}{}{}{}{}{}",
self.foreground,
self.background,
self.underlined,
self.charset,
self.bold,
self.dim,
self.underline,
self.italic,
self.strike,
self.hyperlink,
)
}
}
fn join(
delimiter: &str,
limit: usize,
iterator: &mut dyn Iterator<Item = impl ToString>,
) -> String {
iterator
.take(limit)
.map(|i| i.to_string())
.collect::<Vec<String>>()
.join(delimiter)
}
/// A range of indices for a raw ANSI escape sequence.
#[derive(Debug, PartialEq)]
pub enum EscapeSequenceOffsets {
Text {
start: usize,
end: usize,
},
Unknown {
start: usize,
end: usize,
},
#[allow(clippy::upper_case_acronyms)]
NF {
// https://en.wikipedia.org/wiki/ANSI_escape_code#nF_Escape_sequences
start_sequence: usize,
start: usize,
end: usize,
},
#[allow(clippy::upper_case_acronyms)]
OSC {
// https://en.wikipedia.org/wiki/ANSI_escape_code#OSC_(Operating_System_Command)_sequences
start_sequence: usize,
start_command: usize,
start_terminator: usize,
end: usize,
},
#[allow(clippy::upper_case_acronyms)]
CSI {
// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences
start_sequence: usize,
start_parameters: usize,
start_intermediates: usize,
start_final_byte: usize,
end: usize,
},
}
impl EscapeSequenceOffsets {
/// Returns the byte-index of the first character in the escape sequence.
pub fn index_of_start(&self) -> usize {
use EscapeSequenceOffsets::*;
match self {
Text { start, .. } => *start,
Unknown { start, .. } => *start,
NF { start_sequence, .. } => *start_sequence,
OSC { start_sequence, .. } => *start_sequence,
CSI { start_sequence, .. } => *start_sequence,
}
}
/// Returns the byte-index past the last character in the escape sequence.
pub fn index_past_end(&self) -> usize {
use EscapeSequenceOffsets::*;
match self {
Text { end, .. } => *end,
Unknown { end, .. } => *end,
NF { end, .. } => *end,
OSC { end, .. } => *end,
CSI { end, .. } => *end,
}
}
}
/// An iterator over the offsets of ANSI/VT escape sequences within a string.
///
/// ## Example
///
/// ```ignore
/// let iter = EscapeSequenceOffsetsIterator::new("\x1B[33mThis is yellow text.\x1B[m");
/// ```
pub struct EscapeSequenceOffsetsIterator<'a> {
text: &'a str,
chars: Peekable<CharIndices<'a>>,
}
impl<'a> EscapeSequenceOffsetsIterator<'a> {
pub fn new(text: &'a str) -> EscapeSequenceOffsetsIterator<'a> {
EscapeSequenceOffsetsIterator {
text,
chars: text.char_indices().peekable(),
}
}
/// Takes values from the iterator while the predicate returns true.
/// If the predicate returns false, that value is left.
fn chars_take_while(&mut self, pred: impl Fn(char) -> bool) -> Option<(usize, usize)> {
self.chars.peek()?;
let start = self.chars.peek().unwrap().0;
let mut end: usize = start;
while let Some((i, c)) = self.chars.peek() {
if !pred(*c) {
break;
}
end = *i + c.len_utf8();
self.chars.next();
}
Some((start, end))
}
fn next_text(&mut self) -> Option<EscapeSequenceOffsets> {
self.chars_take_while(|c| c != '\x1B')
.map(|(start, end)| EscapeSequenceOffsets::Text { start, end })
}
fn next_sequence(&mut self) -> Option<EscapeSequenceOffsets> {
let (start_sequence, c) = self.chars.next().expect("to not be finished");
match self.chars.peek() {
None => Some(EscapeSequenceOffsets::Unknown {
start: start_sequence,
end: start_sequence + c.len_utf8(),
}),
Some((_, ']')) => self.next_osc(start_sequence),
Some((_, '[')) => self.next_csi(start_sequence),
Some((i, c)) => match c {
'\x20'..='\x2F' => self.next_nf(start_sequence),
c => Some(EscapeSequenceOffsets::Unknown {
start: start_sequence,
end: i + c.len_utf8(),
}),
},
}
}
fn next_osc(&mut self, start_sequence: usize) -> Option<EscapeSequenceOffsets> {
let (osc_open_index, osc_open_char) = self.chars.next().expect("to not be finished");
debug_assert_eq!(osc_open_char, ']');
let mut start_terminator: usize;
let mut end_sequence: usize;
loop {
match self.chars_take_while(|c| !matches!(c, '\x07' | '\x1B')) {
None => {
start_terminator = self.text.len();
end_sequence = start_terminator;
break;
}
Some((_, end)) => {
start_terminator = end;
end_sequence = end;
}
}
match self.chars.next() {
Some((ti, '\x07')) => {
end_sequence = ti + '\x07'.len_utf8();
break;
}
Some((ti, '\x1B')) => {
match self.chars.next() {
Some((i, '\\')) => {
end_sequence = i + '\\'.len_utf8();
break;
}
None => {
end_sequence = ti + '\x1B'.len_utf8();
break;
}
_ => {
// Repeat, since `\\`(anything) isn't a valid ST.
}
}
}
None => {
// Prematurely ends.
break;
}
Some((_, tc)) => {
panic!("this should not be reached: char {tc:?}")
}
}
}
Some(EscapeSequenceOffsets::OSC {
start_sequence,
start_command: osc_open_index + osc_open_char.len_utf8(),
start_terminator,
end: end_sequence,
})
}
fn next_csi(&mut self, start_sequence: usize) -> Option<EscapeSequenceOffsets> {
let (csi_open_index, csi_open_char) = self.chars.next().expect("to not be finished");
debug_assert_eq!(csi_open_char, '[');
let start_parameters: usize = csi_open_index + csi_open_char.len_utf8();
// Keep iterating while within the range of `0x30-0x3F`.
let mut start_intermediates: usize = start_parameters;
if let Some((_, end)) = self.chars_take_while(|c| matches!(c, '\x30'..='\x3F')) {
start_intermediates = end;
}
// Keep iterating while within the range of `0x20-0x2F`.
let mut start_final_byte: usize = start_intermediates;
if let Some((_, end)) = self.chars_take_while(|c| matches!(c, '\x20'..='\x2F')) {
start_final_byte = end;
}
// Take the last char.
let end_of_sequence = match self.chars.next() {
None => start_final_byte,
Some((i, c)) => i + c.len_utf8(),
};
Some(EscapeSequenceOffsets::CSI {
start_sequence,
start_parameters,
start_intermediates,
start_final_byte,
end: end_of_sequence,
})
}
fn next_nf(&mut self, start_sequence: usize) -> Option<EscapeSequenceOffsets> {
let (nf_open_index, nf_open_char) = self.chars.next().expect("to not be finished");
debug_assert!(matches!(nf_open_char, '\x20'..='\x2F'));
let start: usize = nf_open_index;
let mut end: usize = start;
// Keep iterating while within the range of `0x20-0x2F`.
match self.chars_take_while(|c| matches!(c, '\x20'..='\x2F')) {
Some((_, i)) => end = i,
None => {
return Some(EscapeSequenceOffsets::NF {
start_sequence,
start,
end,
})
}
}
// Get the final byte.
if let Some((i, c)) = self.chars.next() {
end = i + c.len_utf8()
}
Some(EscapeSequenceOffsets::NF {
start_sequence,
start,
end,
})
}
}
impl Iterator for EscapeSequenceOffsetsIterator<'_> {
type Item = EscapeSequenceOffsets;
fn next(&mut self) -> Option<Self::Item> {
match self.chars.peek() {
Some((_, '\x1B')) => self.next_sequence(),
Some((_, _)) => self.next_text(),
None => None,
}
}
}
/// An iterator over ANSI/VT escape sequences within a string.
///
/// ## Example
///
/// ```ignore
/// let iter = EscapeSequenceIterator::new("\x1B[33mThis is yellow text.\x1B[m");
/// ```
pub struct EscapeSequenceIterator<'a> {
text: &'a str,
offset_iter: EscapeSequenceOffsetsIterator<'a>,
}
impl<'a> EscapeSequenceIterator<'a> {
pub fn new(text: &'a str) -> EscapeSequenceIterator<'a> {
EscapeSequenceIterator {
text,
offset_iter: EscapeSequenceOffsetsIterator::new(text),
}
}
}
impl<'a> Iterator for EscapeSequenceIterator<'a> {
type Item = EscapeSequence<'a>;
fn next(&mut self) -> Option<Self::Item> {
use EscapeSequenceOffsets::*;
self.offset_iter.next().map(|offsets| match offsets {
Unknown { start, end } => EscapeSequence::Unknown(&self.text[start..end]),
Text { start, end } => EscapeSequence::Text(&self.text[start..end]),
NF {
start_sequence,
start,
end,
} => EscapeSequence::NF {
raw_sequence: &self.text[start_sequence..end],
nf_sequence: &self.text[start..end],
},
OSC {
start_sequence,
start_command,
start_terminator,
end,
} => EscapeSequence::OSC {
raw_sequence: &self.text[start_sequence..end],
command: &self.text[start_command..start_terminator],
terminator: &self.text[start_terminator..end],
},
CSI {
start_sequence,
start_parameters,
start_intermediates,
start_final_byte,
end,
} => EscapeSequence::CSI {
raw_sequence: &self.text[start_sequence..end],
parameters: &self.text[start_parameters..start_intermediates],
intermediates: &self.text[start_intermediates..start_final_byte],
final_byte: &self.text[start_final_byte..end],
},
})
}
}
/// A parsed ANSI/VT100 escape sequence.
#[derive(Debug, PartialEq)]
pub enum EscapeSequence<'a> {
Text(&'a str),
Unknown(&'a str),
#[allow(clippy::upper_case_acronyms)]
NF {
raw_sequence: &'a str,
nf_sequence: &'a str,
},
#[allow(clippy::upper_case_acronyms)]
OSC {
raw_sequence: &'a str,
command: &'a str,
terminator: &'a str,
},
#[allow(clippy::upper_case_acronyms)]
CSI {
raw_sequence: &'a str,
parameters: &'a str,
intermediates: &'a str,
final_byte: &'a str,
},
}
impl<'a> EscapeSequence<'a> {
pub fn raw(&self) -> &'a str {
use EscapeSequence::*;
match *self {
Text(raw) => raw,
Unknown(raw) => raw,
NF { raw_sequence, .. } => raw_sequence,
OSC { raw_sequence, .. } => raw_sequence,
CSI { raw_sequence, .. } => raw_sequence,
}
}
}
#[cfg(test)]
mod tests {
use crate::vscreen::{
EscapeSequence, EscapeSequenceIterator, EscapeSequenceOffsets,
EscapeSequenceOffsetsIterator,
};
#[test]
fn test_escape_sequence_offsets_iterator_parses_text() {
let mut iter = EscapeSequenceOffsetsIterator::new("text");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::Text { start: 0, end: 4 })
);
}
#[test]
fn test_escape_sequence_offsets_iterator_parses_text_stops_at_esc() {
let mut iter = EscapeSequenceOffsetsIterator::new("text\x1B[ming");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::Text { start: 0, end: 4 })
);
}
#[test]
fn test_escape_sequence_offsets_iterator_parses_osc_with_bel() {
let mut iter = EscapeSequenceOffsetsIterator::new("\x1B]abc\x07");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::OSC {
start_sequence: 0,
start_command: 2,
start_terminator: 5,
end: 6,
})
);
}
#[test]
fn test_escape_sequence_offsets_iterator_parses_osc_with_st() {
let mut iter = EscapeSequenceOffsetsIterator::new("\x1B]abc\x1B\\");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::OSC {
start_sequence: 0,
start_command: 2,
start_terminator: 5,
end: 7,
})
);
}
#[test]
fn test_escape_sequence_offsets_iterator_parses_osc_thats_broken() {
let mut iter = EscapeSequenceOffsetsIterator::new("\x1B]ab");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::OSC {
start_sequence: 0,
start_command: 2,
start_terminator: 4,
end: 4,
})
);
}
#[test]
fn test_escape_sequence_offsets_iterator_parses_csi() {
let mut iter = EscapeSequenceOffsetsIterator::new("\x1B[m");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::CSI {
start_sequence: 0,
start_parameters: 2,
start_intermediates: 2,
start_final_byte: 2,
end: 3
})
);
}
#[test]
fn test_escape_sequence_offsets_iterator_parses_csi_with_parameters() {
let mut iter = EscapeSequenceOffsetsIterator::new("\x1B[1;34m");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::CSI {
start_sequence: 0,
start_parameters: 2,
start_intermediates: 6,
start_final_byte: 6,
end: 7
})
);
}
#[test]
fn test_escape_sequence_offsets_iterator_parses_csi_with_intermediates() {
let mut iter = EscapeSequenceOffsetsIterator::new("\x1B[$m");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::CSI {
start_sequence: 0,
start_parameters: 2,
start_intermediates: 2,
start_final_byte: 3,
end: 4
})
);
}
#[test]
fn test_escape_sequence_offsets_iterator_parses_csi_with_parameters_and_intermediates() {
let mut iter = EscapeSequenceOffsetsIterator::new("\x1B[1$m");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::CSI {
start_sequence: 0,
start_parameters: 2,
start_intermediates: 3,
start_final_byte: 4,
end: 5
})
);
}
#[test]
fn test_escape_sequence_offsets_iterator_parses_csi_thats_broken() {
let mut iter = EscapeSequenceOffsetsIterator::new("\x1B[");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::CSI {
start_sequence: 0,
start_parameters: 2,
start_intermediates: 2,
start_final_byte: 2,
end: 2
})
);
let mut iter = EscapeSequenceOffsetsIterator::new("\x1B[1");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::CSI {
start_sequence: 0,
start_parameters: 2,
start_intermediates: 3,
start_final_byte: 3,
end: 3
})
);
let mut iter = EscapeSequenceOffsetsIterator::new("\x1B[1$");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::CSI {
start_sequence: 0,
start_parameters: 2,
start_intermediates: 3,
start_final_byte: 4,
end: 4
})
);
}
#[test]
fn test_escape_sequence_offsets_iterator_parses_nf() {
let mut iter = EscapeSequenceOffsetsIterator::new("\x1B($0");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::NF {
start_sequence: 0,
start: 1,
end: 4
})
);
}
#[test]
fn test_escape_sequence_offsets_iterator_parses_nf_thats_broken() {
let mut iter = EscapeSequenceOffsetsIterator::new("\x1B(");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::NF {
start_sequence: 0,
start: 1,
end: 1
})
);
}
#[test]
fn test_escape_sequence_offsets_iterator_iterates() {
let mut iter = EscapeSequenceOffsetsIterator::new("text\x1B[33m\x1B]OSC\x07\x1B(0");
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::Text { start: 0, end: 4 })
);
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::CSI {
start_sequence: 4,
start_parameters: 6,
start_intermediates: 8,
start_final_byte: 8,
end: 9
})
);
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::OSC {
start_sequence: 9,
start_command: 11,
start_terminator: 14,
end: 15
})
);
assert_eq!(
iter.next(),
Some(EscapeSequenceOffsets::NF {
start_sequence: 15,
start: 16,
end: 18
})
);
assert_eq!(iter.next(), None);
}
#[test]
fn test_escape_sequence_iterator_iterates() {
let mut iter = EscapeSequenceIterator::new("text\x1B[33m\x1B]OSC\x07\x1B]OSC\x1B\\\x1B(0");
assert_eq!(iter.next(), Some(EscapeSequence::Text("text")));
assert_eq!(
iter.next(),
Some(EscapeSequence::CSI {
raw_sequence: "\x1B[33m",
parameters: "33",
intermediates: "",
final_byte: "m",
})
);
assert_eq!(
iter.next(),
Some(EscapeSequence::OSC {
raw_sequence: "\x1B]OSC\x07",
command: "OSC",
terminator: "\x07",
})
);
assert_eq!(
iter.next(),
Some(EscapeSequence::OSC {
raw_sequence: "\x1B]OSC\x1B\\",
command: "OSC",
terminator: "\x1B\\",
})
);
assert_eq!(
iter.next(),
Some(EscapeSequence::NF {
raw_sequence: "\x1B(0",
nf_sequence: "(0",
})
);
assert_eq!(iter.next(), None);
}
#[test]
fn test_sgr_attributes_do_not_leak_into_wrong_field() {
let mut attrs = crate::vscreen::Attributes::new();
// Bold, Dim, Italic, Underline, Foreground, Background
attrs.update(EscapeSequence::CSI {
raw_sequence: "\x1B[1;2;3;4;31;41m",
parameters: "1;2;3;4;31;41",
intermediates: "",
final_byte: "m",
});
assert_eq!(attrs.bold, "\x1B[1m");
assert_eq!(attrs.dim, "\x1B[2m");
assert_eq!(attrs.italic, "\x1B[3m");
assert_eq!(attrs.underline, "\x1B[4m");
assert_eq!(attrs.foreground, "\x1B[31m");
assert_eq!(attrs.background, "\x1B[41m");
// Bold, Bright Foreground, Bright Background
attrs.sgr_reset();
attrs.update(EscapeSequence::CSI {
raw_sequence: "\x1B[1;94;103m",
parameters: "1;94;103",
intermediates: "",
final_byte: "m",
});
assert_eq!(attrs.bold, "\x1B[1m");
assert_eq!(attrs.foreground, "\x1B[94m");
assert_eq!(attrs.background, "\x1B[103m");
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/less.rs | src/less.rs | #![cfg(feature = "paging")]
use std::ffi::OsStr;
use std::process::Command;
#[derive(Debug, PartialEq, Eq)]
pub enum LessVersion {
Less(usize),
BusyBox,
}
pub fn retrieve_less_version(less_path: &dyn AsRef<OsStr>) -> Option<LessVersion> {
let resolved_path = grep_cli::resolve_binary(less_path.as_ref()).ok()?;
let cmd = Command::new(resolved_path).arg("--version").output().ok()?;
if cmd.status.success() {
parse_less_version(&cmd.stdout)
} else {
parse_less_version_busybox(&cmd.stderr)
}
}
fn parse_less_version(output: &[u8]) -> Option<LessVersion> {
if !output.starts_with(b"less ") {
return None;
}
let version = std::str::from_utf8(&output[5..]).ok()?;
let end = version.find(|c: char| !c.is_ascii_digit())?;
Some(LessVersion::Less(version[..end].parse::<usize>().ok()?))
}
fn parse_less_version_busybox(output: &[u8]) -> Option<LessVersion> {
match std::str::from_utf8(output) {
Ok(version) if version.contains("BusyBox ") => Some(LessVersion::BusyBox),
_ => None,
}
}
#[test]
fn test_parse_less_version_487() {
let output = b"less 487 (GNU regular expressions)
Copyright (C) 1984-2016 Mark Nudelman
less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less";
assert_eq!(Some(LessVersion::Less(487)), parse_less_version(output));
}
#[test]
fn test_parse_less_version_529() {
let output = b"less 529 (Spencer V8 regular expressions)
Copyright (C) 1984-2017 Mark Nudelman
less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less";
assert_eq!(Some(LessVersion::Less(529)), parse_less_version(output));
}
#[test]
fn test_parse_less_version_551() {
let output = b"less 551 (PCRE regular expressions)
Copyright (C) 1984-2019 Mark Nudelman
less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Home page: http://www.greenwoodsoftware.com/less";
assert_eq!(Some(LessVersion::Less(551)), parse_less_version(output));
}
#[test]
fn test_parse_less_version_581_2() {
let output = b"less 581.2 (PCRE2 regular expressions)
Copyright (C) 1984-2021 Mark Nudelman
less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Home page: https://greenwoodsoftware.com/less";
assert_eq!(Some(LessVersion::Less(581)), parse_less_version(output));
}
#[test]
fn test_parse_less_version_wrong_program() {
let output = b"more from util-linux 2.34";
assert_eq!(None, parse_less_version(output));
assert_eq!(None, parse_less_version_busybox(output));
}
#[test]
fn test_parse_less_version_busybox() {
let output = b"pkg/less: unrecognized option '--version'
BusyBox v1.35.0 (2022-04-21 10:38:11 EDT) multi-call binary.
Usage: less [-EFIMmNSRh~] [FILE]...
View FILE (or stdin) one screenful at a time
-E Quit once the end of a file is reached
-F Quit if entire file fits on first screen
-I Ignore case in all searches
-M,-m Display status line with line numbers
and percentage through the file
-N Prefix line number to each line
-S Truncate long lines
-R Remove color escape codes in input
-~ Suppress ~s displayed past EOF";
assert_eq!(
Some(LessVersion::BusyBox),
parse_less_version_busybox(output)
);
}
#[test]
fn test_parse_less_version_invalid_utf_8() {
let output = b"\xff";
assert_eq!(None, parse_less_version(output));
assert_eq!(None, parse_less_version_busybox(output));
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/lessopen.rs | src/lessopen.rs | use std::convert::TryFrom;
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader, Cursor, Read};
use std::path::PathBuf;
use std::process::{ExitStatus, Stdio};
use clircle::{Clircle, Identifier};
use execute::{shell, Execute};
use crate::error::Result;
use crate::{
bat_warning,
input::{Input, InputKind, InputReader, OpenedInput, OpenedInputKind},
};
/// Preprocess files and/or stdin using $LESSOPEN and $LESSCLOSE
pub(crate) struct LessOpenPreprocessor {
lessopen: String,
lessclose: Option<String>,
kind: LessOpenKind,
/// Whether or not data piped via stdin is to be preprocessed
preprocess_stdin: bool,
}
enum LessOpenKind {
Piped,
PipedIgnoreExitCode,
TempFile,
}
impl LessOpenPreprocessor {
/// Create a new instance of LessOpenPreprocessor
/// Will return Ok if and only if $LESSOPEN is set and contains exactly one %s
pub(crate) fn new() -> Result<LessOpenPreprocessor> {
let lessopen = env::var("LESSOPEN")?;
// Ignore $LESSOPEN if it does not contains exactly one %s
// Note that $LESSCLOSE has no such requirement
if lessopen.match_indices("%s").count() != 1 {
let error_msg = "LESSOPEN ignored: must contain exactly one %s";
bat_warning!("{error_msg}");
return Err(error_msg.into());
}
// "||" means pipe directly to bat without making a temporary file
// Also, if preprocessor output is empty and exit code is zero, use the empty output
// Otherwise, if output is empty and exit code is nonzero, use original file contents
let (kind, lessopen) = if lessopen.starts_with("||") {
(LessOpenKind::Piped, lessopen.chars().skip(2).collect())
// "|" means pipe as above, but ignore exit code and always use preprocessor output even if empty
} else if lessopen.starts_with('|') {
(
LessOpenKind::PipedIgnoreExitCode,
lessopen.chars().skip(1).collect(),
)
// If neither appear, write output to a temporary file and read from that
} else {
(LessOpenKind::TempFile, lessopen)
};
// "-" means that stdin is preprocessed along with files and may appear alongside "|" and "||"
let (stdin, lessopen) = if lessopen.starts_with('-') {
(true, lessopen.chars().skip(1).collect())
} else {
(false, lessopen)
};
Ok(Self {
lessopen,
lessclose: env::var("LESSCLOSE").ok(),
kind,
preprocess_stdin: stdin,
})
}
pub(crate) fn open<'a, R: BufRead + 'a>(
&self,
input: Input<'a>,
mut stdin: R,
stdout_identifier: Option<&Identifier>,
) -> Result<OpenedInput<'a>> {
let (lessopen_stdout, path_str, kind) = match input.kind {
InputKind::OrdinaryFile(ref path) => {
let path_str = match path.to_str() {
Some(str) => str,
None => return input.open(stdin, stdout_identifier),
};
let mut lessopen_command = shell(self.lessopen.replacen("%s", path_str, 1));
lessopen_command.stdout(Stdio::piped());
let lessopen_output = match lessopen_command.execute_output() {
Ok(output) => output,
Err(_) => return input.open(stdin, stdout_identifier),
};
if self.fall_back_to_original_file(&lessopen_output.stdout, lessopen_output.status)
{
return input.open(stdin, stdout_identifier);
}
(
lessopen_output.stdout,
path_str.to_string(),
OpenedInputKind::OrdinaryFile(path.to_path_buf()),
)
}
InputKind::StdIn => {
if self.preprocess_stdin {
if let Some(stdout) = stdout_identifier {
let input_identifier = Identifier::try_from(clircle::Stdio::Stdin)
.map_err(|e| format!("Stdin: Error identifying file: {e}"))?;
if stdout.surely_conflicts_with(&input_identifier) {
return Err("IO circle detected. The input from stdin is also an output. Aborting to avoid infinite loop.".into());
}
}
// stdin isn't Clone or AsRef<[u8]>, so move it into a cloneable buffer
// so the data can be used multiple times if necessary
// NOTE: stdin will be empty from this point onwards
let mut stdin_buffer = Vec::new();
stdin.read_to_end(&mut stdin_buffer)?;
let mut lessopen_command = shell(self.lessopen.replacen("%s", "-", 1));
lessopen_command.stdout(Stdio::piped());
let lessopen_output = match lessopen_command.execute_input_output(&stdin_buffer)
{
Ok(output) => output,
Err(_) => {
return input.open(Cursor::new(stdin_buffer), stdout_identifier);
}
};
if self
.fall_back_to_original_file(&lessopen_output.stdout, lessopen_output.status)
{
return input.open(Cursor::new(stdin_buffer), stdout_identifier);
}
(
lessopen_output.stdout,
"-".to_string(),
OpenedInputKind::StdIn,
)
} else {
return input.open(stdin, stdout_identifier);
}
}
InputKind::CustomReader(_) => {
return input.open(stdin, stdout_identifier);
}
};
Ok(OpenedInput {
kind,
reader: InputReader::new(BufReader::new(
if matches!(self.kind, LessOpenKind::TempFile) {
let lessopen_string = match String::from_utf8(lessopen_stdout) {
Ok(string) => string,
Err(_) => {
return input.open(stdin, stdout_identifier);
}
};
// Remove newline at end of temporary file path returned by $LESSOPEN
let stdout = match lessopen_string.strip_suffix("\n") {
Some(stripped) => stripped.to_owned(),
None => lessopen_string,
};
let file = match File::open(PathBuf::from(&stdout)) {
Ok(file) => file,
Err(_) => {
return input.open(stdin, stdout_identifier);
}
};
Preprocessed {
kind: PreprocessedKind::TempFile(file),
lessclose: self
.lessclose
.as_ref()
.map(|s| s.replacen("%s", &path_str, 1).replacen("%s", &stdout, 1)),
}
} else {
Preprocessed {
kind: PreprocessedKind::Piped(Cursor::new(lessopen_stdout)),
lessclose: self
.lessclose
.as_ref()
.map(|s| s.replacen("%s", &path_str, 1).replacen("%s", "-", 1)),
}
},
)),
metadata: input.metadata,
description: input.description,
})
}
fn fall_back_to_original_file(&self, lessopen_stdout: &[u8], exit_code: ExitStatus) -> bool {
lessopen_stdout.is_empty()
&& (!exit_code.success() || matches!(self.kind, LessOpenKind::PipedIgnoreExitCode))
}
#[cfg(test)]
/// For testing purposes only
/// Create an instance of LessOpenPreprocessor with specified valued for $LESSOPEN and $LESSCLOSE
fn mock_new(lessopen: Option<&str>, lessclose: Option<&str>) -> Result<LessOpenPreprocessor> {
if let Some(command) = lessopen {
env::set_var("LESSOPEN", command)
} else {
env::remove_var("LESSOPEN")
}
if let Some(command) = lessclose {
env::set_var("LESSCLOSE", command)
} else {
env::remove_var("LESSCLOSE")
}
Self::new()
}
}
enum PreprocessedKind {
Piped(Cursor<Vec<u8>>),
TempFile(File),
}
impl Read for PreprocessedKind {
fn read(&mut self, buf: &mut [u8]) -> std::result::Result<usize, std::io::Error> {
match self {
PreprocessedKind::Piped(data) => data.read(buf),
PreprocessedKind::TempFile(data) => data.read(buf),
}
}
}
pub struct Preprocessed {
kind: PreprocessedKind,
lessclose: Option<String>,
}
impl Read for Preprocessed {
fn read(&mut self, buf: &mut [u8]) -> std::result::Result<usize, std::io::Error> {
self.kind.read(buf)
}
}
impl Drop for Preprocessed {
fn drop(&mut self) {
if let Some(lessclose) = self.lessclose.clone() {
let mut lessclose_command = shell(lessclose);
let lessclose_output = match lessclose_command.execute_output() {
Ok(output) => output,
Err(_) => {
bat_warning!("failed to run $LESSCLOSE to clean up temporary file");
return;
}
};
if lessclose_output.status.success() {
bat_warning!("$LESSCLOSE exited with nonzero exit code",)
};
}
}
}
#[cfg(test)]
mod tests {
// All tests here are serial because they all involve reading and writing environment variables
// Running them in parallel causes these tests and some others to randomly fail
use serial_test::serial;
use super::*;
/// Reset environment variables after each test as a precaution
fn reset_env_vars() {
env::remove_var("LESSOPEN");
env::remove_var("LESSCLOSE");
}
#[test]
#[serial]
fn test_just_lessopen() -> Result<()> {
let preprocessor = LessOpenPreprocessor::mock_new(Some("|batpipe %s"), None)?;
assert_eq!(preprocessor.lessopen, "batpipe %s");
assert!(preprocessor.lessclose.is_none());
reset_env_vars();
Ok(())
}
#[test]
#[serial]
fn test_just_lessclose() -> Result<()> {
let preprocessor = LessOpenPreprocessor::mock_new(None, Some("lessclose.sh %s %s"));
assert!(preprocessor.is_err());
reset_env_vars();
Ok(())
}
#[test]
#[serial]
fn test_both_lessopen_and_lessclose() -> Result<()> {
let preprocessor =
LessOpenPreprocessor::mock_new(Some("lessopen.sh %s"), Some("lessclose.sh %s %s"))?;
assert_eq!(preprocessor.lessopen, "lessopen.sh %s");
assert_eq!(preprocessor.lessclose.unwrap(), "lessclose.sh %s %s");
reset_env_vars();
Ok(())
}
#[test]
#[serial]
fn test_lessopen_prefixes() -> Result<()> {
let preprocessor = LessOpenPreprocessor::mock_new(Some("batpipe %s"), None)?;
assert_eq!(preprocessor.lessopen, "batpipe %s");
assert!(matches!(preprocessor.kind, LessOpenKind::TempFile));
assert!(!preprocessor.preprocess_stdin);
let preprocessor = LessOpenPreprocessor::mock_new(Some("|batpipe %s"), None)?;
assert_eq!(preprocessor.lessopen, "batpipe %s");
assert!(matches!(
preprocessor.kind,
LessOpenKind::PipedIgnoreExitCode
));
assert!(!preprocessor.preprocess_stdin);
let preprocessor = LessOpenPreprocessor::mock_new(Some("||batpipe %s"), None)?;
assert_eq!(preprocessor.lessopen, "batpipe %s");
assert!(matches!(preprocessor.kind, LessOpenKind::Piped));
assert!(!preprocessor.preprocess_stdin);
let preprocessor = LessOpenPreprocessor::mock_new(Some("-batpipe %s"), None)?;
assert_eq!(preprocessor.lessopen, "batpipe %s");
assert!(matches!(preprocessor.kind, LessOpenKind::TempFile));
assert!(preprocessor.preprocess_stdin);
let preprocessor = LessOpenPreprocessor::mock_new(Some("|-batpipe %s"), None)?;
assert_eq!(preprocessor.lessopen, "batpipe %s");
assert!(matches!(
preprocessor.kind,
LessOpenKind::PipedIgnoreExitCode
));
assert!(preprocessor.preprocess_stdin);
let preprocessor = LessOpenPreprocessor::mock_new(Some("||-batpipe %s"), None)?;
assert_eq!(preprocessor.lessopen, "batpipe %s");
assert!(matches!(preprocessor.kind, LessOpenKind::Piped));
assert!(preprocessor.preprocess_stdin);
reset_env_vars();
Ok(())
}
#[test]
#[serial]
fn replace_part_of_argument() -> Result<()> {
let preprocessor =
LessOpenPreprocessor::mock_new(Some("|echo File:%s"), Some("echo File:%s Temp:%s"))?;
assert_eq!(preprocessor.lessopen, "echo File:%s");
assert_eq!(preprocessor.lessclose.unwrap(), "echo File:%s Temp:%s");
reset_env_vars();
Ok(())
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/assets.rs | src/assets.rs | use std::ffi::OsStr;
use std::fs;
use std::path::Path;
use once_cell::unsync::OnceCell;
use syntect::highlighting::Theme;
use syntect::parsing::{SyntaxReference, SyntaxSet};
use path_abs::PathAbs;
use crate::error::*;
use crate::input::{InputReader, OpenedInput};
use crate::syntax_mapping::ignored_suffixes::IgnoredSuffixes;
use crate::syntax_mapping::MappingTarget;
use crate::theme::{default_theme, ColorScheme};
use crate::{bat_warning, SyntaxMapping};
use lazy_theme_set::LazyThemeSet;
use serialized_syntax_set::*;
#[cfg(feature = "build-assets")]
pub use crate::assets::build_assets::*;
pub(crate) mod assets_metadata;
#[cfg(feature = "build-assets")]
mod build_assets;
mod lazy_theme_set;
mod serialized_syntax_set;
#[derive(Debug)]
pub struct HighlightingAssets {
syntax_set_cell: OnceCell<SyntaxSet>,
serialized_syntax_set: SerializedSyntaxSet,
theme_set: LazyThemeSet,
fallback_theme: Option<&'static str>,
}
#[derive(Debug)]
pub struct SyntaxReferenceInSet<'a> {
pub syntax: &'a SyntaxReference,
pub syntax_set: &'a SyntaxSet,
}
/// Lazy-loaded syntaxes are already compressed, and we don't want to compress
/// already compressed data.
pub(crate) const COMPRESS_SYNTAXES: bool = false;
/// We don't want to compress our [LazyThemeSet] since the lazy-loaded themes
/// within it are already compressed, and compressing another time just makes
/// performance suffer
pub(crate) const COMPRESS_THEMES: bool = false;
/// Compress for size of ~40 kB instead of ~200 kB without much difference in
/// performance due to lazy-loading
pub(crate) const COMPRESS_LAZY_THEMES: bool = true;
/// Compress for size of ~10 kB instead of ~120 kB
pub(crate) const COMPRESS_ACKNOWLEDGEMENTS: bool = true;
impl HighlightingAssets {
fn new(serialized_syntax_set: SerializedSyntaxSet, theme_set: LazyThemeSet) -> Self {
HighlightingAssets {
syntax_set_cell: OnceCell::new(),
serialized_syntax_set,
theme_set,
fallback_theme: None,
}
}
pub fn from_cache(cache_path: &Path) -> Result<Self> {
Ok(HighlightingAssets::new(
SerializedSyntaxSet::FromFile(cache_path.join("syntaxes.bin")),
asset_from_cache(&cache_path.join("themes.bin"), "theme set", COMPRESS_THEMES)?,
))
}
pub fn from_binary() -> Self {
HighlightingAssets::new(
SerializedSyntaxSet::FromBinary(get_serialized_integrated_syntaxset()),
get_integrated_themeset(),
)
}
pub fn set_fallback_theme(&mut self, theme: &'static str) {
self.fallback_theme = Some(theme);
}
/// Return the collection of syntect syntax definitions.
pub fn get_syntax_set(&self) -> Result<&SyntaxSet> {
self.syntax_set_cell
.get_or_try_init(|| self.serialized_syntax_set.deserialize())
}
/// Use [Self::get_syntaxes] instead
#[deprecated]
pub fn syntaxes(&self) -> &[SyntaxReference] {
self.get_syntax_set()
.expect(".syntaxes() is deprecated, use .get_syntaxes() instead")
.syntaxes()
}
pub fn get_syntaxes(&self) -> Result<&[SyntaxReference]> {
Ok(self.get_syntax_set()?.syntaxes())
}
fn get_theme_set(&self) -> &LazyThemeSet {
&self.theme_set
}
pub fn themes(&self) -> impl Iterator<Item = &str> {
self.get_theme_set().themes()
}
/// Use [Self::get_syntax_for_path] instead
#[deprecated]
pub fn syntax_for_file_name(
&self,
file_name: impl AsRef<Path>,
mapping: &SyntaxMapping,
) -> Option<&SyntaxReference> {
self.get_syntax_for_path(file_name, mapping)
.ok()
.map(|syntax_in_set| syntax_in_set.syntax)
}
/// Detect the syntax based on, in order:
/// 1. Syntax mappings with [MappingTarget::MapTo] and [MappingTarget::MapToUnknown]
/// (e.g. `/etc/profile` -> `Bourne Again Shell (bash)`)
/// 2. The file name (e.g. `Dockerfile`)
/// 3. Syntax mappings with [MappingTarget::MapExtensionToUnknown]
/// (e.g. `*.conf`)
/// 4. The file name extension (e.g. `.rs`)
///
/// When detecting syntax based on syntax mappings, the full path is taken
/// into account. When detecting syntax based on file name, no regard is
/// taken to the path of the file. Only the file name itself matters. When
/// detecting syntax based on file name extension, only the file name
/// extension itself matters.
///
/// Returns [Error::UndetectedSyntax] if it was not possible detect syntax
/// based on path/file name/extension (or if the path was mapped to
/// [MappingTarget::MapToUnknown] or [MappingTarget::MapExtensionToUnknown]).
/// In this case it is appropriate to fall back to other methods to detect
/// syntax. Such as using the contents of the first line of the file.
///
/// Returns [Error::UnknownSyntax] if a syntax mapping exist, but the mapped
/// syntax does not exist.
pub fn get_syntax_for_path(
&self,
path: impl AsRef<Path>,
mapping: &SyntaxMapping,
) -> Result<SyntaxReferenceInSet<'_>> {
let path = path.as_ref();
let syntax_match = mapping.get_syntax_for(path);
if let Some(MappingTarget::MapToUnknown) = syntax_match {
return Err(Error::UndetectedSyntax(path.to_string_lossy().into()));
}
if let Some(MappingTarget::MapTo(syntax_name)) = syntax_match {
return self
.find_syntax_by_token(syntax_name)?
.ok_or_else(|| Error::UnknownSyntax(syntax_name.to_owned()));
}
let file_name = path.file_name().unwrap_or_default();
match (
self.get_syntax_for_file_name(file_name, &mapping.ignored_suffixes)?,
syntax_match,
) {
(Some(syntax), _) => Ok(syntax),
(_, Some(MappingTarget::MapExtensionToUnknown)) => {
Err(Error::UndetectedSyntax(path.to_string_lossy().into()))
}
_ => self
.get_syntax_for_file_extension(file_name, &mapping.ignored_suffixes)?
.ok_or_else(|| Error::UndetectedSyntax(path.to_string_lossy().into())),
}
}
/// Look up a syntect theme by name.
pub fn get_theme(&self, theme: &str) -> &Theme {
match self.get_theme_set().get(theme) {
Some(theme) => theme,
None => {
if theme == "ansi-light" || theme == "ansi-dark" {
bat_warning!("Theme '{theme}' is deprecated, using 'ansi' instead.");
return self.get_theme("ansi");
}
if !theme.is_empty() {
bat_warning!("Unknown theme '{theme}', using default.")
}
self.get_theme_set()
.get(
self.fallback_theme
.unwrap_or_else(|| default_theme(ColorScheme::Dark)),
)
.expect("something is very wrong if the default theme is missing")
}
}
}
pub(crate) fn get_syntax(
&self,
language: Option<&str>,
input: &mut OpenedInput,
mapping: &SyntaxMapping,
) -> Result<SyntaxReferenceInSet<'_>> {
if let Some(language) = language {
let syntax_set = self.get_syntax_set()?;
return syntax_set
.find_syntax_by_token(language)
.map(|syntax| SyntaxReferenceInSet { syntax, syntax_set })
.ok_or_else(|| Error::UnknownSyntax(language.to_owned()));
}
let path = input.path();
let path_syntax = if let Some(path) = path {
self.get_syntax_for_path(
PathAbs::new(path).map_or_else(|_| path.to_owned(), |p| p.as_path().to_path_buf()),
mapping,
)
} else {
Err(Error::UndetectedSyntax("[unknown]".into()))
};
match path_syntax {
// If a path wasn't provided, or if path based syntax detection
// above failed, we fall back to first-line syntax detection.
Err(Error::UndetectedSyntax(path)) => self
.get_first_line_syntax(&mut input.reader)?
.ok_or(Error::UndetectedSyntax(path)),
_ => path_syntax,
}
}
pub(crate) fn find_syntax_by_name(
&self,
syntax_name: &str,
) -> Result<Option<SyntaxReferenceInSet<'_>>> {
let syntax_set = self.get_syntax_set()?;
Ok(syntax_set
.find_syntax_by_name(syntax_name)
.map(|syntax| SyntaxReferenceInSet { syntax, syntax_set }))
}
fn find_syntax_by_extension(
&self,
e: Option<&OsStr>,
) -> Result<Option<SyntaxReferenceInSet<'_>>> {
let syntax_set = self.get_syntax_set()?;
let extension = e.and_then(|x| x.to_str()).unwrap_or_default();
Ok(syntax_set
.find_syntax_by_extension(extension)
.map(|syntax| SyntaxReferenceInSet { syntax, syntax_set }))
}
fn find_syntax_by_token(&self, token: &str) -> Result<Option<SyntaxReferenceInSet<'_>>> {
let syntax_set = self.get_syntax_set()?;
Ok(syntax_set
.find_syntax_by_token(token)
.map(|syntax| SyntaxReferenceInSet { syntax, syntax_set }))
}
fn get_syntax_for_file_name(
&self,
file_name: &OsStr,
ignored_suffixes: &IgnoredSuffixes,
) -> Result<Option<SyntaxReferenceInSet<'_>>> {
let mut syntax = self.find_syntax_by_extension(Some(file_name))?;
if syntax.is_none() {
syntax =
ignored_suffixes.try_with_stripped_suffix(file_name, |stripped_file_name| {
// Note: recursion
self.get_syntax_for_file_name(stripped_file_name, ignored_suffixes)
})?;
}
Ok(syntax)
}
fn get_syntax_for_file_extension(
&self,
file_name: &OsStr,
ignored_suffixes: &IgnoredSuffixes,
) -> Result<Option<SyntaxReferenceInSet<'_>>> {
let mut syntax = self.find_syntax_by_extension(Path::new(file_name).extension())?;
if syntax.is_none() {
syntax =
ignored_suffixes.try_with_stripped_suffix(file_name, |stripped_file_name| {
// Note: recursion
self.get_syntax_for_file_extension(stripped_file_name, ignored_suffixes)
})?;
}
Ok(syntax)
}
fn get_first_line_syntax(
&self,
reader: &mut InputReader,
) -> Result<Option<SyntaxReferenceInSet<'_>>> {
let syntax_set = self.get_syntax_set()?;
Ok(String::from_utf8(reader.first_line.clone())
.ok()
.and_then(|l| {
// Strip UTF-8 BOM if present
let line = l.strip_prefix('\u{feff}').unwrap_or(&l);
syntax_set.find_syntax_by_first_line(line)
})
.map(|syntax| SyntaxReferenceInSet { syntax, syntax_set }))
}
}
pub(crate) fn get_serialized_integrated_syntaxset() -> &'static [u8] {
include_bytes!("../assets/syntaxes.bin")
}
pub(crate) fn get_integrated_themeset() -> LazyThemeSet {
from_binary(include_bytes!("../assets/themes.bin"), COMPRESS_THEMES)
}
pub fn get_acknowledgements() -> String {
from_binary(
include_bytes!("../assets/acknowledgements.bin"),
COMPRESS_ACKNOWLEDGEMENTS,
)
}
pub(crate) fn from_binary<T: serde::de::DeserializeOwned>(v: &[u8], compressed: bool) -> T {
asset_from_contents(v, "n/a", compressed)
.expect("data integrated in binary is never faulty, but make sure `compressed` is in sync!")
}
fn asset_from_contents<T: serde::de::DeserializeOwned>(
contents: &[u8],
description: &str,
compressed: bool,
) -> Result<T> {
if compressed {
bincode::deserialize_from(flate2::read::ZlibDecoder::new(contents))
} else {
bincode::deserialize_from(contents)
}
.map_err(|_| format!("Could not parse {description}").into())
}
fn asset_from_cache<T: serde::de::DeserializeOwned>(
path: &Path,
description: &str,
compressed: bool,
) -> Result<T> {
let contents = fs::read(path).map_err(|_| {
format!(
"Could not load cached {description} '{}'",
path.to_string_lossy()
)
})?;
asset_from_contents(&contents[..], description, compressed)
.map_err(|_| format!("Could not parse cached {description}").into())
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{BufReader, Write};
use tempfile::TempDir;
use crate::input::Input;
struct SyntaxDetectionTest<'a> {
assets: HighlightingAssets,
pub syntax_mapping: SyntaxMapping<'a>,
pub temp_dir: TempDir,
}
impl SyntaxDetectionTest<'_> {
fn new() -> Self {
SyntaxDetectionTest {
assets: HighlightingAssets::from_binary(),
syntax_mapping: SyntaxMapping::new(),
temp_dir: TempDir::new().expect("creation of temporary directory"),
}
}
fn get_syntax_name(
&self,
language: Option<&str>,
input: &mut OpenedInput,
mapping: &SyntaxMapping,
) -> String {
self.assets
.get_syntax(language, input, mapping)
.map(|syntax_in_set| syntax_in_set.syntax.name.clone())
.unwrap_or_else(|_| "!no syntax!".to_owned())
}
fn syntax_for_real_file_with_content_os(
&self,
file_name: &OsStr,
first_line: &str,
) -> String {
let file_path = self.temp_dir.path().join(file_name);
{
let mut temp_file = File::create(&file_path).unwrap();
writeln!(temp_file, "{first_line}").unwrap();
}
let input = Input::ordinary_file(&file_path);
let dummy_stdin: &[u8] = &[];
let mut opened_input = input.open(dummy_stdin, None).unwrap();
self.get_syntax_name(None, &mut opened_input, &self.syntax_mapping)
}
fn syntax_for_file_with_content_os(&self, file_name: &OsStr, first_line: &str) -> String {
let file_path = self.temp_dir.path().join(file_name);
let input = Input::from_reader(Box::new(BufReader::new(first_line.as_bytes())))
.with_name(Some(&file_path));
let dummy_stdin: &[u8] = &[];
let mut opened_input = input.open(dummy_stdin, None).unwrap();
self.get_syntax_name(None, &mut opened_input, &self.syntax_mapping)
}
#[cfg(unix)]
fn syntax_for_file_os(&self, file_name: &OsStr) -> String {
self.syntax_for_file_with_content_os(file_name, "")
}
fn syntax_for_file_with_content(&self, file_name: &str, first_line: &str) -> String {
self.syntax_for_file_with_content_os(OsStr::new(file_name), first_line)
}
fn syntax_for_file(&self, file_name: &str) -> String {
self.syntax_for_file_with_content(file_name, "")
}
fn syntax_for_stdin_with_content(&self, file_name: &str, content: &[u8]) -> String {
let input = Input::stdin().with_name(Some(file_name));
let mut opened_input = input.open(content, None).unwrap();
self.get_syntax_name(None, &mut opened_input, &self.syntax_mapping)
}
fn syntax_is_same_for_inputkinds(&self, file_name: &str, content: &str) -> bool {
let as_file = self.syntax_for_real_file_with_content_os(file_name.as_ref(), content);
let as_reader = self.syntax_for_file_with_content_os(file_name.as_ref(), content);
let consistent = as_file == as_reader;
// TODO: Compare StdIn somehow?
if !consistent {
eprintln!(
"Inconsistent syntax detection:\nFor File: {as_file}\nFor Reader: {as_reader}"
)
}
consistent
}
}
#[test]
fn syntax_detection_basic() {
let test = SyntaxDetectionTest::new();
assert_eq!(test.syntax_for_file("test.rs"), "Rust");
assert_eq!(test.syntax_for_file("test.cpp"), "C++");
assert_eq!(test.syntax_for_file("test.build"), "NAnt Build File");
assert_eq!(
test.syntax_for_file("PKGBUILD"),
"Bourne Again Shell (bash)"
);
assert_eq!(test.syntax_for_file(".bashrc"), "Bourne Again Shell (bash)");
assert_eq!(test.syntax_for_file("Makefile"), "Makefile");
}
#[cfg(unix)]
#[test]
fn syntax_detection_invalid_utf8() {
use std::os::unix::ffi::OsStrExt;
let test = SyntaxDetectionTest::new();
assert_eq!(
test.syntax_for_file_os(OsStr::from_bytes(b"invalid_\xFEutf8_filename.rs")),
"Rust"
);
}
#[test]
fn syntax_detection_same_for_inputkinds() {
let mut test = SyntaxDetectionTest::new();
test.syntax_mapping
.insert("*.myext", MappingTarget::MapTo("C"))
.ok();
test.syntax_mapping
.insert("MY_FILE", MappingTarget::MapTo("Markdown"))
.ok();
assert!(test.syntax_is_same_for_inputkinds("Test.md", ""));
assert!(test.syntax_is_same_for_inputkinds("Test.txt", "#!/bin/bash"));
assert!(test.syntax_is_same_for_inputkinds(".bashrc", ""));
assert!(test.syntax_is_same_for_inputkinds("test.h", ""));
assert!(test.syntax_is_same_for_inputkinds("test.js", "#!/bin/bash"));
assert!(test.syntax_is_same_for_inputkinds("test.myext", ""));
assert!(test.syntax_is_same_for_inputkinds("MY_FILE", ""));
assert!(test.syntax_is_same_for_inputkinds("MY_FILE", "<?php"));
}
#[test]
fn syntax_detection_well_defined_mapping_for_duplicate_extensions() {
let test = SyntaxDetectionTest::new();
assert_eq!(test.syntax_for_file("test.h"), "C++");
assert_eq!(test.syntax_for_file("test.sass"), "Sass");
assert_eq!(test.syntax_for_file("test.js"), "JavaScript (Babel)");
assert_eq!(test.syntax_for_file("test.fs"), "F#");
assert_eq!(test.syntax_for_file("test.v"), "Verilog");
}
#[test]
fn syntax_detection_first_line() {
let test = SyntaxDetectionTest::new();
assert_eq!(
test.syntax_for_file_with_content("my_script", "#!/bin/bash"),
"Bourne Again Shell (bash)"
);
assert_eq!(
test.syntax_for_file_with_content("build", "#!/bin/bash"),
"Bourne Again Shell (bash)"
);
assert_eq!(
test.syntax_for_file_with_content("my_script", "<?php"),
"PHP"
);
}
#[test]
fn syntax_detection_first_line_with_utf8_bom() {
let test = SyntaxDetectionTest::new();
// Test that XML files are detected correctly even with UTF-8 BOM
// The BOM should be stripped before first-line syntax detection
let xml_with_bom = "\u{feff}<?xml version=\"1.0\" encoding=\"utf-8\"?>";
assert_eq!(
test.syntax_for_file_with_content("unknown_file", xml_with_bom),
"XML"
);
// Test the specific .csproj case mentioned in the issue
// Even if .csproj has extension mapping, this tests first-line fallback
let csproj_content_with_bom = "\u{feff}<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">";
assert_eq!(
test.syntax_for_file_with_content("test.csproj", csproj_content_with_bom),
"XML"
);
// Test that shell scripts are detected correctly even with UTF-8 BOM
let script_with_bom = "\u{feff}#!/bin/bash";
assert_eq!(
test.syntax_for_file_with_content("unknown_script", script_with_bom),
"Bourne Again Shell (bash)"
);
// Test that PHP files are detected correctly even with UTF-8 BOM
let php_with_bom = "\u{feff}<?php";
assert_eq!(
test.syntax_for_file_with_content("unknown_php", php_with_bom),
"PHP"
);
}
#[test]
fn syntax_detection_with_custom_mapping() {
let mut test = SyntaxDetectionTest::new();
assert_eq!(test.syntax_for_file("test.h"), "C++");
test.syntax_mapping
.insert("*.h", MappingTarget::MapTo("C"))
.ok();
assert_eq!(test.syntax_for_file("test.h"), "C");
}
#[test]
fn syntax_detection_with_extension_mapping_to_unknown() {
let mut test = SyntaxDetectionTest::new();
// Normally, a CMakeLists.txt file shall use the CMake syntax, even if it is
// a bash script in disguise
assert_eq!(
test.syntax_for_file_with_content("CMakeLists.txt", "#!/bin/bash"),
"CMake"
);
// Other .txt files shall use the Plain Text syntax
assert_eq!(
test.syntax_for_file_with_content("some-other.txt", "#!/bin/bash"),
"Plain Text"
);
// If we setup MapExtensionToUnknown on *.txt, the match on the full
// file name of "CMakeLists.txt" shall have higher prio, and CMake shall
// still be used for it
test.syntax_mapping
.insert("*.txt", MappingTarget::MapExtensionToUnknown)
.ok();
assert_eq!(
test.syntax_for_file_with_content("CMakeLists.txt", "#!/bin/bash"),
"CMake"
);
// However, for *other* files with a .txt extension, first-line fallback
// shall now be used
assert_eq!(
test.syntax_for_file_with_content("some-other.txt", "#!/bin/bash"),
"Bourne Again Shell (bash)"
);
}
#[test]
fn syntax_detection_is_case_insensitive() {
let mut test = SyntaxDetectionTest::new();
assert_eq!(test.syntax_for_file("README.md"), "Markdown");
assert_eq!(test.syntax_for_file("README.mD"), "Markdown");
assert_eq!(test.syntax_for_file("README.Md"), "Markdown");
assert_eq!(test.syntax_for_file("README.MD"), "Markdown");
// Adding a mapping for "MD" in addition to "md" should not break the mapping
test.syntax_mapping
.insert("*.MD", MappingTarget::MapTo("Markdown"))
.ok();
assert_eq!(test.syntax_for_file("README.md"), "Markdown");
assert_eq!(test.syntax_for_file("README.mD"), "Markdown");
assert_eq!(test.syntax_for_file("README.Md"), "Markdown");
assert_eq!(test.syntax_for_file("README.MD"), "Markdown");
}
#[test]
fn syntax_detection_stdin_filename() {
let test = SyntaxDetectionTest::new();
// from file extension
assert_eq!(test.syntax_for_stdin_with_content("test.cpp", b"a"), "C++");
// from first line (fallback)
assert_eq!(
test.syntax_for_stdin_with_content("my_script", b"#!/bin/bash"),
"Bourne Again Shell (bash)"
);
}
#[cfg(unix)]
#[test]
fn syntax_detection_for_symlinked_file() {
use std::os::unix::fs::symlink;
let test = SyntaxDetectionTest::new();
let file_path = test.temp_dir.path().join("my_ssh_config_filename");
{
File::create(&file_path).unwrap();
}
let file_path_symlink = test.temp_dir.path().join(".ssh").join("config");
std::fs::create_dir(test.temp_dir.path().join(".ssh"))
.expect("creation of directory succeeds");
symlink(&file_path, &file_path_symlink).expect("creation of symbolic link succeeds");
let input = Input::ordinary_file(&file_path_symlink);
let dummy_stdin: &[u8] = &[];
let mut opened_input = input.open(dummy_stdin, None).unwrap();
assert_eq!(
test.get_syntax_name(None, &mut opened_input, &test.syntax_mapping),
"SSH Config"
);
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/output.rs | src/output.rs | use std::fmt;
use std::io;
#[cfg(feature = "paging")]
use std::process::Child;
#[cfg(feature = "paging")]
use std::thread::{spawn, JoinHandle};
use crate::error::*;
#[cfg(feature = "paging")]
use crate::less::{retrieve_less_version, LessVersion};
#[cfg(feature = "paging")]
use crate::paging::PagingMode;
#[cfg(feature = "paging")]
use crate::wrapping::WrappingMode;
#[cfg(feature = "paging")]
pub struct BuiltinPager {
pager: minus::Pager,
handle: Option<JoinHandle<Result<()>>>,
}
#[cfg(feature = "paging")]
impl BuiltinPager {
fn new() -> Self {
let pager = minus::Pager::new();
let handle = {
let pager = pager.clone();
Some(spawn(move || {
minus::dynamic_paging(pager).map_err(Error::from)
}))
};
Self { pager, handle }
}
}
#[cfg(feature = "paging")]
impl std::fmt::Debug for BuiltinPager {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BuiltinPager")
//.field("pager", &self.pager) /// minus::Pager doesn't implement fmt::Debug
.field("handle", &self.handle)
.finish()
}
}
#[cfg(feature = "paging")]
#[derive(Debug, PartialEq)]
enum SingleScreenAction {
Quit,
Nothing,
}
#[derive(Debug)]
pub enum OutputType {
#[cfg(feature = "paging")]
Pager(Child),
#[cfg(feature = "paging")]
BuiltinPager(BuiltinPager),
Stdout(io::Stdout),
}
impl OutputType {
#[cfg(feature = "paging")]
pub fn from_mode(
paging_mode: PagingMode,
wrapping_mode: WrappingMode,
pager: Option<&str>,
) -> Result<Self> {
use self::PagingMode::*;
Ok(match paging_mode {
Always => OutputType::try_pager(SingleScreenAction::Nothing, wrapping_mode, pager)?,
QuitIfOneScreen => {
OutputType::try_pager(SingleScreenAction::Quit, wrapping_mode, pager)?
}
_ => OutputType::stdout(),
})
}
/// Try to launch the pager. Fall back to stdout in case of errors.
#[cfg(feature = "paging")]
fn try_pager(
single_screen_action: SingleScreenAction,
wrapping_mode: WrappingMode,
pager_from_config: Option<&str>,
) -> Result<Self> {
use crate::pager::{self, PagerKind, PagerSource};
use std::process::{Command, Stdio};
let pager_opt =
pager::get_pager(pager_from_config).map_err(|_| "Could not parse pager command.")?;
let pager = match pager_opt {
Some(pager) => pager,
None => return Ok(OutputType::stdout()),
};
if pager.kind == PagerKind::Bat {
return Err(Error::InvalidPagerValueBat);
}
if pager.kind == PagerKind::Builtin {
return Ok(OutputType::BuiltinPager(BuiltinPager::new()));
}
let resolved_path = match grep_cli::resolve_binary(&pager.bin) {
Ok(path) => path,
Err(_) => {
return Ok(OutputType::stdout());
}
};
let mut p = Command::new(resolved_path);
let args = pager.args;
if pager.kind == PagerKind::Less {
// less needs to be called with the '-R' option in order to properly interpret the
// ANSI color sequences printed by bat. If someone has set PAGER="less -F", we
// therefore need to overwrite the arguments and add '-R'.
//
// We only do this for PAGER (as it is not specific to 'bat'), not for BAT_PAGER
// or bats '--pager' command line option.
let replace_arguments_to_less = pager.source == PagerSource::EnvVarPager;
if args.is_empty() || replace_arguments_to_less {
p.arg("-R"); // Short version of --RAW-CONTROL-CHARS for maximum compatibility
if single_screen_action == SingleScreenAction::Quit {
p.arg("-F"); // Short version of --quit-if-one-screen for compatibility
}
if wrapping_mode == WrappingMode::NoWrapping(true) {
p.arg("-S"); // Short version of --chop-long-lines for compatibility
}
// Ensures that 'less' quits together with 'bat'
p.arg("-K"); // Short version of '--quit-on-intr'
// Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older
// versions of 'less'. Unfortunately, it also breaks mouse-wheel support.
//
// See: http://www.greenwoodsoftware.com/less/news.530.html
//
// For newer versions (530 or 558 on Windows), we omit '--no-init' as it
// is not needed anymore.
if single_screen_action == SingleScreenAction::Quit {
match retrieve_less_version(&pager.bin) {
None => {
p.arg("--no-init");
}
Some(LessVersion::Less(version))
if (version < 530 || (cfg!(windows) && version < 558)) =>
{
p.arg("--no-init");
}
_ => {}
}
}
} else {
p.args(args);
}
p.env("LESSCHARSET", "UTF-8");
#[cfg(feature = "lessopen")]
// Ensures that 'less' does not preprocess input again if '$LESSOPEN' is set.
p.arg("--no-lessopen");
} else {
p.args(args);
};
Ok(p.stdin(Stdio::piped())
.spawn()
.map(OutputType::Pager)
.unwrap_or_else(|_| OutputType::stdout()))
}
pub(crate) fn stdout() -> Self {
OutputType::Stdout(io::stdout())
}
#[cfg(feature = "paging")]
pub(crate) fn is_pager(&self) -> bool {
matches!(self, OutputType::Pager(_) | OutputType::BuiltinPager(_))
}
#[cfg(not(feature = "paging"))]
pub(crate) fn is_pager(&self) -> bool {
false
}
pub fn handle<'a>(&'a mut self) -> Result<OutputHandle<'a>> {
Ok(match *self {
#[cfg(feature = "paging")]
OutputType::Pager(ref mut command) => OutputHandle::IoWrite(
command
.stdin
.as_mut()
.ok_or("Could not open stdin for pager")?,
),
#[cfg(feature = "paging")]
OutputType::BuiltinPager(ref mut pager) => OutputHandle::FmtWrite(&mut pager.pager),
OutputType::Stdout(ref mut handle) => OutputHandle::IoWrite(handle),
})
}
}
#[cfg(feature = "paging")]
impl Drop for OutputType {
fn drop(&mut self) {
match *self {
OutputType::Pager(ref mut command) => {
let _ = command.wait();
}
OutputType::BuiltinPager(ref mut pager) => {
if pager.handle.is_some() {
let _ = pager.handle.take().unwrap().join().unwrap();
}
}
OutputType::Stdout(_) => (),
}
}
}
pub enum OutputHandle<'a> {
IoWrite(&'a mut dyn io::Write),
FmtWrite(&'a mut dyn fmt::Write),
}
impl OutputHandle<'_> {
pub fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<()> {
match self {
Self::IoWrite(handle) => handle.write_fmt(args).map_err(Into::into),
Self::FmtWrite(handle) => handle.write_fmt(args).map_err(Into::into),
}
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/pager.rs | src/pager.rs | use shell_words::ParseError;
use std::env;
/// If we use a pager, this enum tells us from where we were told to use it.
#[derive(Debug, PartialEq)]
pub(crate) enum PagerSource {
/// From --config
Config,
/// From the env var BAT_PAGER
EnvVarBatPager,
/// From the env var PAGER
EnvVarPager,
/// No pager was specified, default is used
Default,
}
/// We know about some pagers, for example 'less'. This is a list of all pagers we know about
#[derive(Debug, PartialEq)]
pub(crate) enum PagerKind {
/// bat
Bat,
/// less
Less,
/// more
More,
/// most
Most,
/// builtin
Builtin,
/// A pager we don't know about
Unknown,
}
impl PagerKind {
fn from_bin(bin: &str) -> PagerKind {
use std::path::Path;
if bin == "builtin" {
return PagerKind::Builtin;
}
// Set to `less` by default on most Linux distros.
let pager_bin = Path::new(bin).file_stem();
// The name of the current running binary. Normally `bat` but sometimes
// `batcat` for compatibility reasons.
let current_bin = env::args_os().next();
// Check if the current running binary is set to be our pager.
let is_current_bin_pager = current_bin
.map(|s| Path::new(&s).file_stem() == pager_bin)
.unwrap_or(false);
match pager_bin.map(|s| s.to_string_lossy()).as_deref() {
Some("less") => PagerKind::Less,
Some("more") => PagerKind::More,
Some("most") => PagerKind::Most,
_ if is_current_bin_pager => PagerKind::Bat,
_ => PagerKind::Unknown,
}
}
}
/// A pager such as 'less', and from where we got it.
#[derive(Debug)]
pub(crate) struct Pager {
/// The pager binary
pub bin: String,
/// The pager binary arguments (that we might tweak)
pub args: Vec<String>,
/// What pager this is
pub kind: PagerKind,
/// From where this pager comes
pub source: PagerSource,
}
impl Pager {
fn new(bin: &str, args: &[String], kind: PagerKind, source: PagerSource) -> Pager {
Pager {
bin: String::from(bin),
args: args.to_vec(),
kind,
source,
}
}
}
/// Returns what pager to use, after looking at both config and environment variables.
pub(crate) fn get_pager(config_pager: Option<&str>) -> Result<Option<Pager>, ParseError> {
let bat_pager = env::var("BAT_PAGER");
let pager = env::var("PAGER");
let (cmd, source) = match (config_pager, &bat_pager, &pager) {
(Some(config_pager), _, _) => (config_pager, PagerSource::Config),
(_, Ok(bat_pager), _) => (bat_pager.as_str(), PagerSource::EnvVarBatPager),
(_, _, Ok(pager)) => (pager.as_str(), PagerSource::EnvVarPager),
_ => ("less", PagerSource::Default),
};
let parts = shell_words::split(cmd)?;
match parts.split_first() {
Some((bin, args)) => {
let kind = PagerKind::from_bin(bin);
let use_less_instead = if source == PagerSource::EnvVarPager {
// 'more' and 'most' do not supports colors; automatically use
// 'less' instead if the problematic pager came from the
// generic PAGER env var.
// If PAGER=bat, silently use 'less' instead to prevent
// recursion.
// Never silently use 'less' if BAT_PAGER or --pager has been
// specified.
matches!(kind, PagerKind::More | PagerKind::Most | PagerKind::Bat)
} else {
false
};
Ok(Some(if use_less_instead {
let no_args = vec![];
Pager::new("less", &no_args, PagerKind::Less, PagerSource::EnvVarPager)
} else {
Pager::new(bin, args, kind, source)
}))
}
None => Ok(None),
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/input.rs | src/input.rs | use std::convert::TryFrom;
use std::fs;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use clircle::{Clircle, Identifier};
use content_inspector::{self, ContentType};
use crate::error::*;
/// A description of an Input source.
/// This tells bat how to refer to the input.
#[derive(Clone)]
pub struct InputDescription {
pub(crate) name: String,
/// The input title.
/// This replaces the name if provided.
title: Option<String>,
/// The input kind.
kind: Option<String>,
/// A summary description of the input.
/// Defaults to "{kind} '{name}'"
summary: Option<String>,
}
impl InputDescription {
/// Creates a description for an input.
pub fn new(name: impl Into<String>) -> Self {
InputDescription {
name: name.into(),
title: None,
kind: None,
summary: None,
}
}
pub fn set_kind(&mut self, kind: Option<String>) {
self.kind = kind;
}
pub fn set_summary(&mut self, summary: Option<String>) {
self.summary = summary;
}
pub fn set_title(&mut self, title: Option<String>) {
self.title = title;
}
pub fn title(&self) -> &String {
match &self.title {
Some(title) => title,
None => &self.name,
}
}
pub fn kind(&self) -> Option<&String> {
self.kind.as_ref()
}
pub fn summary(&self) -> String {
self.summary.clone().unwrap_or_else(|| match &self.kind {
None => self.name.clone(),
Some(kind) => format!("{} '{}'", kind.to_lowercase(), self.name),
})
}
}
pub(crate) enum InputKind<'a> {
OrdinaryFile(PathBuf),
StdIn,
CustomReader(Box<dyn Read + 'a>),
}
impl InputKind<'_> {
pub fn description(&self) -> InputDescription {
match self {
InputKind::OrdinaryFile(ref path) => InputDescription::new(path.to_string_lossy()),
InputKind::StdIn => InputDescription::new("STDIN"),
InputKind::CustomReader(_) => InputDescription::new("READER"),
}
}
}
#[derive(Clone, Default)]
pub(crate) struct InputMetadata {
pub(crate) user_provided_name: Option<PathBuf>,
pub(crate) size: Option<u64>,
}
pub struct Input<'a> {
pub(crate) kind: InputKind<'a>,
pub(crate) metadata: InputMetadata,
pub(crate) description: InputDescription,
}
pub(crate) enum OpenedInputKind {
OrdinaryFile(PathBuf),
StdIn,
CustomReader,
}
pub(crate) struct OpenedInput<'a> {
pub(crate) kind: OpenedInputKind,
pub(crate) metadata: InputMetadata,
pub(crate) reader: InputReader<'a>,
pub(crate) description: InputDescription,
}
impl OpenedInput<'_> {
/// Get the path of the file:
/// If this was set by the metadata, that will take priority.
/// If it wasn't, it will use the real file path (if available).
pub(crate) fn path(&self) -> Option<&PathBuf> {
self.metadata
.user_provided_name
.as_ref()
.or(match self.kind {
OpenedInputKind::OrdinaryFile(ref path) => Some(path),
_ => None,
})
}
}
impl<'a> Input<'a> {
pub fn ordinary_file(path: impl AsRef<Path>) -> Self {
Self::_ordinary_file(path.as_ref())
}
fn _ordinary_file(path: &Path) -> Self {
let kind = InputKind::OrdinaryFile(path.to_path_buf());
let metadata = InputMetadata {
size: fs::metadata(path).map(|m| m.len()).ok(),
..InputMetadata::default()
};
Input {
description: kind.description(),
metadata,
kind,
}
}
pub fn stdin() -> Self {
let kind = InputKind::StdIn;
Input {
description: kind.description(),
metadata: InputMetadata::default(),
kind,
}
}
pub fn from_reader(reader: Box<dyn Read + 'a>) -> Self {
let kind = InputKind::CustomReader(reader);
Input {
description: kind.description(),
metadata: InputMetadata::default(),
kind,
}
}
pub fn is_stdin(&self) -> bool {
matches!(self.kind, InputKind::StdIn)
}
pub fn with_name(self, provided_name: Option<impl AsRef<Path>>) -> Self {
self._with_name(provided_name.as_ref().map(|it| it.as_ref()))
}
fn _with_name(mut self, provided_name: Option<&Path>) -> Self {
if let Some(name) = provided_name {
self.description.name = name.to_string_lossy().to_string()
}
self.metadata.user_provided_name = provided_name.map(|n| n.to_owned());
self
}
pub fn description(&self) -> &InputDescription {
&self.description
}
pub fn description_mut(&mut self) -> &mut InputDescription {
&mut self.description
}
pub(crate) fn open<R: BufRead + 'a>(
self,
stdin: R,
stdout_identifier: Option<&Identifier>,
) -> Result<OpenedInput<'a>> {
let description = self.description().clone();
match self.kind {
InputKind::StdIn => {
if let Some(stdout) = stdout_identifier {
let input_identifier = Identifier::try_from(clircle::Stdio::Stdin)
.map_err(|e| format!("Stdin: Error identifying file: {e}"))?;
if stdout.surely_conflicts_with(&input_identifier) {
return Err("IO circle detected. The input from stdin is also an output. Aborting to avoid infinite loop.".into());
}
}
Ok(OpenedInput {
kind: OpenedInputKind::StdIn,
description,
metadata: self.metadata,
reader: InputReader::new(stdin),
})
}
InputKind::OrdinaryFile(path) => Ok(OpenedInput {
kind: OpenedInputKind::OrdinaryFile(path.clone()),
description,
metadata: self.metadata,
reader: {
let mut file = File::open(&path)
.map_err(|e| format!("'{}': {e}", path.to_string_lossy()))?;
if file.metadata()?.is_dir() {
return Err(format!("'{}' is a directory.", path.to_string_lossy()).into());
}
if let Some(stdout) = stdout_identifier {
let input_identifier = Identifier::try_from(file).map_err(|e| {
format!("{}: Error identifying file: {e}", path.to_string_lossy())
})?;
if stdout.surely_conflicts_with(&input_identifier) {
return Err(format!(
"IO circle detected. The input from '{}' is also an output. Aborting to avoid infinite loop.",
path.to_string_lossy()
)
.into());
}
file = input_identifier.into_inner().expect("The file was lost in the clircle::Identifier, this should not have happened...");
}
InputReader::new(BufReader::new(file))
},
}),
InputKind::CustomReader(reader) => Ok(OpenedInput {
description,
kind: OpenedInputKind::CustomReader,
metadata: self.metadata,
reader: InputReader::new(BufReader::new(reader)),
}),
}
}
}
pub(crate) struct InputReader<'a> {
inner: Box<dyn BufRead + 'a>,
pub(crate) first_line: Vec<u8>,
pub(crate) content_type: Option<ContentType>,
}
impl<'a> InputReader<'a> {
pub(crate) fn new<R: BufRead + 'a>(mut reader: R) -> InputReader<'a> {
let mut first_line = vec![];
reader.read_until(b'\n', &mut first_line).ok();
let content_type = if first_line.is_empty() {
None
} else {
Some(content_inspector::inspect(&first_line[..]))
};
if content_type == Some(ContentType::UTF_16LE) {
read_utf16_line(&mut reader, &mut first_line, 0x00, 0x0A).ok();
} else if content_type == Some(ContentType::UTF_16BE) {
read_utf16_line(&mut reader, &mut first_line, 0x0A, 0x00).ok();
}
InputReader {
inner: Box::new(reader),
first_line,
content_type,
}
}
pub(crate) fn read_line(&mut self, buf: &mut Vec<u8>) -> io::Result<bool> {
if !self.first_line.is_empty() {
buf.append(&mut self.first_line);
return Ok(true);
}
if self.content_type == Some(ContentType::UTF_16LE) {
return read_utf16_line(&mut self.inner, buf, 0x00, 0x0A);
}
if self.content_type == Some(ContentType::UTF_16BE) {
return read_utf16_line(&mut self.inner, buf, 0x0A, 0x00);
}
let res = self.inner.read_until(b'\n', buf).map(|size| size > 0)?;
Ok(res)
}
}
fn read_utf16_line<R: BufRead>(
reader: &mut R,
buf: &mut Vec<u8>,
read_until_char: u8,
preceded_by_char: u8,
) -> io::Result<bool> {
loop {
let mut temp = Vec::new();
let n = reader.read_until(read_until_char, &mut temp)?;
if n == 0 {
// EOF reached
break;
}
buf.extend_from_slice(&temp);
if buf.len() >= 2
&& buf[buf.len() - 2] == preceded_by_char
&& buf[buf.len() - 1] == read_until_char
{
// end of line found
break;
}
// end of line not found, keep going
}
Ok(!buf.is_empty())
}
#[test]
fn basic() {
let content = b"#!/bin/bash\necho hello";
let mut reader = InputReader::new(&content[..]);
assert_eq!(b"#!/bin/bash\n", &reader.first_line[..]);
let mut buffer = vec![];
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(res.unwrap());
assert_eq!(b"#!/bin/bash\n", &buffer[..]);
buffer.clear();
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(res.unwrap());
assert_eq!(b"echo hello", &buffer[..]);
buffer.clear();
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(!res.unwrap());
assert!(buffer.is_empty());
}
#[test]
fn utf16le() {
let content = b"\xFF\xFE\x73\x00\x0A\x00\x64\x00";
let mut reader = InputReader::new(&content[..]);
assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &reader.first_line[..]);
let mut buffer = vec![];
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(res.unwrap());
assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &buffer[..]);
buffer.clear();
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(res.unwrap());
assert_eq!(b"\x64\x00", &buffer[..]);
buffer.clear();
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(!res.unwrap());
assert!(buffer.is_empty());
}
#[test]
fn utf16le_issue3367() {
let content = b"\xFF\xFE\x0A\x4E\x00\x4E\x0A\x4F\x00\x52\x0A\x00\
\x6F\x00\x20\x00\x62\x00\x61\x00\x72\x00\x0A\x00\
\x68\x00\x65\x00\x6C\x00\x6C\x00\x6F\x00\x20\x00\x77\x00\x6F\x00\x72\x00\x6C\x00\x64\x00";
let mut reader = InputReader::new(&content[..]);
assert_eq!(
b"\xFF\xFE\x0A\x4E\x00\x4E\x0A\x4F\x00\x52\x0A\x00",
&reader.first_line[..]
);
let mut buffer = vec![];
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(res.unwrap());
assert_eq!(
b"\xFF\xFE\x0A\x4E\x00\x4E\x0A\x4F\x00\x52\x0A\x00",
&buffer[..]
);
buffer.clear();
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(res.unwrap());
assert_eq!(
b"\x6F\x00\x20\x00\x62\x00\x61\x00\x72\x00\x0A\x00",
&buffer[..]
);
buffer.clear();
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(res.unwrap());
assert_eq!(
b"\x68\x00\x65\x00\x6C\x00\x6C\x00\x6F\x00\x20\x00\x77\x00\x6F\x00\x72\x00\x6C\x00\x64\x00",
&buffer[..]
);
buffer.clear();
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(!res.unwrap());
assert!(buffer.is_empty());
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/bin/bat/config.rs | src/bin/bat/config.rs | use std::env;
use std::ffi::OsString;
use std::fs;
use std::io::{self, Write};
use std::path::PathBuf;
use crate::directories::PROJECT_DIRS;
#[cfg(not(target_os = "windows"))]
const DEFAULT_SYSTEM_CONFIG_PREFIX: &str = "/etc";
#[cfg(target_os = "windows")]
const DEFAULT_SYSTEM_CONFIG_PREFIX: &str = "C:\\ProgramData";
pub fn system_config_file() -> PathBuf {
let folder = option_env!("BAT_SYSTEM_CONFIG_PREFIX").unwrap_or(DEFAULT_SYSTEM_CONFIG_PREFIX);
let mut path = PathBuf::from(folder);
path.push("bat");
path.push("config");
path
}
pub fn config_file() -> PathBuf {
env::var("BAT_CONFIG_PATH")
.ok()
.map(PathBuf::from)
.unwrap_or_else(|| PROJECT_DIRS.config_dir().join("config"))
}
pub fn generate_config_file() -> bat::error::Result<()> {
let config_file = config_file();
if config_file.is_file() {
println!(
"A config file already exists at: {}",
config_file.to_string_lossy()
);
print!("Overwrite? (y/N): ");
io::stdout().flush()?;
let mut decision = String::new();
io::stdin().read_line(&mut decision)?;
if !decision.trim().eq_ignore_ascii_case("Y") {
return Ok(());
}
} else {
let config_dir = config_file.parent();
match config_dir {
Some(path) => fs::create_dir_all(path)?,
None => {
return Err(format!(
"Unable to write config file to: {}",
config_file.to_string_lossy()
)
.into());
}
}
}
let default_config = r#"# This is `bat`s configuration file. Each line either contains a comment or
# a command-line option that you want to pass to `bat` by default. You can
# run `bat --help` to get a list of all possible configuration options.
# Specify desired highlighting theme (e.g. "TwoDark"). Run `bat --list-themes`
# for a list of all available themes
#--theme="TwoDark"
# Enable this to use italic text on the terminal. This is not supported on all
# terminal emulators (like tmux, by default):
#--italic-text=always
# Uncomment the following line to disable automatic paging:
#--paging=never
# Uncomment the following line if you are using less version >= 551 and want to
# enable mouse scrolling support in `bat` when running inside tmux. This might
# disable text selection, unless you press shift.
#--pager="less --RAW-CONTROL-CHARS --quit-if-one-screen --mouse"
# Syntax mappings: map a certain filename pattern to a language.
# Example 1: use the C++ syntax for Arduino .ino files
# Example 2: Use ".gitignore"-style highlighting for ".ignore" files
#--map-syntax "*.ino:C++"
#--map-syntax ".ignore:Git Ignore"
"#;
fs::write(&config_file, default_config).map_err(|e| {
format!(
"Failed to create config file at '{}': {e}",
config_file.to_string_lossy(),
)
})?;
println!(
"Success! Config file written to {}",
config_file.to_string_lossy()
);
Ok(())
}
pub fn get_args_from_config_file() -> Result<Vec<OsString>, shell_words::ParseError> {
let mut config = String::new();
if let Ok(c) = fs::read_to_string(system_config_file()) {
config.push_str(&c);
config.push('\n');
}
if let Ok(c) = fs::read_to_string(config_file()) {
config.push_str(&c);
}
get_args_from_str(&config)
}
pub fn get_args_from_env_opts_var() -> Option<Result<Vec<OsString>, shell_words::ParseError>> {
env::var("BAT_OPTS").ok().map(|s| get_args_from_str(&s))
}
fn get_args_from_str(content: &str) -> Result<Vec<OsString>, shell_words::ParseError> {
let args_per_line = content
.split('\n')
.map(|line| line.trim())
.filter(|line| !line.is_empty())
.filter(|line| !line.starts_with('#'))
.map(shell_words::split)
.collect::<Result<Vec<_>, _>>()?;
Ok(args_per_line
.iter()
.flatten()
.map(|line| line.into())
.collect())
}
pub fn get_args_from_env_vars() -> Vec<OsString> {
[
("--tabs", "BAT_TABS"),
("--theme", bat::theme::env::BAT_THEME),
("--theme-dark", bat::theme::env::BAT_THEME_DARK),
("--theme-light", bat::theme::env::BAT_THEME_LIGHT),
("--pager", "BAT_PAGER"),
("--paging", "BAT_PAGING"),
("--style", "BAT_STYLE"),
]
.iter()
.filter_map(|(flag, key)| {
env::var(key)
.ok()
.map(|var| [flag.to_string(), var].join("="))
})
.map(|a| a.into())
.collect()
}
#[test]
fn empty() {
let args = get_args_from_str("").unwrap();
assert!(args.is_empty());
}
#[test]
fn single() {
assert_eq!(vec!["--plain"], get_args_from_str("--plain").unwrap());
}
#[test]
fn multiple() {
assert_eq!(
vec!["--plain", "--language=cpp"],
get_args_from_str("--plain --language=cpp").unwrap()
);
}
#[test]
fn quotes() {
assert_eq!(
vec!["--theme", "Sublime Snazzy"],
get_args_from_str("--theme \"Sublime Snazzy\"").unwrap()
);
}
#[test]
fn multi_line() {
let config = "
-p
--style numbers,changes
--color=always
";
assert_eq!(
vec!["-p", "--style", "numbers,changes", "--color=always"],
get_args_from_str(config).unwrap()
);
}
#[test]
fn comments() {
let config = "
# plain style
-p
# show line numbers and Git modifications
--style numbers,changes
# Always show ANSI colors
--color=always
";
assert_eq!(
vec!["-p", "--style", "numbers,changes", "--color=always"],
get_args_from_str(config).unwrap()
);
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/bin/bat/app.rs | src/bin/bat/app.rs | use std::collections::HashSet;
use std::env;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::thread::available_parallelism;
use crate::{
clap_app,
config::{get_args_from_config_file, get_args_from_env_opts_var, get_args_from_env_vars},
};
use bat::style::StyleComponentList;
use bat::theme::{theme, ThemeName, ThemeOptions, ThemePreference};
use bat::BinaryBehavior;
use bat::StripAnsiMode;
use clap::ArgMatches;
use console::Term;
use crate::input::{new_file_input, new_stdin_input};
use bat::{
bat_warning,
config::{Config, VisibleLines},
error::*,
input::Input,
line_range::{HighlightedLineRanges, LineRange, LineRanges},
style::{StyleComponent, StyleComponents},
MappingTarget, NonprintableNotation, PagingMode, SyntaxMapping, WrappingMode,
};
fn is_truecolor_terminal() -> bool {
env::var("COLORTERM")
.map(|colorterm| colorterm == "truecolor" || colorterm == "24bit")
.unwrap_or(false)
}
pub fn env_no_color() -> bool {
env::var_os("NO_COLOR").is_some_and(|x| !x.is_empty())
}
enum HelpType {
Short,
Long,
}
pub struct App {
pub matches: ArgMatches,
interactive_output: bool,
/// True if -n / --number was passed on the command line
/// (not from config file or environment variables).
/// This is used to honor the flag when piping output, similar to `cat -n`.
number_from_cli: bool,
}
impl App {
pub fn new() -> Result<Self> {
#[cfg(windows)]
let _ = nu_ansi_term::enable_ansi_support();
let interactive_output = std::io::stdout().is_terminal();
// Check if the -n / --number option was passed on the command line
// (before merging with config file and environment variables).
// This is needed to honor the -n flag when piping output, similar to `cat -n`.
// We need to handle both standalone (-n, --number) and combined short flags (-pn, -An, etc.)
// Note: We only check if -n appears and is not overridden by -p in the same combined flag.
// For combined flags like -np, -p comes after -n and overrides it, so we don't count it.
// For combined flags like -pn, -n comes after -p and takes effect.
let number_from_cli = wild::args_os().any(|arg| {
let arg_str = arg.to_string_lossy();
if arg_str == "-n" || arg_str == "--number" {
return true;
}
// Handle combined short flags
// Only count -n if it's the LAST flag in the combined form (so -p doesn't override it)
// or if -p is not present in the combined form
if arg_str.starts_with('-') && !arg_str.starts_with("--") && arg_str.len() > 2 {
let chars: Vec<char> = arg_str.chars().skip(1).collect();
let n_pos = chars.iter().position(|&c| c == 'n');
let p_pos = chars.iter().position(|&c| c == 'p');
// -n is in the combined flag and either:
// - -p is not present, OR
// - -n comes after -p (so -n takes effect)
if let Some(n) = n_pos {
if p_pos.is_none() || n > p_pos.unwrap() {
return true;
}
}
}
false
});
let matches = Self::matches(interactive_output)?;
if matches.get_flag("help") {
let help_type = if wild::args_os().any(|arg| arg == "--help") {
HelpType::Long
} else {
HelpType::Short
};
let use_pager = match matches.get_one::<String>("paging").map(|s| s.as_str()) {
Some("never") => false,
_ => !matches.get_flag("no-paging"),
};
let use_color = match matches.get_one::<String>("color").map(|s| s.as_str()) {
Some("always") => true,
Some("never") => false,
_ => interactive_output, // auto: use color if interactive
};
let pager = matches.get_one::<String>("pager").map(|s| s.as_str());
let theme_options = Self::theme_options_from_matches(&matches);
let use_custom_assets = !matches.get_flag("no-custom-assets");
Self::display_help(
interactive_output,
help_type,
use_pager,
use_color,
pager,
theme_options,
use_custom_assets,
)?;
std::process::exit(0);
}
Ok(App {
matches,
interactive_output,
number_from_cli,
})
}
fn display_help(
interactive_output: bool,
help_type: HelpType,
use_pager: bool,
use_color: bool,
pager: Option<&str>,
theme_options: ThemeOptions,
use_custom_assets: bool,
) -> Result<()> {
use crate::assets::assets_from_cache_or_binary;
use crate::directories::PROJECT_DIRS;
use bat::{
config::Config,
controller::Controller,
input::Input,
style::{StyleComponent, StyleComponents},
theme::theme,
PagingMode,
};
let mut cmd = clap_app::build_app(interactive_output);
let help_text = match help_type {
HelpType::Short => cmd.render_help().to_string(),
HelpType::Long => cmd.render_long_help().to_string(),
};
let inputs: Vec<Input> = vec![Input::from_reader(Box::new(help_text.as_bytes()))];
let paging_mode = if use_pager {
PagingMode::QuitIfOneScreen
} else {
PagingMode::Never
};
let help_config = Config {
style_components: StyleComponents::new(StyleComponent::Plain.components(false)),
paging_mode,
pager,
colored_output: use_color,
true_color: use_color,
language: if use_color { Some("help") } else { None },
theme: theme(theme_options).to_string(),
..Default::default()
};
let cache_dir = PROJECT_DIRS.cache_dir();
let assets = assets_from_cache_or_binary(use_custom_assets, cache_dir)?;
Controller::new(&help_config, &assets)
.run(inputs, None)
.ok();
Ok(())
}
/// Build argument list with env vars and CLI args (without config file)
fn build_args_without_config() -> Vec<std::ffi::OsString> {
let mut cli_args = wild::args_os();
let mut args = get_args_from_env_vars();
// Put the zero-th CLI argument (program name) first
args.insert(0, cli_args.next().unwrap());
// .. and the rest at the end
cli_args.for_each(|a| args.push(a));
args
}
fn matches(interactive_output: bool) -> Result<ArgMatches> {
// Check if we should skip config file processing for special arguments
// that don't require full application setup (version, diagnostic)
let should_skip_config = wild::args_os().any(|arg| {
matches!(
arg.to_str(),
Some("-V" | "--version" | "--diagnostic" | "--diagnostics")
)
});
// Check if help was requested - help should read the config file but be
// forgiving of invalid arguments (so configured theme etc. can be used)
let help_requested =
wild::args_os().any(|arg| matches!(arg.to_str(), Some("-h" | "--help")));
if wild::args_os().nth(1) == Some("cache".into()) {
// Skip the config file and env vars
let args = wild::args_os().collect::<Vec<_>>();
return Ok(clap_app::build_app(interactive_output).get_matches_from(args));
}
if wild::args_os().any(|arg| arg == "--no-config") || should_skip_config {
// Skip the arguments in bats config file when --no-config is present
// or when user requests version or diagnostic information
let args = Self::build_args_without_config();
return Ok(clap_app::build_app(interactive_output).get_matches_from(args));
}
// Build arguments with config file
let mut cli_args = wild::args_os();
// Read arguments from bats config file
let config_args = match get_args_from_env_opts_var() {
Some(result) => result,
None => get_args_from_config_file(),
};
// For help, ignore config file parse errors (use empty config instead)
// For non-help, propagate the error
let mut args = if help_requested {
config_args.unwrap_or_default()
} else {
config_args.map_err(|_| "Could not parse configuration file")?
};
// Selected env vars supersede config vars
args.extend(get_args_from_env_vars());
// Put the zero-th CLI argument (program name) first
args.insert(0, cli_args.next().unwrap());
// .. and the rest at the end
cli_args.for_each(|a| args.push(a));
// For help, try parsing with config, and if clap fails (e.g., invalid
// argument in config), fall back to parsing without config file args
if help_requested {
let app = clap_app::build_app(interactive_output);
match app.try_get_matches_from(args) {
Ok(matches) => Ok(matches),
Err(_) => {
// Config has invalid arguments, fall back to just env vars + CLI args
let fallback_args = Self::build_args_without_config();
Ok(clap_app::build_app(interactive_output).get_matches_from(fallback_args))
}
}
} else {
Ok(clap_app::build_app(interactive_output).get_matches_from(args))
}
}
pub fn config(&self, inputs: &[Input]) -> Result<Config<'_>> {
let style_components = self.style_components()?;
let extra_plain = self.matches.get_count("plain") > 1;
let plain_last_index = self
.matches
.indices_of("plain")
.and_then(Iterator::max)
.unwrap_or_default();
let paging_last_index = self
.matches
.indices_of("paging")
.and_then(Iterator::max)
.unwrap_or_default();
let paging_mode = match self.matches.get_one::<String>("paging").map(|s| s.as_str()) {
Some("always") => {
// Disable paging if the second -p (or -pp) is specified after --paging=always
if extra_plain && plain_last_index > paging_last_index {
PagingMode::Never
} else {
PagingMode::Always
}
}
Some("never") => PagingMode::Never,
Some("auto") | None => {
// If we have -pp as an option when in auto mode, the pager should be disabled.
if extra_plain || self.matches.get_flag("no-paging") {
PagingMode::Never
} else if inputs.iter().any(Input::is_stdin)
// ignore stdin when --list-themes is used because in that case no input will be read anyways
&& !self.matches.get_flag("list-themes")
{
// If we are reading from stdin, only enable paging if we write to an
// interactive terminal and if we do not *read* from an interactive
// terminal.
if self.interactive_output && !std::io::stdin().is_terminal() {
PagingMode::QuitIfOneScreen
} else {
PagingMode::Never
}
} else if self.interactive_output {
PagingMode::QuitIfOneScreen
} else {
PagingMode::Never
}
}
_ => unreachable!("other values for --paging are not allowed"),
};
let mut syntax_mapping = SyntaxMapping::new();
// start building glob matchers for builtin mappings immediately
// this is an appropriate approach because it's statistically likely that
// all the custom mappings need to be checked
if available_parallelism()?.get() > 1 {
syntax_mapping.start_offload_build_all();
}
if let Some(values) = self.matches.get_many::<String>("ignored-suffix") {
for suffix in values {
syntax_mapping.insert_ignored_suffix(suffix);
}
}
if let Some(values) = self.matches.get_many::<String>("map-syntax") {
// later args take precedence over earlier ones, hence `.rev()`
// see: https://github.com/sharkdp/bat/pull/2755#discussion_r1456416875
for from_to in values.rev() {
let parts: Vec<_> = from_to.split(':').collect();
if parts.len() != 2 {
return Err("Invalid syntax mapping. The format of the -m/--map-syntax option is '<glob-pattern>:<syntax-name>'. For example: '*.cpp:C++'.".into());
}
syntax_mapping.insert(parts[0], MappingTarget::MapTo(parts[1]))?;
}
}
let maybe_term_width = self
.matches
.get_one::<String>("terminal-width")
.and_then(|w| {
if w.starts_with('+') || w.starts_with('-') {
// Treat argument as a delta to the current terminal width
w.parse().ok().map(|delta: i16| {
let old_width: u16 = Term::stdout().size().1;
let new_width: i32 = i32::from(old_width) + i32::from(delta);
if new_width <= 0 {
old_width as usize
} else {
new_width as usize
}
})
} else {
w.parse().ok()
}
});
Ok(Config {
true_color: is_truecolor_terminal(),
language: self
.matches
.get_one::<String>("language")
.map(|s| s.as_str())
.or_else(|| {
if self.matches.get_flag("show-all") {
Some("show-nonprintable")
} else {
None
}
}),
show_nonprintable: self.matches.get_flag("show-all"),
nonprintable_notation: match self
.matches
.get_one::<String>("nonprintable-notation")
.map(|s| s.as_str())
{
Some("unicode") => NonprintableNotation::Unicode,
Some("caret") => NonprintableNotation::Caret,
_ => unreachable!("other values for --nonprintable-notation are not allowed"),
},
binary: match self.matches.get_one::<String>("binary").map(|s| s.as_str()) {
Some("as-text") => BinaryBehavior::AsText,
Some("no-printing") => BinaryBehavior::NoPrinting,
_ => unreachable!("other values for --binary are not allowed"),
},
wrapping_mode: if self.interactive_output || maybe_term_width.is_some() {
if !self.matches.get_flag("chop-long-lines") {
match self.matches.get_one::<String>("wrap").map(|s| s.as_str()) {
Some("character") => WrappingMode::Character,
Some("never") => WrappingMode::NoWrapping(true),
Some("auto") | None => {
if style_components.plain() && maybe_term_width.is_none() {
WrappingMode::NoWrapping(false)
} else {
WrappingMode::Character
}
}
_ => unreachable!("other values for --wrap are not allowed"),
}
} else {
WrappingMode::NoWrapping(true)
}
} else {
// We don't have the tty width when piping to another program.
// There's no point in wrapping when this is the case.
WrappingMode::NoWrapping(false)
},
colored_output: self.matches.get_flag("force-colorization")
|| match self.matches.get_one::<String>("color").map(|s| s.as_str()) {
Some("always") => true,
Some("never") => false,
Some("auto") => !env_no_color() && self.interactive_output,
_ => unreachable!("other values for --color are not allowed"),
},
paging_mode,
term_width: maybe_term_width.unwrap_or(Term::stdout().size().1 as usize),
loop_through: !(self.interactive_output
|| self.matches.get_one::<String>("color").map(|s| s.as_str()) == Some("always")
|| self
.matches
.get_one::<String>("decorations")
.map(|s| s.as_str())
== Some("always")
|| self.matches.get_flag("force-colorization")
|| self.number_from_cli),
tab_width: self
.matches
.get_one::<String>("tabs")
.map(String::from)
.and_then(|t| t.parse().ok())
.unwrap_or(
if style_components.plain() && paging_mode == PagingMode::Never {
0
} else {
4
},
),
strip_ansi: match self
.matches
.get_one::<String>("strip-ansi")
.map(|s| s.as_str())
{
Some("never") => StripAnsiMode::Never,
Some("always") => StripAnsiMode::Always,
Some("auto") => StripAnsiMode::Auto,
_ => unreachable!("other values for --strip-ansi are not allowed"),
},
theme: theme(self.theme_options()).to_string(),
visible_lines: match self.matches.try_contains_id("diff").unwrap_or_default()
&& self.matches.get_flag("diff")
{
#[cfg(feature = "git")]
true => VisibleLines::DiffContext(
self.matches
.get_one::<String>("diff-context")
.and_then(|t| t.parse().ok())
.unwrap_or(2),
),
_ => VisibleLines::Ranges(
self.matches
.get_many::<String>("line-range")
.map(|vs| vs.map(|s| LineRange::from(s.as_str())).collect())
.transpose()?
.map(LineRanges::from)
.unwrap_or_default(),
),
},
style_components,
syntax_mapping,
pager: self.matches.get_one::<String>("pager").map(|s| s.as_str()),
use_italic_text: self
.matches
.get_one::<String>("italic-text")
.map(|s| s.as_str())
== Some("always"),
highlighted_lines: self
.matches
.get_many::<String>("highlight-line")
.map(|ws| ws.map(|s| LineRange::from(s.as_str())).collect())
.transpose()?
.map(LineRanges::from)
.map(HighlightedLineRanges)
.unwrap_or_default(),
use_custom_assets: !self.matches.get_flag("no-custom-assets"),
#[cfg(feature = "lessopen")]
use_lessopen: self.matches.get_flag("lessopen"),
set_terminal_title: self.matches.get_flag("set-terminal-title"),
squeeze_lines: if self.matches.get_flag("squeeze-blank") {
Some(
self.matches
.get_one::<usize>("squeeze-limit")
.map(|limit| limit.to_owned())
.unwrap_or(1),
)
} else {
None
},
})
}
pub fn inputs(&self) -> Result<Vec<Input<'_>>> {
let filenames: Option<Vec<&Path>> = self
.matches
.get_many::<PathBuf>("file-name")
.map(|vs| vs.map(|p| p.as_path()).collect::<Vec<_>>());
let files: Option<Vec<&Path>> = self
.matches
.get_many::<PathBuf>("FILE")
.map(|vs| vs.map(|p| p.as_path()).collect::<Vec<_>>());
// verify equal length of file-names and input FILEs
if filenames.is_some()
&& files.is_some()
&& filenames.as_ref().map(|v| v.len()) != files.as_ref().map(|v| v.len())
{
return Err("Must be one file name per input type.".into());
}
let mut filenames_or_none: Box<dyn Iterator<Item = Option<&Path>>> = match filenames {
Some(filenames) => Box::new(filenames.into_iter().map(Some)),
None => Box::new(std::iter::repeat(None)),
};
if files.is_none() {
return Ok(vec![new_stdin_input(
filenames_or_none.next().unwrap_or(None),
)]);
}
let files_or_none: Box<dyn Iterator<Item = _>> = match files {
Some(ref files) => Box::new(files.iter().map(|name| Some(*name))),
None => Box::new(std::iter::repeat(None)),
};
let mut file_input = Vec::new();
for (filepath, provided_name) in files_or_none.zip(filenames_or_none) {
if let Some(filepath) = filepath {
if filepath.to_str().unwrap_or_default() == "-" {
file_input.push(new_stdin_input(provided_name));
} else {
file_input.push(new_file_input(filepath, provided_name));
}
}
}
Ok(file_input)
}
fn forced_style_components(&self) -> Option<StyleComponents> {
// No components if `--decorations=never``.
if self
.matches
.get_one::<String>("decorations")
.map(|s| s.as_str())
== Some("never")
{
return Some(StyleComponents(HashSet::new()));
}
// Only line numbers if `--number`.
if self.matches.get_flag("number") {
return Some(StyleComponents(HashSet::from([
StyleComponent::LineNumbers,
])));
}
// Plain if `--plain` is specified at least once.
if self.matches.get_count("plain") > 0 {
return Some(StyleComponents(HashSet::from([StyleComponent::Plain])));
}
// Default behavior.
None
}
fn style_components(&self) -> Result<StyleComponents> {
let matches = &self.matches;
let mut styled_components = match self.forced_style_components() {
Some(forced_components) => forced_components,
// Parse the `--style` arguments and merge them.
None if matches.contains_id("style") => {
let lists = matches
.get_many::<String>("style")
.expect("styles present")
.map(|v| StyleComponentList::from_str(v))
.collect::<Result<Vec<StyleComponentList>>>()?;
StyleComponentList::to_components(lists, self.interactive_output, true)
}
// Use the default.
None => StyleComponents(HashSet::from_iter(
StyleComponent::Default
.components(self.interactive_output)
.iter()
.cloned(),
)),
};
// If `grid` is set, remove `rule` as it is a subset of `grid`, and print a warning.
if styled_components.grid() && styled_components.0.remove(&StyleComponent::Rule) {
bat_warning!("Style 'rule' is a subset of style 'grid', 'rule' will not be visible.");
}
Ok(styled_components)
}
fn theme_options(&self) -> ThemeOptions {
Self::theme_options_from_matches(&self.matches)
}
fn theme_options_from_matches(matches: &ArgMatches) -> ThemeOptions {
let theme = matches
.get_one::<String>("theme")
.map(|t| ThemePreference::from_str(t).unwrap())
.unwrap_or_default();
let theme_dark = matches
.get_one::<String>("theme-dark")
.map(|t| ThemeName::from_str(t).unwrap());
let theme_light = matches
.get_one::<String>("theme-light")
.map(|t| ThemeName::from_str(t).unwrap());
ThemeOptions {
theme,
theme_dark,
theme_light,
}
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/bin/bat/directories.rs | src/bin/bat/directories.rs | use std::env;
use std::path::{Path, PathBuf};
use etcetera::BaseStrategy;
use once_cell::sync::Lazy;
/// Wrapper for 'etcetera' that checks BAT_CACHE_PATH and BAT_CONFIG_DIR and falls back to the
/// Windows known folder locations on Windows & the XDG Base Directory Specification everywhere else.
pub struct BatProjectDirs {
cache_dir: PathBuf,
config_dir: PathBuf,
}
impl BatProjectDirs {
fn new() -> Option<BatProjectDirs> {
let basedirs = etcetera::choose_base_strategy().ok()?;
// Checks whether or not `$BAT_CACHE_PATH` exists. If it doesn't, set the cache dir to our
// system's default cache home.
let cache_dir = if let Some(cache_dir) = env::var_os("BAT_CACHE_PATH").map(PathBuf::from) {
cache_dir
} else {
basedirs.cache_dir().join("bat")
};
// Checks whether or not `$BAT_CONFIG_DIR` exists. If it doesn't, set the config dir to our
// system's default configuration home.
let config_dir = if let Some(config_dir) = env::var_os("BAT_CONFIG_DIR").map(PathBuf::from)
{
config_dir
} else {
basedirs.config_dir().join("bat")
};
Some(BatProjectDirs {
cache_dir,
config_dir,
})
}
pub fn cache_dir(&self) -> &Path {
&self.cache_dir
}
pub fn config_dir(&self) -> &Path {
&self.config_dir
}
}
pub static PROJECT_DIRS: Lazy<BatProjectDirs> =
Lazy::new(|| BatProjectDirs::new().expect("Could not get home directory"));
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/bin/bat/completions.rs | src/bin/bat/completions.rs | use std::env;
pub const BASH_COMPLETION: &str = include_str!(env!("BAT_GENERATED_COMPLETION_BASH"));
pub const FISH_COMPLETION: &str = include_str!(env!("BAT_GENERATED_COMPLETION_FISH"));
pub const PS1_COMPLETION: &str = include_str!(env!("BAT_GENERATED_COMPLETION_PS1"));
pub const ZSH_COMPLETION: &str = include_str!(env!("BAT_GENERATED_COMPLETION_ZSH"));
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/bin/bat/clap_app.rs | src/bin/bat/clap_app.rs | use bat::style::StyleComponentList;
use clap::{
crate_name, crate_version, value_parser, Arg, ArgAction, ArgGroup, ColorChoice, Command,
};
use once_cell::sync::Lazy;
use std::env;
use std::path::{Path, PathBuf};
use std::str::FromStr;
static VERSION: Lazy<String> = Lazy::new(|| {
#[cfg(feature = "bugreport")]
let git_version = bugreport::git_version!(fallback = "");
#[cfg(not(feature = "bugreport"))]
let git_version = "";
if git_version.is_empty() {
crate_version!().to_string()
} else {
format!("{} ({git_version})", crate_version!())
}
});
pub fn build_app(interactive_output: bool) -> Command {
let color_when = if interactive_output && !crate::app::env_no_color() {
ColorChoice::Auto
} else {
ColorChoice::Never
};
let mut app = Command::new(crate_name!())
.version(VERSION.as_str())
.color(color_when)
.hide_possible_values(true)
.args_conflicts_with_subcommands(true)
.allow_external_subcommands(true)
.disable_help_subcommand(true)
.disable_help_flag(true)
.disable_version_flag(true)
.max_term_width(100)
.about("A cat(1) clone with wings.")
.long_about("A cat(1) clone with syntax highlighting and Git integration.")
.arg(
Arg::new("FILE")
.help("File(s) to print / concatenate. Use '-' for standard input.")
.long_help(
"File(s) to print / concatenate. Use a dash ('-') or no argument at all \
to read from standard input.",
)
.num_args(1..)
.value_parser(value_parser!(PathBuf)),
)
.arg(
Arg::new("show-all")
.long("show-all")
.alias("show-nonprintable")
.short('A')
.action(ArgAction::SetTrue)
.conflicts_with("language")
.help("Show non-printable characters (space, tab, newline, ..).")
.long_help(
"Show non-printable characters like space, tab or newline. \
This option can also be used to print binary files. \
Use '--tabs' to control the width of the tab-placeholders.",
),
)
.arg(
Arg::new("nonprintable-notation")
.long("nonprintable-notation")
.action(ArgAction::Set)
.default_value("unicode")
.value_parser(["unicode", "caret"])
.value_name("notation")
.hide_default_value(true)
.help("Set notation for non-printable characters.")
.long_help(
"Set notation for non-printable characters.\n\n\
Possible values:\n \
* unicode (␇, ␊, ␀, ..)\n \
* caret (^G, ^J, ^@, ..)",
),
)
.arg(
Arg::new("binary")
.long("binary")
.action(ArgAction::Set)
.default_value("no-printing")
.value_parser(["no-printing", "as-text"])
.value_name("behavior")
.hide_default_value(true)
.help("How to treat binary content. (default: no-printing)")
.long_help(
"How to treat binary content. (default: no-printing)\n\n\
Possible values:\n \
* no-printing: do not print any binary content\n \
* as-text: treat binary content as normal text",
),
)
.arg(
Arg::new("plain")
.overrides_with("plain")
.overrides_with("number")
.short('p')
.long("plain")
.action(ArgAction::Count)
.help("Show plain style (alias for '--style=plain').")
.long_help(
"Only show plain style, no decorations. This is an alias for \
'--style=plain'. When '-p' is used twice ('-pp'), it also disables \
automatic paging (alias for '--style=plain --paging=never').",
),
)
.arg(
Arg::new("language")
.short('l')
.long("language")
.overrides_with("language")
.help("Set the language for syntax highlighting.")
.long_help(
"Explicitly set the language for syntax highlighting. The language can be \
specified as a name (like 'C++' or 'LaTeX') or possible file extension \
(like 'cpp', 'hpp' or 'md'). Use '--list-languages' to show all supported \
language names and file extensions.",
),
)
.arg(
Arg::new("highlight-line")
.long("highlight-line")
.short('H')
.action(ArgAction::Append)
.value_name("N:M")
.help("Highlight lines N through M.")
.long_help(
"Highlight the specified line ranges with a different background color \
For example:\n \
'--highlight-line 40' highlights line 40\n \
'--highlight-line 30:40' highlights lines 30 to 40\n \
'--highlight-line :40' highlights lines 1 to 40\n \
'--highlight-line 40:' highlights lines 40 to the end of the file\n \
'--highlight-line 30:+10' highlights lines 30 to 40",
),
)
.arg(
Arg::new("file-name")
.long("file-name")
.action(ArgAction::Append)
.value_name("name")
.value_parser(value_parser!(PathBuf))
.help("Specify the name to display for a file.")
.long_help(
"Specify the name to display for a file. Useful when piping \
data to bat from STDIN when bat does not otherwise know \
the filename. Note that the provided file name is also \
used for syntax detection.",
),
);
#[cfg(feature = "git")]
{
app = app
.arg(
Arg::new("diff")
.long("diff")
.short('d')
.action(ArgAction::SetTrue)
.conflicts_with("line-range")
.help("Only show lines that have been added/removed/modified.")
.long_help(
"Only show lines that have been added/removed/modified with respect \
to the Git index. Use --diff-context=N to control how much context you want to see.",
),
)
.arg(
Arg::new("diff-context")
.long("diff-context")
.overrides_with("diff-context")
.value_name("N")
.value_parser(
|n: &str| {
n.parse::<usize>()
.map_err(|_| "must be a number")
.map(|_| n.to_owned()) // Convert to Result<String, &str>
.map_err(|e| e.to_string())
}, // Convert to Result<(), String>
)
.hide_short_help(true)
.long_help(
"Include N lines of context around added/removed/modified lines when using '--diff'.",
),
)
}
app = app.arg(
Arg::new("tabs")
.long("tabs")
.overrides_with("tabs")
.value_name("T")
.value_parser(
|t: &str| {
t.parse::<u32>()
.map_err(|_t| "must be a number")
.map(|_t| t.to_owned()) // Convert to Result<String, &str>
.map_err(|e| e.to_string())
}, // Convert to Result<(), String>
)
.help("Set the tab width to T spaces.")
.long_help(
"Set the tab width to T spaces. Use a width of 0 to pass tabs through \
directly",
),
)
.arg(
Arg::new("wrap")
.long("wrap")
.overrides_with("wrap")
.value_name("mode")
.value_parser(["auto", "never", "character"])
.default_value("auto")
.hide_default_value(true)
.help("Specify the text-wrapping mode (*auto*, never, character).")
.long_help("Specify the text-wrapping mode (*auto*, never, character). \
The '--terminal-width' option can be used in addition to \
control the output width."),
)
.arg(
Arg::new("chop-long-lines")
.long("chop-long-lines")
.short('S')
.action(ArgAction::SetTrue)
.help("Truncate all lines longer than screen width. Alias for '--wrap=never'."),
)
.arg(
Arg::new("terminal-width")
.long("terminal-width")
.value_name("width")
.hide_short_help(true)
.allow_hyphen_values(true)
.value_parser(
|t: &str| {
let is_offset = t.starts_with('+') || t.starts_with('-');
t.parse::<i32>()
.map_err(|_e| "must be an offset or number")
.and_then(|v| if v == 0 && !is_offset {
Err("terminal width cannot be zero")
} else {
Ok(t.to_owned())
})
.map_err(|e| e.to_string())
})
.help(
"Explicitly set the width of the terminal instead of determining it \
automatically. If prefixed with '+' or '-', the value will be treated \
as an offset to the actual terminal width. See also: '--wrap'.",
),
)
.arg(
Arg::new("number")
.long("number")
.overrides_with("number")
.short('n')
.action(ArgAction::SetTrue)
.help("Show line numbers (alias for '--style=numbers').")
.long_help(
"Only show line numbers, no other decorations. This is an alias for \
'--style=numbers'",
),
)
.arg(
Arg::new("color")
.long("color")
.overrides_with("color")
.value_name("when")
.value_parser(["auto", "never", "always"])
.hide_default_value(true)
.default_value("auto")
.help("When to use colors (*auto*, never, always).")
.long_help(
"Specify when to use colored output. The automatic mode \
only enables colors if an interactive terminal is detected - \
colors are automatically disabled if the output goes to a pipe.\n\
Possible values: *auto*, never, always.",
),
)
.arg(
Arg::new("italic-text")
.long("italic-text")
.value_name("when")
.value_parser(["always", "never"])
.default_value("never")
.hide_default_value(true)
.help("Use italics in output (always, *never*)")
.long_help("Specify when to use ANSI sequences for italic text in the output. Possible values: always, *never*."),
)
.arg(
Arg::new("decorations")
.long("decorations")
.overrides_with("decorations")
.value_name("when")
.value_parser(["auto", "never", "always"])
.default_value("auto")
.hide_default_value(true)
.help("When to show the decorations (*auto*, never, always).")
.long_help(
"Specify when to use the decorations that have been specified \
via '--style'. The automatic mode only enables decorations if \
an interactive terminal is detected. The always mode will show \
decorations even when piping output. Possible values: *auto*, never, always.",
)
)
.arg(
Arg::new("force-colorization")
.long("force-colorization")
.short('f')
.action(ArgAction::SetTrue)
.conflicts_with("color")
.conflicts_with("decorations")
.overrides_with("force-colorization")
.hide_short_help(true)
.long_help("Alias for '--decorations=always --color=always'. This is useful \
if the output of bat is piped to another program, but you want \
to keep the colorization/decorations.")
)
.arg(
Arg::new("paging")
.long("paging")
.overrides_with("paging")
.overrides_with("no-paging")
.value_name("when")
.value_parser(["auto", "never", "always"])
.default_value("auto")
.hide_default_value(true)
.help("Specify when to use the pager, or use `-P` to disable (*auto*, never, always).")
.long_help(
"Specify when to use the pager. To disable the pager, use \
'--paging=never' or its alias,'-P'. To disable the pager permanently, \
set BAT_PAGING to 'never'. To control which pager is used, see the \
'--pager' option. Possible values: *auto*, never, always."
),
)
.arg(
Arg::new("no-paging")
.short('P')
.long("no-paging")
.alias("no-pager")
.action(ArgAction::SetTrue)
.overrides_with("no-paging")
.hide(true)
.hide_short_help(true)
.help("Alias for '--paging=never'")
)
.arg(
Arg::new("pager")
.long("pager")
.overrides_with("pager")
.value_name("command")
.hide_short_help(true)
.help("Determine which pager to use.")
.long_help(
"Determine which pager is used. This option will override the \
PAGER and BAT_PAGER environment variables. The default pager is 'less'. \
If you provide '--pager=builtin', use the built-in 'minus' pager. \
To control when the pager is used, see the '--paging' option. \
Example: '--pager \"less -RF\"'."
),
)
.arg(
Arg::new("map-syntax")
.short('m')
.long("map-syntax")
.action(ArgAction::Append)
.value_name("glob:syntax")
.help("Use the specified syntax for files matching the glob pattern ('*.cpp:C++').")
.long_help(
"Map a glob pattern to an existing syntax name. The glob pattern is matched \
on the full path and the filename. For example, to highlight *.build files \
with the Python syntax, use -m '*.build:Python'. To highlight files named \
'.myignore' with the Git Ignore syntax, use -m '.myignore:Git Ignore'. Note \
that the right-hand side is the *name* of the syntax, not a file extension.",
)
)
.arg(
Arg::new("ignored-suffix")
.action(ArgAction::Append)
.long("ignored-suffix")
.hide_short_help(true)
.help(
"Ignore extension. For example:\n \
'bat --ignored-suffix \".dev\" my_file.json.dev' will use JSON syntax, and ignore '.dev'"
)
)
.arg(
Arg::new("theme")
.long("theme")
.overrides_with("theme")
.help("Set the color theme for syntax highlighting.")
.long_help(
"Set the theme for syntax highlighting. Use '--list-themes' to \
see all available themes. To set a default theme, add the \
'--theme=\"...\"' option to the configuration file or export the \
BAT_THEME environment variable (e.g.: export \
BAT_THEME=\"...\").\n\n\
Special values:\n\n \
* auto: Picks a dark or light theme depending on the terminal's colors (default).\n \
Use '--theme-light' and '--theme-dark' to customize the selected theme.\n \
* auto:always: Detect the terminal's colors even when the output is redirected.\n \
* auto:system: Detect the color scheme from the system-wide preference (macOS only).\n \
* dark: Use the dark theme specified by '--theme-dark'.\n \
* light: Use the light theme specified by '--theme-light'.",
),
)
.arg(
Arg::new("theme-light")
.long("theme-light")
.overrides_with("theme-light")
.value_name("theme")
.help("Sets the color theme for syntax highlighting used for light backgrounds.")
.long_help(
"Sets the theme name for syntax highlighting used when the terminal uses a light background. \
Use '--list-themes' to see all available themes. To set a default theme, add the \
'--theme-light=\"...\" option to the configuration file or export the BAT_THEME_LIGHT \
environment variable (e.g. export BAT_THEME_LIGHT=\"...\")."),
)
.arg(
Arg::new("theme-dark")
.long("theme-dark")
.overrides_with("theme-dark")
.value_name("theme")
.help("Sets the color theme for syntax highlighting used for dark backgrounds.")
.long_help(
"Sets the theme name for syntax highlighting used when the terminal uses a dark background. \
Use '--list-themes' to see all available themes. To set a default theme, add the \
'--theme-dark=\"...\" option to the configuration file or export the BAT_THEME_DARK \
environment variable (e.g. export BAT_THEME_DARK=\"...\")."),
)
.arg(
Arg::new("list-themes")
.long("list-themes")
.action(ArgAction::SetTrue)
.help("Display all supported highlighting themes.")
.long_help("Display a list of supported themes for syntax highlighting."),
)
.arg(
Arg::new("squeeze-blank")
.long("squeeze-blank")
.short('s')
.action(ArgAction::SetTrue)
.help("Squeeze consecutive empty lines.")
.long_help("Squeeze consecutive empty lines into a single empty line.")
)
.arg(
Arg::new("squeeze-limit")
.long("squeeze-limit")
.value_parser(|s: &str| s.parse::<usize>().map_err(|_| "Requires a non-negative number".to_owned()))
.long_help("Set the maximum number of consecutive empty lines to be printed.")
.hide_short_help(true)
)
.arg(
Arg::new("strip-ansi")
.long("strip-ansi")
.overrides_with("strip-ansi")
.value_name("when")
.value_parser(["auto", "always", "never"])
.default_value("never")
.hide_default_value(true)
.help("Strip colors from the input (auto, always, *never*)")
.long_help("Specify when to strip ANSI escape sequences from the input. \
The automatic mode will remove escape sequences unless the syntax highlighting \
language is plain text. Possible values: auto, always, *never*.")
.hide_short_help(true)
)
.arg(
Arg::new("style")
.long("style")
.action(ArgAction::Append)
.value_name("components")
// Cannot use claps built in validation because we have to turn off clap's delimiters
.value_parser(|val: &str| {
match StyleComponentList::from_str(val) {
Err(err) => Err(err),
Ok(_) => Ok(val.to_owned()),
}
})
.help(
"Comma-separated list of style elements to display \
(*default*, auto, full, plain, changes, header, header-filename, header-filesize, grid, rule, numbers, snip).",
)
.long_help(
"Configure which elements (line numbers, file headers, grid \
borders, Git modifications, ..) to display in addition to the \
file contents. The argument is a comma-separated list of \
components to display (e.g. 'numbers,changes,grid') or a \
pre-defined style ('full'). To set a default style, add the \
'--style=\"..\"' option to the configuration file or export the \
BAT_STYLE environment variable (e.g.: export BAT_STYLE=\"..\").\n\n\
When styles are specified in multiple places, the \"nearest\" set \
of styles take precedence. The command-line arguments are the highest \
priority, followed by the BAT_STYLE environment variable, and then \
the configuration file. If any set of styles consists entirely of \
components prefixed with \"+\" or \"-\", it will modify the \
previous set of styles instead of replacing them.\n\n\
By default, the following components are enabled:\n \
changes, grid, header-filename, numbers, snip\n\n\
Possible values:\n\n \
* default: enables recommended style components (default).\n \
* full: enables all available components.\n \
* auto: same as 'default', unless the output is piped.\n \
* plain: disables all available components.\n \
* changes: show Git modification markers.\n \
* header: alias for 'header-filename'.\n \
* header-filename: show filenames before the content.\n \
* header-filesize: show file sizes before the content.\n \
* grid: vertical/horizontal lines to separate side bar\n \
and the header from the content.\n \
* rule: horizontal lines to delimit files.\n \
* numbers: show line numbers in the side bar.\n \
* snip: draw separation lines between distinct line ranges.",
),
)
.arg(
Arg::new("line-range")
.long("line-range")
.short('r')
.action(ArgAction::Append)
.value_name("N:M")
.allow_hyphen_values(true)
.help("Only print the lines from N to M.")
.long_help(
"Only print the specified range of lines for each file. \
For example:\n \
'--line-range 30:40' prints lines 30 to 40\n \
'--line-range :40' prints lines 1 to 40\n \
'--line-range 40:' prints lines 40 to the end of the file\n \
'--line-range 40' only prints line 40\n \
'--line-range -10:' prints the last 10 lines\n \
'--line-range 30:+10' prints lines 30 to 40\n \
'--line-range 35::5' prints lines 30 to 40 (line 35 with 5 lines of context)\n \
'--line-range 30:40:2' prints lines 28 to 42 (range 30-40 with 2 lines of context)",
),
)
.arg(
Arg::new("list-languages")
.long("list-languages")
.short('L')
.action(ArgAction::SetTrue)
.conflicts_with("list-themes")
.help("Display all supported languages.")
.long_help("Display a list of supported languages for syntax highlighting."),
)
.arg(
Arg::new("unbuffered")
.short('u')
.long("unbuffered")
.action(ArgAction::SetTrue)
.hide_short_help(true)
.long_help(
"This option exists for POSIX-compliance reasons ('u' is for \
'unbuffered'). The output is always unbuffered - this option \
is simply ignored.",
),
)
.arg(
Arg::new("no-config")
.long("no-config")
.action(ArgAction::SetTrue)
.hide(true)
.help("Do not use the configuration file"),
)
.arg(
Arg::new("no-custom-assets")
.long("no-custom-assets")
.action(ArgAction::SetTrue)
.hide(true)
.help("Do not load custom assets"),
);
#[cfg(feature = "application")]
{
app = app.arg(
Arg::new("completion")
.long("completion")
.value_name("SHELL")
.value_parser(["bash", "fish", "ps1", "zsh"])
.help("Show shell completion for a certain shell. [possible values: bash, fish, zsh, ps1]"),
);
}
#[cfg(feature = "lessopen")]
{
app = app
.arg(
Arg::new("lessopen")
.long("lessopen")
.action(ArgAction::SetTrue)
.help("Enable the $LESSOPEN preprocessor"),
)
.arg(
Arg::new("no-lessopen")
.long("no-lessopen")
.action(ArgAction::SetTrue)
.overrides_with("lessopen")
.hide(true)
.help("Disable the $LESSOPEN preprocessor if enabled (overrides --lessopen)"),
)
}
app = app
.arg(
Arg::new("config-file")
.long("config-file")
.action(ArgAction::SetTrue)
.conflicts_with("list-languages")
.conflicts_with("list-themes")
.hide(true)
.help("Show path to the configuration file."),
)
.arg(
Arg::new("generate-config-file")
.long("generate-config-file")
.action(ArgAction::SetTrue)
.conflicts_with("list-languages")
.conflicts_with("list-themes")
.hide(true)
.help("Generates a default configuration file."),
)
.arg(
Arg::new("config-dir")
.long("config-dir")
.action(ArgAction::SetTrue)
.hide(true)
.help("Show bat's configuration directory."),
)
.arg(
Arg::new("cache-dir")
.long("cache-dir")
.action(ArgAction::SetTrue)
.hide(true)
.help("Show bat's cache directory."),
)
.arg(
Arg::new("diagnostic")
.long("diagnostic")
.alias("diagnostics")
.action(ArgAction::SetTrue)
.hide_short_help(true)
.help("Show diagnostic information for bug reports."),
)
.arg(
Arg::new("acknowledgements")
.long("acknowledgements")
.action(ArgAction::SetTrue)
.hide_short_help(true)
.help("Show acknowledgements."),
)
.arg(
Arg::new("set-terminal-title")
.long("set-terminal-title")
.action(ArgAction::SetTrue)
.hide_short_help(true)
.help("Sets terminal title to filenames when using a pager."),
)
.arg(
Arg::new("help")
.short('h')
.long("help")
.action(ArgAction::SetTrue)
.help("Print help (see more with '--help')")
.long_help("Print help (see a summary with '-h')"),
)
.arg(
Arg::new("version")
.long("version")
.short('V')
.action(ArgAction::Version)
.help("Print version"),
);
// Check if the current directory contains a file name cache. Otherwise,
// enable the 'bat cache' subcommand.
if Path::new("cache").exists() {
app
} else {
app.subcommand(
Command::new("cache")
.hide(true)
.about("Modify the syntax-definition and theme cache")
.arg(
Arg::new("build")
.long("build")
.short('b')
.action(ArgAction::SetTrue)
.help("Initialize (or update) the syntax/theme cache.")
.long_help(
"Initialize (or update) the syntax/theme cache by loading from \
the source directory (default: the configuration directory).",
),
)
.arg(
Arg::new("clear")
.long("clear")
.short('c')
.action(ArgAction::SetTrue)
.help("Remove the cached syntax definitions and themes."),
)
.group(
ArgGroup::new("cache-actions")
.args(["build", "clear"])
.required(true),
)
.arg(
Arg::new("source")
.long("source")
.requires("build")
.value_name("dir")
.help("Use a different directory to load syntaxes and themes from."),
)
.arg(
Arg::new("target")
.long("target")
.requires("build")
.value_name("dir")
.help(
"Use a different directory to store the cached syntax and theme set.",
),
)
.arg(
Arg::new("blank")
.long("blank")
.action(ArgAction::SetTrue)
.requires("build")
.help(
"Create completely new syntax and theme sets \
(instead of appending to the default sets).",
),
)
.arg(
Arg::new("acknowledgements")
.long("acknowledgements")
.action(ArgAction::SetTrue)
.requires("build")
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | true |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/bin/bat/main.rs | src/bin/bat/main.rs | #![deny(unsafe_code)]
mod app;
mod assets;
mod clap_app;
#[cfg(feature = "application")]
mod completions;
mod config;
mod directories;
mod input;
use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::io;
use std::io::{BufReader, Write};
use std::path::Path;
use std::process;
use bat::output::{OutputHandle, OutputType};
use bat::theme::DetectColorScheme;
use nu_ansi_term::Color::Green;
use nu_ansi_term::Style;
use crate::{
app::App,
config::{config_file, generate_config_file},
};
#[cfg(feature = "bugreport")]
use crate::config::system_config_file;
use assets::{assets_from_cache_or_binary, clear_assets};
use directories::PROJECT_DIRS;
use globset::GlobMatcher;
use bat::{
config::Config,
controller::Controller,
error::*,
input::Input,
style::{StyleComponent, StyleComponents},
theme::{color_scheme, default_theme, ColorScheme},
MappingTarget, PagingMode,
};
const THEME_PREVIEW_DATA: &[u8] = include_bytes!("../../../assets/theme_preview.rs");
#[cfg(feature = "build-assets")]
fn build_assets(matches: &clap::ArgMatches, config_dir: &Path, cache_dir: &Path) -> Result<()> {
let source_dir = matches
.get_one::<String>("source")
.map(Path::new)
.unwrap_or_else(|| config_dir);
bat::assets::build(
source_dir,
!matches.get_flag("blank"),
matches.get_flag("acknowledgements"),
cache_dir,
clap::crate_version!(),
)
}
fn run_cache_subcommand(
matches: &clap::ArgMatches,
#[cfg(feature = "build-assets")] config_dir: &Path,
default_cache_dir: &Path,
) -> Result<()> {
let cache_dir = matches
.get_one::<String>("target")
.map(Path::new)
.unwrap_or_else(|| default_cache_dir);
if matches.get_flag("build") {
#[cfg(feature = "build-assets")]
build_assets(matches, config_dir, cache_dir)?;
#[cfg(not(feature = "build-assets"))]
println!("bat has been built without the 'build-assets' feature. The 'cache --build' option is not available.");
} else if matches.get_flag("clear") {
clear_assets(cache_dir);
}
Ok(())
}
fn get_syntax_mapping_to_paths<'r, 't, I>(mappings: I) -> HashMap<&'t str, Vec<String>>
where
I: IntoIterator<Item = (&'r GlobMatcher, &'r MappingTarget<'t>)>,
't: 'r, // target text outlives rule
{
let mut map = HashMap::new();
for mapping in mappings {
if let (matcher, MappingTarget::MapTo(s)) = mapping {
let globs = map.entry(*s).or_insert_with(Vec::new);
globs.push(matcher.glob().glob().into());
}
}
map
}
pub fn get_languages(config: &Config, cache_dir: &Path) -> Result<String> {
let mut result: String = String::new();
let assets = assets_from_cache_or_binary(config.use_custom_assets, cache_dir)?;
let mut languages = assets
.get_syntaxes()?
.iter()
.filter(|syntax| !syntax.hidden && !syntax.file_extensions.is_empty())
.cloned()
.collect::<Vec<_>>();
// Handling of file-extension conflicts, see issue #1076
for lang in &mut languages {
let lang_name = lang.name.clone();
lang.file_extensions.retain(|extension| {
// The 'extension' variable is not certainly a real extension.
//
// Skip if 'extension' starts with '.', likely a hidden file like '.vimrc'
// Also skip if the 'extension' contains another real extension, likely
// that is a full match file name like 'CMakeLists.txt' and 'Cargo.lock'
if extension.starts_with('.') || Path::new(extension).extension().is_some() {
return true;
}
let test_file = Path::new("test").with_extension(extension);
let syntax_in_set = assets.get_syntax_for_path(test_file, &config.syntax_mapping);
matches!(syntax_in_set, Ok(syntax_in_set) if syntax_in_set.syntax.name == lang_name)
});
}
languages.sort_by_key(|lang| lang.name.to_uppercase());
let configured_languages = get_syntax_mapping_to_paths(config.syntax_mapping.all_mappings());
for lang in &mut languages {
if let Some(additional_paths) = configured_languages.get(lang.name.as_str()) {
lang.file_extensions
.extend(additional_paths.iter().cloned());
}
}
if config.loop_through {
for lang in languages {
writeln!(result, "{}:{}", lang.name, lang.file_extensions.join(",")).ok();
}
} else {
let longest = languages
.iter()
.map(|syntax| syntax.name.len())
.max()
.unwrap_or(32); // Fallback width if they have no language definitions.
let comma_separator = ", ";
let separator = " ";
// Line-wrapping for the possible file extension overflow.
let desired_width = config.term_width - longest - separator.len();
let style = if config.colored_output {
Green.normal()
} else {
Style::default()
};
for lang in languages {
write!(result, "{:width$}{separator}", lang.name, width = longest).ok();
// Number of characters on this line so far, wrap before `desired_width`
let mut num_chars = 0;
let mut extension = lang.file_extensions.iter().peekable();
while let Some(word) = extension.next() {
// If we can't fit this word in, then create a line break and align it in.
let new_chars = word.len() + comma_separator.len();
if num_chars + new_chars >= desired_width {
num_chars = 0;
write!(result, "\n{:width$}{separator}", "", width = longest).ok();
}
num_chars += new_chars;
write!(result, "{}", style.paint(&word[..])).ok();
if extension.peek().is_some() {
result += comma_separator;
}
}
result += "\n";
}
}
Ok(result)
}
fn theme_preview_file<'a>() -> Input<'a> {
Input::from_reader(Box::new(BufReader::new(THEME_PREVIEW_DATA)))
}
pub fn list_themes(
cfg: &Config,
config_dir: &Path,
cache_dir: &Path,
detect_color_scheme: DetectColorScheme,
) -> Result<()> {
let assets = assets_from_cache_or_binary(cfg.use_custom_assets, cache_dir)?;
let mut config = cfg.clone();
let mut style = HashSet::new();
style.insert(StyleComponent::Plain);
config.language = Some("Rust");
config.style_components = StyleComponents(style);
let default_theme_name = default_theme(color_scheme(detect_color_scheme).unwrap_or_default());
let mut buf = String::new();
let mut handle = OutputHandle::FmtWrite(&mut buf);
for theme in assets.themes() {
let default_theme_info = if default_theme_name == theme {
" (default)"
} else if default_theme(ColorScheme::Dark) == theme {
" (default dark)"
} else if default_theme(ColorScheme::Light) == theme {
" (default light)"
} else {
""
};
if config.colored_output {
handle.write_fmt(format_args!(
"{}{default_theme_info}\n\n",
Style::new().bold().paint(theme.to_string()),
))?;
config.theme = theme.to_string();
Controller::new(&config, &assets)
.run(vec![theme_preview_file()], Some(&mut handle))
.ok();
handle.write_fmt(format_args!("\n"))?;
} else if config.loop_through {
handle.write_fmt(format_args!("{theme}\n"))?;
} else {
handle.write_fmt(format_args!("{theme}{default_theme_info}\n"))?;
}
}
if config.colored_output {
handle.write_fmt(format_args!(
"Further themes can be installed to '{}', \
and are added to the cache with `bat cache --build`. \
For more information, see:\n\n \
https://github.com/sharkdp/bat#adding-new-themes",
config_dir.join("themes").to_string_lossy()
))?;
}
let mut output_type =
OutputType::from_mode(config.paging_mode, config.wrapping_mode, config.pager)?;
let mut writer = output_type.handle()?;
writer.write_fmt(format_args!("{buf}"))?;
Ok(())
}
fn set_terminal_title_to(new_terminal_title: String) {
let osc_command_for_setting_terminal_title = "\x1b]0;";
let osc_end_command = "\x07";
print!("{osc_command_for_setting_terminal_title}{new_terminal_title}{osc_end_command}");
io::stdout().flush().unwrap();
}
fn get_new_terminal_title(inputs: &Vec<Input>) -> String {
let mut new_terminal_title = "bat: ".to_string();
for (index, input) in inputs.iter().enumerate() {
new_terminal_title += input.description().title();
if index < inputs.len() - 1 {
new_terminal_title += ", ";
}
}
new_terminal_title
}
fn run_controller(inputs: Vec<Input>, config: &Config, cache_dir: &Path) -> Result<bool> {
let assets = assets_from_cache_or_binary(config.use_custom_assets, cache_dir)?;
let controller = Controller::new(config, &assets);
if config.paging_mode != PagingMode::Never && config.set_terminal_title {
set_terminal_title_to(get_new_terminal_title(&inputs));
}
controller.run(inputs, None)
}
#[cfg(feature = "bugreport")]
fn invoke_bugreport(app: &App, cache_dir: &Path) {
use bugreport::{bugreport, collector::*, format::Markdown};
let pager = bat::config::get_pager_executable(
app.matches.get_one::<String>("pager").map(|s| s.as_str()),
)
.unwrap_or_else(|| "less".to_owned()); // FIXME: Avoid non-canonical path to "less".
let mut custom_assets_metadata = cache_dir.to_path_buf();
custom_assets_metadata.push("metadata.yaml");
let mut report = bugreport!()
.info(SoftwareVersion::default())
.info(OperatingSystem::default())
.info(CommandLine::default())
.info(EnvironmentVariables::list(&[
"BAT_CACHE_PATH",
"BAT_CONFIG_PATH",
"BAT_OPTS",
"BAT_PAGER",
"BAT_PAGING",
"BAT_STYLE",
"BAT_TABS",
"BAT_THEME",
"COLORTERM",
"LANG",
"LC_ALL",
"LESS",
"MANPAGER",
"NO_COLOR",
"PAGER",
"SHELL",
"TERM",
"XDG_CACHE_HOME",
"XDG_CONFIG_HOME",
]))
.info(FileContent::new("System Config file", system_config_file()))
.info(FileContent::new("Config file", config_file()))
.info(FileContent::new(
"Custom assets metadata",
custom_assets_metadata,
))
.info(DirectoryEntries::new("Custom assets", cache_dir))
.info(CompileTimeInformation::default());
#[cfg(feature = "paging")]
if let Ok(resolved_path) = grep_cli::resolve_binary(pager) {
report = report.info(CommandOutput::new(
"Less version",
resolved_path,
&["--version"],
))
};
report.print::<Markdown>();
}
/// Returns `Err(..)` upon fatal errors. Otherwise, returns `Ok(true)` on full success and
/// `Ok(false)` if any intermediate errors occurred (were printed).
fn run() -> Result<bool> {
let app = App::new()?;
let config_dir = PROJECT_DIRS.config_dir();
let cache_dir = PROJECT_DIRS.cache_dir();
if app.matches.get_flag("diagnostic") {
#[cfg(feature = "bugreport")]
invoke_bugreport(&app, cache_dir);
#[cfg(not(feature = "bugreport"))]
println!("bat has been built without the 'bugreport' feature. The '--diagnostic' option is not available.");
return Ok(true);
}
#[cfg(feature = "application")]
if let Some(shell) = app.matches.get_one::<String>("completion") {
match shell.as_str() {
"bash" => println!("{}", completions::BASH_COMPLETION),
"fish" => println!("{}", completions::FISH_COMPLETION),
"ps1" => println!("{}", completions::PS1_COMPLETION),
"zsh" => println!("{}", completions::ZSH_COMPLETION),
_ => unreachable!("No completion for shell '{shell}' available."),
}
return Ok(true);
}
match app.matches.subcommand() {
Some(("cache", cache_matches)) => {
// If there is a file named 'cache' in the current working directory,
// arguments for subcommand 'cache' are not mandatory.
// If there are non-zero arguments, execute the subcommand cache, else, open the file cache.
if cache_matches.args_present() {
run_cache_subcommand(
cache_matches,
#[cfg(feature = "build-assets")]
config_dir,
cache_dir,
)?;
Ok(true)
} else {
let inputs = vec![Input::ordinary_file("cache")];
let config = app.config(&inputs)?;
run_controller(inputs, &config, cache_dir)
}
}
_ => {
let inputs = app.inputs()?;
let config = app.config(&inputs)?;
if app.matches.get_flag("list-languages") {
let languages: String = get_languages(&config, cache_dir)?;
let inputs: Vec<Input> = vec![Input::from_reader(Box::new(languages.as_bytes()))];
let plain_config = Config {
style_components: StyleComponents::new(StyleComponent::Plain.components(false)),
paging_mode: PagingMode::QuitIfOneScreen,
..Default::default()
};
run_controller(inputs, &plain_config, cache_dir)
} else if app.matches.get_flag("list-themes") {
list_themes(&config, config_dir, cache_dir, DetectColorScheme::default())?;
Ok(true)
} else if app.matches.get_flag("config-file") {
println!("{}", config_file().to_string_lossy());
Ok(true)
} else if app.matches.get_flag("generate-config-file") {
generate_config_file()?;
Ok(true)
} else if app.matches.get_flag("config-dir") {
writeln!(io::stdout(), "{}", config_dir.to_string_lossy())?;
Ok(true)
} else if app.matches.get_flag("cache-dir") {
writeln!(io::stdout(), "{}", cache_dir.to_string_lossy())?;
Ok(true)
} else if app.matches.get_flag("acknowledgements") {
writeln!(io::stdout(), "{}", bat::assets::get_acknowledgements())?;
Ok(true)
} else {
run_controller(inputs, &config, cache_dir)
}
}
}
}
fn main() {
let result = run();
match result {
Err(error) => {
let stderr = std::io::stderr();
default_error_handler(&error, &mut stderr.lock());
process::exit(1);
}
Ok(false) => {
process::exit(1);
}
Ok(true) => {
process::exit(0);
}
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/bin/bat/assets.rs | src/bin/bat/assets.rs | use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use clap::crate_version;
use bat::assets::HighlightingAssets;
use bat::assets_metadata::AssetsMetadata;
use bat::error::*;
pub fn clear_assets(cache_dir: &Path) {
clear_asset(cache_dir.join("themes.bin"), "theme set cache");
clear_asset(cache_dir.join("syntaxes.bin"), "syntax set cache");
clear_asset(cache_dir.join("metadata.yaml"), "metadata file");
}
pub fn assets_from_cache_or_binary(
use_custom_assets: bool,
cache_dir: &Path,
) -> Result<HighlightingAssets> {
if let Some(metadata) = AssetsMetadata::load_from_folder(cache_dir)? {
if !metadata.is_compatible_with(crate_version!()) {
return Err(format!(
"The binary caches for the user-customized syntaxes and themes \
in '{}' are not compatible with this version of bat ({}). To solve this, \
either rebuild the cache (bat cache --build) or remove \
the custom syntaxes/themes (bat cache --clear).\n\
For more information, see:\n\n \
https://github.com/sharkdp/bat#adding-new-syntaxes--language-definitions",
cache_dir.to_string_lossy(),
crate_version!()
)
.into());
}
}
let custom_assets = if use_custom_assets {
HighlightingAssets::from_cache(cache_dir).ok()
} else {
None
};
Ok(custom_assets.unwrap_or_else(HighlightingAssets::from_binary))
}
fn clear_asset(path: PathBuf, description: &str) {
print!("Clearing {description} ... ");
match fs::remove_file(&path) {
Err(err) if err.kind() == io::ErrorKind::NotFound => {
println!("skipped (not present)");
}
Err(err) => {
println!("could not remove the cache file {path:?}: {err}");
}
Ok(_) => println!("okay"),
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/bin/bat/input.rs | src/bin/bat/input.rs | use bat::input::Input;
use std::path::Path;
pub fn new_file_input<'a>(file: &'a Path, name: Option<&'a Path>) -> Input<'a> {
named(Input::ordinary_file(file), name.or(Some(file)))
}
pub fn new_stdin_input(name: Option<&Path>) -> Input<'_> {
named(Input::stdin(), name)
}
fn named<'a>(input: Input<'a>, name: Option<&Path>) -> Input<'a> {
if let Some(provided_name) = name {
let mut input = input.with_name(Some(provided_name));
input.description_mut().set_kind(Some("File".to_owned()));
input
} else {
input
}
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
sharkdp/bat | https://github.com/sharkdp/bat/blob/4e84e838a32e3b326a3d1f9e2cd4c879597ad74d/src/assets/build_assets.rs | src/assets/build_assets.rs | use std::convert::TryInto;
use std::path::Path;
use syntect::highlighting::ThemeSet;
use syntect::parsing::{SyntaxSet, SyntaxSetBuilder};
use crate::assets::*;
use acknowledgements::build_acknowledgements;
mod acknowledgements;
pub fn build(
source_dir: &Path,
include_integrated_assets: bool,
include_acknowledgements: bool,
target_dir: &Path,
current_version: &str,
) -> Result<()> {
let theme_set = build_theme_set(source_dir, include_integrated_assets)?;
let syntax_set_builder = build_syntax_set_builder(source_dir, include_integrated_assets)?;
let syntax_set = syntax_set_builder.build();
let acknowledgements = build_acknowledgements(source_dir, include_acknowledgements)?;
print_unlinked_contexts(&syntax_set);
write_assets(
&theme_set,
&syntax_set,
&acknowledgements,
target_dir,
current_version,
)
}
fn build_theme_set(source_dir: &Path, include_integrated_assets: bool) -> Result<LazyThemeSet> {
let mut theme_set = if include_integrated_assets {
crate::assets::get_integrated_themeset().try_into()?
} else {
ThemeSet::new()
};
let theme_dir = source_dir.join("themes");
if theme_dir.exists() {
let res = theme_set.add_from_folder(&theme_dir);
if let Err(err) = res {
println!(
"Failed to load one or more themes from '{}' (reason: '{err}')",
theme_dir.to_string_lossy(),
);
}
} else {
println!(
"No themes were found in '{}', using the default set",
theme_dir.to_string_lossy()
);
}
theme_set.try_into()
}
fn build_syntax_set_builder(
source_dir: &Path,
include_integrated_assets: bool,
) -> Result<SyntaxSetBuilder> {
let mut syntax_set_builder = if !include_integrated_assets {
let mut builder = syntect::parsing::SyntaxSetBuilder::new();
builder.add_plain_text_syntax();
builder
} else {
from_binary::<SyntaxSet>(get_serialized_integrated_syntaxset(), COMPRESS_SYNTAXES)
.into_builder()
};
let syntax_dir = source_dir.join("syntaxes");
if syntax_dir.exists() {
syntax_set_builder.add_from_folder(syntax_dir, true)?;
} else {
println!(
"No syntaxes were found in '{}', using the default set.",
syntax_dir.to_string_lossy()
);
}
Ok(syntax_set_builder)
}
fn print_unlinked_contexts(syntax_set: &SyntaxSet) {
let missing_contexts = syntax_set.find_unlinked_contexts();
if !missing_contexts.is_empty() {
println!("Some referenced contexts could not be found!");
for context in missing_contexts {
println!("- {context}");
}
}
}
fn write_assets(
theme_set: &LazyThemeSet,
syntax_set: &SyntaxSet,
acknowledgements: &Option<String>,
target_dir: &Path,
current_version: &str,
) -> Result<()> {
let _ = std::fs::create_dir_all(target_dir);
asset_to_cache(
theme_set,
&target_dir.join("themes.bin"),
"theme set",
COMPRESS_THEMES,
)?;
asset_to_cache(
syntax_set,
&target_dir.join("syntaxes.bin"),
"syntax set",
COMPRESS_SYNTAXES,
)?;
if let Some(acknowledgements) = acknowledgements {
asset_to_cache(
acknowledgements,
&target_dir.join("acknowledgements.bin"),
"acknowledgements",
COMPRESS_ACKNOWLEDGEMENTS,
)?;
}
print!(
"Writing metadata to folder {} ... ",
target_dir.to_string_lossy()
);
crate::assets_metadata::AssetsMetadata::new(current_version).save_to_folder(target_dir)?;
println!("okay");
Ok(())
}
pub(crate) fn asset_to_contents<T: serde::Serialize>(
asset: &T,
description: &str,
compressed: bool,
) -> Result<Vec<u8>> {
let mut contents = vec![];
if compressed {
bincode::serialize_into(
flate2::write::ZlibEncoder::new(&mut contents, flate2::Compression::best()),
asset,
)
} else {
bincode::serialize_into(&mut contents, asset)
}
.map_err(|_| format!("Could not serialize {description}"))?;
Ok(contents)
}
fn asset_to_cache<T: serde::Serialize>(
asset: &T,
path: &Path,
description: &str,
compressed: bool,
) -> Result<()> {
print!("Writing {description} to {} ... ", path.to_string_lossy());
let contents = asset_to_contents(asset, description, compressed)?;
std::fs::write(path, &contents[..])
.map_err(|_| format!("Could not save {description} to {}", path.to_string_lossy()))?;
println!("okay");
Ok(())
}
| rust | Apache-2.0 | 4e84e838a32e3b326a3d1f9e2cd4c879597ad74d | 2026-01-04T15:31:58.743241Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.