Code Monkey home page Code Monkey logo

cargo-watch's Introduction

$ cargo watch

Crate release version Crate license: CC0 1.0 Crate download count CI status

Cargo Watch watches over your project's source for changes, and runs Cargo commands when they occur.

If you've used nodemon, guard, or entr, it will probably feel familiar.

  • In the public domain / licensed with CC0.
  • Minimum Supported Rust Version: 1.70.0.
    • Only the last five stable versions are supported.
    • MSRV increases beyond that range at publish time will not incur major version bumps.

Install

Packaging status

With cargo-binstall:

$ cargo binstall cargo-watch

From source:

$ cargo install cargo-watch

Or clone and build with $ cargo build then place in your $PATH.

You can also install from the pre-built binaries available on the release page.

Auxiliary

This repository contains a manual page and Zsh completions that you may want to install.

Usage

By default, it runs check. You can easily override this, though:

$ cargo watch [-x command]...

A few examples:

# Run tests only
$ cargo watch -x test

# Run check then tests
$ cargo watch -x check -x test

# Run run with arguments
$ cargo watch -x 'run -- --some-arg'

# Run an arbitrary command
$ cargo watch -- echo Hello world

# Run with features passed to cargo
$ cargo watch --features "foo,bar"

There's a lot more you can do! Here's a copy of the help:

USAGE:
    cargo watch [FLAGS] [OPTIONS]

FLAGS:
    -c, --clear              Clear the screen before each run
    -h, --help               Display this message
        --ignore-nothing     Ignore nothing, not even target/ and .git/
        --debug              Show debug output
        --why                Show paths that changed
    -q, --quiet              Suppress output from cargo-watch itself
        --no-vcs-ignores       Don’t use .gitignore files
        --no-dot-ignores          Don’t use .ignore files
        --no-restart         Don’t restart command while it’s still running
    -N, --notify             Send a desktop notification when watchexec notices a change
                             (experimental, behaviour may change)
        --poll               Force use of polling for file changes
        --postpone           Postpone first run until a file changes
        --skip-local-deps    Don't try to find local dependencies of the current crate and watch
                             their working directories. Only watch the current directory.
    -V, --version            Display version information
        --watch-when-idle    Ignore events emitted while the commands run.

OPTIONS:
    -x, --exec <cmd>...            Cargo command(s) to execute on changes [default: check]
    -s, --shell <cmd>...           Shell command(s) to execute on changes
    -d, --delay <delay>            File updates debounce delay in seconds [default: 0.5]
        --features <features>      List of features passed to cargo invocations
    -i, --ignore <pattern>...      Ignore a glob/gitignore-style pattern
    -B <rust-backtrace>            Inject RUST_BACKTRACE=VALUE (generally you want to set it to 1)
                                   into the environment
        --use-shell <use-shell>    Use a different shell. E.g. --use-shell=bash
    -w, --watch <watch>...         Watch specific file(s) or folder(s). Disables finding and
                                   watching local dependencies.
    -C, --workdir <workdir>        Change working directory before running command [default: crate
                                   root]

ARGS:
    <cmd:trail>...    Full command to run. -x and -s will be ignored!

Cargo commands (-x) are always executed before shell commands (-s). You can use the `-- command`
style instead, note you'll need to use full commands, it won't prefix `cargo` for you.

By default, the workspace directories of your project and all local dependencies are watched,
except for the target/ and .git/ folders. Your .ignore and .gitignore files are used to filter
paths.

On Windows, patterns given to -i have forward slashes (/) automatically
converted to backward ones (\) to ease command portability.

Ignore files

.gitignore files are used by default to ignore paths to watch and trigger runs. To stop honouring them, pass --no-vcs-ignores.

.ignore files in the same syntax are also used by default. This file can be used to specify files that should be ignored by cargo watch but checked into git, without constantly adding --ignore abc options on the command-line. Do note that .ignore files may also be used by other programs, like ripgrep. To stop honouring these, pass --no-dot-ignores.

Cargo watch also has an internal list of default ignores on top of those specified in files, like target/ and .git/ and various other common types (logs, editor swap files, lockfiles, etc).

To skip absolutely all ignores, use the --ignore-nothing flag.

.git/info/exclude and the global $HOME/.gitignore and similar ignore files are not supported yet.

Ignore syntax

See the Glob patterns page for a description of how they work in the context of this tool. That’s the syntax used for the --ignore option.

Additionally, some specific quirks and behaviours:

  • On Windows, patterns should be specified with Windows-style (\\) separators. Unix-style separators (/) would not match Windows paths, which could be confusing and give the appearance of commandline ignores not working.

  • From Cargo Watch 7.0.0, / in commandline ignores are automatically translated to \\ when running on Windows, but one should still try to write the correct patterns for the platform, as there may be more subtle differences.

  • From Cargo Watch 7.3.0, --ignore patterns were fixed to provide better experience with directory matching. Previously, ignoring a folder would need unyieldy -i folder/** patterns; now that is handled internally, and only -i folder is needed for the same effect.

Reloading servers seamlessly

Cargo Watch pairs very well with systemfd/Catflap, tools for Unixy platforms that lets one spawn a socket before the watcher runs that Rust servers can then bind to, avoiding request-dropping and the infamous ADDRINUSE error. For example:

$ systemfd --no-pid -s http::5000 -- cargo watch -x run

Of course, if you don't need to guard against these issues or don't want to modify your program to grab sockets instead of ports, you can use Cargo Watch as-is: it will happily just restart your server normally.

Restarting an application only if the build/check succeeds

Brought up by @LeDominik, here's a pattern that may be very useful: you're working on a server or app, but want it to keep running while you're writing a new feature or fixing a bug, potentially causing the code not to compile anymore in the meantime.

In this case, you can use this strategy: run a first cargo watch with check, build, test, or whatever you want, and append -s 'touch .trigger (or equivalent for your platform). Then, run a second cargo watch simultaneously that only watches that .trigger file. For example:

$ cargo watch -x check -s 'touch .trigger'

and

$ cargo watch --no-vcs-ignores -w .trigger -x run

The --no-vcs-ignores flag ensures that you can safely add .trigger to your .gitignore file to avoid mistakenly committing it.

Troubleshooting

In all cases, start by checking your version with cargo watch --version and, if necessary, upgrading to the latest one.

RLS is slow while using cargo watch, or vice versa, or it's waiting for the project lock a lot

Cargo builds (and checks, and clippy, and tests because the tests have to be built) take out a lock on the project so two cargo instances don't run at the same time.

However, Rust Analyzer is much better at this, so use that instead of RLS.

On Windows 7 (or lower): "failed to add to job object: Access denied (OS Error 5)"

Cargo Watch versions 5.0.0 and up (and Watchexec versions 1.3.0 and up) do not support Windows 7 or lower. Support will not be added. Issues for Windows <=7 will be closed. If it works, lucky you, but that is not intentional.

I want to run cargo-watch directly, without going through cargo

You can! But you'll have to specify the watch subcommand as the first argument, like so:

$ /path/to/cargo-watch watch -x build

I want to run cargo-watch outside of a Cargo project

That's not supported. If you have a good reason to use a Cargo-specific tool outside a Cargo project, please open an issue! Otherwise, you'll probably be best served with using Watchexec.

If file updates seems to never trigger

Try using --poll to force the polling fallback.

If that still doesn't work, and you're using an editor that does "safe saving", like IntelliJ / PyCharm, you may have to disable "safe saving" as that may prevent file notifications from being generated properly.

Also try using the --why option to see if the paths you expect are changing.

Linux: If it fails to watch some deep directories but not others / "No space left on device"

You may have hit the inotify watch limit. Here's a summary of what this means and how to increase it.

Docker: it's not responding correctly to signal or has trouble managing processes

Cargo Watch (and Watchexec underlying) does not currently support running as PID 1. It will probably work for basic uses, but you should consider using a supervisor, init, or shell to handle PID 1 concerns. With Docker, the --init option may be useful.

See watchexec#140 for more.

Docker: running cargo commands over a mount is very slow

This isn't really a Cargo Watch issue, but when your host system is not Linux, running commands from inside the container on a volume or bind mount from the host will perform very badly due to filesystem indirection. Consider building outside the mount if possible:

# ...
RUN mkdir -p /build
WORKDIR `/src`
ENTRYPOINT cargo watch -C /build --manifest-path=/src/Cargo.toml -- cargo run

Or similarly with CARGO_TARGET_DIR.

# ...
RUN mkdir -p /build
WORKDIR `/src`
ENV CARGO_TARGET_DIR=/build
ENTRYPOINT cargo watch -- cargo run

You may also have issues where it's the file updates that aren't triggering in a timely manner, not the compilation taking a long time. In that case, you should run Cargo Watch or Watchexec outside of Docker, on the host, and signal the container for restart or reload.

If you want to only recompile one Cargo workspace member crate

Watching one or more specific workspace member is not natively supported yet, although you can use -w folder to approximate it.

Watching the entire workspace and running a command in one member is done via the usual -p option on the child command:

$ cargo watch -x 'build -p subcrate'

If it runs repeatedly without touching anything

That can happen when watching files that are modified by the command you're running.

If you're only running compiles or checks (i.e. any command that only affects the target/ folder) and you're using -w, you might be confusing the target-folder-ignorer. Check your options and paths.

You can also use the --watch-when-idle flag to ignore any event that happens while the command is running.

If it runs repeatedly only touching ignored files

Make sure the files you ignored are the only ones being touched. Use the --why option to see exactly which files were modified and triggered the restart. Some programs and libraries create temporary files that may not match a simple ignore pattern.

As above, you can also use the --watch-when-idle flag to help.

I don't have colour in my cargo output / for cargo test

This sometimes happens on some terminal configurations or for test harnesses. A quick workaround (instead of going down the rabbit hole of debugging your console settings) is to pass --color=always to the command. E.g.

$ cargo watch -x 'check --color=always'

For test (and bench) commands, you'll need to pass the flag to the underlying program instead of cargo:

$ cargo watch -x 'test -- --color=always'

I want to compile my build with additional features

$ cargo watch --features foo,bar

will run cargo check --features foo,bar on every watched change.

The --features will be passed to every supported cargo subcommand.

$ cargo watch --features foo,bar -x build -x doc

will run both build and doc with the foo and bar features.

Something not covered above / I have a feature request

Please open an issue, or look through the existing ones. You may also want to look through issues for the Notify library this tool depends on, or the issues for the Watchexec tool that we use under the covers (where I am also a maintainer).

If you want more verbose output, try running with the --debug flag. Note that this will also enable debug mode for watchexec. When filing an issue, make sure to include a log with --debug enabled so problems can be diagnosed.

If your issue is a watchexec issue, open it there directly. If you're not sure, feel free to open it here, but if it is a watchexec issue, it will get closed in favour of the upstream issue.

I want to embed Cargo Watch in my own (Rust) tool

It is not recommended to do that directly. You may of course call cargo-watch as any other program, and technically it exposes an (undocumented) library that could be directly / statically embedded. If you have no other option, that may be your best bet.

However, for most cases, consider building on top of Watchexec instead. That is itself built on Notify, and both of these can be used as Rust libraries.

  • If you want to build a tool that runs, restarts, and otherwise manages commands in response to file changes, you'll most probably want to use Watchexec.

  • If you want to build a tool that responds to file changes, but does not need to run commands, or does so in a way that is not well-supported by Watchexec, then Notify is your ticket.

Wait, is this just a wrapper on top of watchexec?

Kind of! Watchexec does a really good job of watching files and running commands and all the details that go with this. Cargo Watch uses the Watchexec library interface and calls it with its own custom options, defaults, and particularities, so you can just run cargo-watch in your project and be in business.

When asking questions and/or filing bugs, keep in mind that Cargo Watch and Watchexec share the same maintainer at the moment (but Notify does not, anymore)!

About

Created by Félix Saparelli and awesome contributors.

cargo-watch's People

Contributors

aigeruth avatar aij avatar blei avatar bruceg avatar compressed avatar coolreader18 avatar dependabot[bot] avatar detegr avatar dywedir avatar infogulch avatar irevoire avatar jmgao avatar justanotherdot avatar kstep avatar lpil avatar lukaskalbertodt avatar mhlyv avatar mulimoen avatar neuschaefer avatar ordovicia avatar passcod avatar paulkernfeld avatar piggynl avatar rimbi avatar robinst avatar ruipserra avatar senden9 avatar spiralp avatar tanriol avatar waynr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cargo-watch's Issues

Error: could not rename dep info

Hello, I'm using cargo-watch for recompiling a little project (less tan 100 LOC). When I use the command cargo watch run it show that one error occurred. If I run cargo watch "run --verbose" it shows this:

cargo watch "run --verbose"
Waiting for changes... Hit Ctrl-C to stop.

$ cargo run --verbose
       Fresh winapi v0.2.5
       Fresh httparse v1.1.1
       Fresh libc v0.2.7
       Fresh regex-syntax v0.2.3
       Fresh byteorder v0.4.2
       Fresh bitflags v0.3.3
       Fresh rustc-serialize v0.3.18
       Fresh matches v0.1.2
       Fresh winapi-build v0.1.1
       Fresh cfg-if v0.1.0
       Fresh memchr v0.1.10
       Fresh log v0.3.5
       Fresh sha1 v0.1.1
       Fresh bytes v0.3.0
       Fresh utf8-ranges v0.1.3
       Fresh unicode-bidi v0.2.3
       Fresh aho-corasick v0.5.1
       Fresh unicode-normalization v0.1.2
       Fresh rand v0.3.14
       Fresh slab v0.1.3
       Fresh libc v0.1.12
       Fresh regex v0.1.52
       Fresh uuid v0.1.18
       Fresh nix v0.4.2
       Fresh kernel32-sys v0.2.1
       Fresh ws2_32-sys v0.2.1
       Fresh env_logger v0.3.2
       Fresh url v0.5.5
       Fresh time v0.1.34
       Fresh net2 v0.2.21
       Fresh miow v0.1.2
       Fresh mio v0.5.0
       Fresh ws v0.4.5
   Compiling rust-ws-test v0.1.0 (file:///home/david/repositorios/rust-ws-test)
     Running `rustc src/main.rs --crate-name rust_ws_test --crate-type bin -g --out-dir /home/david/repositorios/rust-ws-test/target/debug --emit=dep-info,link -L dependency=/home/david/repositorios/rust-ws-test/target/debug -L dependency=/home/david/repositorios/rust-ws-test/target/debug/deps --extern env_logger=/home/david/repositorios/rust-ws-test/target/debug/deps/libenv_logger-2fedde90a22290a6.rlib --extern uuid=/home/david/repositorios/rust-ws-test/target/debug/deps/libuuid-fed17b74aa7673e2.rlib --extern rustc_serialize=/home/david/repositorios/rust-ws-test/target/debug/deps/librustc_serialize-79a17eda1cd94e46.rlib --extern ws=/home/david/repositorios/rust-ws-test/target/debug/deps/libws-300ac8c32d0f3ece.rlib`
could not rename dep info: "/home/david/repositorios/rust-ws-test/target/debug/rust_ws_test.d"

Caused by:
  No such file or directory (os error 2)
-> exit code: 101

Is I use the command cargo run --verbose the program compiles normally and this is the output:

       Fresh matches v0.1.2
       Fresh winapi-build v0.1.1
       Fresh bytes v0.3.0
       Fresh rustc-serialize v0.3.18
       Fresh slab v0.1.3
       Fresh byteorder v0.4.2
       Fresh unicode-normalization v0.1.2
       Fresh bitflags v0.3.3
       Fresh unicode-bidi v0.2.3
       Fresh httparse v1.1.1
       Fresh libc v0.2.7
       Fresh regex-syntax v0.2.3
       Fresh libc v0.1.12
       Fresh winapi v0.2.5
       Fresh cfg-if v0.1.0
       Fresh sha1 v0.1.1
       Fresh log v0.3.5
       Fresh memchr v0.1.10
       Fresh nix v0.4.2
       Fresh rand v0.3.14
       Fresh utf8-ranges v0.1.3
       Fresh kernel32-sys v0.2.1
       Fresh aho-corasick v0.5.1
       Fresh ws2_32-sys v0.2.1
       Fresh uuid v0.1.18
       Fresh time v0.1.34
       Fresh regex v0.1.52
       Fresh net2 v0.2.21
       Fresh url v0.5.5
       Fresh env_logger v0.3.2
       Fresh miow v0.1.2
       Fresh mio v0.5.0
       Fresh ws v0.4.5
   Compiling rust-ws-test v0.1.0 (file:///home/david/repositorios/rust-ws-test)
     Running `rustc src/main.rs --crate-name rust_ws_test --crate-type bin -g --out-dir /home/david/repositorios/rust-ws-test/target/debug --emit=dep-info,link -L dependency=/home/david/repositorios/rust-ws-test/target/debug -L dependency=/home/david/repositorios/rust-ws-test/target/debug/deps --extern ws=/home/david/repositorios/rust-ws-test/target/debug/deps/libws-300ac8c32d0f3ece.rlib --extern uuid=/home/david/repositorios/rust-ws-test/target/debug/deps/libuuid-fed17b74aa7673e2.rlib --extern rustc_serialize=/home/david/repositorios/rust-ws-test/target/debug/deps/librustc_serialize-79a17eda1cd94e46.rlib --extern env_logger=/home/david/repositorios/rust-ws-test/target/debug/deps/libenv_logger-2fedde90a22290a6.rlib`
     Running `target/debug/rust-ws-test`

Cargo check

The default should probably be changed to run cargo check on Rust 1.17+.

Error building on mac

output from cargo build --verbose

   Compiling gcc v0.1.2
     Running `rustc /Users/reem/.cargo/registry/src/github.com-1ecc6299db9ec823/gcc-0.1.2/src/lib.rs --crate-name gcc --crate-type lib -g -C metadata=165e603132fd5f7c -C extra-filename=-165e603132fd5f7c --out-dir /Users/reem/code/rust/cargo-watch/target/deps --dep-info /Users/reem/code/rust/cargo-watch/target/.fingerprint/gcc-165e603132fd5f7c/dep-lib-gcc -L /Users/reem/code/rust/cargo-watch/target/deps -L /Users/reem/code/rust/cargo-watch/target/deps -Awarnings`
   Compiling time v0.1.3
     Running `rustc build.rs --crate-name build-script-build --crate-type bin -C prefer-dynamic -g --out-dir /Users/reem/code/rust/cargo-watch/target/build/time-ebf8a3b3c11a2cc2 --dep-info /Users/reem/code/rust/cargo-watch/target/.fingerprint/time-ebf8a3b3c11a2cc2/dep-bin-build-script-build -L /Users/reem/code/rust/cargo-watch/target/deps -L /Users/reem/code/rust/cargo-watch/target/deps --extern gcc=/Users/reem/code/rust/cargo-watch/target/deps/libgcc-165e603132fd5f7c.rlib -Awarnings`
     Running `/Users/reem/code/rust/cargo-watch/target/build/time-ebf8a3b3c11a2cc2/build-script-build`
     Running `rustc /Users/reem/.cargo/registry/src/github.com-1ecc6299db9ec823/time-0.1.3/src/lib.rs --crate-name time --crate-type lib -g -C metadata=ebf8a3b3c11a2cc2 -C extra-filename=-ebf8a3b3c11a2cc2 --out-dir /Users/reem/code/rust/cargo-watch/target/deps --dep-info /Users/reem/code/rust/cargo-watch/target/.fingerprint/time-ebf8a3b3c11a2cc2/dep-lib-time -L /Users/reem/code/rust/cargo-watch/target/deps -L /Users/reem/code/rust/cargo-watch/target/deps -Awarnings -L /Users/reem/code/rust/cargo-watch/target/build/time-ebf8a3b3c11a2cc2/out -l time_helpers:static`
   Compiling notify v1.0.1 (https://github.com/passcod/rsnotify.git#f14e83f3)
     Running `rustc /Users/reem/.cargo/git/checkouts/rsnotify-1f201f3fca9ce0e6/master/src/lib.rs --crate-name notify --crate-type lib -g -C metadata=2554c189493a63c9 -C extra-filename=-2554c189493a63c9 --out-dir /Users/reem/code/rust/cargo-watch/target/deps --dep-info /Users/reem/code/rust/cargo-watch/target/.fingerprint/notify-2554c189493a63c9/dep-lib-notify -L /Users/reem/code/rust/cargo-watch/target/deps -L /Users/reem/code/rust/cargo-watch/target/deps --extern time=/Users/reem/code/rust/cargo-watch/target/deps/libtime-ebf8a3b3c11a2cc2.rlib -Awarnings -L /Users/reem/code/rust/cargo-watch/target/build/time-ebf8a3b3c11a2cc2/out`
/Users/reem/.cargo/git/checkouts/rsnotify-1f201f3fca9ce0e6/master/src/lib.rs:6:9: 6:16 error: unresolved import `self::inotify::INotifyWatcher`. Maybe a missing `extern crate inotify`?
/Users/reem/.cargo/git/checkouts/rsnotify-1f201f3fca9ce0e6/master/src/lib.rs:6 pub use self::inotify::INotifyWatcher;
                                                                                       ^~~~~~~
error: aborting due to previous error
Could not compile `notify`.

Caused by:
  Process didn't exit successfully: `rustc /Users/reem/.cargo/git/checkouts/rsnotify-1f201f3fca9ce0e6/master/src/lib.rs --crate-name notify --crate-type lib -g -C metadata=2554c189493a63c9 -C extra-filename=-2554c189493a63c9 --out-dir /Users/reem/code/rust/cargo-watch/target/deps --dep-info /Users/reem/code/rust/cargo-watch/target/.fingerprint/notify-2554c189493a63c9/dep-lib-notify -L /Users/reem/code/rust/cargo-watch/target/deps -L /Users/reem/code/rust/cargo-watch/target/deps --extern time=/Users/reem/code/rust/cargo-watch/target/deps/libtime-ebf8a3b3c11a2cc2.rlib -Awarnings -L /Users/reem/code/rust/cargo-watch/target/build/time-ebf8a3b3c11a2cc2/out` (status=101)

rustc --version=verbose output

rustc 0.13.0-nightly (99d6956c3 2014-12-18 20:32:07 +0000)
binary: rustc
commit-hash: 99d6956c3bdb290b9fd539c5dc15a2b502da5e7a
commit-date: 2014-12-18 20:32:07 +0000
host: x86_64-apple-darwin
release: 0.13.0-nightly

"There is no `AsOsStr` in `std::ffi`" when building

cargo build gives There is no 'AsOsStr' in 'std::ffi':

cargo build
    Updating registry `https://github.com/rust-lang/crates.io-index`
 Downloading libc v0.1.5
 Downloading docopt v0.6.59
 Downloading regex v0.1.26
 Downloading time v0.1.24
 Downloading inotify v0.1.9
 Downloading rustc-serialize v0.3.12
 Downloading gcc v0.3.4
 Downloading docopt_macros v0.6.59
 Downloading notify v1.2.1
   Compiling inotify v0.1.9
   Compiling rustc-serialize v0.3.12
   Compiling time v0.1.24
error: invalid character `-` in crate name: `build-script-build`
error: invalid character `-` in crate name: `build-script-build`
error: aborting due to 2 previous errors
Build failed, waiting for other jobs to finish...
/home/miguel/.cargo/registry/src/github.com-1ecc6299db9ec823/inotify-0.1.9/src/wrapper.rs:23:5: 23:22 error: unresolved import `std::ffi::AsOsStr`. There is no `AsOsStr` in `std::ffi`
/home/miguel/.cargo/registry/src/github.com-1ecc6299db9ec823/inotify-0.1.9/src/wrapper.rs:23 use std::ffi::AsOsStr;
                                                                                                 ^~~~~~~~~~~~~~~~~
error: aborting due to previous error
error: invalid character `-` in crate name: `rustc-serialize`
error: aborting due to previous error
Could not compile `time`.

I am brand new on both Rust and Cargo but it seems AsOsStr has vanished from latest Rust

cargo 0.0.1-pre-nightly (66849de 2015-03-10) (built 2015-03-11)
rustc 1.0.0-dev (built 2015-04-27)

Desktop notifications

Guard can integrate with desktop notification systems (libnotify, growl, etc). Please consider adding this feature to cargo-watch.

rust-libnotify seems reasonably high-quality to me.

Request: Watch anything

One thing I like a lot about nodemon is you can use it with any project (by passing it a command option, obviously). cargo-watch accepts arbitrary commands, but throws an error when you try to use it in a non-rust project.

Add support for ~/.gitignore

When respecting gitignore files to not watch, the current implementation only looks at the local .gitignore file, but not other ones that git itself recognizes, specially ~/.gitignore.

The best and common practice to gitignore editor temp files is to put the patters in ~/.gitignore, as they are something user-dependent and not project-dependent (and its hard for projects to stay inclusive to all types of editors and their settings).

Because of this, right now, when using cargo watch, I get a new execution whenever I open/close my editors (VIM), which is very often, because of the .*.swp files being created and dropped.

Additional maintainers

This is mostly piggy-backing on notify-rs/notify#24. I'm going on holiday and am generally not very present on here anymore (something I hope to change! but that won't be soon). If someone feels up to the task of getting commit rights and crates.io publish rights for Cargo Watch, please step forward.

Support for workspaces

Consider adding support to use cargo watch in a workspace project.

You can see with cargo +nightly build --help the kind of options for workspace projects.

Cargo watch never triggers on OS X El Capitan

I'm new to Rust, so I'm probably doing something stupid. I installed by running cargo install cargo-watch.

When I run cargo watch and edit a file, tests don't seem to run. It just says Waiting for changes... Hit Ctrl-C to stop. and nothing seems to happen after that.

paul ~/projects/iron master $ ls src/ && cargo watch &
main.rs
[1]+ running: cargo watch & & (2635)
paul ~/projects/iron master $ echo "" >> src/main.rs
paul ~/projects/iron master $ fg
[1]+ running: cargo watch & (2635)
Waiting for changes... Hit Ctrl-C to stop.
^C

cannot compile because notify-v2.3.1 cannot be compiled.

I have tried to get cargo-watch to work on my own and have had no luck.

I am new to rust, so forgive me if there is something obvious that I have missed.

I cloned cargo-watch and altered nothing:

ken@ken-desktop:/share/development/rust/cargo-watch$ git status
# On branch master
nothing to commit (working directory clean)

and tried a default cargo build, even a release build, and still produced the same results:

...
/home/ken/.cargo/registry/src/github.com-121aea75f9ef2ce2/notify-2.3.1/src/inotify/mod.rs:1:1: 1:37 error: can't find crate for `inotify_sys`
/home/ken/.cargo/registry/src/github.com-121aea75f9ef2ce2/notify-2.3.1/src/inotify/mod.rs:1 extern crate inotify as inotify_sys;
                                                                                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `notify`.

Not compiling when module is saved

When I'm editing files in a module and click save my intentions are to compile, however rust-watch is not compiling. I have to go into lib.rs or a bin file and save before it compiles.

Is this intended functionality or a bug?

"Bad file descriptor" error on windows 10 bash subsystem

Running cargo watch on the ubuntu bash subsystem of windows 10 results in the following error:

> cargo watch
ERROR:cargo_watch: Failed to init notify (Io(Error { repr: Os { code: 9, message: "Bad file descriptor" } }))

Does this mean anything to you?

Run multiple commands?

Sometimes it is useful to run multiple commands. For example, doc and test (to make sure the doctests still work). Is there a good way to do this?

Running multiple instances of cargo watch in different terminals doesn't work, because they interfere with each other.

Running arbitrary cargo commands

Sometimes I would like to run cargo run when the code changes.

How about changing the command line interface in the following way?

  • Allow commands such as cargo watch run --example foo1 bar baz by simply running the appropriate cargo subcommand.
  • Possibly remove direct options other than --help.

I don't know how to do this with docopt.

Error trying to check status of job, abort.

I ran
cargo watch -x build
The first build ran just fine, the next time I saved the file I got:

sum-of-multiples - master! ❯ cargo watch -x build
[Watching for changes... Ctrl-C to stop]
[Running 'cargo build']
   Compiling sum-of-multiples v0.0.0 (file:///home/evan/personal/exercism/rust/sum-of-multiples)
error: no method named `iter` found for type `T` in the current scope
  --> src/lib.rs:39:19
   |
39 |     for i in iter.iter() {
   |                   ^^^^
   |
   = help: items from traits can only be used if the trait is implemented and in scope; the following trait defines an item `iter`, perhaps you need to implement it:
   = help: candidate #1: `core::slice::SliceExt`

error: aborting due to previous error

error: Could not compile `sum-of-multiples`.

To learn more, run the command again with --verbose.
ERROR:cargo_watch::schedule: Error trying to check status of job, abort.
ERROR:cargo_watch::schedule: command ["/bin/sh", "-c", "cargo build"] exited with code 101

Dupplicated build with vim

Sometimes, instead of sunning the build command one time, wargo-watch run it multiple times. I can't really find why, except that sometime touch src/lib.rs builds one time and vim src/lib.rs builds two. Maybe it's something like vim that saves then touch or something like that, or a race condition in the scheduler loop.

Fix lock behaviour

Current behaviour: "Don't start compiles within 2 seconds of start of current compile."
Intended behaviour: "Don't start compiles while current one is running."

Might also want to:

  • wait until watched directory has "settled";
  • forbid compiles to run within N seconds of each other (end1 -> start2), to avoid compiling too often when in the habit of saving compulsively (configurable, behind a flag);

thread '<unnamed>' panicked at 'internal error: entered unreachable code', ../src/libstd/sync/mpsc/mod.rs:565

Hi,
works on Linux (Ubuntu) but in in MacOS I get error (rustc 1.4.0 (8ab8581f6 2015-10-27)) :
"thread '' panicked at 'internal error: entered unreachable code', ../src/libstd/sync/mpsc/mod.rs:565"

I though this is fixed by:
rust-lang/rust#29201
notify-rs/notify#33

I have updated Cargo.toml build dependencies like:
notify = { git = "https://github.com/passcod/rsnotify.git", rev = "5a48333dde58a01f68c1e6" }
rebuild crate, but get the same issue...

Thanks, Thomas

How to restart long-running process when file changed?

I'm writting a HTTP API server and use cargo-watch to auto re-compile, a simple 'cargo watch test run' does not restart the previous running process but try to start a new process of my program.

Is there any other way to achive the desired effect besides of patching cargo-watch?

Panic when running cargo watch

I installed cargo-watch using cargo install ... and when I try to run it, it panics trying to unwrap a Result. On a mac, Mac OS X Yosemite.

Backtrace:

✗ RUST_BACKTRACE=1 cargo watch
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { repr: Os { code: 2, message: "No such file or directory" } }', ../src/libcore/result.rs:799
stack backtrace:
   1:        0x10fb4a1a8 - std::sys::backtrace::tracing::imp::write::h6f1d53a70916b90d
   2:        0x10fb4e6ff - std::panicking::default_hook::{{closure}}::h137e876f7d3b5850
   3:        0x10fb4d705 - std::panicking::default_hook::h0ac3811ec7cee78c
   4:        0x10fb4dd16 - std::panicking::rust_panic_with_hook::hc303199e04562edf
   5:        0x10fb4dbb4 - std::panicking::begin_panic::h6ed03353807cf54d
   6:        0x10fb4dad2 - std::panicking::begin_panic_fmt::hc321cece241bb2f5
   7:        0x10fb4da37 - rust_begin_unwind
   8:        0x10fb73f60 - core::panicking::panic_fmt::h27224b181f9f037f
   9:        0x10fa90320 - core::result::unwrap_failed::hbbe45964de00535c
  10:        0x10fa9db9d - cargo_watch::main::hd1e92082f03362ed
  11:        0x10fb4ecba - __rust_maybe_catch_panic
  12:        0x10fb4d246 - std::rt::lang_start::h538f8960e7644c80

Clean screen before run

Hi guys,

The rust compiler is very ...talkative.

It would be awesome to add a --clean-screen flag to cargo watch, to clear the screen before compiling and running the Rust program.

warning "unused import" in main.rs

I just installed it on latest stable Rust and got this:

.cargo/registry/src/github.com-88ac128001ac3a9a/cargo-watch-3.1.0/src/main.rs:17:14: 17:19 warning: unused import, #[warn(unused_imports)] on by default
.cargo/registry/src/github.com-88ac128001ac3a9a/cargo-watch-3.1.0/src/main.rs:17 use notify::{Error, RecommendedWatcher, Watcher};

I am not sure if this is just on my platform or on others too, or if this would break anything, so I'm filing an issue rather than sending a PR.

Ignore directories

This is more of a feature request than a pressing issue, but:

Would it be possible to set this to remove certain directories (particularly .git/) from the list of filesystem entities monitored to trigger re-execution of the watch command?

I've noticed that when I perform Git operations that don't affect the main working tree, like stage/unstage, this still causes filesystem events that trigger a re-execution despite the source files not having changed.

This is a fantastic tool and I absolutely love using it. Thanks so much for making it!

Show compile output in color.

I only see the output of cargo build without colors, which is a big drawback from calling cargo build directly. Any chance the colors can come back?

Option for clearing before build

It would be nice to have an optional command-line option for clearing the console before building.
So that on does not have to search for the beginning of the current output in the console.

workflow for server development

when building a server (eg: a webserver that listen on port 3000), it could be useful to automatically kill the already running server (after successful re-compilation) before starting the new one. otherwise, the server cannot start again because the old one still listen to the same port.

here is a log of what is going, if the server is not killed:

# run rshello cargo watch run
$ cargo run
   Compiling hello_world v0.0.1 (file:///app)
     Running `target/debug/hello_world`

$ cargo run
   Compiling hello_world v0.0.1 (file:///app)
     Running `target/debug/hello_world`
thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: Io(Error { repr: Os { code: 98, message: "Address already in use" } })', ../src/libcore/result.rs:738
Process didn't exit successfully: `target/debug/hello_world` (exit code: 101)
-> exit code: 101

$ cargo run
   Compiling hello_world v0.0.1 (file:///app)
     Running `target/debug/hello_world`
thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: Io(Error { repr: Os { code: 98, message: "Address already in use" } })', ../src/libcore/result.rs:738
Process didn't exit successfully: `target/debug/hello_world` (exit code: 101)

Tracking issue: trigger rerun on non-.rs-file changes

Changes of files, whose names do not end with .rs are currently ignored. Sometimes other files are expected to trigger a rerun of compilation. Two examples:

  • parser generators like lalrpop will generate .rs files from .lalrpop files that are in the source directory
  • sometimes arbitrary files are included via include_str! or something similar

Broken in Windows 10 cmd

If I run cargo watch from Git Bash in Windows 10, it runs successfully. It does seem to run more often than should be necessary, but perhaps that is the fault of my editor (VS Code).

If I run cargo watch from cmd in Windows 10, I see:

ERROR:cargo_watch::schedule: Couldn't start, waiting for file change
ERROR:cargo_watch::schedule: The system cannot find the file specified. (os error 2)

I get this message quite a few times, and never see any useful output. cargo build runs fine.

For now I will continue using Git Bash, but for some reason it does not support the syntax colouring in rustc's output, unlike cmd. Syntax colouring is also broken when I run cargo build, so that's not an issue introduced by cargo-watch.

Sometimes cargo-watch crashes when a test fails

I'm guessing that the desired behavior for cargo-watch is to keep running even if a test fails in a weird way. I've seen a few cases where cargo-watch crashes when a test fails.

From running cargo watch -x test, I see the following logs:

...
error: build failed
ERROR:cargo_watch::schedule: Error trying to check status of job, abort.
ERROR:cargo_watch::schedule: command ["/bin/sh", "-c", "cargo test"] exited with code 101

Watch isn't re-running

Cargo watch doesn't appear to be working. It will compile/run my code at first, but subsequent saves to the file or touching them from the cli doesn't trigger a recompile.

I'm trying out gtk-rs and it would be great to have cargo watch recompile and run my binary each time I save my file, so I can save time iterating on the view.

I'm on Linux.

>  ~/dev/rust/clientfile-rs/uploader-gtk [master] ⚡ cargo watch --version
cargo-watch 4.0.3
>  ~/dev/rust/clientfile-rs/uploader-gtk [master] ⚡ cargo watch -x run
[Watching for changes... Ctrl-C to stop]
[Running cargo run]
   Compiling uploader-gtk v0.1.0 (file:///home/leshow/dev/rust/clientfile-rs/uploader-gtk)
warning: unused imports: `CheckMenuItem`, `IconSize`, `Image`
 --> src/main.rs:8:30
  |
8 | use gtk::{Button, ButtonExt, CheckMenuItem, ContainerExt, IconSize, Image, Inhibit, Label, Menu,
  |                              ^^^^^^^^^^^^^                ^^^^^^^^  ^^^^^
  |
  = note: #[warn(unused_imports)] on by default

    Finished dev [unoptimized + debuginfo] target(s) in 1.89 secs
     Running `target/debug/uploader-gtk`

(.:14491): Gtk-WARNING **: Attempting to add a widget with type GtkBox to a container of type GtkWindow, but the widget is already inside a container of type GtkWindow, please remove the widget from its existing container first.
^C

Excessive rebuilds on Windows 10 in VS Code

A possible bug to fix, or perhaps just a note for your troubleshooting section:

I experienced excessive rebuilding (or rechecking) of files when I saved changes made in Visual Studio Code. It looks like it was caused by some kind of interaction between cargo-watch and the VS Code git integration.

If you don't need the editor's git integration, you can prevent this behaviour by adding "git.enabled": false to your VS Code settings file. This can be a global setting or a workspace setting.

Should it run the command upon start up, before any files are modified?

Proposal: When cargo watch starts, run the command, even if no file has changed.

I've often started cargo watch when started working on a project, and it clearly doesn't do anything until a file has changed. Sometimes I can't remember if all the tests passed (or if the code compiles), and I'd like to see the output of cargo test. So I need to make a simple change to something so that it'll run and I can see. But if cargo watch ran the command as soon as it was started, this would be easier.

But maybe that's my workflow, does this sound useful to other people?

Doesn't watch Cargo.toml

If I add a new dependency to my Cargo.toml file, cargo watch doesn't recompile my project. I would expect it to.

`cargo-watch.exe` exited unsuccessfully

cargo 0.10.0-nightly (25e1301 2016-03-25)
rustc 1.9.0-nightly (d5a91e695 2016-03-26)
cargo-watch v3.1.0

OS: Windows 10 Pro

If I run "cargo watch" i get

Argument 'will' is not of the form ARG or .
error: third party subcommand cargo-watch.exe exited unsuccessfully

Any hints how to solve this?

Thanks.
Michael

Single-command install / depend on watchexec automatically

To make v5 installable properly using the normal cargo install cargo-watch, we probably need to figure out how to either:

  • embed watchexec (preferred, as it will make sure we don't break if watchexec's interface changes)
  • install watchexec as a dependency

--version flag

Until cargo can update binaries, it would help detect if an update is needed.

Proposal: cargo-watch and listen

I am playing around with web development in Rust again and it turns out that cargo-watch is actually a good first place to support auto reloading web servers during development in some circumstances. The idea is that once #25 lands one could add a flag to cargo-watch that would spawn a listening TCP socket and then pass it in an environment variable to the process.

Basically something like this:

$ cargo watch --pass-listen-socket=127.0.0.1:5000 run

When pass-listen-socket is specified a new listen socket is created like this:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind('127.0.0.1', 5000)
s.listen(1)

And then passed to the subprocess in an environment variable:

CARGO_WATCH_LISTEN_FD=s.fileno()

Then web frameworks could pick up on it automatically like this:

use std::net::ToSocketAddrs;
use std::os::unix::io::{FromRawFd, RawFd};
use hyper::server::Server;
use hyper::net::HttpListener;

let server = env::var("CARGO_WATCH_LISTEN_FD").ok()
    .and_then(|x| x.parse().ok())
    .and_then(|fd| {
        let listener = unsafe {
            HttpListener::from_raw_fd(fd)
        };
        Some(Server::new(listener))
    })
    .or_else(|| {
        Some(Server::http(addr).unwrap())
    }).unwrap();

For Windows I'm not sure yet how to pass a handle to a subprocess but I'm sure there are ways as well.

`cargo watch --help` starts watching, and issues help when src files change

What I have done:

  • cd to my project dir with Cargo.toml
  • run cargo warch --help (as described in readme)

What I have got:

  • the cargo process is visibly hang up
  • when I modified my lib.rs and saved it in another terminal, the cargo process printed usage help and aborted

What I have expected to get:

  • the cargo process exists immediately, printing usage help

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.