Skip to content

Commit 201e52e

Browse files
committed
Auto merge of #63175 - jsgf:argsfile, r=jsgf
rustc: implement argsfiles for command line Many tools, such as gcc and gnu-ld, support "args files" - that is, being able to specify @file on the command line. This causes `file` to be opened and parsed for command line options. They're separated with whitespace; whitespace can be quoted with double or single quotes, and everything can be \\-escaped. Args files may recursively include other args files via `@file2`. See https://sourceware.org/binutils/docs/ld/Options.html#Options for the documentation of gnu-ld's @file parameters. This is useful for very large command lines, or when command lines are being generated into files by other tooling.
2 parents 42dcd4b + d949774 commit 201e52e

10 files changed

+139
-8
lines changed

src/doc/rustc/src/command-line-arguments.md

+7
Original file line numberDiff line numberDiff line change
@@ -304,3 +304,10 @@ to customize the output:
304304

305305
Note that it is invalid to combine the `--json` argument with the `--color`
306306
argument, and it is required to combine `--json` with `--error-format=json`.
307+
308+
## `@path`: load command-line flags from a path
309+
310+
If you specify `@path` on the command-line, then it will open `path` and read
311+
command line options from it. These options are one per line; a blank line indicates
312+
an empty option. The file can use Unix or Windows style line endings, and must be
313+
encoded as UTF-8.

src/librustc_driver/args.rs

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
use std::error;
2+
use std::fmt;
3+
use std::fs;
4+
use std::io;
5+
use std::str;
6+
use std::sync::atomic::{AtomicBool, Ordering};
7+
8+
static USED_ARGSFILE_FEATURE: AtomicBool = AtomicBool::new(false);
9+
10+
pub fn used_unstable_argsfile() -> bool {
11+
USED_ARGSFILE_FEATURE.load(Ordering::Relaxed)
12+
}
13+
14+
pub fn arg_expand(arg: String) -> Result<Vec<String>, Error> {
15+
if arg.starts_with("@") {
16+
let path = &arg[1..];
17+
let file = match fs::read_to_string(path) {
18+
Ok(file) => {
19+
USED_ARGSFILE_FEATURE.store(true, Ordering::Relaxed);
20+
file
21+
}
22+
Err(ref err) if err.kind() == io::ErrorKind::InvalidData => {
23+
return Err(Error::Utf8Error(Some(path.to_string())));
24+
}
25+
Err(err) => return Err(Error::IOError(path.to_string(), err)),
26+
};
27+
Ok(file.lines().map(ToString::to_string).collect())
28+
} else {
29+
Ok(vec![arg])
30+
}
31+
}
32+
33+
#[derive(Debug)]
34+
pub enum Error {
35+
Utf8Error(Option<String>),
36+
IOError(String, io::Error),
37+
}
38+
39+
impl fmt::Display for Error {
40+
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
41+
match self {
42+
Error::Utf8Error(None) => write!(fmt, "Utf8 error"),
43+
Error::Utf8Error(Some(path)) => write!(fmt, "Utf8 error in {}", path),
44+
Error::IOError(path, err) => write!(fmt, "IO Error: {}: {}", path, err),
45+
}
46+
}
47+
}
48+
49+
impl error::Error for Error {
50+
fn description(&self) -> &'static str {
51+
"argument error"
52+
}
53+
}

src/librustc_driver/lib.rs

+29-8
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ use syntax::symbol::sym;
6868
use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
6969

7070
pub mod pretty;
71+
mod args;
7172

7273
/// Exit status code used for successful compilation and help output.
7374
pub const EXIT_SUCCESS: i32 = 0;
@@ -141,14 +142,22 @@ impl Callbacks for TimePassesCallbacks {
141142
// See comments on CompilerCalls below for details about the callbacks argument.
142143
// The FileLoader provides a way to load files from sources other than the file system.
143144
pub fn run_compiler(
144-
args: &[String],
145+
at_args: &[String],
145146
callbacks: &mut (dyn Callbacks + Send),
146147
file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
147148
emitter: Option<Box<dyn Write + Send>>
148149
) -> interface::Result<()> {
150+
let mut args = Vec::new();
151+
for arg in at_args {
152+
match args::arg_expand(arg.clone()) {
153+
Ok(arg) => args.extend(arg),
154+
Err(err) => early_error(ErrorOutputType::default(),
155+
&format!("Failed to load argument file: {}", err)),
156+
}
157+
}
149158
let diagnostic_output = emitter.map(|emitter| DiagnosticOutput::Raw(emitter))
150159
.unwrap_or(DiagnosticOutput::Default);
151-
let matches = match handle_options(args) {
160+
let matches = match handle_options(&args) {
152161
Some(matches) => matches,
153162
None => return Ok(()),
154163
};
@@ -779,13 +788,19 @@ fn usage(verbose: bool, include_unstable_options: bool) {
779788
} else {
780789
"\n --help -v Print the full set of options rustc accepts"
781790
};
782-
println!("{}\nAdditional help:
791+
let at_path = if verbose && nightly_options::is_nightly_build() {
792+
" @path Read newline separated options from `path`\n"
793+
} else {
794+
""
795+
};
796+
println!("{options}{at_path}\nAdditional help:
783797
-C help Print codegen options
784798
-W help \
785-
Print 'lint' options and default settings{}{}\n",
786-
options.usage(message),
787-
nightly_help,
788-
verbose_help);
799+
Print 'lint' options and default settings{nightly}{verbose}\n",
800+
options = options.usage(message),
801+
at_path = at_path,
802+
nightly = nightly_help,
803+
verbose = verbose_help);
789804
}
790805

791806
fn print_wall_help() {
@@ -1010,6 +1025,12 @@ pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
10101025
// (unstable option being used on stable)
10111026
nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
10121027

1028+
// Late check to see if @file was used without unstable options enabled
1029+
if crate::args::used_unstable_argsfile() && !nightly_options::is_unstable_enabled(&matches) {
1030+
early_error(ErrorOutputType::default(),
1031+
"@path is unstable - use -Z unstable-options to enable its use");
1032+
}
1033+
10131034
if matches.opt_present("h") || matches.opt_present("help") {
10141035
// Only show unstable options in --help if we accept unstable options.
10151036
usage(matches.opt_present("verbose"), nightly_options::is_unstable_enabled(&matches));
@@ -1190,7 +1211,7 @@ pub fn main() {
11901211
let result = report_ices_to_stderr_if_any(|| {
11911212
let args = env::args_os().enumerate()
11921213
.map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1193-
early_error(ErrorOutputType::default(),
1214+
early_error(ErrorOutputType::default(),
11941215
&format!("Argument {} is not valid Unicode: {:?}", i, arg))
11951216
}))
11961217
.collect::<Vec<_>>();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
--cfg
2+
unbroken�
+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Check to see if we can get parameters from an @argsfile file
2+
//
3+
// build-fail
4+
// compile-flags: --cfg cmdline_set @{{src-base}}/commandline-argfile-badutf8.args
5+
6+
#[cfg(not(cmdline_set))]
7+
compile_error!("cmdline_set not set");
8+
9+
#[cfg(not(unbroken))]
10+
compile_error!("unbroken not set");
11+
12+
fn main() {
13+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
error: Failed to load argument file: Utf8 error in $DIR/commandline-argfile-badutf8.args
2+
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Check to see if we can get parameters from an @argsfile file
2+
//
3+
// ignore-tidy-linelength
4+
// build-fail
5+
// normalize-stderr-test: "os error \d+" -> "os error $$ERR"
6+
// normalize-stderr-test: "commandline-argfile-missing.args:[^(]*" -> "commandline-argfile-missing.args: $$FILE_MISSING "
7+
// compile-flags: --cfg cmdline_set @{{src-base}}/commandline-argfile-missing.args
8+
9+
#[cfg(not(cmdline_set))]
10+
compile_error!("cmdline_set not set");
11+
12+
#[cfg(not(unbroken))]
13+
compile_error!("unbroken not set");
14+
15+
fn main() {
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
error: Failed to load argument file: IO Error: $DIR/commandline-argfile-missing.args: $FILE_MISSING (os error $ERR)
2+

src/test/ui/commandline-argfile.args

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
--cfg
2+
unbroken

src/test/ui/commandline-argfile.rs

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Check to see if we can get parameters from an @argsfile file
2+
//
3+
// build-pass
4+
// compile-flags: --cfg cmdline_set @{{src-base}}/commandline-argfile.args
5+
6+
#[cfg(not(cmdline_set))]
7+
compile_error!("cmdline_set not set");
8+
9+
#[cfg(not(unbroken))]
10+
compile_error!("unbroken not set");
11+
12+
fn main() {
13+
}

0 commit comments

Comments
 (0)