Skip to content

Accept manifest path option #3023

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 28 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
5f854ac
First pass at supporting manifest-path option to cargo-fmt
Sep 14, 2018
4d25d11
Use getopts to better detect invalid arguments
Sep 14, 2018
51724a3
propagate errors about failing to rewrite a macro
scampi Sep 7, 2018
7660ab4
normalize_doc_attributes option: convert doc attributes to comments
lqd Sep 7, 2018
3976b8c
Add a test for #2496
YaLTeR Aug 31, 2018
ace4a78
Add a test for match flattening
YaLTeR Sep 11, 2018
90fe2b0
Use correct heuristic for match block flattening
YaLTeR Sep 11, 2018
3288b2e
Add a test for #2985
YaLTeR Sep 11, 2018
d33480e
Fix last chain item shape for Visual indent_style
YaLTeR Sep 11, 2018
37a8cd4
fixes #2914 by handling BadIssue case
PSeitz Sep 11, 2018
bd770f9
implement Drop from FmtVisitor in order to simplify failures passing
scampi Sep 12, 2018
b1c3960
cargo fmt: fix typo in format_crate(): (verison -> version)
matthiaskrgr Sep 12, 2018
38a551d
move config attribute
lqd Sep 12, 2018
0efa58d
add test with multiple levels of indents
lqd Sep 12, 2018
5404fdf
add non-regression test to existing doc attributes
lqd Sep 12, 2018
bb61e16
add non-regression test to existing attributes
lqd Sep 12, 2018
b6176c5
address review comment in Attribute rewrite fn
lqd Sep 12, 2018
0935299
add tests interleaving doc attrib comments and regular comments
lqd Sep 13, 2018
abd39a6
add test ensuring only doc = "" attributes are normalized to comments
lqd Sep 13, 2018
f338cf6
Fix typo in README.md.
chaoticlonghair Sep 13, 2018
7ecb76f
Fix indent computation of a macro with braces.
scampi Sep 17, 2018
0f0af83
Improve error message when failing cargo metadata (#3024)
Sep 18, 2018
5c9e8bb
Add a test for #3006
topecongiro Sep 19, 2018
816f7f1
Format generics on associated types
topecongiro Sep 19, 2018
40917ad
Update tests
topecongiro Sep 19, 2018
47ba64b
Combine chain items only when the item will get orphaned
topecongiro Sep 19, 2018
54a8c73
Fix shape for index
topecongiro Sep 19, 2018
bdc64d0
Cargo fmt
topecongiro Sep 19, 2018
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
30 changes: 28 additions & 2 deletions Configurations.md
Original file line number Diff line number Diff line change
Expand Up @@ -1303,7 +1303,7 @@ fn main() {
});

match lorem {
None => if ipsum {
None => |ipsum| {
println!("Hello World");
},
Some(dolor) => foo(),
Expand All @@ -1324,7 +1324,7 @@ fn main() {

match lorem {
None => {
if ipsum {
|ipsum| {
println!("Hello World");
}
}
Expand Down Expand Up @@ -2188,6 +2188,32 @@ If you want to format code that requires edition 2018, add the following to your
edition = "2018"
```

## `normalize_doc_attributes`

Convert `#![doc]` and `#[doc]` attributes to `//!` and `///` doc comments.

- **Default value**: `false`
- **Possible values**: `true`, `false`
- **Stable**: No

#### `false` (default):

```rust
#![doc = "Example documentation"]

#[doc = "Example item documentation"]
pub enum Foo {}
```

#### `true`:

```rust
//! Example documentation

/// Example item documentation
pub enum Foo {}
```

## `emit_mode`

Internal option
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,15 +189,15 @@ See [Configurations.md](Configurations.md) for details.
Example:

```
cargo fmt --emit files
cargo fmt -- --emit files
```

Options:

| Flag |Description| Nightly Only |
|:---:|:---:|:---:|
| files | overwrites output to files | No |
| stdout | writes output to stdout | No |
| stdout | writes output to stdout | No |
| coverage | displays how much of the input file was processed | Yes |
| checkstyle | emits in a checkstyle format | Yes |

Expand Down
40 changes: 31 additions & 9 deletions src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

//! Format attributes and meta items.

use comment::{contains_comment, rewrite_doc_comment};
use comment::{contains_comment, rewrite_doc_comment, CommentStyle};
use config::lists::*;
use config::IndentStyle;
use expr::rewrite_literal;
Expand Down Expand Up @@ -229,7 +229,8 @@ impl Rewrite for ast::MetaItem {
None,
&inner_meta_item.ident,
shape,
).map_or(false, |s| s.len() + path.len() + 2 <= shape.width),
)
.map_or(false, |s| s.len() + path.len() + 2 <= shape.width),
_ => false,
}
}
Expand Down Expand Up @@ -350,13 +351,34 @@ impl Rewrite for ast::Attribute {
if contains_comment(snippet) {
return Some(snippet.to_owned());
}
// 1 = `[`
let shape = shape.offset_left(prefix.len() + 1)?;
Some(
self.meta()
.and_then(|meta| meta.rewrite(context, shape))
.map_or_else(|| snippet.to_owned(), |rw| format!("{}[{}]", prefix, rw)),
)

if let Some(ref meta) = self.meta() {
// This attribute is possibly a doc attribute needing normalization to a doc comment
if context.config.normalize_doc_attributes() && meta.check_name("doc") {
if let Some(ref literal) = meta.value_str() {
let comment_style = match self.style {
ast::AttrStyle::Inner => CommentStyle::Doc,
ast::AttrStyle::Outer => CommentStyle::TripleSlash,
};

let doc_comment = format!("{}{}", comment_style.opener(), literal);
return rewrite_doc_comment(
&doc_comment,
shape.comment(context.config),
context.config,
);
}
}

// 1 = `[`
let shape = shape.offset_left(prefix.len() + 1)?;
Some(
meta.rewrite(context, shape)
.map_or_else(|| snippet.to_owned(), |rw| format!("{}[{}]", prefix, rw)),
)
} else {
Some(snippet.to_owned())
}
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,8 @@ fn determine_operation(matches: &Matches) -> Result<Operation, ErrorKind> {
// we will do comparison later, so here tries to canonicalize first
// to get the expected behavior.
p.canonicalize().unwrap_or(p)
}).collect();
})
.collect();

Ok(Operation::Format {
files,
Expand Down
64 changes: 36 additions & 28 deletions src/cargo-fmt/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,22 +49,10 @@ fn execute() -> i32 {
"specify package to format (only usable in workspaces)",
"<package>",
);
opts.optopt("", "manifest-path", "Path to Cargo.toml", "<PATH>");
opts.optflag("", "version", "print rustfmt version and exit");
opts.optflag("", "all", "format all packages (only usable in workspaces)");

// If there is any invalid argument passed to `cargo fmt`, return without formatting.
let mut is_package_arg = false;
for arg in env::args().skip(2).take_while(|a| a != "--") {
if arg.starts_with('-') {
is_package_arg = arg.starts_with("--package");
} else if !is_package_arg {
print_usage_to_stderr(&opts, &format!("Invalid argument: `{}`.", arg));
return FAILURE;
} else {
is_package_arg = false;
}
}

let matches = match opts.parse(env::args().skip(1).take_while(|a| a != "--")) {
Ok(m) => m,
Err(e) => {
Expand All @@ -73,6 +61,12 @@ fn execute() -> i32 {
}
};

let invalid_arguments: Vec<&String> = matches.free.iter().take_while(|a| a.to_string() != "--").collect();
if !invalid_arguments.is_empty() {
print_usage_to_stderr(&opts, &format!("Invalid arguments: {}", matches.free.join(" ")));
return FAILURE;
}

let verbosity = match (matches.opt_present("v"), matches.opt_present("q")) {
(false, false) => Verbosity::Normal,
(false, true) => Verbosity::Quiet,
Expand All @@ -92,8 +86,12 @@ fn execute() -> i32 {
return handle_command_status(get_version(verbosity), &opts);
}

let manifest_path = matches
.opt_str("manifest-path")
.map(|path| PathBuf::from(path));
let manifest_path = manifest_path.as_ref().map(AsRef::as_ref);
let strategy = CargoFmtStrategy::from_matches(&matches);
handle_command_status(format_crate(verbosity, &strategy), &opts)
handle_command_status(format_crate(verbosity, &strategy, manifest_path), &opts)
}

macro_rules! print_usage {
Expand Down Expand Up @@ -145,15 +143,16 @@ fn get_version(verbosity: Verbosity) -> Result<ExitStatus, io::Error> {
fn format_crate(
verbosity: Verbosity,
strategy: &CargoFmtStrategy,
manifest_path: Option<&Path>,
) -> Result<ExitStatus, io::Error> {
let rustfmt_args = get_fmt_args();
let targets = if rustfmt_args
.iter()
.any(|s| ["--print-config", "-h", "--help", "-V", "--verison"].contains(&s.as_str()))
.any(|s| ["--print-config", "-h", "--help", "-V", "--version"].contains(&s.as_str()))
{
HashSet::new()
} else {
get_targets(strategy)?
get_targets(manifest_path, strategy)?
};

// Currently only bin and lib files get formatted
Expand All @@ -163,7 +162,8 @@ fn format_crate(
if verbosity == Verbosity::Verbose {
println!("[{}] {:?}", t.kind, t.path)
}
}).map(|t| t.path)
})
.map(|t| t.path)
.collect();

run_rustfmt(&files, &rustfmt_args, verbosity)
Expand Down Expand Up @@ -230,13 +230,20 @@ impl CargoFmtStrategy {
}

/// Based on the specified `CargoFmtStrategy`, returns a set of main source files.
fn get_targets(strategy: &CargoFmtStrategy) -> Result<HashSet<Target>, io::Error> {
fn get_targets(
manifest_path: Option<&Path>,
strategy: &CargoFmtStrategy,
) -> Result<HashSet<Target>, io::Error> {
let mut targets = HashSet::new();

match *strategy {
CargoFmtStrategy::Root => get_targets_root_only(&mut targets)?,
CargoFmtStrategy::All => get_targets_recursive(None, &mut targets, &mut HashSet::new())?,
CargoFmtStrategy::Some(ref hitlist) => get_targets_with_hitlist(hitlist, &mut targets)?,
CargoFmtStrategy::Root => get_targets_root_only(manifest_path, &mut targets)?,
CargoFmtStrategy::All => {
get_targets_recursive(manifest_path, &mut targets, &mut HashSet::new())?
}
CargoFmtStrategy::Some(ref hitlist) => {
get_targets_with_hitlist(manifest_path, hitlist, &mut targets)?
}
}

if targets.is_empty() {
Expand All @@ -249,8 +256,11 @@ fn get_targets(strategy: &CargoFmtStrategy) -> Result<HashSet<Target>, io::Error
}
}

fn get_targets_root_only(targets: &mut HashSet<Target>) -> Result<(), io::Error> {
let metadata = get_cargo_metadata(None)?;
fn get_targets_root_only(
manifest_path: Option<&Path>,
targets: &mut HashSet<Target>,
) -> Result<(), io::Error> {
let metadata = get_cargo_metadata(manifest_path)?;
let current_dir = env::current_dir()?.canonicalize()?;
let current_dir_manifest = current_dir.join("Cargo.toml");
let workspace_root_path = PathBuf::from(&metadata.workspace_root).canonicalize()?;
Expand Down Expand Up @@ -300,10 +310,11 @@ fn get_targets_recursive(
}

fn get_targets_with_hitlist(
manifest_path: Option<&Path>,
hitlist: &[String],
targets: &mut HashSet<Target>,
) -> Result<(), io::Error> {
let metadata = get_cargo_metadata(None)?;
let metadata = get_cargo_metadata(manifest_path)?;

let mut workspace_hitlist: HashSet<&String> = HashSet::from_iter(hitlist);

Expand Down Expand Up @@ -373,9 +384,6 @@ fn run_rustfmt(
fn get_cargo_metadata(manifest_path: Option<&Path>) -> Result<cargo_metadata::Metadata, io::Error> {
match cargo_metadata::metadata(manifest_path) {
Ok(metadata) => Ok(metadata),
Err(..) => Err(io::Error::new(
io::ErrorKind::Other,
"`cargo manifest` failed.",
)),
Err(error) => Err(io::Error::new(io::ErrorKind::Other, error.to_string())),
}
}
Loading