1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
|
use std::{
env::current_dir,
io::Write,
path::PathBuf,
process::{Command, Stdio},
};
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use crate::parse::{FileDiff, Patch};
mod parse;
#[derive(Parser)]
struct Cli {
#[command(subcommand)]
subcommand: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
/// Apply patches to a rollup target.
Apply {
/// The files to pull the patches to rollup from.
patch_files: Vec<PathBuf>,
/// Which repository to use as a target for the rollup
///
/// The repository needs to be clean.
#[arg(short, long)]
to: PathBuf,
/// Show debug information related to the parsing of patch files.
#[arg(short, long)]
debug_parse: bool,
},
/// Create the patch files (based on the given tag)
Create {
#[arg(default_value = "CONFIG_APPLIED")]
tag: String,
},
}
macro_rules! git {
(@_base for $finalizer:ident in $to:expr; $($args:expr),*) => {
Command::new("git")
.args([
"-C",
$to.display().to_string().as_str(),
$($args),*
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.$finalizer()
.with_context(|| format!("Failed to run {}", git!(@_fmt_cmd $($args),*)))?
};
(@_handle_status $output:expr; $($args:expr),*) => {{
if !$output.status.success() {
bail!("{} failed!", git!(@_fmt_cmd $($args),*))
}
if !$output.stderr.is_empty() {
let stderr = String::from_utf8($output.stderr).expect("git should always produce utf8");
bail!("{} returned some errors:\n{stderr}", git!(@_fmt_cmd $($args),*));
}
}};
(@_fmt_cmd $($args:expr),*) => {{
let all = ["git", $($args),*].join(" ");
format!("`{}`", all)
}};
(in $to:expr; $($args:expr),*) => {{
let output = git!(@_base for output in $to; $($args),*);
git!(@_handle_status output; $($args),*);
let stdout = String::from_utf8(output.stdout).expect("git should always produce utf8");
let stderr = String::from_utf8(output.stderr).expect("git should always produce utf8");
(stdout, stderr)
}};
(@set_stdin_to $stdin:expr; in $to:expr; $($args:expr),*) => {{
let mut child = git!(@_base for spawn in $to; $($args),*);
let mut stdin = child.stdin.take().expect("is piped");
write!(stdin, "{}", $stdin)?;
drop(stdin);
let output = child.wait_with_output()
.with_context(|| format!("Failed to run `{}`", git!(@_fmt_cmd $($args),*)))?;
git!(@_handle_status output; $($args),*);
let stdout = String::from_utf8(output.stdout).expect("git should always produce utf8");
let stderr = String::from_utf8(output.stderr).expect("git should always produce utf8");
(stdout, stderr)
}};
}
fn main() -> Result<()> {
let args = Cli::parse();
match args.subcommand {
Cmd::Apply {
patch_files,
to,
debug_parse,
} => apply_patches(patch_files, to, debug_parse)?,
Cmd::Create { tag } => create_patches(tag)?,
}
Ok(())
}
fn create_patches(tag: String) -> Result<()> {
let current_dir = current_dir()?;
let (stdout, _) = git!(in current_dir; "tag", "--contains", "HEAD", tag.as_str());
if !stdout.is_empty() {
println!(
"There are no tags to generate. Tag {} already points to HEAD.",
tag
);
return Ok(());
}
let mktemp = Command::new("mktemp")
.args(["-t", "rollup_patches_XXXXXX", "-d"])
.output()
.context("Failed to run `mktemp -t rollup_patches_XXXXXX -d`")?;
if !mktemp.status.success() {
bail!("Failed to generate temp-directory for generated patches.");
}
let tempdir = PathBuf::from(String::from_utf8(mktemp.stdout).unwrap().trim());
git!(in current_dir; "format-patch", format!("{}..", tag).as_str(), "-o", tempdir.display().to_string().as_str());
git!(in current_dir; "tag", "--delete", tag.as_str());
git!(in current_dir; "tag", "--annotate", tag.as_str(), "-m", "");
println!("Patches have been generated here: `{}`", tempdir.display());
Ok(())
}
fn apply_patches(patch_files: Vec<PathBuf>, to: PathBuf, debug_parse: bool) -> Result<()> {
let mut patches = vec![];
for file in &patch_files {
patches.push(parse::parse_file(file, debug_parse)?);
}
eprintln!("Successfully parsed all {} patch files.", patches.len());
{
let (stdout, _) = git!(in to; "status", "--porcelain");
if !stdout.is_empty() {
bail!(
"`--to` (`{}`) workspace is dirty, refusing to continue.",
to.display()
);
}
}
for (idx, patch) in patches.iter().enumerate() {
eprintln!(
"Applying {}. patch: `{}`... ",
idx + 1,
patch_files[idx].display()
);
let mut final_diffs = vec![];
for file_diff in &patch.files {
match file_diff {
FileDiff::Add { path, .. } => {
if to.join(path).exists() {
bail!("A file was added, that already existed. This should be impossible.")
}
final_diffs.push(file_diff.to_owned());
// eprintln!(" > Keeping add of `{}`", path.display());
}
FileDiff::Remove { path, .. } => {
if to.join(path).exists() {
final_diffs.push(file_diff.to_owned());
// eprintln!(" > Keeping remove of `{}`", path.display());
} else {
eprintln!(
" > Dropping remove of `{}`, as the file does not exist in the rollup target.",
path.display()
);
}
}
FileDiff::RenameNoChange { from, to, .. }
| FileDiff::RenameWithChange { from, to, .. } => {
if to.join(from).exists() {
if to.join(to).exists() {
bail!(
"A rename (`{}` -> `{}`) tried to rename a path to an already existing path. This should be impossible.",
from.display(),
to.display()
)
}
final_diffs.push(file_diff.to_owned());
// eprintln!(" > Keeping rename of `{}` to `{}`", from.display(), to.display());
} else {
eprintln!(
" > Dropping rename from `{}` to `{}`, as the from file does not exist in the rollup target.",
from.display(),
to.display()
);
}
}
FileDiff::Change { path, .. } => {
if to.join(path).exists() {
final_diffs.push(file_diff.to_owned());
} else {
eprintln!(
" > Dropping change to `{}`, as the file does not exist in the rollup target.",
path.display()
);
}
}
}
}
if final_diffs.is_empty() {
eprintln!(" -> Patch is empty after dropping, skipping it.",);
continue;
}
let filtered_patch = Patch {
files: final_diffs,
..patch.to_owned()
};
git!(@set_stdin_to filtered_patch; in to; "apply", "-", "--whitespace=nowarn");
git!(in to; "add", ".");
git!(@set_stdin_to filtered_patch.commit_message; in to; "commit", "--file=-", format!("--date={}", filtered_patch.date).as_str(), "--quiet");
}
Ok(())
}
|