This repository has been archived by the owner on Mar 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 64
/
main.rs
183 lines (163 loc) · 5.93 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// Copyright 2018-2020 Sebastian Wiesner <sebastian@swsnr.de>
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#![deny(warnings, clippy::all)]
//! Show CommonMark documents on TTYs.
use std::fs::File;
use std::io::prelude::*;
use std::io::Result;
use std::io::{stdin, BufWriter};
use std::path::PathBuf;
use pulldown_cmark::{Options, Parser};
use syntect::parsing::SyntaxSet;
use tracing::{event, instrument, Level};
use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::EnvFilter;
use crate::output::Output;
use mdcat::terminal::{TerminalProgram, TerminalSize};
use mdcat::ResourceAccess;
use mdcat::{Environment, Settings};
mod args;
mod output;
/// Read input for `filename`.
///
/// If `filename` is `-` read from standard input, otherwise try to open and
/// read the given file.
fn read_input<T: AsRef<str>>(filename: T) -> Result<(PathBuf, String)> {
let cd = std::env::current_dir()?;
let mut buffer = String::new();
if filename.as_ref() == "-" {
stdin().read_to_string(&mut buffer)?;
Ok((cd, buffer))
} else {
let mut source = File::open(filename.as_ref())?;
source.read_to_string(&mut buffer)?;
let base_dir = cd
.join(filename.as_ref())
.parent()
.map(|p| p.to_path_buf())
.unwrap_or(cd);
Ok((base_dir, buffer))
}
}
#[instrument(skip(output, settings), level = "debug")]
fn process_file(filename: &str, settings: &Settings, output: &mut Output) -> Result<()> {
let (base_dir, input) = read_input(filename)?;
event!(
Level::TRACE,
"Read input, using {} as base directory",
base_dir.display()
);
let parser = Parser::new_ext(
&input,
Options::ENABLE_TASKLISTS | Options::ENABLE_STRIKETHROUGH,
);
let env = Environment::for_local_directory(&base_dir)?;
let mut sink = BufWriter::new(output.writer());
// mdcat::push_tty(settings, &env, &mut sink, parser).expect("FUCK");
mdcat::push_tty(settings, &env, &mut sink, parser)
.and_then(|_| {
event!(Level::TRACE, "Finished rendering, flushing output");
sink.flush()
})
.or_else(|error| {
if error.kind() == std::io::ErrorKind::BrokenPipe {
event!(Level::TRACE, "Ignoring broken pipe");
Ok(())
} else {
event!(Level::ERROR, ?error, "Failed to process file: {:#}", error);
Err(error)
}
})
}
fn main() {
// Setup tracing
let filter = EnvFilter::builder()
// Disable all logging by default, to avoid interfering with regular output at all cost.
// tracing is a debugging tool here so we expect it to be enabled explicitly.
.with_default_directive(LevelFilter::OFF.into())
.with_env_var("MDCAT_LOG")
.from_env_lossy();
tracing_subscriber::fmt::Subscriber::builder()
.pretty()
.with_env_filter(filter)
.with_writer(std::io::stderr)
.init();
use crate::args::Args;
use clap::Parser;
let args = Args::parse().command;
event!(target: "mdcat::main", Level::TRACE, ?args, "mdcat arguments");
let terminal = if args.no_colour {
TerminalProgram::Dumb
} else if args.paginate() || args.ansi_only {
// A pager won't support any terminal-specific features
TerminalProgram::Ansi
} else {
TerminalProgram::detect()
};
if args.detect_and_exit {
println!("Terminal: {terminal}");
} else {
// On Windows 10 we need to enable ANSI term explicitly.
#[cfg(windows)]
{
event!(target: "mdcat::main", Level::TRACE, "Enable ANSI support in windows terminal");
ansi_term::enable_ansi_support().ok();
}
let size = TerminalSize::detect().unwrap_or_default();
let columns = args.columns.unwrap_or(size.columns);
let exit_code = match Output::new(args.paginate()) {
Ok(mut output) => {
let settings = Settings {
terminal_capabilities: terminal.capabilities(),
terminal_size: TerminalSize { columns, ..size },
resource_access: if args.local_only {
ResourceAccess::LocalOnly
} else {
ResourceAccess::RemoteAllowed
},
syntax_set: SyntaxSet::load_defaults_newlines(),
};
event!(
target: "mdcat::main",
Level::TRACE,
?settings.terminal_size,
?settings.terminal_capabilities,
?settings.resource_access,
"settings"
);
args.filenames
.iter()
.try_fold(0, |code, filename| {
process_file(filename, &settings, &mut output)
.map(|_| code)
.or_else(|error| {
eprintln!("Error: {filename}: {error}");
if args.fail_fast {
Err(error)
} else {
Ok(1)
}
})
})
.unwrap_or(1)
}
Err(error) => {
eprintln!("Error: {error:#}");
128
}
};
event!(target: "mdcat::main", Level::TRACE, "Exiting with final exit code {}", exit_code);
std::process::exit(exit_code);
}
}
#[cfg(test)]
mod tests {
use crate::args::Args;
use clap::CommandFactory;
#[test]
fn verify_app() {
Args::command().debug_assert();
}
}