mirror of
https://github.com/sharkdp/fd.git
synced 2026-09-01 04:28:07 +08:00
Compare commits
1138 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cdea7f5633 | |||
| fe0e455fee | |||
| a89e394a0d | |||
| 4f81778774 | |||
| 711ba7fe67 | |||
| c276ac79f4 | |||
| ee20f426dd | |||
| 0b10bf2665 | |||
| aaecbc0a58 | |||
| cb4069ec55 | |||
| 69a25907ab | |||
| 868c3a34e2 | |||
| ee195f4dd6 | |||
| 0f1f9676dc | |||
| 2bb2e2b954 | |||
| a62a59dafe | |||
| 7639bced74 | |||
| 51e44c0626 | |||
| 370174528f | |||
| 30fd75b22b | |||
| 5becb9d52c | |||
| fb0426fed1 | |||
| 41532d114e | |||
| 81efb5028c | |||
| ca51233d27 | |||
| 3381ab89d7 | |||
| 5095e95a95 | |||
| 5a093fdfd6 | |||
| acc64aab12 | |||
| eead1886cd | |||
| fed92120af | |||
| 1bfeea237a | |||
| 369a71a4c5 | |||
| cd755e284c | |||
| 372584e760 | |||
| 5a5852e15b | |||
| dda13cccf6 | |||
| aa41f342b5 | |||
| cffed27a2e | |||
| 6b5d1ac9d6 | |||
| 7d93f3adc7 | |||
| fb1486f210 | |||
| 0c9c101e21 | |||
| 8ff051e801 | |||
| daefe07614 | |||
| cade0b5e76 | |||
| c73e5e58a4 | |||
| f898e95db5 | |||
| b12606438e | |||
| 95dc6454d5 | |||
| 61c5399fa4 | |||
| 126be98699 | |||
| 77629639ff | |||
| 3ae9c9567e | |||
| 8965502e8a | |||
| 86c1e7d30d | |||
| 6aac84e4ae | |||
| a8a77d2162 | |||
| e8730e6ca3 | |||
| 3b3e328b5c | |||
| fccbe9b1ee | |||
| b5ae476fb1 | |||
| 094446004d | |||
| 1161471b7e | |||
| 25461e5ce1 | |||
| f7d4d717c2 | |||
| 21facf8832 | |||
| 8e80bbe721 | |||
| b25ca81375 | |||
| 5ac75050d1 | |||
| f72512ff43 | |||
| 75527dd9c6 | |||
| 86564cd00d | |||
| b955593ac6 | |||
| 1d4fa16433 | |||
| 42b2ab8a84 | |||
| febc1b692f | |||
| 8f1f55b9da | |||
| 2fbecc9bd8 | |||
| 8fdab04b7a | |||
| a2d6bea5ac | |||
| e3a065dfe1 | |||
| 66be8485bc | |||
| 7d18db23a7 | |||
| d491003759 | |||
| 4d88708d79 | |||
| 96a8dcd58b | |||
| f1dd935dea | |||
| 1cfac9ff7b | |||
| 425d7d9e6b | |||
| 8dfa67a245 | |||
| 9f938bea1e | |||
| e60582f838 | |||
| 9f12a3059c | |||
| cb2f37a46a | |||
| d642c446c9 | |||
| b77f9b811a | |||
| c96398c1bb | |||
| a00259bf79 | |||
| 9d536e1a40 | |||
| aeecb5d8c0 | |||
| 7f1b1471d5 | |||
| fe77ab4810 | |||
| a876e69751 | |||
| a58e1a2467 | |||
| 5776a05a24 | |||
| 8af8db28ed | |||
| 104d0ce4e5 | |||
| 825f308931 | |||
| 2250bb0ad1 | |||
| a7a67e4998 | |||
| 468c807049 | |||
| a86e16baa8 | |||
| 0a3a485bd7 | |||
| 4e2c81277a | |||
| 8f5a1675f5 | |||
| 82485bf18a | |||
| de422afd0b | |||
| 4f4900b197 | |||
| 0e74d5b75d | |||
| ed47664191 | |||
| 0fc795935d | |||
| c7f4f19ffb | |||
| 63a7d85d26 | |||
| d45c99b807 | |||
| 92c54d37c0 | |||
| 9ceba25bd9 | |||
| 90e73d72df | |||
| 749ea313f6 | |||
| 72ff3cf694 | |||
| a665a3bba9 | |||
| 078f5d184e | |||
| 607ae385f6 | |||
| 866ba9bfd5 | |||
| 2f6a2a88c5 | |||
| 5c4654acb6 | |||
| c327231e36 | |||
| 246f5b5e66 | |||
| 7cf8c85113 | |||
| fdb5534f66 | |||
| 1b66ab5d7a | |||
| 8a7ff7d438 | |||
| 45646e2eaf | |||
| 5008de5052 | |||
| d6b44b81b6 | |||
| 9d137d358d | |||
| 1d386abc84 | |||
| 0336452b96 | |||
| f8baea833f | |||
| dc9c503c7d | |||
| cd4fd03fa0 | |||
| fcd846651b | |||
| 6d77799759 | |||
| db7d448fd4 | |||
| 2278836060 | |||
| 37f3c2e6cb | |||
| 807aa11d03 | |||
| 647ced8ff0 | |||
| 26756f21fa | |||
| 24f7f2b9ef | |||
| d3a500af7a | |||
| 7027d45303 | |||
| bf6489a79b | |||
| 160d00f8fe | |||
| cb3fad48bb | |||
| a4d86cc1f5 | |||
| b691572928 | |||
| ec25d2bc81 | |||
| 4ea110d8dd | |||
| d766e76351 | |||
| aa35ef4e45 | |||
| b87d919244 | |||
| bb3d57c433 | |||
| ff1f66cceb | |||
| d9fc3272db | |||
| 247a5172e5 | |||
| c60d0076db | |||
| 801ccd7620 | |||
| a07ad51751 | |||
| 6067f72742 | |||
| 73e6f95416 | |||
| 40d8eb30bc | |||
| 38986aa42c | |||
| 171438be2d | |||
| fe0e173e9e | |||
| 9a9c4b921d | |||
| efd9f05fcb | |||
| ccafbbb08a | |||
| 74c389f847 | |||
| 2fc76da442 | |||
| b22a46c103 | |||
| 1586dabeee | |||
| 0a094a883f | |||
| 4410dda6e4 | |||
| bf81fb98fa | |||
| 9508153471 | |||
| 1a37650b2c | |||
| dcc5ff84cd | |||
| 9c9eeda209 | |||
| 4ba10c7837 | |||
| 2efd99bc52 | |||
| cd8fedc183 | |||
| f3a8bb7ce6 | |||
| 1df183e0cd | |||
| 1993c76971 | |||
| 5f95a78121 | |||
| 49ded38b8a | |||
| 9907632b89 | |||
| 8ec9d3115e | |||
| 96502d2611 | |||
| 6c5267e240 | |||
| 84789bfe57 | |||
| 19dcbff562 | |||
| e311e503ba | |||
| bd33bc0eb6 | |||
| f5b4171631 | |||
| 16e5d9b816 | |||
| c90994b36a | |||
| 728b380c67 | |||
| 2d9c8dab31 | |||
| 161f3ba7cd | |||
| e2ae9e88b2 | |||
| a06417d355 | |||
| d05a718be5 | |||
| e3a6f8b7e7 | |||
| 76046b23b0 | |||
| 098bb568e1 | |||
| 1fb1cafc15 | |||
| 8661ac473c | |||
| b6af107ac6 | |||
| 491baaa2d1 | |||
| 68fa2dbaed | |||
| 15b57b9e78 | |||
| 3b32256715 | |||
| 32f9fd3314 | |||
| cfc4ace4f4 | |||
| 7fdfd40107 | |||
| d7bfcf48b8 | |||
| 942b68ea3b | |||
| e08038c34c | |||
| 2f5ab52897 | |||
| 19e752d184 | |||
| c3652afc2b | |||
| 7014993561 | |||
| 72e54e8e9e | |||
| cd95cfcfe0 | |||
| 78a34dd1e9 | |||
| e7e78d7b6a | |||
| a19c874fee | |||
| 90c94a2ea9 | |||
| 73a470d076 | |||
| 7c2584b11d | |||
| 1d85f3be67 | |||
| a836d865f0 | |||
| f360a772b0 | |||
| 202db498c0 | |||
| d23ac06e40 | |||
| dbd3e3c14c | |||
| da731c48d9 | |||
| 5558e407be | |||
| f77b693db2 | |||
| 9842656b2b | |||
| 97b3b0404e | |||
| 54fa0112f5 | |||
| c7a05504f4 | |||
| 80d0fb2b70 | |||
| 3263141223 | |||
| 98a4233e14 | |||
| 4e6f46b191 | |||
| 8c9c6bec75 | |||
| ee5332d0d3 | |||
| 2ae1154be4 | |||
| e89650f169 | |||
| ba2dde80f3 | |||
| 7f3dd94092 | |||
| 10d1ecf2a2 | |||
| 3f77968f1d | |||
| 92bdd78e56 | |||
| 27d90dca17 | |||
| 47cedbb44e | |||
| a32e6a8d3e | |||
| b3e3977c2b | |||
| 8d254c5337 | |||
| 5c4477c9d3 | |||
| 4344a26540 | |||
| 37b67767a2 | |||
| 1c316becf3 | |||
| 1ccb6fd2f2 | |||
| e1cb0f44a3 | |||
| 009d776db5 | |||
| 32558eaf4e | |||
| 5be8cc0167 | |||
| e6cf1875ed | |||
| 377c442c4e | |||
| 13d79ffd41 | |||
| ddf144b596 | |||
| fb3ffca4c7 | |||
| 725b296ce4 | |||
| a13e0b9926 | |||
| 9ed1ce98a9 | |||
| e13dd192f1 | |||
| 498ea1cc77 | |||
| 0d3261daf7 | |||
| d38148f0aa | |||
| 04832f1ac4 | |||
| fd06e69ed2 | |||
| 456afaef88 | |||
| 377f8d6ef7 | |||
| d2d1a8580e | |||
| acb7f72254 | |||
| 677823227c | |||
| d856e78591 | |||
| 0c71954017 | |||
| f58e562809 | |||
| 221e5dc894 | |||
| 6dfbbe86fc | |||
| c8f4a6b546 | |||
| d5894ba4f3 | |||
| be94ec6136 | |||
| 6465ce6d65 | |||
| abb188ef37 | |||
| f91d97e475 | |||
| 377c2c05d8 | |||
| a406b0c5de | |||
| edb12d22a2 | |||
| 275b56c168 | |||
| b108817d31 | |||
| 1cadc21b42 | |||
| db6aefa5b8 | |||
| b7fe2ce91b | |||
| e76e7ffbd3 | |||
| 5c66878fb4 | |||
| 1857ffff0c | |||
| 56ca42aed0 | |||
| ba35c5ea67 | |||
| 3d704fb4b9 | |||
| fd5ec5fed5 | |||
| b2c7cd1e3e | |||
| 851fa4e5bb | |||
| 9f2cf9205d | |||
| f9eaf7e4b9 | |||
| 0e73fe9aa5 | |||
| 8bd92f0572 | |||
| 16fb0cb9d3 | |||
| dbea8a68a8 | |||
| 8b91260815 | |||
| 9bd1647f86 | |||
| c4250eca2a | |||
| cb150c4fd4 | |||
| e389e5d275 | |||
| efe499ac0d | |||
| 0ada245e37 | |||
| 402d4e7c12 | |||
| 26795f6a55 | |||
| bc79395bcf | |||
| ad75d79a52 | |||
| 494eef044c | |||
| 563c5f3074 | |||
| 0d680b48e8 | |||
| ec81815c4c | |||
| abf4e470ed | |||
| 5c0c86c2d5 | |||
| 3651f86162 | |||
| 16b46710ee | |||
| edafedbbc7 | |||
| 5b29a4c8b3 | |||
| 5f606ad6e2 | |||
| 202615ccf7 | |||
| c644330a52 | |||
| 34acf31e0f | |||
| 7cfd25cbb6 | |||
| 39a616d6c4 | |||
| db6eb2959c | |||
| 5e8ae1d337 | |||
| e3ce16a7b4 | |||
| 045fd2d689 | |||
| 029ce455fd | |||
| e5b3269d1d | |||
| 2b0f609a48 | |||
| f370301a5b | |||
| f36c7d0be2 | |||
| e0363fc9f8 | |||
| 9859d5117c | |||
| 803d1fd38b | |||
| bbac76747b | |||
| 7d57f61dfb | |||
| c670a0b366 | |||
| a4fdad6ff7 | |||
| da7ccc21d0 | |||
| 595c1af4b6 | |||
| 69e3f1a6e6 | |||
| df550cce26 | |||
| cc7472d4db | |||
| 0c2b432fd8 | |||
| 5803cdb401 | |||
| fe51550687 | |||
| 54fca540e8 | |||
| 3a56c32a1c | |||
| 34d40443a4 | |||
| 3bbe11169a | |||
| d0e2c3d33b | |||
| 72a58676c6 | |||
| 4e6a47fee5 | |||
| 29bc3345f1 | |||
| 9c5b66b6b4 | |||
| 564a61588d | |||
| 8c177567a7 | |||
| 2a66fbab28 | |||
| 86d6e2d45f | |||
| 62e5b11d8c | |||
| 4327c36280 | |||
| 31f8eda117 | |||
| 727a976d6b | |||
| 0f69a1af62 | |||
| 5ab7a9b56d | |||
| 1cc4cec3cb | |||
| 64b326da79 | |||
| ce39d34483 | |||
| f86a460e48 | |||
| 1785baa372 | |||
| 331daf10b8 | |||
| 4d957d3a63 | |||
| 4104411a1b | |||
| 915483bcd0 | |||
| f272180939 | |||
| 285ff99ce0 | |||
| ff434bb8a0 | |||
| 54015f3fbe | |||
| e11180b323 | |||
| 9547622726 | |||
| 7a908a474c | |||
| 71deea6671 | |||
| bb676df284 | |||
| b517934b42 | |||
| 06483d1df5 | |||
| 8c93b19883 | |||
| 4505da8771 | |||
| 22b73a0253 | |||
| 202e32953c | |||
| 87f230a66e | |||
| 4bdee80afa | |||
| 3d0d1865c8 | |||
| 0d99badc1b | |||
| 3b7b95d081 | |||
| bd9882d797 | |||
| 1fed60d5c1 | |||
| f84c1d67c0 | |||
| e50cb817e1 | |||
| 8207b3ebae | |||
| aa81800ffa | |||
| 5de01fdd7b | |||
| 85764e28ef | |||
| a4b3bd29aa | |||
| 27c6b50919 | |||
| 8e0bd33af7 | |||
| b674b9b820 | |||
| 96ac5fa0a0 | |||
| 9b1017a4d5 | |||
| b191368713 | |||
| e3d4f57e75 | |||
| 1ce6906808 | |||
| 9cf415ccc7 | |||
| e9fe337921 | |||
| 8958a7bd74 | |||
| c26c45dba3 | |||
| 7decd53c70 | |||
| d5253c5372 | |||
| 3e7691ee6e | |||
| 385131765d | |||
| adbae9cf54 | |||
| b862c11550 | |||
| e7b93e6c96 | |||
| 2ea5d2a90e | |||
| 80a73fda49 | |||
| db9d2fa299 | |||
| 830fed4f82 | |||
| e3b7dcbb7e | |||
| 55d2e78cc1 | |||
| 9f0fea6e21 | |||
| 3480df88ef | |||
| cfced9787e | |||
| 9cefd79ef4 | |||
| d5525e171b | |||
| 724275f3ef | |||
| 79d1435c68 | |||
| 5147fd6aec | |||
| f55708e31d | |||
| b6b16ce959 | |||
| e65104e762 | |||
| da65108efc | |||
| c74fefabb6 | |||
| 45d6fbb9e2 | |||
| 4e9672250b | |||
| f8270a6a44 | |||
| 7042dff969 | |||
| f477c4f2c9 | |||
| b1f7aef00b | |||
| d8d2c37ec0 | |||
| 609f1adf90 | |||
| bd649e2fd7 | |||
| be815c261a | |||
| d8a808c0e3 | |||
| c92290c3d7 | |||
| 0649c2b379 | |||
| 755970deba | |||
| f897b82d76 | |||
| dbbabed606 | |||
| ac178e20af | |||
| 29936f0fba | |||
| bfc16a1dee | |||
| 289a68bac3 | |||
| fcaff0f385 | |||
| 36163f9c3a | |||
| d90ec1758e | |||
| ea22cbd712 | |||
| d44badc190 | |||
| 6becb66185 | |||
| 1a1f057e5d | |||
| 10a269bd3f | |||
| 90d3381814 | |||
| b1f83a0bb0 | |||
| 3bc70925a9 | |||
| f287f08b9f | |||
| 0e4488e9dc | |||
| d7d63eddbe | |||
| 8acd7722f0 | |||
| 92fab6e058 | |||
| a0ee0856db | |||
| b8df500a70 | |||
| cd96ca071d | |||
| 216472ff9f | |||
| 3680d10e5c | |||
| abe3b9cd78 | |||
| 7aad6c9edf | |||
| ddd3aae249 | |||
| 6d3bb68faf | |||
| 21d50dae8c | |||
| 9279b1f0af | |||
| 6647085015 | |||
| 6af8f092ee | |||
| c4094c7a05 | |||
| 6d58df5f0c | |||
| ffecccf209 | |||
| 31f2839751 | |||
| e10a4eab2b | |||
| 8eb047945e | |||
| 1031325cca | |||
| 9fc2167cf9 | |||
| ae1de4de24 | |||
| 7e5d14b733 | |||
| 85cbea8dcb | |||
| bc6782624e | |||
| cf6ff87c7d | |||
| 3cd73d7927 | |||
| 7794c4aae5 | |||
| 8c7a84ea30 | |||
| e262ade74e | |||
| 11069e284a | |||
| 6e2e86decb | |||
| 15d3b63ccc | |||
| 453577651e | |||
| 39c07b7b4c | |||
| 5910285db0 | |||
| 68fe31da3f | |||
| f875ea9a52 | |||
| 138919907b | |||
| b8744626e7 | |||
| b08d78f6fc | |||
| 4efc05ef27 | |||
| 0788c43c3f | |||
| 3b2fd158b5 | |||
| c38dbacbd0 | |||
| 728b3200c0 | |||
| 7f74cd9e56 | |||
| 6ae8da6a39 | |||
| f699c8bb6a | |||
| ffde94c10e | |||
| b0a8848f68 | |||
| d651a595d4 | |||
| 969316cc0e | |||
| 5b46867507 | |||
| e117a373a7 | |||
| a4aed14337 | |||
| 9cde3c12a2 | |||
| 906e7a933e | |||
| 077d28d13a | |||
| b55bb1e9be | |||
| 7a6cc92d6d | |||
| b694c6e673 | |||
| 17895538a0 | |||
| 72ff1f9a87 | |||
| ef3194a510 | |||
| 8773402246 | |||
| ff3fc81db4 | |||
| 0dc3342c33 | |||
| c66fc812ac | |||
| 14ed023875 | |||
| 58284b8dbe | |||
| 60889d0b99 | |||
| 7e19bad0a4 | |||
| 4b1d73d39d | |||
| 03e19a1ad2 | |||
| 8fb9499c20 | |||
| 38fb6a5958 | |||
| 49cd62d65e | |||
| 24bb5216bb | |||
| 7f8760fd1f | |||
| 3cb6b9d93a | |||
| c591106b86 | |||
| 9f096737db | |||
| 1bda165b25 | |||
| f48372624d | |||
| 5cd15536b6 | |||
| aeb4a5fdad | |||
| 9529f30129 | |||
| 266311ca33 | |||
| 954a3900b9 | |||
| 07343b5baf | |||
| a03ed8b300 | |||
| 13a93e5cbe | |||
| d9c4e6239f | |||
| 61ebd9be6a | |||
| e3b40208d5 | |||
| 16c2d1e1d0 | |||
| fea1622724 | |||
| 00b64f3ccb | |||
| 74b850a642 | |||
| 4202f3939e | |||
| e1ecba2ce4 | |||
| 0853e35e1f | |||
| 4b4a74c988 | |||
| 84f032eba8 | |||
| b8a5f95cf2 | |||
| 73260c0e35 | |||
| 5903dec289 | |||
| 571ebb349b | |||
| d62bbbbcd1 | |||
| ad5fb44ddc | |||
| 8bbbd7679b | |||
| cd32a3827d | |||
| 66c0637c90 | |||
| c9df4296f9 | |||
| 7c5cf28ace | |||
| 51002c842d | |||
| 8e582971fa | |||
| 6daa72f929 | |||
| 8355d78359 | |||
| dbc1818073 | |||
| e57ce7f2a4 | |||
| d8f89fa59e | |||
| 350003d8da | |||
| 15329f9cfa | |||
| 95b4dff379 | |||
| c96b1af3be | |||
| 5ee6365510 | |||
| 1d57b3a064 | |||
| 325d419e39 | |||
| 8b5532d8dd | |||
| 7263b5e01d | |||
| c6fcdbe000 | |||
| 306dacd0b4 | |||
| 08910e4e3f | |||
| 8897659607 | |||
| 53fd416c47 | |||
| 5e0018fb1f | |||
| 054bae01ef | |||
| 8f32a758a4 | |||
| 0fc8facfb7 | |||
| 069b181625 | |||
| d9b69c8405 | |||
| a11f8426d4 | |||
| e6aa8e82f6 | |||
| 978866d983 | |||
| 36bc84041b | |||
| 3ed4ea7538 | |||
| 6b5fe1c634 | |||
| 7c39fff969 | |||
| b922ca18f0 | |||
| b8e7cbd5e3 | |||
| 9df9a489f0 | |||
| fa01a280ed | |||
| e6b5a4ef9d | |||
| 19832fcbd3 | |||
| d371b10039 | |||
| 8c50bc733d | |||
| 3f9794cd1a | |||
| fc240f7b2a | |||
| dea9110b90 | |||
| 93cdb2628e | |||
| 817c0bc512 | |||
| e97dec777c | |||
| 5f494b0925 | |||
| 59feb7d6ab | |||
| 97f5326393 | |||
| e2a298a84f | |||
| 3317362e78 | |||
| 39d0a3ff3c | |||
| d36c59920d | |||
| 995d2f5e44 | |||
| 3884f054f1 | |||
| 32504fa3d5 | |||
| afd0efa291 | |||
| 737b5bc42e | |||
| 601d2bb13e | |||
| 917c56b120 | |||
| 9ffd57f4ef | |||
| 08a8723ee7 | |||
| efdba804ac | |||
| 6f0632273b | |||
| c848af33d5 | |||
| f33de6544f | |||
| d7e5dcf9d2 | |||
| b38ba68ccc | |||
| e55907dc8b | |||
| a248607bee | |||
| ed23fb9054 | |||
| 7d357a6cec | |||
| 1feed8816a | |||
| 9ce43b2d7b | |||
| a6a78e1c65 | |||
| cd14bb8a2c | |||
| 7162f28a5b | |||
| 2328e9cd17 | |||
| 2a6026b25d | |||
| c62224d2c3 | |||
| 9a40d21ceb | |||
| d019b02829 | |||
| 2f813601aa | |||
| aae8519a1d | |||
| 4bfb903b22 | |||
| d91b2a202e | |||
| a74a43987a | |||
| 2a588a0171 | |||
| 3ae04546ea | |||
| a0370aaf25 | |||
| 740edeb73f | |||
| 91e3c3cba5 | |||
| d6e9cbfff3 | |||
| 8d3172f987 | |||
| 5be58f0f76 | |||
| 8d30d6a4fe | |||
| 5ff866aa26 | |||
| 4ecf013527 | |||
| 1c3a38b423 | |||
| a3a4912ced | |||
| 0d32bebcc2 | |||
| 0884b837b2 | |||
| 11199079c3 | |||
| 69521a1057 | |||
| 59a487b524 | |||
| 0e2a4bac72 | |||
| 35aa52538c | |||
| b680a9de9f | |||
| 42244e5f32 | |||
| 072c9e56e1 | |||
| f7bb60aba5 | |||
| b019d8f1bf | |||
| 15c795d2e1 | |||
| a428f7eb13 | |||
| 02c9efba28 | |||
| aebe7537c3 | |||
| 4356ba3c43 | |||
| c9afbc5b70 | |||
| e38e3078ac | |||
| 5439326aa4 | |||
| 35bc1f95fb | |||
| 161ee64399 | |||
| 399bf3a931 | |||
| bae0a1bfa6 | |||
| e4bca1033c | |||
| da40e76aae | |||
| 31ac4a3f5c | |||
| 424d6efcc0 | |||
| ccf8e69650 | |||
| ee44c1ed90 | |||
| 3ac2e13a25 | |||
| 06a6a118a1 | |||
| c095867154 | |||
| 324005fb3a | |||
| d8166907e6 | |||
| 7cbfb8e29c | |||
| 1c5ce0a661 | |||
| f98496abcd | |||
| 82aa17f9fb | |||
| 9b8457aeb3 | |||
| 535b34e48a | |||
| 0909d413d0 | |||
| 284ee3d0c6 | |||
| f3e6536d59 | |||
| 002645d7ac | |||
| 9f6abded0e | |||
| 840a565d3a | |||
| 3cf5ac0b9a | |||
| a217823510 | |||
| f867c28a2c | |||
| 73a693ef28 | |||
| 9955e20d01 | |||
| 03052757a7 | |||
| bdcc24ed04 | |||
| 8478a2c7eb | |||
| c34bfa30fe | |||
| af9daff4ee | |||
| 10ba34f78b | |||
| 503ede7535 | |||
| 08c0d427bf | |||
| ab7d5eff87 | |||
| 686318c005 | |||
| c04ab74744 | |||
| 8fdfc6c2ef | |||
| 71393fa1be | |||
| 5e50825af2 | |||
| 8fed650de9 | |||
| 4d8569ad6b | |||
| 2f0677b556 | |||
| 0a8a72d4f3 | |||
| de611c8835 | |||
| a36f2cf61c | |||
| b6c7ebc4f1 | |||
| fd707b42c2 | |||
| 7c86c7d585 | |||
| 27013537c9 | |||
| addf00cb16 | |||
| 1964e434e6 | |||
| d5bca085dd | |||
| 8ecfdfee43 | |||
| b7a2f68d59 | |||
| e98a6c6755 | |||
| 614e637dbc | |||
| 7ec795cd57 | |||
| 8f510265fc | |||
| 39d80a59b6 | |||
| 6e3eb26af3 | |||
| 4a66d8fcd8 | |||
| daa986ea35 | |||
| 0a575763a1 | |||
| 547d08c1ef | |||
| bbd66b3240 | |||
| 2ddc2f6c18 | |||
| 58a9dde73f | |||
| d441516c9d | |||
| d991beb942 | |||
| 650a511fa4 | |||
| 2aa966cb3c | |||
| cd5fad3cf3 | |||
| c9d3968475 | |||
| 36e60223eb | |||
| 781bd4bcf2 | |||
| 0d9926de40 | |||
| e147ba901b | |||
| 7e26925933 | |||
| 8dda499830 | |||
| 317a0c3cd3 | |||
| 67cf524287 | |||
| db2590dca5 | |||
| 64e642403e | |||
| 38cdeb0413 | |||
| 5c87ff524e | |||
| 88bebb8aac | |||
| d89b5755d9 | |||
| a3489674bf | |||
| f6e74407e8 | |||
| 41d775bedd | |||
| 45cb15d60f | |||
| ce4e8675ed | |||
| 2fcfe7a5b7 | |||
| fdab5da795 | |||
| 85e3adaf18 | |||
| 38d406876d | |||
| 84bf65e023 | |||
| 2c3e40c9d9 | |||
| 9e88f91c22 | |||
| 0773b3067e | |||
| bba7e0acd8 | |||
| 6ebc366146 | |||
| b389f41cb2 | |||
| 56c405d8e6 | |||
| 99d1db8cb3 | |||
| fbef976b92 | |||
| 55aae3a8c0 | |||
| b04cae2ca0 | |||
| c159ea2042 | |||
| 567ce2640f | |||
| 527fe9e262 | |||
| 0a7b51ad42 | |||
| f15be89bff | |||
| cbd11d8a45 | |||
| f52eaa92e4 | |||
| f4c6d55b9d | |||
| 5e7a870af6 | |||
| 6b7f8da381 | |||
| 8d1c3631cf | |||
| c85929045e | |||
| 715f0a9e44 | |||
| bab77275ec | |||
| 12165c73f8 | |||
| 70c4865191 | |||
| 7f5bc9884f | |||
| ac35b11dc8 | |||
| f8e832f212 | |||
| bc94fcc90f | |||
| b57ed11f65 | |||
| 831fe666fa | |||
| 13a47c3a2c | |||
| 5771e74b95 | |||
| 55029e889e | |||
| ebd48d406e | |||
| 3f72ef4cdd | |||
| 169d22fde2 | |||
| c6f9595a02 | |||
| 5278405263 | |||
| 5bb7a52704 | |||
| 93e5488420 | |||
| 36ee44a3f6 | |||
| 8500c3193d | |||
| cd8ec44abf | |||
| 17d849df6c | |||
| b2c8888a50 | |||
| f0c50befce | |||
| 7917c00887 | |||
| c9f4dec2ed | |||
| e9121ee515 | |||
| 3782278f02 | |||
| a3622ba294 | |||
| aec125637b | |||
| cb95f1dcd5 | |||
| 4257034209 | |||
| b6f0088b68 | |||
| c2115884de | |||
| c0b14705cd | |||
| bf1a6f6680 | |||
| 10ecb64ff3 | |||
| aca64c09f8 | |||
| 86c33492a7 | |||
| c41d61eeda | |||
| 5b9e302e9b | |||
| f4c34b81c7 | |||
| a50e417c67 | |||
| ff7336b202 | |||
| e6f4805bae | |||
| 066ce41299 | |||
| b7f5f4ac7d | |||
| 4e7b403c1f | |||
| 0984ed91ea | |||
| 4ffc34956f | |||
| 5039d2db99 | |||
| ee2396b57a | |||
| 5376676d07 | |||
| 3f33b15e52 | |||
| b1ee6e3046 | |||
| 46c38a827e | |||
| 4f1bcfedf3 | |||
| e3e6057434 | |||
| 12142008df | |||
| 8ccf21437b | |||
| 4419401b6c | |||
| e46d402ed1 | |||
| 9ea882d7cc | |||
| f63c463471 | |||
| bd44c82404 | |||
| 2569317ee8 | |||
| cb91a5c848 | |||
| fcf8099587 | |||
| 97dfd8b428 | |||
| c127dc89a5 | |||
| c48586de08 | |||
| d6b1d16bfc | |||
| 90e860c7a5 | |||
| c7370ca82c | |||
| cbc6ddeefc | |||
| 45d6f55d3a | |||
| 6655356ce3 | |||
| 3e68733c94 | |||
| c9db74bfd4 | |||
| ff77a2e29e | |||
| 19f5de51af | |||
| 9dc1b03905 | |||
| b1296d8557 | |||
| 1550ec3ffc | |||
| 448ed6dfe5 | |||
| a552b57d36 | |||
| e17c592dec | |||
| 441c726d47 | |||
| 9ced5675d2 | |||
| b984596e3c | |||
| 9c1b025695 | |||
| 65837a573e | |||
| a0062b9a1b | |||
| 922f127aca | |||
| cb6295d025 | |||
| a5f69579cf | |||
| fdcbb2f008 | |||
| ac934bd703 | |||
| 3a4bb4f344 | |||
| aed3bac71b | |||
| e76402374f | |||
| 41237e73a5 | |||
| bfba33a230 | |||
| e8615b88f9 | |||
| b1763ba7db | |||
| 6219aa3b26 | |||
| 218d475cb2 | |||
| 00a1abbf43 | |||
| f189d99b98 | |||
| dc1b4ea720 | |||
| 1b71425419 | |||
| 791a66893e | |||
| d298ce15cc | |||
| 7c32932ada | |||
| 777b8a031b | |||
| 4af4c8df44 | |||
| d6e5ee2f63 | |||
| a263b2e58e | |||
| f227bb291a | |||
| b82e48f6da | |||
| c47501ef7c | |||
| 1d2d06ea25 | |||
| 33beb7fc64 | |||
| 8b96a1e99c | |||
| f52dec11a4 | |||
| 941f712975 | |||
| 74d6990b4e | |||
| 42e7e9ec64 | |||
| 40b368e761 | |||
| 16acdeb6ce | |||
| 6782c21d52 | |||
| d00c8ba0d8 | |||
| de27835264 | |||
| 41affe18c4 | |||
| dcde6d358f | |||
| f57206a3a1 | |||
| f823eac672 | |||
| cbf3f11cf8 | |||
| 306cd99273 | |||
| 6fed29eda2 | |||
| 4fecbe4ede | |||
| 3ad15721e0 | |||
| 7ec7c56a01 | |||
| d3dc18ba65 | |||
| 8ab6dd3e45 | |||
| b311b01336 | |||
| ecfcfe448d | |||
| aa5c03834f | |||
| 4269217e28 | |||
| 4e82809624 | |||
| cf4964d0f8 | |||
| 3f6ff2ca32 | |||
| bbd8c78861 | |||
| 9d93807512 | |||
| 8a17ca25d6 | |||
| 6faf9ff1e0 | |||
| 37697f4ad3 | |||
| 36361c39d2 | |||
| 4349bfe985 | |||
| 2f9a858b2f | |||
| d64fca0a32 | |||
| 803ea0a0b1 | |||
| cfa768755f | |||
| 9dcfa4a662 | |||
| 7ab29e17a3 | |||
| 7d2740d6cd | |||
| 60c14b1af2 | |||
| 47e30d3d4a | |||
| 38b84d08d7 | |||
| 50c0fa812f | |||
| 3e201de9b0 | |||
| db2fd00c4a | |||
| c577b0838b | |||
| 5a12a5e421 | |||
| 9f39f1d75b | |||
| 9fb0c5d372 | |||
| e54e352035 | |||
| f27332ee8d | |||
| 0aee9b0fd9 | |||
| 45f490a407 | |||
| 0fd7ec5c2a | |||
| ba473fc925 | |||
| 6e5c8d9c20 | |||
| b29e87ec30 | |||
| 7db25a7b23 | |||
| bbdb8b9d9e | |||
| 6b8056ca86 | |||
| 5ec55eed96 | |||
| efedd9c4e0 | |||
| 4e0b193ab6 | |||
| 1ac2c38b6b | |||
| eb111aa835 | |||
| 25b6ac8b3e | |||
| cdd771a018 | |||
| ae861f7e4b | |||
| 43f683469b | |||
| 2395e7cac5 | |||
| abaed6686d | |||
| 1844ed6b8c | |||
| 9f5ed8534e | |||
| c48d02e0a9 | |||
| b3399c239b | |||
| 4377954cf9 | |||
| 125cb81a5b | |||
| 2e9be3e3f5 | |||
| 43f276e073 | |||
| ec38e23d58 | |||
| 56060a5b6b | |||
| 03548a847f | |||
| 06cd391845 | |||
| ef4abfc1d2 | |||
| 72895675ef | |||
| ccc6cc54b2 | |||
| aa1c0250b7 | |||
| d5f740c9d3 | |||
| aa6933d9e3 | |||
| c800c79976 | |||
| 075c1af7d8 | |||
| fbebaa299d | |||
| f6bbeb35f5 | |||
| 0dc49b07a0 | |||
| c2e5075316 | |||
| e7f192f1c6 | |||
| e5145ffb98 | |||
| 30add71233 | |||
| dade9736ac | |||
| 639ed34791 | |||
| da7ea79034 | |||
| b7e077320d | |||
| 22dbed0545 | |||
| 3dc61b5f28 | |||
| 1153e3e155 | |||
| a26bd3232c | |||
| 813a802b2c | |||
| 81669f4c10 | |||
| 5ea7cb7a05 | |||
| 4baefb2f5a | |||
| 97a8825b00 | |||
| 7fe4bfaacb | |||
| 1a6638ba23 | |||
| 8772708aa7 | |||
| a4bb734482 | |||
| 5fbfdfadb8 | |||
| 16ae03c3b4 |
@@ -0,0 +1,9 @@
|
||||
# On Windows MSVC, statically link the C runtime so that the resulting EXE does
|
||||
# not depend on the vcruntime DLL.
|
||||
#
|
||||
# See: https://github.com/sharkdp/fd/issues/1874
|
||||
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
rustflags = ["-C", "target-feature=+crt-static"]
|
||||
[target.i686-pc-windows-msvc]
|
||||
rustflags = ["-C", "target-feature=+crt-static"]
|
||||
@@ -0,0 +1 @@
|
||||
github: [sharkdp, tavianator]
|
||||
@@ -9,6 +9,7 @@ body:
|
||||
Please check out the [troubleshooting section](https://github.com/sharkdp/fd#troubleshooting) first.
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Checks
|
||||
options:
|
||||
- label: I have read the troubleshooting section and still think this is a bug.
|
||||
required: true
|
||||
|
||||
@@ -4,3 +4,11 @@ updates:
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
cooldown:
|
||||
default-days: 7
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
cooldown:
|
||||
default-days: 7
|
||||
|
||||
+166
-243
@@ -1,8 +1,8 @@
|
||||
name: CICD
|
||||
|
||||
env:
|
||||
MIN_SUPPORTED_RUST_VERSION: "1.53.0"
|
||||
CICD_INTERMEDIATES_DIR: "_cicd-intermediates"
|
||||
MSRV_FEATURES: "--all-features"
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -13,98 +13,140 @@ on:
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
code_quality:
|
||||
name: Code quality
|
||||
runs-on: ubuntu-20.04
|
||||
crate_metadata:
|
||||
name: Extract crate metadata
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@v2
|
||||
- name: Install rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
- uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
toolchain: stable
|
||||
default: true
|
||||
profile: minimal # minimal component installation (ie, no documentation)
|
||||
components: clippy, rustfmt
|
||||
- name: Ensure `cargo fmt` has been run
|
||||
uses: actions-rs/cargo@v1
|
||||
persist-credentials: false
|
||||
- name: Extract crate information
|
||||
id: crate_metadata
|
||||
run: |
|
||||
echo "name=fd" | tee -a $GITHUB_OUTPUT
|
||||
cargo metadata --no-deps --format-version 1 | jq -r '"version=" + .packages[0].version' | tee -a $GITHUB_OUTPUT
|
||||
cargo metadata --no-deps --format-version 1 | jq -r '"maintainer=" + .packages[0].authors[0]' | tee -a $GITHUB_OUTPUT
|
||||
cargo metadata --no-deps --format-version 1 | jq -r '"homepage=" + .packages[0].homepage' | tee -a $GITHUB_OUTPUT
|
||||
cargo metadata --no-deps --format-version 1 | jq -r '"msrv=" + .packages[0].rust_version' | tee -a $GITHUB_OUTPUT
|
||||
outputs:
|
||||
name: ${{ steps.crate_metadata.outputs.name }}
|
||||
version: ${{ steps.crate_metadata.outputs.version }}
|
||||
maintainer: ${{ steps.crate_metadata.outputs.maintainer }}
|
||||
homepage: ${{ steps.crate_metadata.outputs.homepage }}
|
||||
msrv: ${{ steps.crate_metadata.outputs.msrv }}
|
||||
|
||||
ensure_cargo_fmt:
|
||||
name: Ensure 'cargo fmt' has been run
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
command: fmt
|
||||
args: -- --check
|
||||
- name: Ensure MSRV is set in `clippy.toml`
|
||||
run: grep "^msrv = \"${{ env.MIN_SUPPORTED_RUST_VERSION }}\"\$" clippy.toml
|
||||
- name: Run clippy
|
||||
uses: actions-rs/cargo@v1
|
||||
components: rustfmt
|
||||
- uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
command: clippy
|
||||
args: --locked --all-targets --all-features
|
||||
persist-credentials: false
|
||||
- run: cargo fmt -- --check
|
||||
|
||||
lint_check:
|
||||
name: Ensure 'cargo clippy' has no warnings
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: clippy
|
||||
- uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- run: cargo clippy --all-targets --all-features -- -Dwarnings
|
||||
|
||||
min_version:
|
||||
name: Minimum supported rust version
|
||||
runs-on: ubuntu-20.04
|
||||
runs-on: ubuntu-22.04
|
||||
needs: crate_metadata
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@v2
|
||||
- name: Install rust toolchain (v${{ env.MIN_SUPPORTED_RUST_VERSION }})
|
||||
uses: actions-rs/toolchain@v1
|
||||
uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
toolchain: ${{ env.MIN_SUPPORTED_RUST_VERSION }}
|
||||
default: true
|
||||
profile: minimal # minimal component installation (ie, no documentation)
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install rust toolchain (v${{ needs.crate_metadata.outputs.msrv }})
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: ${{ needs.crate_metadata.outputs.msrv }}
|
||||
components: clippy
|
||||
- name: Run clippy (on minimum supported rust version to prevent warnings we can't fix)
|
||||
run: cargo clippy --locked --all-targets "${MSRV_FEATURES}"
|
||||
- name: Run tests
|
||||
uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: test
|
||||
args: --locked
|
||||
run: cargo test --locked "${MSRV_FEATURES}"
|
||||
|
||||
build:
|
||||
name: ${{ matrix.job.os }} (${{ matrix.job.target }})
|
||||
name: '${{ matrix.job.target }} (${{ matrix.job.os }})'
|
||||
runs-on: ${{ matrix.job.os }}
|
||||
needs: crate_metadata
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: write
|
||||
attestations: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
job:
|
||||
- { os: ubuntu-20.04, target: arm-unknown-linux-gnueabihf , use-cross: true }
|
||||
- { os: ubuntu-20.04, target: arm-unknown-linux-musleabihf, use-cross: true }
|
||||
- { os: ubuntu-20.04, target: aarch64-unknown-linux-gnu , use-cross: true }
|
||||
- { os: ubuntu-20.04, target: i686-unknown-linux-gnu , use-cross: true }
|
||||
- { os: ubuntu-20.04, target: i686-unknown-linux-musl , use-cross: true }
|
||||
- { os: ubuntu-20.04, target: x86_64-unknown-linux-gnu }
|
||||
- { os: ubuntu-20.04, target: x86_64-unknown-linux-musl , use-cross: true }
|
||||
- { os: macos-10.15 , target: x86_64-apple-darwin }
|
||||
# - { os: windows-2019, target: i686-pc-windows-gnu } ## disabled; error: linker `i686-w64-mingw32-gcc` not found
|
||||
- { os: windows-2019, target: i686-pc-windows-msvc }
|
||||
- { os: windows-2019, target: x86_64-pc-windows-gnu }
|
||||
- { os: windows-2019, target: x86_64-pc-windows-msvc }
|
||||
- { target: aarch64-unknown-linux-gnu , os: ubuntu-24.04, use-cross: true }
|
||||
- { target: aarch64-unknown-linux-musl , os: ubuntu-24.04, use-cross: true }
|
||||
- { target: arm-unknown-linux-gnueabihf , os: ubuntu-24.04, use-cross: true }
|
||||
- { target: arm-unknown-linux-musleabihf, os: ubuntu-24.04, use-cross: true }
|
||||
- { target: i686-pc-windows-msvc , os: windows-2025 }
|
||||
- { target: i686-unknown-linux-gnu , os: ubuntu-24.04, use-cross: true }
|
||||
- { target: i686-unknown-linux-musl , os: ubuntu-24.04, use-cross: true }
|
||||
- { target: x86_64-apple-darwin , os: macos-26-intel }
|
||||
- { target: aarch64-apple-darwin , os: macos-26 }
|
||||
- { target: x86_64-pc-windows-gnu , os: windows-2025 }
|
||||
- { target: x86_64-pc-windows-msvc , os: windows-2025 }
|
||||
- { target: aarch64-pc-windows-msvc , os: windows-11-arm }
|
||||
- { target: x86_64-unknown-linux-gnu , os: ubuntu-24.04, use-cross: true }
|
||||
- { target: x86_64-unknown-linux-musl , os: ubuntu-24.04, use-cross: true }
|
||||
env:
|
||||
BUILD_CMD: "${{ matrix.job.use-cross && 'cross' || 'cargo' }}"
|
||||
target: ${{ matrix.job.target }}
|
||||
name: ${{ needs.crate_metadata.outputs.name }}
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install prerequisites
|
||||
shell: bash
|
||||
run: |
|
||||
case ${{ matrix.job.target }} in
|
||||
case ${target} in
|
||||
arm-unknown-linux-*) sudo apt-get -y update ; sudo apt-get -y install gcc-arm-linux-gnueabihf ;;
|
||||
aarch64-unknown-linux-gnu) sudo apt-get -y update ; sudo apt-get -y install gcc-aarch64-linux-gnu ;;
|
||||
esac
|
||||
|
||||
- name: Extract crate information
|
||||
shell: bash
|
||||
run: |
|
||||
echo "PROJECT_NAME=fd" >> $GITHUB_ENV
|
||||
echo "PROJECT_VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -n1)" >> $GITHUB_ENV
|
||||
echo "PROJECT_MAINTAINER=$(sed -n 's/^authors = \["\(.*\)"\]/\1/p' Cargo.toml)" >> $GITHUB_ENV
|
||||
echo "PROJECT_HOMEPAGE=$(sed -n 's/^homepage = "\(.*\)"/\1/p' Cargo.toml)" >> $GITHUB_ENV
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: actions-rs/toolchain@v1
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: stable
|
||||
target: ${{ matrix.job.target }}
|
||||
override: true
|
||||
profile: minimal # minimal component installation (ie, no documentation)
|
||||
targets: ${{ matrix.job.target }}
|
||||
toolchain: "stable"
|
||||
|
||||
- name: Install cross
|
||||
if: matrix.job.use-cross
|
||||
env:
|
||||
cross_version: "v0.2.5"
|
||||
package_name: "cross-x86_64-unknown-linux-gnu.tar.gz"
|
||||
GH_TOKEN: "${{ github.token }}"
|
||||
run: |
|
||||
dir="$HOME/.local/bin/"
|
||||
mkdir -p "$dir"
|
||||
gh release download --repo cross-rs/cross \
|
||||
--pattern "${package_name}" -O - "${cross_version}" \
|
||||
| tar -C "$dir" -xz
|
||||
echo "$dir" >> $GITHUB_PATH
|
||||
echo "Installed cross $cross_version" >> $GITHUB_STEP_SUMMARY
|
||||
- name: Show version information (Rust, cargo, GCC)
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -116,47 +158,26 @@ jobs:
|
||||
rustc -V
|
||||
|
||||
- name: Build
|
||||
uses: actions-rs/cargo@v1
|
||||
with:
|
||||
use-cross: ${{ matrix.job.use-cross }}
|
||||
command: build
|
||||
args: --locked --release --target=${{ matrix.job.target }}
|
||||
shell: bash
|
||||
run: $BUILD_CMD build --locked --release --target="${target}"
|
||||
|
||||
- name: Strip debug information from executable
|
||||
id: strip
|
||||
- name: Set binary name & path
|
||||
id: bin
|
||||
shell: bash
|
||||
run: |
|
||||
# Figure out suffix of binary
|
||||
EXE_suffix=""
|
||||
case ${{ matrix.job.target }} in
|
||||
case ${target} in
|
||||
*-pc-windows-*) EXE_suffix=".exe" ;;
|
||||
esac;
|
||||
|
||||
# Figure out what strip tool to use if any
|
||||
STRIP="strip"
|
||||
case ${{ matrix.job.target }} in
|
||||
arm-unknown-linux-*) STRIP="arm-linux-gnueabihf-strip" ;;
|
||||
aarch64-unknown-linux-gnu) STRIP="aarch64-linux-gnu-strip" ;;
|
||||
*-pc-windows-msvc) STRIP="" ;;
|
||||
esac;
|
||||
|
||||
# Setup paths
|
||||
BIN_DIR="${{ env.CICD_INTERMEDIATES_DIR }}/stripped-release-bin/"
|
||||
mkdir -p "${BIN_DIR}"
|
||||
BIN_NAME="${{ env.PROJECT_NAME }}${EXE_suffix}"
|
||||
BIN_PATH="${BIN_DIR}/${BIN_NAME}"
|
||||
BIN_NAME="${name}${EXE_suffix}"
|
||||
BIN_PATH="target/${target}/release/${BIN_NAME}"
|
||||
|
||||
# Copy the release build binary to the result location
|
||||
cp "target/${{ matrix.job.target }}/release/${BIN_NAME}" "${BIN_DIR}"
|
||||
|
||||
# Also strip if possible
|
||||
if [ -n "${STRIP}" ]; then
|
||||
"${STRIP}" "${BIN_PATH}"
|
||||
fi
|
||||
|
||||
# Let subsequent steps know where to find the (stripped) bin
|
||||
echo ::set-output name=BIN_PATH::${BIN_PATH}
|
||||
echo ::set-output name=BIN_NAME::${BIN_NAME}
|
||||
# Let subsequent steps know where to find the binary
|
||||
echo "BIN_PATH=${BIN_PATH}" >> $GITHUB_OUTPUT
|
||||
echo "BIN_NAME=${BIN_NAME}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Set testing options
|
||||
id: test-options
|
||||
@@ -164,187 +185,77 @@ jobs:
|
||||
run: |
|
||||
# test only library unit tests and binary for arm-type targets
|
||||
unset CARGO_TEST_OPTIONS
|
||||
unset CARGO_TEST_OPTIONS ; case ${{ matrix.job.target }} in arm-* | aarch64-*) CARGO_TEST_OPTIONS="--bin ${PROJECT_NAME}" ;; esac;
|
||||
echo ::set-output name=CARGO_TEST_OPTIONS::${CARGO_TEST_OPTIONS}
|
||||
case ${target} in
|
||||
arm-* | aarch64-*)
|
||||
CARGO_TEST_OPTIONS="--bin=${name}" ;;
|
||||
esac
|
||||
echo "CARGO_TEST_OPTIONS=${CARGO_TEST_OPTIONS}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run tests
|
||||
uses: actions-rs/cargo@v1
|
||||
with:
|
||||
use-cross: ${{ matrix.job.use-cross }}
|
||||
command: test
|
||||
args: --locked --target=${{ matrix.job.target }} ${{ steps.test-options.outputs.CARGO_TEST_OPTIONS}}
|
||||
shell: bash
|
||||
env:
|
||||
cargo_test_options: ${{ steps.test-options.outputs.CARGO_TEST_OPTIONS}}
|
||||
run: $BUILD_CMD test --locked --target="${target}" "${cargo_test_options}"
|
||||
|
||||
- name: Generate completions
|
||||
id: completions
|
||||
shell: bash
|
||||
run: make completions
|
||||
|
||||
- name: Create tarball
|
||||
id: package
|
||||
shell: bash
|
||||
run: |
|
||||
PKG_suffix=".tar.gz" ; case ${{ matrix.job.target }} in *-pc-windows-*) PKG_suffix=".zip" ;; esac;
|
||||
PKG_BASENAME=${PROJECT_NAME}-v${PROJECT_VERSION}-${{ matrix.job.target }}
|
||||
PKG_NAME=${PKG_BASENAME}${PKG_suffix}
|
||||
echo ::set-output name=PKG_NAME::${PKG_NAME}
|
||||
|
||||
PKG_STAGING="${{ env.CICD_INTERMEDIATES_DIR }}/package"
|
||||
ARCHIVE_DIR="${PKG_STAGING}/${PKG_BASENAME}/"
|
||||
mkdir -p "${ARCHIVE_DIR}"
|
||||
mkdir -p "${ARCHIVE_DIR}/autocomplete"
|
||||
|
||||
# Binary
|
||||
cp "${{ steps.strip.outputs.BIN_PATH }}" "$ARCHIVE_DIR"
|
||||
|
||||
# Man page
|
||||
cp 'doc/${{ env.PROJECT_NAME }}.1' "$ARCHIVE_DIR"
|
||||
|
||||
# README, LICENSE and CHANGELOG files
|
||||
cp "README.md" "LICENSE-MIT" "LICENSE-APACHE" "CHANGELOG.md" "$ARCHIVE_DIR"
|
||||
|
||||
# Autocompletion files
|
||||
cp 'target/${{ matrix.job.target }}/release/build/${{ env.PROJECT_NAME }}'*/out/'${{ env.PROJECT_NAME }}.bash' "$ARCHIVE_DIR/autocomplete/"
|
||||
cp 'target/${{ matrix.job.target }}/release/build/${{ env.PROJECT_NAME }}'*/out/'${{ env.PROJECT_NAME }}.fish' "$ARCHIVE_DIR/autocomplete/"
|
||||
cp 'target/${{ matrix.job.target }}/release/build/${{ env.PROJECT_NAME }}'*/out/'_${{ env.PROJECT_NAME }}.ps1' "$ARCHIVE_DIR/autocomplete/"
|
||||
cp 'contrib/completion/_fd' "$ARCHIVE_DIR/autocomplete/"
|
||||
|
||||
# base compressed package
|
||||
pushd "${PKG_STAGING}/" >/dev/null
|
||||
case ${{ matrix.job.target }} in
|
||||
*-pc-windows-*) 7z -y a "${PKG_NAME}" "${PKG_BASENAME}"/* | tail -2 ;;
|
||||
*) tar czf "${PKG_NAME}" "${PKG_BASENAME}"/* ;;
|
||||
esac;
|
||||
popd >/dev/null
|
||||
|
||||
# Let subsequent steps know where to find the compressed package
|
||||
echo ::set-output name=PKG_PATH::"${PKG_STAGING}/${PKG_NAME}"
|
||||
run: bash scripts/create-archive.sh
|
||||
env:
|
||||
BIN_PATH: ${{ steps.bin.outputs.BIN_PATH }}
|
||||
TARGET: ${{ env.target }}
|
||||
ARCHIVE_NAME: ${{ env.name }}-v${{ needs.crate_metadata.outputs.version }}-${{ env.target }}
|
||||
PKG_STAGING: "${{ env.CICD_INTERMEDIATES_DIR }}/package"
|
||||
|
||||
- name: Create Debian package
|
||||
id: debian-package
|
||||
shell: bash
|
||||
if: startsWith(matrix.job.os, 'ubuntu')
|
||||
run: |
|
||||
COPYRIGHT_YEARS="2018 - "$(date "+%Y")
|
||||
DPKG_STAGING="${{ env.CICD_INTERMEDIATES_DIR }}/debian-package"
|
||||
DPKG_DIR="${DPKG_STAGING}/dpkg"
|
||||
mkdir -p "${DPKG_DIR}"
|
||||
|
||||
DPKG_BASENAME=${PROJECT_NAME}
|
||||
DPKG_CONFLICTS=${PROJECT_NAME}-musl
|
||||
case ${{ matrix.job.target }} in *-musl) DPKG_BASENAME=${PROJECT_NAME}-musl ; DPKG_CONFLICTS=${PROJECT_NAME} ;; esac;
|
||||
DPKG_VERSION=${PROJECT_VERSION}
|
||||
|
||||
unset DPKG_ARCH
|
||||
case ${{ matrix.job.target }} in
|
||||
aarch64-*-linux-*) DPKG_ARCH=arm64 ;;
|
||||
arm-*-linux-*hf) DPKG_ARCH=armhf ;;
|
||||
i686-*-linux-*) DPKG_ARCH=i686 ;;
|
||||
x86_64-*-linux-*) DPKG_ARCH=amd64 ;;
|
||||
*) DPKG_ARCH=notset ;;
|
||||
esac;
|
||||
|
||||
DPKG_NAME="${DPKG_BASENAME}_${DPKG_VERSION}_${DPKG_ARCH}.deb"
|
||||
echo ::set-output name=DPKG_NAME::${DPKG_NAME}
|
||||
|
||||
# Binary
|
||||
install -Dm755 "${{ steps.strip.outputs.BIN_PATH }}" "${DPKG_DIR}/usr/bin/${{ steps.strip.outputs.BIN_NAME }}"
|
||||
|
||||
# Man page
|
||||
install -Dm644 'doc/${{ env.PROJECT_NAME }}.1' "${DPKG_DIR}/usr/share/man/man1/${{ env.PROJECT_NAME }}.1"
|
||||
gzip -n --best "${DPKG_DIR}/usr/share/man/man1/${{ env.PROJECT_NAME }}.1"
|
||||
|
||||
# Autocompletion files
|
||||
install -Dm644 'target/${{ matrix.job.target }}/release/build/${{ env.PROJECT_NAME }}'*/out/'${{ env.PROJECT_NAME }}.bash' "${DPKG_DIR}/usr/share/bash-completion/completions/${{ env.PROJECT_NAME }}"
|
||||
install -Dm644 'target/${{ matrix.job.target }}/release/build/${{ env.PROJECT_NAME }}'*/out/'${{ env.PROJECT_NAME }}.fish' "${DPKG_DIR}/usr/share/fish/vendor_completions.d/${{ env.PROJECT_NAME }}.fish"
|
||||
install -Dm644 'contrib/completion/_fd' "${DPKG_DIR}/usr/share/zsh/vendor-completions/_${{ env.PROJECT_NAME }}"
|
||||
|
||||
# README and LICENSE
|
||||
install -Dm644 "README.md" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/README.md"
|
||||
install -Dm644 "LICENSE-MIT" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/LICENSE-MIT"
|
||||
install -Dm644 "LICENSE-APACHE" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/LICENSE-APACHE"
|
||||
install -Dm644 "CHANGELOG.md" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/changelog"
|
||||
gzip -n --best "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/changelog"
|
||||
|
||||
cat > "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/copyright" <<EOF
|
||||
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||
Upstream-Name: ${{ env.PROJECT_NAME }}
|
||||
Source: ${{ env.PROJECT_HOMEPAGE }}
|
||||
|
||||
Files: *
|
||||
Copyright: ${{ env.PROJECT_MAINTAINER }}
|
||||
Copyright: $COPYRIGHT_YEARS ${{ env.PROJECT_MAINTAINER }}
|
||||
License: Apache-2.0 or MIT
|
||||
|
||||
License: Apache-2.0
|
||||
On Debian systems, the complete text of the Apache-2.0 can be found in the
|
||||
file /usr/share/common-licenses/Apache-2.0.
|
||||
|
||||
License: MIT
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
.
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
EOF
|
||||
chmod 644 "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/copyright"
|
||||
|
||||
# control file
|
||||
mkdir -p "${DPKG_DIR}/DEBIAN"
|
||||
cat > "${DPKG_DIR}/DEBIAN/control" <<EOF
|
||||
Package: ${DPKG_BASENAME}
|
||||
Version: ${DPKG_VERSION}
|
||||
Section: utils
|
||||
Priority: optional
|
||||
Maintainer: ${{ env.PROJECT_MAINTAINER }}
|
||||
Homepage: ${{ env.PROJECT_HOMEPAGE }}
|
||||
Architecture: ${DPKG_ARCH}
|
||||
Provides: ${{ env.PROJECT_NAME }}
|
||||
Conflicts: ${DPKG_CONFLICTS}
|
||||
Description: cat(1) clone with wings.
|
||||
A cat(1) clone with syntax highlighting and Git integration.
|
||||
EOF
|
||||
|
||||
DPKG_PATH="${DPKG_STAGING}/${DPKG_NAME}"
|
||||
echo ::set-output name=DPKG_PATH::${DPKG_PATH}
|
||||
|
||||
# build dpkg
|
||||
fakeroot dpkg-deb --build "${DPKG_DIR}" "${DPKG_PATH}"
|
||||
run: bash scripts/create-deb.sh
|
||||
env:
|
||||
TARGET: ${{ matrix.job.target }}
|
||||
DPKG_VERSION: ${{ needs.crate_metadata.version }}
|
||||
BIN_PATH: ${{ steps.bin.outputs.BIN_PATH }}
|
||||
|
||||
- name: "Artifact upload: tarball"
|
||||
uses: actions/upload-artifact@master
|
||||
id: upload-tarball
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ${{ steps.package.outputs.PKG_NAME }}
|
||||
path: ${{ steps.package.outputs.PKG_PATH }}
|
||||
compression-level: 0 # tarball is already compressed
|
||||
|
||||
- name: "Artifact upload: Debian package"
|
||||
uses: actions/upload-artifact@master
|
||||
id: upload-deb
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
if: steps.debian-package.outputs.DPKG_NAME
|
||||
with:
|
||||
name: ${{ steps.debian-package.outputs.DPKG_NAME }}
|
||||
path: ${{ steps.debian-package.outputs.DPKG_PATH }}
|
||||
compression-level: 0 # deb files are already compressed
|
||||
|
||||
- name: Check for release
|
||||
id: is-release
|
||||
shell: bash
|
||||
run: |
|
||||
unset IS_RELEASE ; if [[ $GITHUB_REF =~ ^refs/tags/v[0-9].* ]]; then IS_RELEASE='true' ; fi
|
||||
echo ::set-output name=IS_RELEASE::${IS_RELEASE}
|
||||
echo "IS_RELEASE=${IS_RELEASE}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: "Attest artifacts"
|
||||
uses: actions/attest@508db95dd578ae2727ebd6217d5ba78e4fbda05d # v4
|
||||
if: steps.is-release.outputs.IS_RELEASE
|
||||
with:
|
||||
subject-path: |
|
||||
${{ steps.package.outputs.PKG_PATH }}
|
||||
${{ steps.debian-package.outputs.DPKG_PATH }}
|
||||
|
||||
- name: Publish archives and packages
|
||||
uses: softprops/action-gh-release@v1
|
||||
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2
|
||||
if: steps.is-release.outputs.IS_RELEASE
|
||||
with:
|
||||
files: |
|
||||
@@ -352,3 +263,15 @@ jobs:
|
||||
${{ steps.debian-package.outputs.DPKG_PATH }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
winget:
|
||||
name: Publish to Winget
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
steps:
|
||||
- uses: vedantmgoyal9/winget-releaser@4ffc7888bffd451b357355dc214d43bb9f23917e # v2
|
||||
with:
|
||||
identifier: sharkdp.fd
|
||||
installers-regex: '-pc-windows-msvc\.zip$'
|
||||
token: ${{ secrets.WINGET_TOKEN }}
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
target/
|
||||
/autocomplete/
|
||||
/package/
|
||||
**/*.rs.bk
|
||||
|
||||
+317
-3
@@ -1,15 +1,329 @@
|
||||
# Upcoming release
|
||||
|
||||
## Performance improvements
|
||||
# Upcoming Release
|
||||
|
||||
## Features
|
||||
-
|
||||
|
||||
## Bugfixes
|
||||
-
|
||||
|
||||
# 10.5.0
|
||||
|
||||
## Features
|
||||
- Add `--ignore-parent` option to override `--no-ignore-parent`, see #1958 (@tmchow)
|
||||
- Add `--exact` option to match the entire filename exactly (literal, non-substring).
|
||||
|
||||
## Bugfixes
|
||||
- Sanitize control characters and bidirectional override characters in filenames
|
||||
when output goes to a terminal, to prevent terminal escape-sequence injection.
|
||||
Also reject a placeholder as the executable for `--exec-batch`, while still
|
||||
allowing it for `--exec`.
|
||||
- Handle invalid working directories gracefully when using `--full-path`, see #1900 (@Xavrir).
|
||||
- Fire the "search pattern contains a path separator" diagnostic for any pattern containing `/`, not just patterns that happen to name an existing directory. Preserves the legacy Windows behaviour that also flags native `\` separators when the pattern resolves to a real directory. See #1873.
|
||||
- Also fire the "search pattern contains a path separator" diagnostic for `--and` patterns, not only the primary positional pattern. `--and` patterns are matched against the file name just like the primary pattern, so a path separator in them silently returned zero results. See #1873.
|
||||
- Fix bug where passing "-" as a directory argument didn't actually search that directory, see #849 (@Sean-Kenneth-Doherty).
|
||||
- Fix panic when `--changed-before`/`--changed-within` is given an out-of-range `@` Unix timestamp; the value is now rejected gracefully, see #2081 (@nikolauspschuetz).
|
||||
|
||||
# 10.4.2
|
||||
|
||||
## Bugfixes
|
||||
- Fixed performance regression due to `--ignore-contain`; see #1913 and #1914
|
||||
|
||||
# 10.4.1
|
||||
|
||||
This is just a re-release of 10.4.0 due to an issue with the 10.4.0 release.
|
||||
|
||||
# 10.4.0
|
||||
|
||||
## Features
|
||||
- Add `--ignore-contain` option to ignore directories containing a named entry (e.g. to ignore [`CACHEDIR.TAG`](https://bford.info/cachedir/)); see #1727 (@fischman).
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- Fix Windows hyperlink generation for paths with spaces. (#1872)
|
||||
|
||||
- `--print0` combined with `--exec` will now print a `\0` between the output of each entry. Note that if there are multiple instances
|
||||
of `--exec`, the `\0` will be between each _set_ of commands, _not_ between each individual command run. Fixes #1797.
|
||||
|
||||
- Several bugs were fixed by an update to the `ignore` library used for handling ignore rules
|
||||
- #1506
|
||||
- #1667
|
||||
- #1813
|
||||
|
||||
- Fix completions for alias `fdfind` in deb release, see #1888 (@skane-lukas)
|
||||
|
||||
## Changes
|
||||
|
||||
- Minimum required rust version has been increased to 1.90.0. Notably, this means dropping fully support for intel Mac and Windows 7.
|
||||
- Statically link the CRT for MSVC builds via Cargo config to avoid runtime DLL dependencies, see #1874 (@FidelSch)
|
||||
|
||||
# 10.3.0
|
||||
|
||||
## Features
|
||||
|
||||
- Add a hidden `--mindepth` alias for `--min-depth`. (#1617)
|
||||
|
||||
|
||||
## Bugfixes
|
||||
|
||||
|
||||
## Changes
|
||||
|
||||
- Replace `humantime` crate and `chrono` crate with `jiff` crate, see #1690 (@sorairolake). This has some small changes to the
|
||||
way dates given to options such `--changed-within` and `--changed-before` including:
|
||||
- 'M' no longer means "month", as that could be confusing with minutes. Use "mo", "mos", "month" or "months" instead.
|
||||
- month and year now account for variability in the calander rather than being a hard-coded number of seconds. That is probably
|
||||
what you would expect, but it is a slight change in behavior.
|
||||
- aarch64 Windows was added to CI and release artifacts
|
||||
- Many dependencies were updated
|
||||
- Better support building on Illumos (there is no automated testing, but some known issues were fixed)
|
||||
|
||||
## Other
|
||||
|
||||
This will be the last release that has been tested on x86_64 Mac OS, since GitHub is
|
||||
dropping support for runners with that hardware.
|
||||
|
||||
It may also be the last release to use a version of Rust with tier-1 support for
|
||||
x86_64/intel Macs and Windows 7.
|
||||
|
||||
|
||||
# 10.2.0
|
||||
|
||||
## Features
|
||||
|
||||
- Add --hyperlink option to add OSC 8 hyperlinks to output
|
||||
|
||||
|
||||
## Bugfixes
|
||||
|
||||
|
||||
## Changes
|
||||
|
||||
- Build windows releases with rust 1.77 so windows 7 is still supported
|
||||
- Deb packages now include symlink for fdfind to be more consistent with official packages
|
||||
|
||||
|
||||
## Other
|
||||
|
||||
# 10.1.0
|
||||
|
||||
## Features
|
||||
|
||||
- Allow passing an optional argument to `--strip-cwd-prefix` of "always", "never", or "auto". to force whether the cwd prefix is stripped or not.
|
||||
- Add a `--format` option which allows using a format template for direct ouput similar to the template used for `--exec`. (#1043)
|
||||
|
||||
## Bugfixes
|
||||
- Fix aarch64 page size again. This time it should actually work. (#1085, #1549) (@tavianator)
|
||||
|
||||
|
||||
## Other
|
||||
|
||||
- aarch64-apple-darwin target added to builds on the release page. Note that this is a tier 2 rust target.
|
||||
|
||||
# v10.0.0
|
||||
|
||||
## Features
|
||||
|
||||
- Add `dir` as an alias to `directory` when using `-t` \ `--type`, see #1460 and #1464 (@Ato2207).
|
||||
- Add support for @%s date format in time filters similar to GNU date (seconds since Unix epoch for --older/--newer), see #1493 (@nabellows)
|
||||
- Breaking: No longer automatically ignore `.git` when using `--hidden` with vcs ignore enabled. This reverts the change in v9.0.0. While this feature
|
||||
was often useful, it also broke some existing workflows, and there wasn't a good way to opt out of it. And there isn't really a good way for us to add
|
||||
a way to opt out of it. And you can easily get similar behavior by adding `.git/` to your global fdignore file.
|
||||
See #1457.
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- Respect NO_COLOR environment variable with `--list-details` option. (#1455)
|
||||
- Fix bug that would cause hidden files to be included despite gitignore rules
|
||||
if search path is "." (#1461, BurntSushi/ripgrep#2711).
|
||||
- aarch64 builds now use 64k page sizes with jemalloc. This fixes issues on some systems, such as ARM Macs that
|
||||
have a larger system page size than the system that the binary was built on. (#1547)
|
||||
- Address [CVE-2024-24576](https://blog.rust-lang.org/2024/04/09/cve-2024-24576.html), by increasing minimum rust version.
|
||||
|
||||
|
||||
## Changes
|
||||
- Minimum supported rust version is now 1.77.2
|
||||
|
||||
|
||||
# v9.0.0
|
||||
|
||||
## Performance
|
||||
|
||||
- Performance has been *significantly improved*, both due to optimizations in the underlying `ignore`
|
||||
crate (#1429), and in `fd` itself (#1422, #1408, #1362) - @tavianator.
|
||||
[Benchmarks results](https://gist.github.com/tavianator/32edbe052f33ef60570cf5456b59de81) show gains
|
||||
of 6-8x for full traversals of smaller directories (100k files) and up to 13x for larger directories (1M files).
|
||||
|
||||
- The default number of threads is now constrained to be at most 64. This should improve startup time on
|
||||
systems with many CPU cores. (#1203, #1410, #1412, #1431) - @tmccombs and @tavianator
|
||||
|
||||
- New flushing behavior when writing output to stdout, providing better performance for TTY and non-TTY
|
||||
use cases, see #1452 and #1313 (@tavianator).
|
||||
|
||||
## Features
|
||||
|
||||
- Support character and block device file types, see #1213 and #1336 (@cgzones)
|
||||
- Breaking: `.git/` is now ignored by default when using `--hidden` / `-H`, use `--no-ignore` / `-I` or
|
||||
`--no-ignore-vcs` to override, see #1387 and #1396 (@skoriop)
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- Fix `NO_COLOR` support, see #1421 (@acuteenvy)
|
||||
|
||||
## Other
|
||||
|
||||
- Fixed documentation typos, see #1409 (@marcospb19)
|
||||
|
||||
## Thanks
|
||||
|
||||
Special thanks to @tavianator for his incredible work on performance in the `ignore` crate and `fd` itself.
|
||||
|
||||
|
||||
|
||||
# v8.7.1
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- `-1` properly conflicts with the exec family of options.
|
||||
- `--max-results` overrides `-1`
|
||||
- `--quiet` properly conflicts with the exec family of options. This used to be the case, but broke during the switch to clap-derive
|
||||
- `--changed-within` now accepts a space as well as a "T" as the separator between date and time (due to update of chrono dependency)
|
||||
|
||||
## Other
|
||||
- Many dependencies were updated
|
||||
- Some documentation was updated and fixed
|
||||
|
||||
# v8.7.0
|
||||
|
||||
## Features
|
||||
|
||||
- Add flag --no-require-git to always respect gitignore files, see #1216 (@vegerot)
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- Fix logic for when to use global ignore file. There was a bug where the only case where the
|
||||
global ignore file wasn't processed was if `--no-ignore` was passed, but neither `--unrestricted`
|
||||
nor `--no-global-ignore-file` is passed. See #1209
|
||||
|
||||
# v8.6.0
|
||||
|
||||
## Features
|
||||
|
||||
- New `--and <pattern>` option to add additional patterns that must also be matched. See #315
|
||||
and #1139 (@Uthar)
|
||||
- Added `--changed-after` as alias for `--changed-within`, to have a name consistent with `--changed-before`.
|
||||
|
||||
|
||||
## Changes
|
||||
|
||||
- Breaking: On Unix-like systems, `--type executable` now additionally checks if
|
||||
the file is executable by the current user, see #1106 and #1169 (@ptipiak)
|
||||
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- Use fd instead of fd.exe for Powershell completions (when completions are generated on windows)
|
||||
|
||||
|
||||
## Other
|
||||
|
||||
|
||||
# v8.5.3
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- Fix completion generation to not include full path of fd command
|
||||
- Fix build error if completions feature is disabled
|
||||
|
||||
# v8.5.2
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- Fix --owner option value parsing, see #1163 and #1164 (@tmccombs)
|
||||
|
||||
|
||||
# v8.5.1
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- Fix --threads/-j option value parsing, see #1160 and #1162 (@sharkdp)
|
||||
|
||||
|
||||
# v8.5.0
|
||||
|
||||
## Features
|
||||
|
||||
- `--type executable`/`-t` now works on Windows, see #1051 and #1061 (@tavianator)
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- Fixed differences between piped / non-piped output. This changes `fd`s behavior back to what we
|
||||
had before 8.3.0, i.e. there will be no leading `./` prefixes, unless `--exec`/`-x`,
|
||||
`--exec-batch`/`-X`, or `--print0`/`-0` are used. `--strip-cwd-prefix` can be used to strip that
|
||||
prefix in those cases. See #1046, #1115, and #1121 (@tavianator)
|
||||
- `fd` could previously crash with a panic due to a race condition in Rusts standard library
|
||||
(see https://github.com/rust-lang/rust/issues/39364). This has been fixed by switching to a different
|
||||
message passing implementation, see #1060 and #1146 (@tavianator)
|
||||
- `fd`s memory usage will not grow unboundedly on huge directory trees, see #1146 (@tavianator)
|
||||
- fd returns an error when current working directory does not exist while a search path is
|
||||
specified, see #1072 (@vijfhoek)
|
||||
- Improved "command not found" error message, see #1083 and #1109 (@themkat)
|
||||
- Preserve command exit codes when using `--exec-batch`, see #1136 and #1137 (@amesgen)
|
||||
|
||||
## Changes
|
||||
|
||||
- No leading `./` prefix for non-interactive results, see above.
|
||||
- fd now colorizes paths in parallel, significantly improving performance, see #1148 (@tavianator)
|
||||
- fd can now avoid `stat` syscalls even when colorizing paths, as long as the color scheme doesn't
|
||||
require metadata, see #1148 (@tavianator)
|
||||
- The statically linked `musl` versions of `fd` now use `jmalloc`, leading to a significant performance
|
||||
improvement, see #1062 (@tavianator)
|
||||
|
||||
## Other
|
||||
|
||||
- Added link back to GitHub in man page and `--help` text, see #1086 (@scottchiefbaker)
|
||||
- Major update in how `fd` handles command line options internally, see #1067 (@tmccombs)
|
||||
|
||||
# v8.4.0
|
||||
|
||||
## Features
|
||||
|
||||
- Support multiple `--exec <cmd>` instances, see #406 and #960 (@tmccombs)
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- "Argument list too long" errors can not appear anymore when using `--exec-batch`/`-X`, as the command invocations are automatically batched at the maximum possible size, even if `--batch-size` is not given. See #410 and #1020 (@tavianator)
|
||||
|
||||
## Changes
|
||||
|
||||
- Directories are now printed with an additional path separator at the end: `foo/bar/`, see #436 and #812 (@yyogo)
|
||||
- The `-u` flag was changed to be equivalent to `-HI` (previously, a single `-u` was only equivalent to `-I`). Additional `-u` flags are still allowed, but ignored. See #840 and #986 (@jacksontheel)
|
||||
|
||||
## Other
|
||||
|
||||
- Added installation instructions for RHEL8, see #989 (@ethsol)
|
||||
|
||||
|
||||
# v8.3.2
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- Invalid absolute path on windows when searching from the drive root, see #931 and #936 (@gbarta)
|
||||
|
||||
|
||||
# v8.3.1
|
||||
|
||||
## Bugfixes
|
||||
|
||||
- Stop implying `--no-ignore-parent` when `--no-vcs-ignore` is supplied, see #907, #901, #908 (@tmccombs)
|
||||
- fd no longer waits for the whole traversal if the only matches arrive within max_buffer_time, see #868 and #895 (@tavianator)
|
||||
- `--max-results=1` now immediately quits after the first result, see #867
|
||||
- `fd -h` does not panic anymore when stdout is closed, see #897
|
||||
|
||||
## Changes
|
||||
|
||||
- Disable jemalloc on FreeBSD, see #896 (@xanderio)
|
||||
- Updated man page, see #912 (@rlue)
|
||||
- Updated zsh completions, see #932 (@tmccombs)
|
||||
|
||||
|
||||
# v8.3.0
|
||||
|
||||
+20
-3
@@ -1,6 +1,6 @@
|
||||
## Contributing to *fd*
|
||||
|
||||
**Thank you very much for considering to contribute to this project!**
|
||||
**Thank you very much for considering contributing to this project!**
|
||||
|
||||
We welcome any form of contribution:
|
||||
|
||||
@@ -10,14 +10,31 @@ We welcome any form of contribution:
|
||||
**Note**: Before you take the time to open a pull request, please open a ticket first. This will
|
||||
give us the chance to discuss any potential changes first.
|
||||
|
||||
## Pull Request Expectations
|
||||
|
||||
1. Your contribution should be high quality, and best effort. In particular, please don't make a Pull Request
|
||||
that was created using generative AI unless you have reviewed it yourself and understand what it does, and be
|
||||
able to meaningfully answer questions and make changes to it as needed.
|
||||
2. Your code should successfully compile and pass tests before publishing a Pull Request. It's understandable
|
||||
if tests fail on one or two specific targets, but if the build doesn't pass for any targets, that is a signal
|
||||
that the PR is low effort.
|
||||
3. It is your responsibility to ensure that the generated code does not violate any copyrights or patents. This is
|
||||
true of all contributions, but is especially relevant when using an LLM that may be generating output that is
|
||||
very similar or even identical to existing code with an incompatible license.
|
||||
4. If an AI coding assistant or other LLM tool was used, you must indicate that an AI tool was used, and to what extent it was used.
|
||||
5. AI should not be used to generate comments when communicating with maintainers. We expect communication with the maintainers,
|
||||
including PR descriptions and comments, to be from humans, not from an AI. Using an AI to assist with grammar, spelling, and
|
||||
proofreading or translating is acceptable, as long as the content and voice of the
|
||||
message is your own.
|
||||
|
||||
## Add an entry to the changelog
|
||||
|
||||
If your contribution changes the behavior of `fd` (as opposed to a typo-fix
|
||||
in the documentation), please update the [`CHANGELOG.md`](CHANGELOG.md) file
|
||||
in the documentation), please update the [`CHANGELOG.md`](CHANGELOG.md#upcoming-release) file
|
||||
and describe your changes. This makes the release process much easier and
|
||||
therefore helps to get your changes into a new `fd` release faster.
|
||||
|
||||
The top of the `CHANGELOG` contains a *"unreleased"* section with a few
|
||||
The top of the `CHANGELOG` contains an *"Upcoming release"* section with a few
|
||||
subsections (Features, Bugfixes, …). Please add your entry to the subsection
|
||||
that best describes your change.
|
||||
|
||||
|
||||
Generated
+854
-316
File diff suppressed because it is too large
Load Diff
+66
-29
@@ -1,10 +1,10 @@
|
||||
[package]
|
||||
authors = ["David Peter <mail@david-peter.de>"]
|
||||
build = "build.rs"
|
||||
categories = ["command-line-utilities"]
|
||||
description = "fd is a simple, fast and user-friendly alternative to find."
|
||||
exclude = ["/benchmarks/*"]
|
||||
homepage = "https://github.com/sharkdp/fd"
|
||||
documentation = "https://docs.rs/fd-find"
|
||||
keywords = [
|
||||
"search",
|
||||
"find",
|
||||
@@ -12,12 +12,13 @@ keywords = [
|
||||
"filesystem",
|
||||
"tool",
|
||||
]
|
||||
license = "MIT/Apache-2.0"
|
||||
license = "MIT OR Apache-2.0"
|
||||
name = "fd-find"
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/sharkdp/fd"
|
||||
version = "8.3.0"
|
||||
edition= "2018"
|
||||
version = "10.5.0"
|
||||
edition= "2024"
|
||||
rust-version = "1.90.0"
|
||||
|
||||
[badges.appveyor]
|
||||
repository = "sharkdp/fd"
|
||||
@@ -29,34 +30,34 @@ repository = "sharkdp/fd"
|
||||
name = "fd"
|
||||
path = "src/main.rs"
|
||||
|
||||
[build-dependencies]
|
||||
clap = "2.31.2"
|
||||
version_check = "0.9"
|
||||
|
||||
[dependencies]
|
||||
ansi_term = "0.12"
|
||||
atty = "0.2"
|
||||
ignore = "0.4.3"
|
||||
num_cpus = "1.8"
|
||||
regex = "1.5.4"
|
||||
regex-syntax = "0.6"
|
||||
ctrlc = "3.2"
|
||||
humantime = "2.1"
|
||||
lscolors = "0.8"
|
||||
aho-corasick = "1.1"
|
||||
nu-ansi-term = "0.50"
|
||||
argmax = "0.4.0"
|
||||
ignore = "0.4.25"
|
||||
regex = "1.12.2"
|
||||
regex-syntax = "0.8"
|
||||
ctrlc = "3.5"
|
||||
globset = "0.4"
|
||||
anyhow = "1.0"
|
||||
dirs-next = "2.0"
|
||||
normpath = "0.3"
|
||||
chrono = "0.4"
|
||||
once_cell = "1.8.0"
|
||||
etcetera = "0.11"
|
||||
normpath = "1.5.1"
|
||||
crossbeam-channel = "0.5.15"
|
||||
clap_complete = {version = "4.6.5", optional = true}
|
||||
faccess = "0.2.4"
|
||||
jiff = "0.2.27"
|
||||
|
||||
[dependencies.clap]
|
||||
version = "2.31.3"
|
||||
features = ["suggestions", "color", "wrap_help"]
|
||||
version = "4.6.1"
|
||||
features = ["suggestions", "color", "wrap_help", "cargo", "derive"]
|
||||
|
||||
[dependencies.lscolors]
|
||||
version = "0.21"
|
||||
default-features = false
|
||||
features = ["nu-ansi-term"]
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
users = "0.11.0"
|
||||
nix = "0.23.0"
|
||||
nix = { version = "0.31.1", default-features = false, features = ["signal", "user", "hostname"] }
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "redox")))'.dependencies]
|
||||
libc = "0.2"
|
||||
@@ -64,15 +65,51 @@ libc = "0.2"
|
||||
# FIXME: Re-enable jemalloc on macOS
|
||||
# jemalloc is currently disabled on macOS due to a bug in jemalloc in combination with macOS
|
||||
# Catalina. See https://github.com/sharkdp/fd/issues/498 for details.
|
||||
[target.'cfg(all(not(windows), not(target_os = "android"), not(target_os = "macos"), not(target_env = "musl")))'.dependencies]
|
||||
jemallocator = "0.3.0"
|
||||
# This has to be kept in sync with src/main.rs where the allocator for
|
||||
# the program is set.
|
||||
[target.'cfg(all(not(windows), not(target_os = "android"), not(target_os = "macos"), not(target_os = "freebsd"), not(target_os = "openbsd"), not(target_os = "illumos"), not(all(target_env = "musl", target_pointer_width = "32")), not(target_arch = "riscv64")))'.dependencies]
|
||||
tikv-jemallocator = {version = "0.7.0", optional = true}
|
||||
|
||||
[dev-dependencies]
|
||||
diff = "0.1"
|
||||
tempdir = "0.3"
|
||||
tempfile = "3.27"
|
||||
filetime = "0.2"
|
||||
test-case = "1.2"
|
||||
test-case = "3.3"
|
||||
|
||||
[profile.dev]
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.dev.package."*"]
|
||||
debug = false
|
||||
|
||||
[profile.debugging]
|
||||
inherits = "dev"
|
||||
debug = true
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
strip = true
|
||||
codegen-units = 1
|
||||
|
||||
[features]
|
||||
use-jemalloc = ["tikv-jemallocator"]
|
||||
completions = ["clap_complete"]
|
||||
base = ["use-jemalloc"]
|
||||
default = ["completions"]
|
||||
|
||||
[package.metadata.binstall]
|
||||
pkg-url = "{ repo }/releases/download/v{ version }/{ name }-v{ version }-{ target }.{ archive-format }"
|
||||
bin-dir = "{ bin }-v{ version }-{ target }/{ bin }{ binary-ext }"
|
||||
pkg-fmt = "tgz"
|
||||
|
||||
[package.metadata.binstall.overrides.x86_64-pc-windows-msvc]
|
||||
pkg-fmt = "zip"
|
||||
|
||||
[package.metadata.binstall.overrides.x86_64-pc-windows-gnu]
|
||||
pkg-fmt = "zip"
|
||||
|
||||
[package.metadata.binstall.overrides.i686-pc-windows-msvc]
|
||||
pkg-fmt = "zip"
|
||||
|
||||
[package.metadata.binstall.overrides.aarch64-pc-windows-msvc]
|
||||
pkg-fmt = "zip"
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
# https://github.com/sharkdp/fd/issues/1085
|
||||
[target.aarch64-unknown-linux-gnu.env]
|
||||
passthrough = ["JEMALLOC_SYS_WITH_LG_PAGE=16"]
|
||||
|
||||
[target.aarch64-unknown-linux-musl.env]
|
||||
passthrough = ["JEMALLOC_SYS_WITH_LG_PAGE=16"]
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017-2021 The fd developers
|
||||
Copyright (c) 2017-present The fd developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
PROFILE?=release
|
||||
EXE=target/$(PROFILE)/fd
|
||||
prefix=/usr/local
|
||||
bindir=$(prefix)/bin
|
||||
datadir=$(prefix)/share
|
||||
exe_name=fd
|
||||
ifdef VERSION
|
||||
ARCHIVE_NAME = fd-v$(VERSION)
|
||||
else
|
||||
ARCHIVE_NAME = fd
|
||||
endif
|
||||
export ARCHIVE_NAME
|
||||
archive_path=package/$(ARCHIVE_NAME).tar.gz
|
||||
|
||||
$(EXE): Cargo.toml src/**/*.rs
|
||||
cargo build --profile $(PROFILE) --locked
|
||||
|
||||
.PHONY: completions
|
||||
completions: autocomplete/fd.bash autocomplete/fd.fish autocomplete/_fd.ps1 autocomplete/_fd autocomplete/_fdfind autocomplete/fdfind.bash autocomplete/fdfind.fish
|
||||
|
||||
comp_dir=@mkdir -p autocomplete
|
||||
|
||||
autocomplete/fd.bash: $(EXE)
|
||||
$(comp_dir)
|
||||
$(EXE) --gen-completions bash > $@
|
||||
|
||||
autocomplete/fd.fish: $(EXE)
|
||||
$(comp_dir)
|
||||
$(EXE) --gen-completions fish > $@
|
||||
|
||||
autocomplete/_fd.ps1: $(EXE)
|
||||
$(comp_dir)
|
||||
$(EXE) --gen-completions powershell > $@
|
||||
|
||||
autocomplete/_fd: contrib/completion/_fd
|
||||
$(comp_dir)
|
||||
cp $< $@
|
||||
|
||||
autocomplete/_fdfind: contrib/completion/_fdfind
|
||||
$(comp_dir)
|
||||
cp $< $@
|
||||
|
||||
autocomplete/fdfind.bash: contrib/completion/fdfind.bash
|
||||
$(comp_dir)
|
||||
cp $< $@
|
||||
|
||||
autocomplete/fdfind.fish: contrib/completion/fdfind.fish
|
||||
$(comp_dir)
|
||||
cp $< $@
|
||||
|
||||
archive: $(archive_path)
|
||||
|
||||
$(archive_path): completions $(EXE)
|
||||
bash scripts/create-archive.sh
|
||||
|
||||
install: $(EXE) completions
|
||||
install -Dm755 $(EXE) $(DESTDIR)$(bindir)/fd
|
||||
install -Dm644 autocomplete/fd.bash $(DESTDIR)/$(datadir)/bash-completion/completions/$(exe_name)
|
||||
install -Dm644 autocomplete/fd.fish $(DESTDIR)/$(datadir)/fish/vendor_completions.d/$(exe_name).fish
|
||||
install -Dm644 autocomplete/_fd $(DESTDIR)/$(datadir)/zsh/site-functions/_fd
|
||||
install -Dm644 autocomplete/fdfind.bash $(DESTDIR)/$(datadir)/zsh/site-functions/fdfind.bash
|
||||
install -Dm644 autocomplete/fdfind.fish $(DESTDIR)/$(datadir)/zsh/site-functions/fdfind.fish
|
||||
install -Dm644 autocomplete/_fdfind $(DESTDIR)/$(datadir)/zsh/site-functions/_fdfind
|
||||
install -Dm644 doc/fd.1 $(DESTDIR)/$(datadir)/man/man1/$(exe_name).1
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[](https://github.com/sharkdp/fd/actions/workflows/CICD.yml)
|
||||
[](https://crates.io/crates/fd-find)
|
||||
[[中文](https://github.com/chinanf-boy/fd-zh)]
|
||||
[[中文](https://github.com/cha0ran/fd-zh)]
|
||||
[[한국어](https://github.com/spearkkk/fd-kor)]
|
||||
|
||||
`fd` is a program to find entries in your filesystem.
|
||||
@@ -10,17 +10,14 @@ It is a simple, fast and user-friendly alternative to [`find`](https://www.gnu.o
|
||||
While it does not aim to support all of `find`'s powerful functionality, it provides sensible
|
||||
(opinionated) defaults for a majority of use cases.
|
||||
|
||||
Quick links:
|
||||
* [How to use](#how-to-use)
|
||||
* [Installation](#installation)
|
||||
* [Troubleshooting](#troubleshooting)
|
||||
[Installation](#installation) • [How to use](#how-to-use) • [Troubleshooting](#troubleshooting)
|
||||
|
||||
## Features
|
||||
|
||||
* Intuitive syntax: `fd PATTERN` instead of `find -iname '*PATTERN*'`.
|
||||
* Regular expression (default) and glob-based patterns.
|
||||
* [Very fast](#benchmark) due to parallelized directory traversal.
|
||||
* Uses colors to highlight different file types (same as *ls*).
|
||||
* Uses colors to highlight different file types (same as `ls`).
|
||||
* Supports [parallel command execution](#command-execution)
|
||||
* Smart case: the search is case-insensitive by default. It switches to
|
||||
case-sensitive if the pattern contains an uppercase
|
||||
@@ -63,7 +60,7 @@ X11/xinit/xinitrc
|
||||
X11/xinit/xserverrc
|
||||
```
|
||||
|
||||
The regular expression syntax used by `fd` is [documented here](https://docs.rs/regex/1.0.0/regex/#syntax).
|
||||
The regular expression syntax used by `fd` is [documented here](https://docs.rs/regex/latest/regex/#syntax).
|
||||
|
||||
### Specifying the root directory
|
||||
|
||||
@@ -143,14 +140,14 @@ target/debug/deps/libnum_cpus-f5ce7ef99006aa05.rlib
|
||||
```
|
||||
|
||||
To really search *all* files and directories, simply combine the hidden and ignore features to show
|
||||
everything (`-HI`).
|
||||
everything (`-HI`) or use `-u`/`--unrestricted`.
|
||||
|
||||
### Matching the full path
|
||||
By default, *fd* only matches the filename of each file. However, using the `--full-path` or `-p` option,
|
||||
you can match against the full path.
|
||||
|
||||
```bash
|
||||
> fd -p -g '**/.git/config'
|
||||
> fd -u -p -g '**/.git/config'
|
||||
> fd -p '.*/lesson-\d+/[a-z]+.(jpg|png)'
|
||||
```
|
||||
|
||||
@@ -179,6 +176,12 @@ fd -e h -e cpp -x clang-format -i
|
||||
Note how the `-i` option to `clang-format` can be passed as a separate argument. This is why
|
||||
we put the `-x` option last.
|
||||
|
||||
Any positional arguments after `-x` belong to the command template, not to `fd` itself. If you
|
||||
also want to pass a pattern or search path, put `-x` last:
|
||||
``` bash
|
||||
fd pattern path -x echo
|
||||
```
|
||||
|
||||
Find all `test_*.py` files and open them in your favorite editor:
|
||||
``` bash
|
||||
fd -g 'test_*.py' -X vim
|
||||
@@ -206,11 +209,21 @@ fd -e jpg -x convert {} {.}.png
|
||||
Here, `{}` is a placeholder for the search result. `{.}` is the same, without the file extension.
|
||||
See below for more details on the placeholder syntax.
|
||||
|
||||
The terminal output of commands run from parallel threads using `-x` will not be interlaced or garbled,
|
||||
so `fd -x` can be used to rudimentarily parallelize a task run over many files.
|
||||
An example of this is calculating the checksum of each individual file within a directory.
|
||||
``` bash
|
||||
fd -tf -x md5sum > file_checksums.txt
|
||||
```
|
||||
|
||||
#### Placeholder syntax
|
||||
|
||||
The `-x` and `-X` options take a *command template* as a series of arguments (instead of a single string).
|
||||
If you want to add additional options to `fd` after the command template, you can terminate it with a `\;`.
|
||||
|
||||
For example, `fd -x echo \; pattern path` treats `pattern path` as `fd` arguments instead of
|
||||
passing them to `echo`. In practice, it is often clearer to write `fd pattern path -x echo`.
|
||||
|
||||
The syntax for generating commands is similar to that of [GNU Parallel](https://www.gnu.org/software/parallel/):
|
||||
|
||||
- `{}`: A placeholder token that will be replaced with the path of the search result
|
||||
@@ -254,12 +267,17 @@ To make exclude-patterns like these permanent, you can create a `.fdignore` file
|
||||
/mnt/external-drive
|
||||
*.bak
|
||||
```
|
||||
Note: `fd` also supports `.ignore` files that are used by other programs such as `rg` or `ag`.
|
||||
|
||||
> [!NOTE]
|
||||
> `fd` also supports `.ignore` files that are used by other programs such as `rg` or `ag`.
|
||||
|
||||
If you want `fd` to ignore these patterns globally, you can put them in `fd`'s global ignore file.
|
||||
This is usually located in `~/.config/fd/ignore` in macOS or Linux, and `%APPDATA%\fd\ignore` in
|
||||
Windows.
|
||||
|
||||
You may wish to include `.git/` in your `fd/ignore` file so that `.git` directories, and their contents
|
||||
are not included in output if you use the `--hidden` option.
|
||||
|
||||
### Deleting files
|
||||
|
||||
You can use `fd` to remove all files and directories that are matched by your search pattern.
|
||||
@@ -277,7 +295,8 @@ option:
|
||||
If you also want to remove a certain class of directories, you can use the same technique. You will
|
||||
have to use `rm`s `--recursive`/`-r` flag to remove directories.
|
||||
|
||||
Note: there are scenarios where using `fd … -X rm -r` can cause race conditions: if you have a
|
||||
> [!NOTE]
|
||||
> There are scenarios where using `fd … -X rm -r` can cause race conditions: if you have a
|
||||
path like `…/foo/bar/foo/…` and want to remove all directories named `foo`, you can end up in a
|
||||
situation where the outer `foo` directory is removed first, leading to (harmless) *"'foo/bar/foo':
|
||||
No such file or directory"* errors in the `rm` call.
|
||||
@@ -288,101 +307,104 @@ This is the output of `fd -h`. To see the full set of command-line options, use
|
||||
also includes a much more detailed help text.
|
||||
|
||||
```
|
||||
USAGE:
|
||||
fd [FLAGS/OPTIONS] [<pattern>] [<path>...]
|
||||
Usage: fd [OPTIONS] [pattern [path]...]
|
||||
|
||||
FLAGS:
|
||||
-H, --hidden Search hidden files and directories
|
||||
-I, --no-ignore Do not respect .(git|fd)ignore files
|
||||
-s, --case-sensitive Case-sensitive search (default: smart case)
|
||||
-i, --ignore-case Case-insensitive search (default: smart case)
|
||||
-g, --glob Glob-based search (default: regular expression)
|
||||
-a, --absolute-path Show absolute instead of relative paths
|
||||
-l, --list-details Use a long listing format with file metadata
|
||||
-L, --follow Follow symbolic links
|
||||
-p, --full-path Search full abs. path (default: filename only)
|
||||
-h, --help Prints help information
|
||||
-V, --version Prints version information
|
||||
Arguments:
|
||||
[pattern] the search pattern (a regular expression, unless '--glob' is used; optional)
|
||||
[path]... the root directories for the filesystem search (optional)
|
||||
|
||||
OPTIONS:
|
||||
-d, --max-depth <depth> Set maximum search depth (default: none)
|
||||
-t, --type <filetype>... Filter by type: file (f), directory (d), symlink (l),
|
||||
executable (x), empty (e), socket (s), pipe (p)
|
||||
-e, --extension <ext>... Filter by file extension
|
||||
-x, --exec <cmd> Execute a command for each search result
|
||||
-X, --exec-batch <cmd> Execute a command with all search results at once
|
||||
-E, --exclude <pattern>... Exclude entries that match the given glob pattern
|
||||
-c, --color <when> When to use colors: never, *auto*, always
|
||||
-S, --size <size>... Limit results based on the size of files
|
||||
--changed-within <date|dur> Filter by file modification time (newer than)
|
||||
--changed-before <date|dur> Filter by file modification time (older than)
|
||||
-o, --owner <user:group> Filter by owning user and/or group
|
||||
|
||||
ARGS:
|
||||
<pattern> the search pattern (a regular expression, unless '--glob' is used; optional)
|
||||
<path>... the root directory for the filesystem search (optional)
|
||||
Options:
|
||||
-H, --hidden Search hidden files and directories
|
||||
-I, --no-ignore Do not respect .(git|fd)ignore files
|
||||
-s, --case-sensitive Case-sensitive search (default: smart case)
|
||||
-i, --ignore-case Case-insensitive search (default: smart case)
|
||||
-g, --glob Glob-based search (default: regular expression)
|
||||
-a, --absolute-path Show absolute instead of relative paths
|
||||
-l, --list-details Use a long listing format with file metadata
|
||||
-L, --follow Follow symbolic links
|
||||
-p, --full-path Search full abs. path (default: filename only)
|
||||
-d, --max-depth <depth> Set maximum search depth (default: none)
|
||||
-E, --exclude <glob> Exclude entries that match the given glob pattern
|
||||
-t, --type <filetype> Filter by type: file (f), directory (d/dir), symlink (l),
|
||||
executable (x), empty (e), socket (s), pipe (p), char-device
|
||||
(c), block-device (b)
|
||||
-e, --extension <ext> Filter by extension
|
||||
-S, --size <size> Limit results based on the size of files
|
||||
--changed-within <date|dur> Filter by file modification time (newer than)
|
||||
--changed-before <date|dur> Filter by file modification time (older than)
|
||||
-o, --owner <user:group> Filter by owning user and/or group
|
||||
--format <fmt> Print results according to template
|
||||
-x, --exec <cmd>... Execute a command for each search result
|
||||
-X, --exec-batch <cmd>... Execute a command with all search results at once
|
||||
-c, --color <when> When to use colors [default: auto] [possible values: auto,
|
||||
always, never]
|
||||
--hyperlink[=<when>] Add hyperlinks to output paths [default: never] [possible
|
||||
values: auto, always, never]
|
||||
--ignore-contain <name> Ignore directories containing the named entry
|
||||
-h, --help Print help (see more with '--help')
|
||||
-V, --version Print version
|
||||
```
|
||||
|
||||
Note that options can be given after the pattern and/or path as well.
|
||||
|
||||
## Benchmark
|
||||
|
||||
Let's search my home folder for files that end in `[0-9].jpg`. It contains ~190.000
|
||||
subdirectories and about a million files. For averaging and statistical analysis, I'm using
|
||||
Let's search my home folder for files that end in `[0-9].jpg`. It contains ~750,000
|
||||
subdirectories and about a 4 million files. For averaging and statistical analysis, I'm using
|
||||
[hyperfine](https://github.com/sharkdp/hyperfine). The following benchmarks are performed
|
||||
with a "warm"/pre-filled disk-cache (results for a "cold" disk-cache show the same trends).
|
||||
|
||||
Let's start with `find`:
|
||||
```
|
||||
Benchmark #1: find ~ -iregex '.*[0-9]\.jpg$'
|
||||
|
||||
Time (mean ± σ): 7.236 s ± 0.090 s
|
||||
|
||||
Range (min … max): 7.133 s … 7.385 s
|
||||
Benchmark 1: find ~ -iregex '.*[0-9]\.jpg$'
|
||||
Time (mean ± σ): 19.922 s ± 0.109 s
|
||||
Range (min … max): 19.765 s … 20.065 s
|
||||
```
|
||||
|
||||
`find` is much faster if it does not need to perform a regular-expression search:
|
||||
```
|
||||
Benchmark #2: find ~ -iname '*[0-9].jpg'
|
||||
|
||||
Time (mean ± σ): 3.914 s ± 0.027 s
|
||||
|
||||
Range (min … max): 3.876 s … 3.964 s
|
||||
Benchmark 2: find ~ -iname '*[0-9].jpg'
|
||||
Time (mean ± σ): 11.226 s ± 0.104 s
|
||||
Range (min … max): 11.119 s … 11.466 s
|
||||
```
|
||||
|
||||
Now let's try the same for `fd`. Note that `fd` *always* performs a regular expression
|
||||
search. The options `--hidden` and `--no-ignore` are needed for a fair comparison,
|
||||
otherwise `fd` does not have to traverse hidden folders and ignored paths (see below):
|
||||
Now let's try the same for `fd`. Note that `fd` performs a regular expression
|
||||
search by default. The options `-u`/`--unrestricted` option is needed here for
|
||||
a fair comparison. Otherwise `fd` does not have to traverse hidden folders and
|
||||
ignored paths (see below):
|
||||
```
|
||||
Benchmark #3: fd -HI '.*[0-9]\.jpg$' ~
|
||||
|
||||
Time (mean ± σ): 811.6 ms ± 26.9 ms
|
||||
|
||||
Range (min … max): 786.0 ms … 870.7 ms
|
||||
Benchmark 3: fd -u '[0-9]\.jpg$' ~
|
||||
Time (mean ± σ): 854.8 ms ± 10.0 ms
|
||||
Range (min … max): 839.2 ms … 868.9 ms
|
||||
```
|
||||
For this particular example, `fd` is approximately nine times faster than `find -iregex`
|
||||
and about five times faster than `find -iname`. By the way, both tools found the exact
|
||||
same 20880 files :smile:.
|
||||
For this particular example, `fd` is approximately **23 times faster** than `find -iregex`
|
||||
and about **13 times faster** than `find -iname`. By the way, both tools found the exact
|
||||
same 546 files :smile:.
|
||||
|
||||
Finally, let's run `fd` without `--hidden` and `--no-ignore` (this can lead to different
|
||||
search results, of course). If *fd* does not have to traverse the hidden and git-ignored
|
||||
folders, it is almost an order of magnitude faster:
|
||||
```
|
||||
Benchmark #4: fd '[0-9]\.jpg$' ~
|
||||
|
||||
Time (mean ± σ): 123.7 ms ± 6.0 ms
|
||||
|
||||
Range (min … max): 118.8 ms … 140.0 ms
|
||||
```
|
||||
|
||||
**Note**: This is *one particular* benchmark on *one particular* machine. While I have
|
||||
performed quite a lot of different tests (and found consistent results), things might
|
||||
be different for you! I encourage everyone to try it out on their own. See
|
||||
**Note**: This is *one particular* benchmark on *one particular* machine. While we have
|
||||
performed a lot of different tests (and found consistent results), things might
|
||||
be different for you! We encourage everyone to try it out on their own. See
|
||||
[this repository](https://github.com/sharkdp/fd-benchmarks) for all necessary scripts.
|
||||
|
||||
Concerning *fd*'s speed, the main credit goes to the `regex` and `ignore` crates that are also used
|
||||
in [ripgrep](https://github.com/BurntSushi/ripgrep) (check it out!).
|
||||
Concerning *fd*'s speed, a lot of credit goes to the `regex` and `ignore` crates that are
|
||||
also used in [ripgrep](https://github.com/BurntSushi/ripgrep) (check it out!).
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### `fd` does not find my file!
|
||||
|
||||
Remember that `fd` ignores hidden directories and files by default. It also ignores patterns
|
||||
from `.gitignore` files. If you want to make sure to find absolutely every possible file, always
|
||||
use the options `-u`/`--unrestricted` option (or `-HI` to enable hidden and ignored files):
|
||||
``` bash
|
||||
> fd -u …
|
||||
```
|
||||
|
||||
Also remember that by default, `fd` only searches based on the filename and
|
||||
doesn't compare the pattern to the full path. If you want to search based on the
|
||||
full path (similar to the `-path` option of `find`) you need to use the `--full-path`
|
||||
(or `-p`) option.
|
||||
|
||||
### Colorized output
|
||||
|
||||
`fd` can colorize files by extension, just like `ls`. In order for this to work, the environment
|
||||
@@ -396,15 +418,6 @@ for alternative, more complete (or more colorful) variants, see [here](https://g
|
||||
|
||||
`fd` also honors the [`NO_COLOR`](https://no-color.org/) environment variable.
|
||||
|
||||
### `fd` does not find my file!
|
||||
|
||||
Remember that `fd` ignores hidden directories and files by default. It also ignores patterns
|
||||
from `.gitignore` files. If you want to make sure to find absolutely every possible file, always
|
||||
use the options `-H` and `-I` to disable these two features:
|
||||
``` bash
|
||||
> fd -HI …
|
||||
```
|
||||
|
||||
### `fd` doesn't seem to interpret my regex pattern correctly
|
||||
|
||||
A lot of special regex characters (like `[]`, `^`, `$`, ..) are also special characters in your
|
||||
@@ -431,6 +444,11 @@ you can use `export -f my_function` to make available to child processes. You wo
|
||||
need to call `fd -x bash -c 'my_function "$1"' bash`. For other use cases or shells, use
|
||||
a (temporary) shell script.
|
||||
|
||||
### Placeholders in `-x`/`-X`
|
||||
|
||||
Depending on your shell, you may need to quote the placeholders (`{}`, `{/}`, `{//}`,
|
||||
`{.}`, `{/.}`) to prevent the shell from interpreting them before `fd` sees them.
|
||||
|
||||
## Integration with other programs
|
||||
|
||||
### Using fd with `fzf`
|
||||
@@ -483,16 +501,17 @@ In emacs, run `M-x find-file-in-project-by-selected` to find matching files. Alt
|
||||
|
||||
### Printing the output as a tree
|
||||
|
||||
To format the output of `fd` similar to the `tree` command, install [`as-tree`] and pipe the output
|
||||
of `fd` to `as-tree`:
|
||||
To format the output of `fd` as a file-tree you can use the `tree` command with
|
||||
`--fromfile`:
|
||||
```bash
|
||||
fd | as-tree
|
||||
❯ fd | tree --fromfile
|
||||
```
|
||||
|
||||
This can be more useful than running `tree` by itself because `tree` does not ignore any files by
|
||||
default, nor does it support as rich a set of options as `fd` does to control what to print:
|
||||
This can be more useful than running `tree` by itself because `tree` does not
|
||||
ignore any files by default, nor does it support as rich a set of options as
|
||||
`fd` does to control what to print:
|
||||
```bash
|
||||
❯ fd --extension rs | as-tree
|
||||
❯ fd --extension rs | tree --fromfile
|
||||
.
|
||||
├── build.rs
|
||||
└── src
|
||||
@@ -500,9 +519,10 @@ default, nor does it support as rich a set of options as `fd` does to control wh
|
||||
└── error.rs
|
||||
```
|
||||
|
||||
For more information about `as-tree`, see [the `as-tree` README][`as-tree`].
|
||||
|
||||
[`as-tree`]: https://github.com/jez/as-tree
|
||||
On bash and similar you can simply create an alias:
|
||||
```bash
|
||||
❯ alias as-tree='tree --fromfile'
|
||||
```
|
||||
|
||||
### Using fd with `xargs` or `parallel`
|
||||
|
||||
@@ -525,7 +545,7 @@ newlines). In the same way, the `-0` option of `xargs` tells it to read the inpu
|
||||
If you run Ubuntu 19.04 (Disco Dingo) or newer, you can install the
|
||||
[officially maintained package](https://packages.ubuntu.com/fd-find):
|
||||
```
|
||||
sudo apt install fd-find
|
||||
apt install fd-find
|
||||
```
|
||||
Note that the binary is called `fdfind` as the binary name `fd` is already used by another package.
|
||||
It is recommended that after installation, you add a link to `fd` by executing command
|
||||
@@ -535,21 +555,25 @@ Make sure that `$HOME/.local/bin` is in your `$PATH`.
|
||||
If you use an older version of Ubuntu, you can download the latest `.deb` package from the
|
||||
[release page](https://github.com/sharkdp/fd/releases) and install it via:
|
||||
``` bash
|
||||
sudo dpkg -i fd_8.3.0_amd64.deb # adapt version number and architecture
|
||||
dpkg -i fd_9.0.0_amd64.deb # adapt version number and architecture
|
||||
```
|
||||
|
||||
Note that the .deb packages on the release page for this project still name the executable `fd`.
|
||||
|
||||
### On Debian
|
||||
|
||||
If you run Debian Buster or newer, you can install the
|
||||
[officially maintained Debian package](https://tracker.debian.org/pkg/rust-fd-find):
|
||||
```
|
||||
sudo apt-get install fd-find
|
||||
apt-get install fd-find
|
||||
```
|
||||
Note that the binary is called `fdfind` as the binary name `fd` is already used by another package.
|
||||
It is recommended that after installation, you add a link to `fd` by executing command
|
||||
`ln -s $(which fdfind) ~/.local/bin/fd`, in order to use `fd` in the same way as in this documentation.
|
||||
Make sure that `$HOME/.local/bin` is in your `$PATH`.
|
||||
|
||||
Note that the .deb packages on the release page for this project still name the executable `fd`.
|
||||
|
||||
### On Fedora
|
||||
|
||||
Starting with Fedora 28, you can install `fd` from the official package sources:
|
||||
@@ -557,12 +581,6 @@ Starting with Fedora 28, you can install `fd` from the official package sources:
|
||||
dnf install fd-find
|
||||
```
|
||||
|
||||
For older versions, you can use this [Fedora copr](https://copr.fedorainfracloud.org/coprs/keefle/fd/) to install `fd`:
|
||||
``` bash
|
||||
dnf copr enable keefle/fd
|
||||
dnf install fd
|
||||
```
|
||||
|
||||
### On Alpine Linux
|
||||
|
||||
You can install [the fd package](https://pkgs.alpinelinux.org/packages?name=fd)
|
||||
@@ -573,10 +591,12 @@ apk add fd
|
||||
|
||||
### On Arch Linux
|
||||
|
||||
You can install [the fd package](https://www.archlinux.org/packages/community/x86_64/fd/) from the official repos:
|
||||
You can install [the fd package](https://www.archlinux.org/packages/extra/x86_64/fd/) from the official repos:
|
||||
```
|
||||
pacman -S fd
|
||||
```
|
||||
You can also install fd [from the AUR](https://aur.archlinux.org/packages/fd-git).
|
||||
|
||||
### On Gentoo Linux
|
||||
|
||||
You can use [the fd ebuild](https://packages.gentoo.org/packages/sys-apps/fd) from the official repo:
|
||||
@@ -598,6 +618,31 @@ You can install `fd` via xbps-install:
|
||||
xbps-install -S fd
|
||||
```
|
||||
|
||||
### On ALT Linux
|
||||
|
||||
You can install [the fd package](https://packages.altlinux.org/en/sisyphus/srpms/fd/) from the official repo:
|
||||
```
|
||||
apt-get install fd
|
||||
```
|
||||
|
||||
### On Solus
|
||||
|
||||
You can install [the fd package](https://github.com/getsolus/packages/tree/main/packages/f/fd) from the official repo:
|
||||
```
|
||||
eopkg install fd
|
||||
```
|
||||
|
||||
### On RedHat Enterprise Linux (RHEL) 8/9/10, Almalinux 8/9/10, EuroLinux 8/9 or Rocky Linux 8/9/10
|
||||
|
||||
You can install [the `fd` package](https://copr.fedorainfracloud.org/coprs/tkbcopr/fd/) from Fedora Copr.
|
||||
|
||||
```bash
|
||||
dnf copr enable tkbcopr/fd
|
||||
dnf install fd
|
||||
```
|
||||
|
||||
A different version using the [slower](https://github.com/sharkdp/fd/pull/481#issuecomment-534494592) malloc [instead of jemalloc](https://bugzilla.redhat.com/show_bug.cgi?id=2216193#c1) is also available from the EPEL8/9 repo as the package `fd-find`.
|
||||
|
||||
### On macOS
|
||||
|
||||
You can install `fd` with [Homebrew](https://formulae.brew.sh/formula/fd):
|
||||
@@ -607,7 +652,7 @@ brew install fd
|
||||
|
||||
… or with MacPorts:
|
||||
```
|
||||
sudo port install fd
|
||||
port install fd
|
||||
```
|
||||
|
||||
### On Windows
|
||||
@@ -624,6 +669,25 @@ Or via [Chocolatey](https://chocolatey.org):
|
||||
choco install fd
|
||||
```
|
||||
|
||||
Or via [Winget](https://learn.microsoft.com/en-us/windows/package-manager/):
|
||||
```
|
||||
winget install sharkdp.fd
|
||||
```
|
||||
|
||||
### On GuixOS
|
||||
|
||||
You can install [the fd package](https://guix.gnu.org/en/packages/fd-8.1.1/) from the official repo:
|
||||
```
|
||||
guix install fd
|
||||
```
|
||||
|
||||
### On Mise
|
||||
|
||||
You can use [mise](https://github.com/jdx/mise) to install `fd` with a command like this:
|
||||
```
|
||||
mise use -g fd@latest
|
||||
```
|
||||
|
||||
### On NixOS / via Nix
|
||||
|
||||
You can use the [Nix package manager](https://nixos.org/nix/) to install `fd`:
|
||||
@@ -631,6 +695,13 @@ You can use the [Nix package manager](https://nixos.org/nix/) to install `fd`:
|
||||
nix-env -i fd
|
||||
```
|
||||
|
||||
### Via Flox
|
||||
|
||||
You can use [Flox](https://flox.dev) to install `fd` into a Flox environment:
|
||||
```
|
||||
flox install fd
|
||||
```
|
||||
|
||||
### On FreeBSD
|
||||
|
||||
You can install [the fd-find package](https://www.freshports.org/sysutils/fd) from the official repo:
|
||||
@@ -640,7 +711,7 @@ pkg install fd-find
|
||||
|
||||
### From npm
|
||||
|
||||
On linux and macOS, you can install the [fd-find](https://npm.im/fd-find) package:
|
||||
On Linux and macOS, you can install the [fd-find](https://npm.im/fd-find) package:
|
||||
|
||||
```
|
||||
npm install -g fd-find
|
||||
@@ -652,7 +723,7 @@ With Rust's package manager [cargo](https://github.com/rust-lang/cargo), you can
|
||||
```
|
||||
cargo install fd-find
|
||||
```
|
||||
Note that rust version *1.53.0* or later is required.
|
||||
Note that rust version *1.90.0* or later is required.
|
||||
|
||||
`make` is also needed for the build.
|
||||
|
||||
@@ -675,6 +746,37 @@ cargo test
|
||||
cargo install --path .
|
||||
```
|
||||
|
||||
### Completions
|
||||
|
||||
#### From Release Archives
|
||||
|
||||
Pre-built completion files are included in the release archives (`.tar.gz`/`.zip`) on the
|
||||
[Releases page](https://github.com/sharkdp/fd/releases), in the `autocomplete` directory.
|
||||
To use these completions:
|
||||
|
||||
- **bash**: Source the `fd.bash` file in your `~/.bashrc`, or place it in a directory that gets sourced automatically.
|
||||
- **zsh**: Move `_fd` to a directory in your `fpath` (e.g., `~/.zfunc`).
|
||||
- **fish**: Copy `fd.fish` to `~/.config/fish/completions/`.
|
||||
- **powershell**: Source `_fd.ps1` from one of your [profile scripts](https://learn.microsoft.com/en-us/powershell/scripting/learn/shell/creating-profiles?view=powershell-7.5).
|
||||
|
||||
#### Generate from fd
|
||||
|
||||
You can also generate completions directly using `fd --gen-completions <shell>`:
|
||||
|
||||
```bash
|
||||
# Bash
|
||||
fd --gen-completions bash > ~/.local/share/bash-completion/completions/fd
|
||||
|
||||
# Zsh (ensure ~/.zfunc is in your fpath)
|
||||
fd --gen-completions zsh > ~/.zfunc/_fd
|
||||
|
||||
# Fish
|
||||
fd --gen-completions fish > ~/.config/fish/completions/fd.fish
|
||||
|
||||
# PowerShell
|
||||
fd --gen-completions powershell >> $PROFILE
|
||||
```
|
||||
|
||||
## Maintainers
|
||||
|
||||
- [sharkdp](https://github.com/sharkdp)
|
||||
@@ -683,8 +785,6 @@ cargo install --path .
|
||||
|
||||
## License
|
||||
|
||||
Copyright (c) 2017-2021 The fd developers
|
||||
|
||||
`fd` is distributed under the terms of both the MIT License and the Apache License 2.0.
|
||||
|
||||
See the [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT) files for license details.
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
# Security Reporting
|
||||
|
||||
If you wish to report a security vulnerability privately, we appreciate your diligence. Please follow the guidelines below to submit your report.
|
||||
|
||||
## Reporting
|
||||
|
||||
To report a security vulnerability, please provide the following information:
|
||||
|
||||
1. **PROJECT**
|
||||
- Include the URL of the project repository - Example: <https://github.com/sharkdp/fd>
|
||||
|
||||
2. **PUBLIC**
|
||||
- Indicate whether this vulnerability has already been publicly discussed or disclosed.
|
||||
- If so, provide relevant links.
|
||||
|
||||
3. **DESCRIPTION**
|
||||
- Provide a detailed description of the security vulnerability.
|
||||
- Include as much information as possible to help us understand and address the issue.
|
||||
|
||||
Send this information, along with any additional relevant details, to our [vulnerability reporting form](https://github.com/sharkdp/fd/security/advisories/new).
|
||||
|
||||
## Confidentiality
|
||||
|
||||
We kindly ask you to keep the report confidential until a public announcement is made.
|
||||
|
||||
## Notes
|
||||
|
||||
- Vulnerabilities will be handled on a best-effort basis.
|
||||
- You may request an advance copy of the patched release, but we cannot guarantee early access before the public release.
|
||||
- You will be notified via email simultaneously with the public announcement.
|
||||
- We will respond within a few weeks to confirm whether your report has been accepted or rejected.
|
||||
|
||||
Thank you for helping to improve the security of our project!
|
||||
@@ -1,30 +0,0 @@
|
||||
use std::fs;
|
||||
|
||||
use clap::Shell;
|
||||
|
||||
include!("src/app.rs");
|
||||
|
||||
fn main() {
|
||||
let min_version = "1.53";
|
||||
|
||||
match version_check::is_min_version(min_version) {
|
||||
Some(true) => {}
|
||||
// rustc version too small or can't figure it out
|
||||
_ => {
|
||||
eprintln!("'fd' requires rustc >= {}", min_version);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
let var = std::env::var_os("SHELL_COMPLETIONS_DIR").or_else(|| std::env::var_os("OUT_DIR"));
|
||||
let outdir = match var {
|
||||
None => return,
|
||||
Some(outdir) => outdir,
|
||||
};
|
||||
fs::create_dir_all(&outdir).unwrap();
|
||||
|
||||
let mut app = build_app();
|
||||
app.gen_completions("fd", Shell::Bash, &outdir);
|
||||
app.gen_completions("fd", Shell::Fish, &outdir);
|
||||
app.gen_completions("fd", Shell::PowerShell, &outdir);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
msrv = "1.53.0"
|
||||
+18
-2
@@ -26,6 +26,8 @@ _fd() {
|
||||
{l,symlink}'\:"symbolic links"'
|
||||
{e,empty}'\:"empty files or directories"'
|
||||
{x,executable}'\:"executable (files)"'
|
||||
{b,block-device}'\:"block devices"'
|
||||
{c,char-device}'\:"character devices"'
|
||||
{s,socket}'\:"sockets"'
|
||||
{p,pipe}'\:"named pipes (FIFOs)"'
|
||||
)
|
||||
@@ -36,7 +38,7 @@ _fd() {
|
||||
# for all of the potential negation options listed below!
|
||||
if
|
||||
# (--[bpsu]* => match all options marked with '$no')
|
||||
[[ $PREFIX$SUFFIX == --[bopsu]* ]] ||
|
||||
[[ $PREFIX$SUFFIX == --[bopsun]* ]] ||
|
||||
zstyle -t ":complete:$curcontext:*" complete-all
|
||||
then
|
||||
no=
|
||||
@@ -57,6 +59,7 @@ _fd() {
|
||||
+ no-ignore-partial # some ignore files
|
||||
"(no-ignore-full --no-ignore-vcs)--no-ignore-vcs[don't respect .gitignore files]"
|
||||
"!(no-ignore-full --no-global-ignore-file)--no-global-ignore-file[don't respect the global ignore file]"
|
||||
$no'(no-ignore-full --no-ignore-parent)--no-ignore-parent[]'
|
||||
|
||||
+ '(case)' # case-sensitivity
|
||||
{-s,--case-sensitive}'[perform a case-sensitive search]'
|
||||
@@ -69,6 +72,9 @@ _fd() {
|
||||
{-g,--glob}'[perform a glob-based search]'
|
||||
{-F,--fixed-strings}'[treat pattern as literal string instead of a regex]'
|
||||
|
||||
+ '(no-require-git)'
|
||||
"$no(no-ignore-full --no-ignore-vcs --no-require-git)--no-require-git[don't require git repo to respect gitignores]"
|
||||
|
||||
+ '(match-full)' # match against full path
|
||||
{-p,--full-path}'[match the pattern against the full path instead of the basename]'
|
||||
|
||||
@@ -117,6 +123,7 @@ _fd() {
|
||||
|
||||
+ '(filter-mtime-newer)' # filter by files modified after than
|
||||
'--changed-within=[limit search to files/directories modified within the given date/duration]:date or duration'
|
||||
'--changed-after=[alias for --changed-within]:date/duration'
|
||||
'!--change-newer-than=:date/duration'
|
||||
'!--newer=:date/duration'
|
||||
|
||||
@@ -132,6 +139,8 @@ _fd() {
|
||||
always\:"always use colorized output"
|
||||
))'
|
||||
|
||||
'--hyperlink=-[add hyperlinks to output paths]::when:(auto never always)'
|
||||
|
||||
+ '(threads)'
|
||||
{-j+,--threads=}'[set the number of threads for searching and executing]:number of threads'
|
||||
|
||||
@@ -145,7 +154,7 @@ _fd() {
|
||||
|
||||
+ '(about)' # about flags
|
||||
'(: * -)'{-h,--help}'[display help message]'
|
||||
'(: * -)'{-v,--version}'[display version information]'
|
||||
'(: * -)'{-V,--version}'[display version information]'
|
||||
|
||||
+ path-sep # set path separator for output
|
||||
$no'(--path-separator)--path-separator=[set the path separator to use when printing file paths]:path separator'
|
||||
@@ -154,6 +163,13 @@ _fd() {
|
||||
$no'(--base-directory)--base-directory=[change the current working directory to the given path]:directory:_files -/'
|
||||
$no'(*)*--search-path=[set search path (instead of positional <path> arguments)]:directory:_files -/'
|
||||
|
||||
+ strip-cwd-prefix
|
||||
$no'(strip-cwd-prefix exec-cmds)--strip-cwd-prefix=-[When to strip ./]::when:(always never auto)'
|
||||
|
||||
+ and
|
||||
'--and=[additional required search path]:pattern'
|
||||
|
||||
|
||||
+ args # positional arguments
|
||||
'1: :_guard "^-*" pattern'
|
||||
'(--search-path)*:directory:_files -/'
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
#compdef fdfind
|
||||
_fd "$@"
|
||||
@@ -0,0 +1,8 @@
|
||||
# Source fd completions
|
||||
source /usr/share/bash-completion/completions/fd
|
||||
|
||||
if [[ "${BASH_VERSINFO[0]}" -eq 4 && "${BASH_VERSINFO[1]}" -ge 4 || "${BASH_VERSINFO[0]}" -gt 4 ]]; then
|
||||
complete -F _fd -o nosort -o bashdefault -o default fdfind
|
||||
else
|
||||
complete -F _fd -o bashdefault -o default fdfind
|
||||
fi
|
||||
@@ -0,0 +1 @@
|
||||
complete -c fdfind --wraps fd
|
||||
@@ -18,17 +18,36 @@ fd \- find entries in the filesystem
|
||||
.IR num ]
|
||||
.RB [ \-x
|
||||
.IR cmd ]
|
||||
.RI [ pattern ]
|
||||
.RI [ path... ]
|
||||
.RI [ pattern
|
||||
.RI [ path... ]]
|
||||
.SH DESCRIPTION
|
||||
.B fd
|
||||
is a simple, fast and user-friendly alternative to
|
||||
.BR find (1).
|
||||
.P
|
||||
By default
|
||||
.B fd
|
||||
uses regular expressions for the pattern. However, this can be changed to use simple glob patterns
|
||||
with the '\-\-glob' option.
|
||||
.P
|
||||
By default
|
||||
.B fd
|
||||
will exclude hidden files and directories, as well as any files that match gitignore rules
|
||||
or ignore rules in .ignore or .fdignore files.
|
||||
.P
|
||||
If you wish to search all files in a specific directory, you can use '' or . as the search pattern,
|
||||
to match all files. Or you can use the '\-\-search\-path' option to specify the path(s) instead of
|
||||
the positional parameter.
|
||||
.P
|
||||
Options may be given anywhere on the command line.
|
||||
.SH OPTIONS
|
||||
.TP
|
||||
.B \-H, \-\-hidden
|
||||
Include hidden files and directories in the search results
|
||||
(default: hidden files and directories are skipped). The flag can be overridden with '--no-hidden'.
|
||||
.IP
|
||||
Ignored files are still excluded unless \-\-no\-ignore or \-\-no\-ignore\-vcs
|
||||
is also used.
|
||||
.TP
|
||||
.B \-I, \-\-no\-ignore
|
||||
Show search results from files and directories that would otherwise be ignored by
|
||||
@@ -53,7 +72,7 @@ The global fd ignore file (usually
|
||||
The flag can be overridden with '--ignore'.
|
||||
.TP
|
||||
.B \-u, \-\-unrestricted
|
||||
Alias for '--no-ignore'. Can be repeated; '-uu' is an alias for '--no-ignore --hidden'.
|
||||
Perform an unrestricted search, including ignored and hidden files. This is an alias for '--hidden --no-ignore'.
|
||||
.TP
|
||||
.B \-\-no\-ignore\-vcs
|
||||
Show search results from files and directories that would otherwise be ignored by gitignore files
|
||||
@@ -66,6 +85,18 @@ git setting, which defaults to
|
||||
.IR $HOME/.config/git/ignore ).
|
||||
The flag can be overridden with '--ignore-vcs'.
|
||||
.TP
|
||||
.B \-\-no\-require\-git
|
||||
Do not require a git repository to respect gitignores. By default, fd will only
|
||||
respect global gitignore rules, .gitignore rules and local exclude rules if fd
|
||||
detects that you are searching inside a git repository. This flag allows you to
|
||||
relax this restriction such that fd will respect all git related ignore rules
|
||||
regardless of whether you’re searching in a git repository or not. The flag can
|
||||
be overridden with '--require-git'.
|
||||
.TP
|
||||
.B \-\-no\-ignore\-parent
|
||||
Show search results from files and directories that would otherwise be ignored by gitignore files in
|
||||
parent directories.
|
||||
.TP
|
||||
.B \-s, \-\-case\-sensitive
|
||||
Perform a case-sensitive search. By default, fd uses case-insensitive searches, unless the
|
||||
pattern contains an uppercase character (smart case).
|
||||
@@ -83,7 +114,19 @@ Perform a regular-expression based search (default). This can be used to overrid
|
||||
.TP
|
||||
.B \-F, \-\-fixed\-strings
|
||||
Treat the pattern as a literal string instead of a regular expression. Note that this also
|
||||
performs substring comparison. If you want to match on an exact filename, consider using '\-\-glob'.
|
||||
performs substring comparison. If you want to match on an exact filename, consider using '\-\-glob'
|
||||
or '\-\-exact'.
|
||||
.TP
|
||||
.B \-\-exact
|
||||
Perform an exact match. This is equivalent to '\-\-fixed\-strings' but requires the pattern to
|
||||
match the entire filename (or the full path if '\-\-full\-path' is used), rather than a substring.
|
||||
Special regex characters in the pattern are treated as literal characters.
|
||||
Cannot be used together with '\-\-glob' or '\-\-fixed\-strings'.
|
||||
.TP
|
||||
.BI "\-\-and " pattern
|
||||
Add additional required search patterns, all of which must be matched. Multiple additional
|
||||
patterns can be specified. The patterns are regular expressions, unless '\-\-glob'
|
||||
or '\-\-fixed\-strings' is used.
|
||||
.TP
|
||||
.B \-a, \-\-absolute\-path
|
||||
Shows the full path starting from the root as opposed to relative paths.
|
||||
@@ -126,6 +169,21 @@ can be used as an alias.
|
||||
Enable the display of filesystem errors for situations such as insufficient
|
||||
permissions or dead symlinks.
|
||||
.TP
|
||||
.B \-\-strip-cwd-prefix [when]
|
||||
By default, relative paths are prefixed with './' when -x/--exec,
|
||||
-X/--exec-batch, or -0/--print0 are given, to reduce the risk of a
|
||||
path starting with '-' being treated as a command line option. Use
|
||||
this flag to change this behavior. If this flag is used without a value,
|
||||
it is equivalent to passing "always". Possible values are:
|
||||
.RS
|
||||
.IP never
|
||||
Never strip the ./ at the beginning of paths
|
||||
.IP always
|
||||
Always strip the ./ at the beginning of paths
|
||||
.IP auto
|
||||
Only strip if used with --exec, --exec-batch, or --print0. That is, it resets to the default behavior.
|
||||
.RE
|
||||
.TP
|
||||
.B \-\-one\-file\-system, \-\-mount, \-\-xdev
|
||||
By default, fd will traverse the file system tree as far as other options dictate. With this flag, fd ensures that it does not descend into a different file system than the one it started in. Comparable to the -mount or -xdev filters of find(1).
|
||||
.TP
|
||||
@@ -154,10 +212,14 @@ Filter search by type:
|
||||
.RS
|
||||
.IP "f, file"
|
||||
regular files
|
||||
.IP "d, directory"
|
||||
.IP "d, dir, directory"
|
||||
directories
|
||||
.IP "l, symlink"
|
||||
symbolic links
|
||||
.IP "b, block-device"
|
||||
block devices
|
||||
.IP "c, char-device"
|
||||
character devices
|
||||
.IP "s, socket"
|
||||
sockets
|
||||
.IP "p, pipe"
|
||||
@@ -195,14 +257,16 @@ Examples:
|
||||
.RE
|
||||
.TP
|
||||
.BI "\-e, \-\-extension " ext
|
||||
Filter search results by file extension
|
||||
Filter search results by extension
|
||||
.IR ext .
|
||||
This option can be used repeatedly to allow for multiple possible file extensions.
|
||||
This option can be used repeatedly to allow for multiple possible extensions.
|
||||
By default, extension filters apply to both files and directories. Use
|
||||
\fB\-\-type\fR to restrict the search to specific types.
|
||||
|
||||
If you want to search for files without extension, you can use the regex '^[^.]+$'
|
||||
as a normal search pattern.
|
||||
.TP
|
||||
.BI "\-E, \-\-exclude " pattern
|
||||
.BI "\-E, \-\-exclude " glob
|
||||
Exclude files/directories that match the given glob pattern.
|
||||
This overrides any other ignore logic.
|
||||
Multiple exclude patterns can be specified.
|
||||
@@ -210,6 +274,10 @@ Examples:
|
||||
\-\-exclude '*.pyc'
|
||||
\-\-exclude node_modules
|
||||
.TP
|
||||
.BI "\-\-ignore-contain " name
|
||||
Exclude directories that (directly) contain the given name.
|
||||
This option can be specified multiple times.
|
||||
.TP
|
||||
.BI "\-\-ignore-file " path
|
||||
Add a custom ignore-file in '.gitignore' format.
|
||||
These files have a low precedence.
|
||||
@@ -227,6 +295,24 @@ Do not colorize output.
|
||||
Always colorize output.
|
||||
.RE
|
||||
.TP
|
||||
.B "\-\-hyperlink
|
||||
Specify whether the output should use terminal escape codes to indicate a hyperlink to a
|
||||
file url pointing to the path.
|
||||
|
||||
The value can be auto, always, or never.
|
||||
|
||||
Currently, the default is "never", and if the option is used without an argument "auto" is
|
||||
used. In the future this may be changed to "auto" and "always".
|
||||
.RS
|
||||
.IP auto
|
||||
Only output hyperlinks if color is also enabled, as a proxy for whether terminal escape
|
||||
codes are acceptable.
|
||||
.IP never
|
||||
Never output hyperlink escapes.
|
||||
.IP always
|
||||
Always output hyperlink escapes, regardless of color settings.
|
||||
.RE
|
||||
.TP
|
||||
.BI "\-j, \-\-threads " num
|
||||
Set number of threads to use for searching & executing (default: number of available CPU cores).
|
||||
.TP
|
||||
@@ -269,29 +355,39 @@ tebibytes
|
||||
.TP
|
||||
.BI "\-\-changed-within " date|duration
|
||||
Filter results based on the file modification time.
|
||||
Files with modification times greater than the argument will be returned.
|
||||
Files with modification timestamps greater than the argument will be returned.
|
||||
The argument can be provided as a duration (\fI10h, 1d, 35min\fR) or as a specific point
|
||||
in time in either full RFC3339 format with time zone, or as a date or datetime in the
|
||||
local time zone (\fIYYYY-MM-DD\fR or \fIYYYY-MM-DD HH:MM:SS\fR).
|
||||
.B --change-newer-than
|
||||
can be used as an alias.
|
||||
in time as full RFC3339 format with time zone, as a date or datetime in the
|
||||
local time zone (\fIYYYY-MM-DD\fR or \fIYYYY-MM-DD HH:MM:SS\fR), or as the prefix '@'
|
||||
followed by the number of seconds since the Unix epoch (@[0-9]+).
|
||||
\fB\-\-change-newer-than\fR,
|
||||
.B --newer
|
||||
or
|
||||
.B --changed-after
|
||||
can be used as aliases.
|
||||
|
||||
Examples:
|
||||
\-\-changed-within 2weeks
|
||||
\-\-change-newer-than "2018-10-27 10:00:00"
|
||||
\-\-newer 2018-10-27
|
||||
\-\-changed-after @1704067200
|
||||
.TP
|
||||
.BI "\-\-changed-before " date|duration
|
||||
Filter results based on the file modification time.
|
||||
Files with modification times less than the argument will be returned.
|
||||
Files with modification timestamps less than the argument will be returned.
|
||||
The argument can be provided as a duration (\fI10h, 1d, 35min\fR) or as a specific point
|
||||
in time in either full RFC3339 format with time zone, or as a date or datetime in the
|
||||
local time zone (\fIYYYY-MM-DD\fR or \fIYYYY-MM-DD HH:MM:SS\fR).
|
||||
in time as full RFC3339 format with time zone, as a date or datetime in the
|
||||
local time zone (\fIYYYY-MM-DD\fR or \fIYYYY-MM-DD HH:MM:SS\fR), or as the prefix '@'
|
||||
followed by the number of seconds since the Unix epoch (@[0-9]+).
|
||||
.B --change-older-than
|
||||
can be used as an alias.
|
||||
or
|
||||
.B --older
|
||||
can be used as aliases.
|
||||
|
||||
Examples:
|
||||
\-\-changed-before "2018-10-27 10:00:00"
|
||||
\-\-change-older-than 2weeks
|
||||
\-\-older @1704067200
|
||||
.TP
|
||||
.BI "-o, \-\-owner " [user][:group]
|
||||
Filter files by their user and/or group. Format: [(user|uid)][:(group|gid)]. Either side
|
||||
@@ -302,7 +398,7 @@ Examples:
|
||||
\-\-owner :students
|
||||
\-\-owner "!john:students"
|
||||
.TP
|
||||
.BI "\-\-base\-directory " path
|
||||
.BI "-C, \-\-base\-directory " path
|
||||
Change the current working directory of fd to the provided path. This means that search results will
|
||||
be shown with respect to the given base path. Note that relative paths which are passed to fd via the
|
||||
positional \fIpath\fR argument or the \fB\-\-search\-path\fR option will also be resolved relative to
|
||||
@@ -316,6 +412,30 @@ Set the path separator to use when printing file paths. The default is the OS-sp
|
||||
Provide paths to search as an alternative to the positional \fIpath\fR argument. Changes the usage to
|
||||
\'fd [FLAGS/OPTIONS] \-\-search\-path PATH \-\-search\-path PATH2 [PATTERN]\'
|
||||
.TP
|
||||
.BI "\-\-format " fmt
|
||||
Specify a template string that is used for printing a line for each file found.
|
||||
|
||||
The following placeholders are substituted into the string for each file before printing:
|
||||
.RS
|
||||
.IP {}
|
||||
path (of the current search result)
|
||||
.IP {/}
|
||||
basename
|
||||
.IP {//}
|
||||
parent directory
|
||||
.IP {.}
|
||||
path without file extension
|
||||
.IP {/.}
|
||||
basename without file extension
|
||||
.IP {{
|
||||
literal '{' (an escape sequence)
|
||||
.IP }}
|
||||
literal '}' (an escape sequence)
|
||||
.P
|
||||
Notice that you can use "{{" and "}}" to escape "{" and "}" respectively, which is especially
|
||||
useful if you need to include the literal text of one of the above placeholders.
|
||||
.RE
|
||||
.TP
|
||||
.BI "\-x, \-\-exec " command
|
||||
.RS
|
||||
Execute
|
||||
@@ -328,23 +448,23 @@ Note that all subsequent positional arguments are considered to be arguments to
|
||||
It is therefore recommended to place the \-x/\-\-exec option last. Alternatively, you can supply
|
||||
a ';' argument to end the argument list and continue with more fd options.
|
||||
Most shells require ';' to be escaped: '\\;'.
|
||||
This option can be specified multiple times, in which case all commands are run for each
|
||||
file found, in the order they are provided. In that case, you must supply a ';' argument for
|
||||
all but the last commands.
|
||||
|
||||
The following placeholders are substituted before the command is executed:
|
||||
.RS
|
||||
.IP {}
|
||||
path (of the current search result)
|
||||
.IP {/}
|
||||
basename
|
||||
.IP {//}
|
||||
parent directory
|
||||
.IP {.}
|
||||
path without file extension
|
||||
.IP {/.}
|
||||
basename without file extension
|
||||
.RE
|
||||
If parallelism is enabled, the order commands will be executed in is non-deterministic. And even with
|
||||
--threads=1, the order is determined by the operating system and may not be what you expect. Thus, it is
|
||||
recommended that you don't rely on any ordering of the results.
|
||||
|
||||
Before executing the command, any placeholder patterns in the command are replaced with the
|
||||
corresponding values for the current file. The same placeholders are used as in the "\-\-format"
|
||||
option.
|
||||
|
||||
If no placeholder is present, an implicit "{}" at the end is assumed.
|
||||
|
||||
If --print0 is also given, then a null character (\\0) will be printed between the output for each found entry.
|
||||
This allows another program to easily distinguish the output for each file if the command(s) produce multiple lines.
|
||||
|
||||
Examples:
|
||||
|
||||
- find all *.zip files and unzip them:
|
||||
@@ -358,6 +478,10 @@ Examples:
|
||||
- Convert all *.jpg files to *.png files:
|
||||
|
||||
fd -e jpg -x convert {} {.}.png
|
||||
|
||||
- Run stat for each *.txt file, separated by null characters
|
||||
|
||||
fd -0 -e txt -x stat
|
||||
.RE
|
||||
.TP
|
||||
.BI "\-X, \-\-exec-batch " command
|
||||
@@ -365,22 +489,22 @@ Examples:
|
||||
Execute
|
||||
.I command
|
||||
once, with all search results as arguments.
|
||||
One of the following placeholders is substituted before the command is executed:
|
||||
.RS
|
||||
.IP {}
|
||||
path (of all search results)
|
||||
.IP {/}
|
||||
basename
|
||||
.IP {//}
|
||||
parent directory
|
||||
.IP {.}
|
||||
path without file extension
|
||||
.IP {/.}
|
||||
basename without file extension
|
||||
.RE
|
||||
|
||||
The order of the arguments is non-deterministic and should not be relied upon.
|
||||
|
||||
This uses the same placeholders as "\-\-format" and "\-\-exec", but instead of expanding
|
||||
once per command invocation each argument containing a placeholder is expanding for every
|
||||
file in a batch and passed as separate arguments.
|
||||
|
||||
If no placeholder is present, an implicit "{}" at the end is assumed.
|
||||
|
||||
Like \-\-exec, subsequent arguments are assumed to be part of
|
||||
.I command
|
||||
until either the end of command arguments or a ';' argument. See above.
|
||||
|
||||
Like \-\-exec, this can be used multiple times, in which case each command will be run in
|
||||
the order given.
|
||||
|
||||
Examples:
|
||||
|
||||
- Find all test_*.py files and open them in your favorite editor:
|
||||
@@ -393,7 +517,12 @@ Examples:
|
||||
|
||||
fd -e rs -X wc -l
|
||||
.RE
|
||||
|
||||
.TP
|
||||
.BI "\-\-batch-size " size
|
||||
Maximum number of arguments to pass to the command given with -X. If the number of results is
|
||||
greater than the given size, the command given with -X is run again with remaining arguments. A
|
||||
batch size of zero means there is no limit (default), but note that batching might still happen
|
||||
due to OS restrictions on the maximum length of command lines.
|
||||
.SH PATTERN SYNTAX
|
||||
The regular expression syntax used by fd is documented here:
|
||||
|
||||
@@ -418,6 +547,17 @@ is set, use
|
||||
.IR $XDG_CONFIG_HOME/fd/ignore .
|
||||
Otherwise, use
|
||||
.IR $HOME/.config/fd/ignore .
|
||||
.SH FILES
|
||||
.TP
|
||||
.B .fdignore
|
||||
This file works similarly to a .gitignore file anywhere in the searched tree and specifies patterns
|
||||
that should be excluded from the search. However, this file is specific to fd, and will be used even
|
||||
if the --no-ignore-vcs option is used.
|
||||
.TP
|
||||
.B $XDG_CONFIG_HOME/fd/ignore
|
||||
Global ignore file. Unless ignore mode is turned off (such as with --no-ignore)
|
||||
ignore entries in this file will be ignored, as if it was an .fdignore file in the
|
||||
current directory.
|
||||
.SH EXAMPLES
|
||||
.TP
|
||||
.RI "Find files and directories that match the pattern '" needle "':"
|
||||
@@ -431,11 +571,17 @@ $ fd -e py
|
||||
.TP
|
||||
.RI "Open all search results with vim:"
|
||||
$ fd pattern -X vim
|
||||
.TP
|
||||
.BI "\-\-batch\-size " size
|
||||
Pass at most
|
||||
.I size
|
||||
arguments to each call to the command given with -X.
|
||||
.TP
|
||||
.SH Tips and Tricks
|
||||
.IP \[bu]
|
||||
If you add ".git/" to your global ignore file ($XDG_CONFIG_HOME/fd/ignore), then
|
||||
".git" folders will be ignored by default, even when the --hidden option is used.
|
||||
.IP \[bu]
|
||||
You can use a shell alias or a wrapper script in order to pass desired flags to fd
|
||||
by default. For example if you do not like the default behavior of respecting gitignore,
|
||||
you can use
|
||||
`alias fd="/usr/bin/fd --no-ignore-vcs"`
|
||||
in your .bashrc to create an alias for fd that doesn't ignore git files by default.
|
||||
.SH BUGS
|
||||
Bugs can be reported on GitHub: https://github.com/sharkdp/fd/issues
|
||||
.SH SEE ALSO
|
||||
.BR find (1)
|
||||
|
||||
Vendored
BIN
Binary file not shown.
|
After Width: | Height: | Size: 9.9 KiB |
Vendored
+161
@@ -0,0 +1,161 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
width="66mm"
|
||||
height="66mm"
|
||||
viewBox="0 0 66 66.000001"
|
||||
version="1.1"
|
||||
id="svg5"
|
||||
inkscape:version="1.1 (c4e8f9ed74, 2021-05-24)"
|
||||
sodipodi:docname="logo.svg"
|
||||
inkscape:export-filename="/home/shark/Informatik/rust/fd/doc/logo.png"
|
||||
inkscape:export-xdpi="192.42"
|
||||
inkscape:export-ydpi="192.42"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<sodipodi:namedview
|
||||
id="namedview7"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#999999"
|
||||
borderopacity="1"
|
||||
inkscape:pageshadow="0"
|
||||
inkscape:pageopacity="1"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:document-units="mm"
|
||||
showgrid="false"
|
||||
inkscape:zoom="2.1795515"
|
||||
inkscape:cx="114.47309"
|
||||
inkscape:cy="176.18304"
|
||||
inkscape:window-width="1920"
|
||||
inkscape:window-height="1175"
|
||||
inkscape:window-x="1920"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="layer1"
|
||||
showguides="false"
|
||||
inkscape:guide-bbox="true"
|
||||
inkscape:snap-global="false"
|
||||
fit-margin-top="2"
|
||||
fit-margin-left="2"
|
||||
fit-margin-right="2"
|
||||
fit-margin-bottom="2"
|
||||
lock-margins="true">
|
||||
<sodipodi:guide
|
||||
position="26.228232,26.126763"
|
||||
orientation="0,-1"
|
||||
id="guide47826" />
|
||||
<sodipodi:guide
|
||||
position="25.799494,2.3628924"
|
||||
orientation="0,-1"
|
||||
id="guide47828" />
|
||||
</sodipodi:namedview>
|
||||
<defs
|
||||
id="defs2" />
|
||||
<g
|
||||
inkscape:label="Ebene 1"
|
||||
inkscape:groupmode="layer"
|
||||
id="layer1"
|
||||
transform="translate(-21.358009,-148.28012)">
|
||||
<g
|
||||
id="g66267"
|
||||
transform="matrix(0.84959471,0,0,0.84959471,7.9920783,43.351816)">
|
||||
<text
|
||||
xml:space="preserve"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:29.7126px;line-height:0;font-family:'Fira Sans Condensed';-inkscape-font-specification:'Fira Sans Condensed, ';white-space:pre;inline-size:37.3715;fill:#e5e5e5;fill-opacity:1;stroke-width:0.742816"
|
||||
x="50.647034"
|
||||
y="173.19841"
|
||||
id="text50653"
|
||||
transform="matrix(1.0604862,0,0,1.0604862,-3.3101428,-10.150043)"><tspan
|
||||
x="50.647034"
|
||||
y="173.19841"
|
||||
id="tspan66635"><tspan
|
||||
style="font-family:'Source Code Pro';-inkscape-font-specification:'Source Code Pro'"
|
||||
id="tspan66633">fd</tspan></tspan></text>
|
||||
<text
|
||||
xml:space="preserve"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:29.7126px;line-height:0;font-family:'Fira Sans Condensed';-inkscape-font-specification:'Fira Sans Condensed, ';white-space:pre;inline-size:37.3715;fill:#00ccff;fill-opacity:0.996078;stroke-width:0.742816"
|
||||
x="50.647034"
|
||||
y="173.19841"
|
||||
id="text1244"
|
||||
transform="matrix(1.0604862,0,0,1.0604862,-2.8008599,-9.6407599)"><tspan
|
||||
x="50.647034"
|
||||
y="173.19841"
|
||||
id="tspan66639"><tspan
|
||||
style="font-family:'Source Code Pro';-inkscape-font-specification:'Source Code Pro'"
|
||||
id="tspan66637">fd</tspan></tspan></text>
|
||||
<g
|
||||
id="g47824"
|
||||
transform="translate(0.1724878,-0.35338542)">
|
||||
<g
|
||||
id="g42041">
|
||||
<path
|
||||
style="fill:none;stroke:#939dac;stroke-width:1.065;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
d="m 28.209616,155.51329 v 15.68758 H 40.83001"
|
||||
id="path39763"
|
||||
sodipodi:nodetypes="ccc" />
|
||||
<path
|
||||
style="fill:#b7bec8;stroke:#939dac;stroke-width:1.065;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
d="M 27.869464,161.83767 H 40.261291"
|
||||
id="path39765" />
|
||||
</g>
|
||||
<g
|
||||
id="g41945"
|
||||
transform="translate(-1.0583333)">
|
||||
<path
|
||||
style="fill:#0088aa;fill-opacity:0.993797;stroke:none;stroke-width:0.265;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
d="m 42.164961,159.42939 -1.554274,-1.89462 -1.975227,-0.005 c -0.941841,0.014 -1.165466,0.27232 -1.14085,2.88812 z"
|
||||
id="path40006"
|
||||
sodipodi:nodetypes="ccccc" />
|
||||
<rect
|
||||
style="fill:#01ccff;fill-opacity:1;stroke:none;stroke-width:2.3;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0.80126;paint-order:stroke fill markers"
|
||||
id="rect39949"
|
||||
width="9.4925022"
|
||||
height="6.2080379"
|
||||
x="37.492516"
|
||||
y="158.82776"
|
||||
ry="0.90871465" />
|
||||
</g>
|
||||
<g
|
||||
id="g41951"
|
||||
transform="translate(-1.0583334,9.3665773)">
|
||||
<path
|
||||
style="fill:#373e48;fill-opacity:0.993797;stroke:none;stroke-width:0.265;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
d="m 42.164961,159.42939 -1.554274,-1.89462 -1.975227,-0.005 c -0.941841,0.014 -1.165466,0.27232 -1.14085,2.88812 z"
|
||||
id="path41947"
|
||||
sodipodi:nodetypes="ccccc" />
|
||||
<rect
|
||||
style="fill:#535d6c;fill-opacity:0.993797;stroke:none;stroke-width:2.3;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0.80126;paint-order:stroke fill markers"
|
||||
id="rect41949"
|
||||
width="9.4925022"
|
||||
height="6.2080379"
|
||||
x="37.492516"
|
||||
y="158.82776"
|
||||
ry="0.90871465" />
|
||||
</g>
|
||||
<g
|
||||
id="g41957"
|
||||
transform="translate(-14.306994,-6.8962642)">
|
||||
<path
|
||||
style="fill:#373e48;fill-opacity:0.993797;stroke:none;stroke-width:0.265;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||
d="m 42.164961,159.42939 -1.554274,-1.89462 -1.975227,-0.005 c -0.941841,0.014 -1.165466,0.27232 -1.14085,2.88812 z"
|
||||
id="path41953"
|
||||
sodipodi:nodetypes="ccccc" />
|
||||
<rect
|
||||
style="fill:#535d6c;fill-opacity:0.993797;stroke:none;stroke-width:2.3;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0.80126;paint-order:stroke fill markers"
|
||||
id="rect41955"
|
||||
width="9.4925022"
|
||||
height="6.2080379"
|
||||
x="37.492516"
|
||||
y="158.82776"
|
||||
ry="0.90871465" />
|
||||
</g>
|
||||
</g>
|
||||
<g
|
||||
id="g65006"
|
||||
transform="matrix(0.55302761,0,0,0.55302761,66.463548,117.45819)" />
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.8 KiB |
Vendored
+69
@@ -0,0 +1,69 @@
|
||||
# Release checklist
|
||||
|
||||
This file can be used as-is, or copied into the GitHub PR description which includes
|
||||
necessary changes for the upcoming release.
|
||||
|
||||
## Version bump
|
||||
|
||||
This section can be done by running `scripts/version-bump.sh` with the new version
|
||||
as an argument.
|
||||
|
||||
- [ ] Create a new branch for the required changes for this release.
|
||||
- [ ] Update version in `Cargo.toml`. Run `cargo build` to update `Cargo.lock`.
|
||||
Make sure to `git add` the `Cargo.lock` changes as well.
|
||||
- [ ] Find the current min. supported Rust version by running
|
||||
`grep rust-version Cargo.toml`.
|
||||
- [ ] Update the `fd` version and the min. supported Rust version in `README.md`.
|
||||
- [ ] Update `CHANGELOG.md`. Change the heading of the *"Upcoming release"* section
|
||||
to the version of this release.
|
||||
|
||||
## Pre-release checks and updates
|
||||
|
||||
- [ ] Install the latest version (`cargo install --locked -f --path .`) and make
|
||||
sure that it is available on the `PATH` (`fd --version` should show the
|
||||
new version).
|
||||
- [ ] Review `-h`, `--help`, and the `man` page.
|
||||
- [ ] Run `fd -h` and copy the output to the *"Command-line options"* section in
|
||||
the README. This can be done by running `gawk -i inplace -f scripts/update-help.awk README.md`.
|
||||
- [ ] Push all changes and wait for CI to succeed (before continuing with the
|
||||
next section).
|
||||
- [ ] Optional: manually test the new features and command-line options described
|
||||
in the `CHANGELOG.md`.
|
||||
- [ ] Run `cargo publish --dry-run` to make sure that it will succeed later
|
||||
(after creating the GitHub release).
|
||||
|
||||
## Release
|
||||
|
||||
- [ ] Merge your release branch (should be a fast-forward merge).
|
||||
- [ ] Create a tag and push it: `git tag vX.Y.Z; git push origin tag vX.Y.Z`.
|
||||
This will trigger the deployment via GitHub Actions.
|
||||
REMINDER: If your `origin` is a fork, don't forget to push to e.g. `upstream`
|
||||
instead.
|
||||
- [ ] Go to https://github.com/sharkdp/fd/releases/new to create the new
|
||||
release. Select the new tag and also use it as the release title. For the
|
||||
release notes, copy the corresponding section from `CHANGELOG.md` and
|
||||
possibly add additional remarks for package maintainers.
|
||||
Publish the release.
|
||||
- [ ] Check if the binary deployment works (archives and Debian packages should
|
||||
appear when the CI run *for the Git tag* has finished).
|
||||
- [ ] Publish to crates.io by running `cargo publish` in a *clean* repository.
|
||||
One way to do this is to clone a fresh copy.
|
||||
|
||||
## Post-release
|
||||
|
||||
- [ ] Prepare a new *"Upcoming release"* section at the top of `CHANGELOG.md`.
|
||||
Put this at the top:
|
||||
|
||||
# Upcoming release
|
||||
|
||||
## Features
|
||||
|
||||
|
||||
## Bugfixes
|
||||
|
||||
|
||||
## Changes
|
||||
|
||||
|
||||
## Other
|
||||
|
||||
Vendored
+6
-2
@@ -1,6 +1,8 @@
|
||||
#!/bin/bash
|
||||
# Designed to be executed via svg-term from the fd root directory:
|
||||
# svg-term --command="bash doc/screencast.sh" --out doc/screencast.svg --padding=10
|
||||
# Then run this (workaround for #1003):
|
||||
# sed -i '' 's/<text/<text font-size="1.67"/g' doc/screencast.svg
|
||||
set -e
|
||||
set -u
|
||||
|
||||
@@ -34,9 +36,11 @@ main() {
|
||||
|
||||
enter "fd app"
|
||||
|
||||
enter "fd sh"
|
||||
enter "fd fi"
|
||||
|
||||
enter "fd sh --type f"
|
||||
enter "fd fi --type f"
|
||||
|
||||
enter "fd --type d"
|
||||
|
||||
enter "fd -e md"
|
||||
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 115 KiB After Width: | Height: | Size: 124 KiB |
Vendored
+12
@@ -0,0 +1,12 @@
|
||||
## Sponsors
|
||||
|
||||
`fd` development is sponsored by many individuals and companies. Thank you very much!
|
||||
|
||||
Please note, that being sponsored does not affect the individuality of the `fd`
|
||||
project or affect the maintainers' actions in any way.
|
||||
We remain impartial and continue to assess pull requests solely on merit - the
|
||||
features added, bugs solved, and effect on the overall complexity of the code.
|
||||
No issue will have a different priority based on sponsorship status of the
|
||||
reporter.
|
||||
|
||||
Contributions from anybody are most welcomed, please see our [`CONTRIBUTING.md`](../CONTRIBUTING.md) guide.
|
||||
@@ -0,0 +1 @@
|
||||
# Defaults are used
|
||||
Executable
+67
@@ -0,0 +1,67 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Create a .tar.gz archive of the fd project for distribution
|
||||
#
|
||||
# Expected environment variables:
|
||||
#
|
||||
# TARGET: rust target to publish. Defaults to default rustc target
|
||||
# BIN_PATH: path to fd binary
|
||||
# PKG_STAGING: directory to use for staging files to include in the archive
|
||||
# ARCHIVE_NAME: Name of output file, minus extension, defaults to "fd" with a version appended
|
||||
# if VERSION is specified
|
||||
# VERSION: version to publish
|
||||
# GITHUB_OUTPUT: file to store github output variables in
|
||||
|
||||
if [[ -z "$TARGET" ]]; then
|
||||
TARGET="$(rustc -vV | sed -n 's/host: //p')"
|
||||
fi
|
||||
|
||||
PKG_suffix=".tar.gz"
|
||||
EXE_suffix=""
|
||||
case ${TARGET} in
|
||||
*-pc-windows-*)
|
||||
PKG_suffix=".zip"
|
||||
EXE_suffix=".exe"
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ -z $BIN_PATH ]]; then
|
||||
BIN_PATH=target/${PROFILE:-release}/fd
|
||||
fi
|
||||
|
||||
if [[ -z "$ARCHIVE_NAME" ]]; then
|
||||
ARCHIVE_NAME=fd
|
||||
[[ -n "$VERSION" ]] && ARCHIVE_NAME+="-v$VERSION"
|
||||
fi
|
||||
|
||||
PKG_NAME=${ARCHIVE_NAME}${PKG_suffix}
|
||||
|
||||
staging_dir="${PKG_STAGING:-package}"
|
||||
ARCHIVE_DIR="${staging_dir}/${ARCHIVE_NAME}/"
|
||||
mkdir -p "${ARCHIVE_DIR}"
|
||||
|
||||
# Binary
|
||||
cp "${BIN_PATH}" "$ARCHIVE_DIR"
|
||||
|
||||
# README, LICENSE and CHANGELOG files
|
||||
cp "README.md" "LICENSE-MIT" "LICENSE-APACHE" "CHANGELOG.md" "$ARCHIVE_DIR"
|
||||
|
||||
# Man page
|
||||
cp "doc/fd.1" "$ARCHIVE_DIR"
|
||||
|
||||
# Autocompletion files
|
||||
cp -r autocomplete "${ARCHIVE_DIR}"
|
||||
|
||||
# base compressed package
|
||||
pushd "${staging_dir}/" >/dev/null
|
||||
case ${TARGET} in
|
||||
*-pc-windows-*) 7z -y a "${PKG_NAME}" "${ARCHIVE_NAME}"/* | tail -2 ;;
|
||||
*) tar czf "${PKG_NAME}" "${ARCHIVE_NAME}"/* ;;
|
||||
esac;
|
||||
popd >/dev/null
|
||||
|
||||
if [[ -n "$GITHUB_OUTPUT" ]]; then
|
||||
echo "PKG_NAME=${PKG_NAME}" >> $GITHUB_OUTPUT
|
||||
# Let subsequent steps know where to find the compressed package
|
||||
echo "PKG_PATH=${PKG_STAGING}/${PKG_NAME}" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
Executable
+135
@@ -0,0 +1,135 @@
|
||||
#!/bin/bash
|
||||
COPYRIGHT_YEARS="2018 - "$(date "+%Y")
|
||||
MAINTAINER="David Peter <mail@david-peter.de>"
|
||||
REPO="https://github.com/sharkdp/fd"
|
||||
DPKG_STAGING="${CICD_INTERMEDIATES_DIR:-.}/debian-package"
|
||||
DPKG_DIR="${DPKG_STAGING}/dpkg"
|
||||
mkdir -p "${DPKG_DIR}"
|
||||
|
||||
if [[ -z "$TARGET" ]]; then
|
||||
TARGET="$(rustc -vV | sed -n 's|host: \(.*\)|\1|p')"
|
||||
fi
|
||||
|
||||
case "$TARGET" in
|
||||
*-musl*)
|
||||
DPKG_BASENAME=fd-musl
|
||||
DPKG_CONFLICTS="fd, fd-find"
|
||||
;;
|
||||
*)
|
||||
DPKG_BASENAME=fd
|
||||
DPKG_CONFLICTS="fd-musl, fd-find"
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ -z "$DPKG_VERSION" ]]; then
|
||||
DPKG_VERSION=$(cargo metadata --no-deps --format-version 1 | jq -r .packages[0].version)
|
||||
fi
|
||||
|
||||
unset DPKG_ARCH
|
||||
case "${TARGET}" in
|
||||
aarch64-*-linux-*) DPKG_ARCH=arm64 ;;
|
||||
arm-*-linux-*hf) DPKG_ARCH=armhf ;;
|
||||
i686-*-linux-*) DPKG_ARCH=i686 ;;
|
||||
x86_64-*-linux-*) DPKG_ARCH=amd64 ;;
|
||||
*) DPKG_ARCH=notset ;;
|
||||
esac;
|
||||
|
||||
DPKG_NAME="${DPKG_BASENAME}_${DPKG_VERSION}_${DPKG_ARCH}.deb"
|
||||
|
||||
BIN_PATH=${BIN_PATH:-target/${TARGET}/release/fd}
|
||||
|
||||
# Binary
|
||||
install -Dm755 "${BIN_PATH}" "${DPKG_DIR}/usr/bin/fd"
|
||||
|
||||
# Man page
|
||||
install -Dm644 'doc/fd.1' "${DPKG_DIR}/usr/share/man/man1/fd.1"
|
||||
gzip -n --best "${DPKG_DIR}/usr/share/man/man1/fd.1"
|
||||
|
||||
# Autocompletion files
|
||||
install -Dm644 'autocomplete/fd.bash' "${DPKG_DIR}/usr/share/bash-completion/completions/fd"
|
||||
install -Dm644 'autocomplete/fd.fish' "${DPKG_DIR}/usr/share/fish/vendor_completions.d/fd.fish"
|
||||
install -Dm644 'autocomplete/_fd' "${DPKG_DIR}/usr/share/zsh/vendor-completions/_fd"
|
||||
|
||||
# README and LICENSE
|
||||
install -Dm644 "README.md" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/README.md"
|
||||
install -Dm644 "LICENSE-MIT" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/LICENSE-MIT"
|
||||
install -Dm644 "LICENSE-APACHE" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/LICENSE-APACHE"
|
||||
install -Dm644 "CHANGELOG.md" "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/changelog"
|
||||
gzip -n --best "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/changelog"
|
||||
|
||||
# Create symlink and completions so fdfind can be used as well:
|
||||
ln -s "/usr/bin/fd" "${DPKG_DIR}/usr/bin/fdfind"
|
||||
|
||||
install -Dm644 'autocomplete/fdfind.bash' "${DPKG_DIR}/usr/share/bash-completion/completions/fdfind"
|
||||
install -Dm644 'autocomplete/fdfind.fish' "${DPKG_DIR}/usr/share/fish/vendor_completions.d/fdfind.fish"
|
||||
install -Dm644 'autocomplete/_fdfind' "${DPKG_DIR}/usr/share/zsh/vendor-completions/_fdfind"
|
||||
|
||||
cat > "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/copyright" <<EOF
|
||||
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||
Upstream-Name: fd
|
||||
Source: ${REPO}
|
||||
|
||||
Files: *
|
||||
Copyright: ${MAINTAINER}
|
||||
Copyright: $COPYRIGHT_YEARS ${MAINTAINER}
|
||||
License: Apache-2.0 or MIT
|
||||
|
||||
License: Apache-2.0
|
||||
On Debian systems, the complete text of the Apache-2.0 can be found in the
|
||||
file /usr/share/common-licenses/Apache-2.0.
|
||||
|
||||
License: MIT
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
.
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
EOF
|
||||
chmod 644 "${DPKG_DIR}/usr/share/doc/${DPKG_BASENAME}/copyright"
|
||||
|
||||
# control file
|
||||
mkdir -p "${DPKG_DIR}/DEBIAN"
|
||||
cat > "${DPKG_DIR}/DEBIAN/control" <<EOF
|
||||
Package: ${DPKG_BASENAME}
|
||||
Version: ${DPKG_VERSION}
|
||||
Section: utils
|
||||
Priority: optional
|
||||
Maintainer: ${MAINTAINER}
|
||||
Homepage: ${REPO}
|
||||
Architecture: ${DPKG_ARCH}
|
||||
Provides: fd
|
||||
Conflicts: ${DPKG_CONFLICTS}
|
||||
Description: simple, fast and user-friendly alternative to find
|
||||
fd is a program to find entries in your filesystem.
|
||||
It is a simple, fast and user-friendly alternative to find.
|
||||
While it does not aim to support all of finds powerful functionality, it provides
|
||||
sensible (opinionated) defaults for a majority of use cases.
|
||||
EOF
|
||||
|
||||
DPKG_PATH="${DPKG_STAGING}/${DPKG_NAME}"
|
||||
|
||||
if [[ -n $GITHUB_OUTPUT ]]; then
|
||||
echo "DPKG_NAME=${DPKG_NAME}" >> "$GITHUB_OUTPUT"
|
||||
echo "DPKG_PATH=${DPKG_PATH}" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
# build dpkg
|
||||
fakeroot dpkg-deb --build "${DPKG_DIR}" "${DPKG_PATH}"
|
||||
Executable
+41
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/gawk -f
|
||||
|
||||
BEGIN {
|
||||
inSection = 0
|
||||
inBlock = 0
|
||||
}
|
||||
|
||||
|
||||
/Command-line options/ { inSection=1 }
|
||||
|
||||
inSection && /^```/ {
|
||||
inBlock=1
|
||||
inSection=0
|
||||
# print the starting fence then move to next line
|
||||
print
|
||||
next
|
||||
}
|
||||
|
||||
inBlock && /^```/ {
|
||||
cmd="cargo run --release --quiet -- -h"
|
||||
# Output the results of fd -h
|
||||
u=0
|
||||
while (cmd | getline line) {
|
||||
# Skip everything before the usage line
|
||||
if (line ~ /^Usage/) {
|
||||
u=1;
|
||||
}
|
||||
if (u) {
|
||||
print line
|
||||
}
|
||||
}
|
||||
status = close(cmd)
|
||||
if (status) {
|
||||
print "failed to generate help output" > "/dev/stderr"
|
||||
exit 1
|
||||
}
|
||||
inBlock = 0
|
||||
}
|
||||
|
||||
!inBlock
|
||||
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/bash
|
||||
|
||||
set -eu
|
||||
|
||||
# This script automates the "Version bump" section
|
||||
|
||||
version="$1"
|
||||
|
||||
if [[ -z $version ]]; then
|
||||
echo "Usage: must supply version as first argument" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git switch -C "release-$version"
|
||||
sed -i -e "0,/^\[badges/{s/^version =.*/version = \"$version\"/}" Cargo.toml
|
||||
|
||||
msrv="$(grep -F rust-version Cargo.toml | sed -e 's/^rust-version= "\(.*\)"/\1/')"
|
||||
|
||||
sed -i -e "s/Note that rust version \*[0-9.]+\* or later/Note that rust version *$msrv* or later/" README.md
|
||||
|
||||
sed -i -e "s/^# Upcoming release/# $version/" CHANGELOG.md
|
||||
|
||||
-760
@@ -1,760 +0,0 @@
|
||||
use clap::{crate_version, App, AppSettings, Arg};
|
||||
|
||||
pub fn build_app() -> App<'static, 'static> {
|
||||
let clap_color_setting = if std::env::var_os("NO_COLOR").is_none() {
|
||||
AppSettings::ColoredHelp
|
||||
} else {
|
||||
AppSettings::ColorNever
|
||||
};
|
||||
|
||||
let mut app = App::new("fd")
|
||||
.version(crate_version!())
|
||||
.usage("fd [FLAGS/OPTIONS] [<pattern>] [<path>...]")
|
||||
.setting(clap_color_setting)
|
||||
.setting(AppSettings::DeriveDisplayOrder)
|
||||
.after_help(
|
||||
"Note: `fd -h` prints a short and concise overview while `fd --help` gives all \
|
||||
details.",
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("hidden")
|
||||
.long("hidden")
|
||||
.short("H")
|
||||
.overrides_with("hidden")
|
||||
.help("Search hidden files and directories")
|
||||
.long_help(
|
||||
"Include hidden directories and files in the search results (default: \
|
||||
hidden files and directories are skipped). Files and directories are \
|
||||
considered to be hidden if their name starts with a `.` sign (dot). \
|
||||
The flag can be overridden with --no-hidden.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("no-hidden")
|
||||
.long("no-hidden")
|
||||
.overrides_with("hidden")
|
||||
.hidden(true)
|
||||
.long_help(
|
||||
"Overrides --hidden.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("no-ignore")
|
||||
.long("no-ignore")
|
||||
.short("I")
|
||||
.overrides_with("no-ignore")
|
||||
.help("Do not respect .(git|fd)ignore files")
|
||||
.long_help(
|
||||
"Show search results from files and directories that would otherwise be \
|
||||
ignored by '.gitignore', '.ignore', '.fdignore', or the global ignore file. \
|
||||
The flag can be overridden with --ignore.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("ignore")
|
||||
.long("ignore")
|
||||
.overrides_with("no-ignore")
|
||||
.hidden(true)
|
||||
.long_help(
|
||||
"Overrides --no-ignore.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("no-ignore-vcs")
|
||||
.long("no-ignore-vcs")
|
||||
.overrides_with("no-ignore-vcs")
|
||||
.hidden_short_help(true)
|
||||
.help("Do not respect .gitignore files")
|
||||
.long_help(
|
||||
"Show search results from files and directories that would otherwise be \
|
||||
ignored by '.gitignore' files. The flag can be overridden with --ignore-vcs.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("ignore-vcs")
|
||||
.long("ignore-vcs")
|
||||
.overrides_with("no-ignore-vcs")
|
||||
.hidden(true)
|
||||
.long_help(
|
||||
"Overrides --no-ignore-vcs.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("no-ignore-parent")
|
||||
.long("no-ignore-parent")
|
||||
.overrides_with("no-ignore-parent")
|
||||
.hidden_short_help(true)
|
||||
.help("Do not respect .(git|fd)ignore files in parent directories")
|
||||
.long_help(
|
||||
"Show search results from files and directories that would otherwise be \
|
||||
ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("no-global-ignore-file")
|
||||
.long("no-global-ignore-file")
|
||||
.hidden(true)
|
||||
.help("Do not respect the global ignore file")
|
||||
.long_help("Do not respect the global ignore file."),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("rg-alias-hidden-ignore")
|
||||
.short("u")
|
||||
.long("unrestricted")
|
||||
.overrides_with_all(&["ignore", "no-hidden"])
|
||||
.multiple(true)
|
||||
.hidden_short_help(true)
|
||||
.help("Alias for '--no-ignore', and '--hidden' when given twice")
|
||||
.long_help(
|
||||
"Alias for '--no-ignore'. Can be repeated. '-uu' is an alias for \
|
||||
'--no-ignore --hidden'.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("case-sensitive")
|
||||
.long("case-sensitive")
|
||||
.short("s")
|
||||
.overrides_with_all(&["ignore-case", "case-sensitive"])
|
||||
.help("Case-sensitive search (default: smart case)")
|
||||
.long_help(
|
||||
"Perform a case-sensitive search. By default, fd uses case-insensitive \
|
||||
searches, unless the pattern contains an uppercase character (smart \
|
||||
case).",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("ignore-case")
|
||||
.long("ignore-case")
|
||||
.short("i")
|
||||
.overrides_with_all(&["case-sensitive", "ignore-case"])
|
||||
.help("Case-insensitive search (default: smart case)")
|
||||
.long_help(
|
||||
"Perform a case-insensitive search. By default, fd uses case-insensitive \
|
||||
searches, unless the pattern contains an uppercase character (smart \
|
||||
case).",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("glob")
|
||||
.long("glob")
|
||||
.short("g")
|
||||
.conflicts_with("fixed-strings")
|
||||
.overrides_with("glob")
|
||||
.help("Glob-based search (default: regular expression)")
|
||||
.long_help("Perform a glob-based search instead of a regular expression search."),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("regex")
|
||||
.long("regex")
|
||||
.overrides_with_all(&["glob", "regex"])
|
||||
.hidden_short_help(true)
|
||||
.help("Regular-expression based search (default)")
|
||||
.long_help(
|
||||
"Perform a regular-expression based search (default). This can be used to \
|
||||
override --glob.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("fixed-strings")
|
||||
.long("fixed-strings")
|
||||
.short("F")
|
||||
.alias("literal")
|
||||
.overrides_with("fixed-strings")
|
||||
.hidden_short_help(true)
|
||||
.help("Treat pattern as literal string instead of regex")
|
||||
.long_help(
|
||||
"Treat the pattern as a literal string instead of a regular expression. Note \
|
||||
that this also performs substring comparison. If you want to match on an \
|
||||
exact filename, consider using '--glob'.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("absolute-path")
|
||||
.long("absolute-path")
|
||||
.short("a")
|
||||
.overrides_with("absolute-path")
|
||||
.help("Show absolute instead of relative paths")
|
||||
.long_help(
|
||||
"Shows the full path starting from the root as opposed to relative paths. \
|
||||
The flag can be overridden with --relative-path.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("relative-path")
|
||||
.long("relative-path")
|
||||
.overrides_with("absolute-path")
|
||||
.hidden(true)
|
||||
.long_help(
|
||||
"Overrides --absolute-path.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("list-details")
|
||||
.long("list-details")
|
||||
.short("l")
|
||||
.conflicts_with("absolute-path")
|
||||
.help("Use a long listing format with file metadata")
|
||||
.long_help(
|
||||
"Use a detailed listing format like 'ls -l'. This is basically an alias \
|
||||
for '--exec-batch ls -l' with some additional 'ls' options. This can be \
|
||||
used to see more metadata, to show symlink targets and to achieve a \
|
||||
deterministic sort order.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("follow")
|
||||
.long("follow")
|
||||
.short("L")
|
||||
.alias("dereference")
|
||||
.overrides_with("follow")
|
||||
.help("Follow symbolic links")
|
||||
.long_help(
|
||||
"By default, fd does not descend into symlinked directories. Using this \
|
||||
flag, symbolic links are also traversed. \
|
||||
Flag can be overriden with --no-follow.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("no-follow")
|
||||
.long("no-follow")
|
||||
.overrides_with("follow")
|
||||
.hidden(true)
|
||||
.long_help(
|
||||
"Overrides --follow.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("full-path")
|
||||
.long("full-path")
|
||||
.short("p")
|
||||
.overrides_with("full-path")
|
||||
.help("Search full abs. path (default: filename only)")
|
||||
.long_help(
|
||||
"By default, the search pattern is only matched against the filename (or \
|
||||
directory name). Using this flag, the pattern is matched against the full \
|
||||
(absolute) path. Example:\n \
|
||||
fd --glob -p '**/.git/config'",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("null_separator")
|
||||
.long("print0")
|
||||
.short("0")
|
||||
.overrides_with("print0")
|
||||
.conflicts_with("list-details")
|
||||
.hidden_short_help(true)
|
||||
.help("Separate results by the null character")
|
||||
.long_help(
|
||||
"Separate search results by the null character (instead of newlines). \
|
||||
Useful for piping results to 'xargs'.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("max-depth")
|
||||
.long("max-depth")
|
||||
.short("d")
|
||||
.takes_value(true)
|
||||
.value_name("depth")
|
||||
.help("Set maximum search depth (default: none)")
|
||||
.long_help(
|
||||
"Limit the directory traversal to a given depth. By default, there is no \
|
||||
limit on the search depth.",
|
||||
),
|
||||
)
|
||||
// support --maxdepth as well, for compatibility with rg
|
||||
.arg(
|
||||
Arg::with_name("rg-depth")
|
||||
.long("maxdepth")
|
||||
.hidden(true)
|
||||
.takes_value(true)
|
||||
.help("Set maximum search depth (default: none)")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("min-depth")
|
||||
.long("min-depth")
|
||||
.takes_value(true)
|
||||
.value_name("depth")
|
||||
.hidden_short_help(true)
|
||||
.help("Only show results starting at given depth")
|
||||
.long_help(
|
||||
"Only show search results starting at the given depth. \
|
||||
See also: '--max-depth' and '--exact-depth'",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("exact-depth")
|
||||
.long("exact-depth")
|
||||
.takes_value(true)
|
||||
.value_name("depth")
|
||||
.hidden_short_help(true)
|
||||
.conflicts_with_all(&["max-depth", "min-depth"])
|
||||
.help("Only show results at exact given depth")
|
||||
.long_help(
|
||||
"Only show search results at the exact given depth. This is an alias for \
|
||||
'--min-depth <depth> --max-depth <depth>'.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("prune")
|
||||
.long("prune")
|
||||
.conflicts_with_all(&["size", "exact-depth"])
|
||||
.hidden_short_help(true)
|
||||
.help("Do not traverse into matching directories")
|
||||
.long_help("Do not traverse into directories that match the search criteria. If \
|
||||
you want to exclude specific directories, use the '--exclude=…' option.")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("file-type")
|
||||
.long("type")
|
||||
.short("t")
|
||||
.multiple(true)
|
||||
.number_of_values(1)
|
||||
.takes_value(true)
|
||||
.value_name("filetype")
|
||||
.possible_values(&[
|
||||
"f",
|
||||
"file",
|
||||
"d",
|
||||
"directory",
|
||||
"l",
|
||||
"symlink",
|
||||
"x",
|
||||
"executable",
|
||||
"e",
|
||||
"empty",
|
||||
"s",
|
||||
"socket",
|
||||
"p",
|
||||
"pipe",
|
||||
])
|
||||
.hide_possible_values(true)
|
||||
.help(
|
||||
"Filter by type: file (f), directory (d), symlink (l),\nexecutable (x), \
|
||||
empty (e), socket (s), pipe (p)",
|
||||
)
|
||||
.long_help(
|
||||
"Filter the search by type:\n \
|
||||
'f' or 'file': regular files\n \
|
||||
'd' or 'directory': directories\n \
|
||||
'l' or 'symlink': symbolic links\n \
|
||||
's' or 'socket': socket\n \
|
||||
'p' or 'pipe': named pipe (FIFO)\n\n \
|
||||
'x' or 'executable': executables\n \
|
||||
'e' or 'empty': empty files or directories\n\n\
|
||||
This option can be specified more than once to include multiple file types. \
|
||||
Searching for '--type file --type symlink' will show both regular files as \
|
||||
well as symlinks. Note that the 'executable' and 'empty' filters work differently: \
|
||||
'--type executable' implies '--type file' by default. And '--type empty' searches \
|
||||
for empty files and directories, unless either '--type file' or '--type directory' \
|
||||
is specified in addition.\n\n\
|
||||
Examples:\n \
|
||||
- Only search for files:\n \
|
||||
fd --type file …\n \
|
||||
fd -tf …\n \
|
||||
- Find both files and symlinks\n \
|
||||
fd --type file --type symlink …\n \
|
||||
fd -tf -tl …\n \
|
||||
- Find executable files:\n \
|
||||
fd --type executable\n \
|
||||
fd -tx\n \
|
||||
- Find empty files:\n \
|
||||
fd --type empty --type file\n \
|
||||
fd -te -tf\n \
|
||||
- Find empty directories:\n \
|
||||
fd --type empty --type directory\n \
|
||||
fd -te -td"
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("extension")
|
||||
.long("extension")
|
||||
.short("e")
|
||||
.multiple(true)
|
||||
.number_of_values(1)
|
||||
.takes_value(true)
|
||||
.value_name("ext")
|
||||
.help("Filter by file extension")
|
||||
.long_help(
|
||||
"(Additionally) filter search results by their file extension. Multiple \
|
||||
allowable file extensions can be specified.\n\
|
||||
If you want to search for files without extension, \
|
||||
you can use the regex '^[^.]+$' as a normal search pattern.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("exec")
|
||||
.long("exec")
|
||||
.short("x")
|
||||
.min_values(1)
|
||||
.allow_hyphen_values(true)
|
||||
.value_terminator(";")
|
||||
.value_name("cmd")
|
||||
.conflicts_with("list-details")
|
||||
.help("Execute a command for each search result")
|
||||
.long_help(
|
||||
"Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \
|
||||
All positional arguments following --exec are considered to be arguments to the command - not to fd. \
|
||||
It is therefore recommended to place the '-x'/'--exec' option last.\n\
|
||||
The following placeholders are substituted before the command is executed:\n \
|
||||
'{}': path (of the current search result)\n \
|
||||
'{/}': basename\n \
|
||||
'{//}': parent directory\n \
|
||||
'{.}': path without file extension\n \
|
||||
'{/.}': basename without file extension\n\n\
|
||||
If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\
|
||||
Examples:\n\n \
|
||||
- find all *.zip files and unzip them:\n\n \
|
||||
fd -e zip -x unzip\n\n \
|
||||
- find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n \
|
||||
fd -e h -e cpp -x clang-format -i\n\n \
|
||||
- Convert all *.jpg files to *.png files:\n\n \
|
||||
fd -e jpg -x convert {} {.}.png\
|
||||
",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("exec-batch")
|
||||
.long("exec-batch")
|
||||
.short("X")
|
||||
.min_values(1)
|
||||
.allow_hyphen_values(true)
|
||||
.value_terminator(";")
|
||||
.value_name("cmd")
|
||||
.conflicts_with_all(&["exec", "list-details"])
|
||||
.help("Execute a command with all search results at once")
|
||||
.long_help(
|
||||
"Execute the given command once, with all search results as arguments.\n\
|
||||
One of the following placeholders is substituted before the command is executed:\n \
|
||||
'{}': path (of all search results)\n \
|
||||
'{/}': basename\n \
|
||||
'{//}': parent directory\n \
|
||||
'{.}': path without file extension\n \
|
||||
'{/.}': basename without file extension\n\n\
|
||||
If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\
|
||||
Examples:\n\n \
|
||||
- Find all test_*.py files and open them in your favorite editor:\n\n \
|
||||
fd -g 'test_*.py' -X vim\n\n \
|
||||
- Find all *.rs files and count the lines with \"wc -l ...\":\n\n \
|
||||
fd -e rs -X wc -l\
|
||||
"
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("batch-size")
|
||||
.long("batch-size")
|
||||
.takes_value(true)
|
||||
.value_name("size")
|
||||
.hidden_short_help(true)
|
||||
.requires("exec-batch")
|
||||
.help("Max number of arguments to run as a batch with -X")
|
||||
.long_help(
|
||||
"Maximum number of arguments to pass to the command given with -X. \
|
||||
If the number of results is greater than the given size, \
|
||||
the command given with -X is run again with remaining arguments. \
|
||||
A batch size of zero means there is no limit.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("exclude")
|
||||
.long("exclude")
|
||||
.short("E")
|
||||
.takes_value(true)
|
||||
.value_name("pattern")
|
||||
.number_of_values(1)
|
||||
.multiple(true)
|
||||
.help("Exclude entries that match the given glob pattern")
|
||||
.long_help(
|
||||
"Exclude files/directories that match the given glob pattern. This \
|
||||
overrides any other ignore logic. Multiple exclude patterns can be \
|
||||
specified.\n\n\
|
||||
Examples:\n \
|
||||
--exclude '*.pyc'\n \
|
||||
--exclude node_modules",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("ignore-file")
|
||||
.long("ignore-file")
|
||||
.takes_value(true)
|
||||
.value_name("path")
|
||||
.number_of_values(1)
|
||||
.multiple(true)
|
||||
.hidden_short_help(true)
|
||||
.help("Add custom ignore-file in '.gitignore' format")
|
||||
.long_help(
|
||||
"Add a custom ignore-file in '.gitignore' format. These files have a low \
|
||||
precedence.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("color")
|
||||
.long("color")
|
||||
.short("c")
|
||||
.takes_value(true)
|
||||
.value_name("when")
|
||||
.possible_values(&["never", "auto", "always"])
|
||||
.hide_possible_values(true)
|
||||
.help("When to use colors: never, *auto*, always")
|
||||
.long_help(
|
||||
"Declare when to use color for the pattern match output:\n \
|
||||
'auto': show colors if the output goes to an interactive console (default)\n \
|
||||
'never': do not use colorized output\n \
|
||||
'always': always use colorized output",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("threads")
|
||||
.long("threads")
|
||||
.short("j")
|
||||
.takes_value(true)
|
||||
.value_name("num")
|
||||
.hidden_short_help(true)
|
||||
.help("Set number of threads")
|
||||
.long_help(
|
||||
"Set number of threads to use for searching & executing (default: number \
|
||||
of available CPU cores)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("size")
|
||||
.long("size")
|
||||
.short("S")
|
||||
.takes_value(true)
|
||||
.number_of_values(1)
|
||||
.allow_hyphen_values(true)
|
||||
.multiple(true)
|
||||
.help("Limit results based on the size of files")
|
||||
.long_help(
|
||||
"Limit results based on the size of files using the format <+-><NUM><UNIT>.\n \
|
||||
'+': file size must be greater than or equal to this\n \
|
||||
'-': file size must be less than or equal to this\n\
|
||||
If neither '+' nor '-' is specified, file size must be exactly equal to this.\n \
|
||||
'NUM': The numeric size (e.g. 500)\n \
|
||||
'UNIT': The units for NUM. They are not case-sensitive.\n\
|
||||
Allowed unit values:\n \
|
||||
'b': bytes\n \
|
||||
'k': kilobytes (base ten, 10^3 = 1000 bytes)\n \
|
||||
'm': megabytes\n \
|
||||
'g': gigabytes\n \
|
||||
't': terabytes\n \
|
||||
'ki': kibibytes (base two, 2^10 = 1024 bytes)\n \
|
||||
'mi': mebibytes\n \
|
||||
'gi': gibibytes\n \
|
||||
'ti': tebibytes",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("max-buffer-time")
|
||||
.long("max-buffer-time")
|
||||
.takes_value(true)
|
||||
.hidden(true)
|
||||
.help("Milliseconds to buffer before streaming search results to console")
|
||||
.long_help(
|
||||
"Amount of time in milliseconds to buffer, before streaming the search \
|
||||
results to the console.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("changed-within")
|
||||
.long("changed-within")
|
||||
.alias("change-newer-than")
|
||||
.alias("newer")
|
||||
.takes_value(true)
|
||||
.value_name("date|dur")
|
||||
.number_of_values(1)
|
||||
.help("Filter by file modification time (newer than)")
|
||||
.long_help(
|
||||
"Filter results based on the file modification time. The argument can be provided \
|
||||
as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min). \
|
||||
If the time is not specified, it defaults to 00:00:00. \
|
||||
'--change-newer-than' or '--newer' can be used as aliases.\n\
|
||||
Examples:\n \
|
||||
--changed-within 2weeks\n \
|
||||
--change-newer-than '2018-10-27 10:00:00'\n \
|
||||
--newer 2018-10-27",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("changed-before")
|
||||
.long("changed-before")
|
||||
.alias("change-older-than")
|
||||
.alias("older")
|
||||
.takes_value(true)
|
||||
.value_name("date|dur")
|
||||
.number_of_values(1)
|
||||
.help("Filter by file modification time (older than)")
|
||||
.long_help(
|
||||
"Filter results based on the file modification time. The argument can be provided \
|
||||
as a specific point in time (YYYY-MM-DD HH:MM:SS) or as a duration (10h, 1d, 35min). \
|
||||
'--change-older-than' or '--older' can be used as aliases.\n\
|
||||
Examples:\n \
|
||||
--changed-before '2018-10-27 10:00:00'\n \
|
||||
--change-older-than 2weeks\n \
|
||||
--older 2018-10-27",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("max-results")
|
||||
.long("max-results")
|
||||
.takes_value(true)
|
||||
.value_name("count")
|
||||
// We currently do not support --max-results in combination with
|
||||
// program execution because the results that come up in a --max-results
|
||||
// search are non-deterministic. Users might think that they can run the
|
||||
// same search with `--exec rm` attached and get a reliable removal of
|
||||
// the files they saw in the previous search.
|
||||
.conflicts_with_all(&["exec", "exec-batch", "list-details"])
|
||||
.hidden_short_help(true)
|
||||
.help("Limit number of search results")
|
||||
.long_help("Limit the number of search results to 'count' and quit immediately."),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("max-one-result")
|
||||
.short("1")
|
||||
.hidden_short_help(true)
|
||||
.overrides_with("max-results")
|
||||
.conflicts_with_all(&["exec", "exec-batch", "list-details"])
|
||||
.help("Limit search to a single result")
|
||||
.long_help("Limit the search to a single result and quit immediately. \
|
||||
This is an alias for '--max-results=1'.")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("quiet")
|
||||
.long("quiet")
|
||||
.short("q")
|
||||
.alias("has-results")
|
||||
.hidden_short_help(true)
|
||||
.conflicts_with_all(&["exec", "exec-batch", "list-details", "max-results"])
|
||||
.help("Print nothing, exit code 0 if match found, 1 otherwise")
|
||||
.long_help(
|
||||
"When the flag is present, the program does not print anything and will \
|
||||
return with an exit code of 0 if there is at least one match. Otherwise, the \
|
||||
exit code will be 1. \
|
||||
'--has-results' can be used as an alias."
|
||||
)
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("show-errors")
|
||||
.long("show-errors")
|
||||
.hidden_short_help(true)
|
||||
.overrides_with("show-errors")
|
||||
.help("Show filesystem errors")
|
||||
.long_help(
|
||||
"Enable the display of filesystem errors for situations such as \
|
||||
insufficient permissions or dead symlinks.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("base-directory")
|
||||
.long("base-directory")
|
||||
.takes_value(true)
|
||||
.value_name("path")
|
||||
.number_of_values(1)
|
||||
.hidden_short_help(true)
|
||||
.help("Change current working directory")
|
||||
.long_help(
|
||||
"Change the current working directory of fd to the provided path. This \
|
||||
means that search results will be shown with respect to the given base \
|
||||
path. Note that relative paths which are passed to fd via the positional \
|
||||
<path> argument or the '--search-path' option will also be resolved \
|
||||
relative to this directory.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("pattern").help(
|
||||
"the search pattern (a regular expression, unless '--glob' is used; optional)",
|
||||
).long_help(
|
||||
"the search pattern which is either a regular expression (default) or a glob \
|
||||
pattern (if --glob is used). If no pattern has been specified, every entry \
|
||||
is considered a match. If your pattern starts with a dash (-), make sure to \
|
||||
pass '--' first, or it will be considered as a flag (fd -- '-foo').")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("path-separator")
|
||||
.takes_value(true)
|
||||
.value_name("separator")
|
||||
.long("path-separator")
|
||||
.hidden_short_help(true)
|
||||
.help("Set path separator when printing file paths")
|
||||
.long_help(
|
||||
"Set the path separator to use when printing file paths. The default is \
|
||||
the OS-specific separator ('/' on Unix, '\\' on Windows).",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("path")
|
||||
.multiple(true)
|
||||
.help("the root directory for the filesystem search (optional)")
|
||||
.long_help(
|
||||
"The directory where the filesystem search is rooted (optional). If \
|
||||
omitted, search the current working directory.",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("search-path")
|
||||
.long("search-path")
|
||||
.takes_value(true)
|
||||
.conflicts_with("path")
|
||||
.multiple(true)
|
||||
.hidden_short_help(true)
|
||||
.number_of_values(1)
|
||||
.help("Provide paths to search as an alternative to the positional <path>")
|
||||
.long_help(
|
||||
"Provide paths to search as an alternative to the positional <path> \
|
||||
argument. Changes the usage to `fd [FLAGS/OPTIONS] --search-path <path> \
|
||||
--search-path <path2> [<pattern>]`",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("strip-cwd-prefix")
|
||||
.long("strip-cwd-prefix")
|
||||
.conflicts_with_all(&["path", "search-path"])
|
||||
.hidden_short_help(true)
|
||||
.help("strip './' prefix from non-tty outputs")
|
||||
.long_help(
|
||||
"By default, relative paths are prefixed with './' when the output goes to a non \
|
||||
interactive terminal (TTY). Use this flag to disable this behaviour."
|
||||
)
|
||||
);
|
||||
|
||||
if cfg!(unix) {
|
||||
app = app.arg(
|
||||
Arg::with_name("owner")
|
||||
.long("owner")
|
||||
.short("o")
|
||||
.takes_value(true)
|
||||
.value_name("user:group")
|
||||
.help("Filter by owning user and/or group")
|
||||
.long_help(
|
||||
"Filter files by their user and/or group. \
|
||||
Format: [(user|uid)][:(group|gid)]. Either side is optional. \
|
||||
Precede either side with a '!' to exclude files instead.\n\
|
||||
Examples:\n \
|
||||
--owner john\n \
|
||||
--owner :students\n \
|
||||
--owner '!john:students'",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Make `--one-file-system` available only on Unix and Windows platforms, as per the
|
||||
// restrictions on the corresponding option in the `ignore` crate.
|
||||
// Provide aliases `mount` and `xdev` for people coming from `find`.
|
||||
if cfg!(any(unix, windows)) {
|
||||
app = app.arg(
|
||||
Arg::with_name("one-file-system")
|
||||
.long("one-file-system")
|
||||
.aliases(&["mount", "xdev"])
|
||||
.hidden_short_help(true)
|
||||
.help("Do not descend into a different file system")
|
||||
.long_help(
|
||||
"By default, fd will traverse the file system tree as far as other options \
|
||||
dictate. With this flag, fd ensures that it does not descend into a \
|
||||
different file system than the one it started in. Comparable to the -mount \
|
||||
or -xdev filters of find(1).",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
app
|
||||
}
|
||||
+971
@@ -0,0 +1,971 @@
|
||||
use std::num::NonZeroUsize;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use clap::{
|
||||
Arg, ArgAction, ArgGroup, ArgMatches, Command, Parser, ValueEnum, error::ErrorKind,
|
||||
value_parser,
|
||||
};
|
||||
#[cfg(feature = "completions")]
|
||||
use clap_complete::Shell;
|
||||
use normpath::PathExt;
|
||||
|
||||
use crate::error::print_error;
|
||||
use crate::exec::CommandSet;
|
||||
use crate::filesystem;
|
||||
#[cfg(unix)]
|
||||
use crate::filter::OwnerFilter;
|
||||
use crate::filter::SizeFilter;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "fd",
|
||||
version,
|
||||
about = "A program to find entries in your filesystem with regex and glob based matching. By default, fd respects gitignore rules, ignores hidden directories, and is case insensitive.",
|
||||
after_long_help = "Bugs can be reported on GitHub: https://github.com/sharkdp/fd/issues",
|
||||
max_term_width = 98,
|
||||
args_override_self = true,
|
||||
group(ArgGroup::new("execs").args(&["exec", "exec_batch", "list_details"]).conflicts_with_all(&[
|
||||
"max_results", "quiet", "max_one_result"])),
|
||||
)]
|
||||
pub struct Opts {
|
||||
/// Include hidden directories and files in the search results (default:
|
||||
/// hidden files and directories are skipped). Files and directories are
|
||||
/// considered to be hidden if their name starts with a `.` sign (dot).
|
||||
/// Any files or directories that are ignored due to the rules described by
|
||||
/// --no-ignore are still ignored unless otherwise specified.
|
||||
/// The flag can be overridden with --no-hidden.
|
||||
#[arg(
|
||||
long,
|
||||
short = 'H',
|
||||
help = "Search hidden files and directories",
|
||||
long_help
|
||||
)]
|
||||
pub hidden: bool,
|
||||
|
||||
/// Overrides --hidden
|
||||
#[arg(long, overrides_with = "hidden", hide = true, action = ArgAction::SetTrue)]
|
||||
no_hidden: (),
|
||||
|
||||
/// Show search results from files and directories that would otherwise be
|
||||
/// ignored by '.gitignore', '.ignore', '.fdignore', or the global ignore file,
|
||||
/// The flag can be overridden with --ignore.
|
||||
#[arg(
|
||||
long,
|
||||
short = 'I',
|
||||
help = "Do not respect .(git|fd)ignore files",
|
||||
long_help
|
||||
)]
|
||||
pub no_ignore: bool,
|
||||
|
||||
/// Overrides --no-ignore
|
||||
#[arg(long, overrides_with = "no_ignore", hide = true, action = ArgAction::SetTrue)]
|
||||
ignore: (),
|
||||
|
||||
///Show search results from files and directories that
|
||||
///would otherwise be ignored by '.gitignore' files.
|
||||
///The flag can be overridden with --ignore-vcs.
|
||||
#[arg(
|
||||
long,
|
||||
hide_short_help = true,
|
||||
help = "Do not respect .gitignore files",
|
||||
long_help
|
||||
)]
|
||||
pub no_ignore_vcs: bool,
|
||||
|
||||
/// Overrides --no-ignore-vcs
|
||||
#[arg(long, overrides_with = "no_ignore_vcs", hide = true, action = ArgAction::SetTrue)]
|
||||
ignore_vcs: (),
|
||||
|
||||
/// Do not require a git repository to respect gitignores.
|
||||
/// By default, fd will only respect global gitignore rules, .gitignore rules,
|
||||
/// and local exclude rules if fd detects that you are searching inside a
|
||||
/// git repository. This flag allows you to relax this restriction such that
|
||||
/// fd will respect all git related ignore rules regardless of whether you're
|
||||
/// searching in a git repository or not.
|
||||
///
|
||||
///
|
||||
/// This flag can be disabled with --require-git.
|
||||
#[arg(
|
||||
long,
|
||||
overrides_with = "require_git",
|
||||
hide_short_help = true,
|
||||
// same description as ripgrep's flag: ripgrep/crates/core/app.rs
|
||||
long_help
|
||||
)]
|
||||
pub no_require_git: bool,
|
||||
|
||||
/// Overrides --no-require-git
|
||||
#[arg(long, overrides_with = "no_require_git", hide = true, action = ArgAction::SetTrue)]
|
||||
require_git: (),
|
||||
|
||||
/// Show search results from files and directories that would otherwise be
|
||||
/// ignored by '.gitignore', '.ignore', or '.fdignore' files in parent directories.
|
||||
/// The flag can be overridden with --ignore-parent.
|
||||
#[arg(
|
||||
long,
|
||||
hide_short_help = true,
|
||||
help = "Do not respect .(git|fd)ignore files in parent directories",
|
||||
long_help
|
||||
)]
|
||||
pub no_ignore_parent: bool,
|
||||
|
||||
/// Overrides --no-ignore-parent
|
||||
#[arg(long, overrides_with = "no_ignore_parent", hide = true, action = ArgAction::SetTrue)]
|
||||
ignore_parent: (),
|
||||
|
||||
/// Do not respect the global ignore file
|
||||
#[arg(long, hide = true)]
|
||||
pub no_global_ignore_file: bool,
|
||||
|
||||
/// Perform an unrestricted search, including ignored and hidden files. This is
|
||||
/// an alias for '--no-ignore --hidden'.
|
||||
#[arg(long = "unrestricted", short = 'u', overrides_with_all(&["ignore", "no_hidden"]), action(ArgAction::Count), hide_short_help = true,
|
||||
help = "Unrestricted search, alias for '--no-ignore --hidden'",
|
||||
long_help,
|
||||
)]
|
||||
rg_alias_hidden_ignore: u8,
|
||||
|
||||
/// Case-sensitive search (default: smart case)
|
||||
#[arg(
|
||||
long,
|
||||
short = 's',
|
||||
overrides_with("ignore_case"),
|
||||
long_help = "Perform a case-sensitive search. By default, fd uses case-insensitive \
|
||||
searches, unless the pattern contains an uppercase character (smart \
|
||||
case)."
|
||||
)]
|
||||
pub case_sensitive: bool,
|
||||
|
||||
/// Perform a case-insensitive search. By default, fd uses case-insensitive
|
||||
/// searches, unless the pattern contains an uppercase character (smart
|
||||
/// case).
|
||||
#[arg(
|
||||
long,
|
||||
short = 'i',
|
||||
overrides_with("case_sensitive"),
|
||||
help = "Case-insensitive search (default: smart case)",
|
||||
long_help
|
||||
)]
|
||||
pub ignore_case: bool,
|
||||
|
||||
/// Perform a glob-based search instead of a regular expression search.
|
||||
#[arg(
|
||||
long,
|
||||
short = 'g',
|
||||
conflicts_with("fixed_strings"),
|
||||
help = "Glob-based search (default: regular expression)",
|
||||
long_help
|
||||
)]
|
||||
pub glob: bool,
|
||||
|
||||
/// Perform a regular-expression based search (default). This can be used to
|
||||
/// override --glob.
|
||||
#[arg(
|
||||
long,
|
||||
overrides_with("glob"),
|
||||
hide_short_help = true,
|
||||
help = "Regular-expression based search (default)",
|
||||
long_help
|
||||
)]
|
||||
pub regex: bool,
|
||||
|
||||
/// Treat the pattern as a literal string instead of a regular expression. Note
|
||||
/// that this also performs substring comparison. If you want to match on an
|
||||
/// exact filename, consider using '--glob' or '--exact' instead.
|
||||
#[arg(
|
||||
long,
|
||||
short = 'F',
|
||||
alias = "literal",
|
||||
hide_short_help = true,
|
||||
help = "Treat pattern as literal string instead of regex",
|
||||
long_help
|
||||
)]
|
||||
pub fixed_strings: bool,
|
||||
|
||||
/// Perform an exact match. This is equivalent to '--fixed-strings' but requires
|
||||
/// the pattern to match the entire filename (or path if '--full-path' is used),
|
||||
/// rather than a substring. Special regex characters in the pattern are treated
|
||||
/// as literal characters.
|
||||
#[arg(
|
||||
long,
|
||||
conflicts_with_all(["glob", "fixed_strings"]),
|
||||
hide_short_help = true,
|
||||
help = "Match the entire filename exactly (literal, non-substring)",
|
||||
long_help
|
||||
)]
|
||||
pub exact: bool,
|
||||
|
||||
/// Add additional required search patterns, all of which must be matched. Multiple
|
||||
/// additional patterns can be specified. The patterns are regular
|
||||
/// expressions, unless '--glob' or '--fixed-strings' is used.
|
||||
#[arg(
|
||||
long = "and",
|
||||
value_name = "pattern",
|
||||
help = "Additional search patterns that need to be matched",
|
||||
long_help,
|
||||
hide_short_help = true,
|
||||
allow_hyphen_values = true
|
||||
)]
|
||||
pub exprs: Option<Vec<String>>,
|
||||
|
||||
/// Shows the full path starting from the root as opposed to relative paths.
|
||||
/// The flag can be overridden with --relative-path.
|
||||
#[arg(
|
||||
long,
|
||||
short = 'a',
|
||||
help = "Show absolute instead of relative paths",
|
||||
long_help
|
||||
)]
|
||||
pub absolute_path: bool,
|
||||
|
||||
/// Overrides --absolute-path
|
||||
#[arg(long, overrides_with = "absolute_path", hide = true, action = ArgAction::SetTrue)]
|
||||
relative_path: (),
|
||||
|
||||
/// Use a detailed listing format like 'ls -l'. This is basically an alias
|
||||
/// for '--exec-batch ls -l' with some additional 'ls' options. This can be
|
||||
/// used to see more metadata, to show symlink targets and to achieve a
|
||||
/// deterministic sort order.
|
||||
#[arg(
|
||||
long,
|
||||
short = 'l',
|
||||
conflicts_with("absolute_path"),
|
||||
help = "Use a long listing format with file metadata",
|
||||
long_help
|
||||
)]
|
||||
pub list_details: bool,
|
||||
|
||||
/// Follow symbolic links
|
||||
#[arg(
|
||||
long,
|
||||
short = 'L',
|
||||
alias = "dereference",
|
||||
long_help = "By default, fd does not descend into symlinked directories. Using this \
|
||||
flag, symbolic links are also traversed. \
|
||||
Flag can be overridden with --no-follow."
|
||||
)]
|
||||
pub follow: bool,
|
||||
|
||||
/// Overrides --follow
|
||||
#[arg(long, overrides_with = "follow", hide = true, action = ArgAction::SetTrue)]
|
||||
no_follow: (),
|
||||
|
||||
/// By default, the search pattern is only matched against the filename (or directory name). Using this flag, the pattern is matched against the full (absolute) path. Example:
|
||||
/// fd --glob -p '**/.git/config'
|
||||
#[arg(
|
||||
long,
|
||||
short = 'p',
|
||||
help = "Search full abs. path (default: filename only)",
|
||||
long_help,
|
||||
verbatim_doc_comment
|
||||
)]
|
||||
pub full_path: bool,
|
||||
|
||||
/// Separate search results by the null character (instead of newlines).
|
||||
/// Useful for piping results to 'xargs'.
|
||||
#[arg(
|
||||
long = "print0",
|
||||
short = '0',
|
||||
conflicts_with("list_details"),
|
||||
hide_short_help = true,
|
||||
help = "Separate search results by the null character",
|
||||
long_help
|
||||
)]
|
||||
pub null_separator: bool,
|
||||
|
||||
/// Limit the directory traversal to a given depth. By default, there is no
|
||||
/// limit on the search depth.
|
||||
#[arg(
|
||||
long,
|
||||
short = 'd',
|
||||
value_name = "depth",
|
||||
alias("maxdepth"),
|
||||
help = "Set maximum search depth (default: none)",
|
||||
long_help
|
||||
)]
|
||||
max_depth: Option<usize>,
|
||||
|
||||
/// Only show search results starting at the given depth.
|
||||
/// See also: '--max-depth' and '--exact-depth'
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "depth",
|
||||
hide_short_help = true,
|
||||
alias("mindepth"),
|
||||
help = "Only show search results starting at the given depth.",
|
||||
long_help
|
||||
)]
|
||||
min_depth: Option<usize>,
|
||||
|
||||
/// Only show search results at the exact given depth. This is an alias for
|
||||
/// '--min-depth <depth> --max-depth <depth>'.
|
||||
#[arg(long, value_name = "depth", hide_short_help = true, conflicts_with_all(&["max_depth", "min_depth"]),
|
||||
help = "Only show search results at the exact given depth",
|
||||
long_help,
|
||||
)]
|
||||
exact_depth: Option<usize>,
|
||||
|
||||
/// Exclude files/directories that match the given glob pattern. This
|
||||
/// overrides any other ignore logic. Multiple exclude patterns can be
|
||||
/// specified.
|
||||
///
|
||||
/// Examples:
|
||||
/// {n} --exclude '*.pyc'
|
||||
/// {n} --exclude node_modules
|
||||
#[arg(
|
||||
long,
|
||||
short = 'E',
|
||||
value_name = "glob",
|
||||
help = "Exclude entries that match the given glob pattern",
|
||||
long_help
|
||||
)]
|
||||
pub exclude: Vec<String>,
|
||||
|
||||
/// Do not traverse into directories that match the search criteria. If
|
||||
/// you want to exclude specific directories, use the '--exclude=…' option.
|
||||
#[arg(long, hide_short_help = true, conflicts_with_all(&["size", "exact_depth"]),
|
||||
long_help,
|
||||
)]
|
||||
pub prune: bool,
|
||||
|
||||
/// Filter the search by type:
|
||||
/// {n} 'f' or 'file': regular files
|
||||
/// {n} 'd' or 'dir' or 'directory': directories
|
||||
/// {n} 'l' or 'symlink': symbolic links
|
||||
/// {n} 's' or 'socket': socket
|
||||
/// {n} 'p' or 'pipe': named pipe (FIFO)
|
||||
/// {n} 'b' or 'block-device': block device
|
||||
/// {n} 'c' or 'char-device': character device
|
||||
/// {n}{n} 'x' or 'executable': executables
|
||||
/// {n} 'e' or 'empty': empty files or directories
|
||||
///
|
||||
/// This option can be specified more than once to include multiple file types.
|
||||
/// Searching for '--type file --type symlink' will show both regular files as
|
||||
/// well as symlinks. Note that the 'executable' and 'empty' filters work differently:
|
||||
/// '--type executable' implies '--type file' by default. And '--type empty' searches
|
||||
/// for empty files and directories, unless either '--type file' or '--type directory'
|
||||
/// is specified in addition.
|
||||
///
|
||||
/// Examples:
|
||||
/// {n} - Only search for files:
|
||||
/// {n} fd --type file …
|
||||
/// {n} fd -tf …
|
||||
/// {n} - Find both files and symlinks
|
||||
/// {n} fd --type file --type symlink …
|
||||
/// {n} fd -tf -tl …
|
||||
/// {n} - Find executable files:
|
||||
/// {n} fd --type executable
|
||||
/// {n} fd -tx
|
||||
/// {n} - Find empty files:
|
||||
/// {n} fd --type empty --type file
|
||||
/// {n} fd -te -tf
|
||||
/// {n} - Find empty directories:
|
||||
/// {n} fd --type empty --type directory
|
||||
/// {n} fd -te -td
|
||||
#[arg(
|
||||
long = "type",
|
||||
short = 't',
|
||||
value_name = "filetype",
|
||||
hide_possible_values = true,
|
||||
value_enum,
|
||||
help = "Filter by type: file (f), directory (d/dir), symlink (l), \
|
||||
executable (x), empty (e), socket (s), pipe (p), \
|
||||
char-device (c), block-device (b)",
|
||||
long_help
|
||||
)]
|
||||
pub filetype: Option<Vec<FileType>>,
|
||||
|
||||
/// Filter results by extension. By default, this matches all entry types
|
||||
/// (including directories whose names end with the extension). Use `--type`
|
||||
/// to restrict the search to specific types. Multiple extensions can be specified.
|
||||
///
|
||||
/// If you want to search for files without extension,
|
||||
/// you can use the regex '^[^.]+$' as a normal search pattern.
|
||||
#[arg(
|
||||
long = "extension",
|
||||
short = 'e',
|
||||
value_name = "ext",
|
||||
help = "Filter by extension",
|
||||
long_help
|
||||
)]
|
||||
pub extensions: Option<Vec<String>>,
|
||||
|
||||
/// Limit results based on the size of files using the format <+-><NUM><UNIT>.
|
||||
/// '+': file size must be greater than or equal to this
|
||||
/// '-': file size must be less than or equal to this
|
||||
///
|
||||
/// If neither '+' nor '-' is specified, file size must be exactly equal to this.
|
||||
/// 'NUM': The numeric size (e.g. 500)
|
||||
/// 'UNIT': The units for NUM. They are not case-sensitive.
|
||||
/// Allowed unit values:
|
||||
/// 'b': bytes
|
||||
/// 'k': kilobytes (base ten, 10^3 = 1000 bytes)
|
||||
/// 'm': megabytes
|
||||
/// 'g': gigabytes
|
||||
/// 't': terabytes
|
||||
/// 'ki': kibibytes (base two, 2^10 = 1024 bytes)
|
||||
/// 'mi': mebibytes
|
||||
/// 'gi': gibibytes
|
||||
/// 'ti': tebibytes
|
||||
#[arg(long, short = 'S', value_parser = SizeFilter::from_string, allow_hyphen_values = true, verbatim_doc_comment, value_name = "size",
|
||||
help = "Limit results based on the size of files",
|
||||
long_help,
|
||||
verbatim_doc_comment,
|
||||
)]
|
||||
pub size: Vec<SizeFilter>,
|
||||
|
||||
/// Filter results based on the file modification time. Files with modification times
|
||||
/// greater than the argument are returned. The argument can be provided
|
||||
/// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).
|
||||
/// If the time is not specified, it defaults to 00:00:00.
|
||||
/// '--change-newer-than', '--newer', or '--changed-after' can be used as aliases.
|
||||
///
|
||||
/// Examples:
|
||||
/// {n} --changed-within 2weeks
|
||||
/// {n} --change-newer-than '2018-10-27 10:00:00'
|
||||
/// {n} --newer 2018-10-27
|
||||
/// {n} --changed-after 1day
|
||||
#[arg(
|
||||
long,
|
||||
alias("change-newer-than"),
|
||||
alias("newer"),
|
||||
alias("changed-after"),
|
||||
value_name = "date|dur",
|
||||
help = "Filter by file modification time (newer than)",
|
||||
long_help
|
||||
)]
|
||||
pub changed_within: Option<String>,
|
||||
|
||||
/// Filter results based on the file modification time. Files with modification times
|
||||
/// less than the argument are returned. The argument can be provided
|
||||
/// as a specific point in time (YYYY-MM-DD HH:MM:SS or @timestamp) or as a duration (10h, 1d, 35min).
|
||||
/// '--change-older-than' or '--older' can be used as aliases.
|
||||
///
|
||||
/// Examples:
|
||||
/// {n} --changed-before '2018-10-27 10:00:00'
|
||||
/// {n} --change-older-than 2weeks
|
||||
/// {n} --older 2018-10-27
|
||||
#[arg(
|
||||
long,
|
||||
alias("change-older-than"),
|
||||
alias("older"),
|
||||
value_name = "date|dur",
|
||||
help = "Filter by file modification time (older than)",
|
||||
long_help
|
||||
)]
|
||||
pub changed_before: Option<String>,
|
||||
|
||||
/// Filter files by their user and/or group.
|
||||
/// Format: [(user|uid)][:(group|gid)]. Either side is optional.
|
||||
/// Precede either side with a '!' to exclude files instead.
|
||||
///
|
||||
/// Examples:
|
||||
/// {n} --owner john
|
||||
/// {n} --owner :students
|
||||
/// {n} --owner '!john:students'
|
||||
#[cfg(unix)]
|
||||
#[arg(long, short = 'o', value_parser = OwnerFilter::from_string, value_name = "user:group",
|
||||
help = "Filter by owning user and/or group",
|
||||
long_help,
|
||||
)]
|
||||
pub owner: Option<OwnerFilter>,
|
||||
|
||||
/// Instead of printing the file normally, print the format string with the following placeholders replaced:
|
||||
/// '{}': path (of the current search result)
|
||||
/// '{/}': basename
|
||||
/// '{//}': parent directory
|
||||
/// '{.}': path without file extension
|
||||
/// '{/.}': basename without file extension
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "fmt",
|
||||
help = "Print results according to template",
|
||||
conflicts_with = "list_details"
|
||||
)]
|
||||
pub format: Option<String>,
|
||||
|
||||
#[command(flatten)]
|
||||
pub exec: Exec,
|
||||
|
||||
/// Maximum number of arguments to pass to the command given with -X.
|
||||
/// If the number of results is greater than the given size,
|
||||
/// the command given with -X is run again with remaining arguments.
|
||||
/// A batch size of zero means there is no limit (default), but note
|
||||
/// that batching might still happen due to OS restrictions on the
|
||||
/// maximum length of command lines.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "size",
|
||||
hide_short_help = true,
|
||||
requires("exec_batch"),
|
||||
value_parser = value_parser!(usize),
|
||||
default_value_t,
|
||||
help = "Max number of arguments to run as a batch size with -X",
|
||||
long_help,
|
||||
)]
|
||||
pub batch_size: usize,
|
||||
|
||||
/// Add a custom ignore-file in '.gitignore' format. These files have a low precedence.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "path",
|
||||
hide_short_help = true,
|
||||
help = "Add a custom ignore-file in '.gitignore' format",
|
||||
long_help
|
||||
)]
|
||||
pub ignore_file: Vec<PathBuf>,
|
||||
|
||||
/// Declare when to use color for the pattern match output
|
||||
#[arg(
|
||||
long,
|
||||
short = 'c',
|
||||
value_enum,
|
||||
default_value_t = ColorWhen::Auto,
|
||||
value_name = "when",
|
||||
help = "When to use colors",
|
||||
long_help,
|
||||
)]
|
||||
pub color: ColorWhen,
|
||||
|
||||
/// Add a terminal hyperlink to a file:// url for each path in the output.
|
||||
///
|
||||
/// Auto mode is used if no argument is given to this option.
|
||||
///
|
||||
/// This doesn't do anything for --exec and --exec-batch.
|
||||
#[arg(
|
||||
long,
|
||||
alias = "hyper",
|
||||
value_name = "when",
|
||||
require_equals = true,
|
||||
value_enum,
|
||||
default_value_t = HyperlinkWhen::Never,
|
||||
default_missing_value = "auto",
|
||||
num_args = 0..=1,
|
||||
help = "Add hyperlinks to output paths"
|
||||
)]
|
||||
pub hyperlink: HyperlinkWhen,
|
||||
|
||||
/// Ignore directories containing the named entry.
|
||||
#[arg(long, value_name = "name")]
|
||||
pub ignore_contain: Vec<String>,
|
||||
|
||||
/// Set number of threads to use for searching & executing (default: number
|
||||
/// of available CPU cores)
|
||||
#[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = str::parse::<NonZeroUsize>)]
|
||||
pub threads: Option<NonZeroUsize>,
|
||||
|
||||
/// Milliseconds to buffer before streaming search results to console
|
||||
///
|
||||
/// Amount of time in milliseconds to buffer, before streaming the search
|
||||
/// results to the console.
|
||||
#[arg(long, hide = true, value_parser = parse_millis)]
|
||||
pub max_buffer_time: Option<Duration>,
|
||||
|
||||
///Limit the number of search results to 'count' and quit immediately.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "count",
|
||||
hide_short_help = true,
|
||||
overrides_with("max_one_result"),
|
||||
help = "Limit the number of search results",
|
||||
long_help
|
||||
)]
|
||||
max_results: Option<usize>,
|
||||
|
||||
/// Limit the search to a single result and quit immediately.
|
||||
/// This is an alias for '--max-results=1'.
|
||||
#[arg(
|
||||
short = '1',
|
||||
hide_short_help = true,
|
||||
overrides_with("max_results"),
|
||||
help = "Limit search to a single result",
|
||||
long_help
|
||||
)]
|
||||
max_one_result: bool,
|
||||
|
||||
/// When the flag is present, the program does not print anything and will
|
||||
/// return with an exit code of 0 if there is at least one match. Otherwise, the
|
||||
/// exit code will be 1.
|
||||
/// '--has-results' can be used as an alias.
|
||||
#[arg(
|
||||
long,
|
||||
short = 'q',
|
||||
alias = "has-results",
|
||||
hide_short_help = true,
|
||||
conflicts_with("max_results"),
|
||||
help = "Print nothing, exit code 0 if match found, 1 otherwise",
|
||||
long_help
|
||||
)]
|
||||
pub quiet: bool,
|
||||
|
||||
/// Enable the display of filesystem errors for situations such as
|
||||
/// insufficient permissions or dead symlinks.
|
||||
#[arg(
|
||||
long,
|
||||
hide_short_help = true,
|
||||
help = "Show filesystem errors",
|
||||
long_help
|
||||
)]
|
||||
pub show_errors: bool,
|
||||
|
||||
/// Change the current working directory of fd to the provided path. This
|
||||
/// means that search results will be shown with respect to the given base
|
||||
/// path. Note that relative paths which are passed to fd via the positional
|
||||
/// <path> argument or the '--search-path' option will also be resolved
|
||||
/// relative to this directory.
|
||||
#[arg(
|
||||
long,
|
||||
short = 'C',
|
||||
value_name = "path",
|
||||
hide_short_help = true,
|
||||
help = "Change current working directory",
|
||||
long_help
|
||||
)]
|
||||
pub base_directory: Option<PathBuf>,
|
||||
|
||||
/// the search pattern which is either a regular expression (default) or a glob
|
||||
/// pattern (if --glob is used). If no pattern has been specified, every entry
|
||||
/// is considered a match. If your pattern starts with a dash (-), make sure to
|
||||
/// pass '--' first, or it will be considered as a flag (fd -- '-foo').
|
||||
#[arg(
|
||||
default_value = "",
|
||||
hide_default_value = true,
|
||||
value_name = "pattern",
|
||||
help = "the search pattern (a regular expression, unless '--glob' is used; optional)",
|
||||
long_help
|
||||
)]
|
||||
pub pattern: String,
|
||||
|
||||
/// Set the path separator to use when printing file paths. The default is
|
||||
/// the OS-specific separator ('/' on Unix, '\' on Windows).
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "separator",
|
||||
hide_short_help = true,
|
||||
help = "Set path separator when printing file paths",
|
||||
long_help
|
||||
)]
|
||||
pub path_separator: Option<String>,
|
||||
|
||||
/// The directory where the filesystem search is rooted (optional). If
|
||||
/// omitted, search the current working directory.
|
||||
#[arg(action = ArgAction::Append,
|
||||
value_name = "path",
|
||||
help = "the root directories for the filesystem search (optional)",
|
||||
long_help,
|
||||
)]
|
||||
path: Vec<PathBuf>,
|
||||
|
||||
/// Provide paths to search as an alternative to the positional <path>
|
||||
/// argument. Changes the usage to `fd [OPTIONS] --search-path <path>
|
||||
/// --search-path <path2> [<pattern>]`
|
||||
#[arg(
|
||||
long,
|
||||
conflicts_with("path"),
|
||||
value_name = "search-path",
|
||||
hide_short_help = true,
|
||||
help = "Provides paths to search as an alternative to the positional <path> argument",
|
||||
long_help
|
||||
)]
|
||||
search_path: Vec<PathBuf>,
|
||||
|
||||
/// By default, relative paths are prefixed with './' when -x/--exec,
|
||||
/// -X/--exec-batch, or -0/--print0 are given, to reduce the risk of a
|
||||
/// path starting with '-' being treated as a command line option. Use
|
||||
/// this flag to change this behavior. If this flag is used without a value,
|
||||
/// it is equivalent to passing "always".
|
||||
#[arg(long, conflicts_with_all(&["path", "search_path"]), value_name = "when", hide_short_help = true, require_equals = true, long_help)]
|
||||
strip_cwd_prefix: Option<Option<StripCwdWhen>>,
|
||||
|
||||
/// By default, fd will traverse the file system tree as far as other options
|
||||
/// dictate. With this flag, fd ensures that it does not descend into a
|
||||
/// different file system than the one it started in. Comparable to the -mount
|
||||
/// or -xdev filters of find(1).
|
||||
#[cfg(any(unix, windows))]
|
||||
#[arg(long, aliases(&["mount", "xdev"]), hide_short_help = true, long_help)]
|
||||
pub one_file_system: bool,
|
||||
|
||||
#[cfg(feature = "completions")]
|
||||
#[arg(long, hide = true, exclusive = true)]
|
||||
gen_completions: Option<Option<Shell>>,
|
||||
}
|
||||
|
||||
impl Opts {
|
||||
pub fn search_paths(&self) -> anyhow::Result<Vec<PathBuf>> {
|
||||
// would it make sense to concatenate these?
|
||||
let paths = if !self.path.is_empty() {
|
||||
&self.path
|
||||
} else if !self.search_path.is_empty() {
|
||||
&self.search_path
|
||||
} else {
|
||||
let current_directory = Path::new("./");
|
||||
ensure_current_directory_exists(current_directory)?;
|
||||
return Ok(vec![self.normalize_path(current_directory)]);
|
||||
};
|
||||
Ok(paths
|
||||
.iter()
|
||||
.filter_map(|path| {
|
||||
if filesystem::is_existing_directory(path) {
|
||||
Some(self.normalize_path(path))
|
||||
} else {
|
||||
print_error(format!(
|
||||
"Search path '{}' is not a directory.",
|
||||
path.to_string_lossy()
|
||||
));
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn normalize_path(&self, path: &Path) -> PathBuf {
|
||||
if self.absolute_path {
|
||||
filesystem::absolute_path(path.normalize().unwrap().as_path()).unwrap()
|
||||
} else if path == Path::new(".") {
|
||||
// Change "." to "./" as a workaround for https://github.com/BurntSushi/ripgrep/pull/2711
|
||||
PathBuf::from("./")
|
||||
} else if path == Path::new("-") {
|
||||
// Prefix "-" so the underlying walker treats it as a path.
|
||||
// See sharkdp/fd#849.
|
||||
Path::new(".").join(path)
|
||||
} else {
|
||||
path.to_path_buf()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn no_search_paths(&self) -> bool {
|
||||
self.path.is_empty() && self.search_path.is_empty()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn rg_alias_ignore(&self) -> bool {
|
||||
self.rg_alias_hidden_ignore > 0
|
||||
}
|
||||
|
||||
pub fn max_depth(&self) -> Option<usize> {
|
||||
self.max_depth.or(self.exact_depth)
|
||||
}
|
||||
|
||||
pub fn min_depth(&self) -> Option<usize> {
|
||||
self.min_depth.or(self.exact_depth)
|
||||
}
|
||||
|
||||
pub fn threads(&self) -> NonZeroUsize {
|
||||
self.threads.unwrap_or_else(default_num_threads)
|
||||
}
|
||||
|
||||
pub fn max_results(&self) -> Option<usize> {
|
||||
self.max_results
|
||||
.filter(|&m| m > 0)
|
||||
.or_else(|| self.max_one_result.then_some(1))
|
||||
}
|
||||
|
||||
pub fn strip_cwd_prefix<P: FnOnce() -> bool>(&self, auto_pred: P) -> bool {
|
||||
use self::StripCwdWhen::*;
|
||||
self.no_search_paths()
|
||||
&& match self.strip_cwd_prefix.map_or(Auto, |o| o.unwrap_or(Always)) {
|
||||
Auto => auto_pred(),
|
||||
Always => true,
|
||||
Never => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "completions")]
|
||||
pub fn gen_completions(&self) -> anyhow::Result<Option<Shell>> {
|
||||
self.gen_completions
|
||||
.map(|maybe_shell| match maybe_shell {
|
||||
Some(sh) => Ok(sh),
|
||||
None => {
|
||||
Shell::from_env().ok_or_else(|| anyhow!("Unable to get shell from environment"))
|
||||
}
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the default number of threads to use, if not explicitly specified.
|
||||
fn default_num_threads() -> NonZeroUsize {
|
||||
// If we can't get the amount of parallelism for some reason, then
|
||||
// default to a single thread, because that is safe.
|
||||
let fallback = NonZeroUsize::MIN;
|
||||
// To limit startup overhead on massively parallel machines, don't use more
|
||||
// than 64 threads.
|
||||
let limit = NonZeroUsize::new(64).unwrap();
|
||||
|
||||
std::thread::available_parallelism()
|
||||
.unwrap_or(fallback)
|
||||
.min(limit)
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]
|
||||
pub enum FileType {
|
||||
#[value(alias = "f")]
|
||||
File,
|
||||
#[value(alias = "d", alias = "dir")]
|
||||
Directory,
|
||||
#[value(alias = "l")]
|
||||
Symlink,
|
||||
#[value(alias = "b")]
|
||||
BlockDevice,
|
||||
#[value(alias = "c")]
|
||||
CharDevice,
|
||||
/// A file which is executable by the current effective user
|
||||
#[value(alias = "x")]
|
||||
Executable,
|
||||
#[value(alias = "e")]
|
||||
Empty,
|
||||
#[value(alias = "s")]
|
||||
Socket,
|
||||
#[value(alias = "p")]
|
||||
Pipe,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]
|
||||
pub enum ColorWhen {
|
||||
/// show colors if the output goes to an interactive console (default)
|
||||
Auto,
|
||||
/// always use colorized output
|
||||
Always,
|
||||
/// do not use colorized output
|
||||
Never,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]
|
||||
pub enum StripCwdWhen {
|
||||
/// Use the default behavior
|
||||
Auto,
|
||||
/// Always strip the ./ at the beginning of paths
|
||||
Always,
|
||||
/// Never strip the ./
|
||||
Never,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]
|
||||
pub enum HyperlinkWhen {
|
||||
/// Use hyperlinks only if color is enabled
|
||||
Auto,
|
||||
/// Always use hyperlinks when printing file paths
|
||||
Always,
|
||||
/// Never use hyperlinks
|
||||
Never,
|
||||
}
|
||||
|
||||
// there isn't a derive api for getting grouped values yet,
|
||||
// so we have to use hand-rolled parsing for exec and exec-batch
|
||||
pub struct Exec {
|
||||
pub command: Option<CommandSet>,
|
||||
}
|
||||
|
||||
impl clap::FromArgMatches for Exec {
|
||||
fn from_arg_matches(matches: &ArgMatches) -> clap::error::Result<Self> {
|
||||
let command = matches
|
||||
.get_occurrences::<String>("exec")
|
||||
.map(CommandSet::new)
|
||||
.or_else(|| {
|
||||
matches
|
||||
.get_occurrences::<String>("exec_batch")
|
||||
.map(CommandSet::new_batch)
|
||||
})
|
||||
.transpose()
|
||||
.map_err(|e| clap::Error::raw(ErrorKind::InvalidValue, e))?;
|
||||
Ok(Exec { command })
|
||||
}
|
||||
|
||||
fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> clap::error::Result<()> {
|
||||
*self = Self::from_arg_matches(matches)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl clap::Args for Exec {
|
||||
fn augment_args(cmd: Command) -> Command {
|
||||
cmd.arg(Arg::new("exec")
|
||||
.action(ArgAction::Append)
|
||||
.long("exec")
|
||||
.short('x')
|
||||
.num_args(1..)
|
||||
.allow_hyphen_values(true)
|
||||
.value_terminator(";")
|
||||
.value_name("cmd")
|
||||
.conflicts_with("list_details")
|
||||
.help("Execute a command for each search result")
|
||||
.long_help(
|
||||
"Execute a command for each search result in parallel (use --threads=1 for sequential command execution). \
|
||||
There is no guarantee of the order commands are executed in, and the order should not be depended upon. \
|
||||
All positional arguments following --exec are considered to be arguments to the command - not to fd. \
|
||||
It is therefore recommended to place the '-x'/'--exec' option last. \
|
||||
Use '\\;' to terminate the command template if you need to continue passing fd arguments afterwards.\n\
|
||||
The following placeholders are substituted before the command is executed:\n \
|
||||
'{}': path (of the current search result)\n \
|
||||
'{/}': basename\n \
|
||||
'{//}': parent directory\n \
|
||||
'{.}': path without file extension\n \
|
||||
'{/.}': basename without file extension\n \
|
||||
'{{': literal '{' (for escaping)\n \
|
||||
'}}': literal '}' (for escaping)\n\n\
|
||||
If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\
|
||||
Examples:\n\n \
|
||||
- find all *.zip files and unzip them:\n\n \
|
||||
fd -e zip -x unzip\n\n \
|
||||
- find *.h and *.cpp files and run \"clang-format -i ..\" for each of them:\n\n \
|
||||
fd -e h -e cpp -x clang-format -i\n\n \
|
||||
- search within `src/` and echo each match (place `-x` last):\n\n \
|
||||
fd . src -x echo\n\n \
|
||||
- Convert all *.jpg files to *.png files:\n\n \
|
||||
fd -e jpg -x convert {} {.}.png\
|
||||
",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("exec_batch")
|
||||
.action(ArgAction::Append)
|
||||
.long("exec-batch")
|
||||
.short('X')
|
||||
.num_args(1..)
|
||||
.allow_hyphen_values(true)
|
||||
.value_terminator(";")
|
||||
.value_name("cmd")
|
||||
.conflicts_with_all(["exec", "list_details"])
|
||||
.help("Execute a command with all search results at once")
|
||||
.long_help(
|
||||
"Execute the given command once, with all search results as arguments.\n\
|
||||
The order of the arguments is non-deterministic, and should not be relied upon.\n\
|
||||
One of the following placeholders is substituted before the command is executed:\n \
|
||||
'{}': path (of all search results)\n \
|
||||
'{/}': basename\n \
|
||||
'{//}': parent directory\n \
|
||||
'{.}': path without file extension\n \
|
||||
'{/.}': basename without file extension\n \
|
||||
'{{': literal '{' (for escaping)\n \
|
||||
'}}': literal '}' (for escaping)\n\n\
|
||||
If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\
|
||||
Examples:\n\n \
|
||||
- Find all test_*.py files and open them in your favorite editor:\n\n \
|
||||
fd -g 'test_*.py' -X vim\n\n \
|
||||
- Find all *.rs files and count the lines with \"wc -l ...\":\n\n \
|
||||
fd -e rs -X wc -l\
|
||||
"
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn augment_args_for_update(cmd: Command) -> Command {
|
||||
Self::augment_args(cmd)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_millis(arg: &str) -> Result<Duration, std::num::ParseIntError> {
|
||||
Ok(Duration::from_millis(arg.parse()?))
|
||||
}
|
||||
|
||||
fn ensure_current_directory_exists(current_directory: &Path) -> anyhow::Result<()> {
|
||||
if filesystem::is_existing_directory(current_directory) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!(
|
||||
"Could not retrieve current directory (has it been deleted?)."
|
||||
))
|
||||
}
|
||||
}
|
||||
+29
-5
@@ -3,20 +3,21 @@ use std::{path::PathBuf, sync::Arc, time::Duration};
|
||||
use lscolors::LsColors;
|
||||
use regex::bytes::RegexSet;
|
||||
|
||||
use crate::exec::CommandTemplate;
|
||||
use crate::exec::CommandSet;
|
||||
use crate::filetypes::FileTypes;
|
||||
#[cfg(unix)]
|
||||
use crate::filter::OwnerFilter;
|
||||
use crate::filter::{SizeFilter, TimeFilter};
|
||||
use crate::fmt::FormatTemplate;
|
||||
|
||||
/// Configuration options for *fd*.
|
||||
pub struct Config {
|
||||
/// Whether the search is case-sensitive or case-insensitive.
|
||||
pub case_sensitive: bool,
|
||||
|
||||
/// Whether to search within the full file path or just the base name (filename or directory
|
||||
/// name).
|
||||
pub search_full_path: bool,
|
||||
/// Cached current working directory for absolute path construction.
|
||||
/// Populated when `--full-path` is set; `None` means search by filename only.
|
||||
pub full_path_base: Option<PathBuf>,
|
||||
|
||||
/// Whether to ignore hidden files and directories (or not).
|
||||
pub ignore_hidden: bool,
|
||||
@@ -30,6 +31,9 @@ pub struct Config {
|
||||
/// Whether to respect VCS ignore files (`.gitignore`, ..) or not.
|
||||
pub read_vcsignore: bool,
|
||||
|
||||
/// Whether to require a `.git` directory to respect gitignore files.
|
||||
pub require_git_to_read_vcsignore: bool,
|
||||
|
||||
/// Whether to respect the global ignore file or not.
|
||||
pub read_global_ignore: bool,
|
||||
|
||||
@@ -71,6 +75,7 @@ pub struct Config {
|
||||
pub ls_colors: Option<LsColors>,
|
||||
|
||||
/// Whether or not we are writing to an interactive terminal
|
||||
#[cfg_attr(not(unix), allow(unused))]
|
||||
pub interactive_terminal: bool,
|
||||
|
||||
/// The type of file to search for. If set to `None`, all file types are displayed. If
|
||||
@@ -82,8 +87,11 @@ pub struct Config {
|
||||
/// The value (if present) will be a lowercase string without leading dots.
|
||||
pub extensions: Option<RegexSet>,
|
||||
|
||||
/// A format string to use to format results, similarly to exec
|
||||
pub format: Option<FormatTemplate>,
|
||||
|
||||
/// If a value is supplied, each item found will be used to generate and execute commands.
|
||||
pub command: Option<Arc<CommandTemplate>>,
|
||||
pub command: Option<Arc<CommandSet>>,
|
||||
|
||||
/// Maximum number of search results to pass to each `command`. If zero, the number is
|
||||
/// unlimited.
|
||||
@@ -111,9 +119,25 @@ pub struct Config {
|
||||
/// The separator used to print file paths.
|
||||
pub path_separator: Option<String>,
|
||||
|
||||
/// The actual separator, either the system default separator or `path_separator`
|
||||
pub actual_path_separator: String,
|
||||
|
||||
/// The maximum number of search results
|
||||
pub max_results: Option<usize>,
|
||||
|
||||
/// Whether or not to strip the './' prefix for search results
|
||||
pub strip_cwd_prefix: bool,
|
||||
|
||||
/// Whether or not to use hyperlinks on paths
|
||||
pub hyperlink: bool,
|
||||
|
||||
/// Names that should stop traversal down their parent. (e.g. https://bford.info/cachedir/).
|
||||
pub ignore_contain: Vec<String>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Check whether results are being printed.
|
||||
pub fn is_printing(&self) -> bool {
|
||||
self.command.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
use std::cell::OnceCell;
|
||||
use std::ffi::OsString;
|
||||
use std::fs::{FileType, Metadata};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lscolors::{Colorable, LsColors, Style};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::filesystem::strip_current_dir;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum DirEntryInner {
|
||||
Normal(ignore::DirEntry),
|
||||
BrokenSymlink(PathBuf),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DirEntry {
|
||||
inner: DirEntryInner,
|
||||
metadata: OnceCell<Option<Metadata>>,
|
||||
style: OnceCell<Option<Style>>,
|
||||
}
|
||||
|
||||
impl DirEntry {
|
||||
#[inline]
|
||||
pub fn normal(e: ignore::DirEntry) -> Self {
|
||||
Self {
|
||||
inner: DirEntryInner::Normal(e),
|
||||
metadata: OnceCell::new(),
|
||||
style: OnceCell::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn broken_symlink(path: PathBuf) -> Self {
|
||||
Self {
|
||||
inner: DirEntryInner::BrokenSymlink(path),
|
||||
metadata: OnceCell::new(),
|
||||
style: OnceCell::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &Path {
|
||||
match &self.inner {
|
||||
DirEntryInner::Normal(e) => e.path(),
|
||||
DirEntryInner::BrokenSymlink(pathbuf) => pathbuf.as_path(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_path(self) -> PathBuf {
|
||||
match self.inner {
|
||||
DirEntryInner::Normal(e) => e.into_path(),
|
||||
DirEntryInner::BrokenSymlink(p) => p,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the path as it should be presented to the user.
|
||||
/// When stripping `./` would leave the path starting with `-`, keep the original
|
||||
/// (with `./`) so downstream tools don't interpret it as an option.
|
||||
pub fn stripped_path(&self, config: &Config) -> &Path {
|
||||
let path = self.path();
|
||||
if config.strip_cwd_prefix {
|
||||
let stripped = strip_current_dir(path);
|
||||
if starts_with_dash(stripped) {
|
||||
path
|
||||
} else {
|
||||
stripped
|
||||
}
|
||||
} else {
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the path as it should be presented to the user.
|
||||
pub fn into_stripped_path(self, config: &Config) -> PathBuf {
|
||||
if config.strip_cwd_prefix {
|
||||
self.stripped_path(config).to_path_buf()
|
||||
} else {
|
||||
self.into_path()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn file_type(&self) -> Option<FileType> {
|
||||
match &self.inner {
|
||||
DirEntryInner::Normal(e) => e.file_type(),
|
||||
DirEntryInner::BrokenSymlink(_) => self.metadata().map(|m| m.file_type()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn metadata(&self) -> Option<&Metadata> {
|
||||
self.metadata
|
||||
.get_or_init(|| match &self.inner {
|
||||
DirEntryInner::Normal(e) => e.metadata().ok(),
|
||||
DirEntryInner::BrokenSymlink(path) => path.symlink_metadata().ok(),
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
pub fn depth(&self) -> Option<usize> {
|
||||
match &self.inner {
|
||||
DirEntryInner::Normal(e) => Some(e.depth()),
|
||||
DirEntryInner::BrokenSymlink(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn style(&self, ls_colors: &LsColors) -> Option<&Style> {
|
||||
self.style
|
||||
.get_or_init(|| ls_colors.style_for(self).cloned())
|
||||
.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
fn starts_with_dash(path: &Path) -> bool {
|
||||
path.as_os_str().as_encoded_bytes().first() == Some(&b'-')
|
||||
}
|
||||
|
||||
impl PartialEq for DirEntry {
|
||||
#[inline]
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.path() == other.path()
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for DirEntry {}
|
||||
|
||||
impl PartialOrd for DirEntry {
|
||||
#[inline]
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for DirEntry {
|
||||
#[inline]
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.path().cmp(other.path())
|
||||
}
|
||||
}
|
||||
|
||||
impl Colorable for DirEntry {
|
||||
fn path(&self) -> PathBuf {
|
||||
self.path().to_owned()
|
||||
}
|
||||
|
||||
fn file_name(&self) -> OsString {
|
||||
let name = match &self.inner {
|
||||
DirEntryInner::Normal(e) => e.file_name(),
|
||||
DirEntryInner::BrokenSymlink(path) => {
|
||||
// Path::file_name() only works if the last component is Normal,
|
||||
// but we want it for all component types, so we open code it.
|
||||
// Copied from LsColors::style_for_path_with_metadata().
|
||||
path.components()
|
||||
.next_back()
|
||||
.map(|c| c.as_os_str())
|
||||
.unwrap_or_else(|| path.as_os_str())
|
||||
}
|
||||
};
|
||||
name.to_owned()
|
||||
}
|
||||
|
||||
fn file_type(&self) -> Option<FileType> {
|
||||
self.file_type()
|
||||
}
|
||||
|
||||
fn metadata(&self) -> Option<Metadata> {
|
||||
self.metadata().cloned()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::starts_with_dash;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn dash_prefixed_paths_detected() {
|
||||
assert!(starts_with_dash(Path::new("-rf")));
|
||||
assert!(starts_with_dash(Path::new("--delete")));
|
||||
assert!(starts_with_dash(Path::new("-")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safe_paths_not_flagged() {
|
||||
assert!(!starts_with_dash(Path::new("foo")));
|
||||
assert!(!starts_with_dash(Path::new("./foo")));
|
||||
assert!(!starts_with_dash(Path::new("sub/-rf")));
|
||||
assert!(!starts_with_dash(Path::new("")));
|
||||
assert!(!starts_with_dash(Path::new(" -rf")));
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -1,3 +1,9 @@
|
||||
use std::io::IsTerminal;
|
||||
|
||||
use crate::sanitize::maybe_sanitize;
|
||||
|
||||
pub fn print_error(msg: impl Into<String>) {
|
||||
eprintln!("[fd error]: {}", msg.into());
|
||||
let msg = msg.into();
|
||||
let safe = maybe_sanitize(&msg, std::io::stderr().is_terminal());
|
||||
eprintln!("[fd error]: {safe}");
|
||||
}
|
||||
|
||||
+96
-33
@@ -1,51 +1,114 @@
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::process::Command;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use argmax::Command;
|
||||
|
||||
use crate::error::print_error;
|
||||
use crate::exit_codes::ExitCode;
|
||||
|
||||
struct Outputs {
|
||||
stdout: Vec<u8>,
|
||||
stderr: Vec<u8>,
|
||||
}
|
||||
pub struct OutputBuffer {
|
||||
null_separator: bool,
|
||||
outputs: Vec<Outputs>,
|
||||
}
|
||||
|
||||
impl OutputBuffer {
|
||||
pub fn new(null_separator: bool) -> Self {
|
||||
Self {
|
||||
null_separator,
|
||||
outputs: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, stdout: Vec<u8>, stderr: Vec<u8>) {
|
||||
self.outputs.push(Outputs { stdout, stderr });
|
||||
}
|
||||
|
||||
fn write(self) {
|
||||
// Avoid taking the lock if there is nothing to do.
|
||||
// If null_separator is true, then we still need to write the
|
||||
// null separator, because the output may have been written directly
|
||||
// to stdout
|
||||
if self.outputs.is_empty() && !self.null_separator {
|
||||
return;
|
||||
}
|
||||
|
||||
let stdout = io::stdout();
|
||||
let stderr = io::stderr();
|
||||
|
||||
// While we hold these locks, only this thread will be able
|
||||
// to write its outputs.
|
||||
let mut stdout = stdout.lock();
|
||||
let mut stderr = stderr.lock();
|
||||
|
||||
for output in self.outputs.iter() {
|
||||
let _ = stdout.write_all(&output.stdout);
|
||||
let _ = stderr.write_all(&output.stderr);
|
||||
}
|
||||
if self.null_separator {
|
||||
// If null_separator is enabled, then we should write a \0 at the end
|
||||
// of the output for this entry
|
||||
let _ = stdout.write_all(b"\0");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes a command.
|
||||
pub fn execute_command(
|
||||
mut cmd: Command,
|
||||
out_perm: &Mutex<()>,
|
||||
pub fn execute_commands<I: Iterator<Item = io::Result<Command>>>(
|
||||
cmds: I,
|
||||
mut output_buffer: OutputBuffer,
|
||||
enable_output_buffering: bool,
|
||||
) -> ExitCode {
|
||||
// Spawn the supplied command.
|
||||
let output = if enable_output_buffering {
|
||||
cmd.output()
|
||||
} else {
|
||||
// If running on only one thread, don't buffer output
|
||||
// Allows for viewing and interacting with intermediate command output
|
||||
cmd.spawn().and_then(|c| c.wait_with_output())
|
||||
};
|
||||
for result in cmds {
|
||||
let mut cmd = match result {
|
||||
Ok(cmd) => cmd,
|
||||
Err(e) => return handle_cmd_error(None, e),
|
||||
};
|
||||
|
||||
// Then wait for the command to exit, if it was spawned.
|
||||
match output {
|
||||
Ok(output) => {
|
||||
// While this lock is active, this thread will be the only thread allowed
|
||||
// to write its outputs.
|
||||
let _lock = out_perm.lock().unwrap();
|
||||
// Spawn the supplied command.
|
||||
let output = if enable_output_buffering {
|
||||
cmd.output()
|
||||
} else {
|
||||
// If running on only one thread, don't buffer output
|
||||
// Allows for viewing and interacting with intermediate command output
|
||||
cmd.spawn().and_then(|c| c.wait_with_output())
|
||||
};
|
||||
|
||||
let stdout = io::stdout();
|
||||
let stderr = io::stderr();
|
||||
|
||||
let _ = stdout.lock().write_all(&output.stdout);
|
||||
let _ = stderr.lock().write_all(&output.stderr);
|
||||
|
||||
if output.status.code() == Some(0) {
|
||||
ExitCode::Success
|
||||
} else {
|
||||
ExitCode::GeneralError
|
||||
// Then wait for the command to exit, if it was spawned.
|
||||
match output {
|
||||
Ok(output) => {
|
||||
if enable_output_buffering {
|
||||
output_buffer.push(output.stdout, output.stderr);
|
||||
}
|
||||
if output.status.code() != Some(0) {
|
||||
output_buffer.write();
|
||||
return ExitCode::GeneralError;
|
||||
}
|
||||
}
|
||||
Err(why) => {
|
||||
output_buffer.write();
|
||||
return handle_cmd_error(Some(&cmd), why);
|
||||
}
|
||||
}
|
||||
Err(ref why) if why.kind() == io::ErrorKind::NotFound => {
|
||||
print_error(format!("Command not found: {:?}", cmd));
|
||||
}
|
||||
output_buffer.write();
|
||||
ExitCode::Success
|
||||
}
|
||||
|
||||
pub fn handle_cmd_error(cmd: Option<&Command>, err: io::Error) -> ExitCode {
|
||||
match (cmd, err) {
|
||||
(Some(cmd), err) if err.kind() == io::ErrorKind::NotFound => {
|
||||
print_error(format!(
|
||||
"Command not found: {}",
|
||||
cmd.get_program().to_string_lossy()
|
||||
));
|
||||
ExitCode::GeneralError
|
||||
}
|
||||
Err(why) => {
|
||||
print_error(format!("Problem while executing command: {}", why));
|
||||
(_, err) => {
|
||||
print_error(format!("Problem while executing command: {err}"));
|
||||
ExitCode::GeneralError
|
||||
}
|
||||
}
|
||||
|
||||
+36
-49
@@ -1,77 +1,64 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::error::print_error;
|
||||
use crate::exit_codes::{merge_exitcodes, ExitCode};
|
||||
use crate::exit_codes::{ExitCode, merge_exitcodes};
|
||||
use crate::walk::WorkerResult;
|
||||
|
||||
use super::CommandTemplate;
|
||||
use super::CommandSet;
|
||||
|
||||
/// An event loop that listens for inputs from the `rx` receiver. Each received input will
|
||||
/// generate a command with the supplied command template. The generated command will then
|
||||
/// be executed, and this process will continue until the receiver's sender has closed.
|
||||
pub fn job(
|
||||
rx: Arc<Mutex<Receiver<WorkerResult>>>,
|
||||
cmd: Arc<CommandTemplate>,
|
||||
out_perm: Arc<Mutex<()>>,
|
||||
show_filesystem_errors: bool,
|
||||
buffer_output: bool,
|
||||
results: impl IntoIterator<Item = WorkerResult>,
|
||||
cmd: &CommandSet,
|
||||
config: &Config,
|
||||
) -> ExitCode {
|
||||
let mut results: Vec<ExitCode> = Vec::new();
|
||||
loop {
|
||||
// Create a lock on the shared receiver for this thread.
|
||||
let lock = rx.lock().unwrap();
|
||||
// Output should be buffered when only running a single thread
|
||||
let buffer_output: bool = config.threads > 1;
|
||||
|
||||
let mut ret = ExitCode::Success;
|
||||
for result in results {
|
||||
// Obtain the next result from the receiver, else if the channel
|
||||
// has closed, exit from the loop
|
||||
let value: PathBuf = match lock.recv() {
|
||||
Ok(WorkerResult::Entry(path)) => path,
|
||||
Ok(WorkerResult::Error(err)) => {
|
||||
if show_filesystem_errors {
|
||||
let dir_entry = match result {
|
||||
WorkerResult::Entry(dir_entry) => dir_entry,
|
||||
WorkerResult::Error(err) => {
|
||||
if config.show_filesystem_errors {
|
||||
print_error(err.to_string());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Err(_) => break,
|
||||
};
|
||||
|
||||
// Drop the lock so that other threads can read from the receiver.
|
||||
drop(lock);
|
||||
// Generate a command, execute it and store its exit code.
|
||||
results.push(cmd.generate_and_execute(&value, Arc::clone(&out_perm), buffer_output))
|
||||
let code = cmd.execute(
|
||||
dir_entry.stripped_path(config),
|
||||
config.path_separator.as_deref(),
|
||||
config.null_separator,
|
||||
buffer_output,
|
||||
);
|
||||
ret = merge_exitcodes([ret, code]);
|
||||
}
|
||||
// Returns error in case of any error.
|
||||
merge_exitcodes(results)
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn batch(
|
||||
rx: Receiver<WorkerResult>,
|
||||
cmd: &CommandTemplate,
|
||||
show_filesystem_errors: bool,
|
||||
buffer_output: bool,
|
||||
limit: usize,
|
||||
results: impl IntoIterator<Item = WorkerResult>,
|
||||
cmd: &CommandSet,
|
||||
config: &Config,
|
||||
) -> ExitCode {
|
||||
let paths = rx.iter().filter_map(|value| match value {
|
||||
WorkerResult::Entry(path) => Some(path),
|
||||
WorkerResult::Error(err) => {
|
||||
if show_filesystem_errors {
|
||||
print_error(err.to_string());
|
||||
let paths = results
|
||||
.into_iter()
|
||||
.filter_map(|worker_result| match worker_result {
|
||||
WorkerResult::Entry(dir_entry) => Some(dir_entry.into_stripped_path(config)),
|
||||
WorkerResult::Error(err) => {
|
||||
if config.show_filesystem_errors {
|
||||
print_error(err.to_string());
|
||||
}
|
||||
None
|
||||
}
|
||||
None
|
||||
}
|
||||
});
|
||||
if limit == 0 {
|
||||
// no limit
|
||||
return cmd.generate_and_execute_batch(paths, buffer_output);
|
||||
}
|
||||
});
|
||||
|
||||
let mut exit_codes = Vec::new();
|
||||
let mut peekable = paths.peekable();
|
||||
while peekable.peek().is_some() {
|
||||
let limited = peekable.by_ref().take(limit);
|
||||
let exit_code = cmd.generate_and_execute_batch(limited, buffer_output);
|
||||
exit_codes.push(exit_code);
|
||||
}
|
||||
merge_exitcodes(exit_codes)
|
||||
cmd.execute_batch(paths, config.batch_size, config.path_separator.as_deref())
|
||||
}
|
||||
|
||||
+326
-298
@@ -1,27 +1,24 @@
|
||||
mod command;
|
||||
mod input;
|
||||
mod job;
|
||||
mod token;
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Component, Path, PathBuf, Prefix};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::ffi::OsString;
|
||||
use std::io;
|
||||
use std::iter;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
use anyhow::{Result, bail};
|
||||
use argmax::Command;
|
||||
|
||||
use crate::exit_codes::ExitCode;
|
||||
use crate::exec::command::OutputBuffer;
|
||||
use crate::exit_codes::{ExitCode, merge_exitcodes};
|
||||
use crate::fmt::{FormatTemplate, Token};
|
||||
|
||||
use self::command::execute_command;
|
||||
use self::input::{basename, dirname, remove_extension};
|
||||
use self::command::{execute_commands, handle_cmd_error};
|
||||
pub use self::job::{batch, job};
|
||||
use self::token::Token;
|
||||
|
||||
/// Execution mode of the command
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ExecutionMode {
|
||||
/// Command is executed for each search result
|
||||
OneByOne,
|
||||
@@ -29,104 +26,233 @@ pub enum ExecutionMode {
|
||||
Batch,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CommandSet {
|
||||
mode: ExecutionMode,
|
||||
commands: Vec<CommandTemplate>,
|
||||
}
|
||||
|
||||
impl CommandSet {
|
||||
pub fn new<I, T, S>(input: I) -> Result<CommandSet>
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
T: IntoIterator<Item = S>,
|
||||
S: AsRef<str>,
|
||||
{
|
||||
Ok(CommandSet {
|
||||
mode: ExecutionMode::OneByOne,
|
||||
commands: input
|
||||
.into_iter()
|
||||
.map(|args| CommandTemplate::new(args, ExecutionMode::OneByOne))
|
||||
.collect::<Result<_>>()?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn new_batch<I, T, S>(input: I) -> Result<CommandSet>
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
T: IntoIterator<Item = S>,
|
||||
S: AsRef<str>,
|
||||
{
|
||||
Ok(CommandSet {
|
||||
mode: ExecutionMode::Batch,
|
||||
commands: input
|
||||
.into_iter()
|
||||
.map(|args| {
|
||||
let cmd = CommandTemplate::new(args, ExecutionMode::Batch)?;
|
||||
if cmd.number_of_tokens() > 1 {
|
||||
bail!("Only one placeholder allowed for batch commands");
|
||||
}
|
||||
Ok(cmd)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn in_batch_mode(&self) -> bool {
|
||||
self.mode == ExecutionMode::Batch
|
||||
}
|
||||
|
||||
pub fn execute(
|
||||
&self,
|
||||
input: &Path,
|
||||
path_separator: Option<&str>,
|
||||
null_separator: bool,
|
||||
buffer_output: bool,
|
||||
) -> ExitCode {
|
||||
let commands = self
|
||||
.commands
|
||||
.iter()
|
||||
.map(|c| c.generate(input, path_separator));
|
||||
execute_commands(commands, OutputBuffer::new(null_separator), buffer_output)
|
||||
}
|
||||
|
||||
pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCode
|
||||
where
|
||||
I: Iterator<Item = PathBuf>,
|
||||
{
|
||||
let builders: io::Result<Vec<_>> = self
|
||||
.commands
|
||||
.iter()
|
||||
.map(|c| CommandBuilder::new(c, limit))
|
||||
.collect();
|
||||
|
||||
match builders {
|
||||
Ok(mut builders) => {
|
||||
for path in paths {
|
||||
for builder in &mut builders {
|
||||
if let Err(e) = builder.push(&path, path_separator) {
|
||||
return handle_cmd_error(Some(&builder.cmd), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for builder in &mut builders {
|
||||
if let Err(e) = builder.finish() {
|
||||
return handle_cmd_error(Some(&builder.cmd), e);
|
||||
}
|
||||
}
|
||||
|
||||
merge_exitcodes(builders.iter().map(|b| b.exit_code()))
|
||||
}
|
||||
Err(e) => handle_cmd_error(None, e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a multi-exec command as it is built.
|
||||
#[derive(Debug)]
|
||||
struct CommandBuilder {
|
||||
pre_args: Vec<OsString>,
|
||||
path_arg: FormatTemplate,
|
||||
post_args: Vec<OsString>,
|
||||
cmd: Command,
|
||||
count: usize,
|
||||
limit: usize,
|
||||
exit_code: ExitCode,
|
||||
}
|
||||
|
||||
impl CommandBuilder {
|
||||
fn new(template: &CommandTemplate, limit: usize) -> io::Result<Self> {
|
||||
let mut pre_args = vec![];
|
||||
let mut path_arg = None;
|
||||
let mut post_args = vec![];
|
||||
|
||||
for arg in &template.args {
|
||||
if arg.has_tokens() {
|
||||
path_arg = Some(arg.clone());
|
||||
} else if path_arg.is_none() {
|
||||
pre_args.push(arg.generate("", None));
|
||||
} else {
|
||||
post_args.push(arg.generate("", None));
|
||||
}
|
||||
}
|
||||
|
||||
let cmd = Self::new_command(&pre_args)?;
|
||||
|
||||
Ok(Self {
|
||||
pre_args,
|
||||
path_arg: path_arg.unwrap(),
|
||||
post_args,
|
||||
cmd,
|
||||
count: 0,
|
||||
limit,
|
||||
exit_code: ExitCode::Success,
|
||||
})
|
||||
}
|
||||
|
||||
fn new_command(pre_args: &[OsString]) -> io::Result<Command> {
|
||||
let mut cmd = Command::new(&pre_args[0]);
|
||||
cmd.stdin(Stdio::inherit());
|
||||
cmd.stdout(Stdio::inherit());
|
||||
cmd.stderr(Stdio::inherit());
|
||||
cmd.try_args(&pre_args[1..])?;
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {
|
||||
if self.limit > 0 && self.count >= self.limit {
|
||||
self.finish()?;
|
||||
}
|
||||
|
||||
let arg = self.path_arg.generate(path, separator);
|
||||
if !self
|
||||
.cmd
|
||||
.args_would_fit(iter::once(&arg).chain(&self.post_args))
|
||||
{
|
||||
self.finish()?;
|
||||
}
|
||||
|
||||
self.cmd.try_arg(arg)?;
|
||||
self.count += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish(&mut self) -> io::Result<()> {
|
||||
if self.count > 0 {
|
||||
self.cmd.try_args(&self.post_args)?;
|
||||
if !self.cmd.status()?.success() {
|
||||
self.exit_code = ExitCode::GeneralError;
|
||||
}
|
||||
|
||||
self.cmd = Self::new_command(&self.pre_args)?;
|
||||
self.count = 0;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn exit_code(&self) -> ExitCode {
|
||||
self.exit_code
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a template that is utilized to generate command strings.
|
||||
///
|
||||
/// The template is meant to be coupled with an input in order to generate a command. The
|
||||
/// `generate_and_execute()` method will be used to generate a command and execute it.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CommandTemplate {
|
||||
args: Vec<ArgumentTemplate>,
|
||||
mode: ExecutionMode,
|
||||
path_separator: Option<String>,
|
||||
struct CommandTemplate {
|
||||
args: Vec<FormatTemplate>,
|
||||
}
|
||||
|
||||
impl CommandTemplate {
|
||||
pub fn new<I, S>(input: I, path_separator: Option<String>) -> CommandTemplate
|
||||
fn new<I, S>(input: I, mode: ExecutionMode) -> Result<CommandTemplate>
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<str>,
|
||||
{
|
||||
Self::build(input, ExecutionMode::OneByOne, path_separator)
|
||||
}
|
||||
|
||||
pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandTemplate>
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<str>,
|
||||
{
|
||||
let cmd = Self::build(input, ExecutionMode::Batch, path_separator);
|
||||
if cmd.number_of_tokens() > 1 {
|
||||
return Err(anyhow!("Only one placeholder allowed for batch commands"));
|
||||
}
|
||||
if cmd.args[0].has_tokens() {
|
||||
return Err(anyhow!(
|
||||
"First argument of exec-batch is expected to be a fixed executable"
|
||||
));
|
||||
}
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
fn build<I, S>(input: I, mode: ExecutionMode, path_separator: Option<String>) -> CommandTemplate
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<str>,
|
||||
{
|
||||
static PLACEHOLDER_PATTERN: Lazy<Regex> =
|
||||
Lazy::new(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());
|
||||
|
||||
let mut args = Vec::new();
|
||||
let mut has_placeholder = false;
|
||||
|
||||
for arg in input {
|
||||
let arg = arg.as_ref();
|
||||
|
||||
let mut tokens = Vec::new();
|
||||
let mut start = 0;
|
||||
let tmpl = FormatTemplate::parse(arg);
|
||||
has_placeholder |= tmpl.has_tokens();
|
||||
args.push(tmpl);
|
||||
}
|
||||
|
||||
for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {
|
||||
// Leading text before the placeholder.
|
||||
if placeholder.start() > start {
|
||||
tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));
|
||||
}
|
||||
// We need to check that we have at least one argument, because if not
|
||||
// it will try to execute each file and directory it finds.
|
||||
//
|
||||
// Sadly, clap can't currently handle this for us, see
|
||||
// https://github.com/clap-rs/clap/issues/3542
|
||||
if args.is_empty() {
|
||||
bail!("No executable provided for --exec or --exec-batch");
|
||||
}
|
||||
|
||||
start = placeholder.end();
|
||||
|
||||
match placeholder.as_str() {
|
||||
"{}" => tokens.push(Token::Placeholder),
|
||||
"{.}" => tokens.push(Token::NoExt),
|
||||
"{/}" => tokens.push(Token::Basename),
|
||||
"{//}" => tokens.push(Token::Parent),
|
||||
"{/.}" => tokens.push(Token::BasenameNoExt),
|
||||
_ => unreachable!("Unhandled placeholder"),
|
||||
}
|
||||
|
||||
has_placeholder = true;
|
||||
}
|
||||
|
||||
// Without a placeholder, the argument is just fixed text.
|
||||
if tokens.is_empty() {
|
||||
args.push(ArgumentTemplate::Text(arg.to_owned()));
|
||||
continue;
|
||||
}
|
||||
|
||||
if start < arg.len() {
|
||||
// Trailing text after last placeholder.
|
||||
tokens.push(Token::Text(arg[start..].to_owned()));
|
||||
}
|
||||
|
||||
args.push(ArgumentTemplate::Tokens(tokens));
|
||||
// A placeholder as the executable is meaningful for `--exec` but never for `--exec-batch`.
|
||||
if mode == ExecutionMode::Batch && args[0].has_tokens() {
|
||||
bail!("First argument of --exec-batch must be a fixed executable, not a placeholder");
|
||||
}
|
||||
|
||||
// If a placeholder token was not supplied, append one at the end of the command.
|
||||
if !has_placeholder {
|
||||
args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));
|
||||
args.push(FormatTemplate::Tokens(vec![Token::Placeholder]));
|
||||
}
|
||||
|
||||
CommandTemplate {
|
||||
args,
|
||||
mode,
|
||||
path_separator,
|
||||
}
|
||||
Ok(CommandTemplate { args })
|
||||
}
|
||||
|
||||
fn number_of_tokens(&self) -> usize {
|
||||
@@ -136,162 +262,13 @@ impl CommandTemplate {
|
||||
/// Generates and executes a command.
|
||||
///
|
||||
/// Using the internal `args` field, and a supplied `input` variable, a `Command` will be
|
||||
/// build. Once all arguments have been processed, the command is executed.
|
||||
pub fn generate_and_execute(
|
||||
&self,
|
||||
input: &Path,
|
||||
out_perm: Arc<Mutex<()>>,
|
||||
buffer_output: bool,
|
||||
) -> ExitCode {
|
||||
let mut cmd = Command::new(self.args[0].generate(&input, self.path_separator.as_deref()));
|
||||
/// build.
|
||||
fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {
|
||||
let mut cmd = Command::new(self.args[0].generate(input, path_separator));
|
||||
for arg in &self.args[1..] {
|
||||
cmd.arg(arg.generate(&input, self.path_separator.as_deref()));
|
||||
cmd.try_arg(arg.generate(input, path_separator))?;
|
||||
}
|
||||
|
||||
execute_command(cmd, &out_perm, buffer_output)
|
||||
}
|
||||
|
||||
pub fn in_batch_mode(&self) -> bool {
|
||||
self.mode == ExecutionMode::Batch
|
||||
}
|
||||
|
||||
pub fn generate_and_execute_batch<I>(&self, paths: I, buffer_output: bool) -> ExitCode
|
||||
where
|
||||
I: Iterator<Item = PathBuf>,
|
||||
{
|
||||
let mut cmd = Command::new(self.args[0].generate("", None));
|
||||
cmd.stdin(Stdio::inherit());
|
||||
cmd.stdout(Stdio::inherit());
|
||||
cmd.stderr(Stdio::inherit());
|
||||
|
||||
let mut paths: Vec<_> = paths.collect();
|
||||
let mut has_path = false;
|
||||
|
||||
for arg in &self.args[1..] {
|
||||
if arg.has_tokens() {
|
||||
paths.sort();
|
||||
|
||||
// A single `Tokens` is expected
|
||||
// So we can directly consume the iterator once and for all
|
||||
for path in &mut paths {
|
||||
cmd.arg(arg.generate(path, self.path_separator.as_deref()));
|
||||
has_path = true;
|
||||
}
|
||||
} else {
|
||||
cmd.arg(arg.generate("", None));
|
||||
}
|
||||
}
|
||||
|
||||
if has_path {
|
||||
execute_command(cmd, &Mutex::new(()), buffer_output)
|
||||
} else {
|
||||
ExitCode::Success
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a template for a single command argument.
|
||||
///
|
||||
/// The argument is either a collection of `Token`s including at least one placeholder variant, or
|
||||
/// a fixed text.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum ArgumentTemplate {
|
||||
Tokens(Vec<Token>),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
impl ArgumentTemplate {
|
||||
pub fn has_tokens(&self) -> bool {
|
||||
matches!(self, ArgumentTemplate::Tokens(_))
|
||||
}
|
||||
|
||||
/// Generate an argument from this template. If path_separator is Some, then it will replace
|
||||
/// the path separator in all placeholder tokens. Text arguments and tokens are not affected by
|
||||
/// path separator substitution.
|
||||
pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {
|
||||
use self::Token::*;
|
||||
let path = path.as_ref();
|
||||
|
||||
match *self {
|
||||
ArgumentTemplate::Tokens(ref tokens) => {
|
||||
let mut s = OsString::new();
|
||||
for token in tokens {
|
||||
match *token {
|
||||
Basename => s.push(Self::replace_separator(basename(path), path_separator)),
|
||||
BasenameNoExt => s.push(Self::replace_separator(
|
||||
&remove_extension(basename(path).as_ref()),
|
||||
path_separator,
|
||||
)),
|
||||
NoExt => s.push(Self::replace_separator(
|
||||
&remove_extension(path),
|
||||
path_separator,
|
||||
)),
|
||||
Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),
|
||||
Placeholder => {
|
||||
s.push(Self::replace_separator(path.as_ref(), path_separator))
|
||||
}
|
||||
Text(ref string) => s.push(string),
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
ArgumentTemplate::Text(ref text) => OsString::from(text),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the path separator in the input with the custom separator string. If path_separator
|
||||
/// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is
|
||||
/// interpreted as a Path and its components are iterated through and re-joined into a new
|
||||
/// OsString.
|
||||
fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {
|
||||
// fast-path - no replacement necessary
|
||||
if path_separator.is_none() {
|
||||
return Cow::Borrowed(path);
|
||||
}
|
||||
|
||||
let path_separator = path_separator.unwrap();
|
||||
let mut out = OsString::with_capacity(path.len());
|
||||
let mut components = Path::new(path).components().peekable();
|
||||
|
||||
while let Some(comp) = components.next() {
|
||||
match comp {
|
||||
// Absolute paths on Windows are tricky. A Prefix component is usually a drive
|
||||
// letter or UNC path, and is usually followed by RootDir. There are also
|
||||
// "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to
|
||||
// ignore verbatim path prefixes here because they're very rare, might be
|
||||
// impossible to reach here, and there's no good way to deal with them. If users
|
||||
// are doing something advanced involving verbatim windows paths, they can do their
|
||||
// own output filtering with a tool like sed.
|
||||
Component::Prefix(prefix) => {
|
||||
if let Prefix::UNC(server, share) = prefix.kind() {
|
||||
// Prefix::UNC is a parsed version of '\\server\share'
|
||||
out.push(path_separator);
|
||||
out.push(path_separator);
|
||||
out.push(server);
|
||||
out.push(path_separator);
|
||||
out.push(share);
|
||||
} else {
|
||||
// All other Windows prefix types are rendered as-is. This results in e.g. "C:" for
|
||||
// drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,
|
||||
// but they're not returned by directories fd can search anyway so we don't worry
|
||||
// about them.
|
||||
out.push(comp.as_os_str());
|
||||
}
|
||||
}
|
||||
|
||||
// Root directory is always replaced with the custom separator.
|
||||
Component::RootDir => out.push(path_separator),
|
||||
|
||||
// Everything else is joined normally, with a trailing separator if we're not last
|
||||
_ => {
|
||||
out.push(comp.as_os_str());
|
||||
if components.peek().is_some() {
|
||||
out.push(path_separator);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Cow::Owned(out)
|
||||
Ok(cmd)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -299,18 +276,27 @@ impl ArgumentTemplate {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn generate_str(template: &CommandTemplate, input: &str) -> Vec<String> {
|
||||
template
|
||||
.args
|
||||
.iter()
|
||||
.map(|arg| arg.generate(input, None).into_string().unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_with_placeholder() {
|
||||
assert_eq!(
|
||||
CommandTemplate::new(&[&"echo", &"${SHELL}:"], None),
|
||||
CommandTemplate {
|
||||
args: vec![
|
||||
ArgumentTemplate::Text("echo".into()),
|
||||
ArgumentTemplate::Text("${SHELL}:".into()),
|
||||
ArgumentTemplate::Tokens(vec![Token::Placeholder]),
|
||||
],
|
||||
CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),
|
||||
CommandSet {
|
||||
commands: vec![CommandTemplate {
|
||||
args: vec![
|
||||
FormatTemplate::Text("echo".into()),
|
||||
FormatTemplate::Text("${SHELL}:".into()),
|
||||
FormatTemplate::Tokens(vec![Token::Placeholder]),
|
||||
]
|
||||
}],
|
||||
mode: ExecutionMode::OneByOne,
|
||||
path_separator: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -318,14 +304,15 @@ mod tests {
|
||||
#[test]
|
||||
fn tokens_with_no_extension() {
|
||||
assert_eq!(
|
||||
CommandTemplate::new(&["echo", "{.}"], None),
|
||||
CommandTemplate {
|
||||
args: vec![
|
||||
ArgumentTemplate::Text("echo".into()),
|
||||
ArgumentTemplate::Tokens(vec![Token::NoExt]),
|
||||
],
|
||||
CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),
|
||||
CommandSet {
|
||||
commands: vec![CommandTemplate {
|
||||
args: vec![
|
||||
FormatTemplate::Text("echo".into()),
|
||||
FormatTemplate::Tokens(vec![Token::NoExt]),
|
||||
],
|
||||
}],
|
||||
mode: ExecutionMode::OneByOne,
|
||||
path_separator: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -333,14 +320,15 @@ mod tests {
|
||||
#[test]
|
||||
fn tokens_with_basename() {
|
||||
assert_eq!(
|
||||
CommandTemplate::new(&["echo", "{/}"], None),
|
||||
CommandTemplate {
|
||||
args: vec![
|
||||
ArgumentTemplate::Text("echo".into()),
|
||||
ArgumentTemplate::Tokens(vec![Token::Basename]),
|
||||
],
|
||||
CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),
|
||||
CommandSet {
|
||||
commands: vec![CommandTemplate {
|
||||
args: vec![
|
||||
FormatTemplate::Text("echo".into()),
|
||||
FormatTemplate::Tokens(vec![Token::Basename]),
|
||||
],
|
||||
}],
|
||||
mode: ExecutionMode::OneByOne,
|
||||
path_separator: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -348,14 +336,15 @@ mod tests {
|
||||
#[test]
|
||||
fn tokens_with_parent() {
|
||||
assert_eq!(
|
||||
CommandTemplate::new(&["echo", "{//}"], None),
|
||||
CommandTemplate {
|
||||
args: vec![
|
||||
ArgumentTemplate::Text("echo".into()),
|
||||
ArgumentTemplate::Tokens(vec![Token::Parent]),
|
||||
],
|
||||
CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),
|
||||
CommandSet {
|
||||
commands: vec![CommandTemplate {
|
||||
args: vec![
|
||||
FormatTemplate::Text("echo".into()),
|
||||
FormatTemplate::Tokens(vec![Token::Parent]),
|
||||
],
|
||||
}],
|
||||
mode: ExecutionMode::OneByOne,
|
||||
path_separator: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -363,33 +352,52 @@ mod tests {
|
||||
#[test]
|
||||
fn tokens_with_basename_no_extension() {
|
||||
assert_eq!(
|
||||
CommandTemplate::new(&["echo", "{/.}"], None),
|
||||
CommandTemplate {
|
||||
args: vec![
|
||||
ArgumentTemplate::Text("echo".into()),
|
||||
ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),
|
||||
],
|
||||
CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),
|
||||
CommandSet {
|
||||
commands: vec![CommandTemplate {
|
||||
args: vec![
|
||||
FormatTemplate::Text("echo".into()),
|
||||
FormatTemplate::Tokens(vec![Token::BasenameNoExt]),
|
||||
],
|
||||
}],
|
||||
mode: ExecutionMode::OneByOne,
|
||||
path_separator: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_with_literal_braces() {
|
||||
let template =
|
||||
CommandTemplate::new(vec!["{{}}", "{{", "{.}}"], ExecutionMode::OneByOne).unwrap();
|
||||
assert_eq!(
|
||||
generate_str(&template, "foo"),
|
||||
vec!["{}", "{", "{.}", "foo"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_with_literal_braces_and_placeholder() {
|
||||
let template =
|
||||
CommandTemplate::new(vec!["echo", "{{{},end}"], ExecutionMode::OneByOne).unwrap();
|
||||
assert_eq!(generate_str(&template, "foo"), vec!["echo", "{foo,end}"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_multiple() {
|
||||
assert_eq!(
|
||||
CommandTemplate::new(&["cp", "{}", "{/.}.ext"], None),
|
||||
CommandTemplate {
|
||||
args: vec![
|
||||
ArgumentTemplate::Text("cp".into()),
|
||||
ArgumentTemplate::Tokens(vec![Token::Placeholder]),
|
||||
ArgumentTemplate::Tokens(vec![
|
||||
Token::BasenameNoExt,
|
||||
Token::Text(".ext".into())
|
||||
]),
|
||||
],
|
||||
CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),
|
||||
CommandSet {
|
||||
commands: vec![CommandTemplate {
|
||||
args: vec![
|
||||
FormatTemplate::Text("cp".into()),
|
||||
FormatTemplate::Tokens(vec![Token::Placeholder]),
|
||||
FormatTemplate::Tokens(vec![
|
||||
Token::BasenameNoExt,
|
||||
Token::Text(".ext".into())
|
||||
]),
|
||||
],
|
||||
}],
|
||||
mode: ExecutionMode::OneByOne,
|
||||
path_separator: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -397,26 +405,46 @@ mod tests {
|
||||
#[test]
|
||||
fn tokens_single_batch() {
|
||||
assert_eq!(
|
||||
CommandTemplate::new_batch(&["echo", "{.}"], None).unwrap(),
|
||||
CommandTemplate {
|
||||
args: vec![
|
||||
ArgumentTemplate::Text("echo".into()),
|
||||
ArgumentTemplate::Tokens(vec![Token::NoExt]),
|
||||
],
|
||||
CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),
|
||||
CommandSet {
|
||||
commands: vec![CommandTemplate {
|
||||
args: vec![
|
||||
FormatTemplate::Text("echo".into()),
|
||||
FormatTemplate::Tokens(vec![Token::NoExt]),
|
||||
],
|
||||
}],
|
||||
mode: ExecutionMode::Batch,
|
||||
path_separator: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_multiple_batch() {
|
||||
assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"], None).is_err());
|
||||
assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_no_args() {
|
||||
assert!(
|
||||
CommandTemplate::new::<Vec<_>, &'static str>(vec![], ExecutionMode::OneByOne).is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_set_no_args() {
|
||||
assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placeholder_as_executable_rejected() {
|
||||
assert!(CommandSet::new(vec![vec!["{}"]]).is_ok());
|
||||
assert!(CommandSet::new(vec![vec!["{/}", "arg"]]).is_ok());
|
||||
assert!(CommandSet::new_batch(vec![vec!["{}"]]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_custom_path_separator() {
|
||||
let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);
|
||||
let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);
|
||||
macro_rules! check {
|
||||
($input:expr, $expected:expr) => {
|
||||
assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));
|
||||
@@ -431,7 +459,7 @@ mod tests {
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn generate_custom_path_separator_windows() {
|
||||
let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);
|
||||
let arg = FormatTemplate::Tokens(vec![Token::Placeholder]);
|
||||
macro_rules! check {
|
||||
($input:expr, $expected:expr) => {
|
||||
assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
/// Designates what should be written to a buffer
|
||||
///
|
||||
/// Each `Token` contains either text, or a placeholder variant, which will be used to generate
|
||||
/// commands after all tokens for a given command template have been collected.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Token {
|
||||
Placeholder,
|
||||
Basename,
|
||||
Parent,
|
||||
NoExt,
|
||||
BasenameNoExt,
|
||||
Text(String),
|
||||
}
|
||||
|
||||
impl Display for Token {
|
||||
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Token::Placeholder => f.write_str("{}")?,
|
||||
Token::Basename => f.write_str("{/}")?,
|
||||
Token::Parent => f.write_str("{//}")?,
|
||||
Token::NoExt => f.write_str("{.}")?,
|
||||
Token::BasenameNoExt => f.write_str("{/.}")?,
|
||||
Token::Text(ref string) => f.write_str(string)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
use std::process;
|
||||
|
||||
#[cfg(unix)]
|
||||
use nix::sys::signal::{raise, signal, SigHandler, Signal};
|
||||
use nix::sys::signal::{SigHandler, Signal, raise, signal};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ExitCode {
|
||||
Success,
|
||||
HasResults(bool),
|
||||
|
||||
+28
-20
@@ -4,12 +4,12 @@ use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
#[cfg(any(unix, target_os = "redox"))]
|
||||
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
|
||||
use std::os::unix::fs::FileTypeExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use normpath::PathExt;
|
||||
|
||||
use crate::walk;
|
||||
use crate::dir_entry;
|
||||
|
||||
pub fn path_absolute_form(path: &Path) -> io::Result<PathBuf> {
|
||||
if path.is_absolute() {
|
||||
@@ -41,17 +41,7 @@ pub fn is_existing_directory(path: &Path) -> bool {
|
||||
path.is_dir() && (path.file_name().is_some() || path.normalize().is_ok())
|
||||
}
|
||||
|
||||
#[cfg(any(unix, target_os = "redox"))]
|
||||
pub fn is_executable(md: &fs::Metadata) -> bool {
|
||||
md.permissions().mode() & 0o111 != 0
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn is_executable(_: &fs::Metadata) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn is_empty(entry: &walk::DirEntry) -> bool {
|
||||
pub fn is_empty(entry: &dir_entry::DirEntry) -> bool {
|
||||
if let Some(file_type) = entry.file_type() {
|
||||
if file_type.is_dir() {
|
||||
if let Ok(mut entries) = fs::read_dir(entry.path()) {
|
||||
@@ -69,6 +59,26 @@ pub fn is_empty(entry: &walk::DirEntry) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(unix, target_os = "redox"))]
|
||||
pub fn is_block_device(ft: fs::FileType) -> bool {
|
||||
ft.is_block_device()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn is_block_device(_: fs::FileType) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(any(unix, target_os = "redox"))]
|
||||
pub fn is_char_device(ft: fs::FileType) -> bool {
|
||||
ft.is_char_device()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn is_char_device(_: fs::FileType) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(any(unix, target_os = "redox"))]
|
||||
pub fn is_socket(ft: fs::FileType) -> bool {
|
||||
ft.is_socket()
|
||||
@@ -90,13 +100,13 @@ pub fn is_pipe(_: fs::FileType) -> bool {
|
||||
}
|
||||
|
||||
#[cfg(any(unix, target_os = "redox"))]
|
||||
pub fn osstr_to_bytes(input: &OsStr) -> Cow<[u8]> {
|
||||
pub fn osstr_to_bytes(input: &OsStr) -> Cow<'_, [u8]> {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
Cow::Borrowed(input.as_bytes())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn osstr_to_bytes(input: &OsStr) -> Cow<[u8]> {
|
||||
pub fn osstr_to_bytes(input: &OsStr) -> Cow<'_, [u8]> {
|
||||
let string = input.to_string_lossy();
|
||||
|
||||
match string {
|
||||
@@ -118,13 +128,11 @@ pub fn strip_current_dir(path: &Path) -> &Path {
|
||||
pub fn default_path_separator() -> Option<String> {
|
||||
if cfg!(windows) {
|
||||
let msystem = env::var("MSYSTEM").ok()?;
|
||||
match msystem.as_str() {
|
||||
"MINGW64" | "MINGW32" | "MSYS" => Some("/".to_owned()),
|
||||
_ => None,
|
||||
if !msystem.is_empty() {
|
||||
return Some("/".to_owned());
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+12
-21
@@ -1,48 +1,39 @@
|
||||
use crate::dir_entry;
|
||||
use crate::filesystem;
|
||||
use crate::walk;
|
||||
|
||||
use faccess::PathExt;
|
||||
|
||||
/// Whether or not to show
|
||||
#[derive(Default)]
|
||||
pub struct FileTypes {
|
||||
pub files: bool,
|
||||
pub directories: bool,
|
||||
pub symlinks: bool,
|
||||
pub block_devices: bool,
|
||||
pub char_devices: bool,
|
||||
pub sockets: bool,
|
||||
pub pipes: bool,
|
||||
pub executables_only: bool,
|
||||
pub empty_only: bool,
|
||||
}
|
||||
|
||||
impl Default for FileTypes {
|
||||
fn default() -> FileTypes {
|
||||
FileTypes {
|
||||
files: false,
|
||||
directories: false,
|
||||
symlinks: false,
|
||||
sockets: false,
|
||||
pipes: false,
|
||||
executables_only: false,
|
||||
empty_only: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FileTypes {
|
||||
pub fn should_ignore(&self, entry: &walk::DirEntry) -> bool {
|
||||
pub fn should_ignore(&self, entry: &dir_entry::DirEntry) -> bool {
|
||||
if let Some(ref entry_type) = entry.file_type() {
|
||||
(!self.files && entry_type.is_file())
|
||||
|| (!self.directories && entry_type.is_dir())
|
||||
|| (!self.symlinks && entry_type.is_symlink())
|
||||
|| (!self.block_devices && filesystem::is_block_device(*entry_type))
|
||||
|| (!self.char_devices && filesystem::is_char_device(*entry_type))
|
||||
|| (!self.sockets && filesystem::is_socket(*entry_type))
|
||||
|| (!self.pipes && filesystem::is_pipe(*entry_type))
|
||||
|| (self.executables_only
|
||||
&& !entry
|
||||
.metadata()
|
||||
.map(|m| filesystem::is_executable(m))
|
||||
.unwrap_or(false))
|
||||
|| (self.executables_only && !entry.path().executable())
|
||||
|| (self.empty_only && !filesystem::is_empty(entry))
|
||||
|| !(entry_type.is_file()
|
||||
|| entry_type.is_dir()
|
||||
|| entry_type.is_symlink()
|
||||
|| filesystem::is_block_device(*entry_type)
|
||||
|| filesystem::is_char_device(*entry_type)
|
||||
|| filesystem::is_socket(*entry_type)
|
||||
|| filesystem::is_pipe(*entry_type))
|
||||
} else {
|
||||
|
||||
+41
-24
@@ -1,13 +1,14 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use anyhow::{Result, anyhow};
|
||||
use nix::unistd::{Group, User};
|
||||
use std::fs;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct OwnerFilter {
|
||||
uid: Check<u32>,
|
||||
gid: Check<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Check<T> {
|
||||
Equal(T),
|
||||
NotEq(T),
|
||||
@@ -15,10 +16,15 @@ enum Check<T> {
|
||||
}
|
||||
|
||||
impl OwnerFilter {
|
||||
const IGNORE: Self = OwnerFilter {
|
||||
uid: Check::Ignore,
|
||||
gid: Check::Ignore,
|
||||
};
|
||||
|
||||
/// Parses an owner constraint
|
||||
/// Returns an error if the string is invalid
|
||||
/// Returns Ok(None) when string is acceptable but a noop (such as "" or ":")
|
||||
pub fn from_string(input: &str) -> Result<Option<Self>> {
|
||||
pub fn from_string(input: &str) -> Result<Self> {
|
||||
let mut it = input.split(':');
|
||||
let (fst, snd) = (it.next(), it.next());
|
||||
|
||||
@@ -30,22 +36,33 @@ impl OwnerFilter {
|
||||
}
|
||||
|
||||
let uid = Check::parse(fst, |s| {
|
||||
s.parse()
|
||||
.ok()
|
||||
.or_else(|| users::get_user_by_name(s).map(|user| user.uid()))
|
||||
.ok_or_else(|| anyhow!("'{}' is not a recognized user name", s))
|
||||
if let Ok(uid) = s.parse() {
|
||||
Ok(uid)
|
||||
} else {
|
||||
User::from_name(s)?
|
||||
.map(|user| user.uid.as_raw())
|
||||
.ok_or_else(|| anyhow!("'{}' is not a recognized user name", s))
|
||||
}
|
||||
})?;
|
||||
let gid = Check::parse(snd, |s| {
|
||||
s.parse()
|
||||
.ok()
|
||||
.or_else(|| users::get_group_by_name(s).map(|group| group.gid()))
|
||||
.ok_or_else(|| anyhow!("'{}' is not a recognized group name", s))
|
||||
if let Ok(gid) = s.parse() {
|
||||
Ok(gid)
|
||||
} else {
|
||||
Group::from_name(s)?
|
||||
.map(|group| group.gid.as_raw())
|
||||
.ok_or_else(|| anyhow!("'{}' is not a recognized group name", s))
|
||||
}
|
||||
})?;
|
||||
|
||||
if let (Check::Ignore, Check::Ignore) = (uid, gid) {
|
||||
Ok(None)
|
||||
Ok(OwnerFilter { uid, gid })
|
||||
}
|
||||
|
||||
/// If self is a no-op (ignore both uid and gid) then return `None`, otherwise wrap in a `Some`
|
||||
pub fn filter_ignore(self) -> Option<Self> {
|
||||
if self == Self::IGNORE {
|
||||
None
|
||||
} else {
|
||||
Ok(Some(OwnerFilter { uid, gid }))
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,16 +123,16 @@ mod owner_parsing {
|
||||
|
||||
use super::Check::*;
|
||||
owner_tests! {
|
||||
empty: "" => Ok(None),
|
||||
uid_only: "5" => Ok(Some(OwnerFilter { uid: Equal(5), gid: Ignore })),
|
||||
uid_gid: "9:3" => Ok(Some(OwnerFilter { uid: Equal(9), gid: Equal(3) })),
|
||||
gid_only: ":8" => Ok(Some(OwnerFilter { uid: Ignore, gid: Equal(8) })),
|
||||
colon_only: ":" => Ok(None),
|
||||
trailing: "5:" => Ok(Some(OwnerFilter { uid: Equal(5), gid: Ignore })),
|
||||
empty: "" => Ok(OwnerFilter::IGNORE),
|
||||
uid_only: "5" => Ok(OwnerFilter { uid: Equal(5), gid: Ignore }),
|
||||
uid_gid: "9:3" => Ok(OwnerFilter { uid: Equal(9), gid: Equal(3) }),
|
||||
gid_only: ":8" => Ok(OwnerFilter { uid: Ignore, gid: Equal(8) }),
|
||||
colon_only: ":" => Ok(OwnerFilter::IGNORE),
|
||||
trailing: "5:" => Ok(OwnerFilter { uid: Equal(5), gid: Ignore }),
|
||||
|
||||
uid_negate: "!5" => Ok(Some(OwnerFilter { uid: NotEq(5), gid: Ignore })),
|
||||
both_negate:"!4:!3" => Ok(Some(OwnerFilter { uid: NotEq(4), gid: NotEq(3) })),
|
||||
uid_not_gid:"6:!8" => Ok(Some(OwnerFilter { uid: Equal(6), gid: NotEq(8) })),
|
||||
uid_negate: "!5" => Ok(OwnerFilter { uid: NotEq(5), gid: Ignore }),
|
||||
both_negate:"!4:!3" => Ok(OwnerFilter { uid: NotEq(4), gid: NotEq(3) }),
|
||||
uid_not_gid:"6:!8" => Ok(OwnerFilter { uid: Equal(6), gid: NotEq(8) }),
|
||||
|
||||
more_colons:"3:5:" => Err(_),
|
||||
only_colons:"::" => Err(_),
|
||||
|
||||
+16
-8
@@ -1,10 +1,11 @@
|
||||
use once_cell::sync::Lazy;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use regex::Regex;
|
||||
|
||||
static SIZE_CAPTURES: Lazy<Regex> =
|
||||
Lazy::new(|| Regex::new(r"(?i)^([+-]?)(\d+)(b|[kmgt]i?b?)$").unwrap());
|
||||
static SIZE_CAPTURES: OnceLock<Regex> = OnceLock::new();
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SizeFilter {
|
||||
Max(u64),
|
||||
Min(u64),
|
||||
@@ -24,12 +25,19 @@ const GIBI: u64 = MEBI * 1024;
|
||||
const TEBI: u64 = GIBI * 1024;
|
||||
|
||||
impl SizeFilter {
|
||||
pub fn from_string(s: &str) -> Option<Self> {
|
||||
if !SIZE_CAPTURES.is_match(s) {
|
||||
pub fn from_string(s: &str) -> anyhow::Result<Self> {
|
||||
SizeFilter::parse_opt(s)
|
||||
.ok_or_else(|| anyhow!("'{}' is not a valid size constraint. See 'fd --help'.", s))
|
||||
}
|
||||
|
||||
fn parse_opt(s: &str) -> Option<Self> {
|
||||
let pattern =
|
||||
SIZE_CAPTURES.get_or_init(|| Regex::new(r"(?i)^([+-]?)(\d+)(b|[kmgt]i?b?)$").unwrap());
|
||||
if !pattern.is_match(s) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let captures = SIZE_CAPTURES.captures(s)?;
|
||||
let captures = pattern.captures(s)?;
|
||||
let limit_kind = captures.get(1).map_or("+", |m| m.as_str());
|
||||
let quantity = captures
|
||||
.get(2)
|
||||
@@ -165,7 +173,7 @@ mod tests {
|
||||
#[test]
|
||||
fn $name() {
|
||||
let i = SizeFilter::from_string($value);
|
||||
assert!(i.is_none());
|
||||
assert!(i.is_err());
|
||||
}
|
||||
)*
|
||||
};
|
||||
|
||||
+164
-85
@@ -1,40 +1,57 @@
|
||||
use chrono::{offset::TimeZone, DateTime, Local, NaiveDate};
|
||||
use jiff::{Span, Timestamp, Zoned, civil::DateTime, tz::TimeZone};
|
||||
|
||||
use std::time::SystemTime;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// Filter based on time ranges.
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum TimeFilter {
|
||||
Before(SystemTime),
|
||||
After(SystemTime),
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn now() -> Zoned {
|
||||
Zoned::now()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static TESTTIME: std::cell::RefCell<Option<Zoned>> = None.into();
|
||||
}
|
||||
|
||||
/// This allows us to set a specific time when running tests
|
||||
#[cfg(test)]
|
||||
fn now() -> Zoned {
|
||||
TESTTIME.with_borrow(|reftime| reftime.as_ref().cloned().unwrap_or_else(Zoned::now))
|
||||
}
|
||||
|
||||
impl TimeFilter {
|
||||
fn from_str(ref_time: &SystemTime, s: &str) -> Option<SystemTime> {
|
||||
humantime::parse_duration(s)
|
||||
.map(|duration| *ref_time - duration)
|
||||
.ok()
|
||||
.or_else(|| {
|
||||
DateTime::parse_from_rfc3339(s)
|
||||
.map(|dt| dt.into())
|
||||
.ok()
|
||||
.or_else(|| {
|
||||
NaiveDate::parse_from_str(s, "%F")
|
||||
.map(|nd| nd.and_hms(0, 0, 0))
|
||||
.ok()
|
||||
.and_then(|ndt| Local.from_local_datetime(&ndt).single())
|
||||
})
|
||||
.or_else(|| Local.datetime_from_str(s, "%F %T").ok())
|
||||
.map(|dt| dt.into())
|
||||
})
|
||||
fn from_str(s: &str) -> Option<SystemTime> {
|
||||
if let Ok(span) = s.parse::<Span>() {
|
||||
let datetime = now().checked_sub(span).ok()?;
|
||||
Some(datetime.into())
|
||||
} else if let Ok(timestamp) = s.parse::<Timestamp>() {
|
||||
Some(timestamp.into())
|
||||
} else if let Ok(datetime) = s.parse::<DateTime>() {
|
||||
Some(
|
||||
TimeZone::system()
|
||||
.to_ambiguous_zoned(datetime)
|
||||
.later()
|
||||
.ok()?
|
||||
.into(),
|
||||
)
|
||||
} else {
|
||||
let timestamp_secs: u64 = s.strip_prefix('@')?.parse().ok()?;
|
||||
UNIX_EPOCH.checked_add(Duration::from_secs(timestamp_secs))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn before(ref_time: &SystemTime, s: &str) -> Option<TimeFilter> {
|
||||
TimeFilter::from_str(ref_time, s).map(TimeFilter::Before)
|
||||
pub fn before(s: &str) -> Option<TimeFilter> {
|
||||
TimeFilter::from_str(s).map(TimeFilter::Before)
|
||||
}
|
||||
|
||||
pub fn after(ref_time: &SystemTime, s: &str) -> Option<TimeFilter> {
|
||||
TimeFilter::from_str(ref_time, s).map(TimeFilter::After)
|
||||
pub fn after(s: &str) -> Option<TimeFilter> {
|
||||
TimeFilter::from_str(s).map(TimeFilter::After)
|
||||
}
|
||||
|
||||
pub fn applies_to(&self, t: &SystemTime) -> bool {
|
||||
@@ -50,82 +67,144 @@ mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
struct TestTime(SystemTime);
|
||||
|
||||
impl TestTime {
|
||||
fn new(time: Zoned) -> Self {
|
||||
TESTTIME.with_borrow_mut(|t| *t = Some(time.clone()));
|
||||
TestTime(time.into())
|
||||
}
|
||||
|
||||
fn set(&mut self, time: Zoned) {
|
||||
TESTTIME.with_borrow_mut(|t| *t = Some(time.clone()));
|
||||
self.0 = time.into();
|
||||
}
|
||||
|
||||
fn timestamp(&self) -> SystemTime {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestTime {
|
||||
fn drop(&mut self) {
|
||||
// Stop using manually set times
|
||||
TESTTIME.with_borrow_mut(|t| *t = None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_time_filter_applicable() {
|
||||
let ref_time = Local
|
||||
.datetime_from_str("2010-10-10 10:10:10", "%F %T")
|
||||
.unwrap()
|
||||
.into();
|
||||
let local_tz = TimeZone::system();
|
||||
let mut test_time = TestTime::new(
|
||||
local_tz
|
||||
.to_ambiguous_zoned("2010-10-10 10:10:10".parse::<DateTime>().unwrap())
|
||||
.later()
|
||||
.unwrap(),
|
||||
);
|
||||
let mut ref_time = test_time.timestamp();
|
||||
|
||||
assert!(TimeFilter::after(&ref_time, "1min")
|
||||
.unwrap()
|
||||
.applies_to(&ref_time));
|
||||
assert!(!TimeFilter::before(&ref_time, "1min")
|
||||
.unwrap()
|
||||
.applies_to(&ref_time));
|
||||
assert!(TimeFilter::after("1min").unwrap().applies_to(&ref_time));
|
||||
assert!(!TimeFilter::before("1min").unwrap().applies_to(&ref_time));
|
||||
|
||||
let t1m_ago = ref_time - Duration::from_secs(60);
|
||||
assert!(!TimeFilter::after(&ref_time, "30sec")
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago));
|
||||
assert!(TimeFilter::after(&ref_time, "2min")
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago));
|
||||
assert!(!TimeFilter::after("30sec").unwrap().applies_to(&t1m_ago));
|
||||
assert!(TimeFilter::after("2min").unwrap().applies_to(&t1m_ago));
|
||||
|
||||
assert!(TimeFilter::before(&ref_time, "30sec")
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago));
|
||||
assert!(!TimeFilter::before(&ref_time, "2min")
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago));
|
||||
assert!(TimeFilter::before("30sec").unwrap().applies_to(&t1m_ago));
|
||||
assert!(!TimeFilter::before("2min").unwrap().applies_to(&t1m_ago));
|
||||
|
||||
let t10s_before = "2010-10-10 10:10:00";
|
||||
assert!(!TimeFilter::before(&ref_time, t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&ref_time));
|
||||
assert!(TimeFilter::before(&ref_time, t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago));
|
||||
assert!(
|
||||
!TimeFilter::before(t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&ref_time)
|
||||
);
|
||||
assert!(
|
||||
TimeFilter::before(t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago)
|
||||
);
|
||||
|
||||
assert!(TimeFilter::after(&ref_time, t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&ref_time));
|
||||
assert!(!TimeFilter::after(&ref_time, t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago));
|
||||
assert!(
|
||||
TimeFilter::after(t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&ref_time)
|
||||
);
|
||||
assert!(!TimeFilter::after(t10s_before).unwrap().applies_to(&t1m_ago));
|
||||
|
||||
let same_day = "2010-10-10";
|
||||
assert!(!TimeFilter::before(&ref_time, same_day)
|
||||
.unwrap()
|
||||
.applies_to(&ref_time));
|
||||
assert!(!TimeFilter::before(&ref_time, same_day)
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago));
|
||||
assert!(!TimeFilter::before(same_day).unwrap().applies_to(&ref_time));
|
||||
assert!(!TimeFilter::before(same_day).unwrap().applies_to(&t1m_ago));
|
||||
|
||||
assert!(TimeFilter::after(&ref_time, same_day)
|
||||
.unwrap()
|
||||
.applies_to(&ref_time));
|
||||
assert!(TimeFilter::after(&ref_time, same_day)
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago));
|
||||
assert!(TimeFilter::after(same_day).unwrap().applies_to(&ref_time));
|
||||
assert!(TimeFilter::after(same_day).unwrap().applies_to(&t1m_ago));
|
||||
|
||||
let ref_time = DateTime::parse_from_rfc3339("2010-10-10T10:10:10+00:00")
|
||||
.unwrap()
|
||||
.into();
|
||||
test_time.set(
|
||||
"2010-10-10T10:10:10+00:00"
|
||||
.parse::<Timestamp>()
|
||||
.unwrap()
|
||||
.to_zoned(local_tz.clone()),
|
||||
);
|
||||
ref_time = test_time.timestamp();
|
||||
let t1m_ago = ref_time - Duration::from_secs(60);
|
||||
let t10s_before = "2010-10-10T10:10:00+00:00";
|
||||
assert!(!TimeFilter::before(&ref_time, t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&ref_time));
|
||||
assert!(TimeFilter::before(&ref_time, t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago));
|
||||
assert!(
|
||||
!TimeFilter::before(t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&ref_time)
|
||||
);
|
||||
assert!(
|
||||
TimeFilter::before(t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago)
|
||||
);
|
||||
|
||||
assert!(TimeFilter::after(&ref_time, t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&ref_time));
|
||||
assert!(!TimeFilter::after(&ref_time, t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago));
|
||||
assert!(
|
||||
TimeFilter::after(t10s_before)
|
||||
.unwrap()
|
||||
.applies_to(&ref_time)
|
||||
);
|
||||
assert!(!TimeFilter::after(t10s_before).unwrap().applies_to(&t1m_ago));
|
||||
|
||||
let ref_timestamp = 1707723412u64; // Mon Feb 12 07:36:52 UTC 2024
|
||||
test_time.set(
|
||||
"2024-02-12T07:36:52+00:00"
|
||||
.parse::<Timestamp>()
|
||||
.unwrap()
|
||||
.to_zoned(local_tz),
|
||||
);
|
||||
ref_time = test_time.timestamp();
|
||||
let t1m_ago = ref_time - Duration::from_secs(60);
|
||||
let t1s_later = ref_time + Duration::from_secs(1);
|
||||
// Timestamp only supported via '@' prefix
|
||||
assert!(TimeFilter::before(&ref_timestamp.to_string()).is_none());
|
||||
assert!(
|
||||
TimeFilter::before(&format!("@{ref_timestamp}"))
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago)
|
||||
);
|
||||
assert!(
|
||||
!TimeFilter::before(&format!("@{ref_timestamp}"))
|
||||
.unwrap()
|
||||
.applies_to(&t1s_later)
|
||||
);
|
||||
assert!(
|
||||
!TimeFilter::after(&format!("@{ref_timestamp}"))
|
||||
.unwrap()
|
||||
.applies_to(&t1m_ago)
|
||||
);
|
||||
assert!(
|
||||
TimeFilter::after(&format!("@{ref_timestamp}"))
|
||||
.unwrap()
|
||||
.applies_to(&t1s_later)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_range_unix_timestamp_is_rejected() {
|
||||
// A '@' timestamp large enough to overflow SystemTime must return
|
||||
// None rather than panicking.
|
||||
assert!(TimeFilter::before(&format!("@{}", u64::MAX)).is_none());
|
||||
assert!(TimeFilter::after(&format!("@{}", u64::MAX)).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,13 +5,13 @@ use crate::filesystem::strip_current_dir;
|
||||
|
||||
/// Removes the parent component of the path
|
||||
pub fn basename(path: &Path) -> &OsStr {
|
||||
path.file_name().unwrap_or_else(|| path.as_os_str())
|
||||
path.file_name().unwrap_or(path.as_os_str())
|
||||
}
|
||||
|
||||
/// Removes the extension from the path
|
||||
pub fn remove_extension(path: &Path) -> OsString {
|
||||
let dirname = dirname(path);
|
||||
let stem = path.file_stem().unwrap_or_else(|| path.as_os_str());
|
||||
let stem = path.file_stem().unwrap_or(path.as_os_str());
|
||||
|
||||
let path = PathBuf::from(dirname).join(stem);
|
||||
|
||||
@@ -34,10 +34,10 @@ pub fn dirname(path: &Path) -> OsString {
|
||||
#[cfg(test)]
|
||||
mod path_tests {
|
||||
use super::*;
|
||||
use std::path::MAIN_SEPARATOR;
|
||||
use std::path::MAIN_SEPARATOR_STR;
|
||||
|
||||
fn correct(input: &str) -> String {
|
||||
input.replace('/', &MAIN_SEPARATOR.to_string())
|
||||
input.replace('/', MAIN_SEPARATOR_STR)
|
||||
}
|
||||
|
||||
macro_rules! func_tests {
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
mod input;
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
use std::path::{Component, Path, Prefix};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use aho_corasick::AhoCorasick;
|
||||
|
||||
use self::input::{basename, dirname, remove_extension};
|
||||
|
||||
/// Designates what should be written to a buffer
|
||||
///
|
||||
/// Each `Token` contains either text, or a placeholder variant, which will be used to generate
|
||||
/// commands after all tokens for a given command template have been collected.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Token {
|
||||
Placeholder,
|
||||
Basename,
|
||||
Parent,
|
||||
NoExt,
|
||||
BasenameNoExt,
|
||||
Text(String),
|
||||
}
|
||||
|
||||
impl Display for Token {
|
||||
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Token::Placeholder => f.write_str("{}")?,
|
||||
Token::Basename => f.write_str("{/}")?,
|
||||
Token::Parent => f.write_str("{//}")?,
|
||||
Token::NoExt => f.write_str("{.}")?,
|
||||
Token::BasenameNoExt => f.write_str("{/.}")?,
|
||||
Token::Text(ref string) => f.write_str(string)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A parsed format string
|
||||
///
|
||||
/// This is either a collection of `Token`s including at least one placeholder variant,
|
||||
/// or a fixed text.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum FormatTemplate {
|
||||
Tokens(Vec<Token>),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
static PLACEHOLDERS: OnceLock<AhoCorasick> = OnceLock::new();
|
||||
|
||||
impl FormatTemplate {
|
||||
pub fn has_tokens(&self) -> bool {
|
||||
matches!(self, FormatTemplate::Tokens(_))
|
||||
}
|
||||
|
||||
pub fn parse(fmt: &str) -> Self {
|
||||
// NOTE: we assume that { and } have the same length
|
||||
const BRACE_LEN: usize = '{'.len_utf8();
|
||||
let mut tokens = Vec::new();
|
||||
let mut remaining = fmt;
|
||||
let mut buf = String::new();
|
||||
let placeholders = PLACEHOLDERS.get_or_init(|| {
|
||||
AhoCorasick::new(["{{", "}}", "{}", "{/}", "{//}", "{.}", "{/.}"]).unwrap()
|
||||
});
|
||||
while let Some(m) = placeholders.find(remaining) {
|
||||
match m.pattern().as_u32() {
|
||||
0 | 1 => {
|
||||
// we found an escaped {{ or }}, so add
|
||||
// everything up to the first char to the buffer
|
||||
// then skip the second one.
|
||||
buf += &remaining[..m.start() + BRACE_LEN];
|
||||
remaining = &remaining[m.end()..];
|
||||
}
|
||||
id if !remaining[m.end()..].starts_with('}') => {
|
||||
buf += &remaining[..m.start()];
|
||||
if !buf.is_empty() {
|
||||
tokens.push(Token::Text(std::mem::take(&mut buf)));
|
||||
}
|
||||
tokens.push(token_from_pattern_id(id));
|
||||
remaining = &remaining[m.end()..];
|
||||
}
|
||||
_ => {
|
||||
// We got a normal pattern, but the final "}"
|
||||
// is escaped, so add up to that to the buffer, then
|
||||
// skip the final }
|
||||
buf += &remaining[..m.end()];
|
||||
remaining = &remaining[m.end() + BRACE_LEN..];
|
||||
}
|
||||
}
|
||||
}
|
||||
// Add the rest of the string to the buffer, and add the final buffer to the tokens
|
||||
if !remaining.is_empty() {
|
||||
buf += remaining;
|
||||
}
|
||||
if tokens.is_empty() {
|
||||
// No placeholders were found, so just return the text
|
||||
return FormatTemplate::Text(buf);
|
||||
}
|
||||
// Add final text segment
|
||||
if !buf.is_empty() {
|
||||
tokens.push(Token::Text(buf));
|
||||
}
|
||||
debug_assert!(!tokens.is_empty());
|
||||
FormatTemplate::Tokens(tokens)
|
||||
}
|
||||
|
||||
/// Generate a result string from this template. If path_separator is Some, then it will replace
|
||||
/// the path separator in all placeholder tokens. Fixed text and tokens are not affected by
|
||||
/// path separator substitution.
|
||||
pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {
|
||||
use Token::*;
|
||||
let path = path.as_ref();
|
||||
|
||||
match *self {
|
||||
Self::Tokens(ref tokens) => {
|
||||
let mut s = OsString::new();
|
||||
for token in tokens {
|
||||
match token {
|
||||
Basename => s.push(Self::replace_separator(basename(path), path_separator)),
|
||||
BasenameNoExt => s.push(Self::replace_separator(
|
||||
&remove_extension(basename(path).as_ref()),
|
||||
path_separator,
|
||||
)),
|
||||
NoExt => s.push(Self::replace_separator(
|
||||
&remove_extension(path),
|
||||
path_separator,
|
||||
)),
|
||||
Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),
|
||||
Placeholder => {
|
||||
s.push(Self::replace_separator(path.as_ref(), path_separator))
|
||||
}
|
||||
Text(string) => s.push(string),
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
Self::Text(ref text) => OsString::from(text),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the path separator in the input with the custom separator string. If path_separator
|
||||
/// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is
|
||||
/// interpreted as a Path and its components are iterated through and re-joined into a new
|
||||
/// OsString.
|
||||
fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {
|
||||
// fast-path - no replacement necessary
|
||||
if path_separator.is_none() {
|
||||
return Cow::Borrowed(path);
|
||||
}
|
||||
|
||||
let path_separator = path_separator.unwrap();
|
||||
let mut out = OsString::with_capacity(path.len());
|
||||
let mut components = Path::new(path).components().peekable();
|
||||
|
||||
while let Some(comp) = components.next() {
|
||||
match comp {
|
||||
// Absolute paths on Windows are tricky. A Prefix component is usually a drive
|
||||
// letter or UNC path, and is usually followed by RootDir. There are also
|
||||
// "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to
|
||||
// ignore verbatim path prefixes here because they're very rare, might be
|
||||
// impossible to reach here, and there's no good way to deal with them. If users
|
||||
// are doing something advanced involving verbatim windows paths, they can do their
|
||||
// own output filtering with a tool like sed.
|
||||
Component::Prefix(prefix) => {
|
||||
if let Prefix::UNC(server, share) = prefix.kind() {
|
||||
// Prefix::UNC is a parsed version of '\\server\share'
|
||||
out.push(path_separator);
|
||||
out.push(path_separator);
|
||||
out.push(server);
|
||||
out.push(path_separator);
|
||||
out.push(share);
|
||||
} else {
|
||||
// All other Windows prefix types are rendered as-is. This results in e.g. "C:" for
|
||||
// drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,
|
||||
// but they're not returned by directories fd can search anyway so we don't worry
|
||||
// about them.
|
||||
out.push(comp.as_os_str());
|
||||
}
|
||||
}
|
||||
|
||||
// Root directory is always replaced with the custom separator.
|
||||
Component::RootDir => out.push(path_separator),
|
||||
|
||||
// Everything else is joined normally, with a trailing separator if we're not last
|
||||
_ => {
|
||||
out.push(comp.as_os_str());
|
||||
if components.peek().is_some() {
|
||||
out.push(path_separator);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Cow::Owned(out)
|
||||
}
|
||||
}
|
||||
|
||||
// Convert the id from an aho-corasick match to the
|
||||
// appropriate token
|
||||
fn token_from_pattern_id(id: u32) -> Token {
|
||||
use Token::*;
|
||||
match id {
|
||||
2 => Placeholder,
|
||||
3 => Basename,
|
||||
4 => Parent,
|
||||
5 => NoExt,
|
||||
6 => BasenameNoExt,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod fmt_tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn parse_no_placeholders() {
|
||||
let templ = FormatTemplate::parse("This string has no placeholders");
|
||||
assert_eq!(
|
||||
templ,
|
||||
FormatTemplate::Text("This string has no placeholders".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_only_brace_escapes() {
|
||||
let templ = FormatTemplate::parse("This string only has escapes like {{ and }}");
|
||||
assert_eq!(
|
||||
templ,
|
||||
FormatTemplate::Text("This string only has escapes like { and }".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_placeholders() {
|
||||
use Token::*;
|
||||
|
||||
let templ = FormatTemplate::parse(
|
||||
"{{path={} \
|
||||
basename={/} \
|
||||
parent={//} \
|
||||
noExt={.} \
|
||||
basenameNoExt={/.} \
|
||||
}}",
|
||||
);
|
||||
assert_eq!(
|
||||
templ,
|
||||
FormatTemplate::Tokens(vec![
|
||||
Text("{path=".into()),
|
||||
Placeholder,
|
||||
Text(" basename=".into()),
|
||||
Basename,
|
||||
Text(" parent=".into()),
|
||||
Parent,
|
||||
Text(" noExt=".into()),
|
||||
NoExt,
|
||||
Text(" basenameNoExt=".into()),
|
||||
BasenameNoExt,
|
||||
Text(" }".into()),
|
||||
])
|
||||
);
|
||||
|
||||
let mut path = PathBuf::new();
|
||||
path.push("a");
|
||||
path.push("folder");
|
||||
path.push("file.txt");
|
||||
|
||||
let expanded = templ.generate(&path, Some("/")).into_string().unwrap();
|
||||
|
||||
assert_eq!(
|
||||
expanded,
|
||||
"{path=a/folder/file.txt \
|
||||
basename=file.txt \
|
||||
parent=a/folder \
|
||||
noExt=a/folder/file \
|
||||
basenameNoExt=file }"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
use crate::filesystem::absolute_path;
|
||||
use std::fmt::{self, Formatter, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) struct PathUrl(PathBuf);
|
||||
|
||||
impl PathUrl {
|
||||
pub(crate) fn new(path: &Path) -> Option<PathUrl> {
|
||||
Some(PathUrl(absolute_path(path).ok()?))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for PathUrl {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "file://{}", host())?;
|
||||
let bytes = self.0.as_os_str().as_encoded_bytes();
|
||||
for &byte in bytes.iter() {
|
||||
encode(f, byte)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn encode(f: &mut Formatter, byte: u8) -> fmt::Result {
|
||||
// NOTE:
|
||||
// Most terminals can handle non-ascii unicode characters in a file url fine. But on some OSes (notably
|
||||
// windows), the encoded bytes of the path may not be valid UTF-8. Since we don't know if a
|
||||
// byte >= 128 is part of a valid UTF-8 encoding or not, we just percent encode any non-ascii
|
||||
// byte.
|
||||
// Percent encoding these bytes is probably safer anyway.
|
||||
match byte {
|
||||
b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'/' | b':' | b'-' | b'.' | b'_' | b'~' => {
|
||||
f.write_char(byte.into())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
b'\\' => f.write_char('/'),
|
||||
_ => {
|
||||
write!(f, "%{byte:02X}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn host() -> &'static str {
|
||||
use std::sync::OnceLock;
|
||||
|
||||
static HOSTNAME: OnceLock<String> = OnceLock::new();
|
||||
|
||||
HOSTNAME
|
||||
.get_or_init(|| {
|
||||
nix::unistd::gethostname()
|
||||
.ok()
|
||||
.and_then(|h| h.into_string().ok())
|
||||
.unwrap_or_default()
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
const fn host() -> &'static str {
|
||||
"/"
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
// This allows us to test the encoding without having to worry about the host, or absolute path
|
||||
struct Encoded(&'static str);
|
||||
|
||||
impl fmt::Display for Encoded {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
for byte in self.0.bytes() {
|
||||
encode(f, byte)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unicode_encoding() {
|
||||
assert_eq!(
|
||||
Encoded("$*\x1bßé/∫😃\x07").to_string(),
|
||||
"%24%2A%1B%C3%9F%C3%A9/%E2%88%AB%F0%9F%98%83%07",
|
||||
);
|
||||
}
|
||||
}
|
||||
+260
-273
@@ -1,47 +1,57 @@
|
||||
mod app;
|
||||
mod cli;
|
||||
mod config;
|
||||
mod dir_entry;
|
||||
mod error;
|
||||
mod exec;
|
||||
mod exit_codes;
|
||||
mod filesystem;
|
||||
mod filetypes;
|
||||
mod filter;
|
||||
mod fmt;
|
||||
mod hyperlink;
|
||||
mod output;
|
||||
mod regex_helper;
|
||||
mod sanitize;
|
||||
mod walk;
|
||||
|
||||
use std::env;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::io::IsTerminal;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time;
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use atty::Stream;
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use clap::{CommandFactory, Parser};
|
||||
use globset::GlobBuilder;
|
||||
use lscolors::LsColors;
|
||||
use normpath::PathExt;
|
||||
use regex::bytes::{RegexBuilder, RegexSetBuilder};
|
||||
use regex::bytes::{Regex, RegexBuilder, RegexSetBuilder};
|
||||
|
||||
use crate::cli::{ColorWhen, HyperlinkWhen, Opts};
|
||||
use crate::config::Config;
|
||||
use crate::error::print_error;
|
||||
use crate::exec::CommandTemplate;
|
||||
use crate::exec::CommandSet;
|
||||
use crate::exit_codes::ExitCode;
|
||||
use crate::filetypes::FileTypes;
|
||||
#[cfg(unix)]
|
||||
use crate::filter::OwnerFilter;
|
||||
use crate::filter::{SizeFilter, TimeFilter};
|
||||
use crate::filter::TimeFilter;
|
||||
use crate::regex_helper::{pattern_has_uppercase_char, pattern_matches_strings_with_leading_dot};
|
||||
|
||||
// We use jemalloc for performance reasons, see https://github.com/sharkdp/fd/pull/481
|
||||
// FIXME: re-enable jemalloc on macOS, see comment in Cargo.toml file for more infos
|
||||
// This has to be kept in sync with the Cargo.toml file section that declares a
|
||||
// dependency on tikv-jemallocator.
|
||||
#[cfg(all(
|
||||
not(windows),
|
||||
not(target_os = "android"),
|
||||
not(target_os = "macos"),
|
||||
not(target_env = "musl")
|
||||
not(target_os = "freebsd"),
|
||||
not(target_os = "openbsd"),
|
||||
not(target_os = "illumos"),
|
||||
not(all(target_env = "musl", target_pointer_width = "32")),
|
||||
not(target_arch = "riscv64"),
|
||||
feature = "use-jemalloc"
|
||||
))]
|
||||
#[global_allocator]
|
||||
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
|
||||
static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
|
||||
|
||||
// vivid --color-mode 8-bit generate molokai
|
||||
const DEFAULT_LS_COLORS: &str = "
|
||||
@@ -56,33 +66,70 @@ fn main() {
|
||||
exit_code.exit();
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("[fd error]: {:#}", err);
|
||||
crate::error::print_error(format!("{err:#}"));
|
||||
ExitCode::GeneralError.exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> Result<ExitCode> {
|
||||
let matches = app::build_app().get_matches_from(env::args_os());
|
||||
let opts = Opts::parse();
|
||||
|
||||
set_working_dir(&matches)?;
|
||||
let current_directory = Path::new(".");
|
||||
ensure_current_directory_exists(current_directory)?;
|
||||
let search_paths = extract_search_paths(&matches, current_directory)?;
|
||||
#[cfg(feature = "completions")]
|
||||
if let Some(shell) = opts.gen_completions()? {
|
||||
return print_completions(shell);
|
||||
}
|
||||
|
||||
let pattern = extract_search_pattern(&matches)?;
|
||||
ensure_search_pattern_is_not_a_path(&matches, pattern)?;
|
||||
let pattern_regex = build_pattern_regex(&matches, pattern)?;
|
||||
set_working_dir(&opts)?;
|
||||
let search_paths = opts.search_paths()?;
|
||||
if search_paths.is_empty() {
|
||||
bail!("No valid search paths given.");
|
||||
}
|
||||
|
||||
let config = construct_config(matches, &pattern_regex)?;
|
||||
ensure_use_hidden_option_for_leading_dot_pattern(&config, &pattern_regex)?;
|
||||
let re = build_regex(pattern_regex, &config)?;
|
||||
walk::scan(&search_paths, Arc::new(re), Arc::new(config))
|
||||
ensure_search_pattern_is_not_a_path(&opts)?;
|
||||
let pattern = &opts.pattern;
|
||||
let exprs = &opts.exprs;
|
||||
let empty = Vec::new();
|
||||
|
||||
let pattern_regexps = exprs
|
||||
.as_ref()
|
||||
.unwrap_or(&empty)
|
||||
.iter()
|
||||
.chain([pattern])
|
||||
.map(|pat| build_pattern_regex(pat, &opts))
|
||||
.collect::<Result<Vec<String>>>()?;
|
||||
|
||||
let config = construct_config(opts, &pattern_regexps)?;
|
||||
|
||||
ensure_use_hidden_option_for_leading_dot_pattern(&config, &pattern_regexps)?;
|
||||
|
||||
let regexps = pattern_regexps
|
||||
.into_iter()
|
||||
.map(|pat| build_regex(pat, &config))
|
||||
.collect::<Result<Vec<Regex>>>()?;
|
||||
|
||||
walk::scan(&search_paths, regexps, config)
|
||||
}
|
||||
|
||||
fn set_working_dir(matches: &clap::ArgMatches) -> Result<()> {
|
||||
if let Some(base_directory) = matches.value_of_os("base-directory") {
|
||||
let base_directory = Path::new(base_directory);
|
||||
#[cfg(feature = "completions")]
|
||||
#[cold]
|
||||
fn print_completions(shell: clap_complete::Shell) -> Result<ExitCode> {
|
||||
// The program name is the first argument.
|
||||
let first_arg = env::args().next();
|
||||
let program_name = first_arg
|
||||
.as_ref()
|
||||
.map(Path::new)
|
||||
.and_then(|path| path.file_stem())
|
||||
.and_then(|file| file.to_str())
|
||||
.unwrap_or("fd");
|
||||
let mut cmd = Opts::command();
|
||||
cmd.build();
|
||||
clap_complete::generate(shell, &mut cmd, program_name, &mut std::io::stdout());
|
||||
Ok(ExitCode::Success)
|
||||
}
|
||||
|
||||
fn set_working_dir(opts: &Opts) -> Result<()> {
|
||||
if let Some(ref base_directory) = opts.base_directory {
|
||||
if !filesystem::is_existing_directory(base_directory) {
|
||||
return Err(anyhow!(
|
||||
"The '--base-directory' path '{}' is not a directory.",
|
||||
@@ -99,95 +146,84 @@ fn set_working_dir(matches: &clap::ArgMatches) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_current_directory_exists(current_directory: &Path) -> Result<()> {
|
||||
if filesystem::is_existing_directory(current_directory) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!(
|
||||
"Could not retrieve current directory (has it been deleted?)."
|
||||
))
|
||||
/// Detect if the user accidentally supplied a path instead of a search pattern.
|
||||
///
|
||||
/// Without `--full-path`, fd matches patterns against file names, so any pattern
|
||||
/// containing a path separator can never match. This applies to the primary
|
||||
/// positional pattern *and* to every `--and` pattern, since all of them are
|
||||
/// chained together and matched against the file name (see `run`). Two cases per
|
||||
/// pattern are worth a friendly error rather than silent "no results":
|
||||
///
|
||||
/// 1. The pattern contains '/'. '/' is always a path separator (including on
|
||||
/// Windows) and has no regex meaning, so flagging it is safe and catches the
|
||||
/// common Linux/macOS mistake of pasting a full path as the pattern.
|
||||
/// 2. On Windows only, the pattern contains the native `\` separator *and*
|
||||
/// names an existing directory on disk. We can't treat `\` as a pure
|
||||
/// path-separator signal there because it is also the regex escape char,
|
||||
/// so valid regex patterns like `\Ac` or `\d+` must still run. Requiring
|
||||
/// that the pattern resolves to a real directory avoids those false
|
||||
/// positives while preserving the legacy diagnostic for operators who
|
||||
/// literally typed a directory path.
|
||||
///
|
||||
/// See https://github.com/sharkdp/fd/issues/1873.
|
||||
fn ensure_search_pattern_is_not_a_path(opts: &Opts) -> Result<()> {
|
||||
if opts.full_path {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Check the primary pattern and every `--and` pattern. They are all matched
|
||||
// against the file name (see `run`), so a path separator in any of them is
|
||||
// the same silent "no results" footgun.
|
||||
for pattern in std::iter::once(&opts.pattern).chain(opts.exprs.iter().flatten()) {
|
||||
ensure_single_search_pattern_is_not_a_path(pattern)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn extract_search_pattern<'a>(matches: &'a clap::ArgMatches) -> Result<&'a str> {
|
||||
let pattern = matches
|
||||
.value_of_os("pattern")
|
||||
.map(|p| {
|
||||
p.to_str()
|
||||
.ok_or_else(|| anyhow!("The search pattern includes invalid UTF-8 sequences."))
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or("");
|
||||
Ok(pattern)
|
||||
}
|
||||
/// Apply the path-separator diagnostic to a single pattern. See
|
||||
/// [`ensure_search_pattern_is_not_a_path`] for the rationale of each case.
|
||||
fn ensure_single_search_pattern_is_not_a_path(pattern: &str) -> Result<()> {
|
||||
// Start with the cheap check: '/' is always a path separator, including on
|
||||
// Windows, and has no regex meaning, so flagging it is safe and catches the
|
||||
// Linux/macOS mistake of pasting a full path as the pattern.
|
||||
#[cfg_attr(not(windows), allow(unused_mut))]
|
||||
let mut should_warn = pattern.contains('/');
|
||||
|
||||
fn extract_search_paths(
|
||||
matches: &clap::ArgMatches,
|
||||
current_directory: &Path,
|
||||
) -> Result<Vec<PathBuf>> {
|
||||
let mut search_paths = matches
|
||||
.values_of_os("path")
|
||||
.or_else(|| matches.values_of_os("search-path"))
|
||||
.map_or_else(
|
||||
|| vec![current_directory.to_path_buf()],
|
||||
|paths| {
|
||||
paths
|
||||
.filter_map(|path| {
|
||||
let path_buffer = PathBuf::from(path);
|
||||
if filesystem::is_existing_directory(&path_buffer) {
|
||||
Some(path_buffer)
|
||||
} else {
|
||||
print_error(format!(
|
||||
"Search path '{}' is not a directory.",
|
||||
path_buffer.to_string_lossy()
|
||||
));
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
},
|
||||
);
|
||||
if search_paths.is_empty() {
|
||||
return Err(anyhow!("No valid search paths given."));
|
||||
}
|
||||
if matches.is_present("absolute-path") {
|
||||
update_to_absolute_paths(&mut search_paths);
|
||||
}
|
||||
Ok(search_paths)
|
||||
}
|
||||
|
||||
fn update_to_absolute_paths(search_paths: &mut [PathBuf]) {
|
||||
for buffer in search_paths.iter_mut() {
|
||||
*buffer = filesystem::absolute_path(buffer.normalize().unwrap().as_path()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Detect if the user accidentally supplied a path instead of a search pattern
|
||||
fn ensure_search_pattern_is_not_a_path(matches: &clap::ArgMatches, pattern: &str) -> Result<()> {
|
||||
if !matches.is_present("full-path")
|
||||
&& pattern.contains(std::path::MAIN_SEPARATOR)
|
||||
&& Path::new(pattern).is_dir()
|
||||
// On Windows we additionally accept the native `\` separator, but only when
|
||||
// the pattern actually resolves to an existing directory - `\` is also the
|
||||
// regex escape char there, so valid patterns like `\Ac` or `\d+` must still
|
||||
// run. The is_dir syscall is only needed when `should_warn` is still false,
|
||||
// so short-circuit via `||` to avoid the stat call on the happy path.
|
||||
#[cfg(windows)]
|
||||
{
|
||||
should_warn = should_warn
|
||||
|| (pattern.contains(std::path::MAIN_SEPARATOR) && Path::new(pattern).is_dir());
|
||||
}
|
||||
|
||||
if should_warn {
|
||||
Err(anyhow!(
|
||||
"The search pattern '{pattern}' contains a path-separation character ('{sep}') \
|
||||
"The search pattern '{pattern}' contains a path-separation character \
|
||||
and will not lead to any search results.\n\n\
|
||||
If you want to search for all files inside the '{pattern}' directory, use a match-all pattern:\n\n \
|
||||
fd . '{pattern}'\n\n\
|
||||
Instead, if you want your pattern to match the full file path, use:\n\n \
|
||||
fd --full-path '{pattern}'",
|
||||
pattern = pattern,
|
||||
sep = std::path::MAIN_SEPARATOR,
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn build_pattern_regex(matches: &clap::ArgMatches, pattern: &str) -> Result<String> {
|
||||
Ok(if matches.is_present("glob") && !pattern.is_empty() {
|
||||
fn build_pattern_regex(pattern: &str, opts: &Opts) -> Result<String> {
|
||||
Ok(if opts.glob && !pattern.is_empty() {
|
||||
let glob = GlobBuilder::new(pattern).literal_separator(true).build()?;
|
||||
glob.regex().to_owned()
|
||||
} else if matches.is_present("fixed-strings") {
|
||||
} else if opts.exact {
|
||||
// Anchor the escaped pattern so the full filename (or path) must match exactly.
|
||||
// Literal. No substring matching.
|
||||
format!("^{}$", regex::escape(pattern))
|
||||
} else if opts.fixed_strings {
|
||||
// Treat pattern as literal string if '--fixed-strings' is used
|
||||
regex::escape(pattern)
|
||||
} else {
|
||||
@@ -209,37 +245,44 @@ fn check_path_separator_length(path_separator: Option<&str>) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
fn construct_config(matches: clap::ArgMatches, pattern_regex: &str) -> Result<Config> {
|
||||
fn construct_config(mut opts: Opts, pattern_regexps: &[String]) -> Result<Config> {
|
||||
// The search will be case-sensitive if the command line flag is set or
|
||||
// if the pattern has an uppercase character (smart case).
|
||||
let case_sensitive = !matches.is_present("ignore-case")
|
||||
&& (matches.is_present("case-sensitive") || pattern_has_uppercase_char(pattern_regex));
|
||||
// if any of the patterns has an uppercase character (smart case).
|
||||
let case_sensitive = !opts.ignore_case
|
||||
&& (opts.case_sensitive
|
||||
|| pattern_regexps
|
||||
.iter()
|
||||
.any(|pat| pattern_has_uppercase_char(pat)));
|
||||
|
||||
let path_separator = matches
|
||||
.value_of("path-separator")
|
||||
.map_or_else(filesystem::default_path_separator, |s| Some(s.to_owned()));
|
||||
let path_separator = opts
|
||||
.path_separator
|
||||
.take()
|
||||
.or_else(filesystem::default_path_separator);
|
||||
let actual_path_separator = path_separator
|
||||
.clone()
|
||||
.unwrap_or_else(|| std::path::MAIN_SEPARATOR.to_string());
|
||||
check_path_separator_length(path_separator.as_deref())?;
|
||||
|
||||
let size_limits = extract_size_limits(&matches)?;
|
||||
let time_constraints = extract_time_constraints(&matches)?;
|
||||
let size_limits = std::mem::take(&mut opts.size);
|
||||
let time_constraints = extract_time_constraints(&opts)?;
|
||||
#[cfg(unix)]
|
||||
let owner_constraint = matches
|
||||
.value_of("owner")
|
||||
.map(OwnerFilter::from_string)
|
||||
.transpose()?
|
||||
.flatten();
|
||||
let owner_constraint: Option<OwnerFilter> = opts.owner.and_then(OwnerFilter::filter_ignore);
|
||||
|
||||
#[cfg(windows)]
|
||||
let ansi_colors_support =
|
||||
ansi_term::enable_ansi_support().is_ok() || std::env::var_os("TERM").is_some();
|
||||
nu_ansi_term::enable_ansi_support().is_ok() || std::env::var_os("TERM").is_some();
|
||||
#[cfg(not(windows))]
|
||||
let ansi_colors_support = true;
|
||||
|
||||
let interactive_terminal = atty::is(Stream::Stdout);
|
||||
let colored_output = match matches.value_of("color") {
|
||||
Some("always") => true,
|
||||
Some("never") => false,
|
||||
_ => ansi_colors_support && env::var_os("NO_COLOR").is_none() && interactive_terminal,
|
||||
let interactive_terminal = std::io::stdout().is_terminal();
|
||||
|
||||
let colored_output = match opts.color {
|
||||
ColorWhen::Always => true,
|
||||
ColorWhen::Never => false,
|
||||
ColorWhen::Auto => {
|
||||
let no_color = env::var_os("NO_COLOR").is_some_and(|x| !x.is_empty());
|
||||
ansi_colors_support && !no_color && interactive_terminal
|
||||
}
|
||||
};
|
||||
|
||||
let ls_colors = if colored_output {
|
||||
@@ -247,83 +290,63 @@ fn construct_config(matches: clap::ArgMatches, pattern_regex: &str) -> Result<Co
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let command = extract_command(&matches, path_separator.as_deref(), colored_output)?;
|
||||
let hyperlink = match opts.hyperlink {
|
||||
HyperlinkWhen::Always => true,
|
||||
HyperlinkWhen::Never => false,
|
||||
HyperlinkWhen::Auto => colored_output,
|
||||
};
|
||||
let command = extract_command(&mut opts, colored_output)?;
|
||||
let has_command = command.is_some();
|
||||
|
||||
let full_path_base = if opts.full_path {
|
||||
Some(env::current_dir().context(
|
||||
"Could not determine current directory. \
|
||||
This is required for --full-path.",
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(Config {
|
||||
case_sensitive,
|
||||
search_full_path: matches.is_present("full-path"),
|
||||
ignore_hidden: !(matches.is_present("hidden")
|
||||
|| matches.occurrences_of("rg-alias-hidden-ignore") >= 2),
|
||||
read_fdignore: !(matches.is_present("no-ignore")
|
||||
|| matches.is_present("rg-alias-hidden-ignore")),
|
||||
read_vcsignore: !(matches.is_present("no-ignore")
|
||||
|| matches.is_present("rg-alias-hidden-ignore")
|
||||
|| matches.is_present("no-ignore-vcs")),
|
||||
read_parent_ignore: !(matches.is_present("no-ignore")
|
||||
|| matches.is_present("rg-alias-hidden-ignore")
|
||||
|| matches.is_present("no-ignore-vcs")
|
||||
|| matches.is_present("no-ignore-parent")),
|
||||
read_global_ignore: !(matches.is_present("no-ignore")
|
||||
|| matches.is_present("rg-alias-hidden-ignore")
|
||||
|| matches.is_present("no-global-ignore-file")),
|
||||
follow_links: matches.is_present("follow"),
|
||||
one_file_system: matches.is_present("one-file-system"),
|
||||
null_separator: matches.is_present("null_separator"),
|
||||
quiet: matches.is_present("quiet"),
|
||||
max_depth: matches
|
||||
.value_of("max-depth")
|
||||
.or_else(|| matches.value_of("rg-depth"))
|
||||
.or_else(|| matches.value_of("exact-depth"))
|
||||
.map(|n| n.parse::<usize>())
|
||||
.transpose()
|
||||
.context("Failed to parse argument to --max-depth/--exact-depth")?,
|
||||
min_depth: matches
|
||||
.value_of("min-depth")
|
||||
.or_else(|| matches.value_of("exact-depth"))
|
||||
.map(|n| n.parse::<usize>())
|
||||
.transpose()
|
||||
.context("Failed to parse argument to --min-depth/--exact-depth")?,
|
||||
prune: matches.is_present("prune"),
|
||||
threads: std::cmp::max(
|
||||
matches
|
||||
.value_of("threads")
|
||||
.map(|n| n.parse::<usize>())
|
||||
.transpose()
|
||||
.context("Failed to parse number of threads")?
|
||||
.map(|n| {
|
||||
if n > 0 {
|
||||
Ok(n)
|
||||
} else {
|
||||
Err(anyhow!("Number of threads must be positive."))
|
||||
}
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or_else(num_cpus::get),
|
||||
1,
|
||||
),
|
||||
max_buffer_time: matches
|
||||
.value_of("max-buffer-time")
|
||||
.map(|n| n.parse::<u64>())
|
||||
.transpose()
|
||||
.context("Failed to parse max. buffer time argument")?
|
||||
.map(time::Duration::from_millis),
|
||||
full_path_base,
|
||||
ignore_hidden: !(opts.hidden || opts.rg_alias_ignore()),
|
||||
read_fdignore: !(opts.no_ignore || opts.rg_alias_ignore()),
|
||||
read_vcsignore: !(opts.no_ignore || opts.rg_alias_ignore() || opts.no_ignore_vcs),
|
||||
require_git_to_read_vcsignore: !opts.no_require_git,
|
||||
read_parent_ignore: !opts.no_ignore_parent,
|
||||
read_global_ignore: !(opts.no_ignore
|
||||
|| opts.rg_alias_ignore()
|
||||
|| opts.no_global_ignore_file),
|
||||
follow_links: opts.follow,
|
||||
one_file_system: opts.one_file_system,
|
||||
null_separator: opts.null_separator,
|
||||
quiet: opts.quiet,
|
||||
max_depth: opts.max_depth(),
|
||||
min_depth: opts.min_depth(),
|
||||
prune: opts.prune,
|
||||
threads: opts.threads().get(),
|
||||
max_buffer_time: opts.max_buffer_time,
|
||||
ls_colors,
|
||||
hyperlink,
|
||||
interactive_terminal,
|
||||
file_types: matches.values_of("file-type").map(|values| {
|
||||
file_types: opts.filetype.as_ref().map(|values| {
|
||||
use crate::cli::FileType::*;
|
||||
let mut file_types = FileTypes::default();
|
||||
for value in values {
|
||||
match value {
|
||||
"f" | "file" => file_types.files = true,
|
||||
"d" | "directory" => file_types.directories = true,
|
||||
"l" | "symlink" => file_types.symlinks = true,
|
||||
"x" | "executable" => {
|
||||
File => file_types.files = true,
|
||||
Directory => file_types.directories = true,
|
||||
Symlink => file_types.symlinks = true,
|
||||
Executable => {
|
||||
file_types.executables_only = true;
|
||||
file_types.files = true;
|
||||
}
|
||||
"e" | "empty" => file_types.empty_only = true,
|
||||
"s" | "socket" => file_types.sockets = true,
|
||||
"p" | "pipe" => file_types.pipes = true,
|
||||
_ => unreachable!(),
|
||||
Empty => file_types.empty_only = true,
|
||||
BlockDevice => file_types.block_devices = true,
|
||||
CharDevice => file_types.char_devices = true,
|
||||
Socket => file_types.sockets = true,
|
||||
Pipe => file_types.pipes = true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,10 +358,12 @@ fn construct_config(matches: clap::ArgMatches, pattern_regex: &str) -> Result<Co
|
||||
|
||||
file_types
|
||||
}),
|
||||
extensions: matches
|
||||
.values_of("extension")
|
||||
extensions: opts
|
||||
.extensions
|
||||
.as_ref()
|
||||
.map(|exts| {
|
||||
let patterns = exts
|
||||
.iter()
|
||||
.map(|e| e.trim_start_matches('.'))
|
||||
.map(|e| format!(r".\.{}$", regex::escape(e)));
|
||||
RegexSetBuilder::new(patterns)
|
||||
@@ -346,84 +371,52 @@ fn construct_config(matches: clap::ArgMatches, pattern_regex: &str) -> Result<Co
|
||||
.build()
|
||||
})
|
||||
.transpose()?,
|
||||
format: opts
|
||||
.format
|
||||
.as_deref()
|
||||
.map(crate::fmt::FormatTemplate::parse),
|
||||
command: command.map(Arc::new),
|
||||
batch_size: matches
|
||||
.value_of("batch-size")
|
||||
.map(|n| n.parse::<usize>())
|
||||
.transpose()
|
||||
.context("Failed to parse --batch-size argument")?
|
||||
.unwrap_or_default(),
|
||||
exclude_patterns: matches
|
||||
.values_of("exclude")
|
||||
.map(|v| v.map(|p| String::from("!") + p).collect())
|
||||
.unwrap_or_else(Vec::new),
|
||||
ignore_files: matches
|
||||
.values_of("ignore-file")
|
||||
.map(|vs| vs.map(PathBuf::from).collect())
|
||||
.unwrap_or_else(Vec::new),
|
||||
batch_size: opts.batch_size,
|
||||
exclude_patterns: opts.exclude.iter().map(|p| String::from("!") + p).collect(),
|
||||
ignore_files: std::mem::take(&mut opts.ignore_file),
|
||||
size_constraints: size_limits,
|
||||
time_constraints,
|
||||
#[cfg(unix)]
|
||||
owner_constraint,
|
||||
show_filesystem_errors: matches.is_present("show-errors"),
|
||||
show_filesystem_errors: opts.show_errors,
|
||||
path_separator,
|
||||
max_results: matches
|
||||
.value_of("max-results")
|
||||
.map(|n| n.parse::<usize>())
|
||||
.transpose()
|
||||
.context("Failed to parse --max-results argument")?
|
||||
.filter(|&n| n > 0)
|
||||
.or_else(|| {
|
||||
if matches.is_present("max-one-result") {
|
||||
Some(1)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}),
|
||||
strip_cwd_prefix: (!matches.is_present("path")
|
||||
&& !matches.is_present("search-path")
|
||||
&& (interactive_terminal || matches.is_present("strip-cwd-prefix"))),
|
||||
actual_path_separator,
|
||||
max_results: opts.max_results(),
|
||||
strip_cwd_prefix: opts.strip_cwd_prefix(|| !(opts.null_separator || has_command)),
|
||||
ignore_contain: opts.ignore_contain,
|
||||
})
|
||||
}
|
||||
|
||||
fn extract_command(
|
||||
matches: &clap::ArgMatches,
|
||||
path_separator: Option<&str>,
|
||||
colored_output: bool,
|
||||
) -> Result<Option<CommandTemplate>> {
|
||||
None.or_else(|| {
|
||||
matches.values_of("exec").map(|args| {
|
||||
Ok(CommandTemplate::new(
|
||||
args,
|
||||
path_separator.map(str::to_string),
|
||||
))
|
||||
fn extract_command(opts: &mut Opts, colored_output: bool) -> Result<Option<CommandSet>> {
|
||||
opts.exec
|
||||
.command
|
||||
.take()
|
||||
.map(Ok)
|
||||
.or_else(|| {
|
||||
if !opts.list_details {
|
||||
return None;
|
||||
}
|
||||
|
||||
let res = determine_ls_command(colored_output)
|
||||
.map(|cmd| CommandSet::new_batch([cmd]).unwrap());
|
||||
Some(res)
|
||||
})
|
||||
})
|
||||
.or_else(|| {
|
||||
matches
|
||||
.values_of("exec-batch")
|
||||
.map(|args| CommandTemplate::new_batch(args, path_separator.map(str::to_string)))
|
||||
})
|
||||
.or_else(|| {
|
||||
if !matches.is_present("list-details") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let color = matches.value_of("color").unwrap_or("auto");
|
||||
let color_arg = format!("--color={}", color);
|
||||
|
||||
let res = determine_ls_command(&color_arg, colored_output).map(|cmd| {
|
||||
CommandTemplate::new_batch(cmd, path_separator.map(str::to_string)).unwrap()
|
||||
});
|
||||
|
||||
Some(res)
|
||||
})
|
||||
.transpose()
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn determine_ls_command(color_arg: &str, colored_output: bool) -> Result<Vec<&str>> {
|
||||
fn determine_ls_command(colored_output: bool) -> Result<Vec<&'static str>> {
|
||||
#[allow(unused)]
|
||||
let gnu_ls = |command_name| {
|
||||
let color_arg = if colored_output {
|
||||
"--color=always"
|
||||
} else {
|
||||
"--color=never"
|
||||
};
|
||||
// Note: we use short options here (instead of --long-options) to support more
|
||||
// platforms (like BusyBox).
|
||||
vec![
|
||||
@@ -445,7 +438,7 @@ fn determine_ls_command(color_arg: &str, colored_output: bool) -> Result<Vec<&st
|
||||
// Assume ls is GNU ls
|
||||
gnu_ls("ls")
|
||||
} else {
|
||||
// MacOS, DragonFlyBSD, FreeBSD
|
||||
// macOS, DragonFlyBSD, FreeBSD
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
// Use GNU ls, if available (support for --color=auto, better LS_COLORS support)
|
||||
@@ -500,21 +493,10 @@ fn determine_ls_command(color_arg: &str, colored_output: bool) -> Result<Vec<&st
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
fn extract_size_limits(matches: &clap::ArgMatches) -> Result<Vec<SizeFilter>> {
|
||||
matches.values_of("size").map_or(Ok(Vec::new()), |vs| {
|
||||
vs.map(|sf| {
|
||||
SizeFilter::from_string(sf)
|
||||
.ok_or_else(|| anyhow!("'{}' is not a valid size constraint. See 'fd --help'.", sf))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
})
|
||||
}
|
||||
|
||||
fn extract_time_constraints(matches: &clap::ArgMatches) -> Result<Vec<TimeFilter>> {
|
||||
let now = time::SystemTime::now();
|
||||
fn extract_time_constraints(opts: &Opts) -> Result<Vec<TimeFilter>> {
|
||||
let mut time_constraints: Vec<TimeFilter> = Vec::new();
|
||||
if let Some(t) = matches.value_of("changed-within") {
|
||||
if let Some(f) = TimeFilter::after(&now, t) {
|
||||
if let Some(ref t) = opts.changed_within {
|
||||
if let Some(f) = TimeFilter::after(t) {
|
||||
time_constraints.push(f);
|
||||
} else {
|
||||
return Err(anyhow!(
|
||||
@@ -523,8 +505,8 @@ fn extract_time_constraints(matches: &clap::ArgMatches) -> Result<Vec<TimeFilter
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(t) = matches.value_of("changed-before") {
|
||||
if let Some(f) = TimeFilter::before(&now, t) {
|
||||
if let Some(ref t) = opts.changed_before {
|
||||
if let Some(f) = TimeFilter::before(t) {
|
||||
time_constraints.push(f);
|
||||
} else {
|
||||
return Err(anyhow!(
|
||||
@@ -538,14 +520,18 @@ fn extract_time_constraints(matches: &clap::ArgMatches) -> Result<Vec<TimeFilter
|
||||
|
||||
fn ensure_use_hidden_option_for_leading_dot_pattern(
|
||||
config: &Config,
|
||||
pattern_regex: &str,
|
||||
pattern_regexps: &[String],
|
||||
) -> Result<()> {
|
||||
if cfg!(unix) && config.ignore_hidden && pattern_matches_strings_with_leading_dot(pattern_regex)
|
||||
if cfg!(unix)
|
||||
&& config.ignore_hidden
|
||||
&& pattern_regexps
|
||||
.iter()
|
||||
.any(|pat| pattern_matches_strings_with_leading_dot(pat))
|
||||
{
|
||||
Err(anyhow!(
|
||||
"The pattern seems to only match files with a leading dot, but hidden files are \
|
||||
"The pattern(s) seems to only match files with a leading dot, but hidden files are \
|
||||
filtered by default. Consider adding -H/--hidden to search hidden files as well \
|
||||
or adjust your search pattern."
|
||||
or adjust your search pattern(s)."
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
@@ -559,10 +545,11 @@ fn build_regex(pattern_regex: String, config: &Config) -> Result<regex::bytes::R
|
||||
.build()
|
||||
.map_err(|e| {
|
||||
anyhow!(
|
||||
"{}\n\nNote: You can use the '--fixed-strings' option to search for a \
|
||||
literal string instead of a regular expression. Alternatively, you can \
|
||||
"{}\n\nNote: You can search for literal substrings with '--fixed-strings' \
|
||||
or literal strings with '--exact' options (instead of a regular expression). \
|
||||
Alternatively, you can \
|
||||
also use the '--glob' option to match on a glob pattern.",
|
||||
e.to_string()
|
||||
e
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
+100
-63
@@ -1,59 +1,99 @@
|
||||
use std::borrow::Cow;
|
||||
use std::io::{self, Write};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use lscolors::{Indicator, LsColors, Style};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::error::print_error;
|
||||
use crate::exit_codes::ExitCode;
|
||||
use crate::filesystem::strip_current_dir;
|
||||
use crate::dir_entry::DirEntry;
|
||||
use crate::fmt::FormatTemplate;
|
||||
use crate::hyperlink::PathUrl;
|
||||
use crate::sanitize::maybe_sanitize;
|
||||
|
||||
fn replace_path_separator(path: &str, new_path_separator: &str) -> String {
|
||||
path.replace(std::path::MAIN_SEPARATOR, new_path_separator)
|
||||
}
|
||||
|
||||
// TODO: this function is performance critical and can probably be optimized
|
||||
pub fn print_entry<W: Write>(
|
||||
stdout: &mut W,
|
||||
entry: &Path,
|
||||
config: &Config,
|
||||
wants_to_quit: &AtomicBool,
|
||||
) {
|
||||
let path = if config.strip_cwd_prefix {
|
||||
strip_current_dir(entry)
|
||||
} else {
|
||||
entry
|
||||
};
|
||||
|
||||
let r = if let Some(ref ls_colors) = config.ls_colors {
|
||||
print_entry_colorized(stdout, path, config, ls_colors, wants_to_quit)
|
||||
} else {
|
||||
print_entry_uncolorized(stdout, path, config)
|
||||
};
|
||||
|
||||
if let Err(e) = r {
|
||||
if e.kind() == ::std::io::ErrorKind::BrokenPipe {
|
||||
// Exit gracefully in case of a broken pipe (e.g. 'fd ... | head -n 3').
|
||||
ExitCode::Success.exit();
|
||||
} else {
|
||||
print_error(format!("Could not write to output: {}", e));
|
||||
ExitCode::GeneralError.exit();
|
||||
}
|
||||
pub fn print_entry<W: Write>(stdout: &mut W, entry: &DirEntry, config: &Config) -> io::Result<()> {
|
||||
let mut has_hyperlink = false;
|
||||
if config.hyperlink
|
||||
&& let Some(url) = PathUrl::new(entry.path())
|
||||
{
|
||||
write!(stdout, "\x1B]8;;{url}\x1B\\")?;
|
||||
has_hyperlink = true;
|
||||
}
|
||||
|
||||
if let Some(ref format) = config.format {
|
||||
print_entry_format(stdout, entry, config, format)?;
|
||||
} else if let Some(ref ls_colors) = config.ls_colors {
|
||||
print_entry_colorized(stdout, entry, config, ls_colors)?;
|
||||
} else {
|
||||
print_entry_uncolorized(stdout, entry, config)?;
|
||||
};
|
||||
|
||||
if has_hyperlink {
|
||||
write!(stdout, "\x1B]8;;\x1B\\")?;
|
||||
}
|
||||
|
||||
if config.null_separator {
|
||||
write!(stdout, "\0")
|
||||
} else {
|
||||
writeln!(stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// Display a trailing slash if the path is a directory and the config option is enabled.
|
||||
// If the path_separator option is set, display that instead.
|
||||
// The trailing slash will not be colored.
|
||||
#[inline]
|
||||
fn print_trailing_slash<W: Write>(
|
||||
stdout: &mut W,
|
||||
entry: &DirEntry,
|
||||
config: &Config,
|
||||
style: Option<&Style>,
|
||||
) -> io::Result<()> {
|
||||
if entry.file_type().is_some_and(|ft| ft.is_dir()) {
|
||||
write!(
|
||||
stdout,
|
||||
"{}",
|
||||
style
|
||||
.map(Style::to_nu_ansi_term_style)
|
||||
.unwrap_or_default()
|
||||
.paint(&config.actual_path_separator)
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// TODO: this function is performance critical and can probably be optimized
|
||||
fn print_entry_format<W: Write>(
|
||||
stdout: &mut W,
|
||||
entry: &DirEntry,
|
||||
config: &Config,
|
||||
format: &FormatTemplate,
|
||||
) -> io::Result<()> {
|
||||
let output = format.generate(
|
||||
entry.stripped_path(config),
|
||||
config.path_separator.as_deref(),
|
||||
);
|
||||
// TODO: support writing raw bytes on unix?
|
||||
let s = output.to_string_lossy();
|
||||
write!(
|
||||
stdout,
|
||||
"{}",
|
||||
maybe_sanitize(&s, config.interactive_terminal)
|
||||
)
|
||||
}
|
||||
|
||||
// TODO: this function is performance critical and can probably be optimized
|
||||
fn print_entry_colorized<W: Write>(
|
||||
stdout: &mut W,
|
||||
path: &Path,
|
||||
entry: &DirEntry,
|
||||
config: &Config,
|
||||
ls_colors: &LsColors,
|
||||
wants_to_quit: &AtomicBool,
|
||||
) -> io::Result<()> {
|
||||
// Split the path between the parent and the last component
|
||||
let mut offset = 0;
|
||||
let path = entry.stripped_path(config);
|
||||
let path_str = path.to_string_lossy();
|
||||
|
||||
if let Some(parent) = path.parent() {
|
||||
@@ -75,28 +115,25 @@ fn print_entry_colorized<W: Write>(
|
||||
|
||||
let style = ls_colors
|
||||
.style_for_indicator(Indicator::Directory)
|
||||
.map(Style::to_ansi_term_style)
|
||||
.map(Style::to_nu_ansi_term_style)
|
||||
.unwrap_or_default();
|
||||
write!(stdout, "{}", style.paint(parent_str))?;
|
||||
let safe_parent = maybe_sanitize(&parent_str, config.interactive_terminal);
|
||||
write!(stdout, "{}", style.paint(safe_parent.as_ref()))?;
|
||||
}
|
||||
|
||||
let style = ls_colors
|
||||
.style_for_path(path)
|
||||
.map(Style::to_ansi_term_style)
|
||||
let style = entry
|
||||
.style(ls_colors)
|
||||
.map(Style::to_nu_ansi_term_style)
|
||||
.unwrap_or_default();
|
||||
write!(stdout, "{}", style.paint(&path_str[offset..]))?;
|
||||
let safe_basename = maybe_sanitize(&path_str[offset..], config.interactive_terminal);
|
||||
write!(stdout, "{}", style.paint(safe_basename.as_ref()))?;
|
||||
|
||||
if config.null_separator {
|
||||
write!(stdout, "\0")?;
|
||||
} else {
|
||||
writeln!(stdout)?;
|
||||
}
|
||||
|
||||
if wants_to_quit.load(Ordering::Relaxed) {
|
||||
// Ignore any errors on flush, because we're about to exit anyway
|
||||
let _ = stdout.flush();
|
||||
ExitCode::KilledBySigint.exit();
|
||||
}
|
||||
print_trailing_slash(
|
||||
stdout,
|
||||
entry,
|
||||
config,
|
||||
ls_colors.style_for_indicator(Indicator::Directory),
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -104,42 +141,42 @@ fn print_entry_colorized<W: Write>(
|
||||
// TODO: this function is performance critical and can probably be optimized
|
||||
fn print_entry_uncolorized_base<W: Write>(
|
||||
stdout: &mut W,
|
||||
path: &Path,
|
||||
entry: &DirEntry,
|
||||
config: &Config,
|
||||
) -> io::Result<()> {
|
||||
let separator = if config.null_separator { "\0" } else { "\n" };
|
||||
let path = entry.stripped_path(config);
|
||||
|
||||
let mut path_string = path.to_string_lossy();
|
||||
if let Some(ref separator) = config.path_separator {
|
||||
*path_string.to_mut() = replace_path_separator(&path_string, separator);
|
||||
}
|
||||
write!(stdout, "{}{}", path_string, separator)
|
||||
let safe = maybe_sanitize(&path_string, config.interactive_terminal);
|
||||
write!(stdout, "{safe}")?;
|
||||
print_trailing_slash(stdout, entry, config, None)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn print_entry_uncolorized<W: Write>(
|
||||
stdout: &mut W,
|
||||
path: &Path,
|
||||
entry: &DirEntry,
|
||||
config: &Config,
|
||||
) -> io::Result<()> {
|
||||
print_entry_uncolorized_base(stdout, path, config)
|
||||
print_entry_uncolorized_base(stdout, entry, config)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn print_entry_uncolorized<W: Write>(
|
||||
stdout: &mut W,
|
||||
path: &Path,
|
||||
entry: &DirEntry,
|
||||
config: &Config,
|
||||
) -> io::Result<()> {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
if config.interactive_terminal || config.path_separator.is_some() {
|
||||
// Fall back to the base implementation
|
||||
print_entry_uncolorized_base(stdout, path, config)
|
||||
print_entry_uncolorized_base(stdout, entry, config)
|
||||
} else {
|
||||
// Print path as raw bytes, allowing invalid UTF-8 filenames to be passed to other processes
|
||||
let separator = if config.null_separator { b"\0" } else { b"\n" };
|
||||
stdout.write_all(path.as_os_str().as_bytes())?;
|
||||
stdout.write_all(separator)
|
||||
// Piped output: raw bytes so invalid UTF-8 filenames reach downstream tools intact.
|
||||
stdout.write_all(entry.stripped_path(config).as_os_str().as_bytes())?;
|
||||
print_trailing_slash(stdout, entry, config, None)
|
||||
}
|
||||
}
|
||||
|
||||
+20
-15
@@ -1,9 +1,9 @@
|
||||
use regex_syntax::hir::Hir;
|
||||
use regex_syntax::ParserBuilder;
|
||||
use regex_syntax::hir::Hir;
|
||||
|
||||
/// Determine if a regex pattern contains a literal uppercase character.
|
||||
pub fn pattern_has_uppercase_char(pattern: &str) -> bool {
|
||||
let mut parser = ParserBuilder::new().allow_invalid_utf8(true).build();
|
||||
let mut parser = ParserBuilder::new().utf8(false).build();
|
||||
|
||||
parser
|
||||
.parse(pattern)
|
||||
@@ -15,19 +15,21 @@ pub fn pattern_has_uppercase_char(pattern: &str) -> bool {
|
||||
fn hir_has_uppercase_char(hir: &Hir) -> bool {
|
||||
use regex_syntax::hir::*;
|
||||
|
||||
match *hir.kind() {
|
||||
HirKind::Literal(Literal::Unicode(c)) => c.is_uppercase(),
|
||||
HirKind::Literal(Literal::Byte(b)) => char::from(b).is_uppercase(),
|
||||
HirKind::Class(Class::Unicode(ref ranges)) => ranges
|
||||
match hir.kind() {
|
||||
HirKind::Literal(Literal(bytes)) => match std::str::from_utf8(bytes) {
|
||||
Ok(s) => s.chars().any(|c| c.is_uppercase()),
|
||||
Err(_) => bytes.iter().any(|b| char::from(*b).is_uppercase()),
|
||||
},
|
||||
HirKind::Class(Class::Unicode(ranges)) => ranges
|
||||
.iter()
|
||||
.any(|r| r.start().is_uppercase() || r.end().is_uppercase()),
|
||||
HirKind::Class(Class::Bytes(ref ranges)) => ranges
|
||||
HirKind::Class(Class::Bytes(ranges)) => ranges
|
||||
.iter()
|
||||
.any(|r| char::from(r.start()).is_uppercase() || char::from(r.end()).is_uppercase()),
|
||||
HirKind::Group(Group { ref hir, .. }) | HirKind::Repetition(Repetition { ref hir, .. }) => {
|
||||
hir_has_uppercase_char(hir)
|
||||
HirKind::Capture(Capture { sub, .. }) | HirKind::Repetition(Repetition { sub, .. }) => {
|
||||
hir_has_uppercase_char(sub)
|
||||
}
|
||||
HirKind::Concat(ref hirs) | HirKind::Alternation(ref hirs) => {
|
||||
HirKind::Concat(hirs) | HirKind::Alternation(hirs) => {
|
||||
hirs.iter().any(hir_has_uppercase_char)
|
||||
}
|
||||
_ => false,
|
||||
@@ -36,7 +38,7 @@ fn hir_has_uppercase_char(hir: &Hir) -> bool {
|
||||
|
||||
/// Determine if a regex pattern only matches strings starting with a literal dot (hidden files)
|
||||
pub fn pattern_matches_strings_with_leading_dot(pattern: &str) -> bool {
|
||||
let mut parser = ParserBuilder::new().allow_invalid_utf8(true).build();
|
||||
let mut parser = ParserBuilder::new().utf8(false).build();
|
||||
|
||||
parser
|
||||
.parse(pattern)
|
||||
@@ -52,11 +54,11 @@ fn hir_matches_strings_with_leading_dot(hir: &Hir) -> bool {
|
||||
// "^\\.", i.e. a start text anchor and a literal dot character. There are a lot
|
||||
// of other patterns that ONLY match hidden files, e.g. ^(\\.foo|\\.bar) which are
|
||||
// not (yet) detected by this algorithm.
|
||||
match *hir.kind() {
|
||||
HirKind::Concat(ref hirs) => {
|
||||
match hir.kind() {
|
||||
HirKind::Concat(hirs) => {
|
||||
let mut hirs = hirs.iter();
|
||||
if let Some(hir) = hirs.next() {
|
||||
if *hir.kind() != HirKind::Anchor(Anchor::StartText) {
|
||||
if hir.kind() != &HirKind::Look(Look::Start) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
@@ -64,7 +66,10 @@ fn hir_matches_strings_with_leading_dot(hir: &Hir) -> bool {
|
||||
}
|
||||
|
||||
if let Some(hir) = hirs.next() {
|
||||
*hir.kind() == HirKind::Literal(Literal::Unicode('.'))
|
||||
match hir.kind() {
|
||||
HirKind::Literal(Literal(bytes)) => bytes.starts_with(b"."),
|
||||
_ => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
//! TTY-output sanitization to prevent terminal escape injection via filenames.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::fmt::Write;
|
||||
|
||||
/// True for any char that is neither printable nor permitted whitespace (only HT).
|
||||
/// Covers C0/C1/DEL, bidi overrides, zero-width and format chars, and tag chars.
|
||||
#[inline]
|
||||
fn needs_escape(c: char) -> bool {
|
||||
if c == '\t' {
|
||||
return false;
|
||||
}
|
||||
c.is_control()
|
||||
|| matches!(c,
|
||||
'\u{00AD}' // soft hyphen (invisible)
|
||||
| '\u{180E}' // Mongolian vowel separator
|
||||
| '\u{200B}'..='\u{200F}' // zero-width + LRM/RLM
|
||||
| '\u{202A}'..='\u{202E}' // bidi embedding/override
|
||||
| '\u{2060}'..='\u{206F}' // word joiner, invisibles, deprecated formats
|
||||
| '\u{FEFF}' // BOM / zero-width no-break space
|
||||
| '\u{FFF9}'..='\u{FFFB}' // interlinear annotation
|
||||
| '\u{E0000}'..='\u{E007F}' // language tags
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns a `Cow<str>` borrowing `s` when no escaping is needed, otherwise an owned
|
||||
/// escaped copy. Use this when an owned `&str`/`String` is required (e.g. ANSI paint).
|
||||
pub fn sanitize_for_terminal(s: &str) -> Cow<'_, str> {
|
||||
if !s.chars().any(needs_escape) {
|
||||
return Cow::Borrowed(s);
|
||||
}
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
if needs_escape(c) {
|
||||
let v = c as u32;
|
||||
if v <= 0xFF {
|
||||
let _ = write!(out, "\\x{v:02X}");
|
||||
} else {
|
||||
let _ = write!(out, "\\u{{{v:04X}}}");
|
||||
}
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
Cow::Owned(out)
|
||||
}
|
||||
|
||||
/// Sanitize for terminal output only; raw bytes pass through on pipes/files.
|
||||
pub fn maybe_sanitize<'a>(s: &'a str, is_terminal: bool) -> Cow<'a, str> {
|
||||
if is_terminal {
|
||||
sanitize_for_terminal(s)
|
||||
} else {
|
||||
Cow::Borrowed(s)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn preserves_safe_content() {
|
||||
for s in [
|
||||
"hello.txt",
|
||||
"résumé.pdf",
|
||||
"文档.txt",
|
||||
"🦀.rs",
|
||||
"a\tb",
|
||||
"a\u{FFFD}b",
|
||||
] {
|
||||
assert!(
|
||||
matches!(sanitize_for_terminal(s), Cow::Borrowed(_)),
|
||||
"{s:?}"
|
||||
);
|
||||
assert_eq!(sanitize_for_terminal(s), s);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_osc52_clipboard_payload() {
|
||||
let attack = "innocent\x1b]52;c;cHduZWQ=\x1b\\.txt";
|
||||
let safe = sanitize_for_terminal(attack);
|
||||
assert!(!safe.contains('\x1b'));
|
||||
assert_eq!(safe, "innocent\\x1B]52;c;cHduZWQ=\\x1B\\.txt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_cr_output_forgery() {
|
||||
assert_eq!(sanitize_for_terminal("A\rFAKE OUTPUT"), "A\\x0DFAKE OUTPUT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_osc8_hyperlink_injection() {
|
||||
let attack = "phish\x1b]8;;https:evil.example\x1b\\phony.txt";
|
||||
assert!(!sanitize_for_terminal(attack).contains('\x1b'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_del() {
|
||||
assert_eq!(sanitize_for_terminal("a\x7fb"), "a\\x7Fb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_bel_and_null() {
|
||||
assert_eq!(sanitize_for_terminal("a\x07b"), "a\\x07b");
|
||||
assert_eq!(sanitize_for_terminal("a\0b"), "a\\x00b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_newline() {
|
||||
assert_eq!(sanitize_for_terminal("a\nb"), "a\\x0Ab");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_preserves_information() {
|
||||
let s = "name\x1bX\x07Y.txt";
|
||||
assert_eq!(sanitize_for_terminal(s), "name\\x1BX\\x07Y.txt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_c1_csi_and_osc_initiators() {
|
||||
// U+009B is CSI, U+009D is OSC; dangerous on 8-bit-control terminals.
|
||||
assert_eq!(sanitize_for_terminal("\u{9b}31m"), "\\x9B31m");
|
||||
assert_eq!(
|
||||
sanitize_for_terminal("\u{9d}0;pwned\u{9c}"),
|
||||
"\\x9D0;pwned\\x9C"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_bidi_overrides_and_zero_width() {
|
||||
// Trojan-Source style RLO/LRO that flip rendered order of filename text.
|
||||
assert_eq!(
|
||||
sanitize_for_terminal("safe\u{202E}fil\u{202D}gnp.exe"),
|
||||
"safe\\u{202E}fil\\u{202D}gnp.exe"
|
||||
);
|
||||
// Zero-width space and BOM are also format chars used to disguise filenames.
|
||||
assert_eq!(sanitize_for_terminal("a\u{200B}b"), "a\\u{200B}b");
|
||||
assert_eq!(sanitize_for_terminal("\u{FEFF}name"), "\\u{FEFF}name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_legitimate_unicode_features() {
|
||||
// Variation selectors (U+FE0F, U+E0100..) modify preceding glyphs in CJK/emoji
|
||||
// and are legitimate in filenames. Private-use chars are used by icon fonts.
|
||||
for s in [
|
||||
"heart\u{2764}\u{FE0F}.txt",
|
||||
"icon\u{E000}.cfg",
|
||||
"cjk\u{6F22}\u{E0101}.txt",
|
||||
] {
|
||||
assert!(
|
||||
matches!(sanitize_for_terminal(s), Cow::Borrowed(_)),
|
||||
"{s:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maybe_sanitize_passthrough_when_not_terminal() {
|
||||
let attack = "x\x1by";
|
||||
// Pipe context: bytes pass through unchanged (zero-copy).
|
||||
let out = maybe_sanitize(attack, false);
|
||||
assert!(matches!(out, Cow::Borrowed(_)));
|
||||
assert_eq!(out, attack);
|
||||
// TTY context: escapes apply.
|
||||
assert_eq!(maybe_sanitize(attack, true), "x\\x1By");
|
||||
}
|
||||
}
|
||||
+648
-433
File diff suppressed because it is too large
Load Diff
+89
-46
@@ -8,7 +8,7 @@ use std::os::windows;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process;
|
||||
|
||||
use tempdir::TempDir;
|
||||
use tempfile::TempDir;
|
||||
|
||||
/// Environment for the integration tests.
|
||||
pub struct TestEnv {
|
||||
@@ -20,6 +20,9 @@ pub struct TestEnv {
|
||||
|
||||
/// Normalize each line by sorting the whitespace-separated words
|
||||
normalize_line: bool,
|
||||
|
||||
/// Temporary directory for storing test config (global ignore file)
|
||||
config_dir: Option<TempDir>,
|
||||
}
|
||||
|
||||
/// Create the working directory and the test files.
|
||||
@@ -27,7 +30,7 @@ fn create_working_directory(
|
||||
directories: &[&'static str],
|
||||
files: &[&'static str],
|
||||
) -> Result<TempDir, io::Error> {
|
||||
let temp_dir = TempDir::new("fd-tests")?;
|
||||
let temp_dir = tempfile::Builder::new().prefix("fd-tests").tempdir()?;
|
||||
|
||||
{
|
||||
let root = temp_dir.path();
|
||||
@@ -59,20 +62,20 @@ fn create_working_directory(
|
||||
Ok(temp_dir)
|
||||
}
|
||||
|
||||
fn create_config_directory_with_global_ignore(ignore_file_content: &str) -> io::Result<TempDir> {
|
||||
let config_dir = tempfile::Builder::new().prefix("fd-config").tempdir()?;
|
||||
let fd_dir = config_dir.path().join("fd");
|
||||
fs::create_dir(&fd_dir)?;
|
||||
let mut ignore_file = fs::File::create(fd_dir.join("ignore"))?;
|
||||
ignore_file.write_all(ignore_file_content.as_bytes())?;
|
||||
|
||||
Ok(config_dir)
|
||||
}
|
||||
|
||||
/// Find the *fd* executable.
|
||||
fn find_fd_exe() -> PathBuf {
|
||||
// Tests exe is in target/debug/deps, the *fd* exe is in target/debug
|
||||
let root = env::current_exe()
|
||||
.expect("tests executable")
|
||||
.parent()
|
||||
.expect("tests executable directory")
|
||||
.parent()
|
||||
.expect("fd executable directory")
|
||||
.to_path_buf();
|
||||
|
||||
let exe_name = if cfg!(windows) { "fd.exe" } else { "fd" };
|
||||
|
||||
root.join(exe_name)
|
||||
// Read the location of the fd executable from the environment
|
||||
PathBuf::from(env::var("CARGO_BIN_EXE_fd").unwrap_or(env!("CARGO_BIN_EXE_fd").to_string()))
|
||||
}
|
||||
|
||||
/// Format an error message for when *fd* did not exit successfully.
|
||||
@@ -91,9 +94,9 @@ fn format_output_error(args: &[&str], expected: &str, actual: &str) -> String {
|
||||
let diff_text = diff::lines(expected, actual)
|
||||
.into_iter()
|
||||
.map(|diff| match diff {
|
||||
diff::Result::Left(l) => format!("-{}", l),
|
||||
diff::Result::Both(l, _) => format!(" {}", l),
|
||||
diff::Result::Right(r) => format!("+{}", r),
|
||||
diff::Result::Left(l) => format!("-{l}"),
|
||||
diff::Result::Both(l, _) => format!(" {l}"),
|
||||
diff::Result::Right(r) => format!("+{r}"),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
@@ -116,7 +119,7 @@ fn normalize_output(s: &str, trim_start: bool, normalize_line: bool) -> String {
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let line = if trim_start { line.trim_start() } else { line };
|
||||
let line = line.replace('/', &std::path::MAIN_SEPARATOR.to_string());
|
||||
let line = line.replace('/', std::path::MAIN_SEPARATOR_STR);
|
||||
if normalize_line {
|
||||
let mut words: Vec<_> = line.split_whitespace().collect();
|
||||
words.sort_unstable();
|
||||
@@ -130,6 +133,17 @@ fn normalize_output(s: &str, trim_start: bool, normalize_line: bool) -> String {
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
/// Trim whitespace from the beginning of each line.
|
||||
fn trim_lines(s: &str) -> String {
|
||||
s.lines()
|
||||
.map(|line| line.trim_start())
|
||||
.fold(String::new(), |mut str, line| {
|
||||
str.push_str(line);
|
||||
str.push('\n');
|
||||
str
|
||||
})
|
||||
}
|
||||
|
||||
impl TestEnv {
|
||||
pub fn new(directories: &[&'static str], files: &[&'static str]) -> TestEnv {
|
||||
let temp_dir = create_working_directory(directories, files).expect("working directory");
|
||||
@@ -139,6 +153,7 @@ impl TestEnv {
|
||||
temp_dir,
|
||||
fd_exe,
|
||||
normalize_line: false,
|
||||
config_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,6 +162,16 @@ impl TestEnv {
|
||||
temp_dir: self.temp_dir,
|
||||
fd_exe: self.fd_exe,
|
||||
normalize_line: normalize,
|
||||
config_dir: self.config_dir,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn global_ignore_file(self, content: &str) -> TestEnv {
|
||||
let config_dir =
|
||||
create_config_directory_with_global_ignore(content).expect("config directory");
|
||||
TestEnv {
|
||||
config_dir: Some(config_dir),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,7 +183,9 @@ impl TestEnv {
|
||||
let root = self.test_root();
|
||||
let broken_symlink_link = root.join(link_path);
|
||||
{
|
||||
let temp_target_dir = TempDir::new("fd-tests-broken-symlink")?;
|
||||
let temp_target_dir = tempfile::Builder::new()
|
||||
.prefix("fd-tests-broken-symlink")
|
||||
.tempdir()?;
|
||||
let broken_symlink_target = temp_target_dir.path().join("broken_symlink_target");
|
||||
fs::File::create(&broken_symlink_target)?;
|
||||
#[cfg(unix)]
|
||||
@@ -174,6 +201,12 @@ impl TestEnv {
|
||||
self.temp_dir.path().to_path_buf()
|
||||
}
|
||||
|
||||
/// Get the path of the fd executable.
|
||||
#[cfg_attr(windows, allow(unused))]
|
||||
pub fn test_exe(&self) -> &PathBuf {
|
||||
&self.fd_exe
|
||||
}
|
||||
|
||||
/// Get the root directory of the file system.
|
||||
pub fn system_root(&self) -> PathBuf {
|
||||
let mut components = self.temp_dir.path().components();
|
||||
@@ -187,13 +220,8 @@ impl TestEnv {
|
||||
path: P,
|
||||
args: &[&str],
|
||||
) -> process::Output {
|
||||
// Setup *fd* command.
|
||||
let mut cmd = process::Command::new(&self.fd_exe);
|
||||
cmd.current_dir(self.temp_dir.path().join(path));
|
||||
cmd.arg("--no-global-ignore-file").args(args);
|
||||
|
||||
// Run *fd*.
|
||||
let output = cmd.output().expect("fd output");
|
||||
let output = self.run_command(path.as_ref(), args);
|
||||
|
||||
// Check for exit status.
|
||||
if !output.status.success() {
|
||||
@@ -203,6 +231,19 @@ impl TestEnv {
|
||||
output
|
||||
}
|
||||
|
||||
pub fn assert_success_and_get_normalized_output<P: AsRef<Path>>(
|
||||
&self,
|
||||
path: P,
|
||||
args: &[&str],
|
||||
) -> String {
|
||||
let output = self.assert_success_and_get_output(path, args);
|
||||
normalize_output(
|
||||
&String::from_utf8_lossy(&output.stdout),
|
||||
false,
|
||||
self.normalize_line,
|
||||
)
|
||||
}
|
||||
|
||||
/// Assert that calling *fd* with the specified arguments produces the expected output.
|
||||
pub fn assert_output(&self, args: &[&str], expected: &str) {
|
||||
self.assert_output_subdirectory(".", args, expected)
|
||||
@@ -224,15 +265,9 @@ impl TestEnv {
|
||||
args: &[&str],
|
||||
expected: &str,
|
||||
) {
|
||||
let output = self.assert_success_and_get_output(path, args);
|
||||
|
||||
// Normalize both expected and actual output.
|
||||
let expected = normalize_output(expected, true, self.normalize_line);
|
||||
let actual = normalize_output(
|
||||
&String::from_utf8_lossy(&output.stdout),
|
||||
false,
|
||||
self.normalize_line,
|
||||
);
|
||||
let actual = self.assert_success_and_get_normalized_output(path, args);
|
||||
|
||||
// Compare actual output to expected output.
|
||||
if expected != actual {
|
||||
@@ -245,7 +280,7 @@ impl TestEnv {
|
||||
pub fn assert_failure_with_error(&self, args: &[&str], expected: &str) {
|
||||
let status = self.assert_error_subdirectory(".", args, Some(expected));
|
||||
if status.success() {
|
||||
panic!("error '{}' did not occur.", expected);
|
||||
panic!("error '{expected}' did not occur.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,6 +297,24 @@ impl TestEnv {
|
||||
self.assert_error_subdirectory(".", args, Some(expected))
|
||||
}
|
||||
|
||||
fn run_command(&self, path: &Path, args: &[&str]) -> process::Output {
|
||||
// Setup *fd* command.
|
||||
let mut cmd = process::Command::new(&self.fd_exe);
|
||||
cmd.current_dir(self.temp_dir.path().join(path));
|
||||
if let Some(config_dir) = &self.config_dir {
|
||||
cmd.env("XDG_CONFIG_HOME", config_dir.path());
|
||||
} else {
|
||||
cmd.arg("--no-global-ignore-file");
|
||||
}
|
||||
// Make sure LS_COLORS is unset to ensure consistent
|
||||
// color output
|
||||
cmd.env("LS_COLORS", "");
|
||||
cmd.args(args);
|
||||
|
||||
// Run *fd*.
|
||||
cmd.output().expect("fd output")
|
||||
}
|
||||
|
||||
/// Assert that calling *fd* in the specified path under the root working directory,
|
||||
/// and with the specified arguments produces an error with the expected message.
|
||||
fn assert_error_subdirectory<P: AsRef<Path>>(
|
||||
@@ -270,22 +323,12 @@ impl TestEnv {
|
||||
args: &[&str],
|
||||
expected: Option<&str>,
|
||||
) -> process::ExitStatus {
|
||||
// Setup *fd* command.
|
||||
let mut cmd = process::Command::new(&self.fd_exe);
|
||||
cmd.current_dir(self.temp_dir.path().join(path));
|
||||
cmd.arg("--no-global-ignore-file").args(args);
|
||||
|
||||
// Run *fd*.
|
||||
let output = cmd.output().expect("fd output");
|
||||
let output = self.run_command(path.as_ref(), args);
|
||||
|
||||
if let Some(expected) = expected {
|
||||
// Normalize both expected and actual output.
|
||||
let expected_error = normalize_output(expected, true, self.normalize_line);
|
||||
let actual_err = normalize_output(
|
||||
&String::from_utf8_lossy(&output.stderr),
|
||||
false,
|
||||
self.normalize_line,
|
||||
);
|
||||
let expected_error = trim_lines(expected);
|
||||
let actual_err = trim_lines(&String::from_utf8_lossy(&output.stderr));
|
||||
|
||||
// Compare actual output to expected output.
|
||||
if !actual_err.trim_start().starts_with(&expected_error) {
|
||||
|
||||
+1294
-418
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user