Clap 4 and revamp manpage, completions (#513)

This commit is contained in:
Félix Saparelli 2023-03-05 14:57:34 +13:00 committed by GitHub
parent 1e72cf6866
commit 14f53a6bf5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 3342 additions and 1820 deletions

View File

@ -11,7 +11,7 @@ Please delete this template text before filing, but you _need_ to include the fo
- Watchexec's version
- The OS you're using
- A log with `-vvv --log-file ../watchexec.log` (if it has sensitive info you can email it at felix@passcod.name — do that _after_ filing so you can reference the issue ID)
- A log with `-vvv --log-file` (if it has sensitive info you can email it at felix@passcod.name — do that _after_ filing so you can reference the issue ID)
- A sample command that you've run that has the issue
Thank you

View File

@ -15,7 +15,7 @@ assignees: ''
- Latest version that worked:
- Earliest version that doesn't: (don't sweat testing earlier versions if you don't remember or have time, your current version will do)
- OS:
- A debug log with `-vvv --log-file ../watchexec.log`:
- A debug log with `-vvv --log-file`:
```
```

View File

@ -25,6 +25,7 @@ concurrency:
jobs:
test:
strategy:
fail-fast: false
matrix:
platform:
- macos
@ -72,6 +73,16 @@ jobs:
- name: Check that CLI runs
run: cargo run ${{ env.flags }} -p watchexec-cli -- -1 echo
- name: Generate manpage
run: cargo run ${{ env.flags }} -p watchexec-cli -- --manpage > doc/watchexec.1
- name: Check that manpage is up to date
run: git diff --exit-code -- doc/
- name: Generate completions
run: bin/completions
- name: Check that completions are up to date
run: git diff --exit-code -- completions/
cross-checks:
name: Checks only against select targets
runs-on: ubuntu-latest

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
target
/watchexec-*
watchexec.*.log

View File

@ -128,8 +128,5 @@ These are generic guides for implementing specific bits of functionality.
- process relevant events [in the action
handler](https://github.com/watchexec/watchexec/blob/main/crates/cli/src/config/runtime.rs)
- document the option in the [manual
page](https://github.com/watchexec/watchexec/blob/main/doc/watchexec.1.ronn)
---
vim: tw=100

580
Cargo.lock generated
View File

@ -37,12 +37,30 @@ dependencies = [
"memchr",
]
[[package]]
name = "android_system_properties"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
dependencies = [
"libc",
]
[[package]]
name = "anyhow"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224afbd727c3d6e4b90103ece64b8d1b67fbb1973b1046c2281eed3f3803f800"
[[package]]
name = "argfile"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "265f5108974489a217d5098cd81666b60480c8dd67302acbbe7cbdd8aa09d638"
dependencies = [
"os_str_bytes",
]
[[package]]
name = "async-broadcast"
version = "0.5.1"
@ -89,12 +107,11 @@ dependencies = [
[[package]]
name = "async-lock"
version = "2.6.0"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8101efe8695a6c17e02911402145357e718ac92d3ff88ae8419e84b1707b685"
checksum = "fa24f727524730b077666307f2734b4a1a1c57acb79193127dcc8914d5242dd7"
dependencies = [
"event-listener",
"futures-lite",
]
[[package]]
@ -288,6 +305,12 @@ dependencies = [
"num-traits",
]
[[package]]
name = "bumpalo"
version = "3.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535"
[[package]]
name = "byteorder"
version = "1.4.3"
@ -305,6 +328,9 @@ name = "cc"
version = "1.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
dependencies = [
"jobserver",
]
[[package]]
name = "cfg-if"
@ -313,31 +339,87 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "3.2.23"
name = "chrono"
version = "0.4.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71655c45cb9845d3270c9d6df84ebe72b4dad3c2ba3f7023ad47c144e4e473a5"
checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f"
dependencies = [
"iana-time-zone",
"js-sys",
"num-integer",
"num-traits",
"time 0.1.45",
"wasm-bindgen",
"winapi",
]
[[package]]
name = "clap"
version = "4.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d7ae14b20b94cb02149ed21a86c423859cbe18dc7ed69845cace50e52b40a5"
dependencies = [
"atty",
"bitflags",
"clap_derive",
"clap_lex",
"indexmap",
"is-terminal",
"once_cell",
"strsim",
"termcolor",
"terminal_size 0.2.5",
"textwrap 0.16.0",
]
[[package]]
name = "clap_complete"
version = "4.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "501ff0a401473ea1d4c3b125ff95506b62c5bc5768d818634195fbb7c4ad5ff4"
dependencies = [
"clap",
]
[[package]]
name = "clap_complete_nushell"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7fa41f5e6aa83bd151b70fd0ceaee703d68cd669522795dc812df9edad1252c"
dependencies = [
"clap",
"clap_complete",
]
[[package]]
name = "clap_derive"
version = "4.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44bec8e5c9d09e439c4335b1af0abaab56dcf3b94999a936e1bb47b9134288f0"
dependencies = [
"heck 0.4.1",
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.2.4"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5"
checksum = "350b9cf31731f9957399229e9b2adc51eeabdfbe9d71d9a0552275fd12710d09"
dependencies = [
"os_str_bytes",
]
[[package]]
name = "clap_mangen"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0f09a0ca8f0dd8ac92c546b426f466ef19828185c6d504c80c48c9c2768ed9"
dependencies = [
"clap",
"roff",
]
[[package]]
name = "clearscreen"
version = "2.0.0"
@ -352,10 +434,20 @@ dependencies = [
]
[[package]]
name = "command-group"
version = "2.0.1"
name = "codespan-reporting"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "026c3922235f9f7d78f21251a026f3acdeb7cce3deba107fe09a4bfa63d850a2"
checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e"
dependencies = [
"termcolor",
"unicode-width",
]
[[package]]
name = "command-group"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5080df6b0f0ecb76cab30808f00d937ba725cebe266a3da8cd89dff92f2a9916"
dependencies = [
"async-trait",
"nix 0.26.2",
@ -408,6 +500,38 @@ dependencies = [
"tracing-subscriber",
]
[[package]]
name = "const_fn"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fbdcdcb6d86f71c5e97409ad45898af11cbc995b4ee8112d59095a28d376c935"
[[package]]
name = "const_format"
version = "0.2.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7309d9b4d3d2c0641e018d449232f2e28f1b22933c137f157d3dbc14228b8c0e"
dependencies = [
"const_format_proc_macros",
]
[[package]]
name = "const_format_proc_macros"
version = "0.2.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d897f47bf7270cf70d370f8f98c1abb6d2d4cf60a6845d30e05bfb90c6568650"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc"
[[package]]
name = "cpufeatures"
version = "0.2.5"
@ -455,6 +579,50 @@ dependencies = [
"typenum",
]
[[package]]
name = "cxx"
version = "1.0.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86d3488e7665a7a483b57e25bdd90d0aeb2bc7608c8d0346acf2ad3f1caf1d62"
dependencies = [
"cc",
"cxxbridge-flags",
"cxxbridge-macro",
"link-cplusplus",
]
[[package]]
name = "cxx-build"
version = "1.0.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48fcaf066a053a41a81dfb14d57d99738b767febb8b735c3016e469fac5da690"
dependencies = [
"cc",
"codespan-reporting",
"once_cell",
"proc-macro2",
"quote",
"scratch",
"syn",
]
[[package]]
name = "cxxbridge-flags"
version = "1.0.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2ef98b8b717a829ca5603af80e1f9e2e48013ab227b68ef37872ef84ee479bf"
[[package]]
name = "cxxbridge-macro"
version = "1.0.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "086c685979a698443656e5cf7856c95c642295a38599f12fb1ff76fb28d19892"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "derivative"
version = "2.2.0"
@ -621,6 +789,15 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "form_urlencoded"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8"
dependencies = [
"percent-encoding",
]
[[package]]
name = "fsevent-sys"
version = "4.1.0"
@ -752,7 +929,7 @@ checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31"
dependencies = [
"cfg-if",
"libc",
"wasi",
"wasi 0.11.0+wasi-snapshot-preview1",
]
[[package]]
@ -761,6 +938,19 @@ version = "0.27.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad0a93d233ebf96623465aad4046a8d3aa4da22d4f4beba5388838c8a434bbb4"
[[package]]
name = "git2"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf7f68c2995f392c49fffb4f95ae2c873297830eb25c6bc4c114ce8f4562acc"
dependencies = [
"bitflags",
"libc",
"libgit2-sys",
"log",
"url",
]
[[package]]
name = "gix-actor"
version = "0.18.0"
@ -818,7 +1008,7 @@ dependencies = [
"bstr",
"itoa",
"thiserror",
"time",
"time 0.3.20",
]
[[package]]
@ -1010,6 +1200,12 @@ dependencies = [
"unicode-segmentation",
]
[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]
name = "hermit-abi"
version = "0.1.19"
@ -1028,6 +1224,12 @@ dependencies = [
"libc",
]
[[package]]
name = "hermit-abi"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286"
[[package]]
name = "hex"
version = "0.4.3"
@ -1116,6 +1318,40 @@ dependencies = [
"tokio-io-timeout",
]
[[package]]
name = "iana-time-zone"
version = "0.1.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64c122667b287044802d6ce17ee2ddf13207ed924c712de9a66a5814d5b64765"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"wasm-bindgen",
"winapi",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca"
dependencies = [
"cxx",
"cxx-build",
]
[[package]]
name = "idna"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6"
dependencies = [
"unicode-bidi",
"unicode-normalization",
]
[[package]]
name = "ignore"
version = "0.4.20"
@ -1196,12 +1432,30 @@ dependencies = [
"windows-sys 0.45.0",
]
[[package]]
name = "is-terminal"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b6b32576413a8e69b90e952e4a026476040d81017b80445deda5f2d3921857"
dependencies = [
"hermit-abi 0.3.1",
"io-lifetimes",
"rustix",
"windows-sys 0.45.0",
]
[[package]]
name = "is_ci"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "616cde7c720bb2bb5824a224687d8f77bfd38922027f01d825cd7453be5099fb"
[[package]]
name = "is_debug"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06d198e9919d9822d5f7083ba8530e04de87841eaf21ead9af8f2304efd57c89"
[[package]]
name = "itertools"
version = "0.10.5"
@ -1217,6 +1471,24 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440"
[[package]]
name = "jobserver"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "936cfd212a0155903bcbc060e316fb6cc7cbf2e1907329391ebadc1fe0ce77c2"
dependencies = [
"libc",
]
[[package]]
name = "js-sys"
version = "0.3.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "445dde2150c55e483f3d8416706b97ec8e8237c307e5b7b4b8dd15e6af2a0730"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "kqueue"
version = "1.0.7"
@ -1249,6 +1521,18 @@ version = "0.2.139"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79"
[[package]]
name = "libgit2-sys"
version = "0.14.2+1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f3d95f6b51075fe9810a7ae22c7095f12b98005ab364d8544797a825ce946a4"
dependencies = [
"cc",
"libc",
"libz-sys",
"pkg-config",
]
[[package]]
name = "libmimalloc-sys"
version = "0.1.30"
@ -1259,6 +1543,27 @@ dependencies = [
"libc",
]
[[package]]
name = "libz-sys"
version = "1.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9702761c3935f8cc2f101793272e202c72b99da8f4224a19ddcf1279a6450bbf"
dependencies = [
"cc",
"libc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "link-cplusplus"
version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5"
dependencies = [
"cc",
]
[[package]]
name = "linux-raw-sys"
version = "0.1.4"
@ -1294,7 +1599,7 @@ dependencies = [
"dirs-next",
"objc-foundation",
"objc_id",
"time",
"time 0.3.20",
]
[[package]]
@ -1369,7 +1674,7 @@ dependencies = [
"supports-hyperlinks",
"supports-unicode",
"terminal_size 0.1.17",
"textwrap 0.15.2",
"textwrap",
"thiserror",
"unicode-width",
]
@ -1423,7 +1728,7 @@ checksum = "5b9d9a46eff5b4ff64b45a9e316a6d1e0bc719ef429cbec4dc630684212bfdf9"
dependencies = [
"libc",
"log",
"wasi",
"wasi 0.11.0+wasi-snapshot-preview1",
"windows-sys 0.45.0",
]
@ -1522,6 +1827,16 @@ dependencies = [
"winapi",
]
[[package]]
name = "num-integer"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9"
dependencies = [
"autocfg",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.15"
@ -1609,6 +1924,9 @@ name = "os_str_bytes"
version = "6.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b7820b9daea5457c9f21c69448905d723fbd21136ccf521748f23fd49e723ee"
dependencies = [
"memchr",
]
[[package]]
name = "overload"
@ -1727,6 +2045,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "pkg-config"
version = "0.3.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"
[[package]]
name = "polling"
version = "2.5.2"
@ -1757,6 +2081,30 @@ dependencies = [
"toml_edit",
]
[[package]]
name = "proc-macro-error"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [
"proc-macro-error-attr",
"proc-macro2",
"quote",
"syn",
"version_check",
]
[[package]]
name = "proc-macro-error-attr"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [
"proc-macro2",
"quote",
"version_check",
]
[[package]]
name = "proc-macro2"
version = "1.0.51"
@ -1903,6 +2251,12 @@ version = "0.6.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848"
[[package]]
name = "roff"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b833d8d034ea094b1ea68aa6d5c740e0d04bad9d16568d08ba6f76823a114316"
[[package]]
name = "rustc-demangle"
version = "0.1.21"
@ -1959,6 +2313,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "scratch"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddccb15bcce173023b3fedd9436f882a0739b8dfb45e4f6b6002bee5929f61b2"
[[package]]
name = "semver"
version = "1.0.16"
@ -2024,6 +2384,19 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012"
[[package]]
name = "shadow-rs"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "427f07ab5f873000cf55324882e12a88c0a7ea7025df4fc1e7e35e688877a583"
dependencies = [
"const_format",
"git2",
"is_debug",
"time 0.3.20",
"tzdb",
]
[[package]]
name = "sharded-slab"
version = "0.1.4"
@ -2071,9 +2444,9 @@ checksum = "f67ad224767faa3c7d8b6d91985b78e70a1324408abcb1cfcc2be4c06bc06043"
[[package]]
name = "socket2"
version = "0.4.7"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02e2d2db9033d13a1567121ddd7a095ee144db4e1ca1b1bda3419bc0da294ebd"
checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662"
dependencies = [
"libc",
"winapi",
@ -2106,7 +2479,7 @@ version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "339f799d8b549e3744c7ac7feb216383e4005d94bdb22561b3ab8f3b808ae9fb"
dependencies = [
"heck",
"heck 0.3.3",
"proc-macro2",
"quote",
"syn",
@ -2234,15 +2607,6 @@ dependencies = [
"unicode-width",
]
[[package]]
name = "textwrap"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d"
dependencies = [
"terminal_size 0.2.5",
]
[[package]]
name = "thiserror"
version = "1.0.38"
@ -2273,6 +2637,17 @@ dependencies = [
"once_cell",
]
[[package]]
name = "time"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a"
dependencies = [
"libc",
"wasi 0.10.0+wasi-snapshot-preview1",
"winapi",
]
[[package]]
name = "time"
version = "0.3.20"
@ -2302,6 +2677,21 @@ dependencies = [
"time-core",
]
[[package]]
name = "tinyvec"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.26.0"
@ -2575,6 +2965,25 @@ version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"
[[package]]
name = "tz-rs"
version = "0.6.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33851b15c848fad2cf4b105c6bb66eb9512b6f6c44a4b13f57c53c73c707e2b4"
dependencies = [
"const_fn",
]
[[package]]
name = "tzdb"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4b882d864be6a5d7c3c916719944458b1e03c85f86dbc825ec98155117c4408"
dependencies = [
"iana-time-zone",
"tz-rs",
]
[[package]]
name = "uds_windows"
version = "1.0.2"
@ -2594,6 +3003,12 @@ dependencies = [
"version_check",
]
[[package]]
name = "unicode-bidi"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d54675592c1dbefd78cbd98db9bacd89886e1ca50692a0692baefffdeb92dd58"
[[package]]
name = "unicode-bom"
version = "1.1.4"
@ -2616,6 +3031,15 @@ dependencies = [
"regex",
]
[[package]]
name = "unicode-normalization"
version = "0.1.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-segmentation"
version = "1.10.1"
@ -2628,12 +3052,35 @@ version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"
[[package]]
name = "unicode-xid"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c"
[[package]]
name = "url"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
]
[[package]]
name = "valuable"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d"
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "version_check"
version = "0.9.4"
@ -2687,12 +3134,72 @@ dependencies = [
"try-lock",
]
[[package]]
name = "wasi"
version = "0.10.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31f8dcbc21f30d9b8f2ea926ecb58f6b91192c17e9d33594b3df58b2007ca53b"
dependencies = [
"cfg-if",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95ce90fd5bcc06af55a641a86428ee4229e44e07033963a2290a8e241607ccb9"
dependencies = [
"bumpalo",
"log",
"once_cell",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c21f77c0bedc37fd5dc21f897894a5ca01e7bb159884559461862ae90c0b4c5"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2aff81306fcac3c7515ad4e177f521b5c9a15f2b08f4e32d823066102f35a5f6"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d"
[[package]]
name = "watchexec"
version = "2.1.1"
@ -2720,22 +3227,31 @@ dependencies = [
name = "watchexec-cli"
version = "1.21.1"
dependencies = [
"argfile",
"chrono",
"clap",
"clap_complete",
"clap_complete_nushell",
"clap_mangen",
"command-group",
"console-subscriber",
"dirs",
"embed-resource",
"futures",
"humantime",
"ignore-files",
"is-terminal",
"miette",
"mimalloc",
"notify-rust",
"project-origins",
"shadow-rs",
"tokio",
"tracing",
"tracing-subscriber",
"watchexec",
"watchexec-filterer-globset",
"watchexec-filterer-tagged",
"which",
]
[[package]]

View File

@ -47,8 +47,9 @@ More usage examples: [in the CLI README](./crates/cli/#usage-examples)!
- As [pre-built binary package from Github](https://github.com/watchexec/watchexec/releases/latest)
- From source with Cargo: `cargo install --locked watchexec-cli`
All options in detail: [in the CLI README](./crates/cli/#installation)
and [in the manual page](./doc/watchexec.1.ronn).
All options in detail: [in the CLI README](./crates/cli/#installation),
in the online help (`watchexec -h`, `watchexec --help`, or `watchexec --manual`),
and [in the manual page](./doc/watchexec.1.md) ([PDF](./doc/watchexec.1.pdf)).
## Augment

7
bin/completions Executable file
View File

@ -0,0 +1,7 @@
#!/bin/sh
cargo run -p watchexec-cli -- --completions bash > completions/bash
cargo run -p watchexec-cli -- --completions elvish > completions/elvish
cargo run -p watchexec-cli -- --completions fish > completions/fish
cargo run -p watchexec-cli -- --completions nu > completions/nu
cargo run -p watchexec-cli -- --completions powershell > completions/powershell
cargo run -p watchexec-cli -- --completions zsh > completions/zsh

View File

@ -1,2 +1,4 @@
#!/bin/sh
exec ronn --roff --html --style=toc doc/watchexec.1.ronn
cargo run -p watchexec-cli -- --manpage > doc/watchexec.1
roff2pdf < doc/watchexec.1 > doc/watchexec.1.pdf
pandoc doc/watchexec.1 -t markdown > doc/watchexec.1.md

158
completions/bash Normal file
View File

@ -0,0 +1,158 @@
_watchexec() {
local i cur prev opts cmd
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
cmd=""
opts=""
for i in ${COMP_WORDS[@]}
do
case "${cmd},${i}" in
",$1")
cmd="watchexec"
;;
*)
;;
esac
done
case "${cmd}" in
watchexec)
opts="-w -c -o -W -r -s -k -p -n -E -1 -N -e -f -i -v -h -V --watch --clear --on-busy-update --watch-when-idle --restart --signal --kill --stop-signal --stop-timeout --debounce --stdin-quit --no-vcs-ignore --no-project-ignore --no-global-ignore --no-default-ignore --postpone --delay-run --poll --shell --no-shell-long --no-environment --emit-events-to --env --no-process-group --notify --project-origin --workdir --exts --filter --filter-file --ignore --ignore-file --fs-events --no-meta --print-events --verbose --log-file --manpage --completions --help --version [COMMAND]..."
if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
fi
case "${prev}" in
--watch)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
-w)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--clear)
COMPREPLY=($(compgen -W "clear reset" -- "${cur}"))
return 0
;;
-c)
COMPREPLY=($(compgen -W "clear reset" -- "${cur}"))
return 0
;;
--on-busy-update)
COMPREPLY=($(compgen -W "queue do-nothing restart signal" -- "${cur}"))
return 0
;;
-o)
COMPREPLY=($(compgen -W "queue do-nothing restart signal" -- "${cur}"))
return 0
;;
--signal)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
-s)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--stop-signal)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--stop-timeout)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--debounce)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--delay-run)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--poll)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--shell)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--emit-events-to)
COMPREPLY=($(compgen -W "environment stdin file json-stdin json-file none" -- "${cur}"))
return 0
;;
--env)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
-E)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--project-origin)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--workdir)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--exts)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
-e)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--filter)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
-f)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--filter-file)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--ignore)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
-i)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--ignore-file)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--fs-events)
COMPREPLY=($(compgen -W "access create remove rename modify metadata" -- "${cur}"))
return 0
;;
--log-file)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
--completions)
COMPREPLY=($(compgen -W "bash elvish fish nu powershell zsh" -- "${cur}"))
return 0
;;
*)
COMPREPLY=()
;;
esac
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
;;
esac
}
complete -F _watchexec -o bashdefault -o default watchexec

83
completions/elvish Normal file
View File

@ -0,0 +1,83 @@
use builtin;
use str;
set edit:completion:arg-completer[watchexec] = {|@words|
fn spaces {|n|
builtin:repeat $n ' ' | str:join ''
}
fn cand {|text desc|
edit:complex-candidate $text &display=$text' '(spaces (- 14 (wcswidth $text)))$desc
}
var command = 'watchexec'
for word $words[1..-1] {
if (str:has-prefix $word '-') {
break
}
set command = $command';'$word
}
var completions = [
&'watchexec'= {
cand -w 'Watch a specific file or directory'
cand --watch 'Watch a specific file or directory'
cand -c 'Clear screen before running command'
cand --clear 'Clear screen before running command'
cand -o 'What to do when receiving events while the command is running'
cand --on-busy-update 'What to do when receiving events while the command is running'
cand -s 'Send a signal to the process when it''s still running'
cand --signal 'Send a signal to the process when it''s still running'
cand --stop-signal 'Signal to send to stop the command'
cand --stop-timeout 'Time to wait for the command to exit gracefully'
cand --debounce 'Time to wait for new events before taking action'
cand --delay-run 'Sleep before running the command'
cand --poll 'Poll for filesystem changes'
cand --shell 'Use a different shell'
cand --emit-events-to 'Configure event emission'
cand -E 'Add env vars to the command'
cand --env 'Add env vars to the command'
cand --project-origin 'Set the project origin'
cand --workdir 'Set the working directory'
cand -e 'Filename extensions to filter to'
cand --exts 'Filename extensions to filter to'
cand -f 'Filename patterns to filter to'
cand --filter 'Filename patterns to filter to'
cand --filter-file 'Files to load filters from'
cand -i 'Filename patterns to filter out'
cand --ignore 'Filename patterns to filter out'
cand --ignore-file 'Files to load ignores from'
cand --fs-events 'Filesystem events to filter to'
cand --log-file 'Write diagnostic logs to a file'
cand --completions 'Generate a shell completions script'
cand -W 'Deprecated alias for ''--on-busy-update=do-nothing'''
cand --watch-when-idle 'Deprecated alias for ''--on-busy-update=do-nothing'''
cand -r 'Restart the process if it''s still running'
cand --restart 'Restart the process if it''s still running'
cand -k 'Hidden legacy shorthand for ''--signal=kill'''
cand --kill 'Hidden legacy shorthand for ''--signal=kill'''
cand --stdin-quit 'Exit when stdin closes'
cand --no-vcs-ignore 'Don''t load gitignores'
cand --no-project-ignore 'Don''t load project-local ignores'
cand --no-global-ignore 'Don''t load global ignores'
cand --no-default-ignore 'Don''t use internal default ignores'
cand -p 'Wait until first change before running command'
cand --postpone 'Wait until first change before running command'
cand -n 'Don''t use a shell'
cand --no-shell-long 'Don''t use a shell'
cand --no-environment 'Shorthand for ''--emit-events=none'''
cand --no-process-group 'Don''t use a process group'
cand -1 'Testing only: exit Watchexec after the first run'
cand -N 'Alert when commands start and end'
cand --notify 'Alert when commands start and end'
cand --no-meta 'Don''t emit fs events for metadata changes'
cand --print-events 'Print events that trigger actions'
cand -v 'Set diagnostic log level'
cand --verbose 'Set diagnostic log level'
cand --manpage 'Show the manual page'
cand -h 'Print help (see more with ''--help'')'
cand --help 'Print help (see more with ''--help'')'
cand -V 'Print version'
cand --version 'Print version'
}
]
$completions[$command]
}

43
completions/fish Normal file
View File

@ -0,0 +1,43 @@
complete -c watchexec -s w -l watch -d 'Watch a specific file or directory' -r -F
complete -c watchexec -s c -l clear -d 'Clear screen before running command' -r -f -a "{clear ,reset }"
complete -c watchexec -s o -l on-busy-update -d 'What to do when receiving events while the command is running' -r -f -a "{queue ,do-nothing ,restart ,signal }"
complete -c watchexec -s s -l signal -d 'Send a signal to the process when it\'s still running' -r
complete -c watchexec -l stop-signal -d 'Signal to send to stop the command' -r
complete -c watchexec -l stop-timeout -d 'Time to wait for the command to exit gracefully' -r
complete -c watchexec -l debounce -d 'Time to wait for new events before taking action' -r
complete -c watchexec -l delay-run -d 'Sleep before running the command' -r
complete -c watchexec -l poll -d 'Poll for filesystem changes' -r
complete -c watchexec -l shell -d 'Use a different shell' -r
complete -c watchexec -l emit-events-to -d 'Configure event emission' -r -f -a "{environment ,stdin ,file ,json-stdin ,json-file ,none }"
complete -c watchexec -s E -l env -d 'Add env vars to the command' -r
complete -c watchexec -l project-origin -d 'Set the project origin' -r -f -a "(__fish_complete_directories)"
complete -c watchexec -l workdir -d 'Set the working directory' -r -f -a "(__fish_complete_directories)"
complete -c watchexec -s e -l exts -d 'Filename extensions to filter to' -r
complete -c watchexec -s f -l filter -d 'Filename patterns to filter to' -r
complete -c watchexec -l filter-file -d 'Files to load filters from' -r -F
complete -c watchexec -s i -l ignore -d 'Filename patterns to filter out' -r
complete -c watchexec -l ignore-file -d 'Files to load ignores from' -r -F
complete -c watchexec -l fs-events -d 'Filesystem events to filter to' -r -f -a "{access ,create ,remove ,rename ,modify ,metadata }"
complete -c watchexec -l log-file -d 'Write diagnostic logs to a file' -r -F
complete -c watchexec -l completions -d 'Generate a shell completions script' -r -f -a "{bash ,elvish ,fish ,nu ,powershell ,zsh }"
complete -c watchexec -s W -l watch-when-idle -d 'Deprecated alias for \'--on-busy-update=do-nothing\''
complete -c watchexec -s r -l restart -d 'Restart the process if it\'s still running'
complete -c watchexec -s k -l kill -d 'Hidden legacy shorthand for \'--signal=kill\''
complete -c watchexec -l stdin-quit -d 'Exit when stdin closes'
complete -c watchexec -l no-vcs-ignore -d 'Don\'t load gitignores'
complete -c watchexec -l no-project-ignore -d 'Don\'t load project-local ignores'
complete -c watchexec -l no-global-ignore -d 'Don\'t load global ignores'
complete -c watchexec -l no-default-ignore -d 'Don\'t use internal default ignores'
complete -c watchexec -s p -l postpone -d 'Wait until first change before running command'
complete -c watchexec -s n -d 'Don\'t use a shell'
complete -c watchexec -l no-shell-long -d 'Don\'t use a shell'
complete -c watchexec -l no-environment -d 'Shorthand for \'--emit-events=none\''
complete -c watchexec -l no-process-group -d 'Don\'t use a process group'
complete -c watchexec -s 1 -d 'Testing only: exit Watchexec after the first run'
complete -c watchexec -s N -l notify -d 'Alert when commands start and end'
complete -c watchexec -l no-meta -d 'Don\'t emit fs events for metadata changes'
complete -c watchexec -l print-events -d 'Print events that trigger actions'
complete -c watchexec -s v -l verbose -d 'Set diagnostic log level'
complete -c watchexec -l manpage -d 'Show the manual page'
complete -c watchexec -s h -l help -d 'Print help (see more with \'--help\')'
complete -c watchexec -s V -l version -d 'Print version'

73
completions/nu Normal file
View File

@ -0,0 +1,73 @@
module completions {
def "nu-complete watchexec screen_clear" [] {
[ "clear" "reset" ]
}
def "nu-complete watchexec on_busy_update" [] {
[ "queue" "do-nothing" "restart" "signal" ]
}
def "nu-complete watchexec emit_events_to" [] {
[ "environment" "stdin" "file" "json-stdin" "json-file" "none" ]
}
def "nu-complete watchexec filter_fs_events" [] {
[ "access" "create" "remove" "rename" "modify" "metadata" ]
}
def "nu-complete watchexec completions" [] {
[ "bash" "elvish" "fish" "nu" "powershell" "zsh" ]
}
# Execute commands when watched files change
export extern watchexec [
...command: string # Command to run on changes
--watch(-w): string # Watch a specific file or directory
--clear(-c): string@"nu-complete watchexec screen_clear" # Clear screen before running command
--on-busy-update(-o): string@"nu-complete watchexec on_busy_update" # What to do when receiving events while the command is running
--watch-when-idle(-W) # Deprecated alias for '--on-busy-update=do-nothing'
--restart(-r) # Restart the process if it's still running
--signal(-s): string # Send a signal to the process when it's still running
--kill(-k) # Hidden legacy shorthand for '--signal=kill'
--stop-signal: string # Signal to send to stop the command
--stop-timeout: string # Time to wait for the command to exit gracefully
--debounce: string # Time to wait for new events before taking action
--stdin-quit # Exit when stdin closes
--no-vcs-ignore # Don't load gitignores
--no-project-ignore # Don't load project-local ignores
--no-global-ignore # Don't load global ignores
--no-default-ignore # Don't use internal default ignores
--postpone(-p) # Wait until first change before running command
--delay-run: string # Sleep before running the command
--poll: string # Poll for filesystem changes
--shell: string # Use a different shell
-n # Don't use a shell
--no-shell-long # Don't use a shell
--no-environment # Shorthand for '--emit-events=none'
--emit-events-to: string@"nu-complete watchexec emit_events_to" # Configure event emission
--env(-E): string # Add env vars to the command
--no-process-group # Don't use a process group
-1 # Testing only: exit Watchexec after the first run
--notify(-N) # Alert when commands start and end
--project-origin: string # Set the project origin
--workdir: string # Set the working directory
--exts(-e): string # Filename extensions to filter to
--filter(-f): string # Filename patterns to filter to
--filter-file: string # Files to load filters from
--ignore(-i): string # Filename patterns to filter out
--ignore-file: string # Files to load ignores from
--fs-events: string@"nu-complete watchexec filter_fs_events" # Filesystem events to filter to
--no-meta # Don't emit fs events for metadata changes
--print-events # Print events that trigger actions
--verbose(-v) # Set diagnostic log level
--log-file: string # Write diagnostic logs to a file
--manpage # Show the manual page
--completions: string@"nu-complete watchexec completions" # Generate a shell completions script
--help(-h) # Print help (see more with '--help')
--version(-V) # Print version
]
}
use completions *

89
completions/powershell Normal file
View File

@ -0,0 +1,89 @@
using namespace System.Management.Automation
using namespace System.Management.Automation.Language
Register-ArgumentCompleter -Native -CommandName 'watchexec' -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
$commandElements = $commandAst.CommandElements
$command = @(
'watchexec'
for ($i = 1; $i -lt $commandElements.Count; $i++) {
$element = $commandElements[$i]
if ($element -isnot [StringConstantExpressionAst] -or
$element.StringConstantType -ne [StringConstantType]::BareWord -or
$element.Value.StartsWith('-') -or
$element.Value -eq $wordToComplete) {
break
}
$element.Value
}) -join ';'
$completions = @(switch ($command) {
'watchexec' {
[CompletionResult]::new('-w', 'w', [CompletionResultType]::ParameterName, 'Watch a specific file or directory')
[CompletionResult]::new('--watch', 'watch', [CompletionResultType]::ParameterName, 'Watch a specific file or directory')
[CompletionResult]::new('-c', 'c', [CompletionResultType]::ParameterName, 'Clear screen before running command')
[CompletionResult]::new('--clear', 'clear', [CompletionResultType]::ParameterName, 'Clear screen before running command')
[CompletionResult]::new('-o', 'o', [CompletionResultType]::ParameterName, 'What to do when receiving events while the command is running')
[CompletionResult]::new('--on-busy-update', 'on-busy-update', [CompletionResultType]::ParameterName, 'What to do when receiving events while the command is running')
[CompletionResult]::new('-s', 's', [CompletionResultType]::ParameterName, 'Send a signal to the process when it''s still running')
[CompletionResult]::new('--signal', 'signal', [CompletionResultType]::ParameterName, 'Send a signal to the process when it''s still running')
[CompletionResult]::new('--stop-signal', 'stop-signal', [CompletionResultType]::ParameterName, 'Signal to send to stop the command')
[CompletionResult]::new('--stop-timeout', 'stop-timeout', [CompletionResultType]::ParameterName, 'Time to wait for the command to exit gracefully')
[CompletionResult]::new('--debounce', 'debounce', [CompletionResultType]::ParameterName, 'Time to wait for new events before taking action')
[CompletionResult]::new('--delay-run', 'delay-run', [CompletionResultType]::ParameterName, 'Sleep before running the command')
[CompletionResult]::new('--poll', 'poll', [CompletionResultType]::ParameterName, 'Poll for filesystem changes')
[CompletionResult]::new('--shell', 'shell', [CompletionResultType]::ParameterName, 'Use a different shell')
[CompletionResult]::new('--emit-events-to', 'emit-events-to', [CompletionResultType]::ParameterName, 'Configure event emission')
[CompletionResult]::new('-E', 'E', [CompletionResultType]::ParameterName, 'Add env vars to the command')
[CompletionResult]::new('--env', 'env', [CompletionResultType]::ParameterName, 'Add env vars to the command')
[CompletionResult]::new('--project-origin', 'project-origin', [CompletionResultType]::ParameterName, 'Set the project origin')
[CompletionResult]::new('--workdir', 'workdir', [CompletionResultType]::ParameterName, 'Set the working directory')
[CompletionResult]::new('-e', 'e', [CompletionResultType]::ParameterName, 'Filename extensions to filter to')
[CompletionResult]::new('--exts', 'exts', [CompletionResultType]::ParameterName, 'Filename extensions to filter to')
[CompletionResult]::new('-f', 'f', [CompletionResultType]::ParameterName, 'Filename patterns to filter to')
[CompletionResult]::new('--filter', 'filter', [CompletionResultType]::ParameterName, 'Filename patterns to filter to')
[CompletionResult]::new('--filter-file', 'filter-file', [CompletionResultType]::ParameterName, 'Files to load filters from')
[CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'Filename patterns to filter out')
[CompletionResult]::new('--ignore', 'ignore', [CompletionResultType]::ParameterName, 'Filename patterns to filter out')
[CompletionResult]::new('--ignore-file', 'ignore-file', [CompletionResultType]::ParameterName, 'Files to load ignores from')
[CompletionResult]::new('--fs-events', 'fs-events', [CompletionResultType]::ParameterName, 'Filesystem events to filter to')
[CompletionResult]::new('--log-file', 'log-file', [CompletionResultType]::ParameterName, 'Write diagnostic logs to a file')
[CompletionResult]::new('--completions', 'completions', [CompletionResultType]::ParameterName, 'Generate a shell completions script')
[CompletionResult]::new('-W', 'W', [CompletionResultType]::ParameterName, 'Deprecated alias for ''--on-busy-update=do-nothing''')
[CompletionResult]::new('--watch-when-idle', 'watch-when-idle', [CompletionResultType]::ParameterName, 'Deprecated alias for ''--on-busy-update=do-nothing''')
[CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'Restart the process if it''s still running')
[CompletionResult]::new('--restart', 'restart', [CompletionResultType]::ParameterName, 'Restart the process if it''s still running')
[CompletionResult]::new('-k', 'k', [CompletionResultType]::ParameterName, 'Hidden legacy shorthand for ''--signal=kill''')
[CompletionResult]::new('--kill', 'kill', [CompletionResultType]::ParameterName, 'Hidden legacy shorthand for ''--signal=kill''')
[CompletionResult]::new('--stdin-quit', 'stdin-quit', [CompletionResultType]::ParameterName, 'Exit when stdin closes')
[CompletionResult]::new('--no-vcs-ignore', 'no-vcs-ignore', [CompletionResultType]::ParameterName, 'Don''t load gitignores')
[CompletionResult]::new('--no-project-ignore', 'no-project-ignore', [CompletionResultType]::ParameterName, 'Don''t load project-local ignores')
[CompletionResult]::new('--no-global-ignore', 'no-global-ignore', [CompletionResultType]::ParameterName, 'Don''t load global ignores')
[CompletionResult]::new('--no-default-ignore', 'no-default-ignore', [CompletionResultType]::ParameterName, 'Don''t use internal default ignores')
[CompletionResult]::new('-p', 'p', [CompletionResultType]::ParameterName, 'Wait until first change before running command')
[CompletionResult]::new('--postpone', 'postpone', [CompletionResultType]::ParameterName, 'Wait until first change before running command')
[CompletionResult]::new('-n', 'n', [CompletionResultType]::ParameterName, 'Don''t use a shell')
[CompletionResult]::new('--no-shell-long', 'no-shell-long', [CompletionResultType]::ParameterName, 'Don''t use a shell')
[CompletionResult]::new('--no-environment', 'no-environment', [CompletionResultType]::ParameterName, 'Shorthand for ''--emit-events=none''')
[CompletionResult]::new('--no-process-group', 'no-process-group', [CompletionResultType]::ParameterName, 'Don''t use a process group')
[CompletionResult]::new('-1', '1', [CompletionResultType]::ParameterName, 'Testing only: exit Watchexec after the first run')
[CompletionResult]::new('-N', 'N', [CompletionResultType]::ParameterName, 'Alert when commands start and end')
[CompletionResult]::new('--notify', 'notify', [CompletionResultType]::ParameterName, 'Alert when commands start and end')
[CompletionResult]::new('--no-meta', 'no-meta', [CompletionResultType]::ParameterName, 'Don''t emit fs events for metadata changes')
[CompletionResult]::new('--print-events', 'print-events', [CompletionResultType]::ParameterName, 'Print events that trigger actions')
[CompletionResult]::new('-v', 'v', [CompletionResultType]::ParameterName, 'Set diagnostic log level')
[CompletionResult]::new('--verbose', 'verbose', [CompletionResultType]::ParameterName, 'Set diagnostic log level')
[CompletionResult]::new('--manpage', 'manpage', [CompletionResultType]::ParameterName, 'Show the manual page')
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help (see more with ''--help'')')
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help (see more with ''--help'')')
[CompletionResult]::new('-V', 'V', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
break
}
})
$completions.Where{ $_.CompletionText -like "$wordToComplete*" } |
Sort-Object -Property ListItemText
}

View File

@ -1,41 +1,91 @@
#compdef watchexec
setopt localoptions extended_glob
autoload -U is-at-least
local cmd
local -a args
local -a _comp_priv_prefix
_watchexec() {
typeset -A opt_args
typeset -a _arguments_options
local ret=1
cmd="$words[1]"
if is-at-least 5.2; then
_arguments_options=(-s -S -C)
else
_arguments_options=(-s -C)
fi
args=(
'(-c --clear)'{-c,--clear}'[Clear screen before executing command]'
'(-h --help)'{-h,--help}'[Prints help information]'
'--shell=[Change the wrapping shell, or set to none to disable]:SHELL'
'-n[Shorthand for --shell=none]'
'--no-environment[Do not set WATCHEXEC_*_PATH environment variables for command]'
'--no-meta[Ignore metadata changes]'
'(-p --postpone)'{-p,--postpone}'[Wait until first change to execute command]'
'(-r --restart)'{-r,--restart}'[Restart the process if it''s still running]'
'(-W --watch-when-idle)'{-W,--watch-when-idle}'[Ignore events while the command is still running]'
'(-V --version)'{-V,--version}'[Prints version information]'
'(-v --verbose)'{-v,-vv,-vvv,-vvvv,--verbose}'[Print debugging messages to stderr]'
'--log-file=[Output logs to a file, in JSON format]:path:_path_files -/'
'(-N --notify)'{-N,--notify}'[Send desktop notifications on command start and end]'
'--print-events[Print triggering events to stderr (changed paths, etc)]'
'(-d --debounce)'{-d+,--debounce=}'[Set the timeout between detected change and command execution, defaults to 100ms]:milliseconds'
'(-e --exts)'{-e+,--exts=}'[Comma-separated list of file extensions to watch (js,css,html)]:extensions'
'(-f --filter)'{-f+,--filter=}'[Ignore all modifications except those matching the pattern]:pattern'
'(-i --ignore)'{-i+,--ignore=}'[Ignore modifications to paths matching the pattern]:pattern'
'(-w --watch)'{-w+,--watch=}'[Watch a specific directory]:path:_path_files -/'
'(-s --signal)'{-s+,--signal=}'[Send signal to process upon changes, e.g. SIGHUP]:signal'
'--force-poll=[Forces polling mode]:interval'
'--no-project-ignore[Skip auto-loading of project-local ignore files (.gitignore, .ignore, etc.) for filtering]'
'--no-default-ignore[Skip auto-ignoring of commonly ignored globs]'
'--no-global-ignore[Skip auto-loading of global or environment-wide ignore files]'
'--no-vcs-ignore[Skip auto-loading of VCS ignore files for filtering]'
'(-)1:command: _command_names -e'
'*::arguments:{ _comp_priv_prefix=( $cmd -n ${(kv)opt_args[-u]} ) ; _normal }'
)
local context curcontext="$curcontext" state line
_arguments "${_arguments_options[@]}" \
'*-w+[Watch a specific file or directory]:PATH:_files' \
'*--watch=[Watch a specific file or directory]:PATH:_files' \
'-c+[Clear screen before running command]' \
'--clear=[Clear screen before running command]' \
'-o+[What to do when receiving events while the command is running]:MODE:(queue do-nothing restart signal)' \
'--on-busy-update=[What to do when receiving events while the command is running]:MODE:(queue do-nothing restart signal)' \
'(-r --restart -W --watch-when-idle)-s+[Send a signal to the process when it'\''s still running]:SIGNAL: ' \
'(-r --restart -W --watch-when-idle)--signal=[Send a signal to the process when it'\''s still running]:SIGNAL: ' \
'--stop-signal=[Signal to send to stop the command]:SIGNAL: ' \
'--stop-timeout=[Time to wait for the command to exit gracefully]:TIMEOUT: ' \
'--debounce=[Time to wait for new events before taking action]:TIMEOUT: ' \
'--delay-run=[Sleep before running the command]:DURATION: ' \
'--poll=[Poll for filesystem changes]' \
'--shell=[Use a different shell]:SHELL: ' \
'--emit-events-to=[Configure event emission]:MODE:(environment stdin file json-stdin json-file none)' \
'*-E+[Add env vars to the command]:KEY=VALUE: ' \
'*--env=[Add env vars to the command]:KEY=VALUE: ' \
'--project-origin=[Set the project origin]:DIRECTORY:_files -/' \
'--workdir=[Set the working directory]:DIRECTORY:_files -/' \
'*-e+[Filename extensions to filter to]:EXTENSIONS: ' \
'*--exts=[Filename extensions to filter to]:EXTENSIONS: ' \
'*-f+[Filename patterns to filter to]:PATTERN: ' \
'*--filter=[Filename patterns to filter to]:PATTERN: ' \
'*--filter-file=[Files to load filters from]:PATH:_files' \
'*-i+[Filename patterns to filter out]:PATTERN: ' \
'*--ignore=[Filename patterns to filter out]:PATTERN: ' \
'*--ignore-file=[Files to load ignores from]:PATH:_files' \
'*--fs-events=[Filesystem events to filter to]:EVENTS:(access create remove rename modify metadata)' \
'--log-file=[Write diagnostic logs to a file]' \
'(--manpage)--completions=[Generate a shell completions script]:COMPLETIONS:(bash elvish fish nu powershell zsh)' \
'(-o --on-busy-update -r --restart)-W[Deprecated alias for '\''--on-busy-update=do-nothing'\'']' \
'(-o --on-busy-update -r --restart)--watch-when-idle[Deprecated alias for '\''--on-busy-update=do-nothing'\'']' \
'(-o --on-busy-update -W --watch-when-idle)-r[Restart the process if it'\''s still running]' \
'(-o --on-busy-update -W --watch-when-idle)--restart[Restart the process if it'\''s still running]' \
'-k[Hidden legacy shorthand for '\''--signal=kill'\'']' \
'--kill[Hidden legacy shorthand for '\''--signal=kill'\'']' \
'--stdin-quit[Exit when stdin closes]' \
'--no-vcs-ignore[Don'\''t load gitignores]' \
'--no-project-ignore[Don'\''t load project-local ignores]' \
'--no-global-ignore[Don'\''t load global ignores]' \
'--no-default-ignore[Don'\''t use internal default ignores]' \
'-p[Wait until first change before running command]' \
'--postpone[Wait until first change before running command]' \
'-n[Don'\''t use a shell]' \
'--no-shell-long[Don'\''t use a shell]' \
'--no-environment[Shorthand for '\''--emit-events=none'\'']' \
'--no-process-group[Don'\''t use a process group]' \
'-1[Testing only: exit Watchexec after the first run]' \
'-N[Alert when commands start and end]' \
'--notify[Alert when commands start and end]' \
'(--fs-events)--no-meta[Don'\''t emit fs events for metadata changes]' \
'--print-events[Print events that trigger actions]' \
'*-v[Set diagnostic log level]' \
'*--verbose[Set diagnostic log level]' \
'(--completions)--manpage[Show the manual page]' \
'-h[Print help (see more with '\''--help'\'')]' \
'--help[Print help (see more with '\''--help'\'')]' \
'-V[Print version]' \
'--version[Print version]' \
'*::command -- Command to run on changes:_cmdstring' \
&& ret=0
}
_arguments -s -S $args
(( $+functions[_watchexec_commands] )) ||
_watchexec_commands() {
local commands; commands=()
_describe -t commands 'watchexec commands' commands "$@"
}
if [ "$funcstack[1]" = "_watchexec" ]; then
_watchexec "$@"
else
compdef _watchexec watchexec
fi

View File

@ -2,7 +2,7 @@
name = "watchexec-cli"
version = "1.21.1"
authors = ["Matt Green <mattgreenrocks@gmail.com>", "Félix Saparelli <felix@passcod.name>"]
authors = ["Félix Saparelli <felix@passcod.name>", "Matt Green <mattgreenrocks@gmail.com>"]
license = "Apache-2.0"
description = "Executes commands in response to file modifications"
keywords = ["watcher", "filesystem", "cli", "watchexec"]
@ -20,16 +20,25 @@ name = "watchexec"
path = "src/main.rs"
[dependencies]
argfile = "0.1.5"
chrono = "0.4.23"
clap_complete = "4.1.4"
clap_mangen = "0.2.9"
command-group = { version = "2.1.0", features = ["with-tokio"] }
console-subscriber = { version = "0.1.0", optional = true }
dirs = "4.0.0"
futures = "0.3.17"
humantime = "2.1.0"
is-terminal = "0.4.4"
miette = { version = "5.3.0", features = ["fancy"] }
notify-rust = "4.5.2"
tracing = "0.1.26"
which = "4.4.0"
clap_complete_nushell = "0.1.10"
[dependencies.clap]
version = "3.1.18"
features = ["cargo", "wrap_help"]
version = "4.1.8"
features = ["cargo", "derive", "env", "wrap_help"]
[dependencies.ignore-files]
version = "1.1.0"
@ -47,10 +56,6 @@ path = "../lib"
version = "1.1.0"
path = "../filterer/globset"
[dependencies.watchexec-filterer-tagged]
version = "0.2.0"
path = "../filterer/tagged"
[dependencies.tokio]
version = "1.24.2"
features = [
@ -75,6 +80,12 @@ features = [
[target.'cfg(target_env = "musl")'.dependencies]
mimalloc = "0.1.26"
[target.'cfg(target_os = "linux")'.dependencies]
shadow-rs = "0.21.0"
[target.'cfg(target_os = "linux")'.build-dependencies]
shadow-rs = "0.21.0"
[build-dependencies]
embed-resource = "1.6.1"

View File

@ -95,13 +95,13 @@ On Windows, you may prefer to use Powershell:
$ watchexec --shell=powershell -- test-connection localhost
## Complex Usage Examples
## Complex Usage Examples
Turn a plain converter tool like PlantUML or Pandoc into a powerful live-editing tool, either as a script
#!/usr/bin/env bash
set -Eeuo pipefail
SOURCE="test.puml" # Define source file
TARGET="test.png" # Define conversion target file
CONVERT="plantuml $SOURCE" # Define how to convert source to target
@ -111,14 +111,13 @@ Turn a plain converter tool like PlantUML or Pandoc into a powerful live-editing
watchexec --filter $SOURCE -- $CONVERT # Update target file on any source file change
or condensed as a single line
# Bash
$ SOURCE="test.puml"; TARGET="test.png"; CONVERT="plantuml $SOURCE"; VIEW="feh $TARGET"; if [ ! -f $TARGET ]; then $CONVERT; fi; ($VIEW &); watchexec -f $SOURCE -- $CONVERT
# Zsh
$ SOURCE="test.puml"; TARGET="test.png"; CONVERT="plantuml $SOURCE"; VIEW="feh $TARGET"; if [ ! -f $TARGET ]; then $CONVERT; fi; ($=VIEW &); watchexec -f $SOURCE -- $CONVERT
Replace [PlantUML](https://plantuml.com/) with another converter like [Pandoc](https://pandoc.org/):
`plantuml $SOURCE` turns into `pandoc $SOURCE --output $TARGET`,
Replace [PlantUML](https://plantuml.com/) with another converter like [Pandoc](https://pandoc.org/): `plantuml $SOURCE` turns into `pandoc $SOURCE --output $TARGET`.
Similarly, replace the [Feh](https://feh.finalrewind.org/) image viewer with another viewer for your target file like the PDF viewer [Evince](https://wiki.gnome.org/Apps/Evince): `feh $TARGET` turns into `evince $TARGET`.
## Installation
@ -161,4 +160,18 @@ Only the latest Rust stable is supported, but older versions may work.
Currently available shell completions:
- bash: `completions/bash` should be installed to `/usr/share/bash-completion/completions/watchexec`
- elvish: `completions/elvish` should be installed to `$XDG_CONFIG_HOME/elvish/completions/`
- fish: `completions/fish` should be installed to `/usr/share/fish/vendor_completions.d/watchexec.fish`
- nu: `completions/nu` should be installed to `$XDG_CONFIG_HOME/nu/completions/`
- powershell: `completions/powershell` should be installed to `$PROFILE/`
- zsh: `completions/zsh` should be installed to `/usr/share/zsh/site-functions/_watchexec`
If not bundled, you can generate completions for your shell with `watchexec --completions <shell>`.
## Manual
There's a manual page at `doc/watchexec.1`. Install it to `/usr/share/man/man1/`.
If not bundled, you can generate a manual page with `watchexec --manual > /path/to/watchexec.1`, or view it inline with `watchexec --manual` (requires `man`).
You can also [read a text version](../../doc/watchexec.1.md) or a [PDF](../../doc/watchexec.1.pdf).

View File

@ -1,3 +1,5 @@
fn main() {
embed_resource::compile("watchexec-manifest.rc");
#[cfg(target_os = "linux")]
shadow_rs::new().unwrap();
}

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,5 @@
use std::convert::Infallible;
use clap::ArgMatches;
use miette::Report;
use tracing::error;
use watchexec::{
@ -10,7 +9,9 @@ use watchexec::{
ErrorHook,
};
pub fn init(_args: &ArgMatches) -> InitConfig {
use crate::args::Args;
pub fn init(_args: &Args) -> InitConfig {
let mut config = InitConfig::default();
config.on_error(SyncFnHandler::from(
|err: ErrorHook| -> std::result::Result<(), Infallible> {

View File

@ -1,9 +1,5 @@
use std::{
collections::HashMap, convert::Infallible, env::current_dir, ffi::OsString, path::Path,
str::FromStr, string::ToString, time::Duration,
};
use std::{collections::HashMap, convert::Infallible, env::current_dir, ffi::OsString};
use clap::ArgMatches;
use miette::{miette, IntoDiagnostic, Result};
use notify_rust::Notification;
use tracing::{debug, debug_span};
@ -20,64 +16,39 @@ use watchexec::{
signal::{process::SubSignal, source::MainSignal},
};
pub fn runtime(args: &ArgMatches) -> Result<RuntimeConfig> {
use crate::args::{Args, ClearMode, EmitEvents, OnBusyUpdate};
pub fn runtime(args: &Args) -> Result<RuntimeConfig> {
let _span = debug_span!("args-runtime").entered();
let mut config = RuntimeConfig::default();
config.command(interpret_command_args(args)?);
config.pathset(match args.values_of_os("paths") {
Some(paths) => paths.map(|os| Path::new(os).to_owned()).collect(),
None => vec![current_dir().into_diagnostic()?],
config.pathset(if args.paths.is_empty() {
vec![current_dir().into_diagnostic()?]
} else {
args.paths.clone()
});
config.action_throttle(Duration::from_millis(
args.value_of("debounce")
.unwrap_or("50")
.parse()
.into_diagnostic()?,
));
config.action_throttle(args.debounce.0);
config.command_grouped(!args.no_process_group);
config.keyboard_emit_eof(args.stdin_quit);
config.keyboard_emit_eof(args.is_present("stdin-quit"));
if let Some(interval) = args.value_of("poll") {
config.file_watcher(Watcher::Poll(Duration::from_millis(
interval.parse().into_diagnostic()?,
)));
if let Some(interval) = args.poll {
config.file_watcher(Watcher::Poll(interval.0));
}
if args.is_present("no-process-group") {
config.command_grouped(false);
}
let clear = args.screen_clear;
let notif = args.notify;
let on_busy = args.on_busy_update;
let clear = args.is_present("clear");
let notif = args.is_present("notif");
let on_busy = if args.is_present("restart") {
"restart"
} else if args.is_present("watch-when-idle") {
"do-nothing"
} else {
args.value_of("on-busy-update").unwrap_or("queue")
}
.to_owned();
let signal = args.signal;
let stop_signal = args.stop_signal;
let stop_timeout = args.stop_timeout.0;
let signal = if args.is_present("kill") {
Some(SubSignal::ForceStop)
} else {
args.value_of("signal")
.map(SubSignal::from_str)
.transpose()
.into_diagnostic()?
};
let print_events = args.is_present("print-events");
let once = args.is_present("once");
let delay_run = args
.value_of("delay-run")
.map(u64::from_str)
.transpose()
.into_diagnostic()?
.map(Duration::from_secs);
let print_events = args.print_events;
let once = args.once;
let delay_run = args.delay_run.map(|ts| ts.0);
config.on_action(move |action: Action| {
let fut = async { Ok::<(), Infallible>(()) };
@ -176,8 +147,14 @@ pub fn runtime(args: &ArgMatches) -> Result<RuntimeConfig> {
}
}
let start = if clear {
Outcome::both(Outcome::Clear, Outcome::Start)
let start = if let Some(mode) = clear {
Outcome::both(
match mode {
ClearMode::Clear => Outcome::Clear,
ClearMode::Reset => Outcome::Reset,
},
Outcome::Start,
)
} else {
Outcome::Start
};
@ -189,22 +166,19 @@ pub fn runtime(args: &ArgMatches) -> Result<RuntimeConfig> {
};
let when_idle = start.clone();
let when_running = match on_busy.as_str() {
"restart" => Outcome::both(
if let Some(sig) = signal {
Outcome::both(
Outcome::Signal(sig),
Outcome::both(Outcome::Sleep(Duration::from_secs(60)), Outcome::Stop),
)
} else {
Outcome::Stop
},
let when_running = match on_busy {
OnBusyUpdate::Restart => Outcome::both(
Outcome::both(
Outcome::Signal(stop_signal.unwrap_or(SubSignal::Terminate)),
Outcome::both(Outcome::Sleep(stop_timeout), Outcome::Stop),
),
start,
),
"signal" => Outcome::Signal(signal.unwrap_or(SubSignal::Terminate)),
"queue" => Outcome::wait(start),
// "do-nothing" => Outcome::DoNothing,
_ => Outcome::DoNothing,
OnBusyUpdate::Signal => {
Outcome::Signal(stop_signal.or(signal).unwrap_or(SubSignal::Terminate))
}
OnBusyUpdate::Queue => Outcome::wait(start),
OnBusyUpdate::DoNothing => Outcome::DoNothing,
};
action.outcome(Outcome::if_running(when_running, when_idle));
@ -213,7 +187,8 @@ pub fn runtime(args: &ArgMatches) -> Result<RuntimeConfig> {
});
let mut add_envs = HashMap::new();
for pair in args.values_of("command-env").unwrap_or_default() {
// TODO: move to args and use osstrings
for pair in &args.env {
if let Some((k, v)) = pair.split_once('=') {
add_envs.insert(k.to_owned(), OsString::from(v));
} else {
@ -225,28 +200,32 @@ pub fn runtime(args: &ArgMatches) -> Result<RuntimeConfig> {
"additional environment variables to add to command"
);
let workdir = args
.value_of_os("command-workdir")
.map(|wkd| Path::new(wkd).to_owned());
let workdir = args.workdir.clone();
let no_env = args.is_present("no-environment");
let emit_events_to = args.emit_events_to;
config.on_pre_spawn(move |prespawn: PreSpawn| {
let add_envs = add_envs.clone();
let workdir = workdir.clone();
let mut add_envs = add_envs.clone();
match emit_events_to {
EmitEvents::Environment => {
add_envs.extend(
summarise_events_to_env(prespawn.events.iter())
.into_iter()
.map(|(k, v)| (format!("WATCHEXEC_{k}_PATH"), v)),
);
}
EmitEvents::Stdin => todo!(),
EmitEvents::File => todo!(),
EmitEvents::JsonStdin => todo!(),
EmitEvents::JsonFile => todo!(),
EmitEvents::None => {}
}
async move {
if !no_env || !add_envs.is_empty() || workdir.is_some() {
if !add_envs.is_empty() || workdir.is_some() {
if let Some(mut command) = prespawn.command().await {
let mut envs = add_envs.clone();
if !no_env {
envs.extend(
summarise_events_to_env(prespawn.events.iter())
.into_iter()
.map(|(k, v)| (format!("WATCHEXEC_{k}_PATH"), v)),
);
}
for (k, v) in envs {
for (k, v) in add_envs {
debug!(?k, ?v, "inserting environment variable");
command.env(k, v);
}
@ -282,20 +261,19 @@ pub fn runtime(args: &ArgMatches) -> Result<RuntimeConfig> {
Ok(config)
}
fn interpret_command_args(args: &ArgMatches) -> Result<Command> {
let mut cmd = args
.values_of("command")
.expect("(clap) Bug: command is not present")
.map(ToString::to_string)
.collect::<Vec<_>>();
fn interpret_command_args(args: &Args) -> Result<Command> {
let mut cmd = args.command.clone();
if cmd.is_empty() {
panic!("(clap) Bug: command is not present");
}
Ok(if args.is_present("no-shell") {
Ok(if args.no_shell || args.no_shell_long {
Command::Exec {
prog: cmd.remove(0),
args: cmd,
}
} else {
let (shell, shopts) = if let Some(s) = args.value_of("shell") {
let (shell, shopts) = if let Some(s) = &args.shell {
if s.is_empty() {
return Err(RuntimeError::CommandShellEmptyShell).into_diagnostic();
} else if s.eq_ignore_ascii_case("powershell") {

View File

@ -1,6 +1,4 @@
mod common;
mod globset;
mod tagged;
pub use globset::globset;
pub use tagged::tagged;

View File

@ -4,7 +4,6 @@ use std::{
path::{Path, PathBuf},
};
use clap::ArgMatches;
use ignore_files::IgnoreFile;
use miette::{miette, IntoDiagnostic, Result};
use project_origins::ProjectType;
@ -12,12 +11,14 @@ use tokio::fs::canonicalize;
use tracing::{debug, info, warn};
use watchexec::paths::common_prefix;
pub async fn dirs(args: &ArgMatches) -> Result<(PathBuf, PathBuf)> {
use crate::args::Args;
pub async fn dirs(args: &Args) -> Result<(PathBuf, PathBuf)> {
let curdir = env::current_dir().into_diagnostic()?;
let curdir = canonicalize(curdir).await.into_diagnostic()?;
debug!(?curdir, "current directory");
let project_origin = if let Some(origin) = args.value_of_os("project-origin") {
let project_origin = if let Some(origin) = &args.project_origin {
debug!(?origin, "project origin override");
canonicalize(origin).await.into_diagnostic()?
} else {
@ -28,7 +29,7 @@ pub async fn dirs(args: &ArgMatches) -> Result<(PathBuf, PathBuf)> {
debug!(?homedir, "home directory");
let mut paths = HashSet::new();
for path in args.values_of_os("paths").unwrap_or_default() {
for path in &args.paths {
paths.insert(canonicalize(path).await.into_diagnostic()?);
}
@ -91,19 +92,13 @@ pub async fn vcs_types(origin: &Path) -> Vec<ProjectType> {
vcs_types
}
pub async fn ignores(
args: &ArgMatches,
vcs_types: &[ProjectType],
origin: &Path,
) -> Vec<IgnoreFile> {
pub async fn ignores(args: &Args, vcs_types: &[ProjectType], origin: &Path) -> Vec<IgnoreFile> {
let (mut ignores, errors) = ignore_files::from_origin(origin).await;
for err in errors {
warn!("while discovering project-local ignore files: {}", err);
}
debug!(?ignores, "discovered ignore files from project origin");
// TODO: use drain_ignore instead for x = x.filter()... when that stabilises
let mut skip_git_global_excludes = false;
if !vcs_types.is_empty() {
ignores = ignores
@ -163,7 +158,18 @@ pub async fn ignores(
"combined and applied overall vcs filter over ignores"
);
if args.is_present("no-project-ignore") {
ignores.extend(args.ignore_files.iter().map(|ig| IgnoreFile {
applies_to: None,
applies_in: None,
path: ig.clone(),
}));
debug!(
?ignores,
?args.ignore_files,
"combined with ignore files from command line / env"
);
if args.no_project_ignore {
ignores = ignores
.into_iter()
.filter(|ig| {
@ -178,7 +184,7 @@ pub async fn ignores(
);
}
if args.is_present("no-global-ignore") {
if args.no_global_ignore {
ignores = ignores
.into_iter()
.filter(|ig| !matches!(ig.applies_in, None))
@ -186,7 +192,7 @@ pub async fn ignores(
debug!(?ignores, "filtered ignores to exclude global ignores");
}
if args.is_present("no-vcs-ignore") {
if args.no_vcs_ignore {
ignores = ignores
.into_iter()
.filter(|ig| matches!(ig.applies_to, None))

View File

@ -1,12 +1,12 @@
use std::{
ffi::{OsStr, OsString},
path::MAIN_SEPARATOR,
ffi::OsString,
path::{Path, PathBuf, MAIN_SEPARATOR},
sync::Arc,
};
use clap::ArgMatches;
use miette::{IntoDiagnostic, Result};
use tracing::info;
use tokio::io::{AsyncBufReadExt, BufReader};
use tracing::{info, trace, trace_span};
use watchexec::{
error::RuntimeError,
event::{
@ -17,16 +17,19 @@ use watchexec::{
};
use watchexec_filterer_globset::GlobsetFilterer;
pub async fn globset(args: &ArgMatches) -> Result<Arc<WatchexecFilterer>> {
use crate::args::{Args, FsEvent};
pub async fn globset(args: &Args) -> Result<Arc<WatchexecFilterer>> {
let (project_origin, workdir) = super::common::dirs(args).await?;
let vcs_types = super::common::vcs_types(&project_origin).await;
let ignore_files = super::common::ignores(args, &vcs_types, &project_origin).await;
let mut ignores = Vec::new();
if !args.is_present("no-default-ignore") {
if !args.no_default_ignore {
ignores.extend([
(format!("**{MAIN_SEPARATOR}.DS_Store"), None),
(String::from("watchexec.*.log"), None),
(String::from("*.py[co]"), None),
(String::from("#*#"), None),
(String::from(".#*"), None),
@ -46,246 +49,86 @@ pub async fn globset(args: &ArgMatches) -> Result<Arc<WatchexecFilterer>> {
]);
}
let filters = args
.values_of("filter")
.unwrap_or_default()
.map(|f| (f.to_owned(), Some(workdir.clone())));
let mut filters = args
.filter_patterns
.iter()
.map(|f| (f.to_owned(), Some(workdir.clone())))
.collect::<Vec<_>>();
for filter_file in &args.filter_files {
filters.extend(read_filter_file(filter_file).await?);
}
ignores.extend(
args.values_of("ignore")
.unwrap_or_default()
args.ignore_patterns
.iter()
.map(|f| (f.to_owned(), Some(workdir.clone()))),
);
let exts = args
.values_of_os("extensions")
.unwrap_or_default()
.flat_map(|s| s.split(b','))
.map(|e| os_strip_prefix(e, b'.'));
.filter_extensions
.iter()
.map(|e| OsString::from(e.strip_prefix('.').unwrap_or(e)));
info!("initialising Globset filterer");
Ok(Arc::new(WatchexecFilterer {
inner: GlobsetFilterer::new(project_origin, filters, ignores, ignore_files, exts)
.await
.into_diagnostic()?,
no_meta: args.is_present("no-meta"),
fs_events: args.filter_fs_events.clone(),
}))
}
async fn read_filter_file(path: &Path) -> Result<Vec<(String, Option<PathBuf>)>> {
let _span = trace_span!("loading filter file", ?path).entered();
let file = tokio::fs::File::open(path).await.into_diagnostic()?;
let mut filters =
Vec::with_capacity(file.metadata().await.map(|m| m.len() as usize).unwrap_or(0) / 20);
let reader = BufReader::new(file);
let mut lines = reader.lines();
while let Some(line) = lines.next_line().await.into_diagnostic()? {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
trace!(?line, "adding filter line");
filters.push((line.to_owned(), Some(path.to_owned())));
}
Ok(filters)
}
/// A custom filterer that combines the library's Globset filterer and a switch for --no-meta
#[derive(Debug)]
pub struct WatchexecFilterer {
inner: GlobsetFilterer,
no_meta: bool,
fs_events: Vec<FsEvent>,
}
impl Filterer for WatchexecFilterer {
fn check_event(&self, event: &Event, priority: Priority) -> Result<bool, RuntimeError> {
let is_meta = event.tags.iter().any(|tag| {
matches!(
tag,
Tag::FileEventKind(FileEventKind::Modify(ModifyKind::Metadata(_)))
)
});
for tag in &event.tags {
if let Tag::FileEventKind(fek) = tag {
let normalised = match fek {
FileEventKind::Access(_) => FsEvent::Access,
FileEventKind::Modify(ModifyKind::Name(_)) => FsEvent::Rename,
FileEventKind::Modify(ModifyKind::Metadata(_)) => FsEvent::Metadata,
FileEventKind::Modify(_) => FsEvent::Modify,
FileEventKind::Create(_) => FsEvent::Create,
FileEventKind::Remove(_) => FsEvent::Remove,
_ => continue,
};
if self.no_meta && is_meta {
Ok(false)
} else {
self.inner.check_event(event, priority)
}
}
}
trait OsStringSplit {
fn split(&self, sep: u8) -> OsSplit;
}
impl OsStringSplit for OsStr {
fn split(&self, sep: u8) -> OsSplit {
OsSplit {
os: self.to_os_string(),
pos: 0,
sep,
}
}
}
struct OsSplit {
os: OsString,
pos: usize,
sep: u8,
}
#[cfg(unix)]
impl Iterator for OsSplit {
type Item = OsString;
fn next(&mut self) -> Option<Self::Item> {
use std::os::unix::ffi::{OsStrExt, OsStringExt};
let bytes = self.os.as_bytes();
if self.pos >= bytes.len() {
None
} else {
let mut pos = self.pos;
while pos < bytes.len() && bytes[pos] != self.sep {
pos += 1;
if !self.fs_events.contains(&normalised) {
return Ok(false);
}
}
let res = OsString::from_vec(bytes[self.pos..pos].to_vec());
self.pos = pos + 1;
Some(res)
}
}
}
#[cfg(unix)]
fn os_strip_prefix(os: OsString, prefix: u8) -> OsString {
use std::os::unix::ffi::{OsStrExt, OsStringExt};
let bytes = os.as_bytes();
if bytes.first().copied() == Some(prefix) {
OsString::from_vec(bytes[1..].to_vec())
} else {
os
}
}
#[cfg(windows)]
impl Iterator for OsSplit {
type Item = OsString;
fn next(&mut self) -> Option<Self::Item> {
use std::os::windows::ffi::{OsStrExt, OsStringExt};
let wides = self.os.encode_wide().skip(self.pos);
let mut cur = Vec::new();
for wide in wides {
if wide == u16::from(self.sep) {
break;
}
cur.push(wide);
}
self.pos += cur.len() + 1;
if cur.is_empty() && self.pos >= self.os.len() {
None
} else {
Some(OsString::from_wide(&cur))
}
self.inner.check_event(event, priority)
}
}
#[cfg(windows)]
fn os_strip_prefix(os: OsString, prefix: u8) -> OsString {
use std::os::windows::ffi::{OsStrExt, OsStringExt};
let wides: Vec<u16> = os.encode_wide().collect();
if wides.first().copied() == Some(u16::from(prefix)) {
OsString::from_wide(&wides[1..])
} else {
os
}
}
#[cfg(test)]
#[test]
fn os_split_none() {
let os = OsString::from("");
assert_eq!(
os.split(b',').collect::<Vec<OsString>>(),
Vec::<OsString>::new()
);
let mut split = os.split(b',');
assert_eq!(split.next(), None);
}
#[cfg(test)]
#[test]
fn os_split_one() {
let os = OsString::from("abc");
assert_eq!(
os.split(b',').collect::<Vec<OsString>>(),
vec![OsString::from("abc")]
);
let mut split = os.split(b',');
assert_eq!(split.next(), Some(OsString::from("abc")));
assert_eq!(split.next(), None);
}
#[cfg(test)]
#[test]
fn os_split_multi() {
let os = OsString::from("a,b,c");
assert_eq!(
os.split(b',').collect::<Vec<OsString>>(),
vec![
OsString::from("a"),
OsString::from("b"),
OsString::from("c"),
]
);
let mut split = os.split(b',');
assert_eq!(split.next(), Some(OsString::from("a")));
assert_eq!(split.next(), Some(OsString::from("b")));
assert_eq!(split.next(), Some(OsString::from("c")));
assert_eq!(split.next(), None);
}
#[cfg(test)]
#[test]
fn os_split_leading() {
let os = OsString::from(",a,b,c");
assert_eq!(
os.split(b',').collect::<Vec<OsString>>(),
vec![
OsString::from(""),
OsString::from("a"),
OsString::from("b"),
OsString::from("c"),
]
);
let mut split = os.split(b',');
assert_eq!(split.next(), Some(OsString::from("")));
assert_eq!(split.next(), Some(OsString::from("a")));
assert_eq!(split.next(), Some(OsString::from("b")));
assert_eq!(split.next(), Some(OsString::from("c")));
assert_eq!(split.next(), None);
}
#[cfg(test)]
#[test]
fn os_strip_none() {
let os = OsString::from("abc");
assert_eq!(os_strip_prefix(os, b'.'), OsString::from("abc"));
}
#[cfg(test)]
#[test]
fn os_strip_left() {
let os = OsString::from(".abc");
assert_eq!(os_strip_prefix(os, b'.'), OsString::from("abc"));
}
#[cfg(test)]
#[test]
fn os_strip_not_right() {
let os = OsString::from("abc.");
assert_eq!(os_strip_prefix(os, b'.'), OsString::from("abc."));
}
#[cfg(test)]
#[test]
fn os_strip_only_left() {
let os = OsString::from(".abc.");
assert_eq!(os_strip_prefix(os, b'.'), OsString::from("abc."));
}
#[cfg(test)]
#[test]
fn os_strip_only_once() {
let os = OsString::from("..abc");
assert_eq!(os_strip_prefix(os, b'.'), OsString::from(".abc"));
}

View File

@ -1,93 +0,0 @@
use std::sync::Arc;
use clap::ArgMatches;
use futures::future::try_join_all;
use ignore_files::IgnoreFile;
use miette::{IntoDiagnostic, Result};
use tracing::{info, trace, warn};
use watchexec_filterer_tagged::{
discover_files_from_environment, Filter, FilterFile, Matcher, Op, Pattern, TaggedFilterer,
};
pub async fn tagged(args: &ArgMatches) -> Result<Arc<TaggedFilterer>> {
let (project_origin, workdir) = super::common::dirs(args).await?;
let vcs_types = super::common::vcs_types(&project_origin).await;
let ignores = super::common::ignores(args, &vcs_types, &project_origin).await;
let filterer = TaggedFilterer::new(project_origin, workdir.clone()).await?;
for ignore in &ignores {
filterer.add_ignore_file(ignore).await?;
}
let mut filter_files = Vec::new();
for path in args.values_of_os("filter-files").unwrap_or_default() {
let file = FilterFile(IgnoreFile {
applies_in: None,
applies_to: None,
path: tokio::fs::canonicalize(path).await.into_diagnostic()?,
});
filter_files.push(file);
}
info!(?filter_files, "resolved command filter files");
if !args.is_present("no-global-filters") {
let (global_filter_files, errors) = discover_files_from_environment().await;
for err in errors {
warn!("while discovering project-local filter files: {}", err);
}
info!(?global_filter_files, "discovered global filter files");
filter_files.extend(global_filter_files);
}
let mut filters = try_join_all(
filter_files
.into_iter()
.map(|file| async move { file.load().await }),
)
.await?
.into_iter()
.flatten()
.collect::<Vec<_>>();
for filter in args.values_of("filter").unwrap_or_default() {
let mut filter: Filter = filter.parse()?;
filter.in_path = Some(workdir.clone());
filters.push(filter);
}
if !args.is_present("no-default-ignore") {
filters.extend([
Filter::from_glob_ignore(None, ".DS_Store/"),
Filter::from_glob_ignore(None, "*.py[co]"),
Filter::from_glob_ignore(None, "#*#"),
Filter::from_glob_ignore(None, ".#*"),
Filter::from_glob_ignore(None, ".*.kate-swp"),
Filter::from_glob_ignore(None, ".*.sw?"),
Filter::from_glob_ignore(None, ".*.sw?x"),
Filter::from_glob_ignore(None, ".bzr"),
Filter::from_glob_ignore(None, "_darcs"),
Filter::from_glob_ignore(None, ".fossil-settings"),
Filter::from_glob_ignore(None, ".git"),
Filter::from_glob_ignore(None, ".hg"),
Filter::from_glob_ignore(None, ".pijul"),
Filter::from_glob_ignore(None, ".svn"),
]);
}
if args.is_present("no-meta") {
filters.push(Filter {
in_path: Some(workdir.clone()),
on: Matcher::FileEventKind,
op: Op::NotGlob,
pat: Pattern::Glob("Modify(Metadata(*))".to_string()),
negate: false,
});
}
trace!(?filters, "all filters");
filterer.add_filters(&filters).await?;
info!(filters=%filters.len(), "initialising Tagged filterer");
Ok(filterer)
}

View File

@ -1,20 +1,27 @@
#![deny(rust_2018_idioms)]
#![allow(clippy::missing_const_for_fn, clippy::future_not_send)]
use std::{env::var, fs::File, sync::Mutex};
use std::{env::var, fs::File, io::Write, process::Stdio, sync::Mutex};
use miette::{IntoDiagnostic, Result};
use args::{Args, ShellCompletion};
use clap::CommandFactory;
use clap_complete::{Generator, Shell};
use clap_mangen::Man;
use command_group::AsyncCommandGroup;
use is_terminal::IsTerminal;
use miette::{Context, IntoDiagnostic, Result};
use tokio::{fs::metadata, io::AsyncWriteExt, process::Command};
use tracing::{debug, info, warn};
use watchexec::{
event::{Event, Priority},
Watchexec,
};
mod args;
pub mod args;
mod config;
mod filterer;
pub async fn run() -> Result<()> {
async fn init() -> Result<Args> {
let mut log_on = false;
#[cfg(feature = "dev-console")]
@ -38,19 +45,29 @@ pub async fn run() -> Result<()> {
}
}
let tagged_filterer = var("WATCHEXEC_FILTERER")
.map(|v| v == "tagged")
.unwrap_or(false);
let args = args::get_args(tagged_filterer)?;
let verbosity = args.occurrences_of("verbose");
let args = args::get_args();
let verbosity = args.verbose.unwrap_or(0);
if log_on {
warn!("ignoring logging options from args");
} else if verbosity > 0 {
let log_file = if let Some(file) = args.value_of_os("log-file") {
let log_file = if let Some(file) = &args.log_file {
let info = metadata(&file)
.await
.into_diagnostic()
.wrap_err("Opening log file failed")?;
let path = if info.is_dir() {
let filename = format!(
"watchexec.{}.log",
chrono::Utc::now().format("%Y-%m-%dT%H-%M-%SZ")
);
file.join(filename)
} else {
file.to_owned()
};
// TODO: use tracing-appender instead
Some(File::create(file).into_diagnostic()?)
Some(File::create(path).into_diagnostic()?)
} else {
None
};
@ -80,22 +97,20 @@ pub async fn run() -> Result<()> {
}
}
Ok(args)
}
async fn run_watchexec(args: Args) -> Result<()> {
info!(version=%env!("CARGO_PKG_VERSION"), "constructing Watchexec from CLI");
debug!(?args, "arguments");
let init = config::init(&args);
let mut runtime = config::runtime(&args)?;
runtime.filterer(if tagged_filterer {
eprintln!("!!! EXPERIMENTAL: using tagged filterer !!!");
filterer::tagged(&args).await?
} else {
filterer::globset(&args).await?
});
runtime.filterer(filterer::globset(&args).await?);
info!("initialising Watchexec runtime");
let wx = Watchexec::new(init, runtime)?;
if !args.is_present("postpone") {
if !args.postpone {
debug!("kicking off with empty event");
wx.send_event(Event::default(), Priority::Urgent).await?;
}
@ -106,3 +121,82 @@ pub async fn run() -> Result<()> {
Ok(())
}
async fn run_manpage(_args: Args) -> Result<()> {
info!(version=%env!("CARGO_PKG_VERSION"), "constructing manpage");
let man = Man::new(Args::command().long_version(None));
let mut buffer: Vec<u8> = Default::default();
man.render(&mut buffer).into_diagnostic()?;
if std::io::stdout().is_terminal() && which::which("man").is_ok() {
let mut child = Command::new("man")
.arg("-l")
.arg("-")
.stdin(Stdio::piped())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.group()
.kill_on_drop(true)
.spawn()
.into_diagnostic()?;
child
.inner()
.stdin
.as_mut()
.unwrap()
.write_all(&buffer)
.await
.into_diagnostic()?;
if let Some(code) = child
.wait()
.await
.into_diagnostic()?
.code()
.and_then(|code| if code == 0 { None } else { Some(code) })
{
return Err(miette::miette!("Exited with status code {}", code));
}
} else {
std::io::stdout()
.lock()
.write_all(&buffer)
.into_diagnostic()?;
}
Ok(())
}
async fn run_completions(shell: ShellCompletion) -> Result<()> {
info!(version=%env!("CARGO_PKG_VERSION"), "constructing completions");
fn generate(generator: impl Generator) {
let mut cmd = Args::command();
clap_complete::generate(generator, &mut cmd, "watchexec", &mut std::io::stdout());
}
match shell {
ShellCompletion::Bash => generate(Shell::Bash),
ShellCompletion::Elvish => generate(Shell::Elvish),
ShellCompletion::Fish => generate(Shell::Fish),
ShellCompletion::Nu => generate(clap_complete_nushell::Nushell),
ShellCompletion::Powershell => generate(Shell::PowerShell),
ShellCompletion::Zsh => generate(Shell::Zsh),
}
Ok(())
}
pub async fn run() -> Result<()> {
let args = init().await?;
debug!(?args, "arguments");
if args.manpage {
run_manpage(args).await
} else if let Some(shell) = args.completions {
run_completions(shell).await
} else {
run_watchexec(args).await
}
}

View File

@ -12,13 +12,6 @@ use tracing::{trace, trace_span};
use crate::{IgnoreFile, IgnoreFilter};
/// The separator for paths used in environment variables.
#[cfg(unix)]
const PATH_SEPARATOR: &str = ":";
/// The separator for paths used in environment variables.
#[cfg(not(unix))]
const PATH_SEPARATOR: &str = ";";
/// Finds all ignore files in the given directory and subdirectories.
///
/// This considers:
@ -184,14 +177,12 @@ pub async fn from_origin(path: impl AsRef<Path> + Send) -> (Vec<IgnoreFile>, Vec
/// Finds all ignore files that apply to the current runtime.
///
/// Takes an optional `appname` for the calling application for looking at an environment variable
/// and an application-specific config location.
/// Takes an optional `appname` for the calling application for application-specific config files.
///
/// This considers:
/// - User-specific git ignore files (e.g. `~/.gitignore`)
/// - Git configurable ignore files (e.g. with `core.excludesFile` in system or user config)
/// - `$XDG_CONFIG_HOME/{appname}/ignore`, as well as other locations (APPDATA on Windows…)
/// - Files from the `{APPNAME}_IGNORE_FILES` environment variable (separated the same was as `PATH`)
///
/// All errors (permissions, etc) are collected and returned alongside the ignore files: you may
/// want to show them to the user while still using whatever ignores were successfully found. Errors
@ -205,15 +196,6 @@ pub async fn from_environment(appname: Option<&str>) -> (Vec<IgnoreFile>, Vec<Er
let mut files = Vec::new();
let mut errors = Vec::new();
if let Some(name) = appname {
for path in env::var(format!("{}_IGNORE_FILES", name.to_uppercase()))
.unwrap_or_default()
.split(PATH_SEPARATOR)
{
discover_file(&mut files, &mut errors, None, None, PathBuf::from(path)).await;
}
}
let mut found_git_global = false;
match File::from_environment_overrides().map(|mut env| {
File::from_globals().map(move |glo| {

View File

@ -56,7 +56,7 @@ async fn main() -> Result<()> {
eprintln!("Switching to polling for funsies");
config.file_watcher(Watcher::Poll(Duration::from_millis(50)));
w.reconfigure(config)?;
} else if (action.events.iter().flat_map(Event::paths).next().is_some()) {
} else if action.events.iter().flat_map(Event::paths).next().is_some() {
action.outcome(Outcome::if_running(
Outcome::both(Outcome::Stop, Outcome::Start),
Outcome::Start,

View File

@ -104,10 +104,14 @@ pub async fn worker(
set.push(event);
let elapsed = last.elapsed();
if elapsed < working.borrow().throttle {
trace!(?elapsed, "still within throttle window, cycling");
continue;
if priority == Priority::Urgent {
trace!("urgent event, by-passing throttle");
} else {
let elapsed = last.elapsed();
if elapsed < working.borrow().throttle {
trace!(?elapsed, "still within throttle window, cycling");
continue;
}
}
}
}

View File

@ -173,11 +173,31 @@ impl From<i32> for SubSignal {
}
}
impl FromStr for SubSignal {
type Err = SignalParseError;
impl SubSignal {
/// Parse the input as a unix signal.
///
/// This parses the input as a signal name, or a signal number, in a case-insensitive manner.
/// It supports integers, the short name of the signal (like `INT`, `HUP`, `USR1`, etc), and
/// the long name of the signal (like `SIGINT`, `SIGHUP`, `SIGUSR1`, etc).
///
/// Note that this is entirely accurate only when used on unix targets; on other targets it
/// falls back to a hardcoded approximation instead of looking up signal tables (via [`nix`]).
///
/// ```
/// # use watchexec::signal::process::SubSignal;
/// assert_eq!(SubSignal::Hangup, SubSignal::from_unix_str("hup").unwrap());
/// assert_eq!(SubSignal::Interrupt, SubSignal::from_unix_str("SIGINT").unwrap());
/// assert_eq!(SubSignal::ForceStop, SubSignal::from_unix_str("Kill").unwrap());
/// ```
///
/// Using [`FromStr`] is recommended for practical use, as it will also parse Windows control
/// events, see [`SubSignal::from_windows_str`].
pub fn from_unix_str(s: &str) -> Result<Self, SignalParseError> {
Self::from_unix_str_impl(s)
}
#[cfg(unix)]
fn from_str(s: &str) -> Result<Self, Self::Err> {
fn from_unix_str_impl(s: &str) -> Result<Self, SignalParseError> {
if let Ok(sig) = i32::from_str(s) {
if let Ok(sig) = NixSignal::try_from(sig) {
return Ok(Self::from_nix(sig));
@ -193,8 +213,45 @@ impl FromStr for SubSignal {
Err(SignalParseError::new(s, "unsupported signal"))
}
#[cfg(windows)]
fn from_str(s: &str) -> Result<Self, Self::Err> {
#[cfg(not(unix))]
fn from_unix_str_impl(s: &str) -> Result<Self, SignalParseError> {
match s.to_ascii_uppercase().as_str() {
"KILL" | "SIGKILL" | "9" => Ok(Self::ForceStop),
"HUP" | "SIGHUP" | "1" => Ok(Self::Hangup),
"INT" | "SIGINT" | "2" => Ok(Self::Interrupt),
"QUIT" | "SIGQUIT" | "3" => Ok(Self::Quit),
"TERM" | "SIGTERM" | "15" => Ok(Self::Terminate),
"USR1" | "SIGUSR1" | "10" => Ok(Self::User1),
"USR2" | "SIGUSR2" | "12" => Ok(Self::User2),
number => match i32::from_str(number) {
Ok(int) => Ok(Self::Custom(int)),
Err(_) => Err(SignalParseError::new(s, "unsupported signal")),
},
}
}
/// Parse the input as a windows control event.
///
/// This parses the input as a control event name, in a case-insensitive manner.
///
/// The names matched are mostly made up as there's no standard for them, but should be familiar
/// to Windows users. They are mapped to the corresponding unix concepts as follows:
///
/// - `CTRL-CLOSE`, `CTRL+CLOSE`, or `CLOSE` for a hangup
/// - `CTRL-BREAK`, `CTRL+BREAK`, or `BREAK` for a terminate
/// - `CTRL-C`, `CTRL+C`, or `C` for an interrupt
/// - `STOP`, `FORCE-STOP` for a forced stop. This is also mapped to `KILL` and `SIGKILL`.
///
/// ```
/// # use watchexec::signal::process::SubSignal;
/// assert_eq!(SubSignal::Hangup, SubSignal::from_windows_str("ctrl+close").unwrap());
/// assert_eq!(SubSignal::Interrupt, SubSignal::from_windows_str("C").unwrap());
/// assert_eq!(SubSignal::ForceStop, SubSignal::from_windows_str("Stop").unwrap());
/// ```
///
/// Using [`FromStr`] is recommended for practical use, as it will fall back to parsing as a
/// unix signal, which can be helpful for portability.
pub fn from_windows_str(s: &str) -> Result<Self, SignalParseError> {
match s.to_ascii_uppercase().as_str() {
"CTRL-CLOSE" | "CTRL+CLOSE" | "CLOSE" => Ok(Self::Hangup),
"CTRL-BREAK" | "CTRL+BREAK" | "BREAK" => Ok(Self::Terminate),
@ -203,9 +260,12 @@ impl FromStr for SubSignal {
_ => Err(SignalParseError::new(s, "unknown control name")),
}
}
}
impl FromStr for SubSignal {
type Err = SignalParseError;
#[cfg(not(any(unix, windows)))]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Err(SignalParseError::new(s, "no signals supported"))
Self::from_windows_str(s).or_else(|err| Self::from_unix_str(s).map_err(|_| err))
}
}

View File

@ -1,425 +1,374 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "WATCHEXEC" "1" "June 2022" "" ""
.
.SH "NAME"
\fBwatchexec\fR \- execute commands when watched files change
.
.SH "SYNOPSIS"
watchexec [OPTIONS] [\-\-] \fIcommand\fR [\fIargument\fR\.\.\.] watchexec \-V|\-\-version watchexec [\-h|\-\-help]
.
.SH "DESCRIPTION"
Recursively monitors the current directory for changes, executing the command when a filesystem change is detected\. By default, watchexec uses efficient kernel\-level mechanisms to watch for changes\.
.
.P
At startup, the specified \fIcommand\fR (passing any supplied \fIargument\fRs) is run once, and watchexec begins monitoring for changes\.
.
.SH "OPTIONS"
.
.SS "Command options"
.
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.TH watchexec 1 "watchexec 1.21.1"
.SH NAME
watchexec \- Execute commands when watched files change
.SH SYNOPSIS
\fBwatchexec\fR [\fB\-w\fR|\fB\-\-watch\fR] [\fB\-c\fR|\fB\-\-clear\fR] [\fB\-o\fR|\fB\-\-on\-busy\-update\fR] [\fB\-r\fR|\fB\-\-restart\fR] [\fB\-s\fR|\fB\-\-signal\fR] [\fB\-\-stop\-signal\fR] [\fB\-\-stop\-timeout\fR] [\fB\-\-debounce\fR] [\fB\-\-stdin\-quit\fR] [\fB\-\-no\-vcs\-ignore\fR] [\fB\-\-no\-project\-ignore\fR] [\fB\-\-no\-global\-ignore\fR] [\fB\-\-no\-default\-ignore\fR] [\fB\-p\fR|\fB\-\-postpone\fR] [\fB\-\-delay\-run\fR] [\fB\-\-poll\fR] [\fB\-\-shell\fR] [\fB\-n \fR] [\fB\-\-no\-environment\fR] [\fB\-E\fR|\fB\-\-env\fR] [\fB\-\-no\-process\-group\fR] [\fB\-N\fR|\fB\-\-notify\fR] [\fB\-\-project\-origin\fR] [\fB\-\-workdir\fR] [\fB\-e\fR|\fB\-\-exts\fR] [\fB\-f\fR|\fB\-\-filter\fR] [\fB\-\-filter\-file\fR] [\fB\-i\fR|\fB\-\-ignore\fR] [\fB\-\-ignore\-file\fR] [\fB\-\-fs\-events\fR] [\fB\-\-no\-meta\fR] [\fB\-\-print\-events\fR] [\fB\-v\fR|\fB\-\-verbose\fR]... [\fB\-\-log\-file\fR] [\fB\-\-manpage\fR] [\fB\-\-completions\fR] [\fB\-h\fR|\fB\-\-help\fR] [\fB\-V\fR|\fB\-\-version\fR] [\fICOMMAND\fR]
.SH DESCRIPTION
Execute commands when watched files change.
.PP
Recursively monitors the current directory for changes, executing the command when a filesystem change is detected (among other event sources). By default, watchexec uses efficient kernel\-level mechanisms to watch for changes.
.PP
At startup, the specified <COMMAND> is run once, and watchexec begins monitoring for changes.
.PP
Examples:
.PP
Rebuild a project when source files change:
.PP
$ watchexec make
.PP
Watch all HTML, CSS, and JavaScript files for changes:
.PP
$ watchexec \-e html,css,js make
.PP
Run tests when source files change, clearing the screen each time:
.PP
$ watchexec \-c make test
.PP
Launch and restart a node.js server:
.PP
$ watchexec \-r node app.js
.PP
Watch lib and src directories for changes, rebuilding each time:
.PP
$ watchexec \-w lib \-w src make
.SH OPTIONS
.TP
\fIcommand\fR
Command to run when watched files are modified, and at startup, unless \fB\-\-postpone\fR is specified\. All \fIargument\fRs are passed to \fIcommand\fR\. If you pass flags to the command, you should separate it with \fB\-\-\fR, for example: \fBwatchexec \-w src \-\- rsync \-a src dest\fR\.
.
.P
Behaviour depends on the value of \fB\-\-shell\fR: for all except \fBnone\fR, every part of \fIcommand\fR is joined together into one string with a single ascii space character, and given to the shell as described\. For \fBnone\fR, each distinct element of \fIcommand\fR is passed as per the execvp(3) convention: first argument is the program, as a file or searched in the \fBPATH\fR, rest are arguments\.
.
\fB\-w\fR, \fB\-\-watch\fR=\fIPATH\fR
Watch a specific file or directory
By default, Watchexec watches the current directory.
When watching a single file, it\*(Aqs often better to watch the containing directory instead, and filter on the filename. Some editors may replace the file with a new one when saving, and some platforms may not detect that or further changes.
Upon starting, Watchexec resolves a "project origin" from the watched paths. See the help for \*(Aq\-\-project\-origin\*(Aq for more information.
This option can be specified multiple times to watch multiple files or directories.
.TP
\fB\-E\fR, \fB\-\-env\fR \fIkey=value pair\fR
Set additional environment variables on the command (not to Watchexec itself)\. Can be given multiple times (one per variable to set)\.
.
\fB\-c\fR, \fB\-\-clear\fR=\fIMODE\fR
Clear screen before running command
If this doesn\*(Aqt completely clear the screen, try \*(Aq\-\-clear=reset\*(Aq.
.TP
\fB\-n\fR
Shorthand for \fB\-\-shell=none\fR\.
.
.TP
\fB\-\-no\-process\-group\fR
Do not use a process group when running \fIcommand\fR\.
.
.TP
\fB\-\-no\-environment\fR
Do not set WATCHEXEC\fI*\fRPATH environment variables for the command\.
.
.TP
\fB\-\-no\-shell\fR
Deprecated\. Alias for \fB\-\-shell=none\fR\.
.
.TP
\fB\-\-shell\fR \fIshell\fR
Change the shell used to run the command\. Set to \fBnone\fR to run the command directly without a shell\.
.
.P
The special value \fBpowershell\fR will use Microsoft Powershell\'s calling convention, otherwise \fBSHELL \-c COMMAND\fR\.
.
.P
On Windows, the additional \fBcmd\fR special value uses CMD\.EXE calling convention\.
.
.P
The \fBnone\fR value is especially useful in combination with \fB\-\-signal\fR, as the signal is then sent directly to the running command\. While \fB\-\-shell=none\fR is a little more performant than the default, it prevents using shell\-features like pipes and redirects\.
.
.P
If not a special value, the string provided may contain arguments to the shell as long as that is kept simple: the string is split along whitespace, and used as per execvp(3): first is shell program, rest are arguments to the shell, then \fB\-c\fR is added, and finally the \fBCOMMAND\fR\.
.
.P
See the \fIEXAMPLES\fR for uses of each of these\.
.
.TP
\fB\-\-workdir <path>\fR
Set the working directory of the command (not of Watchexec itself!)\. By default not set, and inherited from the Watchexec instance as is usual\.
.
.SS "Filtering options"
.
.TP
\fB\-e\fR, \fB\-\-exts\fR \fIextensions\fR
Comma\-separated list of file extensions to filter by\. Leading dots (\.rs) are allowed\. (This is a shorthand for \fB\-f\fR)\.
.
.TP
\fB\-f\fR, \fB\-\-filter\fR \fIpattern\fR
Ignores modifications from paths that do not match \fIpattern\fR\. This option can be specified multiple times, where a match on any given pattern causes the path to trigger \fIcommand\fR\.
.
.TP
\fB\-i\fR, \fB\-\-ignore\fR \fIpattern\fR
Ignores modifications from paths that match \fIpattern\fR\. This option can be specified multiple times, and a match on any pattern causes the path to be ignored\.
.
.TP
\fB\-\-no\-default\-ignore\fR
Skip default ignore statements\. By default, watchexec ignores common temporary files for you, for example \fB*\.swp\fR, \fB*\.pyc\fR, and \fB\.DS_Store\fR, as well as the data directories of known VCS: \fB\.bzr\fR, \fB_darcs\fR, \fB\.fossil\-settings\fR, \fB\.git\fR, \fB\.hg\fR, \fB\.pijul\fR, and \fB\.svn\fR\.
.
.TP
\fB\-\-no\-global\-ignore\fR
Skip loading of global ignore files\. By default, watchexec loads $HOME/\.gitignore and other such global files and uses them to filter change events\.
.
.TP
\fB\-\-no\-meta\fR
Ignore metadata changes\.
.
.TP
\fB\-\-no\-project\-ignore\fR, \fB\-\-no\-ignore\fR (deprecated alias)
Skip loading of project\-local ignore files (include VCS ignore files)\. By default, watchexec loads \.ignore, \.gitignore, \.hgignore, and other such files in the current directory (or child directories as applicable) and uses them to filter change events\.
.
.P
The \fB\-\-no\-ignore\fR alias will be replaced by a new option in 2\.0\.0, beware!
.
.TP
\fB\-\-no\-vcs\-ignore\fR
Skip loading of version control system (VCS) ignore files\. By default, watchexec loads \.gitignore, \.hgignore, and other such files in the current directory (or child directories as applicable) and uses them to filter change events\.
.
.TP
\fB\-\-project\-origin\fR \fIpath\fR
Overrides the project origin, where ignore files are resolved from (see \fIPATHS\fR section below)\.
.
.TP
\fB\-w\fR, \fB\-\-watch\fR \fIpath\fR
Monitor a specific path for changes\. By default, the current working directory is watched\. This may be specified multiple times, where a change in any watched directory (and subdirectories) causes \fIcommand\fR to be executed\.
.
.SS "Behaviour options"
.
.TP
\fB\-d\fR, \fB\-\-debounce\fR
Set the timeout between detected change and command execution, to avoid restarting too frequently when there are many events; defaults to 100ms\.
.
.TP
\fB\-\-force\-poll\fR \fIinterval\fR
Poll for changes every \fIinterval\fR ms instead of using system\-specific notification mechanisms (such as inotify)\. This is useful when you are monitoring NFS shares\.
.
.TP
\fB\-p\fR, \fB\-\-postpone\fR
Postpone execution of \fIcommand\fR until the first file modification is detected\.
.
\fB\-o\fR, \fB\-\-on\-busy\-update\fR=\fIMODE\fR
What to do when receiving events while the command is running
Default is to \*(Aqqueue\*(Aq up events and run the command once again when the previous run has finished. You can also use \*(Aqdo\-nothing\*(Aq, which ignores events while the command is running and may be useful to avoid spurious changes made by that command, or \*(Aqrestart\*(Aq, which terminates the running command and starts a new one. Finally, there\*(Aqs \*(Aqsignal\*(Aq, which only sends a signal; this can be useful with programs that can reload their configuration without a full restart.
The signal can be specified with the \*(Aq\-\-signal\*(Aq option.
Note that this option is scheduled to change its default to \*(Aqdo\-nothing\*(Aq in the next major release. File an issue if you have any concerns.
.TP
\fB\-r\fR, \fB\-\-restart\fR
Terminates the command if it is still running when subsequent file modifications are detected\. By default, sends \fBSIGTERM\fR; use \fB\-\-signal\fR to change that\.
.
.TP
\fB\-s\fR, \fB\-\-signal\fR
Sends the specified signal (e\.g\. \fBSIGKILL\fR) to the command\. Defaults to \fBSIGTERM\fR\.
.
.TP
\fB\-W\fR, \fB\-\-watch\-when\-idle\fR
Ignore events while the process is still running\. This is distinct from \fB\-\-restart\fR in that with this option, events received while the command is running will not trigger a new run immediately after the current command is done\.
.
.P
This behaviour will become the default in v2\.0\.
.
.SS "Output options"
.
.TP
\fB\-c\fR, \fB\-\-clear\fR
Clears the screen before executing \fIcommand\fR\.
.
.TP
\fB\-N\fR, \fB\-\-notify\fR
Sends desktop notifications on command start and command end\.
.
.SS "Debugging options"
.
.TP
\fB\-\-print\-events\fR, \fB\-\-changes\-only\fR (deprecated alias)
Prints the events (changed paths, etc) that have triggered an action to STDERR\.
.
.TP
\fB\-v\fR, \fB\-\-verbose\fR, \fB\-vv\fR, etc
Prints diagnostic and debugging messages to STDERR\. Increase the amount of \fBv\fRs to get progressively more output: for bug reports use \fBthree\fR, and for deep debugging \fBfour\fR can be helpful\.
.
.TP
\fB\-\-log\-file\fR \fIpath\fR
Writes diagnostic and debugging messages (from the \fB\-v\fR options) to file instead of STDERR, in JSON format\. This is preferrable for reporting bugs\. Be careful \fBnot\fR to write to a file within the purview of Watchexec to avoid recursion!
.
.TP
\fB\-V\fR, \fB\-\-version\fR
Print the version of watchexec\.
.
.TP
\fB\-h\fR, \fB\-\-help\fR
Print a help message\.
.
.SH "PATHS"
By default, Watchexec watches the current directory\. This can be changed with the \fB\-\-watch\fR option, which can be passed multiple times\.
.
.P
Upon starting, Watchexec resolves a "project origin" from the watched paths\. To do so, it recurses up every parent directory from each watched path, looking for file and directory patterns which indicate a project origin among many different software systems, such as a Git repo, Cargo crate, licensing files, readmes, workspace configuration, etc\. For the full current list, consult the source at \fBlib/src/project\.rs\fR\.
.
.P
Once it has a list of "potential project origins", it resolves the common prefix they all have, and uses this as the overall project origin\. Note that the home directory is excluded from potential origins unless it\'s explicitly requested as a watched path\.
.
.P
The overall project origin is used to find and resolve ignore files, such that in most cases it acts as one would expect for a tool that runs anywhere inside a project\.
.
.P
For this reason, it is not recommended to use Watchexec for watching disparate folders in a filesystem, where those would resolve to a too\-broad project origin\.
.
.P
The project origin can be overridden with the \fB\-\-project\-origin\fR option\.
.
.SH "ENVIRONMENT"
In variables that contain lists of paths, the separator is as for the \fB$PATH\fR environment variable (a colon, or semicolon on Windows)\.
.
.SS "Set on child processes"
Processes started by watchexec have environment variables set describing the changes observed\.
.
.P
\fB$WATCHEXEC_COMMON_PATH\fR is set to the longest common path of all of the below variables, and so should be prepended to each path to obtain the full/real path\. Then:
.
.IP "\(bu" 4
\fB$WATCHEXEC_CREATED_PATH\fR is set when files/folders were created
.
.IP "\(bu" 4
\fB$WATCHEXEC_REMOVED_PATH\fR is set when files/folders were removed
.
.IP "\(bu" 4
\fB$WATCHEXEC_RENAMED_PATH\fR is set when files/folders were renamed
.
.IP "\(bu" 4
\fB$WATCHEXEC_WRITTEN_PATH\fR is set when files/folders were modified
.
.IP "\(bu" 4
\fB$WATCHEXEC_META_CHANGED_PATH\fR is set when files/folders\' metadata were modified
.
.IP "\(bu" 4
\fB$WATCHEXEC_OTHERWISE_CHANGED_PATH\fR is set for every other kind of pathed event
.
.IP "" 0
.
.P
These variables may contain multiple paths: these are separated by the platform\'s path separator, as with the \fBPATH\fR system environment variable\. On Unix that is \fB:\fR, and on Windows \fB;\fR\. Within each variable, paths are deduplicated and sorted in binary order (i\.e\. neither Unicode nor locale aware)\.
.
.P
One thing to take care of is assuming inherent behaviour where there is only chance\. Notably, it could appear as if the \fBRENAMED\fR variable contains both the original and the new path being renamed\. In previous versions, it would even appear on some platforms as if the original always came before the new\. However, none of this was true\. It\'s impossible to reliably and portably know which changed path is the old or new, "half" renames may appear (only the original, only the new), "unknown" renames may appear (change was a rename, but whether it was the old or new isn\'t known), rename events might split across two debouncing boundaries, and so on\.
.
.P
This variable group can be disabled or limited with \fB\-\-no\-environment\fR (doesn\'t set any of these variables) and \fB\-\-no\-meta\fR (ignores metadata changes)\.
.
.SS "Read upon startup"
.
.IP "\(bu" 4
\fB$WATCHEXEC_FILTERER\fR: select the filterer implementation: \fBglobset\fR (default), or \fBtagged\fR (experimental)\.
.
.IP "\(bu" 4
\fB$WATCHEXEC_IGNORE_FILES\fR: a list of paths to additional ignore files to be loaded\.
.
.IP "\(bu" 4
\fB$WATCHEXEC_FILTER_FILES\fR: a list of paths to additional "Tagged" filter files to be loaded (when enabled)\.
.
.IP "\(bu" 4
\fB$RUST_LOG\fR: use for advanced verbose logging configuration\. Refer to tracing\-subscriber for documentation\.
.
.IP "" 0
.
.SH "FILES"
.
.SS "Supported project ignore files"
.
.IP "\(bu" 4
Git: \fB\.gitignore\fR at project root and child directories, \fB\.git/info/exclude\fR, and the file pointed to by \fBcore\.excludesFile\fR in \fB\.git/config\fR\.
.
.IP "\(bu" 4
Mercurial: \fB\.hgignore\fR at project root and child directories\.
.
.IP "\(bu" 4
Bazaar: \fB\.bzrignore\fR at project root\.
.
.IP "\(bu" 4
Darcs: \fB_darcs/prefs/boring\fR
.
.IP "\(bu" 4
Fossil: \fB\.fossil\-settings/ignore\-glob\fR
.
.IP "\(bu" 4
Ripgrep/Watchexec/generic: \fB\.ignore\fR at project root and child directories\.
.
.IP "" 0
.
.P
Note that VCS ignore files (Git, Mercurial, Bazaar, Darcs, Fossil) are only used if the corresponding VCS is discovered to be in use for the project/origin\. For example, a \fB\.bzrignore\fR in a Git repository will be discarded\.
.
.SS "Supported global ignore files"
.
.IP "\(bu" 4
Git (if core\.excludesFile is set): the file at that path
.
.IP "\(bu" 4
Git (otherwise): the first found of \fB$XDG_CONFIG_HOME/git/ignore\fR, \fB%APPDATA%/\.gitignore\fR, \fB%USERPROFILE%/\.gitignore\fR, \fB$HOME/\.config/git/ignore\fR, \fB$HOME/\.gitignore\fR\.
.
.IP "\(bu" 4
Bazaar: the first found of \fB%APPDATA%/Bazzar/2\.0/ignore\fR, \fB$HOME/\.bazaar/ignore\fR\.
.
.IP "\(bu" 4
Watchexec: the first found of \fB$XDG_CONFIG_HOME/watchexec/ignore\fR, \fB%APPDATA%/watchexec/ignore\fR, \fB%USERPROFILE%/\.watchexec/ignore\fR, \fB$HOME/\.watchexec/ignore\fR\.
.
.IP "" 0
.
.P
Note that like for project files, Git and Bazaar global files will only be used for the corresponding VCS as used in the project\.
.
.SH "EXAMPLES"
Rebuild a project when source files change:
.
.IP "" 4
.
.nf
Restart the process if it\*(Aqs still running
$ watchexec make
.
.fi
.
.IP "" 0
.
.P
Watch all HTML, CSS, and JavaScript files for changes:
.
.IP "" 4
.
.nf
This is a shorthand for \*(Aq\-\-on\-busy\-update=restart\*(Aq.
.TP
\fB\-s\fR, \fB\-\-signal\fR=\fISIGNAL\fR
Send a signal to the process when it\*(Aqs still running
$ watchexec \-e html,css,js make
.
.fi
.
.IP "" 0
.
.P
Run tests when source files change, clearing the screen each time:
.
.IP "" 4
.
.nf
Specify a signal to send to the process when it\*(Aqs still running. This implies \*(Aq\-\-on\-busy\-update=signal\*(Aq; otherwise the signal used when that mode is \*(Aqrestart\*(Aq is controlled by \*(Aq\-\-stop\-signal\*(Aq.
$ watchexec \-c make test
.
.fi
.
.IP "" 0
.
.P
Launch and restart a node\.js server:
.
.IP "" 4
.
.nf
See the long documentation for \*(Aq\-\-stop\-signal\*(Aq for syntax.
.TP
\fB\-\-stop\-signal\fR=\fISIGNAL\fR
Signal to send to stop the command
$ watchexec \-r node app\.js
.
.fi
.
.IP "" 0
.
.P
Watch lib and src directories for changes, rebuilding each time:
.
.IP "" 4
.
.nf
This is used by \*(Aqrestart\*(Aq and \*(Aqsignal\*(Aq modes of \*(Aq\-\-on\-busy\-update\*(Aq (unless \*(Aq\-\-signal\*(Aq is provided). The restart behaviour is to send the signal, wait for the command to exit, and if it hasn\*(Aqt exited after some time (see \*(Aq\-\-timeout\-stop\*(Aq), forcefully terminate it.
The default on unix is "SIGTERM".
Input is parsed as a full signal name (like "SIGTERM"), a short signal name (like "TERM"), or a signal number (like "15"). All input is case\-insensitive.
On Windows this option is technically supported but only supports the "KILL" event, as Watchexec cannot yet deliver other events. Windows doesn\*(Aqt have signals as such; instead it has termination (here called "KILL" or "STOP") and "CTRL+C", "CTRL+BREAK", and "CTRL+CLOSE" events. For portability the unix signals "SIGKILL", "SIGINT", "SIGTERM", and "SIGHUP" are respectively mapped to these.
.TP
\fB\-\-stop\-timeout\fR=\fITIMEOUT\fR
Time to wait for the command to exit gracefully
This is used by the \*(Aqrestart\*(Aq mode of \*(Aq\-\-on\-busy\-update\*(Aq. After the graceful stop signal is sent, Watchexec will wait for the command to exit. If it hasn\*(Aqt exited after this time, it is forcefully terminated.
Takes a unit\-less value in seconds, or a time span value such as "5min 20s".
The default is 60 seconds. Set to 0 to immediately force\-kill the command.
.TP
\fB\-\-debounce\fR=\fITIMEOUT\fR
Time to wait for new events before taking action
When an event is received, Watchexec will wait for up to this amount of time before handling it (such as running the command). This is essential as what you might perceive as a single change may actually emit many events, and without this behaviour, Watchexec would run much too often. Additionally, it\*(Aqs not infrequent that file writes are not atomic, and each write may emit an event, so this is a good way to avoid running a command while a file is partially written.
An alternative use is to set a high value (like "30min" or longer), to save power or bandwidth on intensive tasks, like an ad\-hoc backup script. In those use cases, note that every accumulated event will build up in memory.
Takes a unit\-less value in milliseconds, or a time span value such as "5sec 20ms".
The default is 50 milliseconds. Setting to 0 is highly discouraged.
.TP
\fB\-\-stdin\-quit\fR
Exit when stdin closes
This watches the stdin file descriptor for EOF, and exits Watchexec gracefully when it is closed. This is used by some process managers to avoid leaving zombie processes around.
.TP
\fB\-\-no\-vcs\-ignore\fR
Don\*(Aqt load gitignores
Among other VCS exclude files, like for Mercurial, Subversion, Bazaar, DARCS, Fossil. Note that Watchexec will detect which of these is in use, if any, and only load the relevant files. Both global (like \*(Aq~/.gitignore\*(Aq) and local (like \*(Aq.gitignore\*(Aq) files are considered.
This option is useful if you want to watch files that are ignored by Git.
.TP
\fB\-\-no\-project\-ignore\fR
Don\*(Aqt load project\-local ignores
This disables loading of project\-local ignore files, like \*(Aq.gitignore\*(Aq or \*(Aq.ignore\*(Aq in the
watched project. This is contrasted with \*(Aq\-\-no\-vcs\-ignore\*(Aq, which disables loading of Git
and other VCS ignore files, and with \*(Aq\-\-no\-global\-ignore\*(Aq, which disables loading of global
or user ignore files, like \*(Aq~/.gitignore\*(Aq or \*(Aq~/.config/watchexec/ignore\*(Aq.
Supported project ignore files:
\- Git: .gitignore at project root and child directories, .git/info/exclude, and the file pointed to by `core.excludesFile` in .git/config.
\- Mercurial: .hgignore at project root and child directories.
\- Bazaar: .bzrignore at project root.
\- Darcs: _darcs/prefs/boring
\- Fossil: .fossil\-settings/ignore\-glob
\- Ripgrep/Watchexec/generic: .ignore at project root and child directories.
VCS ignore files (Git, Mercurial, Bazaar, Darcs, Fossil) are only used if the corresponding
VCS is discovered to be in use for the project/origin. For example, a .bzrignore in a Git
repository will be discarded.
Note that this was previously called \*(Aq\-\-no\-ignore\*(Aq, but that\*(Aqs now deprecated and its use is
discouraged, as it may be repurposed in the future.
.TP
\fB\-\-no\-global\-ignore\fR
Don\*(Aqt load global ignores
This disables loading of global or user ignore files, like \*(Aq~/.gitignore\*(Aq,
\*(Aq~/.config/watchexec/ignore\*(Aq, or \*(Aq%APPDATA%\\Bazzar\\2.0\\ignore\*(Aq. Contrast with
\*(Aq\-\-no\-vcs\-ignore\*(Aq and \*(Aq\-\-no\-project\-ignore\*(Aq.
Supported global ignore files
\- Git (if core.excludesFile is set): the file at that path
\- Git (otherwise): the first found of $XDG_CONFIG_HOME/git/ignore, %APPDATA%/.gitignore, %USERPROFILE%/.gitignore, $HOME/.config/git/ignore, $HOME/.gitignore.
\- Bazaar: the first found of %APPDATA%/Bazzar/2.0/ignore, $HOME/.bazaar/ignore.
\- Watchexec: the first found of $XDG_CONFIG_HOME/watchexec/ignore, %APPDATA%/watchexec/ignore, %USERPROFILE%/.watchexec/ignore, $HOME/.watchexec/ignore.
Like for project files, Git and Bazaar global files will only be used for the corresponding
VCS as used in the project.
.TP
\fB\-\-no\-default\-ignore\fR
Don\*(Aqt use internal default ignores
Watchexec has a set of default ignore patterns, such as editor swap files, `*.pyc`, `*.pyo`, `.DS_Store`, `.bzr`, `_darcs`, `.fossil\-settings`, `.git`, `.hg`, `.pijul`, `.svn`, and Watchexec log files.
.TP
\fB\-p\fR, \fB\-\-postpone\fR
Wait until first change before running command
By default, Watchexec will run the command once immediately. With this option, it will instead wait until an event is detected before running the command as normal.
.TP
\fB\-\-delay\-run\fR=\fIDURATION\fR
Sleep before running the command
This option will cause Watchexec to sleep for the specified amount of time before running the command, after an event is detected. This is like using "sleep 5 && command" in a shell, but portable and slightly more efficient.
Takes a unit\-less value in seconds, or a time span value such as "2min 5s".
.TP
\fB\-\-poll\fR=\fIINTERVAL\fR
Poll for filesystem changes
By default, and where available, Watchexec uses the operating system\*(Aqs native file system watching capabilities. This option disables that and instead uses a polling mechanism, which is less efficient but can work around issues with some file systems (like network shares) or edge cases.
Optionally takes a unit\-less value in milliseconds, or a time span value such as "2s 500ms", to use as the polling interval. If not specified, the default is 30 seconds.
Aliased as \*(Aq\-\-force\-poll\*(Aq.
.TP
\fB\-\-shell\fR=\fISHELL\fR
Use a different shell
By default, Watchexec will use \*(Aqsh\*(Aq on unix and \*(Aqcmd\*(Aq (CMD.EXE) on Windows. With this, you can override that and use a different shell, for example one with more features or one which has your custom aliases and functions.
If the value has spaces, it is parsed as a command line, and the first word used as the shell program, with the rest as arguments to the shell.
The command is run with the \*(Aq\-c\*(Aq flag (except for \*(Aqcmd\*(Aq and \*(Aqpowershell\*(Aq on Windows, where the \*(Aq/C\*(Aq option is used).
Note that the default shell will change at the next major release: the value of \*(Aq$SHELL\*(Aq will be respected, falling back to \*(Aqsh\*(Aq on unix and to PowerShell on Windows.
The special value \*(Aqnone\*(Aq can be used to disable shell use entirely. In that case, the command provided to Watchexec will be parsed, with the first word being the executable and the rest being the arguments, and executed directly. Note that this parsing is rudimentary, and may not work as expected in all cases.
Using \*(Aqnone\*(Aq is a little more efficient and can enable a stricter interpretation of the input, but it also means that you can\*(Aqt use shell features like globbing, redirection, or pipes.
Examples:
$ watchexec \-w lib \-w src make
.
.fi
.
.IP "" 0
.
.P
Use without shell:
.
.IP "" 4
.
.nf
$ watchexec \-n \-\- zsh \-x \-o shwordsplit scr
.
.fi
.
.IP "" 0
.
.P
Use with powershell (default on windows from 2\.0):
.
.IP "" 4
.
.nf
Use with powershell:
$ watchexec \-\-shell=powershell \-\- test\-connection localhost
.
.fi
.
.IP "" 0
.
.P
Use with cmd (default on windows until 2\.0):
.
.IP "" 4
.
.nf
Use with cmd:
$ watchexec \-\-shell=cmd \-\- dir
.
.fi
.
.IP "" 0
.
.P
Use with a different unix shell:
.
.IP "" 4
.
.nf
$ watchexec \-\-shell=bash \-\- \'echo $BASH_VERSION\'
.
.fi
.
.IP "" 0
.
.P
$ watchexec \-\-shell=bash \-\- \*(Aqecho $BASH_VERSION\*(Aq
Use with a unix shell and options:
.
.IP "" 4
.
.nf
$ watchexec \-\-shell=\'zsh \-x \-o shwordsplit\' \-\- scr
.
.fi
.
.IP "" 0
$ watchexec \-\-shell=\*(Aqzsh \-x \-o shwordsplit\*(Aq \-\- scr
.TP
\fB\-n\fR
Don\*(Aqt use a shell
This is a shorthand for \*(Aq\-\-shell=none\*(Aq.
.TP
\fB\-\-no\-environment\fR
Shorthand for \*(Aq\-\-emit\-events=none\*(Aq
This is the old way to disable event emission into the environment. See \*(Aq\-\-emit\-events\*(Aq for more.
.TP
\fB\-E\fR, \fB\-\-env\fR=\fIKEY=VALUE\fR
Add env vars to the command
This is a convenience option for setting environment variables for the command, without setting them for the Watchexec process itself.
Use key=value syntax. Multiple variables can be set by repeating the option.
.TP
\fB\-\-no\-process\-group\fR
Don\*(Aqt use a process group
By default, Watchexec will run the command in a process group, so that signals and terminations are sent to all processes in the group. Sometimes that\*(Aqs not what you want, and you can disable the behaviour with this option.
.TP
\fB\-N\fR, \fB\-\-notify\fR
Alert when commands start and end
With this, Watchexec will emit a desktop notification when a command starts and ends, on supported platforms. On unsupported platforms, it may silently do nothing, or log a warning.
.TP
\fB\-\-project\-origin\fR=\fIDIRECTORY\fR
Set the project origin
Watchexec will attempt to discover the project\*(Aqs "origin" (or "root") by searching for a variety of markers, like files or directory patterns. It does its best but sometimes gets it it wrong, and you can override that with this option.
The project origin is used to determine the path of certain ignore files, which VCS is being used, the meaning of a leading \*(Aq/\*(Aq in filtering patterns, and maybe more in the future.
When set, Watchexec will also not bother searching, which can be significantly faster.
.TP
\fB\-\-workdir\fR=\fIDIRECTORY\fR
Set the working directory
By default, the working directory of the command is the working directory of Watchexec. You can change that with this option. Note that paths may be less intuitive to use with this.
.TP
\fB\-e\fR, \fB\-\-exts\fR=\fIEXTENSIONS\fR
Filename extensions to filter to
This is a quick filter to only emit events for files with the given extensions. Extensions can be given with or without the leading dot (e.g. \*(Aqjs\*(Aq or \*(Aq.js\*(Aq). Multiple extensions can be given by repeating the option or by separating them with commas.
.TP
\fB\-f\fR, \fB\-\-filter\fR=\fIPATTERN\fR
Filename patterns to filter to
Provide a glob\-like filter pattern, and only events for files matching the pattern will be emitted. Multiple patterns can be given by repeating the option. Events that are not from files (e.g. signals, keyboard events) will pass through untouched.
.TP
\fB\-\-filter\-file\fR=\fIPATH\fR
Files to load filters from
Provide a path to a file containing filters, one per line. Empty lines and lines starting with \*(Aq#\*(Aq are ignored. Uses the same pattern format as the \*(Aq\-\-filter\*(Aq option.
This can also be used via the $WATCHEXEC_FILTER_FILES environment variable.
.TP
\fB\-i\fR, \fB\-\-ignore\fR=\fIPATTERN\fR
Filename patterns to filter out
Provide a glob\-like filter pattern, and events for files matching the pattern will be excluded. Multiple patterns can be given by repeating the option. Events that are not from files (e.g. signals, keyboard events) will pass through untouched.
.TP
\fB\-\-ignore\-file\fR=\fIPATH\fR
Files to load ignores from
Provide a path to a file containing ignores, one per line. Empty lines and lines starting with \*(Aq#\*(Aq are ignored. Uses the same pattern format as the \*(Aq\-\-ignore\*(Aq option.
This can also be used via the $WATCHEXEC_IGNORE_FILES environment variable.
.TP
\fB\-\-fs\-events\fR=\fIEVENTS\fR
Filesystem events to filter to
This is a quick filter to only emit events for the given types of filesystem changes. Choose from \*(Aqaccess\*(Aq, \*(Aqcreate\*(Aq, \*(Aqremove\*(Aq, \*(Aqrename\*(Aq, \*(Aqmodify\*(Aq, \*(Aqmetadata\*(Aq. Multiple types can be given by repeating the option or by separating them with commas. By default, this is all types except for \*(Aqaccess\*(Aq.
This may apply filtering at the kernel level when possible, which can be more efficient, but may be more confusing when reading the logs.
.TP
\fB\-\-no\-meta\fR
Don\*(Aqt emit fs events for metadata changes
This is a shorthand for \*(Aq\-\-fs\-events create,remove,rename,modify\*(Aq. Using it alongside the \*(Aq\-\-fs\-events\*(Aq option is non\-sensical and not allowed.
.TP
\fB\-\-print\-events\fR
Print events that trigger actions
This prints the events that triggered the action when handling it (after debouncing), in a human readable form. This is useful for debugging filters.
Use \*(Aq\-v\*(Aq when you need more diagnostic information.
.TP
\fB\-v\fR, \fB\-\-verbose\fR
Set diagnostic log level
This enables diagnostic logging, which is useful for investigating bugs or gaining more insight into faulty filters or "missing" events. Use multiple times to increase verbosity.
Goes up to \*(Aq\-vvvv\*(Aq. When submitting bug reports, default to a \*(Aq\-vvv\*(Aq log level.
You may want to use with \*(Aq\-\-log\-file\*(Aq to avoid polluting your terminal.
Setting $RUST_LOG also works, and takes precendence, but is not recommended. However, using $RUST_LOG is the only way to get logs from before these options are parsed.
.TP
\fB\-\-log\-file\fR=\fIPATH\fR
Write diagnostic logs to a file
This writes diagnostic logs to a file, instead of the terminal, in JSON format. If a log level was not already specified, this will set it to \*(Aq\-vvv\*(Aq.
If a path is not provided, the default is the working directory. Note that with \*(Aq\-\-ignore\-nothing\*(Aq, the write events to the log will likely get picked up by Watchexec, causing a loop; prefer setting a path outside of the watched directory.
If the path provided is a directory, a file will be created in that directory. The file name will be the current date and time, in the format \*(Aqwatchexec.YYYY\-MM\-DDTHH\-MM\-SSZ.log\*(Aq.
.TP
\fB\-\-manpage\fR
Show the manual page
This shows the manual page for Watchexec, if the output is a terminal and the \*(Aqman\*(Aq program is available. If not, the manual page is printed to stdout in ROFF format (suitable for writing to a watchexec.1 file).
.TP
\fB\-\-completions\fR=\fICOMPLETIONS\fR
Generate a shell completions script
Provides a completions script or configuration for the given shell. If Watchexec is not distributed with pre\-generated completions, you can use this to generate them yourself.
Supported shells: bash, elvish, fish, nu, powershell, zsh.
.TP
\fB\-h\fR, \fB\-\-help\fR
Print help (see a summary with \*(Aq\-h\*(Aq)
.TP
\fB\-V\fR, \fB\-\-version\fR
Print version
.TP
[\fICOMMAND\fR]
Command to run on changes
It\*(Aqs run when events pass filters and the debounce period (and once at startup unless \*(Aq\-\-postpone\*(Aq is given). If you pass flags to the command, you should separate it with \-\- though that is not strictly required.
Examples:
$ watchexec \-w src npm run build
$ watchexec \-w src \-\- rsync \-a src dest
Take care when using globs or other shell expansions in the command. Your shell may expand them before ever passing them to Watchexec, and the results may not be what you expect. Compare:
$ watchexec echo src/*.rs
$ watchexec echo \*(Aqsrc/*.rs\*(Aq
$ watchexec \-\-shell=none echo \*(Aqsrc/*.rs\*(Aq
Behaviour depends on the value of \*(Aq\-\-shell\*(Aq: for all except \*(Aqnone\*(Aq, every part of the command is joined together into one string with a single ascii space character, and given to the shell as described in the help for \*(Aq\-\-shell\*(Aq. For \*(Aqnone\*(Aq, each distinct element the command is passed as per the execvp(3) convention: first argument is the program, as a path or searched for in the \*(AqPATH\*(Aq environment variable, rest are arguments.
.SH EXTRA
Use @argfile as first argument to load arguments from the file \*(Aqargfile\*(Aq (one argument per line) which will be inserted in place of the @argfile (further arguments on the CLI will override or add onto those in the file).
.SH VERSION
v1.21.1
.SH AUTHORS
Félix Saparelli <felix@passcod.name>, Matt Green <mattgreenrocks@gmail.com>

View File

@ -1,325 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' value='text/html;charset=utf8'>
<meta name='generator' value='Ronn/v0.7.3 (http://github.com/rtomayko/ronn/tree/0.7.3)'>
<title>watchexec(1) - execute commands when watched files change</title>
<style type='text/css' media='all'>
/* style: man */
body#manpage {margin:0}
.mp {max-width:100ex;padding:0 9ex 1ex 4ex}
.mp p,.mp pre,.mp ul,.mp ol,.mp dl {margin:0 0 20px 0}
.mp h2 {margin:10px 0 0 0}
.mp > p,.mp > pre,.mp > ul,.mp > ol,.mp > dl {margin-left:8ex}
.mp h3 {margin:0 0 0 4ex}
.mp dt {margin:0;clear:left}
.mp dt.flush {float:left;width:8ex}
.mp dd {margin:0 0 0 9ex}
.mp h1,.mp h2,.mp h3,.mp h4 {clear:left}
.mp pre {margin-bottom:20px}
.mp pre+h2,.mp pre+h3 {margin-top:22px}
.mp h2+pre,.mp h3+pre {margin-top:5px}
.mp img {display:block;margin:auto}
.mp h1.man-title {display:none}
.mp,.mp code,.mp pre,.mp tt,.mp kbd,.mp samp,.mp h3,.mp h4 {font-family:monospace;font-size:14px;line-height:1.42857142857143}
.mp h2 {font-size:16px;line-height:1.25}
.mp h1 {font-size:20px;line-height:2}
.mp {text-align:justify;background:#fff}
.mp,.mp code,.mp pre,.mp pre code,.mp tt,.mp kbd,.mp samp {color:#131211}
.mp h1,.mp h2,.mp h3,.mp h4 {color:#030201}
.mp u {text-decoration:underline}
.mp code,.mp strong,.mp b {font-weight:bold;color:#131211}
.mp em,.mp var {font-style:italic;color:#232221;text-decoration:none}
.mp a,.mp a:link,.mp a:hover,.mp a code,.mp a pre,.mp a tt,.mp a kbd,.mp a samp {color:#0000ff}
.mp b.man-ref {font-weight:normal;color:#434241}
.mp pre {padding:0 4ex}
.mp pre code {font-weight:normal;color:#434241}
.mp h2+pre,h3+pre {padding-left:0}
ol.man-decor,ol.man-decor li {margin:3px 0 10px 0;padding:0;float:left;width:33%;list-style-type:none;text-transform:uppercase;color:#999;letter-spacing:1px}
ol.man-decor {width:100%}
ol.man-decor li.tl {text-align:left}
ol.man-decor li.tc {text-align:center;letter-spacing:4px}
ol.man-decor li.tr {text-align:right;float:right}
</style>
<style type='text/css' media='all'>
/* style: toc */
.man-navigation {display:block !important;position:fixed;top:0;left:113ex;height:100%;width:100%;padding:48px 0 0 0;border-left:1px solid #dbdbdb;background:#eee}
.man-navigation a,.man-navigation a:hover,.man-navigation a:link,.man-navigation a:visited {display:block;margin:0;padding:5px 2px 5px 30px;color:#999;text-decoration:none}
.man-navigation a:hover {color:#111;text-decoration:underline}
</style>
</head>
<!--
The following styles are deprecated and will be removed at some point:
div#man, div#man ol.man, div#man ol.head, div#man ol.man.
The .man-page, .man-decor, .man-head, .man-foot, .man-title, and
.man-navigation should be used instead.
-->
<body id='manpage'>
<div class='mp' id='man'>
<div class='man-navigation' style='display:none'>
<a href="#NAME">NAME</a>
<a href="#SYNOPSIS">SYNOPSIS</a>
<a href="#DESCRIPTION">DESCRIPTION</a>
<a href="#OPTIONS">OPTIONS</a>
<a href="#PATHS">PATHS</a>
<a href="#ENVIRONMENT">ENVIRONMENT</a>
<a href="#FILES">FILES</a>
<a href="#EXAMPLES">EXAMPLES</a>
</div>
<ol class='man-decor man-head man head'>
<li class='tl'>watchexec(1)</li>
<li class='tc'></li>
<li class='tr'>watchexec(1)</li>
</ol>
<h2 id="NAME">NAME</h2>
<p class="man-name">
<code>watchexec</code> - <span class="man-whatis">execute commands when watched files change</span>
</p>
<h2 id="SYNOPSIS">SYNOPSIS</h2>
<p>watchexec [OPTIONS] [--] <var>command</var> [<var>argument</var>...]
watchexec -V|--version
watchexec [-h|--help]</p>
<h2 id="DESCRIPTION">DESCRIPTION</h2>
<p>Recursively monitors the current directory for changes, executing the command when a filesystem change is detected. By default, watchexec uses efficient kernel-level mechanisms to watch for changes.</p>
<p>At startup, the specified <var>command</var> (passing any supplied <var>argument</var>s) is run once, and watchexec begins monitoring for changes.</p>
<h2 id="OPTIONS">OPTIONS</h2>
<h3 id="Command-options">Command options</h3>
<dl>
<dt class="flush"><var>command</var></dt><dd>Command to run when watched files are modified, and at startup, unless <code>--postpone</code> is specified. All <var>argument</var>s are passed to <var>command</var>. If you pass flags to the command, you should separate it with <code>--</code>, for example: <code>watchexec -w src -- rsync -a src dest</code>.</dd>
</dl>
<p>Behaviour depends on the value of <code>--shell</code>: for all except <code>none</code>, every part of <var>command</var> is joined together into one string with a single ascii space character, and given to the shell as described. For <code>none</code>, each distinct element of <var>command</var> is passed as per the <span class="man-ref">execvp<span class="s">(3)</span></span> convention: first argument is the program, as a file or searched in the <code>PATH</code>, rest are arguments.</p>
<dl>
<dt><code>-E</code>, <code>--env</code> <var>key=value pair</var></dt><dd><p>Set additional environment variables on the command (not to Watchexec itself). Can be given multiple times (one per variable to set).</p></dd>
<dt class="flush"><code>-n</code></dt><dd><p>Shorthand for <code>--shell=none</code>.</p></dd>
<dt><code>--no-process-group</code></dt><dd><p>Do not use a process group when running <var>command</var>.</p></dd>
<dt><code>--no-environment</code></dt><dd><p>Do not set WATCHEXEC<em>*</em>PATH environment variables for the command.</p></dd>
<dt><code>--no-shell</code></dt><dd><p>Deprecated. Alias for <code>--shell=none</code>.</p></dd>
<dt><code>--shell</code> <var>shell</var></dt><dd><p>Change the shell used to run the command. Set to <code>none</code> to run the command directly without a shell.</p></dd>
</dl>
<p>The special value <code>powershell</code> will use Microsoft Powershell's calling convention, otherwise <code>SHELL -c COMMAND</code>.</p>
<p>On Windows, the additional <code>cmd</code> special value uses CMD.EXE calling convention.</p>
<p>The <code>none</code> value is especially useful in combination with <code>--signal</code>, as the signal is then sent directly to the running command. While <code>--shell=none</code> is a little more performant than the default, it prevents using shell-features like pipes and redirects.</p>
<p>If not a special value, the string provided may contain arguments to the shell as long as that is kept simple: the string is split along whitespace, and used as per <span class="man-ref">execvp<span class="s">(3)</span></span>: first is shell program, rest are arguments to the shell, then <code>-c</code> is added, and finally the <code>COMMAND</code>.</p>
<p>See the <a href="#EXAMPLES" title="EXAMPLES" data-bare-link="true">EXAMPLES</a> for uses of each of these.</p>
<dl>
<dt><code>--workdir &lt;path></code></dt><dd>Set the working directory of the command (not of Watchexec itself!). By default not set, and inherited from the Watchexec instance as is usual.</dd>
</dl>
<h3 id="Filtering-options">Filtering options</h3>
<dl>
<dt><code>-e</code>, <code>--exts</code> <var>extensions</var></dt><dd><p>Comma-separated list of file extensions to filter by. Leading dots (.rs) are allowed. (This is a shorthand for <code>-f</code>).</p></dd>
<dt><code>-f</code>, <code>--filter</code> <var>pattern</var></dt><dd><p>Ignores modifications from paths that do not match <var>pattern</var>. This option can be specified multiple times, where a match on any given pattern causes the path to trigger <var>command</var>.</p></dd>
<dt><code>-i</code>, <code>--ignore</code> <var>pattern</var></dt><dd><p>Ignores modifications from paths that match <var>pattern</var>. This option can be specified multiple times, and a match on any pattern causes the path to be ignored.</p></dd>
<dt><code>--no-default-ignore</code></dt><dd><p>Skip default ignore statements. By default, watchexec ignores common temporary files for you, for example <code>*.swp</code>, <code>*.pyc</code>, and <code>.DS_Store</code>, as well as the data directories of known VCS: <code>.bzr</code>, <code>_darcs</code>, <code>.fossil-settings</code>, <code>.git</code>, <code>.hg</code>, <code>.pijul</code>, and <code>.svn</code>.</p></dd>
<dt><code>--no-global-ignore</code></dt><dd><p>Skip loading of global ignore files. By default, watchexec loads $HOME/.gitignore and other such global files and uses them to filter change events.</p></dd>
<dt><code>--no-meta</code></dt><dd><p>Ignore metadata changes.</p></dd>
<dt><code>--no-project-ignore</code>, <code>--no-ignore</code> (deprecated alias)</dt><dd><p>Skip loading of project-local ignore files (include VCS ignore files). By default, watchexec loads .ignore, .gitignore, .hgignore, and other such files in the current directory (or child directories as applicable) and uses them to filter change events.</p></dd>
</dl>
<p>The <code>--no-ignore</code> alias will be replaced by a new option in 2.0.0, beware!</p>
<dl>
<dt><code>--no-vcs-ignore</code></dt><dd><p>Skip loading of version control system (VCS) ignore files. By default, watchexec loads .gitignore, .hgignore, and other such files in the current directory (or child directories as applicable) and uses them to filter change events.</p></dd>
<dt><code>--project-origin</code> <var>path</var></dt><dd><p>Overrides the project origin, where ignore files are resolved from (see <a href="#PATHS" title="PATHS" data-bare-link="true">PATHS</a> section below).</p></dd>
<dt><code>-w</code>, <code>--watch</code> <var>path</var></dt><dd><p>Monitor a specific path for changes. By default, the current working directory is watched. This may be specified multiple times, where a change in any watched directory (and subdirectories) causes <var>command</var> to be executed.</p></dd>
</dl>
<h3 id="Behaviour-options">Behaviour options</h3>
<dl>
<dt><code>-d</code>, <code>--debounce</code></dt><dd><p>Set the timeout between detected change and command execution, to avoid restarting too frequently when there are many events; defaults to 100ms.</p></dd>
<dt><code>--force-poll</code> <var>interval</var></dt><dd><p>Poll for changes every <var>interval</var> ms instead of using system-specific notification mechanisms (such as inotify). This is useful when you are monitoring NFS shares.</p></dd>
<dt><code>-p</code>, <code>--postpone</code></dt><dd><p>Postpone execution of <var>command</var> until the first file modification is detected.</p></dd>
<dt><code>-r</code>, <code>--restart</code></dt><dd><p>Terminates the command if it is still running when subsequent file modifications are detected. By default, sends <code>SIGTERM</code>; use <code>--signal</code> to change that.</p></dd>
<dt><code>-s</code>, <code>--signal</code></dt><dd><p>Sends the specified signal (e.g. <code>SIGKILL</code>) to the command. Defaults to <code>SIGTERM</code>.</p></dd>
<dt><code>-W</code>, <code>--watch-when-idle</code></dt><dd><p>Ignore events while the process is still running. This is distinct from <code>--restart</code> in that with this option, events received while the command is running will not trigger a new run immediately after the current command is done.</p></dd>
</dl>
<p>This behaviour will become the default in v2.0.</p>
<h3 id="Output-options">Output options</h3>
<dl>
<dt><code>-c</code>, <code>--clear</code></dt><dd><p>Clears the screen before executing <var>command</var>.</p></dd>
<dt><code>-N</code>, <code>--notify</code></dt><dd><p>Sends desktop notifications on command start and command end.</p></dd>
</dl>
<h3 id="Debugging-options">Debugging options</h3>
<dl>
<dt><code>--print-events</code>, <code>--changes-only</code> (deprecated alias)</dt><dd><p>Prints the events (changed paths, etc) that have triggered an action to STDERR.</p></dd>
<dt><code>-v</code>, <code>--verbose</code>, <code>-vv</code>, etc</dt><dd><p>Prints diagnostic and debugging messages to STDERR. Increase the amount of <code>v</code>s to get progressively more output: for bug reports use <strong>three</strong>, and for deep debugging <strong>four</strong> can be helpful.</p></dd>
<dt><code>--log-file</code> <var>path</var></dt><dd><p>Writes diagnostic and debugging messages (from the <code>-v</code> options) to file instead of STDERR, in JSON format. This is preferrable for reporting bugs. Be careful <strong>not</strong> to write to a file within the purview of Watchexec to avoid recursion!</p></dd>
<dt><code>-V</code>, <code>--version</code></dt><dd><p>Print the version of watchexec.</p></dd>
<dt><code>-h</code>, <code>--help</code></dt><dd><p>Print a help message.</p></dd>
</dl>
<h2 id="PATHS">PATHS</h2>
<p>By default, Watchexec watches the current directory. This can be changed with the <code>--watch</code> option, which can be passed multiple times.</p>
<p>Upon starting, Watchexec resolves a "project origin" from the watched paths. To do so, it recurses up every parent directory from each watched path, looking for file and directory patterns which indicate a project origin among many different software systems, such as a Git repo, Cargo crate, licensing files, readmes, workspace configuration, etc. For the full current list, consult the source at <code>lib/src/project.rs</code>.</p>
<p>Once it has a list of "potential project origins", it resolves the common prefix they all have, and uses this as the overall project origin. Note that the home directory is excluded from potential origins unless it's explicitly requested as a watched path.</p>
<p>The overall project origin is used to find and resolve ignore files, such that in most cases it acts as one would expect for a tool that runs anywhere inside a project.</p>
<p>For this reason, it is not recommended to use Watchexec for watching disparate folders in a filesystem, where those would resolve to a too-broad project origin.</p>
<p>The project origin can be overridden with the <code>--project-origin</code> option.</p>
<h2 id="ENVIRONMENT">ENVIRONMENT</h2>
<p>In variables that contain lists of paths, the separator is as for the <code>$PATH</code> environment variable (a colon, or semicolon on Windows).</p>
<h3 id="Set-on-child-processes">Set on child processes</h3>
<p>Processes started by watchexec have environment variables set describing the changes observed.</p>
<p><code>$WATCHEXEC_COMMON_PATH</code> is set to the longest common path of all of the below variables, and so should be prepended to each path to obtain the full/real path. Then:</p>
<ul>
<li><code>$WATCHEXEC_CREATED_PATH</code> is set when files/folders were created</li>
<li><code>$WATCHEXEC_REMOVED_PATH</code> is set when files/folders were removed</li>
<li><code>$WATCHEXEC_RENAMED_PATH</code> is set when files/folders were renamed</li>
<li><code>$WATCHEXEC_WRITTEN_PATH</code> is set when files/folders were modified</li>
<li><code>$WATCHEXEC_META_CHANGED_PATH</code> is set when files/folders' metadata were modified</li>
<li><code>$WATCHEXEC_OTHERWISE_CHANGED_PATH</code> is set for every other kind of pathed event</li>
</ul>
<p>These variables may contain multiple paths: these are separated by the platform's path separator, as with the <code>PATH</code> system environment variable. On Unix that is <code>:</code>, and on Windows <code>;</code>. Within each variable, paths are deduplicated and sorted in binary order (i.e. neither Unicode nor locale aware).</p>
<p>One thing to take care of is assuming inherent behaviour where there is only chance. Notably, it could appear as if the <code>RENAMED</code> variable contains both the original and the new path being renamed. In previous versions, it would even appear on some platforms as if the original always came before the new. However, none of this was true. It's impossible to reliably and portably know which changed path is the old or new, "half" renames may appear (only the original, only the new), "unknown" renames may appear (change was a rename, but whether it was the old or new isn't known), rename events might split across two debouncing boundaries, and so on.</p>
<p>This variable group can be disabled or limited with <code>--no-environment</code> (doesn't set any of these variables) and <code>--no-meta</code> (ignores metadata changes).</p>
<h3 id="Read-upon-startup">Read upon startup</h3>
<ul>
<li><code>$WATCHEXEC_FILTERER</code>: select the filterer implementation: <code>globset</code> (default), or <code>tagged</code> (experimental).</li>
<li><code>$WATCHEXEC_IGNORE_FILES</code>: a list of paths to additional ignore files to be loaded.</li>
<li><code>$WATCHEXEC_FILTER_FILES</code>: a list of paths to additional "Tagged" filter files to be loaded (when enabled).</li>
<li><code>$RUST_LOG</code>: use for advanced verbose logging configuration. Refer to tracing-subscriber for documentation.</li>
</ul>
<h2 id="FILES">FILES</h2>
<h3 id="Supported-project-ignore-files">Supported project ignore files</h3>
<ul>
<li>Git: <code>.gitignore</code> at project root and child directories, <code>.git/info/exclude</code>, and the file pointed to by <code>core.excludesFile</code> in <code>.git/config</code>.</li>
<li>Mercurial: <code>.hgignore</code> at project root and child directories.</li>
<li>Bazaar: <code>.bzrignore</code> at project root.</li>
<li>Darcs: <code>_darcs/prefs/boring</code></li>
<li>Fossil: <code>.fossil-settings/ignore-glob</code></li>
<li>Ripgrep/Watchexec/generic: <code>.ignore</code> at project root and child directories.</li>
</ul>
<p>Note that VCS ignore files (Git, Mercurial, Bazaar, Darcs, Fossil) are only used if the corresponding VCS is discovered to be in use for the project/origin. For example, a <code>.bzrignore</code> in a Git repository will be discarded.</p>
<h3 id="Supported-global-ignore-files">Supported global ignore files</h3>
<ul>
<li>Git (if core.excludesFile is set): the file at that path</li>
<li>Git (otherwise): the first found of <code>$XDG_CONFIG_HOME/git/ignore</code>, <code>%APPDATA%/.gitignore</code>, <code>%USERPROFILE%/.gitignore</code>, <code>$HOME/.config/git/ignore</code>, <code>$HOME/.gitignore</code>.</li>
<li>Bazaar: the first found of <code>%APPDATA%/Bazzar/2.0/ignore</code>, <code>$HOME/.bazaar/ignore</code>.</li>
<li>Watchexec: the first found of <code>$XDG_CONFIG_HOME/watchexec/ignore</code>, <code>%APPDATA%/watchexec/ignore</code>, <code>%USERPROFILE%/.watchexec/ignore</code>, <code>$HOME/.watchexec/ignore</code>.</li>
</ul>
<p>Note that like for project files, Git and Bazaar global files will only be used for the corresponding VCS as used in the project.</p>
<h2 id="EXAMPLES">EXAMPLES</h2>
<p>Rebuild a project when source files change:</p>
<pre><code>$ watchexec make
</code></pre>
<p>Watch all HTML, CSS, and JavaScript files for changes:</p>
<pre><code>$ watchexec -e html,css,js make
</code></pre>
<p>Run tests when source files change, clearing the screen each time:</p>
<pre><code>$ watchexec -c make test
</code></pre>
<p>Launch and restart a node.js server:</p>
<pre><code>$ watchexec -r node app.js
</code></pre>
<p>Watch lib and src directories for changes, rebuilding each time:</p>
<pre><code>$ watchexec -w lib -w src make
</code></pre>
<p>Use without shell:</p>
<pre><code>$ watchexec -n -- zsh -x -o shwordsplit scr
</code></pre>
<p>Use with powershell (default on windows from 2.0):</p>
<pre><code>$ watchexec --shell=powershell -- test-connection localhost
</code></pre>
<p>Use with cmd (default on windows until 2.0):</p>
<pre><code>$ watchexec --shell=cmd -- dir
</code></pre>
<p>Use with a different unix shell:</p>
<pre><code>$ watchexec --shell=bash -- 'echo $BASH_VERSION'
</code></pre>
<p>Use with a unix shell and options:</p>
<pre><code>$ watchexec --shell='zsh -x -o shwordsplit' -- scr
</code></pre>
<ol class='man-decor man-foot man foot'>
<li class='tl'></li>
<li class='tc'>June 2022</li>
<li class='tr'>watchexec(1)</li>
</ol>
</div>
</body>
</html>

590
doc/watchexec.1.md Normal file
View File

@ -0,0 +1,590 @@
# NAME
watchexec - Execute commands when watched files change
# SYNOPSIS
**watchexec** \[**-w**\|**\--watch**\] \[**-c**\|**\--clear**\]
\[**-o**\|**\--on-busy-update**\] \[**-r**\|**\--restart**\]
\[**-s**\|**\--signal**\] \[**\--stop-signal**\] \[**\--stop-timeout**\]
\[**\--debounce**\] \[**\--stdin-quit**\] \[**\--no-vcs-ignore**\]
\[**\--no-project-ignore**\] \[**\--no-global-ignore**\]
\[**\--no-default-ignore**\] \[**-p**\|**\--postpone**\]
\[**\--delay-run**\] \[**\--poll**\] \[**\--shell**\] \[**-n **\]
\[**\--no-environment**\] \[**-E**\|**\--env**\]
\[**\--no-process-group**\] \[**-N**\|**\--notify**\]
\[**\--project-origin**\] \[**\--workdir**\] \[**-e**\|**\--exts**\]
\[**-f**\|**\--filter**\] \[**\--filter-file**\]
\[**-i**\|**\--ignore**\] \[**\--ignore-file**\] \[**\--fs-events**\]
\[**\--no-meta**\] \[**\--print-events**\]
\[**-v**\|**\--verbose**\]\... \[**\--log-file**\] \[**\--manpage**\]
\[**\--completions**\] \[**-h**\|**\--help**\]
\[**-V**\|**\--version**\] \[*COMMAND*\]
# DESCRIPTION
Execute commands when watched files change.
Recursively monitors the current directory for changes, executing the
command when a filesystem change is detected (among other event
sources). By default, watchexec uses efficient kernel-level mechanisms
to watch for changes.
At startup, the specified \<COMMAND\> is run once, and watchexec begins
monitoring for changes.
Examples:
Rebuild a project when source files change:
\$ watchexec make
Watch all HTML, CSS, and JavaScript files for changes:
\$ watchexec -e html,css,js make
Run tests when source files change, clearing the screen each time:
\$ watchexec -c make test
Launch and restart a node.js server:
\$ watchexec -r node app.js
Watch lib and src directories for changes, rebuilding each time:
\$ watchexec -w lib -w src make
# OPTIONS
**-w**, **\--watch**=*PATH*
: Watch a specific file or directory
By default, Watchexec watches the current directory.
When watching a single file, its often better to watch the containing
directory instead, and filter on the filename. Some editors may replace
the file with a new one when saving, and some platforms may not detect
that or further changes.
Upon starting, Watchexec resolves a \"project origin\" from the watched
paths. See the help for \--project-origin for more information.
This option can be specified multiple times to watch multiple files or
directories.
**-c**, **\--clear**=*MODE*
: Clear screen before running command
If this doesnt completely clear the screen, try \--clear=reset.
**-o**, **\--on-busy-update**=*MODE*
: What to do when receiving events while the command is running
Default is to queue up events and run the command once again when the
previous run has finished. You can also use do-nothing, which ignores
events while the command is running and may be useful to avoid spurious
changes made by that command, or restart, which terminates the running
command and starts a new one. Finally, theres signal, which only sends a
signal; this can be useful with programs that can reload their
configuration without a full restart.
The signal can be specified with the \--signal option.
Note that this option is scheduled to change its default to do-nothing
in the next major release. File an issue if you have any concerns.
**-r**, **\--restart**
: Restart the process if its still running
This is a shorthand for \--on-busy-update=restart.
**-s**, **\--signal**=*SIGNAL*
: Send a signal to the process when its still running
Specify a signal to send to the process when its still running. This
implies \--on-busy-update=signal; otherwise the signal used when that
mode is restart is controlled by \--stop-signal.
See the long documentation for \--stop-signal for syntax.
**\--stop-signal**=*SIGNAL*
: Signal to send to stop the command
This is used by restart and signal modes of \--on-busy-update (unless
\--signal is provided). The restart behaviour is to send the signal,
wait for the command to exit, and if it hasnt exited after some time
(see \--timeout-stop), forcefully terminate it.
The default on unix is \"SIGTERM\".
Input is parsed as a full signal name (like \"SIGTERM\"), a short signal
name (like \"TERM\"), or a signal number (like \"15\"). All input is
case-insensitive.
On Windows this option is technically supported but only supports the
\"KILL\" event, as Watchexec cannot yet deliver other events. Windows
doesnt have signals as such; instead it has termination (here called
\"KILL\" or \"STOP\") and \"CTRL+C\", \"CTRL+BREAK\", and \"CTRL+CLOSE\"
events. For portability the unix signals \"SIGKILL\", \"SIGINT\",
\"SIGTERM\", and \"SIGHUP\" are respectively mapped to these.
**\--stop-timeout**=*TIMEOUT*
: Time to wait for the command to exit gracefully
This is used by the restart mode of \--on-busy-update. After the
graceful stop signal is sent, Watchexec will wait for the command to
exit. If it hasnt exited after this time, it is forcefully terminated.
Takes a unit-less value in seconds, or a time span value such as \"5min
20s\".
The default is 60 seconds. Set to 0 to immediately force-kill the
command.
**\--debounce**=*TIMEOUT*
: Time to wait for new events before taking action
When an event is received, Watchexec will wait for up to this amount of
time before handling it (such as running the command). This is essential
as what you might perceive as a single change may actually emit many
events, and without this behaviour, Watchexec would run much too often.
Additionally, its not infrequent that file writes are not atomic, and
each write may emit an event, so this is a good way to avoid running a
command while a file is partially written.
An alternative use is to set a high value (like \"30min\" or longer), to
save power or bandwidth on intensive tasks, like an ad-hoc backup
script. In those use cases, note that every accumulated event will build
up in memory.
Takes a unit-less value in milliseconds, or a time span value such as
\"5sec 20ms\".
The default is 50 milliseconds. Setting to 0 is highly discouraged.
**\--stdin-quit**
: Exit when stdin closes
This watches the stdin file descriptor for EOF, and exits Watchexec
gracefully when it is closed. This is used by some process managers to
avoid leaving zombie processes around.
**\--no-vcs-ignore**
: Dont load gitignores
Among other VCS exclude files, like for Mercurial, Subversion, Bazaar,
DARCS, Fossil. Note that Watchexec will detect which of these is in use,
if any, and only load the relevant files. Both global (like
\~/.gitignore) and local (like .gitignore) files are considered.
This option is useful if you want to watch files that are ignored by
Git.
**\--no-project-ignore**
: Dont load project-local ignores
This disables loading of project-local ignore files, like .gitignore or
.ignore in the watched project. This is contrasted with
\--no-vcs-ignore, which disables loading of Git and other VCS ignore
files, and with \--no-global-ignore, which disables loading of global or
user ignore files, like \~/.gitignore or \~/.config/watchexec/ignore.
Supported project ignore files:
\- Git: .gitignore at project root and child directories,
.git/info/exclude, and the file pointed to by \`core.excludesFile\` in
.git/config. - Mercurial: .hgignore at project root and child
directories. - Bazaar: .bzrignore at project root. - Darcs:
\_darcs/prefs/boring - Fossil: .fossil-settings/ignore-glob -
Ripgrep/Watchexec/generic: .ignore at project root and child
directories.
VCS ignore files (Git, Mercurial, Bazaar, Darcs, Fossil) are only used
if the corresponding VCS is discovered to be in use for the
project/origin. For example, a .bzrignore in a Git repository will be
discarded.
Note that this was previously called \--no-ignore, but thats now
deprecated and its use is discouraged, as it may be repurposed in the
future.
**\--no-global-ignore**
: Dont load global ignores
This disables loading of global or user ignore files, like
\~/.gitignore, \~/.config/watchexec/ignore, or
%APPDATA%\\Bazzar\\2.0\\ignore. Contrast with \--no-vcs-ignore and
\--no-project-ignore.
Supported global ignore files
\- Git (if core.excludesFile is set): the file at that path - Git
(otherwise): the first found of \$XDG_CONFIG_HOME/git/ignore,
%APPDATA%/.gitignore, %USERPROFILE%/.gitignore,
\$HOME/.config/git/ignore, \$HOME/.gitignore. - Bazaar: the first found
of %APPDATA%/Bazzar/2.0/ignore, \$HOME/.bazaar/ignore. - Watchexec: the
first found of \$XDG_CONFIG_HOME/watchexec/ignore,
%APPDATA%/watchexec/ignore, %USERPROFILE%/.watchexec/ignore,
\$HOME/.watchexec/ignore.
Like for project files, Git and Bazaar global files will only be used
for the corresponding VCS as used in the project.
**\--no-default-ignore**
: Dont use internal default ignores
Watchexec has a set of default ignore patterns, such as editor swap
files, \`\*.pyc\`, \`\*.pyo\`, \`.DS_Store\`, \`.bzr\`, \`\_darcs\`,
\`.fossil-settings\`, \`.git\`, \`.hg\`, \`.pijul\`, \`.svn\`, and
Watchexec log files.
**-p**, **\--postpone**
: Wait until first change before running command
By default, Watchexec will run the command once immediately. With this
option, it will instead wait until an event is detected before running
the command as normal.
**\--delay-run**=*DURATION*
: Sleep before running the command
This option will cause Watchexec to sleep for the specified amount of
time before running the command, after an event is detected. This is
like using \"sleep 5 && command\" in a shell, but portable and slightly
more efficient.
Takes a unit-less value in seconds, or a time span value such as \"2min
5s\".
**\--poll**=*INTERVAL*
: Poll for filesystem changes
By default, and where available, Watchexec uses the operating systems
native file system watching capabilities. This option disables that and
instead uses a polling mechanism, which is less efficient but can work
around issues with some file systems (like network shares) or edge
cases.
Optionally takes a unit-less value in milliseconds, or a time span value
such as \"2s 500ms\", to use as the polling interval. If not specified,
the default is 30 seconds.
Aliased as \--force-poll.
**\--shell**=*SHELL*
: Use a different shell
By default, Watchexec will use sh on unix and cmd (CMD.EXE) on Windows.
With this, you can override that and use a different shell, for example
one with more features or one which has your custom aliases and
functions.
If the value has spaces, it is parsed as a command line, and the first
word used as the shell program, with the rest as arguments to the shell.
The command is run with the -c flag (except for cmd and powershell on
Windows, where the /C option is used).
Note that the default shell will change at the next major release: the
value of \$SHELL will be respected, falling back to sh on unix and to
PowerShell on Windows.
The special value none can be used to disable shell use entirely. In
that case, the command provided to Watchexec will be parsed, with the
first word being the executable and the rest being the arguments, and
executed directly. Note that this parsing is rudimentary, and may not
work as expected in all cases.
Using none is a little more efficient and can enable a stricter
interpretation of the input, but it also means that you cant use shell
features like globbing, redirection, or pipes.
Examples:
Use without shell:
\$ watchexec -n \-- zsh -x -o shwordsplit scr
Use with powershell:
\$ watchexec \--shell=powershell \-- test-connection localhost
Use with cmd:
\$ watchexec \--shell=cmd \-- dir
Use with a different unix shell:
\$ watchexec \--shell=bash \-- echo \$BASH_VERSION
Use with a unix shell and options:
\$ watchexec \--shell=zsh -x -o shwordsplit \-- scr
**-n**
: Dont use a shell
This is a shorthand for \--shell=none.
**\--no-environment**
: Shorthand for \--emit-events=none
This is the old way to disable event emission into the environment. See
\--emit-events for more.
**-E**, **\--env**=*KEY=VALUE*
: Add env vars to the command
This is a convenience option for setting environment variables for the
command, without setting them for the Watchexec process itself.
Use key=value syntax. Multiple variables can be set by repeating the
option.
**\--no-process-group**
: Dont use a process group
By default, Watchexec will run the command in a process group, so that
signals and terminations are sent to all processes in the group.
Sometimes thats not what you want, and you can disable the behaviour
with this option.
**-N**, **\--notify**
: Alert when commands start and end
With this, Watchexec will emit a desktop notification when a command
starts and ends, on supported platforms. On unsupported platforms, it
may silently do nothing, or log a warning.
**\--project-origin**=*DIRECTORY*
: Set the project origin
Watchexec will attempt to discover the projects \"origin\" (or \"root\")
by searching for a variety of markers, like files or directory patterns.
It does its best but sometimes gets it it wrong, and you can override
that with this option.
The project origin is used to determine the path of certain ignore
files, which VCS is being used, the meaning of a leading / in filtering
patterns, and maybe more in the future.
When set, Watchexec will also not bother searching, which can be
significantly faster.
**\--workdir**=*DIRECTORY*
: Set the working directory
By default, the working directory of the command is the working
directory of Watchexec. You can change that with this option. Note that
paths may be less intuitive to use with this.
**-e**, **\--exts**=*EXTENSIONS*
: Filename extensions to filter to
This is a quick filter to only emit events for files with the given
extensions. Extensions can be given with or without the leading dot
(e.g. js or .js). Multiple extensions can be given by repeating the
option or by separating them with commas.
**-f**, **\--filter**=*PATTERN*
: Filename patterns to filter to
Provide a glob-like filter pattern, and only events for files matching
the pattern will be emitted. Multiple patterns can be given by repeating
the option. Events that are not from files (e.g. signals, keyboard
events) will pass through untouched.
**\--filter-file**=*PATH*
: Files to load filters from
Provide a path to a file containing filters, one per line. Empty lines
and lines starting with \# are ignored. Uses the same pattern format as
the \--filter option.
This can also be used via the \$WATCHEXEC_FILTER_FILES environment
variable.
**-i**, **\--ignore**=*PATTERN*
: Filename patterns to filter out
Provide a glob-like filter pattern, and events for files matching the
pattern will be excluded. Multiple patterns can be given by repeating
the option. Events that are not from files (e.g. signals, keyboard
events) will pass through untouched.
**\--ignore-file**=*PATH*
: Files to load ignores from
Provide a path to a file containing ignores, one per line. Empty lines
and lines starting with \# are ignored. Uses the same pattern format as
the \--ignore option.
This can also be used via the \$WATCHEXEC_IGNORE_FILES environment
variable.
**\--fs-events**=*EVENTS*
: Filesystem events to filter to
This is a quick filter to only emit events for the given types of
filesystem changes. Choose from access, create, remove, rename, modify,
metadata. Multiple types can be given by repeating the option or by
separating them with commas. By default, this is all types except for
access.
This may apply filtering at the kernel level when possible, which can be
more efficient, but may be more confusing when reading the logs.
**\--no-meta**
: Dont emit fs events for metadata changes
This is a shorthand for \--fs-events create,remove,rename,modify. Using
it alongside the \--fs-events option is non-sensical and not allowed.
**\--print-events**
: Print events that trigger actions
This prints the events that triggered the action when handling it (after
debouncing), in a human readable form. This is useful for debugging
filters.
Use -v when you need more diagnostic information.
**-v**, **\--verbose**
: Set diagnostic log level
This enables diagnostic logging, which is useful for investigating bugs
or gaining more insight into faulty filters or \"missing\" events. Use
multiple times to increase verbosity.
Goes up to -vvvv. When submitting bug reports, default to a -vvv log
level.
You may want to use with \--log-file to avoid polluting your terminal.
Setting \$RUST_LOG also works, and takes precendence, but is not
recommended. However, using \$RUST_LOG is the only way to get logs from
before these options are parsed.
**\--log-file**=*PATH*
: Write diagnostic logs to a file
This writes diagnostic logs to a file, instead of the terminal, in JSON
format. If a log level was not already specified, this will set it to
-vvv.
If a path is not provided, the default is the working directory. Note
that with \--ignore-nothing, the write events to the log will likely get
picked up by Watchexec, causing a loop; prefer setting a path outside of
the watched directory.
If the path provided is a directory, a file will be created in that
directory. The file name will be the current date and time, in the
format watchexec.YYYY-MM-DDTHH-MM-SSZ.log.
**\--manpage**
: Show the manual page
This shows the manual page for Watchexec, if the output is a terminal
and the man program is available. If not, the manual page is printed to
stdout in ROFF format (suitable for writing to a watchexec.1 file).
**\--completions**=*COMPLETIONS*
: Generate a shell completions script
Provides a completions script or configuration for the given shell. If
Watchexec is not distributed with pre-generated completions, you can use
this to generate them yourself.
Supported shells: bash, elvish, fish, nu, powershell, zsh.
**-h**, **\--help**
: Print help (see a summary with -h)
**-V**, **\--version**
: Print version
\[*COMMAND*\]
: Command to run on changes
Its run when events pass filters and the debounce period (and once at
startup unless \--postpone is given). If you pass flags to the command,
you should separate it with \-- though that is not strictly required.
Examples:
\$ watchexec -w src npm run build
\$ watchexec -w src \-- rsync -a src dest
Take care when using globs or other shell expansions in the command.
Your shell may expand them before ever passing them to Watchexec, and
the results may not be what you expect. Compare:
\$ watchexec echo src/\*.rs
\$ watchexec echo src/\*.rs
\$ watchexec \--shell=none echo src/\*.rs
Behaviour depends on the value of \--shell: for all except none, every
part of the command is joined together into one string with a single
ascii space character, and given to the shell as described in the help
for \--shell. For none, each distinct element the command is passed as
per the execvp(3) convention: first argument is the program, as a path
or searched for in the PATH environment variable, rest are arguments.
# EXTRA
Use \@argfile as first argument to load arguments from the file argfile
(one argument per line) which will be inserted in place of the \@argfile
(further arguments on the CLI will override or add onto those in the
file).
# VERSION
v1.21.1
# AUTHORS
Félix Saparelli \<felix@passcod.name\>, Matt Green
\<mattgreenrocks@gmail.com\>

BIN
doc/watchexec.1.pdf Normal file

Binary file not shown.

View File

@ -1,246 +0,0 @@
watchexec(1) -- execute commands when watched files change
==========================================================
## SYNOPSIS
watchexec [OPTIONS] [--] <command> [<argument>...]
watchexec -V|--version
watchexec [-h|--help]
## DESCRIPTION
Recursively monitors the current directory for changes, executing the command when a filesystem change is detected. By default, watchexec uses efficient kernel-level mechanisms to watch for changes.
At startup, the specified <command> (passing any supplied <argument>s) is run once, and watchexec begins monitoring for changes.
## OPTIONS
### Command options
* <command>:
Command to run when watched files are modified, and at startup, unless `--postpone` is specified. All <argument>s are passed to <command>. If you pass flags to the command, you should separate it with `--`, for example: `watchexec -w src -- rsync -a src dest`.
Behaviour depends on the value of `--shell`: for all except `none`, every part of <command> is joined together into one string with a single ascii space character, and given to the shell as described. For `none`, each distinct element of <command> is passed as per the execvp(3) convention: first argument is the program, as a file or searched in the `PATH`, rest are arguments.
* `-E`, `--env` <key=value pair>:
Set additional environment variables on the command (not to Watchexec itself). Can be given multiple times (one per variable to set).
* `-n`:
Shorthand for `--shell=none`.
* `--no-process-group`:
Do not use a process group when running <command>.
* `--no-environment`:
Do not set WATCHEXEC_*_PATH environment variables for the command.
* `--no-shell`:
Deprecated. Alias for `--shell=none`.
* `--shell` <shell>:
Change the shell used to run the command. Set to `none` to run the command directly without a shell.
The special value `powershell` will use Microsoft Powershell's calling convention, otherwise `SHELL -c COMMAND`.
On Windows, the additional `cmd` special value uses CMD.EXE calling convention.
The `none` value is especially useful in combination with `--signal`, as the signal is then sent directly to the running command. While `--shell=none` is a little more performant than the default, it prevents using shell-features like pipes and redirects.
If not a special value, the string provided may contain arguments to the shell as long as that is kept simple: the string is split along whitespace, and used as per execvp(3): first is shell program, rest are arguments to the shell, then `-c` is added, and finally the `COMMAND`.
See the [EXAMPLES] for uses of each of these.
* `--workdir <path>`:
Set the working directory of the command (not of Watchexec itself!). By default not set, and inherited from the Watchexec instance as is usual.
### Filtering options
* `-e`, `--exts` <extensions>:
Comma-separated list of file extensions to filter by. Leading dots (.rs) are allowed. (This is a shorthand for `-f`).
* `-f`, `--filter` <pattern>:
Ignores modifications from paths that do not match <pattern>. This option can be specified multiple times, where a match on any given pattern causes the path to trigger <command>.
* `-i`, `--ignore` <pattern>:
Ignores modifications from paths that match <pattern>. This option can be specified multiple times, and a match on any pattern causes the path to be ignored.
* `--no-default-ignore`:
Skip default ignore statements. By default, watchexec ignores common temporary files for you, for example `*.swp`, `*.pyc`, and `.DS_Store`, as well as the data directories of known VCS: `.bzr`, `_darcs`, `.fossil-settings`, `.git`, `.hg`, `.pijul`, and `.svn`.
* `--no-global-ignore`:
Skip loading of global ignore files. By default, watchexec loads $HOME/.gitignore and other such global files and uses them to filter change events.
* `--no-meta`:
Ignore metadata changes.
* `--no-project-ignore`, `--no-ignore` (deprecated alias):
Skip loading of project-local ignore files (include VCS ignore files). By default, watchexec loads .ignore, .gitignore, .hgignore, and other such files in the current directory (or child directories as applicable) and uses them to filter change events.
The `--no-ignore` alias will be replaced by a new option in 2.0.0, beware!
* `--no-vcs-ignore`:
Skip loading of version control system (VCS) ignore files. By default, watchexec loads .gitignore, .hgignore, and other such files in the current directory (or child directories as applicable) and uses them to filter change events.
* `--project-origin` <path>:
Overrides the project origin, where ignore files are resolved from (see [PATHS] section below).
* `-w`, `--watch` <path>:
Monitor a specific path for changes. By default, the current working directory is watched. This may be specified multiple times, where a change in any watched directory (and subdirectories) causes <command> to be executed.
### Behaviour options
* `-d`, `--debounce`:
Set the timeout between detected change and command execution, to avoid restarting too frequently when there are many events; defaults to 100ms.
* `--force-poll` <interval>:
Poll for changes every <interval> ms instead of using system-specific notification mechanisms (such as inotify). This is useful when you are monitoring NFS shares.
* `-p`, `--postpone`:
Postpone execution of <command> until the first file modification is detected.
* `-r`, `--restart`:
Terminates the command if it is still running when subsequent file modifications are detected. By default, sends `SIGTERM`; use `--signal` to change that.
* `-s`, `--signal`:
Sends the specified signal (e.g. `SIGKILL`) to the command. Defaults to `SIGTERM`.
* `--stdin-quit`:
Exit when watchexec's stdin is closed. This is useful when watchexec is run as a subprocess and should shut itself down when the parent process stops.
* `-W`, `--watch-when-idle`:
Ignore events while the process is still running. This is distinct from `--restart` in that with this option, events received while the command is running will not trigger a new run immediately after the current command is done.
This behaviour will become the default in v2.0.
### Output options
* `-c`, `--clear`:
Clears the screen before executing <command>.
* `-N`, `--notify`:
Sends desktop notifications on command start and command end.
### Debugging options
* `--print-events`, `--changes-only` (deprecated alias):
Prints the events (changed paths, etc) that have triggered an action to STDERR.
* `-v`, `--verbose`, `-vv`, etc:
Prints diagnostic and debugging messages to STDERR. Increase the amount of `v`s to get progressively more output: for bug reports use **three**, and for deep debugging **four** can be helpful.
* `--log-file` <path>:
Writes diagnostic and debugging messages (from the `-v` options) to file instead of STDERR, in JSON format. This is preferrable for reporting bugs. Be careful **not** to write to a file within the purview of Watchexec to avoid recursion!
* `-V`, `--version`:
Print the version of watchexec.
* `-h`, `--help`:
Print a help message.
## PATHS
By default, Watchexec watches the current directory. This can be changed with the `--watch` option, which can be passed multiple times.
Upon starting, Watchexec resolves a "project origin" from the watched paths. To do so, it recurses up every parent directory from each watched path, looking for file and directory patterns which indicate a project origin among many different software systems, such as a Git repo, Cargo crate, licensing files, readmes, workspace configuration, etc. For the full current list, consult the source at `lib/src/project.rs`.
Once it has a list of "potential project origins", it resolves the common prefix they all have, and uses this as the overall project origin. Note that the home directory is excluded from potential origins unless it's explicitly requested as a watched path.
The overall project origin is used to find and resolve ignore files, such that in most cases it acts as one would expect for a tool that runs anywhere inside a project.
For this reason, it is not recommended to use Watchexec for watching disparate folders in a filesystem, where those would resolve to a too-broad project origin.
The project origin can be overridden with the `--project-origin` option.
## ENVIRONMENT
In variables that contain lists of paths, the separator is as for the `$PATH` environment variable (a colon, or semicolon on Windows).
### Set on child processes
Processes started by watchexec have environment variables set describing the changes observed.
`$WATCHEXEC_COMMON_PATH` is set to the longest common path of all of the below variables, and so should be prepended to each path to obtain the full/real path. Then:
- `$WATCHEXEC_CREATED_PATH` is set when files/folders were created
- `$WATCHEXEC_REMOVED_PATH` is set when files/folders were removed
- `$WATCHEXEC_RENAMED_PATH` is set when files/folders were renamed
- `$WATCHEXEC_WRITTEN_PATH` is set when files/folders were modified
- `$WATCHEXEC_META_CHANGED_PATH` is set when files/folders' metadata were modified
- `$WATCHEXEC_OTHERWISE_CHANGED_PATH` is set for every other kind of pathed event
These variables may contain multiple paths: these are separated by the platform's path separator, as with the `PATH` system environment variable. On Unix that is `:`, and on Windows `;`. Within each variable, paths are deduplicated and sorted in binary order (i.e. neither Unicode nor locale aware).
One thing to take care of is assuming inherent behaviour where there is only chance. Notably, it could appear as if the `RENAMED` variable contains both the original and the new path being renamed. In previous versions, it would even appear on some platforms as if the original always came before the new. However, none of this was true. It's impossible to reliably and portably know which changed path is the old or new, "half" renames may appear (only the original, only the new), "unknown" renames may appear (change was a rename, but whether it was the old or new isn't known), rename events might split across two debouncing boundaries, and so on.
This variable group can be disabled or limited with `--no-environment` (doesn't set any of these variables) and `--no-meta` (ignores metadata changes).
### Read upon startup
- `$WATCHEXEC_FILTERER`: select the filterer implementation: `globset` (default), or `tagged` (experimental).
- `$WATCHEXEC_IGNORE_FILES`: a list of paths to additional ignore files to be loaded.
- `$WATCHEXEC_FILTER_FILES`: a list of paths to additional "Tagged" filter files to be loaded (when enabled).
- `$RUST_LOG`: use for advanced verbose logging configuration. Refer to tracing-subscriber for documentation.
## FILES
### Supported project ignore files
- Git: `.gitignore` at project root and child directories, `.git/info/exclude`, and the file pointed to by `core.excludesFile` in `.git/config`.
- Mercurial: `.hgignore` at project root and child directories.
- Bazaar: `.bzrignore` at project root.
- Darcs: `_darcs/prefs/boring`
- Fossil: `.fossil-settings/ignore-glob`
- Ripgrep/Watchexec/generic: `.ignore` at project root and child directories.
Note that VCS ignore files (Git, Mercurial, Bazaar, Darcs, Fossil) are only used if the corresponding VCS is discovered to be in use for the project/origin. For example, a `.bzrignore` in a Git repository will be discarded.
### Supported global ignore files
- Git (if core.excludesFile is set): the file at that path
- Git (otherwise): the first found of `$XDG_CONFIG_HOME/git/ignore`, `%APPDATA%/.gitignore`, `%USERPROFILE%/.gitignore`, `$HOME/.config/git/ignore`, `$HOME/.gitignore`.
- Bazaar: the first found of `%APPDATA%/Bazzar/2.0/ignore`, `$HOME/.bazaar/ignore`.
- Watchexec: the first found of `$XDG_CONFIG_HOME/watchexec/ignore`, `%APPDATA%/watchexec/ignore`, `%USERPROFILE%/.watchexec/ignore`, `$HOME/.watchexec/ignore`.
Note that like for project files, Git and Bazaar global files will only be used for the corresponding VCS as used in the project.
## EXAMPLES
Rebuild a project when source files change:
$ watchexec make
Watch all HTML, CSS, and JavaScript files for changes:
$ watchexec -e html,css,js make
Run tests when source files change, clearing the screen each time:
$ watchexec -c make test
Launch and restart a node.js server:
$ watchexec -r node app.js
Watch lib and src directories for changes, rebuilding each time:
$ watchexec -w lib -w src make
Use without shell:
$ watchexec -n -- zsh -x -o shwordsplit scr
Use with powershell (default on windows from 2.0):
$ watchexec --shell=powershell -- test-connection localhost
Use with cmd (default on windows until 2.0):
$ watchexec --shell=cmd -- dir
Use with a different unix shell:
$ watchexec --shell=bash -- 'echo $BASH_VERSION'
Use with a unix shell and options:
$ watchexec --shell='zsh -x -o shwordsplit' -- scr