8000 format with nixfmt if it's found + new format.command config by figsoda · Pull Request #674 · nix-community/nix-init · GitHub
[go: up one dir, main page]

Skip to content
8000
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
24 changes: 24 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 @@ -58,6 +58,7 @@ time = { version = "0.3.44", features = ["parsing", "serde"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.22", features = ["env-filter"] }
url = "2.5.7"
which = "8.0.0"
xdg = "3.0.0"
zip = "7.0.0"

Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ commit = true
"github.com" = "ghp_blahblahblah..."
"gitlab.com".command = ["secret-tool", "or", "whatever", "you", "use"]
"gitlab.gnome.org".file = "/path/to/api/token"

# if unspecified, nix-init tries to format the output file with nixfmt if it's found in PATH
# the formatter should take a Nix file from stdin and output the formatted file to stdout
[format]
command = ["alejandra"]
```

## Changelog
Expand Down
6 changes: 6 additions & 0 deletions src/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,17 @@ pub struct Config {
pub maintainers: Vec<String>,
pub nixpkgs: Option<String>,
pub access_tokens: AccessTokens,
pub format: Option<Format>,
}

#[derive(Default, Deserialize)]
pub struct AccessTokens(FxHashMap<String, AccessToken>);

#[derive(Deserialize)]
pub struct Format {
pub command: Vec<String>,
}

impl AccessTokens {
pub async fn insert_header(&mut self, headers: &mut HeaderMap, host: &str) {
let value = match self.0.get(host) {
Expand Down
55 changes: 51 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ use std::{
collections::{BTreeMap, BTreeSet},
fmt::Write as _,
fs::{File, create_dir_all, metadata, read_dir},
io::{IsTerminal, Write as _, stderr},
io::{IsTerminal, Seek, Write as _, pipe, stderr},
path::{Component, Path, PathBuf},
process::Stdio,
};

use anyhow::{Context, Result};
use anyhow::{Context, Result, bail};
use askalono::ScanStrategy;
use bstr::{ByteSlice, ByteVec};
use cargo::core::Resolve;
Expand All @@ -33,8 +34,9 @@ use once_cell::sync::Lazy;
use serde::Deserialize;
use tempfile::tempdir;
use tokio::process::Command;
use tracing::{debug, warn};
use tracing::{debug, error, info, warn};
use tracing_subscriber::EnvFilter;
use which::which;
use zip::ZipArchive;

use crate::{
Expand Down Expand Up @@ -1040,7 +1042,21 @@ async fn run() -> Result<()> {
writeln!(out, " }};\n}})")?;

let mut out_file = File::create(&out_path).context("failed to create output file")?;
write!(out_file, "{out}")?;
if let Some(fmt) = cfg.format {
let mut args = fmt.command.into_iter();
if let Some(cmd) = args.next() {
let mut cmd = Command::new(cmd);
cmd.args(args);
maybe_format(&out, out_file, cmd).await?;
} else {
error!("format.command should contain at least 1 element");
write!(out_file, "{out}")?;
}
} else if which("nixfmt").is_ok() {
maybe_format(&out, out_file, Command::new("nixfmt")).await?;
} else {
write!(out_file, "{out}")?;
}

if !opts.commit.unwrap_or(cfg.commit) || !Path::new(".git").is_dir() {
return Ok(());
Expand Down Expand Up @@ -1100,3 +1116,34 @@ fn get_version(rev: &str) -> &str {
fn get_version_number(rev: &str) -> &str {
&rev[rev.find(char::is_numeric).unwrap_or_default() ..]
}

async fn maybe_format(content: &str, mut file: File, cmd: Command) -> Result<()> {
if let Err(e) = try_format(content, &file, cmd).await {
error!("{e}");
file.rewind()?;
file.set_len(0)?;
write!(file, "{content}")?;
}
Ok(())
}

async fn try_format(content: &str, file: &File, mut cmd: Command) -> Result<()> {
let (reader, mut writer) = pipe()?;
info!("{cmd:?}");

let mut child = cmd
.stdin(reader)
.stdout(file.try_clone()?)
.stderr(Stdio::inherit())
.spawn()?;

write!(writer, "{content}")?;
drop(writer);

let status = child.wait().await?;
if !status.success() {
bail!("formatter failed with {status}");
}

Ok(())
}
0