1use std::{2 fs,3 io::{self, Write as _},4 path::PathBuf,5 process,6};78use clap::Parser;9use jrsonnet_formatter::{FormatOptions, format};1011#[derive(Parser)]12#[allow(clippy::struct_excessive_bools)]13struct Opts {14 15 #[clap(long, short = 'e')]16 exec: bool,17 18 input: String,19 20 21 #[clap(long, short = 'i')]22 in_place: bool,2324 25 #[arg(long)]26 test: bool,27 28 #[arg(long, default_value = "2")]29 indent: u8,30 31 #[arg(long)]32 hard_tabs: bool,3334 35 36 37 #[arg(long, default_value = "0")]38 conv_limit: usize,39}4041#[derive(thiserror::Error, Debug)]42enum Error {43 #[error("--in-place is incompatible with --exec")]44 InPlaceExec,45 #[error("io: {0}")]46 Io(#[from] io::Error),47 #[error("persist: {0}")]48 Persist(#[from] tempfile::PersistError),49 #[error("parsing failed, refusing to reformat corrupted input")]50 Parse,51}5253fn main_result() -> Result<(), Error> {54 eprintln!(55 "jrsonnet-fmt is a prototype of a jsonnet code formatter, do not expect it to produce meaningful results right now."56 );57 eprintln!(58 "It is not expected for its output to match other implementations, it will be completly separate implementation with maybe different name."59 );60 let mut opts = Opts::parse();61 let input = if opts.exec {62 if opts.in_place {63 return Err(Error::InPlaceExec);64 }65 opts.input.clone()66 } else {67 fs::read_to_string(&opts.input)?68 };6970 if opts.indent == 0 {71 72 73 opts.hard_tabs = true;74 }7576 let mut iteration = 0;77 let mut formatted = input.clone();78 let mut convergence_tmp;79 80 loop {81 let reformatted = match format(82 &formatted,83 &FormatOptions {84 indent: if opts.indent == 0 || opts.hard_tabs {85 086 } else {87 opts.indent88 },89 },90 ) {91 Ok(v) => v,92 Err(e) => {93 let snippet = e.build();94 let ansi = hi_doc::source_to_ansi(&snippet);95 eprintln!("{ansi}");96 return Err(Error::Parse);97 }98 };99 convergence_tmp = reformatted.trim().to_owned();100 if formatted == convergence_tmp {101 break;102 }103 formatted = convergence_tmp;104 if opts.conv_limit == 0 {105 break;106 }107 iteration += 1;108 assert!(iteration <= opts.conv_limit, "formatting not converged");109 }110 formatted.push('\n');111 if opts.test && formatted != input {112 process::exit(1);113 }114 if opts.in_place {115 let path = PathBuf::from(opts.input);116 let mut temp = tempfile::NamedTempFile::new_in(path.parent().expect(117 "not failed during read, this path is not a directory, and there is a parent",118 ))?;119 temp.write_all(formatted.as_bytes())?;120 temp.flush()?;121 temp.persist(&path)?;122 } else {123 print!("{formatted}");124 }125 Ok(())126}127128fn main() {129 if let Err(e) = main_result() {130 eprintln!("{e}");131 process::exit(1);132 }133}