Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Repl no color no header flags #7040

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions crates/cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 69,8 @@ pub const FLAG_NO_LINK: &str = "no-link";
pub const FLAG_TARGET: &str = "target";
pub const FLAG_TIME: &str = "time";
pub const FLAG_VERBOSE: &str = "verbose";
pub const FLAG_NO_COLOR: &str = "no-color";
pub const FLAG_NO_HEADER: &str = "no-header";
pub const FLAG_LINKER: &str = "linker";
pub const FLAG_PREBUILT: &str = "prebuilt-platform";
pub const FLAG_CHECK: &str = "check";
Expand Down Expand Up @@ -271,6 273,20 @@ pub fn build_app() -> Command {
)
.subcommand(Command::new(CMD_REPL)
.about("Launch the interactive Read Eval Print Loop (REPL)")
.arg(
Arg::new(FLAG_NO_COLOR)
.long(FLAG_NO_COLOR)
.help("Do not use any ANSI color codes in the repl output")
.action(ArgAction::SetTrue)
.required(false)
)
.arg(
Arg::new(FLAG_NO_HEADER)
.long(FLAG_NO_HEADER)
.help("Do not print the repl header")
.action(ArgAction::SetTrue)
.required(false)
)
)
.subcommand(Command::new(CMD_RUN)
.about("Run a .roc file even if it has build errors")
Expand Down
12 changes: 9 additions & 3 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 6,9 @@ use roc_cli::{
build_app, format_files, format_src, test, BuildConfig, FormatMode, CMD_BUILD, CMD_CHECK,
CMD_DEV, CMD_DOCS, CMD_FORMAT, CMD_GEN_STUB_LIB, CMD_GLUE, CMD_PREPROCESS_HOST, CMD_REPL,
CMD_RUN, CMD_TEST, CMD_VERSION, DIRECTORY_OR_FILES, FLAG_CHECK, FLAG_DEV, FLAG_LIB, FLAG_MAIN,
FLAG_NO_LINK, FLAG_OUTPUT, FLAG_PP_DYLIB, FLAG_PP_HOST, FLAG_PP_PLATFORM, FLAG_STDIN,
FLAG_STDOUT, FLAG_TARGET, FLAG_TIME, GLUE_DIR, GLUE_SPEC, ROC_FILE,
FLAG_NO_COLOR, FLAG_NO_HEADER, FLAG_NO_LINK, FLAG_OUTPUT, FLAG_PP_DYLIB, FLAG_PP_HOST,
FLAG_PP_PLATFORM, FLAG_STDIN, FLAG_STDOUT, FLAG_TARGET, FLAG_TIME, GLUE_DIR, GLUE_SPEC,
ROC_FILE,
};
use roc_docs::generate_docs_html;
use roc_error_macros::user_error;
Expand Down Expand Up @@ -242,7 243,12 @@ fn main() -> io::Result<()> {
}
}
}
Some((CMD_REPL, _)) => Ok(roc_repl_cli::main()),
Some((CMD_REPL, matches)) => {
let has_color = !matches.get_one::<bool>(FLAG_NO_COLOR).unwrap();
let has_header = !matches.get_one::<bool>(FLAG_NO_HEADER).unwrap();

Ok(roc_repl_cli::main(has_color, has_header))
}
Some((CMD_DOCS, matches)) => {
let root_path = matches.get_one::<PathBuf>(ROC_FILE).unwrap();
let out_dir = matches.get_one::<OsString>(FLAG_OUTPUT).unwrap();
Expand Down
4 changes: 2 additions & 2 deletions crates/compiler/load_internal/src/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1665,7 1665,7 @@ fn state_thread_step<'a>(
Ok(ControlFlow::Break(LoadResult::Monomorphized(monomorphized)))
}
Msg::FailedToReadFile { filename, error } => {
let buf = to_file_problem_report_string(filename, error);
let buf = to_file_problem_report_string(filename, error, true);
Err(LoadingProblem::FormattedReport(buf))
}

Expand Down Expand Up @@ -1839,7 1839,7 @@ pub fn report_loading_problem(
}
LoadingProblem::FormattedReport(report) => report,
LoadingProblem::FileProblem { filename, error } => {
to_file_problem_report_string(filename, error)
to_file_problem_report_string(filename, error, true)
}
LoadingProblem::NoPlatformPackage {
filename,
Expand Down
40 changes: 33 additions & 7 deletions crates/repl_cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 9,13 @@ use roc_repl_eval::gen::Problems;
use roc_repl_ui::colors::{CYAN, END_COL};
use roc_repl_ui::repl_state::{ReplAction, ReplState};
use roc_repl_ui::{format_output, is_incomplete, CONT_PROMPT, PROMPT, SHORT_INSTRUCTIONS, TIPS};
use roc_reporting::report::{to_file_problem_report_string, ANSI_STYLE_CODES, DEFAULT_PALETTE};
use roc_reporting::report::{
strip_colors, to_file_problem_report_string, ANSI_STYLE_CODES, DEFAULT_PALETTE,
};
use roc_target::Target;
use rustyline::highlight::{Highlighter, PromptInfo};
use rustyline::validate::{self, ValidationContext, ValidationResult, Validator};
use rustyline::Config;
use rustyline_derive::{Completer, Helper, Hinter};
use std::borrow::Cow;
use target_lexicon::Triple;
Expand All @@ -34,23 37,43 @@ pub struct ReplHelper {
state: ReplState,
}

pub fn main() -> i32 {
pub fn main(has_color: bool, has_header: bool) -> i32 {
use rustyline::error::ReadlineError;
use rustyline::Editor;

let strip_colors_if_necessary = |s: &str| {
if has_color {
s.to_string()
} else {
strip_colors(s)
}
};

// To debug rustyline:
// <UNCOMMENT> env_logger::init();
// <RUN WITH:> RUST_LOG=rustyline=debug cargo run repl 2> debug.log
print!("{WELCOME_MESSAGE}{SHORT_INSTRUCTIONS}");
if has_header {
print!(
"{}{}",
strip_colors_if_necessary(WELCOME_MESSAGE),
strip_colors_if_necessary(SHORT_INSTRUCTIONS),
);
}

let mut editor = Editor::<ReplHelper>::new();
let editor_color_mode = if has_color {
rustyline::ColorMode::Enabled
} else {
rustyline::ColorMode::Disabled
};
let mut editor =
Editor::<ReplHelper>::with_config(Config::builder().color_mode(editor_color_mode).build());
let repl_helper = ReplHelper::default();
editor.set_helper(Some(repl_helper));
let target = Triple::host().into();
let mut arena = Bump::new();

loop {
match editor.readline(PROMPT) {
match editor.readline(&strip_colors_if_necessary(PROMPT)) {
Ok(line) => {
let line = line.trim();

Expand All @@ -68,14 91,17 @@ pub fn main() -> i32 {
// If there was no output, don't print a blank line!
// (This happens for something like a type annotation.)
if !output.is_empty() {
println!("{output}");
println!("{}", strip_colors_if_necessary(&output));
}
}
ReplAction::Exit => {
return 0;
}
ReplAction::FileProblem { filename, error } => {
println!("{}", to_file_problem_report_string(filename, error));
println!(
"{}",
to_file_problem_report_string(filename, error, has_color)
);
}
ReplAction::Help => {
println!("{TIPS}");
Expand Down
48 changes: 46 additions & 2 deletions crates/reporting/src/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,10 255,43 @@ const fn default_palette_from_style_codes(codes: StyleCodes) -> Palette {
}
}

/// Set colorless styles for printing with no color,
/// given a set of StyleCodes for an environment (web or terminal).
const fn no_color_palette_from_style_codes(codes: StyleCodes) -> Palette {
Palette {
primary: codes.no_color,
code_block: codes.no_color,
keyword: codes.no_color,
ellipsis: codes.no_color,
variable: codes.no_color,
type_variable: codes.no_color,
structure: codes.no_color,
alias: codes.no_color,
opaque: codes.no_color,
error: codes.no_color,
line_number: codes.no_color,
header: codes.no_color,
gutter_bar: codes.no_color,
module_name: codes.no_color,
binop: codes.no_color,
typo: codes.no_color,
typo_suggestion: codes.no_color,
parser_suggestion: codes.no_color,
bold: codes.no_color,
underline: codes.no_color,
reset: codes.no_color,
warning: codes.no_color,
}
}

pub const DEFAULT_PALETTE: Palette = default_palette_from_style_codes(ANSI_STYLE_CODES);

pub const DEFAULT_PALETTE_HTML: Palette = default_palette_from_style_codes(HTML_STYLE_CODES);

pub const NO_COLOR_PALETTE: Palette = no_color_palette_from_style_codes(ANSI_STYLE_CODES);

pub const NO_COLOR_PALETTE_HTML: Palette = no_color_palette_from_style_codes(HTML_STYLE_CODES);

/// A machine-readable format for text styles (colors and other styles)
#[derive(Debug, PartialEq)]
pub struct StyleCodes {
Expand All @@ -270,6 303,7 @@ pub struct StyleCodes {
pub bold: &'static str,
pub underline: &'static str,
pub reset: &'static str,
pub no_color: &'static str,
}

pub const ANSI_STYLE_CODES: StyleCodes = StyleCodes {
Expand All @@ -281,6 315,7 @@ pub const ANSI_STYLE_CODES: StyleCodes = StyleCodes {
bold: "\u{001b}[1m",
underline: "\u{001b}[4m",
reset: "\u{001b}[0m",
no_color: "",
};

macro_rules! html_color {
Expand All @@ -298,6 333,7 @@ pub const HTML_STYLE_CODES: StyleCodes = StyleCodes {
bold: "<span class='bold'>",
underline: "<span class='underline'>",
reset: "</span>",
no_color: "",
};

// useful for tests
Expand Down Expand Up @@ -1652,7 1688,11 @@ pub fn to_https_problem_report<'b>(
}
}

pub fn to_file_problem_report_string(filename: PathBuf, error: io::ErrorKind) -> String {
pub fn to_file_problem_report_string(
filename: PathBuf,
error: io::ErrorKind,
has_color: bool,
) -> String {
let src_lines: Vec<&str> = Vec::new();
let mut module_ids = ModuleIds::default();
let module_id = module_ids.get_or_insert(&"find module name somehow?".into());
Expand All @@ -1662,7 1702,11 @@ pub fn to_file_problem_report_string(filename: PathBuf, error: io::ErrorKind) ->
let alloc = RocDocAllocator::new(&src_lines, module_id, &interns);

let mut buf = String::new();
let palette = DEFAULT_PALETTE;
let palette = if has_color {
DEFAULT_PALETTE
} else {
NO_COLOR_PALETTE
};
let report = to_file_problem_report(&alloc, filename, error);
report.render_color_terminal(&mut buf, &alloc, &palette);

Expand Down