cargo-shuttle 0.57.3

CLI for the Shuttle platform (shuttle.dev)
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
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
mod args;
pub mod builder;
pub mod config;
mod init;
mod provisioner_server;
mod util;

use std::collections::{BTreeMap, HashMap};
use std::ffi::OsString;
use std::fs;
use std::io::{Read, Write};
use std::net::{Ipv4Addr, SocketAddr};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;

use anyhow::{bail, Context, Result};
use args::DeploymentTrackingArgs;
use chrono::Utc;
use clap::{parser::ValueSource, CommandFactory, FromArgMatches};
use crossterm::style::Stylize;
use dialoguer::{theme::ColorfulTheme, Confirm, Input, Password, Select};
use futures::{SinkExt, StreamExt};
use git2::Repository;
use globset::{Glob, GlobSetBuilder};
use ignore::overrides::OverrideBuilder;
use ignore::WalkBuilder;
use indicatif::ProgressBar;
use indoc::formatdoc;
use reqwest::header::HeaderMap;
use shuttle_api_client::ShuttleApiClient;
use shuttle_builder::render_rust_dockerfile;
use shuttle_common::{
    constants::{
        headers::X_CARGO_SHUTTLE_VERSION, other_env_api_url, EXAMPLES_REPO, SHUTTLE_API_URL,
        SHUTTLE_CONSOLE_URL, TEMPLATES_SCHEMA_VERSION,
    },
    models::{
        auth::{KeyMessage, TokenMessage},
        deployment::{
            BuildArgs as CommonBuildArgs, BuildMeta, DeploymentRequest,
            DeploymentRequestBuildArchive, DeploymentRequestImage, DeploymentResponse,
            DeploymentState, Environment, GIT_STRINGS_MAX_LENGTH,
        },
        error::ApiError,
        log::LogItem,
        project::ProjectUpdateRequest,
        resource::ResourceType,
    },
    tables::{deployments_table, get_certificates_table, get_projects_table, get_resource_tables},
};
use shuttle_ifc::parse_infra_from_code;
use strum::{EnumMessage, VariantArray};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::time::{sleep, Duration};
use tokio_tungstenite::tungstenite::Message;
use tracing::{debug, error, info, trace, warn};
use tracing_subscriber::{fmt, prelude::*, registry, EnvFilter};
use util::cargo_green_eprintln;
use zip::write::FileOptions;

use crate::args::{
    BuildArgs, CertificateCommand, ConfirmationArgs, DeployArgs, DeploymentCommand,
    GenerateCommand, InitArgs, LoginArgs, LogoutArgs, LogsArgs, McpCommand, OutputMode,
    ProjectCommand, ProjectUpdateCommand, ResourceCommand, SecretsArgs, TableArgs,
    TemplateLocation,
};
pub use crate::args::{BuildArgsShared, Command, ProjectArgs, RunArgs, ShuttleArgs};
use crate::builder::{
    cargo_build, find_first_shuttle_package, gather_rust_build_args, BuiltService,
};
use crate::config::RequestContext;
use crate::provisioner_server::{ProvApiState, ProvisionerServer};
use crate::util::{
    bacon, cargo_metadata, check_and_warn_runtime_version, generate_completions, generate_manpage,
    get_templates_schema, is_dirty, open_gh_issue, read_ws_until_text, update_cargo_shuttle,
};

const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Returns the args and whether the PATH arg of the init command was explicitly given
pub fn parse_args() -> (ShuttleArgs, bool) {
    let matches = ShuttleArgs::command().get_matches();
    let mut args =
        ShuttleArgs::from_arg_matches(&matches).expect("args to already be parsed successfully");
    let provided_path_to_init = matches
        .subcommand_matches("init")
        .is_some_and(|init_matches| {
            init_matches.value_source("path") == Some(ValueSource::CommandLine)
        });

    // don't use an override if production is targetted
    if args
        .api_env
        .as_ref()
        .is_some_and(|e| e == "prod" || e == "production")
    {
        args.api_env = None;
    }

    (args, provided_path_to_init)
}

pub fn setup_tracing(debug: bool) {
    registry()
        .with(fmt::layer().with_writer(std::io::stderr))
        .with(
            // let user set RUST_LOG if they want to
            EnvFilter::try_from_default_env().unwrap_or_else(|_| {
                if debug {
                    EnvFilter::new("info,cargo_shuttle=trace,shuttle=trace")
                } else {
                    EnvFilter::default()
                }
            }),
        )
        .init();
}

#[derive(PartialEq)]
pub enum Binary {
    CargoShuttle,
    Shuttle,
}

impl Binary {
    pub fn name(&self) -> String {
        match self {
            Self::CargoShuttle => "cargo-shuttle".to_owned(),
            Self::Shuttle => "shuttle".to_owned(),
        }
    }
}

pub struct Shuttle {
    ctx: RequestContext,
    client: Option<ShuttleApiClient>,
    output_mode: OutputMode,
    /// Alter behaviour based on which CLI is used
    bin: Binary,
}

impl Shuttle {
    pub fn new(bin: Binary, env_override: Option<String>) -> Result<Self> {
        let ctx = RequestContext::load_global(env_override.inspect(|e| {
            eprintln!(
                "{}",
                format!("INFO: Using non-default global config file: {e}").yellow(),
            )
        }))?;
        Ok(Self {
            ctx,
            client: None,
            output_mode: OutputMode::Normal,
            bin,
        })
    }

    pub async fn run(mut self, args: ShuttleArgs, provided_path_to_init: bool) -> Result<()> {
        self.output_mode = args.output_mode;

        // Set up the API client for all commands that call the API
        if matches!(
            args.cmd,
            Command::Init(..)
                | Command::Deploy(..)
                | Command::Logs { .. }
                | Command::Account
                | Command::Login(..)
                | Command::Logout(..)
                | Command::Deployment(..)
                | Command::Resource(..)
                | Command::Certificate(..)
                | Command::Project(..)
        ) {
            let api_url = args
                .api_url
                // calculate env-specific url if no explicit url given but an env was given
                .or_else(|| args.api_env.as_ref().map(|env| other_env_api_url(env)))
                // add /admin prefix if in admin mode
                .map(|u| if args.admin { format!("{u}/admin") } else { u });
            if let Some(ref url) = api_url {
                if url != SHUTTLE_API_URL {
                    eprintln!(
                        "{}",
                        format!("INFO: Targeting non-default API: {url}").yellow(),
                    );
                }
                if url.ends_with('/') {
                    eprintln!("WARNING: API URL is probably incorrect. Ends with '/': {url}");
                }
            }
            self.ctx.set_api_url(api_url);

            let client = ShuttleApiClient::new(
                self.ctx.api_url(),
                self.ctx.api_key().ok(),
                Some(
                    HeaderMap::try_from(&HashMap::from([(
                        X_CARGO_SHUTTLE_VERSION.clone(),
                        crate::VERSION.to_owned(),
                    )]))
                    .unwrap(),
                ),
                None,
            );
            self.client = Some(client);
        }

        // Load project context for all commands that need to know which project is being targetted
        if matches!(
            args.cmd,
            Command::Deploy(..)
                | Command::Deployment(..)
                | Command::Resource(..)
                | Command::Certificate(..)
                | Command::Project(
                    // ProjectCommand::List does not need to know which project we are in
                    // ProjectCommand::Create is handled separately and will always make the POST call
                    ProjectCommand::Update(..)
                        | ProjectCommand::Status
                        | ProjectCommand::Delete { .. }
                        | ProjectCommand::Link
                )
                | Command::Logs { .. }
        ) {
            // Command::Run and Command::Build use `load_local_config` (below) instead of `load_project_id` since they don't target a project in the API
            self.load_project_id(
                &args.project_args,
                matches!(args.cmd, Command::Project(ProjectCommand::Link)),
                // Only 'deploy' should create a project if the provided name is not found in the project list
                matches!(args.cmd, Command::Deploy(..)),
            )
            .await?;
        }

        match args.cmd {
            Command::Init(init_args) => {
                self.init(
                    init_args,
                    args.project_args,
                    provided_path_to_init,
                    args.offline,
                )
                .await
            }
            Command::Generate(cmd) => match cmd {
                GenerateCommand::Manpage => generate_manpage(),
                GenerateCommand::Shell { shell, output_file } => {
                    generate_completions(self.bin, shell, output_file)
                }
            },
            Command::Account => self.account().await,
            Command::Login(login_args) => self.login(login_args, args.offline, true).await,
            Command::Logout(logout_args) => self.logout(logout_args).await,
            Command::Feedback => open_gh_issue(),
            Command::Run(run_args) => {
                self.ctx.load_local_config(&args.project_args)?;
                self.local_run(run_args, args.debug).await
            }
            Command::Build(build_args) => {
                self.ctx.load_local_config(&args.project_args)?;
                self.build(&build_args).await
            }
            Command::Deploy(deploy_args) => self.deploy(deploy_args).await,
            Command::Logs(logs_args) => self.logs(logs_args).await,
            Command::Deployment(cmd) => match cmd {
                DeploymentCommand::List { page, limit, table } => {
                    self.deployments_list(page, limit, table).await
                }
                DeploymentCommand::Status { deployment_id } => {
                    self.deployment_get(deployment_id).await
                }
                DeploymentCommand::Redeploy {
                    deployment_id,
                    tracking_args,
                } => self.deployment_redeploy(deployment_id, tracking_args).await,
                DeploymentCommand::Stop { tracking_args } => {
                    self.deployment_stop(tracking_args).await
                }
            },
            Command::Resource(cmd) => match cmd {
                ResourceCommand::List {
                    table,
                    show_secrets,
                } => self.resources_list(table, show_secrets).await,
                ResourceCommand::Delete {
                    resource_type,
                    confirmation: ConfirmationArgs { yes },
                } => self.resource_delete(&resource_type, yes).await,
                ResourceCommand::Dump { resource_type } => self.resource_dump(&resource_type).await,
            },
            Command::Certificate(cmd) => match cmd {
                CertificateCommand::Add { domain } => self.add_certificate(domain).await,
                CertificateCommand::List { table } => self.list_certificates(table).await,
                CertificateCommand::Delete {
                    domain,
                    confirmation: ConfirmationArgs { yes },
                } => self.delete_certificate(domain, yes).await,
            },
            Command::Project(cmd) => match cmd {
                ProjectCommand::Create => self.project_create(args.project_args.name).await,
                ProjectCommand::Update(cmd) => match cmd {
                    ProjectUpdateCommand::Name { new_name } => self.project_rename(new_name).await,
                },
                ProjectCommand::Status => self.project_status().await,
                ProjectCommand::List { table, .. } => self.projects_list(table).await,
                ProjectCommand::Delete(ConfirmationArgs { yes }) => self.project_delete(yes).await,
                ProjectCommand::Link => Ok(()), // logic is done in `load_project_id` in previous step
            },
            Command::Upgrade { preview } => update_cargo_shuttle(preview).await,
            Command::Mcp(cmd) => match cmd {
                McpCommand::Start => shuttle_mcp::run_mcp_server().await,
            },
        }
    }

    /// Log in, initialize a project and potentially create the Shuttle environment for it.
    ///
    /// If project name, template, and path are passed as arguments, it will run without any extra
    /// interaction.
    async fn init(
        &mut self,
        args: InitArgs,
        mut project_args: ProjectArgs,
        provided_path_to_init: bool,
        offline: bool,
    ) -> Result<()> {
        // Turns the template or git args (if present) to a repo+folder.
        let git_template = args.git_template()?;
        let no_git = args.no_git;

        let needs_name = project_args.name.is_none();
        let needs_template = git_template.is_none();
        let needs_path = !provided_path_to_init;
        let needs_login = self.ctx.api_key().is_err() && args.login_args.api_key.is_none();
        let should_link = project_args.id.is_some();
        let interactive = needs_name || needs_template || needs_path || needs_login;

        let theme = ColorfulTheme::default();

        // 1. Log in (if not logged in yet)
        if needs_login {
            eprintln!("First, let's log in to your Shuttle account.");
            self.login(args.login_args.clone(), offline, false).await?;
            eprintln!();
        } else if args.login_args.api_key.is_some() {
            self.login(args.login_args.clone(), offline, false).await?;
        }

        // 2. Ask for project name or validate the given one
        let mut prev_name: Option<String> = None;
        loop {
            // prompt if interactive
            let name: String = if let Some(name) = project_args.name.clone() {
                name
            } else {
                // not using `validate_with` due to being blocking.
                Input::with_theme(&theme)
                    .with_prompt("Project name")
                    .interact()?
            };
            let force_name = args.force_name
                || (needs_name && prev_name.as_ref().is_some_and(|prev| prev == &name));
            if force_name {
                project_args.name = Some(name);
                break;
            }
            // validate and take action based on result
            if self
                .check_project_name(&mut project_args, name.clone())
                .await
            {
                // success
                break;
            } else if needs_name {
                // try again
                eprintln!(r#"Type the same name again to use "{}" anyways."#, name);
                prev_name = Some(name);
            } else {
                // don't continue if non-interactive
                bail!(
                    "Invalid or unavailable project name. Use `--force-name` to use this project name anyways."
                );
            }
        }
        if needs_name {
            eprintln!();
        }

        // 3. Confirm the project directory
        let path = if needs_path {
            let path = args
                .path
                .join(project_args.name.as_ref().expect("name should be set"));

            loop {
                eprintln!("Where should we create this project?");

                let directory_str: String = Input::with_theme(&theme)
                    .with_prompt("Directory")
                    .default(format!("{}", path.display()))
                    .interact()?;
                eprintln!();

                let path = args::create_and_parse_path(OsString::from(directory_str))?;

                if fs::read_dir(&path)
                    .expect("init dir to exist and list entries")
                    .count()
                    > 0
                    && !Confirm::with_theme(&theme)
                        .with_prompt("Target directory is not empty. Are you sure?")
                        .default(true)
                        .interact()?
                {
                    eprintln!();
                    continue;
                }

                break path;
            }
        } else {
            args.path.clone()
        };

        // 4. Ask for the template
        let template = match git_template {
            Some(git_template) => git_template,
            None => {
                // Try to present choices from our up-to-date examples.
                // Fall back to the internal (potentially outdated) list.
                let schema = if offline {
                    None
                } else {
                    get_templates_schema()
                        .await
                        .map_err(|e| {
                            error!(err = %e, "Failed to get templates");
                            eprintln!(
                                "{}",
                                "Failed to look up template list. Falling back to internal list."
                                    .yellow()
                            )
                        })
                        .ok()
                        .and_then(|s| {
                            if s.version == TEMPLATES_SCHEMA_VERSION {
                                return Some(s);
                            }
                            eprintln!(
                                "{}",
                                "Template list with incompatible version found. Consider upgrading Shuttle CLI. Falling back to internal list."
                                    .yellow()
                            );

                            None
                        })
                };
                if let Some(schema) = schema {
                    eprintln!("What type of project template would you like to start from?");
                    let i = Select::with_theme(&theme)
                        .items(&[
                            "A Hello World app in a supported framework",
                            "Browse our full library of templates", // TODO(when templates page is live): Add link to it?
                        ])
                        .clear(false)
                        .default(0)
                        .interact()?;
                    eprintln!();
                    if i == 0 {
                        // Use a Hello world starter
                        let mut starters = schema.starters.into_values().collect::<Vec<_>>();
                        starters.sort_by_key(|t| {
                            // Make the "No templates" appear last in the list
                            if t.title.starts_with("No") {
                                "zzz".to_owned()
                            } else {
                                t.title.clone()
                            }
                        });
                        let starter_strings = starters
                            .iter()
                            .map(|t| {
                                format!("{} - {}", t.title.clone().bold(), t.description.clone())
                            })
                            .collect::<Vec<_>>();
                        let index = Select::with_theme(&theme)
                            .with_prompt("Select template")
                            .items(&starter_strings)
                            .default(0)
                            .interact()?;
                        eprintln!();
                        let path = starters[index]
                            .path
                            .clone()
                            .expect("starter to have a path");

                        TemplateLocation {
                            auto_path: EXAMPLES_REPO.into(),
                            subfolder: Some(path),
                        }
                    } else {
                        // Browse all non-starter templates
                        let mut templates = schema.templates.into_values().collect::<Vec<_>>();
                        templates.sort_by_key(|t| t.title.clone());
                        let template_strings = templates
                            .iter()
                            .map(|t| {
                                format!(
                                    "{} - {}{}",
                                    t.title.clone().bold(),
                                    t.description.clone(),
                                    t.tags
                                        .first()
                                        .map(|tag| format!(" ({tag})").dim().to_string())
                                        .unwrap_or_default(),
                                )
                            })
                            .collect::<Vec<_>>();
                        let index = Select::with_theme(&theme)
                            .with_prompt("Select template")
                            .items(&template_strings)
                            .default(0)
                            .interact()?;
                        eprintln!();
                        let path = templates[index]
                            .path
                            .clone()
                            .expect("template to have a path");

                        TemplateLocation {
                            auto_path: EXAMPLES_REPO.into(),
                            subfolder: Some(path),
                        }
                    }
                } else {
                    eprintln!("Shuttle works with many frameworks. Which one do you want to use?");
                    let frameworks = args::InitTemplateArg::VARIANTS;
                    let framework_strings = frameworks
                        .iter()
                        .map(|t| {
                            t.get_documentation()
                                .expect("all template variants to have docs")
                        })
                        .collect::<Vec<_>>();
                    let index = Select::with_theme(&theme)
                        .items(&framework_strings)
                        .default(0)
                        .interact()?;
                    eprintln!();
                    frameworks[index].template()
                }
            }
        };

        // 5. Initialize locally
        crate::init::generate_project(
            path.clone(),
            project_args
                .name
                .as_ref()
                .expect("to have a project name provided"),
            &template,
            no_git,
        )?;
        eprintln!();

        // 6. Confirm that the user wants to create the project on Shuttle
        let should_create_project = if should_link {
            // user wants to link project that already exists
            false
        } else if !interactive {
            // non-interactive mode: use value of arg
            args.create_project
        } else if args.create_project {
            // interactive and arg is true
            true
        } else {
            // interactive and arg was not set, so ask
            let name = project_args
                .name
                .as_ref()
                .expect("to have a project name provided");

            let should_create = Confirm::with_theme(&theme)
                .with_prompt(format!(
                    r#"Create a project on Shuttle with the name "{name}"?"#
                ))
                .default(true)
                .interact()?;
            eprintln!();
            should_create
        };

        if should_link || should_create_project {
            // Set the project working directory path to the init path,
            // so `load_project_id` is ran with the correct project path when linking
            project_args.working_directory.clone_from(&path);

            self.load_project_id(&project_args, true, true).await?;
        }

        if std::env::current_dir().is_ok_and(|d| d != path) {
            eprintln!("You can `cd` to the directory, then:");
        }
        eprintln!("Run `shuttle deploy` to deploy it to Shuttle.");

        Ok(())
    }

    /// Return value: true -> success or unknown. false -> try again.
    async fn check_project_name(&self, project_args: &mut ProjectArgs, name: String) -> bool {
        let client = self.client.as_ref().unwrap();
        match client
            .check_project_name(&name)
            .await
            .map(|r| r.into_inner())
        {
            Ok(true) => {
                project_args.name = Some(name);

                true
            }
            Ok(false) => {
                // should not be possible
                panic!("Unexpected API response");
            }
            Err(e) => {
                // If API error contains message regarding format of error name, print that error and prompt again
                if let Ok(api_error) = e.downcast::<ApiError>() {
                    // If the returned error string changes, this could break
                    if api_error.message().contains("Invalid project name") {
                        eprintln!("{}", api_error.message().yellow());
                        eprintln!("{}", "Try a different name.".yellow());
                        return false;
                    }
                }
                // Else, the API error was about something else.
                // Ignore and keep going to not prevent the flow of the init command.
                project_args.name = Some(name);
                eprintln!(
                    "{}",
                    "Failed to check if project name is available.".yellow()
                );

                true
            }
        }
    }

    /// Ensures a project id is known, either by explicit --id/--name args or config file(s)
    /// or by asking user to link the project folder.
    pub async fn load_project_id(
        &mut self,
        project_args: &ProjectArgs,
        do_linking: bool,
        create_missing_project: bool,
    ) -> Result<()> {
        trace!("project arguments: {project_args:?}");

        self.ctx.load_local_config(project_args)?;
        // load project id from args if given or from internal config file if present
        self.ctx.load_local_internal_config(project_args)?;

        // If project id was not given via arg but a name was, try to translate the project name to a project id.
        // (A --name from args takes precedence over an id from internal config.)
        if project_args.id.is_none() {
            if let Some(name) = project_args.name.as_ref() {
                let client = self.client.as_ref().unwrap();
                trace!(%name, "looking up project id from project name");
                if let Some(proj) = client
                    .get_projects_list()
                    .await?
                    .into_inner()
                    .projects
                    .into_iter()
                    .find(|p| p.name == *name)
                {
                    trace!("found project by name");
                    self.ctx.set_project_id(proj.id);
                } else {
                    trace!("did not find project by name");
                    if create_missing_project {
                        trace!("creating project since it was not found");
                        // This is a side effect (non-primary output), so OutputMode::Json is not considered
                        let proj = client.create_project(name).await?.into_inner();
                        eprintln!("Created project '{}' with id {}", proj.name, proj.id);
                        self.ctx.set_project_id(proj.id);
                    } else if do_linking {
                        self.project_link_interactive().await?;
                        return Ok(());
                    } else {
                        bail!(
                            "Project with name '{}' not found in your project list. \
                            Use 'shuttle project link' to create it or link an existing project.",
                            name
                        );
                    }
                }
            }
        }

        match (self.ctx.project_id_found(), do_linking) {
            (true, true) => {
                let arg_given = project_args.id.is_some() || project_args.name.is_some();
                if arg_given {
                    // project id was found via explicitly given arg, save config
                    eprintln!("Linking to project {}", self.ctx.project_id());
                    self.ctx.save_local_internal()?;
                } else {
                    // project id was found but not given via arg, ask the user interactively
                    self.project_link_interactive().await?;
                }
            }
            // if project id is known, we are done and nothing more to do
            (true, false) => (),
            // we still don't know the project id, so ask the user interactively
            (false, _) => {
                trace!("no project id found");
                self.project_link_interactive().await?;
            }
        }

        Ok(())
    }

    async fn project_link_interactive(&mut self) -> Result<()> {
        let client = self.client.as_ref().unwrap();
        let projs = client.get_projects_list().await?.into_inner().projects;

        let theme = ColorfulTheme::default();

        let selected_project = if projs.is_empty() {
            eprintln!("Create a new project to link to this directory:");

            None
        } else {
            eprintln!("Which project do you want to link this directory to?");

            let mut items = projs
                .iter()
                .map(|p| {
                    if let Some(team_id) = p.team_id.as_ref() {
                        format!("Team {}: {}", team_id, p.name)
                    } else {
                        p.name.clone()
                    }
                })
                .collect::<Vec<_>>();
            items.extend_from_slice(&["[CREATE NEW]".to_string()]);
            let index = Select::with_theme(&theme)
                .items(&items)
                .default(0)
                .interact()?;

            if index == projs.len() {
                // last item selected (create new)
                None
            } else {
                Some(projs[index].clone())
            }
        };

        let proj = match selected_project {
            Some(proj) => proj,
            None => {
                let name: String = Input::with_theme(&theme)
                    .with_prompt("Project name")
                    .interact()?;

                // This is a side effect (non-primary output), so OutputMode::Json is not considered
                let proj = client.create_project(&name).await?.into_inner();
                eprintln!("Created project '{}' with id {}", proj.name, proj.id);

                proj
            }
        };

        eprintln!("Linking to project '{}' with id {}", proj.name, proj.id);
        self.ctx.set_project_id(proj.id);
        self.ctx.save_local_internal()?;

        Ok(())
    }

    async fn account(&self) -> Result<()> {
        let client = self.client.as_ref().unwrap();
        let r = client.get_current_user().await?;
        match self.output_mode {
            OutputMode::Normal => {
                print!("{}", r.into_inner().to_string_colored());
            }
            OutputMode::Json => {
                println!("{}", r.raw_json);
            }
        }

        Ok(())
    }

    /// Log in with the given API key or after prompting the user for one.
    async fn login(&mut self, login_args: LoginArgs, offline: bool, login_cmd: bool) -> Result<()> {
        let api_key = match login_args.api_key {
            Some(api_key) => api_key,
            None => {
                if login_args.prompt {
                    Password::with_theme(&ColorfulTheme::default())
                        .with_prompt("API key")
                        .validate_with(|input: &String| {
                            if input.is_empty() {
                                return Err("Empty API key was provided");
                            }
                            Ok(())
                        })
                        .interact()?
                } else {
                    // device auth flow via Shuttle Console
                    self.device_auth(login_args.console_url).await?
                }
            }
        };

        self.ctx.set_api_key(api_key.clone())?;

        if let Some(client) = self.client.as_mut() {
            client.api_key = Some(api_key);

            if offline {
                eprintln!("INFO: Skipping API key verification");
            } else {
                let (user, raw_json) = client
                    .get_current_user()
                    .await
                    .context("failed to check API key validity")?
                    .into_parts();
                if login_cmd {
                    match self.output_mode {
                        OutputMode::Normal => {
                            println!("Logged in as {}", user.id.bold());
                        }
                        OutputMode::Json => {
                            println!("{}", raw_json);
                        }
                    }
                } else {
                    eprintln!("Logged in as {}", user.id.bold());
                }
            }
        }

        Ok(())
    }

    async fn device_auth(&self, console_url: Option<String>) -> Result<String> {
        let client = self.client.as_ref().unwrap();

        // should not have trailing slash
        if let Some(u) = console_url.as_ref() {
            if u.ends_with('/') {
                eprintln!("WARNING: Console URL is probably incorrect. Ends with '/': {u}");
            }
        }

        let (mut tx, mut rx) = client.get_device_auth_ws().await?.split();

        // keep the socket alive with ping/pong
        let pinger = tokio::spawn(async move {
            loop {
                if let Err(e) = tx.send(Message::Ping(Default::default())).await {
                    error!(error = %e, "Error when pinging websocket");
                    break;
                };
                sleep(Duration::from_secs(20)).await;
            }
        });

        let token_message = read_ws_until_text(&mut rx).await?;
        let Some(token_message) = token_message else {
            bail!("Did not receive device auth token over websocket");
        };
        let token_message = serde_json::from_str::<TokenMessage>(&token_message)?;
        let token = token_message.token;

        // use provided url if it exists, otherwise fall back to old behavior of constructing it here
        let url = token_message.url.unwrap_or_else(|| {
            format!(
                "{}/device-auth?token={}",
                console_url.as_deref().unwrap_or(SHUTTLE_CONSOLE_URL),
                token
            )
        });
        let _ = webbrowser::open(&url);
        eprintln!("Complete login in Shuttle Console to authenticate the Shuttle CLI.");
        eprintln!("If your browser did not automatically open, go to {url}");
        eprintln!();
        eprintln!("{}", format!("Token: {token}").bold());
        eprintln!();

        let key = read_ws_until_text(&mut rx).await?;
        let Some(key) = key else {
            bail!("Failed to receive API key over websocket");
        };
        let key = serde_json::from_str::<KeyMessage>(&key)?.api_key;

        pinger.abort();

        Ok(key)
    }

    async fn logout(&mut self, logout_args: LogoutArgs) -> Result<()> {
        if logout_args.reset_api_key {
            let client = self.client.as_ref().unwrap();
            client.reset_api_key().await.context("Resetting API key")?;
            eprintln!("Successfully reset the API key.");
        }
        self.ctx.clear_api_key()?;
        eprintln!("Successfully logged out.");
        eprintln!(" -> Use `shuttle login` to log in again.");

        Ok(())
    }

    async fn deployment_stop(&self, tracking_args: DeploymentTrackingArgs) -> Result<()> {
        let client = self.client.as_ref().unwrap();
        let pid = self.ctx.project_id();
        let res = client.stop_service(pid).await?.into_inner();
        println!("{res}");

        if tracking_args.no_follow {
            return Ok(());
        }

        wait_with_spinner(2000, |_, pb| async move {
            let (deployment, raw_json) = client.get_current_deployment(pid).await?.into_parts();

            let get_cleanup = |d: Option<DeploymentResponse>| {
                move || {
                    if let Some(d) = d {
                        match self.output_mode {
                            OutputMode::Normal => {
                                eprintln!("{}", d.to_string_colored());
                            }
                            OutputMode::Json => {
                                // last deployment response already printed
                            }
                        }
                    }
                }
            };
            let Some(deployment) = deployment else {
                return Ok(Some(get_cleanup(None)));
            };

            let state = deployment.state.clone();
            match self.output_mode {
                OutputMode::Normal => {
                    pb.set_message(deployment.to_string_summary_colored());
                }
                OutputMode::Json => {
                    println!("{}", raw_json);
                }
            }
            let cleanup = get_cleanup(Some(deployment));
            match state {
                DeploymentState::Pending
                | DeploymentState::Stopping
                | DeploymentState::InProgress
                | DeploymentState::Running => Ok(None),
                DeploymentState::Building // a building deployment should take it back to InProgress then Running, so don't follow that sequence
                | DeploymentState::Failed
                | DeploymentState::Stopped
                | DeploymentState::Unknown(_) => Ok(Some(cleanup)),
            }
        })
        .await?;

        Ok(())
    }

    async fn logs(&self, args: LogsArgs) -> Result<()> {
        if args.follow {
            eprintln!("Streamed logs are not yet supported on the shuttle.dev platform.");
            return Ok(());
        }
        if args.tail.is_some() | args.head.is_some() {
            eprintln!("Fetching log ranges are not yet supported on the shuttle.dev platform.");
            return Ok(());
        }
        let client = self.client.as_ref().unwrap();
        let pid = self.ctx.project_id();
        let r = if args.all_deployments {
            client.get_project_logs(pid).await?
        } else {
            let id = if args.latest {
                // Find latest deployment (not always an active one)
                let deployments = client
                    .get_deployments(pid, 1, 1)
                    .await?
                    .into_inner()
                    .deployments;
                let Some(most_recent) = deployments.into_iter().next() else {
                    println!("No deployments found");
                    return Ok(());
                };
                eprintln!("Getting logs from: {}", most_recent.id);
                most_recent.id
            } else if let Some(id) = args.deployment_id {
                id
            } else {
                let Some(current) = client.get_current_deployment(pid).await?.into_inner() else {
                    println!("No deployments found");
                    return Ok(());
                };
                eprintln!("Getting logs from: {}", current.id);
                current.id
            };
            client.get_deployment_logs(pid, &id).await?
        };
        match self.output_mode {
            OutputMode::Normal => {
                let logs = r.into_inner().logs;
                for log in logs {
                    if args.raw {
                        println!("{}", log.line);
                    } else {
                        println!("{log}");
                    }
                }
            }
            OutputMode::Json => {
                println!("{}", r.raw_json);
            }
        }

        Ok(())
    }

    async fn deployments_list(&self, page: u32, limit: u32, table_args: TableArgs) -> Result<()> {
        if limit == 0 {
            warn!("Limit is set to 0, no deployments will be listed.");
            return Ok(());
        }
        let client = self.client.as_ref().unwrap();
        let pid = self.ctx.project_id();

        // fetch one additional to know if there is another page available
        let limit = limit + 1;
        let (deployments, raw_json) = client
            .get_deployments(pid, page as i32, limit as i32)
            .await?
            .into_parts();
        let mut deployments = deployments.deployments;
        let page_hint = if deployments.len() == limit as usize {
            // hide the extra one and show hint instead
            deployments.pop();
            true
        } else {
            false
        };
        match self.output_mode {
            OutputMode::Normal => {
                let table = deployments_table(&deployments, table_args.raw);
                println!("{}", format!("Deployments in project '{}'", pid).bold());
                println!("{table}");
                if page_hint {
                    println!("View the next page using `--page {}`", page + 1);
                }
            }
            OutputMode::Json => {
                println!("{}", raw_json);
            }
        }

        Ok(())
    }

    async fn deployment_get(&self, deployment_id: Option<String>) -> Result<()> {
        let client = self.client.as_ref().unwrap();
        let pid = self.ctx.project_id();

        let deployment = match deployment_id {
            Some(id) => {
                let r = client.get_deployment(pid, &id).await?;
                if self.output_mode == OutputMode::Json {
                    println!("{}", r.raw_json);
                    return Ok(());
                }
                r.into_inner()
            }
            None => {
                let r = client.get_current_deployment(pid).await?;
                if self.output_mode == OutputMode::Json {
                    println!("{}", r.raw_json);
                    return Ok(());
                }

                let Some(d) = r.into_inner() else {
                    println!("No deployment found");
                    return Ok(());
                };
                d
            }
        };

        println!("{}", deployment.to_string_colored());

        Ok(())
    }

    async fn deployment_redeploy(
        &self,
        deployment_id: Option<String>,
        tracking_args: DeploymentTrackingArgs,
    ) -> Result<()> {
        let client = self.client.as_ref().unwrap();

        let pid = self.ctx.project_id();
        let deployment_id = match deployment_id {
            Some(id) => id,
            None => {
                let d = client.get_current_deployment(pid).await?.into_inner();
                let Some(d) = d else {
                    println!("No deployment found");
                    return Ok(());
                };
                d.id
            }
        };
        let (deployment, raw_json) = client.redeploy(pid, &deployment_id).await?.into_parts();

        if tracking_args.no_follow {
            match self.output_mode {
                OutputMode::Normal => {
                    println!("{}", deployment.to_string_colored());
                }
                OutputMode::Json => {
                    println!("{}", raw_json);
                }
            }
            return Ok(());
        }

        self.track_deployment_status_and_print_logs_on_fail(pid, &deployment.id, tracking_args.raw)
            .await
    }

    async fn resources_list(&self, table_args: TableArgs, show_secrets: bool) -> Result<()> {
        let client = self.client.as_ref().unwrap();
        let pid = self.ctx.project_id();
        let r = client.get_service_resources(pid).await?;

        match self.output_mode {
            OutputMode::Normal => {
                let table = get_resource_tables(
                    r.into_inner().resources.as_slice(),
                    pid,
                    table_args.raw,
                    show_secrets,
                );
                println!("{table}");
            }
            OutputMode::Json => {
                println!("{}", r.raw_json);
            }
        }

        Ok(())
    }

    async fn resource_delete(&self, resource_type: &ResourceType, no_confirm: bool) -> Result<()> {
        let client = self.client.as_ref().unwrap();

        if !no_confirm {
            eprintln!(
                "{}",
                formatdoc!(
                    "
                WARNING:
                    Are you sure you want to delete this project's {}?
                    This action is permanent.",
                    resource_type
                )
                .bold()
                .red()
            );
            if !Confirm::with_theme(&ColorfulTheme::default())
                .with_prompt("Are you sure?")
                .default(false)
                .interact()
                .unwrap()
            {
                return Ok(());
            }
        }

        let msg = client
            .delete_service_resource(self.ctx.project_id(), resource_type)
            .await?
            .into_inner();
        println!("{msg}");

        eprintln!(
            "{}",
            formatdoc! {"
                Note:
                    Remember to remove the resource annotation from your #[shuttle_runtime::main] function.
                    Otherwise, it will be provisioned again during the next deployment."
            }
            .yellow(),
        );

        Ok(())
    }

    async fn resource_dump(&self, resource_type: &ResourceType) -> Result<()> {
        let client = self.client.as_ref().unwrap();

        let bytes = client
            .dump_service_resource(self.ctx.project_id(), resource_type)
            .await?;
        std::io::stdout()
            .write_all(&bytes)
            .context("writing output to stdout")?;

        Ok(())
    }

    async fn list_certificates(&self, table_args: TableArgs) -> Result<()> {
        let client = self.client.as_ref().unwrap();
        let r = client.list_certificates(self.ctx.project_id()).await?;

        match self.output_mode {
            OutputMode::Normal => {
                let table =
                    get_certificates_table(r.into_inner().certificates.as_ref(), table_args.raw);
                println!("{table}");
            }
            OutputMode::Json => {
                println!("{}", r.raw_json);
            }
        }

        Ok(())
    }
    async fn add_certificate(&self, domain: String) -> Result<()> {
        let client = self.client.as_ref().unwrap();
        let r = client
            .add_certificate(self.ctx.project_id(), domain.clone())
            .await?;

        match self.output_mode {
            OutputMode::Normal => {
                println!("Added certificate for {}", r.into_inner().subject);
            }
            OutputMode::Json => {
                println!("{}", r.raw_json);
            }
        }

        Ok(())
    }
    async fn delete_certificate(&self, domain: String, no_confirm: bool) -> Result<()> {
        let client = self.client.as_ref().unwrap();

        if !no_confirm {
            eprintln!(
                "{}",
                formatdoc!(
                    "
                WARNING:
                    Delete the certificate for {}?",
                    domain
                )
                .bold()
                .red()
            );
            if !Confirm::with_theme(&ColorfulTheme::default())
                .with_prompt("Are you sure?")
                .default(false)
                .interact()
                .unwrap()
            {
                return Ok(());
            }
        }

        let msg = client
            .delete_certificate(self.ctx.project_id(), domain.clone())
            .await?
            .into_inner();
        println!("{msg}");

        Ok(())
    }

    fn get_secrets(
        args: &SecretsArgs,
        workspace_root: &Path,
        dev: bool,
    ) -> Result<Option<HashMap<String, String>>> {
        // Look for a secrets file, first in the command args, then in the root of the workspace.
        let files: &[PathBuf] = if dev {
            &[
                workspace_root.join("Secrets.dev.toml"),
                workspace_root.join("Secrets.toml"),
            ]
        } else {
            &[workspace_root.join("Secrets.toml")]
        };
        let secrets_file = args.secrets.as_ref().or_else(|| {
            files
                .iter()
                .find(|&secrets_file| secrets_file.exists() && secrets_file.is_file())
        });

        let Some(secrets_file) = secrets_file else {
            trace!("No secrets file was found");
            return Ok(None);
        };

        trace!("Loading secrets from {}", secrets_file.display());
        let Ok(secrets_str) = fs::read_to_string(secrets_file) else {
            tracing::warn!("Failed to read secrets file, no secrets were loaded");
            return Ok(None);
        };

        let secrets = toml::from_str::<HashMap<String, String>>(&secrets_str)
            .context("parsing secrets file")?;
        trace!(keys = ?secrets.keys(), "Loaded secrets");

        Ok(Some(secrets))
    }

    async fn build(&self, build_args: &BuildArgs) -> Result<()> {
        eprintln!("WARN: The build command is EXPERIMENTAL. Please submit feedback on GitHub or Discord if you encounter issues.");
        if let Some(path) = build_args.output_archive.as_ref() {
            let archive = self.make_archive()?;
            eprintln!("Writing archive to {}", path.display());
            fs::write(path, archive).context("writing archive")?;
            Ok(())
        } else if build_args.inner.docker {
            self.local_docker_build(&build_args.inner).await
        } else {
            self.local_build(&build_args.inner).await.map(|_| ())
        }
    }

    async fn local_build(&self, build_args: &BuildArgsShared) -> Result<BuiltService> {
        let project_directory = self.ctx.project_directory();

        cargo_green_eprintln("Building", project_directory.display());

        // TODO: hook up -q/--quiet flag
        let quiet = false;
        cargo_build(project_directory.to_owned(), build_args.release, quiet).await
    }

    fn find_available_port(run_args: &mut RunArgs) {
        let original_port = run_args.port;
        for port in (run_args.port..=u16::MAX).step_by(10) {
            if !portpicker::is_free_tcp(port) {
                continue;
            }
            run_args.port = port;
            break;
        }

        if run_args.port != original_port {
            eprintln!(
                "Port {} is already in use. Using port {}.",
                original_port, run_args.port,
            )
        };
    }

    async fn local_run(&self, mut run_args: RunArgs, debug: bool) -> Result<()> {
        let project_name = self.ctx.project_name().to_owned();
        let project_directory = self.ctx.project_directory();

        trace!("starting a local run with args: {run_args:?}");

        // Handle bacon mode
        if run_args.build_args.bacon {
            cargo_green_eprintln(
                "Starting",
                format!("{} in watch mode using bacon", project_name),
            );
            eprintln!();
            return bacon::run_bacon(project_directory).await;
        }

        if run_args.build_args.docker {
            eprintln!("WARN: Local run with --docker is EXPERIMENTAL. Please submit feedback on GitHub or Discord if you encounter issues.");
        }

        let secrets = Shuttle::get_secrets(&run_args.secret_args, project_directory, true)?
            .unwrap_or_default();
        Shuttle::find_available_port(&mut run_args);

        let s_re = if !run_args.build_args.docker {
            let service = self.local_build(&run_args.build_args).await?;
            trace!(path = ?service.executable_path, "runtime executable");
            if let Some(warning) = check_and_warn_runtime_version(&service.executable_path).await? {
                eprint!("{}", warning);
            }
            let runtime_executable = service.executable_path.clone();

            Some((service, runtime_executable))
        } else {
            self.local_docker_build(&run_args.build_args).await?;
            None
        };

        let api_port = portpicker::pick_unused_port()
            .expect("failed to find available port for local provisioner server");
        let api_addr = SocketAddr::new(Ipv4Addr::LOCALHOST.into(), api_port);
        let healthz_port = portpicker::pick_unused_port()
            .expect("failed to find available port for runtime health check");
        let ip = if run_args.external {
            Ipv4Addr::UNSPECIFIED
        } else {
            Ipv4Addr::LOCALHOST
        };

        let state = Arc::new(ProvApiState {
            project_name: project_name.clone(),
            secrets,
        });
        tokio::spawn(async move { ProvisionerServer::run(state, &api_addr).await });

        let mut envs = vec![
            ("SHUTTLE_BETA", "true".to_owned()),
            ("SHUTTLE_PROJECT_ID", "proj_LOCAL".to_owned()),
            ("SHUTTLE_PROJECT_NAME", project_name.clone()),
            ("SHUTTLE_ENV", Environment::Local.to_string()),
            ("SHUTTLE_RUNTIME_IP", ip.to_string()),
            ("SHUTTLE_RUNTIME_PORT", run_args.port.to_string()),
            ("SHUTTLE_HEALTHZ_PORT", healthz_port.to_string()),
            ("SHUTTLE_API", format!("http://127.0.0.1:{}", api_port)),
        ];
        // Use a nice debugging tracing level if user does not provide their own
        if debug && std::env::var("RUST_LOG").is_err() {
            envs.push(("RUST_LOG", "info,shuttle=trace,reqwest=debug".to_owned()));
        } else if let Ok(v) = std::env::var("RUST_LOG") {
            // forward the RUST_LOG var into the container if using docker
            envs.push(("RUST_LOG", v));
        }

        let name = format!("shuttle-run-{project_name}");
        let mut child = if run_args.build_args.docker {
            let image = format!("shuttle-build-{project_name}");
            eprintln!();
            cargo_green_eprintln(
                "Starting",
                format!("{} on http://{}:{}", image, ip, run_args.port),
            );
            eprintln!();
            info!(image, "Spawning 'docker run' process");
            let mut docker = tokio::process::Command::new("docker");
            docker
                .arg("run")
                // the kill on docker run does not work as well as manual docker stop after quitting,
                // but this is good to have regardless
                .arg("--rm")
                .arg("--network")
                .arg("host")
                .arg("--name")
                .arg(&name);
            for (k, v) in envs {
                docker.arg("--env").arg(format!("{k}={v}"));
            }

            docker
                .arg(&image)
                .stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::piped())
                .kill_on_drop(true)
                .spawn()
                .context("spawning 'docker run' process")?
        } else {
            let (service, runtime_executable) = s_re.context("developer skill issue")?;
            eprintln!();
            cargo_green_eprintln(
                "Starting",
                format!("{} on http://{}:{}", service.target_name, ip, run_args.port),
            );
            eprintln!();
            info!(
                path = %runtime_executable.display(),
                "Spawning runtime process",
            );
            tokio::process::Command::new(
                dunce::canonicalize(runtime_executable)
                    .context("canonicalize path of executable")?,
            )
            .current_dir(&service.workspace_path)
            .envs(envs)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .context("spawning runtime process")?
        };

        // Start background tasks for reading child's stdout and stderr
        let raw = run_args.raw;
        let mut stdout_reader = BufReader::new(
            child
                .stdout
                .take()
                .context("child process did not have a handle to stdout")?,
        )
        .lines();
        tokio::spawn(async move {
            while let Some(line) = stdout_reader.next_line().await.unwrap() {
                if raw {
                    println!("{}", line);
                } else {
                    let log_item = LogItem::new(Utc::now(), "app".to_owned(), line);
                    println!("{log_item}");
                }
            }
        });
        let mut stderr_reader = BufReader::new(
            child
                .stderr
                .take()
                .context("child process did not have a handle to stderr")?,
        )
        .lines();
        tokio::spawn(async move {
            while let Some(line) = stderr_reader.next_line().await.unwrap() {
                if raw {
                    println!("{}", line);
                } else {
                    let log_item = LogItem::new(Utc::now(), "app".to_owned(), line);
                    println!("{log_item}");
                }
            }
        });

        // Start background task for simulated health check
        tokio::spawn(async move {
            loop {
                // ECS health check runs ever 5s
                tokio::time::sleep(tokio::time::Duration::from_millis(5000)).await;

                tracing::trace!("Health check against runtime");
                if let Err(e) = reqwest::get(format!("http://127.0.0.1:{}/", healthz_port)).await {
                    tracing::trace!("Health check against runtime failed: {e}");
                }
            }
        });

        #[cfg(target_family = "unix")]
        let exit_result = {
            let mut sigterm_notif =
                tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
                    .expect("Can not get the SIGTERM signal receptor");
            let mut sigint_notif =
                tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())
                    .expect("Can not get the SIGINT signal receptor");
            tokio::select! {
                exit_result = child.wait() => {
                    Some(exit_result)
                }
                _ = sigterm_notif.recv() => {
                    eprintln!("Received SIGTERM.");
                    None
                },
                _ = sigint_notif.recv() => {
                    eprintln!("Received SIGINT.");
                    None
                }
            }
        };
        #[cfg(target_family = "windows")]
        let exit_result = {
            let mut ctrl_break_notif = tokio::signal::windows::ctrl_break()
                .expect("Can not get the CtrlBreak signal receptor");
            let mut ctrl_c_notif =
                tokio::signal::windows::ctrl_c().expect("Can not get the CtrlC signal receptor");
            let mut ctrl_close_notif = tokio::signal::windows::ctrl_close()
                .expect("Can not get the CtrlClose signal receptor");
            let mut ctrl_logoff_notif = tokio::signal::windows::ctrl_logoff()
                .expect("Can not get the CtrlLogoff signal receptor");
            let mut ctrl_shutdown_notif = tokio::signal::windows::ctrl_shutdown()
                .expect("Can not get the CtrlShutdown signal receptor");
            tokio::select! {
                exit_result = child.wait() => {
                    Some(exit_result)
                }
                _ = ctrl_break_notif.recv() => {
                    eprintln!("Received ctrl-break.");
                    None
                },
                _ = ctrl_c_notif.recv() => {
                    eprintln!("Received ctrl-c.");
                    None
                },
                _ = ctrl_close_notif.recv() => {
                    eprintln!("Received ctrl-close.");
                    None
                },
                _ = ctrl_logoff_notif.recv() => {
                    eprintln!("Received ctrl-logoff.");
                    None
                },
                _ = ctrl_shutdown_notif.recv() => {
                    eprintln!("Received ctrl-shutdown.");
                    None
                }
            }
        };
        match exit_result {
            Some(Ok(exit_status)) => {
                bail!(
                    "Runtime process exited with code {}",
                    exit_status.code().unwrap_or_default()
                );
            }
            Some(Err(e)) => {
                bail!("Failed to wait for runtime process to exit: {e}");
            }
            None => {
                eprintln!("Stopping runtime.");
                child.kill().await?;
                if run_args.build_args.docker {
                    let status = tokio::process::Command::new("docker")
                        .arg("stop")
                        .arg(name)
                        .kill_on_drop(true)
                        .stdout(Stdio::null())
                        .spawn()
                        .context("spawning 'docker stop'")?
                        .wait()
                        .await
                        .context("waiting for 'docker stop'")?;

                    if !status.success() {
                        eprintln!("WARN: 'docker stop' failed");
                    }
                }
            }
        }

        Ok(())
    }

    async fn local_docker_build(&self, build_args: &BuildArgsShared) -> Result<()> {
        let project_name = self.ctx.project_name().to_owned();
        let project_directory = self.ctx.project_directory();

        let metadata = cargo_metadata(project_directory)?;
        let rust_build_args = gather_rust_build_args(&metadata)?;

        cargo_green_eprintln("Building", format!("{} with docker", project_name));

        let tempdir = tempfile::Builder::new()
            .prefix("shuttle-build-")
            .tempdir()?
            .keep();
        tracing::debug!("Building in {}", tempdir.display());

        let build_files = self.gather_build_files()?;
        if build_files.is_empty() {
            error!("No files included in build. Aborting...");
            bail!("No files included in build");
        }

        // make sure this file exists
        tracing::debug!("Creating prebuild script file");
        fs::write(tempdir.join("shuttle_prebuild.sh"), "")?;
        for (path, name) in build_files {
            let dest = tempdir.join(&name);
            tracing::debug!("Copying {} to tempdir", name.display());
            fs::create_dir_all(dest.parent().expect("destination to not be the root"))?;
            fs::copy(path, dest)?;
        }
        tracing::debug!("Removing any .dockerignore file");
        // remove .dockerignore to not interfere
        let _ = fs::remove_file(tempdir.join(".dockerignore"));

        // TODO?: Support custom shuttle.Dockerfile
        let dockerfile = tempdir.join("__shuttle.Dockerfile");
        tracing::debug!("Writing dockerfile to {}", dockerfile.display());
        fs::write(&dockerfile, render_rust_dockerfile(&rust_build_args))?;

        let mut docker_cmd = tokio::process::Command::new("docker");
        docker_cmd
            .arg("buildx")
            .arg("build")
            .arg("--file")
            .arg(dockerfile)
            .arg("--tag")
            .arg(format!("shuttle-build-{project_name}"));
        if let Some(ref tag) = build_args.tag {
            docker_cmd.arg("--tag").arg(tag);
        }

        let docker = docker_cmd.arg(tempdir).kill_on_drop(true).spawn();

        let result = docker
            .context("spawning docker build command")?
            .wait()
            .await
            .context("waiting for docker build to exit")?;
        if !result.success() {
            bail!("Docker build error");
        }

        cargo_green_eprintln("Finished", "building with docker");

        Ok(())
    }

    async fn deploy(&mut self, args: DeployArgs) -> Result<()> {
        let client = self.client.as_ref().unwrap();
        let project_directory = self.ctx.project_directory();

        let secrets = Shuttle::get_secrets(&args.secret_args, project_directory, false)?;

        // Image deployment mode
        if let Some(image) = args.image {
            let pid = self.ctx.project_id();
            let deployment_req_image = DeploymentRequestImage { image, secrets };

            let (deployment, raw_json) = client
                .deploy(pid, DeploymentRequest::Image(deployment_req_image))
                .await?
                .into_parts();

            if args.tracking_args.no_follow {
                match self.output_mode {
                    OutputMode::Normal => {
                        println!("{}", deployment.to_string_colored());
                    }
                    OutputMode::Json => {
                        println!("{}", raw_json);
                    }
                }
                return Ok(());
            }

            return self
                .track_deployment_status_and_print_logs_on_fail(
                    pid,
                    &deployment.id,
                    args.tracking_args.raw,
                )
                .await;
        }

        // Build archive deployment mode
        let mut deployment_req = DeploymentRequestBuildArchive {
            secrets,
            ..Default::default()
        };
        let mut build_meta = BuildMeta::default();

        let metadata = cargo_metadata(project_directory)?;

        let rust_build_args = gather_rust_build_args(&metadata)?;
        deployment_req.build_args = Some(CommonBuildArgs::Rust(rust_build_args));

        let (_, target, _) = find_first_shuttle_package(&metadata)?;
        deployment_req.infra = parse_infra_from_code(
            &fs::read_to_string(target.src_path.as_path())
                .context("reading target file when extracting infra annotations")?,
        )
        .context("parsing infra annotations")?;

        if let Ok(repo) = Repository::discover(project_directory) {
            let repo_path = repo
                .workdir()
                .context("getting working directory of repository")?;
            let repo_path = dunce::canonicalize(repo_path)?;
            trace!(?repo_path, "found git repository");

            let dirty = is_dirty(&repo);
            build_meta.git_dirty = Some(dirty.is_err());

            let check_dirty = self.ctx.deny_dirty().is_some_and(|d| d);
            if check_dirty && !args.allow_dirty && dirty.is_err() {
                bail!(dirty.unwrap_err());
            }

            if let Ok(head) = repo.head() {
                // This is typically the name of the current branch
                // It is "HEAD" when head detached, for example when a tag is checked out
                build_meta.git_branch = head
                    .shorthand()
                    .map(|s| s.chars().take(GIT_STRINGS_MAX_LENGTH).collect());
                if let Ok(commit) = head.peel_to_commit() {
                    build_meta.git_commit_id = Some(commit.id().to_string());
                    // Summary is None if error or invalid utf-8
                    build_meta.git_commit_msg = commit
                        .summary()
                        .map(|s| s.chars().take(GIT_STRINGS_MAX_LENGTH).collect());
                }
            }
        }

        cargo_green_eprintln("Packing", "build files");
        let archive = self.make_archive()?;

        if let Some(path) = args.output_archive {
            eprintln!("Writing archive to {}", path.display());
            fs::write(path, archive).context("writing archive")?;

            return Ok(());
        }

        // TODO: upload secrets separately

        let pid = self.ctx.project_id();

        cargo_green_eprintln("Uploading", "build archive");
        let arch = client.upload_archive(pid, archive).await?.into_inner();
        deployment_req.archive_version_id = arch.archive_version_id;
        deployment_req.build_meta = Some(build_meta);

        cargo_green_eprintln("Creating", "deployment");
        let (deployment, raw_json) = client
            .deploy(
                pid,
                DeploymentRequest::BuildArchive(Box::new(deployment_req)),
            )
            .await?
            .into_parts();

        if args.tracking_args.no_follow {
            match self.output_mode {
                OutputMode::Normal => {
                    println!("{}", deployment.to_string_colored());
                }
                OutputMode::Json => {
                    println!("{}", raw_json);
                }
            }
            return Ok(());
        }

        self.track_deployment_status_and_print_logs_on_fail(
            pid,
            &deployment.id,
            args.tracking_args.raw,
        )
        .await
    }

    /// Returns true if the deployment failed
    async fn track_deployment_status(&self, pid: &str, id: &str) -> Result<bool> {
        let client = self.client.as_ref().unwrap();
        let failed = wait_with_spinner(2000, |_, pb| async move {
            let (deployment, raw_json) = client.get_deployment(pid, id).await?.into_parts();

            let state = deployment.state.clone();
            match self.output_mode {
                OutputMode::Normal => {
                    pb.set_message(deployment.to_string_summary_colored());
                }
                OutputMode::Json => {
                    println!("{}", raw_json);
                }
            }
            let failed = state == DeploymentState::Failed;
            let cleanup = move || {
                match self.output_mode {
                    OutputMode::Normal => {
                        eprintln!("{}", deployment.to_string_colored());
                    }
                    OutputMode::Json => {
                        // last deployment response already printed
                    }
                }
                failed
            };
            match state {
                // non-end states
                DeploymentState::Pending
                | DeploymentState::Building
                | DeploymentState::InProgress => Ok(None),
                // end states
                DeploymentState::Running
                | DeploymentState::Stopped
                | DeploymentState::Stopping
                | DeploymentState::Unknown(_)
                | DeploymentState::Failed => Ok(Some(cleanup)),
            }
        })
        .await?;

        Ok(failed)
    }

    async fn track_deployment_status_and_print_logs_on_fail(
        &self,
        proj_id: &str,
        depl_id: &str,
        raw: bool,
    ) -> Result<()> {
        let client = self.client.as_ref().unwrap();
        let failed = self.track_deployment_status(proj_id, depl_id).await?;
        if failed {
            let r = client.get_deployment_logs(proj_id, depl_id).await?;
            match self.output_mode {
                OutputMode::Normal => {
                    let logs = r.into_inner().logs;
                    for log in logs {
                        if raw {
                            println!("{}", log.line);
                        } else {
                            println!("{log}");
                        }
                    }
                }
                OutputMode::Json => {
                    println!("{}", r.raw_json);
                }
            }
            bail!("Deployment failed");
        }

        Ok(())
    }

    async fn project_create(&self, name: Option<String>) -> Result<()> {
        let Some(ref name) = name else {
            bail!("Provide a project name with '--name <name>'");
        };

        let client = self.client.as_ref().unwrap();
        let r = client.create_project(name).await?;

        match self.output_mode {
            OutputMode::Normal => {
                let project = r.into_inner();
                println!("Created project '{}' with id {}", project.name, project.id);
            }
            OutputMode::Json => {
                println!("{}", r.raw_json);
            }
        }

        Ok(())
    }

    async fn project_rename(&self, name: String) -> Result<()> {
        let client = self.client.as_ref().unwrap();

        let r = client
            .update_project(
                self.ctx.project_id(),
                ProjectUpdateRequest {
                    name: Some(name),
                    ..Default::default()
                },
            )
            .await?;

        match self.output_mode {
            OutputMode::Normal => {
                let project = r.into_inner();
                println!("Renamed project {} to '{}'", project.id, project.name);
            }
            OutputMode::Json => {
                println!("{}", r.raw_json);
            }
        }

        Ok(())
    }

    async fn projects_list(&self, table_args: TableArgs) -> Result<()> {
        let client = self.client.as_ref().unwrap();
        let r = client.get_projects_list().await?;

        match self.output_mode {
            OutputMode::Normal => {
                let all_projects = r.into_inner().projects;
                // partition by team id and print separate tables
                let mut all_projects_map = BTreeMap::new();
                for proj in all_projects {
                    all_projects_map
                        .entry(proj.team_id.clone())
                        .or_insert_with(Vec::new)
                        .push(proj);
                }
                for (team_id, projects) in all_projects_map {
                    println!(
                        "{}",
                        if let Some(team_id) = team_id {
                            format!("Team {} projects", team_id)
                        } else {
                            "Personal Projects".to_owned()
                        }
                        .bold()
                    );
                    println!("{}\n", get_projects_table(&projects, table_args.raw));
                }
            }
            OutputMode::Json => {
                println!("{}", r.raw_json);
            }
        }

        Ok(())
    }

    async fn project_status(&self) -> Result<()> {
        let client = self.client.as_ref().unwrap();
        let r = client.get_project(self.ctx.project_id()).await?;

        match self.output_mode {
            OutputMode::Normal => {
                print!("{}", r.into_inner().to_string_colored());
            }
            OutputMode::Json => {
                println!("{}", r.raw_json);
            }
        }

        Ok(())
    }

    async fn project_delete(&self, no_confirm: bool) -> Result<()> {
        let client = self.client.as_ref().unwrap();
        let pid = self.ctx.project_id();

        if !no_confirm {
            // check that the project exists, and look up the name
            let proj = client.get_project(pid).await?.into_inner();
            eprintln!(
                "{}",
                formatdoc!(
                    r#"
                    WARNING:
                        Are you sure you want to delete '{}' ({})?
                        This will...
                        - Shut down your service
                        - Delete any databases and secrets in this project
                        - Delete any custom domains linked to this project
                        This action is permanent."#,
                    proj.name,
                    pid,
                )
                .bold()
                .red()
            );
            if !Confirm::with_theme(&ColorfulTheme::default())
                .with_prompt("Are you sure?")
                .default(false)
                .interact()
                .unwrap()
            {
                return Ok(());
            }
        }

        let res = client.delete_project(pid).await?.into_inner();

        println!("{res}");

        Ok(())
    }

    /// Find list of all files to include in a build, ready for placing in a zip archive
    fn gather_build_files(&self) -> Result<BTreeMap<PathBuf, PathBuf>> {
        let include_patterns = self.ctx.include();
        let project_directory = self.ctx.project_directory();

        //
        // Mixing include and exclude overrides messes up the .ignore and .gitignore etc,
        // therefore these "ignore" walk and the "include" walk are separate.
        //
        let mut entries = Vec::new();

        // Default excludes
        let ignore_overrides = OverrideBuilder::new(project_directory)
            .add("!.git/")
            .context("adding override `!.git/`")?
            .add("!target/")
            .context("adding override `!target/`")?
            .build()
            .context("building archive override rules")?;
        for r in WalkBuilder::new(project_directory)
            .hidden(false)
            .overrides(ignore_overrides)
            .build()
        {
            entries.push(r.context("list dir entry")?.into_path())
        }

        // User provided includes
        let mut globs = GlobSetBuilder::new();
        if let Some(rules) = include_patterns {
            for r in rules {
                globs.add(Glob::new(r.as_str()).context(format!("parsing glob pattern {:?}", r))?);
            }
        }

        // Find the files
        let globs = globs.build().context("glob glob")?;
        for entry in walkdir::WalkDir::new(project_directory) {
            let path = entry.context("list dir")?.into_path();
            if globs.is_match(
                path.strip_prefix(project_directory)
                    .context("strip prefix of path")?,
            ) {
                entries.push(path);
            }
        }

        let mut archive_files = BTreeMap::new();
        for path in entries {
            // It's not possible to add a directory to an archive
            if path.is_dir() {
                trace!("Skipping {:?}: is a directory", path);
                continue;
            }
            // symlinks == chaos
            if path.is_symlink() {
                trace!("Skipping {:?}: is a symlink", path);
                continue;
            }

            // zip file puts all files in root
            let name = path
                .strip_prefix(project_directory)
                .context("strip prefix of path")?
                .to_owned();

            archive_files.insert(path, name);
        }

        Ok(archive_files)
    }

    fn make_archive(&self) -> Result<Vec<u8>> {
        let archive_files = self.gather_build_files()?;
        if archive_files.is_empty() {
            bail!("No files included in build");
        }

        let bytes = {
            debug!("making zip archive");
            let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
            for (path, name) in archive_files {
                debug!("Packing {path:?}");

                // windows things
                let name = name.to_str().expect("valid filename").replace('\\', "/");
                zip.start_file(name, FileOptions::<()>::default())?;

                let mut b = Vec::new();
                fs::File::open(path)?.read_to_end(&mut b)?;
                zip.write_all(&b)?;
            }
            let r = zip.finish().context("finish encoding zip archive")?;

            r.into_inner()
        };
        debug!("Archive size: {} bytes", bytes.len());

        Ok(bytes)
    }
}

/// Calls async function `f` in a loop with `millis` sleep between iterations,
/// providing iteration count and reference to update the progress bar.
/// `f` returns Some with a cleanup function if done.
/// The cleanup function is called after teardown of progress bar,
/// and its return value is returned from here.
async fn wait_with_spinner<Fut, C, O>(
    millis: u64,
    f: impl Fn(usize, ProgressBar) -> Fut,
) -> Result<O, anyhow::Error>
where
    Fut: std::future::Future<Output = Result<Option<C>>>,
    C: FnOnce() -> O,
{
    let progress_bar = create_spinner();
    let mut count = 0usize;
    let cleanup = loop {
        if let Some(cleanup) = f(count, progress_bar.clone()).await? {
            break cleanup;
        }
        count += 1;
        sleep(Duration::from_millis(millis)).await;
    };
    progress_bar.finish_and_clear();

    Ok(cleanup())
}

fn create_spinner() -> ProgressBar {
    let pb = indicatif::ProgressBar::new_spinner();
    pb.enable_steady_tick(std::time::Duration::from_millis(250));
    pb.set_style(
        indicatif::ProgressStyle::with_template("{spinner:.orange} {msg}")
            .unwrap()
            .tick_strings(&[
                "( ●    )",
                "(  ●   )",
                "(   ●  )",
                "(    ● )",
                "(     ●)",
                "(    ● )",
                "(   ●  )",
                "(  ●   )",
                "( ●    )",
                "(●     )",
                "(●●●●●●)",
            ]),
    );

    pb
}

#[cfg(test)]
mod tests {
    use zip::ZipArchive;

    use crate::args::ProjectArgs;
    use crate::Shuttle;
    use std::fs;
    use std::io::Cursor;
    use std::path::PathBuf;

    pub fn path_from_workspace_root(path: &str) -> PathBuf {
        let path = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap())
            .join("..")
            .join(path);

        dunce::canonicalize(path).unwrap()
    }

    async fn get_archive_entries(project_args: ProjectArgs) -> Vec<String> {
        let mut shuttle = Shuttle::new(crate::Binary::Shuttle, None).unwrap();
        shuttle
            .load_project_id(&project_args, false, false)
            .await
            .unwrap();

        let archive = shuttle.make_archive().unwrap();

        let mut zip = ZipArchive::new(Cursor::new(archive)).unwrap();
        (0..zip.len())
            .map(|i| zip.by_index(i).unwrap().name().to_owned())
            .collect()
    }

    #[tokio::test]
    async fn make_archive_respect_rules() {
        let working_directory = fs::canonicalize(path_from_workspace_root(
            "cargo-shuttle/tests/resources/archiving",
        ))
        .unwrap();

        fs::write(working_directory.join("Secrets.toml"), "KEY = 'value'").unwrap();
        fs::write(working_directory.join("Secrets.dev.toml"), "KEY = 'dev'").unwrap();
        fs::write(working_directory.join("asset2"), "").unwrap();
        fs::write(working_directory.join("asset4"), "").unwrap();
        fs::create_dir_all(working_directory.join("dist")).unwrap();
        fs::write(working_directory.join("dist").join("dist1"), "").unwrap();

        fs::create_dir_all(working_directory.join("target")).unwrap();
        fs::write(working_directory.join("target").join("binary"), b"12345").unwrap();

        let project_args = ProjectArgs {
            working_directory: working_directory.clone(),
            name: None,
            id: Some("proj_archiving-test".to_owned()),
        };
        let mut entries = get_archive_entries(project_args.clone()).await;
        entries.sort();

        let expected = vec![
            ".gitignore",
            ".ignore",
            "Cargo.toml",
            "Secrets.toml.example",
            "Shuttle.toml",
            "asset1", // normal file
            "asset2", // .gitignore'd, but included in Shuttle.toml
            // asset3 is .ignore'd
            "asset4",                // .gitignore'd, but un-ignored in .ignore
            "asset5",                // .ignore'd, but included in Shuttle.toml
            "dist/dist1",            // .gitignore'd, but included in Shuttle.toml
            "nested/static/nested1", // normal file
            // nested/static/nestedignore is .gitignore'd
            "src/main.rs",
        ];
        assert_eq!(entries, expected);
    }

    #[tokio::test]
    async fn finds_workspace_root() {
        let project_args = ProjectArgs {
            working_directory: path_from_workspace_root("examples/axum/hello-world/src"),
            name: None,
            id: None,
        };

        assert_eq!(
            project_args.workspace_path().unwrap(),
            path_from_workspace_root("examples/axum/hello-world")
        );
    }
}