summaryrefslogtreecommitdiff
path: root/src/bin
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2019-10-14 17:32:37 +0200
committerLaurenz <laurmaedje@gmail.com>2019-10-14 18:07:18 +0200
commit5e41672a91536c1f740bbc1630a6908adff57329 (patch)
tree2f481ab7a205154b11deaf4925aa5a0f693d7f23 /src/bin
parent7c0899b5373cdc4f1083a0a8515856207c431423 (diff)
Refactor and refine PDF exporter ♻
Diffstat (limited to 'src/bin')
-rw-r--r--src/bin/main.rs30
1 files changed, 11 insertions, 19 deletions
diff --git a/src/bin/main.rs b/src/bin/main.rs
index 58b2c00e..c8028c7f 100644
--- a/src/bin/main.rs
+++ b/src/bin/main.rs
@@ -16,7 +16,6 @@ fn main() {
}
}
-/// The actual main function.
fn run() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = env::args().collect();
if args.len() < 2 || args.len() > 3 {
@@ -24,42 +23,30 @@ fn run() -> Result<(), Box<dyn Error>> {
}
let source_path = Path::new(&args[1]);
-
- // Compute the output filename from the input filename by replacing the
- // extension.
let dest_path = if args.len() <= 2 {
- let stem = source_path
- .file_stem()
- .ok_or_else(|| "missing destation file name")?;
-
- let base = source_path
- .parent()
- .ok_or_else(|| "missing destation folder")?;
-
- base.join(format!("{}.pdf", stem.to_string_lossy()))
+ source_path.with_extension("pdf")
} else {
PathBuf::from(&args[2])
};
if dest_path == source_path {
- return Err("source and destination path are the same".into());
+ return err("source and destination path are the same");
}
+ let mut source_file = File::open(source_path)
+ .map_err(|_| "failed to open source file")?;
+
let mut src = String::new();
- let mut source_file = File::open(source_path).map_err(|_| "failed to open source file")?;
source_file
.read_to_string(&mut src)
.map_err(|_| "failed to read from source file")?;
- // Create a typesetter with a font provider that provides the default fonts.
let mut typesetter = Typesetter::new();
let provider = FileSystemFontProvider::from_listing("fonts/fonts.toml").unwrap();
typesetter.add_font_provider(provider);
- // Typeset the source code.
let document = typesetter.typeset(&src)?;
- // Export the document into a PDF file.
let exporter = PdfExporter::new();
let dest_file = File::create(&dest_path)?;
exporter.export(&document, typesetter.loader(), BufWriter::new(dest_file))?;
@@ -67,7 +54,12 @@ fn run() -> Result<(), Box<dyn Error>> {
Ok(())
}
-/// Print a usage message and quit.
+/// Construct an error `Result` from a message.
+fn err<S: Into<String>, T>(message: S) -> Result<T, Box<dyn Error>> {
+ Err(message.into().into())
+}
+
+/// Print a usage message and exit the process.
fn help_and_quit() {
let name = env::args().next().unwrap_or("typst".to_string());
println!("usage: {} source [destination]", name);