ssg/lib.rs
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
// Copyright © 2025 Shokunin Static Site Generator (SSG). All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
#![doc = include_str!("../README.md")]
#![doc(
html_favicon_url = "https://kura.pro/shokunin/images/favicon.ico",
html_logo_url = "https://kura.pro/shokunin/images/logos/shokunin.svg",
html_root_url = "https://docs.rs/ssg"
)]
#![crate_name = "ssg"]
#![crate_type = "lib"]
// Standard library imports
use std::{
fs::{self, File},
io::Write,
path::{Path, PathBuf},
};
use crate::cmd::{Cli, ShokuninConfig};
// Third-party imports
use anyhow::{anyhow, ensure, Context, Result};
use dtt::datetime::DateTime;
use http_handle::Server;
use indicatif::{ProgressBar, ProgressStyle};
use langweave::translate;
use log::{info, LevelFilter};
use rayon::prelude::*;
use rlg::{macro_log, LogFormat, LogLevel};
use staticdatagen::{compile, generate_unique_string};
use tokio::fs as async_fs;
pub mod cmd;
/// Module declarations
pub mod process;
/// Re-exports
pub use staticdatagen;
/// Represents the necessary directory paths for the site generator.
#[derive(Debug, Clone)]
pub struct Paths {
/// The site output directory
pub site: PathBuf,
/// The content directory
pub content: PathBuf,
/// The build directory
pub build: PathBuf,
/// The template directory
pub template: PathBuf,
}
impl Paths {
/// Creates a new builder for configuring Paths
pub fn builder() -> PathsBuilder {
PathsBuilder::default()
}
/// Creates paths with default directories
pub fn default_paths() -> Self {
Self {
site: PathBuf::from("public"),
content: PathBuf::from("content"),
build: PathBuf::from("build"),
template: PathBuf::from("templates"),
}
}
}
// Modify the validate method in Paths impl
impl Paths {
/// Validates all paths in the configuration
pub fn validate(&self) -> Result<()> {
// Check for path traversal and other security concerns
for (name, path) in [
("site", &self.site),
("content", &self.content),
("build", &self.build),
("template", &self.template),
] {
// For non-existent paths, validate their components
let path_str = path.to_string_lossy();
if path_str.contains("..") {
anyhow::bail!(
"{} path contains directory traversal: {}",
name,
path.display()
);
}
if path_str.contains("//") {
anyhow::bail!(
"{} path contains invalid double slashes: {}",
name,
path.display()
);
}
// If path exists, perform additional checks
if path.exists() {
let metadata =
path.symlink_metadata().with_context(|| {
format!(
"Failed to get metadata for {}: {}",
name,
path.display()
)
})?;
if metadata.file_type().is_symlink() {
anyhow::bail!(
"{} path is a symlink which is not allowed: {}",
name,
path.display()
);
}
}
}
Ok(())
}
}
/// Builder for creating Paths configurations
#[derive(Debug, Default, Clone)]
pub struct PathsBuilder {
/// The site output directory
pub site: Option<PathBuf>,
/// The content directory
pub content: Option<PathBuf>,
/// The build directory
pub build: Option<PathBuf>,
/// The template directory
pub template: Option<PathBuf>,
}
impl PathsBuilder {
/// Sets the site output directory
pub fn site<P: Into<PathBuf>>(mut self, path: P) -> Self {
self.site = Some(path.into());
self
}
/// Sets the content directory
pub fn content<P: Into<PathBuf>>(mut self, path: P) -> Self {
self.content = Some(path.into());
self
}
/// Sets the build directory
pub fn build_dir<P: Into<PathBuf>>(mut self, path: P) -> Self {
self.build = Some(path.into());
self
}
/// Sets the template directory
pub fn template<P: Into<PathBuf>>(mut self, path: P) -> Self {
self.template = Some(path.into());
self
}
/// Sets all paths relative to a base directory
pub fn relative_to<P: AsRef<Path>>(self, base: P) -> Self {
let base = base.as_ref();
self.site(base.join("public"))
.content(base.join("content"))
.build_dir(base.join("build"))
.template(base.join("templates"))
}
/// Builds the Paths configuration
///
/// # Returns
///
/// * `Result<Paths>` - The configured paths if valid
///
/// # Errors
///
/// Returns an error if:
/// * Required paths are missing
/// * Paths are invalid or unsafe
/// * Unable to create necessary directories
pub fn build(self) -> Result<Paths> {
let paths = Paths {
site: self.site.unwrap_or_else(|| PathBuf::from("public")),
content: self
.content
.unwrap_or_else(|| PathBuf::from("content")),
build: self.build.unwrap_or_else(|| PathBuf::from("build")),
template: self
.template
.unwrap_or_else(|| PathBuf::from("templates")),
};
// Validate the configuration
paths.validate()?;
Ok(paths)
}
}
// Constants for configuration
const DEFAULT_LOG_LEVEL: &str = "info";
const ENV_LOG_LEVEL: &str = "SHOKUNIN_LOG_LEVEL";
/// Initializes the logging system based on environment variables
fn initialize_logging() -> Result<()> {
let log_level = std::env::var(ENV_LOG_LEVEL)
.unwrap_or_else(|_| DEFAULT_LOG_LEVEL.to_string());
let level = match log_level.to_lowercase().as_str() {
"error" => LevelFilter::Error,
"warn" => LevelFilter::Warn,
"info" => LevelFilter::Info,
"debug" => LevelFilter::Debug,
"trace" => LevelFilter::Trace,
_ => LevelFilter::Info,
};
env_logger::Builder::new()
.filter_level(level)
.format_timestamp_millis()
.init();
info!("Logging initialized at level: {}", log_level);
Ok(())
}
/// Executes the static site generation process.
///
/// Introduces asynchronous file operations, parallel processing, and a progress bar for feedback.
pub async fn run() -> Result<()> {
// 1. Initialize logging
initialize_logging()?;
info!("Starting site generation process");
// 2. Parse command-line arguments
let matches = Cli::build().get_matches();
// 3. Create/override config from CLI
let config = ShokuninConfig::from_matches(&matches)?;
println!("Configuration loaded: {:?}", config);
// 4. Directories gleaned from `config`.
// If you want a separate “build” folder vs. final “site” folder,
// you can store that in ShokuninConfig as well.
//
let build_dir = &config.output_dir; // “Temporary” build location
let content_dir = &config.content_dir;
let template_dir = &config.template_dir;
// 5. Use `serve_dir` if set, else fall back to `output_dir` for the final site.
let site_dir =
config.serve_dir.as_ref().unwrap_or(&config.output_dir);
// 6. Compile the site
compile(build_dir, content_dir, site_dir, template_dir).map_err(
|e| {
eprintln!(" ❌ Error compiling site: {:?}", e);
// Convert the error into an anyhow::Error so run() will fail
anyhow!("Failed to compile site: {:?}", e)
},
)?;
// 7. If compilation succeeded, serve the generated website locally.
let example_root =
site_dir.to_str().unwrap_or("./examples/public").to_string();
// 8. Create a new server with an address and document root
let server = Server::new("127.0.0.1:3000", &example_root);
// 9. Start the server (this will block in practice)
let _ = server.start();
// 10. If everything goes well, return Ok.
Ok(())
}
/// Validates and copies files from source to destination.
///
/// This function performs comprehensive safety checks before copying files,
/// including path validation, symlink detection, and size limitations.
///
/// # Arguments
///
/// * `src` - Source path to copy from
/// * `dst` - Destination path to copy to
///
/// # Returns
///
/// Returns `Ok(())` if the copy operation succeeds, or an error if:
/// * Source path is invalid or inaccessible
/// * Source contains symlinks (not allowed)
/// * Files exceed size limits (default: 10MB)
/// * Destination cannot be created or written to
///
/// # Example
///
/// ```rust,no_run
/// use std::path::Path;
/// use ssg::verify_and_copy_files;
///
/// fn main() -> anyhow::Result<()> {
/// let source = Path::new("source_directory");
/// let destination = Path::new("destination_directory");
///
/// verify_and_copy_files(source, destination)?;
/// println!("Files copied successfully");
/// Ok(())
/// }
/// ```
///
/// # Security
///
/// This function implements several security measures:
/// * Path traversal prevention
/// * Symlink restriction
/// * File size limits
/// * Permission validation
pub fn verify_and_copy_files(src: &Path, dst: &Path) -> Result<()> {
ensure!(
is_safe_path(src)?,
"Source directory is unsafe or inaccessible: {:?}",
src
);
if !src.exists() {
anyhow::bail!("Source directory does not exist: {:?}", src);
}
// If source is a file, verify its safety
if src.is_file() {
verify_file_safety(src)?;
}
// Ensure the destination directory exists
fs::create_dir_all(dst)
.with_context(|| format!("Failed to create or access destination directory at path: {:?}", dst))?;
// Copy directory contents with safety checks
copy_dir_all(src, dst).with_context(|| {
format!("Failed to copy files from source: {:?} to destination: {:?}", src, dst)
})?;
Ok(())
}
/// Asynchronously validates and copies files between directories.
pub async fn verify_and_copy_files_async(
src: &Path,
dst: &Path,
) -> Result<()> {
if !src.exists() {
return Err(anyhow::anyhow!(
"Source directory does not exist: {:?}",
src
));
}
async_fs::create_dir_all(dst).await.with_context(|| format!(
"Failed to create or access destination directory at path: {:?}",
dst
))?;
let mut entries = async_fs::read_dir(src).await?;
while let Some(entry) = entries.next_entry().await? {
let src_path = entry.path();
let dst_path = dst.join(entry.file_name());
if src_path.is_dir() {
Box::pin(verify_and_copy_files_async(&src_path, &dst_path))
.await?;
}
}
Ok(())
}
/// Recursively copies directories with a progress bar for feedback.
pub fn copy_dir_with_progress(src: &Path, dst: &Path) -> Result<()> {
if !src.exists() {
anyhow::bail!(
"Source directory does not exist: {}",
src.display()
);
}
fs::create_dir_all(dst).with_context(|| {
format!(
"Failed to create destination directory: {}",
dst.display()
)
})?;
let entries = fs::read_dir(src).with_context(|| {
format!("Failed to read source directory: {}", src.display())
})?;
let progress_bar = ProgressBar::new(entries.count() as u64);
progress_bar.set_style(
ProgressStyle::default_bar()
.template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} {msg}")
.unwrap()
.progress_chars("#>-"),
);
for entry in fs::read_dir(src)? {
let entry = entry?;
let src_path = entry.path();
let dst_path = dst.join(entry.file_name());
if src_path.is_dir() {
copy_dir_with_progress(&src_path, &dst_path)?;
} else {
let _ =
fs::copy(&src_path, &dst_path).with_context(|| {
format!(
"Failed to copy file from {} to {}",
src_path.display(),
dst_path.display()
)
})?;
}
progress_bar.inc(1);
}
progress_bar.finish_with_message("Copy complete.");
Ok(())
}
/// Checks if a given path is safe to use.
///
/// Validates that the provided path does not contain directory traversal attempts
/// or other potential security risks.
///
/// # Arguments
///
/// * `path` - The path to validate
///
/// # Returns
///
/// * `Ok(true)` - If the path is safe to use
/// * `Ok(false)` - If the path contains unsafe elements
/// * `Err` - If path validation fails
///
/// # Security
///
/// This function prevents directory traversal attacks by:
/// * Resolving symbolic links
/// * Checking for parent directory references (`..`)
/// * Validating path components
///
pub fn is_safe_path(path: &Path) -> Result<bool> {
// If path doesn't exist, check its parent
if !path.exists() {
if let Some(parent) = path.parent() {
if !parent.exists() {
return Ok(true); // Consider non-existent paths safe if they'll be created
}
}
}
let canonical = path.canonicalize().map_err(|e| {
anyhow::anyhow!(
"Failed to canonicalize path {}: {}",
path.display(),
e
)
})?;
let normalized = canonical.components().collect::<PathBuf>();
// Check if the path contains any parent directory references
let contains_parent_refs = normalized
.components()
.any(|comp| matches!(comp, std::path::Component::ParentDir));
// Consider the path safe if it doesn't contain parent refs and starts with current directory
Ok(!contains_parent_refs)
}
/// Verifies the safety of a file for processing.
///
/// Performs comprehensive safety checks on a file to ensure it meets security
/// requirements before processing. These checks include symlink detection and
/// file size validation.
///
/// # Arguments
///
/// * `path` - Reference to the path of the file to verify
///
/// # Returns
///
/// * `Ok(())` - If the file passes all safety checks
/// * `Err` - If any safety check fails
///
/// # Safety Checks
///
/// * Symlinks: Not allowed (returns error)
/// * File size: Must be under 10MB
/// * File type: Must be a regular file
///
/// # Examples
///
/// Verifies the safety of a file.
///
/// ```rust
/// use std::fs;
/// use std::path::Path;
/// use ssg::verify_file_safety;
/// use tempfile::tempdir;
///
/// # fn main() -> anyhow::Result<()> {
/// // Create temporary directory
/// let temp_dir = tempdir()?;
/// let file_path = temp_dir.path().join("index.md");
///
/// // Create test file
/// fs::write(&file_path, "Hello, world!")?;
///
/// // Perform verification
/// verify_file_safety(&file_path)?;
///
/// // Directory and file are automatically cleaned up
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// * File is a symlink
/// * File size exceeds 10MB
/// * Cannot read file metadata
pub fn verify_file_safety(path: &Path) -> Result<()> {
const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024; // 10MB limit
// Get symlink metadata without following the symlink
let symlink_metadata = path.symlink_metadata().map_err(|e| {
anyhow::anyhow!(
"Failed to get symlink metadata for {}: {}",
path.display(),
e
)
})?;
// Explicitly check for symlinks first
if symlink_metadata.file_type().is_symlink() {
return Err(anyhow::anyhow!(
"Symlinks are not allowed: {}",
path.display()
));
}
// Only check size if it's a regular file
if symlink_metadata.file_type().is_file()
&& symlink_metadata.len() > MAX_FILE_SIZE
{
return Err(anyhow::anyhow!(
"File exceeds maximum allowed size of {} bytes: {}",
MAX_FILE_SIZE,
path.display()
));
}
Ok(())
}
/// Creates and initialises a log file for the static site generator.
///
/// Establishes a new log file at the specified path with appropriate permissions
/// and write capabilities. The log file is used to track the generation process
/// and any errors that occur.
///
/// # Arguments
///
/// * `file_path` - The desired location for the log file
///
/// # Returns
///
/// * `Ok(File)` - A file handle for the created log file
/// * `Err` - If the file cannot be created or permissions are insufficient
///
/// # Examples
///
/// ```rust
/// use ssg::create_log_file;
///
/// fn main() -> anyhow::Result<()> {
/// let log_file = create_log_file("./site_generation.log")?;
/// println!("Log file created successfully");
/// Ok(())
/// }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// * The specified path is invalid
/// * File creation permissions are insufficient
/// * The parent directory is not writable
pub fn create_log_file(file_path: &str) -> Result<File> {
File::create(file_path).context("Failed to create log file")
}
/// Records system initialisation in the logging system.
///
/// Creates a detailed log entry capturing the system's startup state,
/// including configuration and initial conditions. Uses the Common Log Format (CLF)
/// for consistent logging.
///
/// # Arguments
///
/// * `log_file` - Active file handle for writing log entries
/// * `date` - Current date and time for log timestamps
///
/// # Returns
///
/// * `Ok(())` - If the log entry is written successfully
/// * `Err` - If writing fails or translation errors occur
///
/// # Examples
///
/// ```rust
/// use ssg::{create_log_file, log_initialization};
/// use dtt::datetime::DateTime;
///
/// fn main() -> anyhow::Result<()> {
/// let mut log_file = create_log_file("./site.log")?;
/// let date = DateTime::new();
///
/// log_initialization(&mut log_file, &date)?;
/// println!("System initialisation logged");
/// Ok(())
/// }
/// ```
pub fn log_initialization(
log_file: &mut File,
date: &DateTime,
) -> Result<()> {
let banner_log = macro_log!(
&generate_unique_string(),
&date.to_string(),
&LogLevel::INFO,
"process",
&translate("lib_banner_log_msg", "default message")
.unwrap_or_else(|_| {
"Default banner log message".to_string()
}),
&LogFormat::CLF
);
writeln!(log_file, "{}", banner_log)
.context("Failed to write banner log")
}
/// Logs processed command-line arguments for debugging and auditing.
///
/// Records all provided command-line arguments and their values in the log file,
/// providing a traceable record of site generation parameters.
///
/// # Arguments
///
/// * `log_file` - Active file handle for writing log entries
/// * `date` - Current date and time for log timestamps
///
/// # Returns
///
/// * `Ok(())` - If arguments are logged successfully
/// * `Err` - If writing fails or translation errors occur
///
/// # Examples
///
/// ```rust
/// use ssg::{create_log_file, log_arguments};
/// use dtt::datetime::DateTime;
///
/// fn main() -> anyhow::Result<()> {
/// let mut log_file = create_log_file("./site.log")?;
/// let date = DateTime::new();
///
/// log_arguments(&mut log_file, &date)?;
/// println!("Arguments logged successfully");
/// Ok(())
/// }
/// ```
pub fn log_arguments(
log_file: &mut File,
date: &DateTime,
) -> Result<()> {
let args_log = macro_log!(
&generate_unique_string(),
&date.to_string(),
&LogLevel::INFO,
"process",
&translate("lib_banner_log_msg", "default message")
.unwrap_or_else(|_| {
"Default banner log message".to_string()
}),
&LogFormat::CLF
);
writeln!(log_file, "{}", args_log)
.context("Failed to write arguments log")
}
/// Creates and verifies required directories for site generation.
///
/// Ensures all necessary directories exist and are safe to use, creating
/// them if necessary. Also performs security checks on each directory.
///
/// # Arguments
///
/// * `paths` - Reference to a Paths struct containing required directory paths
///
/// # Returns
///
/// * `Ok(())` - If all directories are created/verified successfully
/// * `Err` - If any directory operation fails
///
/// # Examples
///
/// ```rust
/// use std::path::PathBuf;
/// use ssg::{Paths, create_directories};
///
/// fn main() -> anyhow::Result<()> {
/// let paths = Paths {
/// site: PathBuf::from("public"),
/// content: PathBuf::from("content"),
/// build: PathBuf::from("build"),
/// template: PathBuf::from("templates"),
/// };
///
/// create_directories(&paths)?;
/// println!("All directories ready");
/// Ok(())
/// }
/// ```
///
/// # Security
///
/// Performs the following security checks:
/// * Path traversal prevention
/// * Permission validation
/// * Safe path verification
pub fn create_directories(paths: &Paths) -> Result<()> {
// Ensure each directory exists, with custom error messages for each.
fs::create_dir_all(&paths.content)
.with_context(|| format!("Failed to create or access content directory at path: {:?}", &paths.content))?;
fs::create_dir_all(&paths.build).with_context(|| {
format!(
"Failed to create or access build directory at path: {:?}",
&paths.build
)
})?;
fs::create_dir_all(&paths.site).with_context(|| {
format!(
"Failed to create or access site directory at path: {:?}",
&paths.site
)
})?;
fs::create_dir_all(&paths.template)
.with_context(|| format!("Failed to create or access template directory at path: {:?}", &paths.template))?;
// Path safety check with additional context
if !is_safe_path(&paths.content)?
|| !is_safe_path(&paths.build)?
|| !is_safe_path(&paths.site)?
|| !is_safe_path(&paths.template)?
{
anyhow::bail!("One or more paths are unsafe. Ensure paths do not contain '..' and are accessible.");
}
// Optional directory listing with error context
list_directory_contents(&paths.content)
.with_context(|| format!("Failed to list contents of content directory at path: {:?}", &paths.content))?;
Ok(())
}
/// Configures and launches the development server.
///
/// Sets up a local server for testing and previewing the generated site.
/// Handles file copying and server configuration for local development.
///
/// # Arguments
///
/// * `log_file` - Reference to the active log file
/// * `date` - Current timestamp for logging
/// * `paths` - All required directory paths
/// * `serve_dir` - Directory to serve content from
///
/// # Returns
///
/// * `Ok(())` - If server starts successfully
/// * `Err` - If server configuration or startup fails
///
/// # Examples
///
/// ```rust,no_run
/// use std::path::PathBuf;
/// use ssg::{Paths, handle_server, create_log_file};
/// use dtt::datetime::DateTime;
///
/// #[tokio::main]
/// async fn main() -> anyhow::Result<()> {
/// let mut log_file = create_log_file("./server.log")?;
/// let date = DateTime::new();
/// let paths = Paths {
/// site: PathBuf::from("public"),
/// content: PathBuf::from("content"),
/// build: PathBuf::from("build"),
/// template: PathBuf::from("templates"),
/// };
/// let serve_dir = PathBuf::from("serve");
///
/// handle_server(&mut log_file, &date, &paths, &serve_dir).await?;
/// Ok(())
/// }
/// ```
///
/// # Server Configuration
///
/// * Default port: 8000
/// * Host: 127.0.0.1 (localhost)
/// * Serves static files from the specified directory
pub async fn handle_server(
log_file: &mut File,
date: &DateTime,
paths: &Paths,
serve_dir: &PathBuf,
) -> Result<()> {
// Log server initialization
let server_log = macro_log!(
&generate_unique_string(),
&date.to_string(),
&LogLevel::INFO,
"process",
&translate("lib_server_log_msg", "default server message")
.unwrap_or("Default server message".to_string()),
&LogFormat::CLF
);
writeln!(log_file, "{}", server_log)?;
fs::create_dir_all(serve_dir)
.context("Failed to create serve directory")?;
println!("Setting up server...");
println!("Source: {}", paths.site.display());
println!("Serving from: {}", serve_dir.display());
if serve_dir != &paths.site {
verify_and_copy_files_async(&paths.site, serve_dir).await?;
}
println!("\nStarting server at http://127.0.0.1:8000");
println!("Serving content from: {}", serve_dir.display());
warp::serve(warp::fs::dir(serve_dir.clone()))
.run(([127, 0, 0, 1], 8000))
.await;
Ok(())
}
/// Recursively collects all file paths within a directory.
///
/// Traverses a directory tree and compiles a list of all file paths found,
/// excluding directories themselves.
///
/// # Arguments
///
/// * `dir` - Reference to the directory to search
/// * `files` - Mutable vector to store found file paths
///
/// # Returns
///
/// * `Ok(())` - If the collection process succeeds
/// * `Err` - If any file system operation fails
///
/// # Examples
///
/// ```rust
/// use std::path::{Path, PathBuf};
/// use ssg::collect_files_recursive;
///
/// fn main() -> anyhow::Result<()> {
/// let mut files = Vec::new();
/// let dir_path = Path::new("./examples/content");
///
/// collect_files_recursive(dir_path, &mut files)?;
///
/// for file in files {
/// println!("Found file: {}", file.display());
/// }
///
/// Ok(())
/// }
/// ```
///
/// # Note
///
/// This function:
/// * Only collects file paths, not directory paths
/// * Follows symbolic links (use with caution)
/// * Maintains original path structure
pub fn collect_files_recursive(
dir: &Path,
files: &mut Vec<PathBuf>,
) -> Result<()> {
for entry in fs::read_dir(dir)? {
let entry = entry;
let path = entry?.path();
if path.is_dir() {
collect_files_recursive(&path, files)?;
} else {
files.push(path);
}
}
Ok(())
}
/// Recursively copies a directory whilst maintaining structure and attributes.
///
/// Performs a deep copy of a directory tree, preserving file attributes and
/// handling nested directories. Uses parallel processing for improved performance.
///
/// # Arguments
///
/// * `src` - Source directory path
/// * `dst` - Destination directory path
///
/// # Returns
///
/// * `Ok(())` - If the copy operation succeeds
/// * `Err` - If any part of the copy operation fails
///
/// # Performance
///
/// Uses rayon for parallel processing of files, significantly improving
/// performance for directories with many files.
///
/// # Safety
///
/// * Verifies file safety before copying
/// * Maintains original file permissions
/// * Handles circular references
pub fn copy_dir_all(src: &Path, dst: &Path) -> Result<()> {
fs::create_dir_all(dst)?;
let entries: Vec<_> =
fs::read_dir(src)?.collect::<std::io::Result<Vec<_>>>()?;
entries
.into_par_iter()
.try_for_each(|entry| -> Result<()> {
let src_path = entry.path();
let dst_path = dst.join(entry.file_name());
if src_path.is_dir() {
copy_dir_all(&src_path, &dst_path)?;
} else {
verify_file_safety(&src_path)?;
_ = fs::copy(&src_path, &dst_path)?;
}
Ok(())
})?;
Ok(())
}
/// Asynchronously copies an entire directory structure, preserving file attributes and handling nested directories.
///
/// # Parameters
///
/// * `src`: A reference to the source directory path.
/// * `dst`: A reference to the destination directory path.
///
/// # Returns
///
/// * `Result<()>`:
/// - `Ok(())`: If the directory copying is successful.
/// - `Err(e)`: If an error occurs during the directory copying, where `e` is the associated error.
///
/// # Errors
///
/// This function can return the following errors:
///
/// * `std::io::Error`: If an error occurs during directory creation, file copying, or permission issues.
/// * `anyhow::Error`: If a file safety check fails.
#[cfg(feature = "async")]
pub async fn copy_dir_all_async(src: &Path, dst: &Path) -> Result<()> {
internal_copy_dir_async(src, dst).await
}
#[cfg(feature = "async")]
async fn internal_copy_dir_async(src: &Path, dst: &Path) -> Result<()> {
tokio::fs::create_dir_all(dst).await?;
let mut stack = vec![(src.to_path_buf(), dst.to_path_buf())];
while let Some((src_path, dst_path)) = stack.pop() {
let mut entries = tokio::fs::read_dir(&src_path).await?;
while let Some(entry) = entries.next_entry().await? {
let src_entry = entry.path();
let dst_entry = dst_path.join(entry.file_name());
if src_entry.is_dir() {
tokio::fs::create_dir_all(&dst_entry).await?;
stack.push((src_entry, dst_entry));
} else {
verify_file_safety(&src_entry)?;
_ = tokio::fs::copy(&src_entry, &dst_entry).await?;
}
}
}
Ok(())
}
/// Creates a recursive directory listing.
///
/// Generates a complete listing of directory contents
/// for verification and debugging purposes.
///
/// # Arguments
///
/// * `dir` - Directory to list recursively
///
/// # Errors
///
/// Returns an error if:
/// * Directory access fails
/// * Permission issues occur
/// * Resource limits are exceeded
fn list_directory_contents(dir: &Path) -> Result<()> {
let entries: Vec<_> =
fs::read_dir(dir)?.collect::<std::io::Result<Vec<_>>>()?;
entries.par_iter().try_for_each(|entry| -> Result<()> {
let path = entry.path();
if path.is_dir() {
list_directory_contents(&path)?;
}
Ok(())
})?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cmd::Cli;
use anyhow::Result;
use std::env;
use std::{
fs::{self, File},
path::PathBuf,
};
use tempfile::{tempdir, TempDir};
#[test]
fn test_create_log_file_success() -> Result<()> {
let temp_dir = tempdir()?;
let log_file_path = temp_dir.path().join("test.log");
let log_file =
create_log_file(log_file_path.to_str().unwrap())?;
assert!(log_file.metadata()?.is_file());
Ok(())
}
#[test]
fn test_log_arguments() -> Result<()> {
let temp_dir = tempdir()?;
let log_file_path = temp_dir.path().join("args_log.log");
let mut log_file = File::create(&log_file_path)?;
let date = DateTime::new();
log_arguments(&mut log_file, &date)?;
let log_content = fs::read_to_string(log_file_path)?;
assert!(log_content.contains("process"));
Ok(())
}
#[test]
fn test_create_directories_success() -> Result<()> {
let temp_dir = tempdir()?;
let base_path = temp_dir.path().to_path_buf();
let paths = Paths {
site: base_path.join("public"),
content: base_path.join("content"),
build: base_path.join("build"),
template: base_path.join("templates"),
};
create_directories(&paths)?;
// Verify each directory exists
assert!(paths.site.exists());
assert!(paths.content.exists());
assert!(paths.build.exists());
assert!(paths.template.exists());
Ok(())
}
#[test]
fn test_create_directories_failure() {
let invalid_paths = Paths {
site: PathBuf::from("/invalid/site"),
content: PathBuf::from("/invalid/content"),
build: PathBuf::from("/invalid/build"),
template: PathBuf::from("/invalid/template"),
};
let result = create_directories(&invalid_paths);
assert!(result.is_err());
}
#[test]
fn test_copy_dir_all() -> Result<()> {
let src_dir = tempdir()?;
let dst_dir = tempdir()?;
let src_file = src_dir.path().join("test_file.txt");
_ = File::create(&src_file)?;
let result = copy_dir_all(src_dir.path(), dst_dir.path());
assert!(result.is_ok());
assert!(dst_dir.path().join("test_file.txt").exists());
Ok(())
}
#[test]
fn test_verify_and_copy_files_success() -> Result<()> {
let temp_dir = tempdir()?;
let base_path = temp_dir.path().to_path_buf();
// Create source directory and test file
let src_dir = base_path.join("src");
fs::create_dir_all(&src_dir)?;
let test_file = src_dir.join("test_file.txt");
fs::write(&test_file, "test content")?;
// Create destination directory
let dst_dir = base_path.join("dst");
// Verify and copy files
verify_and_copy_files(&src_dir, &dst_dir)?;
// Verify the file was copied
assert!(dst_dir.join("test_file.txt").exists());
Ok(())
}
#[test]
fn test_verify_and_copy_files_failure() {
let src_dir = PathBuf::from("/invalid/src");
let dst_dir = PathBuf::from("/invalid/dst");
let result = verify_and_copy_files(&src_dir, &dst_dir);
assert!(result.is_err());
}
#[tokio::test]
async fn test_handle_server_failure() {
let temp_dir = tempdir().unwrap();
let log_file_path = temp_dir.path().join("server_log.log");
let mut log_file = File::create(&log_file_path).unwrap();
let paths = Paths {
site: PathBuf::from("/invalid/site"),
content: PathBuf::from("/invalid/content"),
build: PathBuf::from("/invalid/build"),
template: PathBuf::from("/invalid/template"),
};
let serve_dir = temp_dir.path().join("serve");
let date = DateTime::new();
let result =
handle_server(&mut log_file, &date, &paths, &serve_dir);
assert!(result.await.is_err());
}
#[test]
fn test_list_directory_contents() -> Result<()> {
let temp_dir = tempdir()?;
let sub_dir = temp_dir.path().join("subdir");
fs::create_dir(&sub_dir)?;
let temp_file = sub_dir.join("test_file.txt");
_ = File::create(&temp_file)?;
let result = list_directory_contents(temp_dir.path());
assert!(result.is_ok());
Ok(())
}
#[test]
fn test_is_safe_path_safe() -> Result<()> {
let temp_dir = tempdir()?;
let safe_path = temp_dir.path().to_path_buf().join("safe_path");
// Create the directory
fs::create_dir_all(&safe_path)?;
// Use the absolute path
let absolute_safe_path = safe_path.canonicalize()?;
assert!(is_safe_path(&absolute_safe_path)?);
Ok(())
}
#[test]
fn test_create_directories_partial_failure() {
let temp_dir = tempdir().unwrap();
let valid_path = temp_dir.path().join("valid_dir");
let invalid_path = PathBuf::from("/invalid/path");
let paths = Paths {
site: valid_path,
content: invalid_path.clone(),
build: temp_dir.path().join("build"),
template: temp_dir.path().join("template"),
};
let result = create_directories(&paths);
assert!(result.is_err());
}
#[test]
fn test_copy_dir_all_nested() -> Result<()> {
let src_dir = tempdir()?;
let dst_dir = tempdir()?;
let nested_dir = src_dir.path().join("nested_dir");
fs::create_dir(&nested_dir)?;
let nested_file = nested_dir.join("nested_file.txt");
_ = File::create(&nested_file)?;
copy_dir_all(src_dir.path(), dst_dir.path())?;
assert!(dst_dir
.path()
.join("nested_dir/nested_file.txt")
.exists());
Ok(())
}
#[test]
fn test_verify_and_copy_files_missing_source() {
let src_path = PathBuf::from("/non_existent_dir");
let dst_dir = tempdir().unwrap();
let result = verify_and_copy_files(&src_path, dst_dir.path());
assert!(result.is_err());
}
#[tokio::test]
async fn test_handle_server_missing_serve_dir() {
let temp_dir = tempdir().unwrap();
let log_file_path = temp_dir.path().join("server_log.log");
let mut log_file = File::create(&log_file_path).unwrap();
let paths = Paths {
site: temp_dir.path().join("site"),
content: temp_dir.path().join("content"),
build: temp_dir.path().join("build"),
template: temp_dir.path().join("template"),
};
let non_existent_serve_dir =
PathBuf::from("/non_existent_serve_dir");
let binding = DateTime::new();
let result = handle_server(
&mut log_file,
&binding,
&paths,
&non_existent_serve_dir,
);
assert!(result.await.is_err());
}
#[test]
fn test_collect_files_recursive_empty() -> Result<()> {
let temp_dir = tempdir()?;
let mut files = Vec::new();
collect_files_recursive(temp_dir.path(), &mut files)?;
assert!(files.is_empty());
Ok(())
}
#[test]
fn test_print_banner() {
// Simply call the function to ensure it runs without errors.
Cli::print_banner();
}
#[test]
fn test_collect_files_recursive_with_nested_directories(
) -> Result<()> {
let temp_dir = tempdir()?;
let nested_dir = temp_dir.path().join("nested_dir");
fs::create_dir(&nested_dir)?;
let nested_file = nested_dir.join("nested_file.txt");
_ = File::create(&nested_file)?;
let mut files = Vec::new();
collect_files_recursive(temp_dir.path(), &mut files)?;
assert!(files.contains(&nested_file));
assert_eq!(files.len(), 1);
Ok(())
}
#[tokio::test]
async fn test_handle_server_start_message() -> Result<()> {
let temp_dir = tempdir()?;
let log_file_path = temp_dir.path().join("server_log.log");
let mut log_file = File::create(&log_file_path)?;
let paths = Paths {
site: temp_dir.path().join("site"),
content: temp_dir.path().join("content"),
build: temp_dir.path().join("build"),
template: temp_dir.path().join("template"),
};
let serve_dir = temp_dir.path().join("serve");
// Check setup conditions before calling `handle_server`
fs::create_dir_all(&serve_dir)?;
assert!(
serve_dir.exists(),
"Expected serve directory to be created"
);
// Now, call `handle_server` and check for specific output or error
let date = DateTime::new();
let result =
handle_server(&mut log_file, &date, &paths, &serve_dir);
assert!(
result.await.is_err(),
"Expected handle_server to fail without valid setup"
);
Ok(())
}
#[cfg(any(unix, windows))]
#[test]
fn test_verify_file_safety_symlink() -> Result<()> {
let temp_dir = tempdir()?;
let file_path = temp_dir.path().join("test.txt");
let symlink_path = temp_dir.path().join("test_link.txt");
// Create a regular file
fs::write(&file_path, "test content")?;
// Create a symlink
#[cfg(unix)]
std::os::unix::fs::symlink(&file_path, &symlink_path)?;
#[cfg(windows)]
std::os::windows::fs::symlink_file(&file_path, &symlink_path)?;
// Debug output
println!("File exists: {}", file_path.exists());
println!("Symlink exists: {}", symlink_path.exists());
println!(
"Is symlink: {}",
symlink_path.symlink_metadata()?.file_type().is_symlink()
);
// Try to verify the symlink
let result = verify_file_safety(&symlink_path);
// Print the result for debugging
println!("Result: {:?}", result);
// Verify that we got an error
assert!(
result.is_err(),
"Expected error for symlink, got success"
);
// Verify the error message
let err = result.unwrap_err();
println!("Error message: {}", err);
assert!(
err.to_string().contains("Symlinks are not allowed"),
"Unexpected error message: {}",
err
);
Ok(())
}
#[test]
fn test_verify_file_safety_size() -> Result<()> {
let temp_dir = tempdir()?;
let large_file_path = temp_dir.path().join("large.txt");
// Create a large file
let file = File::create(&large_file_path)?;
file.set_len(11 * 1024 * 1024)?; // 11MB
let result = verify_file_safety(&large_file_path);
assert!(result.is_err(), "Expected error, got: {:?}", result);
Ok(())
}
#[test]
fn test_verify_file_safety_regular() -> Result<()> {
let temp_dir = tempdir()?;
let file_path = temp_dir.path().join("regular.txt");
// Create a regular file
fs::write(&file_path, "test content")?;
assert!(verify_file_safety(&file_path).is_ok());
Ok(())
}
/// Tests successful copying of an empty directory
#[tokio::test]
async fn test_copy_empty_directory_async() -> Result<()> {
let src_dir = tempdir()?;
let dst_dir = tempdir()?;
let result =
copy_dir_all_async(src_dir.path(), dst_dir.path()).await;
assert!(result.is_ok());
// Verify destination directory exists
assert!(dst_dir.path().exists());
Ok(())
}
/// Tests copying a directory with a single file
#[tokio::test]
async fn test_copy_single_file_async() -> Result<()> {
let src_dir = tempdir()?;
let dst_dir = tempdir()?;
// Create a test file
let test_file = src_dir.path().join("test.txt");
fs::write(&test_file, "test content")?;
copy_dir_all_async(src_dir.path(), dst_dir.path()).await?;
// Verify file was copied
let copied_file = dst_dir.path().join("test.txt");
assert!(copied_file.exists());
assert_eq!(fs::read_to_string(copied_file)?, "test content");
Ok(())
}
/// Tests copying a directory with nested subdirectories
#[tokio::test]
async fn test_copy_nested_directories_async() -> Result<()> {
let src_dir = tempdir()?;
let dst_dir = tempdir()?;
// Create nested directory structure
let nested_dir = src_dir.path().join("nested");
fs::create_dir(&nested_dir)?;
// Create files in both root and nested directory
fs::write(src_dir.path().join("root.txt"), "root content")?;
fs::write(nested_dir.join("nested.txt"), "nested content")?;
copy_dir_all_async(src_dir.path(), dst_dir.path()).await?;
// Verify directory structure and contents
assert!(dst_dir.path().join("nested").exists());
assert!(dst_dir.path().join("root.txt").exists());
assert!(dst_dir.path().join("nested/nested.txt").exists());
assert_eq!(
fs::read_to_string(dst_dir.path().join("root.txt"))?,
"root content"
);
assert_eq!(
fs::read_to_string(
dst_dir.path().join("nested/nested.txt")
)?,
"nested content"
);
Ok(())
}
/// Tests handling of symlinks
#[tokio::test]
async fn test_copy_with_symlink_async() -> Result<()> {
let src_dir = tempdir()?;
let dst_dir = tempdir()?;
// Create a regular file
let file_path = src_dir.path().join("original.txt");
fs::write(&file_path, "original content")?;
// Create a symlink
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
let symlink_path = src_dir.path().join("link.txt");
symlink(&file_path, &symlink_path)?;
}
#[cfg(windows)]
{
use std::os::windows::fs::symlink_file;
let symlink_path = src_dir.path().join("link.txt");
symlink_file(&file_path, &symlink_path)?;
}
// Attempt to copy - should fail due to symlink
let result =
copy_dir_all_async(src_dir.path(), dst_dir.path()).await;
assert!(result.is_err());
Ok(())
}
/// Tests copying large files
#[tokio::test]
async fn test_copy_large_file_async() -> Result<()> {
let src_dir = tempdir()?;
let dst_dir = tempdir()?;
// Create a large file (11MB)
let large_file = src_dir.path().join("large.txt");
let file = fs::File::create(&large_file)?;
file.set_len(11 * 1024 * 1024)?;
// Attempt to copy - should fail due to file size limit
let result =
copy_dir_all_async(src_dir.path(), dst_dir.path()).await;
assert!(result.is_err());
Ok(())
}
/// Tests copying with invalid destination
#[tokio::test]
async fn test_copy_invalid_destination_async() -> Result<()> {
let src_dir = tempdir()?;
let invalid_dst = PathBuf::from("/nonexistent/path");
let result =
copy_dir_all_async(src_dir.path(), &invalid_dst).await;
assert!(result.is_err());
Ok(())
}
/// Tests concurrent copying of multiple files
#[tokio::test]
async fn test_concurrent_copy_async() -> Result<()> {
let src_dir = tempdir()?;
let dst_dir = tempdir()?;
// Create multiple files
for i in 0..5 {
fs::write(
src_dir.path().join(format!("file{}.txt", i)),
format!("content {}", i),
)?;
}
copy_dir_all_async(src_dir.path(), dst_dir.path()).await?;
// Verify all files were copied
for i in 0..5 {
let copied_file =
dst_dir.path().join(format!("file{}.txt", i));
assert!(copied_file.exists());
assert_eq!(
fs::read_to_string(copied_file)?,
format!("content {}", i)
);
}
Ok(())
}
/// Tests copying with maximum directory depth
#[tokio::test]
async fn test_max_directory_depth_async() -> Result<()> {
let src_dir = tempdir()?;
let dst_dir = tempdir()?;
let max_depth = 5;
// Create deeply nested directory structure
let mut current_dir = src_dir.path().to_path_buf();
for i in 0..max_depth {
current_dir = current_dir.join(format!("level{}", i));
fs::create_dir(¤t_dir)?;
fs::write(
current_dir.join("file.txt"),
format!("content level {}", i),
)?;
}
copy_dir_all_async(src_dir.path(), dst_dir.path()).await?;
// Verify the entire structure was copied
current_dir = dst_dir.path().to_path_buf();
for i in 0..max_depth {
current_dir = current_dir.join(format!("level{}", i));
assert!(current_dir.exists());
assert!(current_dir.join("file.txt").exists());
assert_eq!(
fs::read_to_string(current_dir.join("file.txt"))?,
format!("content level {}", i)
);
}
Ok(())
}
#[tokio::test]
async fn test_verify_and_copy_files_async_missing_source(
) -> Result<()> {
let temp_dir = tempdir()?;
let src_dir = temp_dir.path().join("nonexistent");
let dst_dir = temp_dir.path().join("dst");
let error = verify_and_copy_files_async(&src_dir, &dst_dir)
.await
.unwrap_err()
.to_string();
assert!(
error.contains("does not exist"),
"Expected error message about non-existent source, got: {}",
error
);
Ok(())
}
#[test]
fn test_paths_builder_default() -> Result<()> {
let paths = Paths::builder().build()?;
assert_eq!(paths.site, PathBuf::from("public"));
assert_eq!(paths.content, PathBuf::from("content"));
assert_eq!(paths.build, PathBuf::from("build"));
assert_eq!(paths.template, PathBuf::from("templates"));
Ok(())
}
#[test]
fn test_paths_builder_custom() -> Result<()> {
let temp_dir = tempdir()?;
let paths = Paths::builder()
.site(temp_dir.path().join("custom_public"))
.content(temp_dir.path().join("custom_content"))
.build_dir(temp_dir.path().join("custom_build"))
.template(temp_dir.path().join("custom_templates"))
.build()?;
assert_eq!(paths.site, temp_dir.path().join("custom_public"));
assert_eq!(
paths.content,
temp_dir.path().join("custom_content")
);
assert_eq!(paths.build, temp_dir.path().join("custom_build"));
assert_eq!(
paths.template,
temp_dir.path().join("custom_templates")
);
Ok(())
}
#[test]
fn test_paths_builder_relative() -> Result<()> {
let temp_dir = tempdir()?;
// Create the directories first
fs::create_dir_all(temp_dir.path().join("public"))?;
fs::create_dir_all(temp_dir.path().join("content"))?;
fs::create_dir_all(temp_dir.path().join("build"))?;
fs::create_dir_all(temp_dir.path().join("templates"))?;
let paths =
Paths::builder().relative_to(temp_dir.path()).build()?;
assert_eq!(paths.site, temp_dir.path().join("public"));
assert_eq!(paths.content, temp_dir.path().join("content"));
assert_eq!(paths.build, temp_dir.path().join("build"));
assert_eq!(paths.template, temp_dir.path().join("templates"));
Ok(())
}
#[test]
fn test_paths_validation() -> Result<()> {
// Test directory traversal
let result = Paths::builder().site("../invalid").build();
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("directory traversal"),
"Expected error about directory traversal"
);
// Test double slashes
let result = Paths::builder().site("invalid//path").build();
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("invalid double slashes"),
"Expected error about invalid double slashes"
);
// Test symlinks if possible
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
let temp_dir = tempdir()?;
let real_path = temp_dir.path().join("real");
let symlink_path = temp_dir.path().join("symlink");
fs::create_dir(&real_path)?;
symlink(&real_path, &symlink_path)?;
let result = Paths::builder().site(symlink_path).build();
assert!(result.is_err());
assert!(
result.unwrap_err().to_string().contains("symlink"),
"Expected error about symlinks"
);
}
Ok(())
}
#[test]
fn test_paths_default_paths() {
let paths = Paths::default_paths();
assert_eq!(paths.site, PathBuf::from("public"));
assert_eq!(paths.content, PathBuf::from("content"));
assert_eq!(paths.build, PathBuf::from("build"));
assert_eq!(paths.template, PathBuf::from("templates"));
}
// Add a new test for non-existent but valid paths
#[test]
fn test_paths_nonexistent_valid() -> Result<()> {
let temp_dir = tempdir()?;
let valid_path = temp_dir.path().join("new_directory");
let paths =
Paths::builder().site(valid_path.clone()).build()?;
assert_eq!(paths.site, valid_path);
Ok(())
}
#[test]
fn test_initialize_logging_with_custom_level() -> Result<()> {
env::set_var(ENV_LOG_LEVEL, "debug");
assert!(initialize_logging().is_ok());
env::remove_var(ENV_LOG_LEVEL);
Ok(())
}
#[test]
fn test_paths_builder_with_all_invalid_paths() -> Result<()> {
let result = Paths::builder()
.site("../invalid")
.content("content//invalid")
.build_dir("build/../invalid")
.template("template//invalid")
.build();
assert!(result.is_err());
Ok(())
}
#[test]
fn test_paths_builder_clone() {
let builder = PathsBuilder::default();
let cloned = builder.clone();
assert!(cloned.site.is_none());
assert!(cloned.content.is_none());
assert!(cloned.build.is_none());
assert!(cloned.template.is_none());
}
#[test]
fn test_paths_clone() -> Result<()> {
let paths = Paths::default_paths();
let cloned = paths.clone();
assert_eq!(paths.site, cloned.site);
assert_eq!(paths.content, cloned.content);
assert_eq!(paths.build, cloned.build);
assert_eq!(paths.template, cloned.template);
Ok(())
}
#[tokio::test]
async fn test_async_copy_with_empty_source() -> Result<()> {
let temp_dir = tempdir()?;
let src_dir = temp_dir.path().join("empty_src");
let dst_dir = temp_dir.path().join("empty_dst");
fs::create_dir(&src_dir)?;
let result =
verify_and_copy_files_async(&src_dir, &dst_dir).await;
assert!(result.is_ok());
assert!(dst_dir.exists());
Ok(())
}
#[test]
fn test_paths_validation_all_aspects() -> Result<()> {
let temp_dir = tempdir()?;
// Test with absolute paths
let result = Paths::builder()
.site(temp_dir.path().join("site"))
.content(temp_dir.path().join("content"))
.build_dir(temp_dir.path().join("build"))
.template(temp_dir.path().join("template"))
.build();
assert!(result.is_ok());
// Test with multiple validation issues
let result = Paths::builder()
.site("../site")
.content("content//test")
.build_dir("build/../../test")
.template("template//test")
.build();
assert!(result.is_err());
Ok(())
}
#[test]
fn test_log_initialization_with_empty_log_file() -> Result<()> {
let temp_dir = tempdir()?;
let log_path = temp_dir.path().join("empty.log");
let mut log_file = File::create(&log_path)?;
let date = DateTime::new();
log_initialization(&mut log_file, &date)?;
let content = fs::read_to_string(&log_path)?;
assert!(!content.is_empty());
assert!(content.contains("process"));
Ok(())
}
#[tokio::test]
async fn test_verify_and_copy_files_async_with_nested_empty_dirs(
) -> Result<()> {
let temp_dir = tempdir()?;
let src_dir = temp_dir.path().join("src");
let dst_dir = temp_dir.path().join("dst");
// Create nested empty directory structure
fs::create_dir_all(src_dir.join("a/b/c"))?;
fs::create_dir_all(src_dir.join("d/e/f"))?;
verify_and_copy_files_async(&src_dir, &dst_dir).await?;
assert!(dst_dir.join("a/b/c").exists());
assert!(dst_dir.join("d/e/f").exists());
Ok(())
}
#[test]
fn test_validate_nonexistent_paths() -> Result<()> {
let paths = Paths {
site: PathBuf::from("nonexistent/site"),
content: PathBuf::from("nonexistent/content"),
build: PathBuf::from("nonexistent/build"),
template: PathBuf::from("nonexistent/template"),
};
// Non-existent paths should be valid if they don't contain unsafe patterns
assert!(paths.validate().is_ok());
Ok(())
}
#[test]
fn test_list_directory_contents_with_many_files() -> Result<()> {
let temp_dir = tempdir()?;
// Create multiple files and directories
for i in 0..5 {
fs::create_dir(temp_dir.path().join(format!("dir{}", i)))?;
for j in 0..5 {
fs::write(
temp_dir
.path()
.join(format!("dir{}/file{}.txt", i, j)),
"content",
)?;
}
}
list_directory_contents(temp_dir.path())?;
Ok(())
}
#[tokio::test]
async fn test_copy_dir_all_async_with_empty_dirs() -> Result<()> {
let temp_dir = tempdir()?;
let src_dir = temp_dir.path().join("src");
let dst_dir = temp_dir.path().join("dst");
fs::create_dir_all(src_dir.join("empty1"))?;
fs::create_dir_all(src_dir.join("empty2/empty3"))?;
copy_dir_all_async(&src_dir, &dst_dir).await?;
assert!(dst_dir.join("empty1").exists());
assert!(dst_dir.join("empty2/empty3").exists());
Ok(())
}
#[test]
fn test_log_level_from_env() {
// Save the current environment variable value
let original_value = env::var(ENV_LOG_LEVEL).ok();
// Helper function to get processed log level
fn get_processed_log_level() -> String {
let log_level = env::var(ENV_LOG_LEVEL)
.unwrap_or_else(|_| DEFAULT_LOG_LEVEL.to_string());
match log_level.to_lowercase().as_str() {
"error" => "error",
"warn" => "warn",
"info" => "info",
"debug" => "debug",
"trace" => "trace",
_ => "info", // Default to info for invalid values
}
.to_string()
}
// Test various log level settings
let test_levels = vec![
("DEBUG", "debug"),
("ERROR", "error"),
("WARN", "warn"),
("INFO", "info"),
("TRACE", "trace"),
("INVALID", "info"), // Should default to info
];
for (input, expected) in test_levels {
env::set_var(ENV_LOG_LEVEL, input);
let processed_level = get_processed_log_level();
assert_eq!(
processed_level, expected,
"Expected log level '{}' for input '{}', but got '{}'",
expected, input, processed_level
);
}
// Restore the original environment variable state
match original_value {
Some(value) => env::set_var(ENV_LOG_LEVEL, value),
None => env::remove_var(ENV_LOG_LEVEL),
}
}
/// Test for default log level when environment variable is not set
#[test]
fn test_default_log_level() {
// Save current environment variable value
let original_value = env::var(ENV_LOG_LEVEL).ok();
// Remove the environment variable to test default behavior
env::remove_var(ENV_LOG_LEVEL);
let log_level = env::var(ENV_LOG_LEVEL)
.unwrap_or_else(|_| DEFAULT_LOG_LEVEL.to_string())
.to_lowercase();
assert_eq!(log_level, DEFAULT_LOG_LEVEL.to_lowercase());
// Restore original environment variable state
if let Some(value) = original_value {
env::set_var(ENV_LOG_LEVEL, value);
}
}
/// Test the logic for translating string log levels to LevelFilter values
#[test]
fn test_log_level_translation() {
let test_cases = vec![
("error", LevelFilter::Error),
("warn", LevelFilter::Warn),
("info", LevelFilter::Info),
("debug", LevelFilter::Debug),
("trace", LevelFilter::Trace),
("invalid", LevelFilter::Info),
("", LevelFilter::Info),
];
for (input, expected) in test_cases {
let level = match input.to_lowercase().as_str() {
"error" => LevelFilter::Error,
"warn" => LevelFilter::Warn,
"info" => LevelFilter::Info,
"debug" => LevelFilter::Debug,
"trace" => LevelFilter::Trace,
_ => LevelFilter::Info,
};
assert_eq!(
level,
expected,
"Log level mismatch for input: '{}' - expected {:?}, got {:?}",
input,
expected,
level
);
}
}
/// Test environment variable handling with cleanup
#[test]
fn test_env_log_level_handling() {
// Save original state
let original_value = env::var(ENV_LOG_LEVEL).ok();
let test_cases = vec![
(Some("DEBUG"), "debug"),
(Some("ERROR"), "error"),
(Some("WARN"), "warn"),
(Some("INFO"), "info"),
(Some("TRACE"), "trace"),
(Some("INVALID"), "info"),
(None, "info"),
];
for (env_value, expected) in test_cases {
// Clear any existing env var
env::remove_var(ENV_LOG_LEVEL);
// Set new value if provided
if let Some(value) = env_value {
env::set_var(ENV_LOG_LEVEL, value);
}
let log_level = env::var(ENV_LOG_LEVEL)
.unwrap_or_else(|_| DEFAULT_LOG_LEVEL.to_string())
.to_lowercase();
let actual = match log_level.as_str() {
"error" => "error",
"warn" => "warn",
"info" => "info",
"debug" => "debug",
"trace" => "trace",
_ => "info",
};
assert_eq!(
actual, expected,
"Log level mismatch for env value: {:?}",
env_value
);
}
// Restore original state
match original_value {
Some(value) => env::set_var(ENV_LOG_LEVEL, value),
None => env::remove_var(ENV_LOG_LEVEL),
}
}
#[test]
fn test_initialize_logging_custom_levels() {
// Instead of actually initializing the logger, just verify the level parsing
for level in &["debug", "warn", "error", "trace"] {
env::set_var(ENV_LOG_LEVEL, level);
let log_level = env::var(ENV_LOG_LEVEL)
.unwrap_or_else(|_| DEFAULT_LOG_LEVEL.to_string());
assert_eq!(log_level, *level);
}
env::remove_var(ENV_LOG_LEVEL);
}
#[tokio::test]
async fn test_concurrent_operations() -> Result<()> {
use tokio::fs as async_fs;
let temp_dir = TempDir::new()?;
let src_dir = temp_dir.path().join("src");
let dst_dir = temp_dir.path().join("dst");
// Create source directory
async_fs::create_dir_all(&src_dir).await?;
// Create files concurrently
let mut handles = Vec::new();
for i in 0..100 {
let src = src_dir.clone();
handles.push(tokio::spawn(async move {
async_fs::write(
src.join(format!("file_{}.txt", i)),
format!("content {}", i),
)
.await
}));
}
// Wait for all files to be created
for handle in handles {
handle.await??;
}
// Ensure source files exist before copying
tokio::time::sleep(tokio::time::Duration::from_millis(100))
.await;
// Verify source files
let mut src_files = Vec::new();
collect_files_recursive(&src_dir, &mut src_files)?;
assert_eq!(
src_files.len(),
100,
"Source directory should have 100 files, found {}",
src_files.len()
);
// Create destination directory
async_fs::create_dir_all(&dst_dir).await?;
// Copy files using verify_and_copy_files instead of async version
verify_and_copy_files(&src_dir, &dst_dir)?;
// Allow some time for filesystem operations to complete
tokio::time::sleep(tokio::time::Duration::from_millis(100))
.await;
// Verify destination files
let mut dst_files = Vec::new();
collect_files_recursive(&dst_dir, &mut dst_files)?;
// Debug output
if dst_files.len() != 100 {
println!("Source directory contents:");
for file in &src_files {
println!(" {:?}", file);
}
println!("Destination directory contents:");
for file in &dst_files {
println!(" {:?}", file);
}
}
assert_eq!(
dst_files.len(),
100,
"Destination directory should have 100 files, found {}",
dst_files.len()
);
// Verify file contents
for i in 0..100 {
let dst_path = dst_dir.join(format!("file_{}.txt", i));
assert!(
dst_path.exists(),
"File {} does not exist in destination",
dst_path.display()
);
let content = fs::read_to_string(&dst_path)?;
assert_eq!(
content,
format!("content {}", i),
"Content mismatch for file {}",
i
);
}
Ok(())
}
#[test]
fn test_verify_and_copy_files_basic() -> Result<()> {
let temp_dir = TempDir::new()?;
let src_dir = temp_dir.path().join("src");
let dst_dir = temp_dir.path().join("dst");
fs::create_dir_all(&src_dir)?;
// Create a test file
fs::write(src_dir.join("test.txt"), "test content")?;
// Copy files
verify_and_copy_files(&src_dir, &dst_dir)?;
// Verify file was copied
assert!(dst_dir.join("test.txt").exists());
assert_eq!(
fs::read_to_string(dst_dir.join("test.txt"))?,
"test content"
);
Ok(())
}
#[test]
fn test_copy_dir_with_progress_empty_source() -> Result<()> {
let src_dir = tempdir()?;
let dst_dir = tempdir()?;
// Call the function with an empty source directory
copy_dir_with_progress(src_dir.path(), dst_dir.path())?;
// Verify that the destination directory exists and is empty
assert!(dst_dir.path().exists());
assert!(fs::read_dir(dst_dir.path())?.next().is_none());
Ok(())
}
#[test]
fn test_copy_dir_with_progress_source_does_not_exist() {
let src_dir = Path::new("/nonexistent");
let dst_dir = tempdir().unwrap();
let result = copy_dir_with_progress(src_dir, dst_dir.path());
assert!(result.is_err());
}
#[test]
fn test_copy_dir_with_progress_single_file() -> Result<()> {
let src_dir = tempdir()?;
let dst_dir = tempdir()?;
fs::write(src_dir.path().join("file1.txt"), "content")?;
copy_dir_with_progress(src_dir.path(), dst_dir.path())?;
let copied_file = dst_dir.path().join("file1.txt");
assert!(copied_file.exists());
assert_eq!(fs::read_to_string(copied_file)?, "content");
Ok(())
}
#[test]
fn test_copy_dir_with_progress_nested_directories() -> Result<()> {
let src_dir = tempdir()?;
let dst_dir = tempdir()?;
let nested_dir = src_dir.path().join("nested");
fs::create_dir(&nested_dir)?;
fs::write(nested_dir.join("file.txt"), "nested content")?;
copy_dir_with_progress(src_dir.path(), dst_dir.path())?;
let copied_nested_file = dst_dir.path().join("nested/file.txt");
assert!(copied_nested_file.exists());
assert_eq!(
fs::read_to_string(copied_nested_file)?,
"nested content"
);
Ok(())
}
#[test]
fn test_copy_dir_with_progress_destination_creation_failure() {
let src_dir = tempdir().unwrap();
let dst_dir = Path::new("/invalid_path");
let result = copy_dir_with_progress(src_dir.path(), dst_dir);
assert!(result.is_err());
}
}