rmuxinator 4.1.0

tmux project configuration utility
Documentation
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
use clap::{App, AppSettings, Arg, SubCommand};
use derivative::Derivative;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::ffi::OsString;
use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::process::{Command, Output};
use std::str::FromStr;

extern crate toml;

// The following TmuxCommandRunner business exists only to facilitate mocking.
// Coming from a dynamic language background, this does not smell right to me
// but I don't see any way around it.
// I may yet wind up yanking this out in favor of a different mocking library
// or strategy,
// We're mocking run_tmux_command instead of Command (via some combination of
// CommandFactor and CommandRunner), which feels slightly ... less bad because
// at least it's something we _own_ (in TDD parlance) but it's admittedly a bit
// weird and contrived.
// So, unless we _really_ want to verify that the conditional in
// run_tmux_command is dispatching the correct arguments to Command, this is
// probably good enough. In an ideal world, we would mock Command/args/output
// but doing so using mockall will require at least one additional layer of
// indirection and dependency injection and mocking to stub the command struct
// _and_ the instance it returns and the methods
// - ethagnawl

fn binary_exists(name: &str) -> bool {
    Command::new(name)
        .arg("-V")
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false)
}

fn run_tmux_command(
    terminal_multiplexer: &String,
    command: &[String],
    wait: bool,
) -> Result<Output, Box<dyn Error>> {
    // TODO: Validate Command status and either panic or log useful error
    // message.
    // TODO: This fn should also accept an optional tmux config file to use with `-f`

    // TODO: This is very lazy as it repeatedly shells out to terminal_multiplexer.
    // A better solution would be to introduce something akin to tmuxinator's
    // Doctor class which does basic validation about the environment (tmux, term, etc.)
    // only once at the beginning of the top-level routine.
    if !binary_exists(terminal_multiplexer) {
        panic!(
            "'{}' does not seem to be a compatible terminal multiplexer",
            terminal_multiplexer
        );
    }

    let mut tmux = Command::new(terminal_multiplexer);
    if wait {
        let child = tmux.args(command).spawn()?;
        let output: Output = child.wait_with_output()?;
        Ok(output)
    } else {
        Ok(tmux.args(command).output()?)
    }
}

trait TmuxCommandRunner {
    fn run_tmux_command(
        &self,
        terminal_multiplexer: &String,
        command: &[String],
        wait: bool,
    ) -> Result<Output, Box<dyn Error>>;
}

struct TmuxWrapper;

impl TmuxCommandRunner for TmuxWrapper {
    fn run_tmux_command(
        &self,
        terminal_multiplexer: &String,
        command: &[String],
        wait: bool,
    ) -> Result<Output, Box<dyn Error>> {
        run_tmux_command(terminal_multiplexer, command, wait)
    }
}

fn build_pane_args(session_name: &str, window_index: usize) -> Vec<Vec<String>> {
    // NOTE: Like tmuxinator does, we want to continually apply the tiled layout
    // after splitting and then _only_ at the very end of the window config
    // constructor context apply the specified or inherited layout. This
    // prevents errors like, "no space for new pane" which occur if the
    // window's current size/layout won't (otherwise) allow it to be split
    // again.
    // We should document that tiled _is_ used by default when splitting panes
    // and, that if no other layouts are specified, it will result in tiled
    // output.
    // See:
    // - https://github.com/ethagnawl/rmuxinator/issues/45
    // - https://web.archive.org/web/20250709171739/https://www.mail-archive.com/tmux-users@googlegroups.com/msg01241.html
    vec![
        vec![
            String::from("split-window"),
            String::from("-t"),
            format!("{}:{}", session_name, window_index.to_string()),
        ],
        vec![
            String::from("select-layout"),
            String::from("-t"),
            format!("{}:{}", session_name, window_index.to_string()),
            String::from("tiled"),
        ],
    ]
}

fn build_window_layout_args(
    session_name: &str,
    window_index: &usize,
    config_layout: &Option<Layout>,
    window_layout: &Option<Layout>,
) -> Option<Vec<String>> {
    let maybe_layout = if window_layout.is_some() {
        &window_layout
    } else if config_layout.is_some() {
        &config_layout
    } else {
        &None
    };

    if let Some(layout) = maybe_layout {
        Some(vec![
            String::from("select-layout"),
            String::from("-t"),
            format!("{}:{}", session_name, window_index.to_string()),
            layout.to_string(),
        ])
    } else {
        None
    }
}

fn build_create_window_args(
    session_name: &str,
    window_index: usize,
    window_name: &Option<String>,
    start_directory: &Option<String>,
) -> Vec<String> {
    let mut create_window_args = vec![
        String::from("new-window"),
        String::from("-t"),
        format!("{}:{}", session_name, window_index.to_string()),
    ];

    if let Some(_window_name) = window_name {
        create_window_args.push(String::from("-n"));
        create_window_args.push(_window_name.to_string());
    }

    if let Some(start_directory_) = start_directory {
        create_window_args.push(String::from("-c"));
        create_window_args.push(String::from(start_directory_));
    }

    create_window_args
}

fn build_session_args(
    session_name: &str,
    window_name: Option<String>,
    start_directory: &StartDirectory,
) -> Vec<String> {
    // Pass first window name to new-session, otherwise a default window gets
    // created that would need to be killed at a later point. I tried doing
    // this, but saw unexpected behavior -- most likely because the indexes get
    // shuffled.
    let mut session_args = vec![
        String::from("new-session"),
        String::from("-d"),
        String::from("-s"),
        String::from(session_name),
    ];

    if let Some(_window_name) = window_name {
        session_args.push(String::from("-n"));
        session_args.push(_window_name);
    }

    if let Some(start_directory_) = start_directory {
        session_args.push(String::from("-c"));
        session_args.push(String::from(start_directory_));
    }

    session_args
}

fn build_pane_command_args(
    session_name: &str,
    window_index: &usize,
    pane_index: &usize,
    command: &str,
) -> Vec<String> {
    vec![
        String::from("send-keys"),
        String::from("-t"),
        format!("{}:{}.{}", session_name, window_index, pane_index),
        String::from(command),
        String::from("Enter"),
    ]
}

trait EnvProvider {
    fn get_var(&self, key: &str) -> Option<String>;
}

struct SystemEnv;
impl EnvProvider for SystemEnv {
    fn get_var(&self, key: &str) -> Option<String> {
        std::env::var(key).ok()
    }
}

fn in_tmux_context(env: &dyn EnvProvider) -> bool {
    env.get_var("TMUX")
        // NOTE: This is naive but if a value is present and non-sensical
        // (e.g.  999), then all bets are off, anyways.
        .map(|val| !val.is_empty())
        .unwrap_or(false)
}

fn build_attach_command_args(session_name: &str) -> Vec<String> {
    let session_op = if in_tmux_context(&SystemEnv) {
        String::from("switch-client")
    } else {
        String::from("attach-session")
    };
    vec![
        String::from("-u"),
        String::from(session_op),
        String::from("-t"),
        String::from(session_name),
    ]
}

fn build_session_start_directory(config: &Config) -> StartDirectory {
    // Compute start_directory for session/first window using:
    // window.start_directory || config.start_directory
    if !config.windows.is_empty() {
        config.windows[0].start_directory.clone()
    } else {
        config.start_directory.clone()
    }
}

fn build_window_start_directory(
    config_start_directory: &StartDirectory,
    window_start_directory: &StartDirectory,
) -> StartDirectory {
    let config_start_directory_ = config_start_directory.clone();
    let window_start_directory_ = window_start_directory.clone();
    window_start_directory_.or(config_start_directory_)
}

fn build_pane_start_directory(
    config_start_directory: &StartDirectory,
    window_start_directory: &StartDirectory,
    pane_start_directory: &StartDirectory,
) -> StartDirectory {
    let config_start_directory_ = config_start_directory.clone();
    let window_start_directory_ = window_start_directory.clone();
    let pane_start_directory_ = pane_start_directory.clone();
    pane_start_directory_
        .or(window_start_directory_)
        .or(config_start_directory_)
}

fn build_hook_args(hook: &Hook) -> Vec<String> {
    vec![
        String::from("set-hook"),
        String::from("-a"),
        hook.name.to_string(),
        hook.command.to_string(),
    ]
}

fn build_rename_pane_args(
    session_name: &str,
    window_index: usize,
    pane_index: usize,
    pane_name_user_option: &Option<String>,
    pane_name: &Option<String>,
) -> Option<Vec<String>> {
    // requires tmux >= 3.0a and some variation of the following in
    // tmux.conf:
    // e.g. `set -g pane-border-format "#{@user_option}"`
    // TODO: Is it worth sniffing out user option support?
    if pane_name.is_some() && pane_name_user_option.is_some() {
        Some(vec![
            String::from("set-option"),
            String::from("-p"),
            String::from("-t"),
            format!("{}:{}.{}", session_name, window_index, pane_index),
            format!("@{}", pane_name_user_option.clone().unwrap()),
            pane_name.clone().unwrap(),
        ])
    } else {
        None
    }
}

pub fn test_for_tmux(tmux_command: &str) -> bool {
    // TODO: an optarg would be nice, but they're not currently supported.
    // This parameter exists only to facilitate testing and the main caller
    // will never _need_ to pass anything non-standard.
    let mut shell = Command::new("sh");
    let output = shell
        .arg("-c")
        .arg(format!("command -v {}", tmux_command))
        .output()
        .expect("Unable to test for tmux.");
    output.status.success()
}

fn build_commands_with_tmux_options_prefix(
    tmux_options: String,
    commands: Vec<(Vec<String>, bool)>,
) -> Vec<(Vec<String>, bool)> {
    // NOTE: If the full string (e.g. -f /tmp/custom.conf) is used it results
    // in an error. There's something up with the whitespace or similar which
    // results in the flag being consumed and the shell trying to execute the
    // path to the config file.
    // TODO: Ideally we'd do _some_ amount of validation of these arguments.
    // Right now, anything and everything is being passed through and can/will
    // cause tmux errors.
    let tmux_options_parts: Vec<&str> = tmux_options.split(" ").collect();
    let tmux_option_strs: Vec<String> = tmux_options_parts
        .clone()
        .into_iter()
        .map(|x| x.to_string())
        .collect();
    commands
        .into_iter()
        .map(|(nested_vec, bool)| {
            // (["new-session", "-d", "-s", "new-sesh", "-n", "one"], false)
            // becomes
            // (["-f", "/tmp/tmux.custom.conf", "new-session", "-d", "-s", "new-sesh", "-n", "one"], false)
            let mut command = tmux_option_strs.clone();
            command.extend(nested_vec.iter().cloned());
            (command, bool)
        })
        .collect()
}

fn convert_config_to_tmux_commands(
    config: &Config,
    base_indices: TmuxBaseIndices,
) -> Vec<(Vec<String>, bool)> {
    // TODO: We should consider adding sensible line endings
    // to clearly delineate command boundaries.
    let mut commands = vec![];

    let session_name = &config.name;

    let session_start_directory = build_session_start_directory(&config);

    let first_window = if let Some(window) = config.windows.first() {
        window.name.clone()
    } else {
        None
    };

    let create_session_args =
        build_session_args(session_name, first_window, &session_start_directory);
    commands.push((create_session_args, false));

    for hook in config.hooks.iter() {
        let hook_command = build_hook_args(&hook);
        commands.push((hook_command, false));
    }

    for (window_iterator_index, window) in config.windows.iter().enumerate() {
        // The "first" window is created by create_session because tmux always
        // creates a window when creating a session.
        // The alternative would be to create all of the project windows and
        // then kill the first/default one, but I saw unexpected behavior
        // (first window's commands not being run) when attempting that -- I
        // think it's because the indexes get shuffled.
        // The alternative approach would be more explicit and preferable, so
        // maybe it's worth revisiting.
        let window_index = base_indices.base_index + window_iterator_index;
        if window_iterator_index > 0 {
            // TODO: This is heavy handed and this logic is _sort of_ duped
            // in a few places. Maybe each type should have a method which is
            // able to compute its own starting directory?
            let window_start_directory =
                build_window_start_directory(&config.start_directory, &window.start_directory);
            let create_window_args = build_create_window_args(
                session_name,
                window_index,
                &window.name,
                &window_start_directory,
            );

            commands.push((create_window_args, false));
        }

        for (pane_iterator_index, pane) in window.panes.iter().enumerate() {
            let pane_index = base_indices.pane_base_index + pane_iterator_index;
            // The "first" pane is created by default by the containing window
            if pane_iterator_index > 0 {
                let pane_args = build_pane_args(session_name, window_index);
                for pane_arg in pane_args {
                    commands.push((pane_arg, false));
                }
            }

            // Conditionally set start_directory for pane.
            // Unfortunately, this can't be done cleanly using create_pane
            // because pane 0 is created implicitly.
            let pane_start_directory = build_pane_start_directory(
                &config.start_directory,
                &window.start_directory,
                &pane.start_directory,
            );
            if let Some(pane_start_directory) = pane_start_directory {
                let command = format!("cd {}", pane_start_directory);
                let pane_command_args =
                    build_pane_command_args(session_name, &window_index, &pane_index, &command);
                commands.push((pane_command_args, false));
            }

            for (_, command) in pane.commands.iter().enumerate() {
                let pane_command_args =
                    build_pane_command_args(session_name, &window_index, &pane_index, command);
                commands.push((pane_command_args, false));
            }

            let rename_pane_args = build_rename_pane_args(
                session_name,
                window_index,
                pane_index,
                &config.pane_name_user_option,
                &pane.name.clone(),
            );
            if let Some(rename_pane_args_) = rename_pane_args {
                commands.push((rename_pane_args_, false));
            }
        }

        let window_layout_args =
            build_window_layout_args(session_name, &window_index, &config.layout, &window.layout);

        if let Some(window_layout_args_) = window_layout_args {
            commands.push((window_layout_args_, false));
        }
    }

    // TODO: It's not ideal that logic for constructing this command lives in
    // multiple places (i.e. here and in build_attach_command_args)
    // I think ideally this would be a _tell, don't ask_ situation and we
    // either validate that the output is valid (i.e. via Option) and let the
    // function figure out whether or how to compute the command. This is
    // probably also something we should do for all of these helper functions.
    if config.attached {
        let attach_args = build_attach_command_args(&config.name);
        commands.push((attach_args, true));
    }

    if let Some(tmux_options) = config.tmux_options.clone() {
        commands = build_commands_with_tmux_options_prefix(tmux_options, commands);
    }

    commands
}

#[derive(Debug, PartialEq)]
struct TmuxBaseIndices {
    base_index: usize,
    pane_base_index: usize,
}

fn get_tmux_base_indices(
    config: &Config,
    tmux_command_runner: &dyn TmuxCommandRunner,
) -> TmuxBaseIndices {
    // `args` will result in the following command:
    // `tmux start-server\; show-option -g base-index\; show-window-option -g pane-base-index`

    let mut commands = vec![(
        vec![
            "start-server".to_string(),
            ";".to_string(),
            "show-option".to_string(),
            "-g".to_string(),
            "base-index".to_string(),
            ";".to_string(),
            "show-window-option".to_string(),
            "-g".to_string(),
            "pane-base-index".to_string(),
        ],
        false,
    )];

    if let Some(tmux_options) = config.tmux_options.clone() {
        commands = build_commands_with_tmux_options_prefix(tmux_options, commands);
    }

    let output = tmux_command_runner.run_tmux_command(
        &config.terminal_multiplexer,
        &commands[0].0,
        commands[0].1,
    );
    let pane_base_index_re = Regex::new(r"(?:base-index (?P<base_index>\d+))?(?:.*\n)?(?:pane-base-index (?P<pane_base_index>\d+))?").unwrap();

    // NOTE: This is a bit redundant but feels _better_ than using Option
    // values and then immediately setting them to Some(N).
    let mut base_index = 0;
    let mut pane_base_index = 0;

    if let Some(captures) =
        pane_base_index_re.captures(&String::from_utf8(output.unwrap().stdout).unwrap())
    {
        base_index = captures
            .name("base_index")
            .map_or("0", |m| m.as_str())
            .parse::<usize>()
            .unwrap();

        pane_base_index = captures
            .name("pane_base_index")
            .map_or("0", |m| m.as_str())
            .parse::<usize>()
            .unwrap();
    }

    let tmux_base_indices = TmuxBaseIndices {
        base_index: base_index,
        pane_base_index: pane_base_index,
    };

    tmux_base_indices
}

fn run_start_(
    config: Config,
    tmux_command_runner: &dyn TmuxCommandRunner,
) -> Result<(), Box<dyn Error>> {
    let base_indices = get_tmux_base_indices(&config, tmux_command_runner);
    let commands = convert_config_to_tmux_commands(&config, base_indices);
    for command in commands {
        // TODO: run_tmux_command output should be handled and used to report
        // errors to the user.
        let _ = tmux_command_runner.run_tmux_command(
            &config.terminal_multiplexer,
            &command.0,
            command.1,
        );
    }
    Ok(())
}

pub fn run_start(config: Config) -> Result<(), Box<dyn Error>> {
    // NOTE: This exists to prevent the public API from having to change in
    // order pass in an optional TmuxCommandRunner (e.g. `None` in the
    // application/non-test environment). As noted above this indirection
    // exists soley to facilitate mocking run_tmux_command in the test env.
    // This is the best approach I've hit upon yet but I'm still not convinced
    // it's a good, worthwhile idea.
    // - ethagnawl
    run_start_(config, &TmuxWrapper)
}

fn run_debug_(
    config: Config,
    tmux_command_runner: &dyn TmuxCommandRunner,
) -> Result<(), Box<dyn Error>> {
    let base_indices = get_tmux_base_indices(&config, tmux_command_runner);
    for command in convert_config_to_tmux_commands(&config, base_indices) {
        println!("{} {}", &config.terminal_multiplexer, command.0.join(" "));
    }

    Ok(())
}

pub fn run_debug(config: Config) -> Result<(), Box<dyn Error>> {
    // See run_start docstring for TmuxWrapper rationale.
    // - ethagnawl
    run_debug_(config, &TmuxWrapper)
}

pub fn parse_args<I, T>(args: I) -> CliArgs
where
    I: IntoIterator<Item = T>,
    T: Into<OsString> + Clone,
{
    let project_config_file_arg = Arg::with_name("PROJECT_CONFIG_FILE")
        .help("The path to the project config file")
        .required(true);
    let app_matches = App::new(clap::crate_name!())
        .version(clap::crate_version!())
        .author(clap::crate_authors!())
        .about(clap::crate_description!())
        .setting(AppSettings::SubcommandRequiredElseHelp)
        .subcommand(
            SubCommand::with_name("debug")
            .about("Print the tmux commands that would be used to start and configure a tmux session using a path to a project config file")
            .arg(&project_config_file_arg)
        )
        .subcommand(
            SubCommand::with_name("start")
            .about("Start a tmux session using a path to a project config file")
            .arg(&project_config_file_arg)
        )
        .get_matches_from(args);

    let (command_name, command_matches) = match app_matches.subcommand() {
        (name, Some(matches)) => (name, matches),
        (_, None) => {
            panic!("Subcommand should be forced by clap");
        }
    };

    let command = match CliCommand::from_str(command_name) {
        Ok(command) => command,
        Err(error) => {
            panic!("{}", error.to_string());
        }
    };

    let project_name = command_matches
        .value_of("PROJECT_CONFIG_FILE")
        .expect("project file is required by clap")
        .to_string();

    CliArgs {
        command,
        project_name,
    }
}

#[derive(Debug, PartialEq)]
pub enum CliCommand {
    Debug,
    Start,
}

#[derive(Debug)]
pub struct ParseCliCommandError;

// TODO: this boilerplate can be cut down by using a third-party crate
impl fmt::Display for ParseCliCommandError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Missing implementation for subcommand, please file a bug report"
        )
    }
}

impl Error for ParseCliCommandError {}

impl FromStr for CliCommand {
    type Err = ParseCliCommandError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "debug" => Ok(Self::Debug),
            "start" => Ok(Self::Start),
            // This should only ever be reached if subcommands are added to
            // clap and not here
            _ => Err(ParseCliCommandError),
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct CliArgs {
    pub command: CliCommand,
    // TODO: `project_name` is currently overloaded and also used as the config
    // path. We should either make this more explicit or introduce separate
    // args.
    pub project_name: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", untagged)]
pub enum Layout {
    // NOTE: This does not attempt to do _any_ validation on the provided
    // string. I'm not even sure if that's possible? We could attept to do
    // basic shape validation using a regex or something but it seems like
    // overkill.
    Custom(String),
    EvenHorizontal,
    EvenVertical,
    MainHorizontal,
    MainVertical,
    Tiled,
}

impl fmt::Display for Layout {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let layout_name = match self {
            Layout::Custom(value) => value.clone(),
            _ => {
                let pascal_case_layout_name = format!("{:?}", self);
                convert_pascal_case_to_kebab_case(&pascal_case_layout_name)
            }
        };
        write!(f, "{}", layout_name)
    }
}

type StartDirectory = Option<String>;

#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Pane {
    pub commands: Vec<String>,
    pub name: Option<String>,
    pub start_directory: StartDirectory,
}

#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Window {
    pub layout: Option<Layout>,
    pub name: Option<String>,
    #[serde(default)]
    pub panes: Vec<Pane>,
    pub start_directory: StartDirectory,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
enum HookName {
    // TODO: Does this make sense? If not, document exclusion.
    // AfterNewSession,

    // TODO: why doesn't this fire? It seems to be valid, but isn't ever
    // triggered.
    // AfterKillPane,
    // AfterKillWindow,
    AfterBindKey,
    AfterCapturePane,
    AfterCopyMode,
    AfterCursorDown,
    AfterDisplayPanes,
    AfterListClients,
    AfterListKeys,
    AfterListPanes,
    AfterListSessions,
    AfterListWindows,
    AfterNewWindow,
    AfterPipePane,
    AfterRefreshClient,
    AfterRenameSession,
    AfterRenameWindow,
    AfterResizePane,
    AfterResizeWindow,
    AfterSelectLayout,
    AfterSelectPane,
    AfterSelectWindow,
    AfterSendKeys,
    AfterSetOption,
    AfterShowMessages,
    AfterShowOptions,
    AfterSplitWindow,
    AfterUnbindKey,
    AlertActivity,
    AlertBell,
    AlertSilence,
    ClientAttached,
    ClientDetached,
    ClientResized,
    ClientSessionChanged,
    LayoutChange,
    Output,
    PaneDied,
    PaneExited,
    PaneFocusIn,
    PaneFocusOut,
    PaneModeChanged,
    PaneSetClipboard,
    SessionChanged,
    SessionClosed,
    SessionCreated,
    SessionRenamed,
    SessionWindowChanged,
    SessionsChanged,
    UnlinkedWindowAdd,
    WindowAdd,
    WindowClose,
    WindowLinked,
    WindowPaneChanged,
    WindowRenamed,
    WindowUnlinked,
}

impl fmt::Display for HookName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let pascal_case_hook_name = format!("{:?}", self);
        let kebab_case_hook_name = convert_pascal_case_to_kebab_case(&pascal_case_hook_name);
        write!(f, "{}", kebab_case_hook_name)
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Hook {
    command: String,
    name: HookName,
}

#[derive(Derivative, Debug, Default, Deserialize, Serialize)]
pub struct Config {
    #[serde(default = "ConfigDefaultValues::default_as_tmux")]
    pub terminal_multiplexer: String,
    // TODO: add base_index w/ default?
    #[serde(default = "ConfigDefaultValues::default_as_true")]
    pub attached: bool,
    pub pane_name_user_option: Option<String>,
    #[serde(default)]
    pub hooks: Vec<Hook>,
    pub layout: Option<Layout>,
    pub name: String,
    pub start_directory: StartDirectory,
    #[derivative(Default(value = "None"))]
    pub tmux_options: Option<String>,
    #[serde(default)]
    pub windows: Vec<Window>,
}

impl Config {
    pub fn new_from_file_path(config_path: &String) -> Result<Config, String> {
        // Need to return String in failure case because toml::from_str may
        // return a toml::de::Error.
        let mut config_file = match File::open(&config_path) {
            Ok(file) => file,
            Err(_) => return Err(String::from("Unable to open config file.")),
        };
        let mut contents = String::new();

        match config_file.read_to_string(&mut contents) {
            Ok(_) => (),
            Err(_) => return Err(String::from("Unable to read config file.")),
        }

        let decoded = toml::from_str(&contents);

        match decoded {
            Ok(config) => Ok(config),
            Err(error) => Err(error.to_string()),
        }
    }
}

struct ConfigDefaultValues;
impl ConfigDefaultValues {
    pub fn default_as_tmux() -> String {
        "tmux".to_string()
    }
    pub fn default_as_true() -> bool {
        true
    }
}

/// Convert a PascalCase string to a kebab-case string
fn convert_pascal_case_to_kebab_case(input: &str) -> String {
    // Split string by uppercase characters and join with '-'
    // TODO: This can be simplified once `.split_inclusive()` stablizes
    input.chars().fold(String::from(""), |mut acc, mut c| {
        // Separate uppercase letters by '-' after the first
        if !acc.is_empty() && c.is_ascii_uppercase() {
            acc.push('-');
        }
        c.make_ascii_lowercase();
        acc.push(c);
        acc
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use mockall::mock;
    use mockall::predicate::*;
    use std::collections::HashMap;

    struct MockEnv(HashMap<String, String>);

    impl EnvProvider for MockEnv {
        fn get_var(&self, key: &str) -> Option<String> {
            self.0.get(key).cloned()
        }
    }

    fn create_dummy_output_instance(status: i32, stdout: Vec<u8>, stderr: Vec<u8>) -> Output {
        // NOTE: There's no simple way to create an arbitrary ExitStatus
        // instance, so we actually have to shell out. We could mock ExitStatus
        // but that would require introducing a trait of our own which wraps
        // ExitStatus and is used throughout the program, which seems like
        // overkill.
        let status = Command::new("sh")
            .arg("-c")
            .arg(format!("exit {}", status))
            .status()
            .expect("failed to execute process");
        Output {
            status,
            stdout,
            stderr,
        }
    }

    mock! {
        TmuxCommandRunner {}
        impl TmuxCommandRunner for TmuxCommandRunner {
            fn run_tmux_command(&self, terminal_multiplexer: &String, command: &[String], wait: bool) -> Result<Output, Box<dyn Error>>;
        }
    }

    #[test]
    fn test_in_tmux_context_returns_true_when_env_var_is_non_empty_string() {
        let env = MockEnv(HashMap::from([(
            String::from("TMUX"),
            String::from("/tmp/tmux-1000/default,12345,0"),
        )]));
        assert_eq!(true, in_tmux_context(&env));
    }

    #[test]
    fn test_in_tmux_context_returns_false_when_env_var_is_empty_string() {
        let env = MockEnv(HashMap::from([(String::from("TMUX"), String::from(""))]));
        assert_eq!(false, in_tmux_context(&env));
    }

    #[test]
    fn test_in_tmux_context_returns_false_when_env_var_not_set() {
        let env = MockEnv(HashMap::new());
        assert_eq!(false, in_tmux_context(&env))
    }

    #[test]
    fn test_it_returns_default_base_index_when_no_value_found_in_tmux_session() {
        let mut tmux_command_runner = MockTmuxCommandRunner::new();
        tmux_command_runner
            .expect_run_tmux_command()
            .times(1)
            .with(always(), always(), eq(false))
            .returning(|_x, _y, _z| {
                Ok(create_dummy_output_instance(
                    0,
                    "nope".bytes().collect(),
                    vec![],
                ))
            });
        let config = Config::default();
        let indices = get_tmux_base_indices(&config, &tmux_command_runner);
        let expected = 0;
        let actual = indices.base_index;
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_it_returns_default_pane_base_index_when_no_value_found_in_tmux_session() {
        let mut tmux_command_runner = MockTmuxCommandRunner::new();
        tmux_command_runner
            .expect_run_tmux_command()
            .times(1)
            .with(always(), always(), eq(false))
            .returning(|_x, _y, _z| {
                Ok(create_dummy_output_instance(
                    0,
                    "nope".bytes().collect(),
                    vec![],
                ))
            });
        let config = Config::default();
        let indices = get_tmux_base_indices(&config, &tmux_command_runner);
        let expected = 0;
        let actual = indices.pane_base_index;
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_it_returns_default_base_index_when_good_value_found_in_tmux_session() {
        let mut tmux_command_runner = MockTmuxCommandRunner::new();
        tmux_command_runner
            .expect_run_tmux_command()
            .times(1)
            .with(always(), always(), eq(false))
            .returning(|_x, _y, _z| {
                Ok(create_dummy_output_instance(
                    0,
                    "base-index 0".bytes().collect(),
                    vec![],
                ))
            });

        let config = Config::default();
        let indices = get_tmux_base_indices(&config, &tmux_command_runner);
        let expected = 0;
        let actual = indices.base_index;
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_it_returns_default_pane_base_index_when_good_value_found_in_tmux_session() {
        let mut tmux_command_runner = MockTmuxCommandRunner::new();
        tmux_command_runner
            .expect_run_tmux_command()
            .times(1)
            .with(always(), always(), eq(false))
            .returning(|_x, _y, _z| {
                Ok(create_dummy_output_instance(
                    0,
                    "pane-base-index 0".bytes().collect(),
                    vec![],
                ))
            });
        let config = Config::default();
        let indices = get_tmux_base_indices(&config, &tmux_command_runner);
        let expected = 0;
        let actual = indices.base_index;
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_it_returns_custom_base_index_when_good_value_found_in_tmux_session() {
        let mut tmux_command_runner = MockTmuxCommandRunner::new();
        tmux_command_runner
            .expect_run_tmux_command()
            .times(1)
            .with(always(), always(), eq(false))
            .returning(|_x, _y, _z| {
                Ok(create_dummy_output_instance(
                    0,
                    "base-index 99".bytes().collect(),
                    vec![],
                ))
            });
        let config = Config::default();
        let indices = get_tmux_base_indices(&config, &tmux_command_runner);
        let expected = 99;
        let actual = indices.base_index;
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_it_returns_custom_pane_base_index_when_good_value_found_in_tmux_session() {
        let mut tmux_command_runner = MockTmuxCommandRunner::new();
        tmux_command_runner
            .expect_run_tmux_command()
            .once()
            .withf(|_terminal_multiplexer: &String, command: &[String], bool| {
                *bool == false
                    && *command
                        == vec![
                            "start-server".to_string(),
                            ";".to_string(),
                            "show-option".to_string(),
                            "-g".to_string(),
                            "base-index".to_string(),
                            ";".to_string(),
                            "show-window-option".to_string(),
                            "-g".to_string(),
                            "pane-base-index".to_string(),
                        ]
            })
            .returning(|_x, _y, _z| {
                Ok(create_dummy_output_instance(
                    0,
                    "pane-base-index 99".bytes().collect(),
                    vec![],
                ))
            });
        let config = Config::default();
        let indices = get_tmux_base_indices(&config, &tmux_command_runner);
        let expected = 99;
        let actual = indices.pane_base_index;
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_it_passes_tmux_options_to_tmux_when_present() {
        let tmux_options = "-f another-one.conf".to_string();
        let config = Config {
            attached: false,
            name: "foo".to_string(),
            tmux_options: Some(tmux_options.clone()),
            windows: vec![Window {
                layout: None,
                name: Some(String::from("a window")),
                panes: Vec::new(),
                start_directory: None,
            }],
            ..Config::default()
        };

        let mut tmux_command_runner = MockTmuxCommandRunner::new();
        tmux_command_runner
            .expect_run_tmux_command()
            .once()
            .withf(|_terminal_multiplexer: &String, command: &[String], _| {
                *command
                    == vec![
                        "-f".to_string(),
                        "another-one.conf".to_string(),
                        "start-server".to_string(),
                        ";".to_string(),
                        "show-option".to_string(),
                        "-g".to_string(),
                        "base-index".to_string(),
                        ";".to_string(),
                        "show-window-option".to_string(),
                        "-g".to_string(),
                        "pane-base-index".to_string(),
                    ]
            })
            .returning(|_x, _y, _z| Ok(create_dummy_output_instance(0, vec![], vec![])));

        tmux_command_runner
            .expect_run_tmux_command()
            .once()
            .withf(
                move |_terminal_multiplexer: &String, command: &[String], _| {
                    *command
                        == vec![
                            "-f",
                            "another-one.conf",
                            "new-session",
                            "-d",
                            "-s",
                            "foo",
                            "-n",
                            "a window",
                        ]
                },
            )
            .returning(|_x, _y, _z| Ok(create_dummy_output_instance(0, vec![], vec![])));
        let _ = run_start_(config, &tmux_command_runner);
    }

    #[test]
    fn test_it_passes_multiple_tmux_options_to_tmux_when_present() {
        let tmux_options = "-f another-one.conf -L custom-socket".to_string();
        let config = Config {
            attached: false,
            name: "foo".to_string(),
            tmux_options: Some(tmux_options.clone()),
            windows: vec![Window {
                layout: None,
                name: Some(String::from("a window")),
                panes: Vec::new(),
                start_directory: None,
            }],
            ..Config::default()
        };

        let mut tmux_command_runner = MockTmuxCommandRunner::new();
        tmux_command_runner
            .expect_run_tmux_command()
            .once()
            .withf(|_terminal_multiplexer: &String, command: &[String], _| {
                *command
                    == vec![
                        "-f".to_string(),
                        "another-one.conf".to_string(),
                        "-L".to_string(),
                        "custom-socket".to_string(),
                        "start-server".to_string(),
                        ";".to_string(),
                        "show-option".to_string(),
                        "-g".to_string(),
                        "base-index".to_string(),
                        ";".to_string(),
                        "show-window-option".to_string(),
                        "-g".to_string(),
                        "pane-base-index".to_string(),
                    ]
            })
            .returning(|_x, _y, _z| Ok(create_dummy_output_instance(0, vec![], vec![])));

        tmux_command_runner
            .expect_run_tmux_command()
            .once()
            .withf(
                move |_terminal_multiplexer: &String, command: &[String], _| {
                    *command
                        == vec![
                            "-f",
                            "another-one.conf",
                            "-L",
                            "custom-socket",
                            "new-session",
                            "-d",
                            "-s",
                            "foo",
                            "-n",
                            "a window",
                        ]
                },
            )
            .returning(|_x, _y, _z| Ok(create_dummy_output_instance(0, vec![], vec![])));
        let _ = run_start_(config, &tmux_command_runner);
    }

    #[test]
    fn test_it_uses_a_custom_terminal_multiplexer_when_provided() {
        let terminal_multiplexer = String::from("tmux-yolo");
        let config = Config {
            terminal_multiplexer: terminal_multiplexer.clone(),
            ..Config::default()
        };

        let mut tmux_command_runner = MockTmuxCommandRunner::new();

        tmux_command_runner
            .expect_run_tmux_command()
            .with(eq(terminal_multiplexer.clone()), always(), always())
            .times(1..)
            .returning(|_, _, _| Ok(create_dummy_output_instance(0, vec![], vec![])));

        let _ = run_start_(config, &tmux_command_runner);
    }

    #[test]
    #[should_panic(expected = "'not-tmux' does not seem to be a compatible terminal multiplexer")]
    fn test_run_tmux_command_does_basic_validation_on_terminal_multiplexer() {
        let terminal_multiplexer = String::from("not-tmux");
        let command = vec![];
        let wait = false;
        let _ = run_tmux_command(&terminal_multiplexer, &command, wait);
    }

    #[test]
    fn test_it_doesnt_pass_tmux_options_to_tmux_when_absent() {
        let config = Config {
            attached: false,
            name: "foo".to_string(),
            tmux_options: None,
            windows: vec![Window {
                layout: None,
                name: Some(String::from("a window")),
                panes: Vec::new(),
                start_directory: None,
            }],
            ..Config::default()
        };

        let mut tmux_command_runner = MockTmuxCommandRunner::new();
        tmux_command_runner
            .expect_run_tmux_command()
            .once()
            .withf(|_terminal_multiplexer: &String, command: &[String], _| {
                *command
                    == vec![
                        "start-server".to_string(),
                        ";".to_string(),
                        "show-option".to_string(),
                        "-g".to_string(),
                        "base-index".to_string(),
                        ";".to_string(),
                        "show-window-option".to_string(),
                        "-g".to_string(),
                        "pane-base-index".to_string(),
                    ]
            })
            .returning(|_x, _y, _z| Ok(create_dummy_output_instance(0, vec![], vec![])));

        tmux_command_runner
            .expect_run_tmux_command()
            .once()
            .withf(
                move |_terminal_multiplexer: &String, command: &[String], _| {
                    *command == vec!["new-session", "-d", "-s", "foo", "-n", "a window"]
                },
            )
            .returning(|_x, _y, _z| Ok(create_dummy_output_instance(0, vec![], vec![])));
        let _ = run_start_(config, &tmux_command_runner);
    }

    #[test]
    fn test_run_tmux_command_does_not_receive_an_attach_command_when_attached_false() {
        let config = Config {
            attached: false,
            name: "foo".to_string(),
            windows: vec![Window {
                layout: None,
                name: Some(String::from("a window")),
                panes: Vec::new(),
                start_directory: None,
            }],
            ..Config::default()
        };
        let mut tmux_command_runner = MockTmuxCommandRunner::new();
        tmux_command_runner
            .expect_run_tmux_command()
            .once()
            .withf(|_terminal_multiplexer: &String, command: &[String], _| {
                *command
                    == vec![
                        "start-server".to_string(),
                        ";".to_string(),
                        "show-option".to_string(),
                        "-g".to_string(),
                        "base-index".to_string(),
                        ";".to_string(),
                        "show-window-option".to_string(),
                        "-g".to_string(),
                        "pane-base-index".to_string(),
                    ]
            })
            .returning(|_x, _y, _z| Ok(create_dummy_output_instance(0, vec![], vec![])));

        tmux_command_runner
            .expect_run_tmux_command()
            .once()
            .withf(|_terminal_multiplexer: &String, command: &[String], bool| {
                *bool == false
                    && *command == vec!["new-session", "-d", "-s", "foo", "-n", "a window"]
            })
            .returning(|_x, _y, _z| Ok(create_dummy_output_instance(0, vec![], vec![])));
        let _ = run_start_(config, &tmux_command_runner);
    }

    #[test]
    fn test_run_tmux_command_does_receive_an_attach_command_when_attached_true() {
        let config = Config {
            attached: true,
            name: "foo".to_string(),
            windows: vec![Window {
                layout: None,
                name: Some(String::from("a window")),
                panes: Vec::new(),
                start_directory: None,
            }],
            ..Config::default()
        };

        let mut tmux_command_runner = MockTmuxCommandRunner::new();
        tmux_command_runner
            .expect_run_tmux_command()
            .once()
            .withf(|_terminal_multiplexer: &String, command: &[String], bool| {
                *bool == false
                    && *command
                        == vec![
                            "start-server".to_string(),
                            ";".to_string(),
                            "show-option".to_string(),
                            "-g".to_string(),
                            "base-index".to_string(),
                            ";".to_string(),
                            "show-window-option".to_string(),
                            "-g".to_string(),
                            "pane-base-index".to_string(),
                        ]
            })
            .returning(|_x, _y, _z| Ok(create_dummy_output_instance(0, vec![], vec![])));

        tmux_command_runner
            .expect_run_tmux_command()
            .once()
            .withf(|_terminal_multiplexer: &String, command: &[String], bool| {
                *bool == false
                    && *command == vec!["new-session", "-d", "-s", "foo", "-n", "a window"]
            })
            .returning(|_x, _y, _z| Ok(create_dummy_output_instance(0, vec![], vec![])));

        tmux_command_runner
            .expect_run_tmux_command()
            .once()
            .withf(|_terminal_multiplexer: &String, command: &[String], bool| {
                *bool == true && *command == vec!["-u", "attach-session", "-t", "foo"]
            })
            .returning(|_x, _y, _z| Ok(create_dummy_output_instance(0, vec![], vec![])));

        let _ = run_start_(config, &tmux_command_runner);
    }

    #[test]
    fn it_converts_a_pascal_case_string_to_a_kebab_case_string() {
        let pascal = "KebabCase";
        let expected = "kebab-case";
        let actual = convert_pascal_case_to_kebab_case(&pascal);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_no_ops_on_a_non_pascal_case_string() {
        let pascal = "foo";
        let expected = "foo";
        let actual = convert_pascal_case_to_kebab_case(&pascal);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_builds_session_args_without_start_directory() {
        let session_name = "a session";
        let window_name = Some(String::from("a window"));
        let start_directory = None;
        let expected = vec![
            String::from("new-session"),
            String::from("-d"),
            String::from("-s"),
            String::from(session_name),
            String::from("-n"),
            window_name.clone().unwrap(),
        ];
        let actual = build_session_args(&session_name, window_name, &start_directory);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_builds_session_args_with_window_name() {
        let session_name = String::from("a session");
        let window_name = Some(String::from("a window"));
        let start_directory = None;
        let expected = vec![
            String::from("new-session"),
            String::from("-d"),
            String::from("-s"),
            String::from(&session_name),
            String::from("-n"),
            window_name.clone().unwrap(),
        ];
        let actual = build_session_args(&session_name, window_name, &start_directory);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_builds_session_args_without_window_name() {
        let session_name = String::from("a session");
        let window_name = None;
        let start_directory = None;
        let expected = vec![
            String::from("new-session"),
            String::from("-d"),
            String::from("-s"),
            String::from(&session_name),
        ];
        let actual = build_session_args(&session_name, window_name, &start_directory);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_builds_session_args_with_start_directory() {
        let session_name = "a session";
        let window_name = Some(String::from("a window"));
        let start_directory_ = String::from("/foo/bar");
        let start_directory = Some(start_directory_.clone());
        let expected = vec![
            String::from("new-session"),
            String::from("-d"),
            String::from("-s"),
            String::from(session_name),
            String::from("-n"),
            window_name.clone().unwrap(),
            String::from("-c"),
            String::from(start_directory_),
        ];
        let actual = build_session_args(&session_name, window_name, &start_directory);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_builds_window_layout_args_without_a_window_layout_or_a_config_layout() {
        let session_name = "foo";
        let window_index = 2;
        let config_layout = None;
        let window_layout = None;
        let actual =
            build_window_layout_args(&session_name, &window_index, &config_layout, &window_layout);
        assert!(actual.is_none());
    }

    #[test]
    fn it_builds_window_layout_args_with_a_config_layout_and_no_window_layout() {
        let session_name = "foo";
        let window_index = 2;
        let config_layout = Some(Layout::EvenHorizontal);
        let window_layout = None;
        let expected = vec![
            String::from("select-layout"),
            String::from("-t"),
            format!("{}:{}", &session_name, &window_index),
            config_layout.clone().unwrap().to_string(),
        ];
        let actual =
            build_window_layout_args(&session_name, &window_index, &config_layout, &window_layout);
        assert_eq!(expected, actual.unwrap());
    }

    #[test]
    fn it_builds_window_layout_args_with_a_window_layout_and_no_config_layout() {
        let session_name = "foo";
        let window_index = 2;
        let config_layout = None;
        let window_layout = Some(Layout::Tiled);
        let expected = vec![
            String::from("select-layout"),
            String::from("-t"),
            format!("{}:{}", &session_name, &window_index),
            window_layout.clone().unwrap().to_string(),
        ];
        let actual =
            build_window_layout_args(&session_name, &window_index, &config_layout, &window_layout);
        assert_eq!(expected, actual.unwrap());
    }

    #[test]
    fn it_builds_window_layout_args_with_a_window_layout_and_a_config_layout() {
        let session_name = "foo";
        let window_index = 2;
        let config_layout = Some(Layout::Tiled);
        let window_layout = Some(Layout::EvenHorizontal);
        let expected = vec![
            String::from("select-layout"),
            String::from("-t"),
            format!("{}:{}", &session_name, &window_index),
            window_layout.clone().unwrap().to_string(),
        ];
        let actual =
            build_window_layout_args(&session_name, &window_index, &config_layout, &window_layout);
        assert_eq!(expected, actual.unwrap());
    }

    #[test]
    fn it_builds_window_args_without_a_start_directory() {
        let session_name = "a session";
        let window_name = Some(String::from("a window"));
        let window_index = 42;
        let start_directory = None;
        let expected = vec![
            String::from("new-window"),
            String::from("-t"),
            format!("{}:{}", &session_name, &window_index),
            String::from("-n"),
            window_name.clone().unwrap(),
        ];
        let actual =
            build_create_window_args(&session_name, window_index, &window_name, &start_directory);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_builds_window_args_with_a_start_directory() {
        let session_name = "a session";
        let window_name = Some(String::from("a window"));
        let window_index = 42;
        let start_directory = Some(String::from("/tmp/neat"));

        let expected = vec![
            String::from("new-window"),
            String::from("-t"),
            format!("{}:{}", &session_name, &window_index),
            String::from("-n"),
            window_name.clone().unwrap(),
            String::from("-c"),
            String::from("/tmp/neat"),
        ];
        let actual =
            build_create_window_args(&session_name, window_index, &window_name, &start_directory);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_builds_attach_args() {
        let session_name = "a session";
        let expected = vec![
            String::from("-u"),
            String::from("attach-session"),
            String::from("-t"),
            String::from(session_name),
        ];
        let actual = build_attach_command_args(&session_name);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_converts_layout_to_string() {
        let layout = Layout::Tiled;
        let expected = String::from("tiled");
        let actual = layout.to_string();
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_converts_custom_layout_to_string() {
        let custom_layout = String::from(
            "9959,213x59,0,0[213x24,0,0,4,213x2,0,25,5,213x31,0,28{166x31,0,28,6,46x31,167,28,7}]",
        );
        let layout = Layout::Custom(custom_layout.clone());
        let expected = custom_layout;
        let actual = layout.to_string();
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_uses_no_start_directory_when_none_present_for_session_start_directory() {
        let config = Config {
            name: String::from("foo"),
            windows: vec![Window {
                layout: None,
                name: Some(String::from("a window")),
                panes: Vec::new(),
                start_directory: None,
            }],
            ..Config::default()
        };

        let actual = build_session_start_directory(&config);
        assert!(actual.is_none());
    }

    #[test]
    fn it_uses_configs_start_directory_when_no_window_start_directory_present_for_session_start_directory(
    ) {
        let config = Config {
            name: String::from("foo"),
            start_directory: Some(String::from("/foo/bar")),
            ..Config::default()
        };
        let expected = Some(String::from("/foo/bar"));
        let actual = build_session_start_directory(&config);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_uses_windows_start_directory_over_configs_start_directory_for_session_start_directory() {
        let config = Config {
            name: String::from("foo"),
            start_directory: Some(String::from("/this/is/ignored")),
            windows: vec![Window {
                layout: None,
                name: Some(String::from("a window")),
                panes: Vec::new(),
                start_directory: Some(String::from("/bar/baz")),
            }],

            ..Config::default()
        };
        let expected = Some(String::from("/bar/baz"));
        let actual = build_session_start_directory(&config);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_uses_no_start_directory_when_none_present_for_window_start_directory() {
        let config_start_directory = None;
        let window_start_directory = None;

        let actual = build_window_start_directory(&config_start_directory, &window_start_directory);
        assert!(actual.is_none());
    }

    #[test]
    fn it_uses_windows_start_directory_over_configs_start_directory_for_window_start_directory() {
        let config_start_directory = Some(String::from("/this/is/ignored"));
        let window_start_directory = Some(String::from("/bar/baz"));

        let expected = window_start_directory.clone();
        let actual = build_window_start_directory(&config_start_directory, &window_start_directory);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_uses_configs_start_directory_when_no_window_start_directory_present_for_window_start_directory(
    ) {
        let config_start_directory = Some(String::from("/foo/bar"));
        let window_start_directory = None;

        let expected = config_start_directory.clone();
        let actual = build_window_start_directory(&config_start_directory, &window_start_directory);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_uses_pane_sd_when_window_sd_is_none_and_config_sd_is_none() {
        let config_start_directory = None;
        let window_start_directory = None;
        let pane_start_directory = Some(String::from("/foo/bar"));

        let expected = pane_start_directory.clone();
        let actual = build_pane_start_directory(
            &config_start_directory,
            &window_start_directory,
            &pane_start_directory,
        );
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_uses_pane_sd_when_window_sd_is_some_and_config_sd_is_none() {
        let config_start_directory = None;
        let window_start_directory = Some(String::from("/bar/baz"));
        let pane_start_directory = Some(String::from("/foo/bar"));

        let expected = pane_start_directory.clone();
        let actual = build_pane_start_directory(
            &config_start_directory,
            &window_start_directory,
            &pane_start_directory,
        );
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_uses_pane_sd_when_window_sd_is_none_and_config_sd_is_some() {
        let config_start_directory = Some(String::from("/bar/baz"));
        let window_start_directory = None;
        let pane_start_directory = Some(String::from("/foo/bar"));

        let expected = pane_start_directory.clone();
        let actual = build_pane_start_directory(
            &config_start_directory,
            &window_start_directory,
            &pane_start_directory,
        );
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_uses_pane_sd_when_window_sd_is_some_and_config_sd_is_some() {
        let config_start_directory = Some(String::from("/bar/baz"));
        let window_start_directory = Some(String::from("/bar/baz"));
        let pane_start_directory = Some(String::from("/foo/bar"));

        let expected = pane_start_directory.clone();
        let actual = build_pane_start_directory(
            &config_start_directory,
            &window_start_directory,
            &pane_start_directory,
        );
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_uses_window_sd_when_pane_sd_is_none_and_config_sd_is_none() {
        let config_start_directory = None;
        let window_start_directory = Some(String::from("/foo/bar"));
        let pane_start_directory = None;

        let expected = window_start_directory.clone();
        let actual = build_pane_start_directory(
            &config_start_directory,
            &window_start_directory,
            &pane_start_directory,
        );
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_uses_window_sd_when_pane_sd_is_none_and_config_sd_is_some() {
        let config_start_directory = Some(String::from("/bar/baz"));
        let window_start_directory = Some(String::from("/foo/bar"));
        let pane_start_directory = None;

        let expected = window_start_directory.clone();
        let actual = build_pane_start_directory(
            &config_start_directory,
            &window_start_directory,
            &pane_start_directory,
        );
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_uses_config_sd_when_pane_sd_is_none_and_config_sd_is_none() {
        let config_start_directory = Some(String::from("/foo/bar"));
        let window_start_directory = None;
        let pane_start_directory = None;

        let expected = config_start_directory.clone();
        let actual = build_pane_start_directory(
            &config_start_directory,
            &window_start_directory,
            &pane_start_directory,
        );
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_uses_no_pane_sd_when_none_are_set() {
        let config_start_directory = None;
        let window_start_directory = None;
        let pane_start_directory = None;

        let actual = build_pane_start_directory(
            &config_start_directory,
            &window_start_directory,
            &pane_start_directory,
        );
        assert!(actual.is_none());
    }

    #[test]
    fn it_builds_hook_arguments() {
        let hook = Hook {
            command: String::from("run \"echo hi\""),
            name: HookName::PaneFocusIn,
        };
        let expected = vec![
            String::from("set-hook"),
            String::from("-a"),
            String::from("pane-focus-in"),
            String::from("run \"echo hi\""),
        ];
        let actual = build_hook_args(&hook);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_builds_rename_pane_args_when_pane_name_and_pane_name_user_option_present() {
        let session_name = "session-name";
        let window_index = 3;
        let pane_index = 4;
        let pane_name_user_option = Some(String::from("pane_name_user_option"));
        let pane_name = Some(String::from("pane-name"));
        let expected = vec![
            String::from("set-option"),
            String::from("-p"),
            String::from("-t"),
            format!("{}:{}.{}", session_name, window_index, pane_index),
            String::from("@pane_name_user_option"),
            String::from("pane-name"),
        ];
        let actual = build_rename_pane_args(
            &session_name,
            window_index,
            pane_index,
            &pane_name_user_option,
            &pane_name,
        );
        assert_eq!(expected, actual.unwrap());
    }

    #[test]
    fn it_doesnt_build_rename_pane_args_when_no_pane_name_present() {
        let session_name = "session-name";
        let window_index = 3;
        let pane_index = 4;
        let pane_name_user_option = Some(String::from("pane_name_user_option"));
        let pane_name = None;
        let actual = build_rename_pane_args(
            &session_name,
            window_index,
            pane_index,
            &pane_name_user_option,
            &pane_name,
        );
        assert!(actual.is_none());
    }

    #[test]
    fn it_doesnt_build_rename_pane_args_when_no_pane_name_user_option_present() {
        let session_name = "session-name";
        let window_index = 3;
        let pane_index = 4;
        let pane_name_user_option = None;
        let pane_name = Some(String::from("pane-name"));
        let actual = build_rename_pane_args(
            &session_name,
            window_index,
            pane_index,
            &pane_name_user_option,
            &pane_name,
        );
        assert!(actual.is_none());
    }

    #[test]
    fn it_computes_the_expected_commands() {
        let config = Config {
            name: String::from("most basic config"),
            ..Config::default()
        };

        let expected = vec![(
            vec![
                String::from("new-session"),
                String::from("-d"),
                String::from("-s"),
                String::from("most basic config"),
            ],
            false,
        )];
        let base_indices = TmuxBaseIndices {
            base_index: 0,
            pane_base_index: 0,
        };
        let actual = convert_config_to_tmux_commands(&config, base_indices);
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_accepts_valid_cli_command_arg() {
        let expected = CliCommand::Start;
        let actual = CliCommand::from_str("start").unwrap();
        assert_eq!(expected, actual);
    }

    #[test]
    fn it_rejects_invalid_cli_command_arg() {
        let actual = CliCommand::from_str("xtart");
        assert!(actual.is_err());
    }

    #[test]
    fn it_accepts_correct_cli_args() {
        let expected = CliArgs {
            command: CliCommand::Start,
            project_name: String::from("Foo.toml"),
        };
        let args = vec!["rmuxinator", "start", "Foo.toml"];
        let actual = parse_args(args);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_for_tmux_returns_true_when_tmux_exists() {
        let actual = test_for_tmux("tmux");
        assert!(actual);
    }

    #[test]
    fn test_for_tmux_returns_false_when_tmux_doesnt_exist() {
        let actual = test_for_tmux("xmux");
        assert!(!actual);
    }
}