Skip to content

rustfmt: Add --file-lines flag behind an env var #844

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

Closed
wants to merge 3 commits into from
Closed
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
6 changes: 6 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ syntex_syntax = "0.23.0"
log = "0.3.2"
env_logger = "0.3.1"
getopts = "0.2"
nom = "1.2.1"
128 changes: 127 additions & 1 deletion src/bin/rustfmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,19 @@

#[macro_use]
extern crate log;
#[macro_use]
extern crate nom;

extern crate rustfmt;
extern crate toml;
extern crate env_logger;
extern crate getopts;

use nom::IResult;

use rustfmt::{run, run_from_stdin};
use rustfmt::config::{Config, WriteMode};
use rustfmt::config::{FileLinesMap, LineRanges};

use std::env;
use std::fs::{self, File};
Expand Down Expand Up @@ -50,6 +56,10 @@ enum Operation {
input: String,
config_path: Option<PathBuf>,
},
/// Format a set of line ranges.
FormatLineRanges {
file_lines_map: FileLinesMap,
},
}

/// Try to find a project file in the given directory and its parents. Returns the path of a the
Expand Down Expand Up @@ -120,7 +130,9 @@ fn match_cli_path_or_file(config_path: Option<PathBuf>,

fn update_config(config: &mut Config, matches: &Matches) -> Result<(), String> {
config.verbose = matches.opt_present("verbose");
config.skip_children = matches.opt_present("skip-children");
// `file-lines` implies `skip-children`.
config.skip_children = matches.opt_present("skip-children") ||
(file_lines_enabled() && matches.opt_present("file-lines"));

let write_mode = matches.opt_str("write-mode");
match matches.opt_str("write-mode").map(|wm| WriteMode::from_str(&wm)) {
Expand All @@ -133,6 +145,13 @@ fn update_config(config: &mut Config, matches: &Matches) -> Result<(), String> {
}
}

fn file_lines_enabled() -> bool {
match env::var("RUSTFMT_EXPERIMENTAL_FILE_LINES") {
Ok(ref v) if v == "1" => true,
_ => false,
}
}

fn execute() -> i32 {
let mut opts = Options::new();
opts.optflag("h", "help", "show this message");
Expand All @@ -152,6 +171,13 @@ fn execute() -> i32 {
"Recursively searches the given path for the rustfmt.toml config file. If not \
found reverts to the input file path",
"[Path for the configuration file]");
if file_lines_enabled() {
opts.optmulti("",
"file-lines",
"Format specified line RANGEs in FILE. RANGEs are inclusive of both \
endpoints. May be specified multiple times.",
"FILE:RANGE,RANGE,...");
}

let matches = match opts.parse(env::args().skip(1)) {
Ok(m) => m,
Expand Down Expand Up @@ -228,6 +254,27 @@ fn execute() -> i32 {
}
0
}
// TODO: figure out what to do with config_path.
Operation::FormatLineRanges { file_lines_map } => {
for (file, line_ranges) in file_lines_map {
let (mut config, config_path) = resolve_config(file.parent().unwrap())
.expect(&format!("Error resolving config \
for {}",
file.display()));
if let Some(path) = config_path.as_ref() {
println!("Using rustfmt config file {} for {}",
path.display(),
file.display());
}
if let Err(e) = update_config(&mut config, &matches) {
print_usage(&opts, &e);
return 1;
}
config.line_ranges = line_ranges;
run(&file, &config);
}
0
}
}
}

Expand Down Expand Up @@ -283,6 +330,29 @@ fn determine_operation(matches: &Matches) -> Operation {
Some(dir)
});

if file_lines_enabled() && matches.opt_present("file-lines") {
let file_lines = matches.opt_strs("file-lines");
let mut file_lines_map = FileLinesMap::new();
for range_spec in file_lines {
let invalid = || {
Operation::InvalidInput {
reason: format!("invalid file-lines argument: {}", range_spec),
}
};

let (file, line_ranges) = match parse::file_lines_arg(&range_spec) {
IResult::Error(_) |
IResult::Incomplete(_) => return invalid(),
IResult::Done(remaining, _) if !remaining.is_empty() => return invalid(),
IResult::Done(_, (file, line_ranges)) => (file, line_ranges),
};

let entry = file_lines_map.entry(file).or_insert(LineRanges(Vec::new()));
entry.0.extend(line_ranges.0);
}
return Operation::FormatLineRanges { file_lines_map: file_lines_map };
}

// if no file argument is supplied, read from stdin
if matches.free.is_empty() {

Expand All @@ -305,3 +375,59 @@ fn determine_operation(matches: &Matches) -> Operation {
config_path: config_path,
}
}


/// Parser for the `file-lines` argument.
mod parse {
use std::path::PathBuf;
use std::str::FromStr;
use rustfmt::config::{LineRange, LineRanges};

use nom::digit;

named!(pub file_lines_arg<&str, (PathBuf, LineRanges)>,
chain!(
file: map!(
is_not_s!(":"),
PathBuf::from
) ~
tag_s!(":") ~
line_ranges: line_ranges,
|| (file, line_ranges)
)
);

named!(usize_digit<&str, usize>,
map_res!(
digit,
FromStr::from_str
)
);

named!(line_range<&str, LineRange>,
map_res!(
separated_pair!(
usize_digit,
tag_s!("-"),
usize_digit
),
|pair| {
let (lo, hi) = pair;
if lo < hi {
return Err(format!("empty line range: {}-{}", lo, hi));
}
Ok(LineRange { lo: lo, hi: hi })
}
)
);

named!(line_ranges<&str, LineRanges>,
map!(
separated_nonempty_list!(
tag_s!(","),
line_range
),
LineRanges
)
);
}
Loading