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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
use commands::*;
use error::Error;
use options::*;
use regex::Regex;
use std::io::{stdin, stdout, Write};
pub const COLUMN_SPACER_LENGTH: usize = 30;
#[derive(Debug)]
pub struct Branches {
pub string: String,
pub vec: Vec<String>,
}
impl Branches {
pub fn new(branches: Vec<String>) -> Branches {
let trimmed_string = branches.join("\n").trim_end_matches('\n').into();
Branches {
string: trimmed_string,
vec: branches,
}
}
pub fn print_warning_and_prompt(&self, delete_mode: &DeleteMode) -> Result<(), Error> {
println!("{}", delete_mode.warning_message());
println!("{}", self.format_columns());
print!("Continue? (Y/n) ");
stdout().flush()?;
// Read the user's response on continuing
let mut input = String::new();
stdin().read_line(&mut input)?;
match input.to_lowercase().as_ref() {
"y\n" | "y\r\n" | "yes\n" | "yes\r\n" | "\n" | "\r\n" => Ok(()),
_ => Err(Error::ExitEarly),
}
}
pub fn merged(options: &Options) -> Branches {
let mut branches: Vec<String> = vec![];
println!("Updating remote {}", options.remote);
run_command_with_no_output(&["git", "remote", "update", &options.remote, "--prune"]);
let merged_branches_regex = format!("^\\*?\\s*{}$", options.base_branch);
let merged_branches_filter = Regex::new(&merged_branches_regex).unwrap();
let merged_branches_cmd = run_command(&["git", "branch", "--merged"]);
let merged_branches_output = std::str::from_utf8(&merged_branches_cmd.stdout).unwrap();
let merged_branches =
merged_branches_output
.lines()
.fold(Vec::<String>::new(), |mut acc, line| {
if !merged_branches_filter.is_match(line) {
acc.push(line.trim().to_string());
}
acc
});
let local_branches_regex = format!("^\\*?\\s*{}$", options.base_branch);
let local_branches_filter = Regex::new(&local_branches_regex).unwrap();
let local_branches_cmd = run_command(&["git", "branch"]);
let local_branches_output = std::str::from_utf8(&local_branches_cmd.stdout).unwrap();
let local_branches = local_branches_output
.lines()
.fold(Vec::<String>::new(), |mut acc, line| {
if !local_branches_filter.is_match(line) {
acc.push(line.trim().to_string());
}
acc
})
.iter()
.filter(|branch| !options.ignored_branches.contains(branch))
.cloned()
.collect::<Vec<String>>();
let remote_branches_regex = format!("\\b(HEAD|{})\\b", &options.base_branch);
let remote_branches_filter = Regex::new(&remote_branches_regex).unwrap();
let remote_branches_cmd = run_command(&["git", "branch", "-r"]);
let remote_branches_output = std::str::from_utf8(&remote_branches_cmd.stdout).unwrap();
let remote_branches =
remote_branches_output
.lines()
.fold(Vec::<String>::new(), |mut acc, line| {
if !remote_branches_filter.is_match(line) {
acc.push(line.trim().to_string());
}
acc
});
for branch in local_branches {
// First check if the local branch doesn't exist in the remote, it's the cheapest and easiest
// way to determine if we want to suggest to delete it.
if options.delete_unpushed_branches
&& !remote_branches
.iter()
.any(|b: &String| *b == format!("{}/{}", &options.remote, branch))
{
branches.push(branch.to_owned());
continue;
}
// If it does exist in the remote, check to see if it's listed in git branches --merged. If
// it is, that means it wasn't merged using Github squashes, and we can suggest it.
if merged_branches.iter().any(|b: &String| *b == branch) {
branches.push(branch.to_owned());
continue;
}
// If neither of the above matched, merge main into the branch and see if it succeeds.
// If it can't cleanly merge, then it has likely been merged with Github squashes, and we
// can suggest it.
if options.squashes {
run_command(&["git", "checkout", &branch]);
match run_command_with_status(&[
"git",
"pull",
"--ff-only",
&options.remote,
&options.base_branch,
]) {
Ok(status) => {
if !status.success() {
println!("why");
branches.push(branch);
}
}
Err(err) => {
println!(
"Encountered error trying to update branch {} with branch {}: {}",
branch, options.base_branch, err
);
continue;
}
}
run_command(&["git", "reset", "--hard"]);
run_command(&["git", "checkout", &options.base_branch]);
}
}
// if deleted in remote, list
//
// g branch -d -r <remote>/<branch>
// g branch -d <branch>
Branches::new(branches)
}
fn format_columns(&self) -> String {
// Covers the single column case
if self.vec.len() < 26 {
return self.string.clone();
}
let col_count = {
let total_cols = self.vec.len() / 25 + 1;
::std::cmp::min(total_cols, 3)
};
let chunks = self.vec.chunks(col_count);
let mut col_indices = [0; 3];
for i in 1..col_count {
let index = i - 1;
let largest_col_member = chunks
.clone()
.map(|chunk| {
if let Some(branch) = chunk.get(index) {
branch.len()
} else {
0
}
})
.max()
.unwrap();
let next_col_start = largest_col_member + COLUMN_SPACER_LENGTH;
col_indices[i - 1] = next_col_start;
}
let rows: Vec<String> = self
.vec
.chunks(col_count)
.map(|chunk| make_row(chunk, &col_indices))
.collect();
rows.join("\n").trim().to_owned()
}
pub fn delete(&self, options: &Options) -> String {
match options.delete_mode {
DeleteMode::Local => delete_local_branches(self),
DeleteMode::Remote => delete_remote_branches(self, options),
DeleteMode::Both => {
let local_output = delete_local_branches(self);
let remote_output = delete_remote_branches(self, options);
[
"Remote:".to_owned(),
remote_output,
"\nLocal:".to_owned(),
local_output,
]
.join("\n")
}
}
}
}
fn make_row(chunks: &[String], col_indices: &[usize]) -> String {
match chunks.len() {
1 => chunks[0].clone(),
2 => {
format!(
"{b1:0$}{b2}",
col_indices[0],
b1 = chunks[0],
b2 = chunks[1]
)
}
3 => {
format!(
"{b1:0$}{b2:1$}{b3}",
col_indices[0],
col_indices[1],
b1 = chunks[0],
b2 = chunks[1],
b3 = chunks[2]
)
}
_ => unreachable!("This code should never be reached!"),
}
}
#[cfg(test)]
mod test {
use super::Branches;
#[test]
fn test_branches_new() {
let input = vec!["branch1".to_owned(), "branch2".to_owned()];
let branches = Branches::new(input);
assert_eq!("branch1\nbranch2".to_owned(), branches.string);
assert_eq!(
vec!["branch1".to_owned(), "branch2".to_owned()],
branches.vec
);
}
#[test]
fn test_format_single_column() {
let mut input = vec![];
for _ in 0..24 {
input.push("branch".to_owned())
}
let branches = Branches::new(input);
let expected = "\
branch
branch
branch
branch
branch
branch
branch
branch
branch
branch
\
branch
branch
branch
branch
branch
branch
branch
branch
branch
branch
\
branch
branch
branch
branch";
assert_eq!(expected, branches.format_columns());
}
#[test]
fn test_format_two_columns() {
let mut input = vec![];
for _ in 0..26 {
input.push("branch".to_owned())
}
let branches = Branches::new(input);
let expected = "\
branch branch
branch \
branch
branch branch
branch \
branch
branch branch
branch \
branch
branch branch
branch \
branch
branch branch
branch \
branch
branch branch
branch \
branch
branch branch";
assert_eq!(expected, branches.format_columns());
}
#[test]
fn test_format_three_columns() {
let mut input = vec![];
for _ in 0..51 {
input.push("branch".to_owned())
}
let branches = Branches::new(input);
let expected = "\
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch";
assert_eq!(expected, branches.format_columns());
}
#[test]
fn test_format_maxes_at_three_columns() {
let mut input = vec![];
for _ in 0..76 {
input.push("branch".to_owned())
}
let branches = Branches::new(input);
let expected = "\
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch branch \
branch
branch";
assert_eq!(expected, branches.format_columns());
}
#[test]
fn test_branches_of_different_lengths() {
let mut input = vec![];
for (i, _) in (0..26).enumerate() {
input.push(format!("branch{}", i))
}
let branches = Branches::new(input);
let expected = "\
branch0 branch1
branch2 \
branch3
branch4 branch5
branch6 \
branch7
branch8 branch9
branch10 \
branch11
branch12 branch13
branch14 \
branch15
branch16 branch17
branch18 \
branch19
branch20 branch21
branch22 \
branch23
branch24 branch25";
assert_eq!(expected, branches.format_columns());
}
#[test]
fn test_branches_of_bigger_lengths() {
let mut input = vec!["really_long_branch_name".to_owned(), "branch-1".to_owned()];
for (i, _) in (0..26).enumerate() {
input.push(format!("branch{}", i));
}
let branches = Branches::new(input);
let expected = "\
really_long_branch_name branch-1
branch0 \
branch1
branch2 branch3
branch4 \
branch5
branch6 branch7
branch8 \
branch9
branch10 branch11
branch12 \
branch13
branch14 branch15
branch16 \
branch17
branch18 branch19
branch20 \
branch21
branch22 branch23
branch24 \
branch25";
assert_eq!(expected, branches.format_columns());
}
#[test]
fn test_long_branches_with_three_columns() {
let mut input = vec![
"really_long_branch_name".to_owned(),
"branch".to_owned(),
"branch".to_owned(),
"branch".to_owned(),
"really_long_middle_col".to_owned(),
"branch".to_owned(),
];
for i in 0..45 {
input.push(format!("branch{}", i));
}
let branches = Branches::new(input);
let expected = "\
really_long_branch_name branch branch
branch really_long_middle_col branch
branch0 branch1 branch2
branch3 branch4 branch5
branch6 branch7 branch8
branch9 branch10 branch11
branch12 branch13 branch14
branch15 branch16 branch17
branch18 branch19 branch20
branch21 branch22 branch23
branch24 branch25 branch26
branch27 branch28 branch29
branch30 branch31 branch32
branch33 branch34 branch35
branch36 branch37 branch38
branch39 branch40 branch41
branch42 branch43 branch44";
assert_eq!(expected, branches.format_columns());
}
}