### Build C++ Application with Watchman Client Source: https://github.com/facebook/watchman/blob/main/website/docs/cppclient.md Example of how to build a C++ application using the Watchman client library with GNU Make and pkg-config. Ensure Watchman is installed and pkg-config can find its package configuration files. ```bash make LDFLAGS=$(pkg-config watchmanclient --libs) CPPFLAGS=$(pkg-config watchmanclient --cflags) app ``` -------------------------------- ### Install Watchman Executable Source: https://github.com/facebook/watchman/blob/main/CMakeLists.txt Installs the watchman executable to the bin directory. ```cmake install(TARGETS watchman RUNTIME DESTINATION bin) ``` -------------------------------- ### Start Local Development Server Source: https://github.com/facebook/watchman/blob/main/website/README.md Starts a local development server and opens the project in a browser. Changes are reflected live without server restarts. ```bash $ yarn start ``` -------------------------------- ### Configure Watchman State Directory and Installation Source: https://github.com/facebook/watchman/blob/main/CMakeLists.txt Sets up the Watchman state directory, with options for installation and using XDG standards on non-Windows systems. Installs the state directory if specified and permissions allow. ```cmake if(NOT WIN32) set(WATCHMAN_STATE_DIR "${CMAKE_INSTALL_PREFIX}/var/run/watchman" CACHE STRING "Run-time path of the persistent state directory") set(INSTALL_WATCHMAN_STATE_DIR OFF CACHE BOOL "Whether WATCHMAN_STATE_DIR should be created by the cmake install target. Disabling this is useful in the case where the CMAKE_INSTALL_PREFIX is owned by a non-privileged user but where the WATCHMAN_STATE_DIR requires administrative rights to create and set its permissions.") option(WATCHMAN_USE_XDG_STATE_HOME "If enabled, use $XDG_STATE_HOME/watchman as the Watchman state directory. XDG_STATE_HOME defaults to $HOME/.local/state." OFF ) else() set(WATCHMAN_STATE_DIR) set(INSTALL_WATCHMAN_STATE_DIR) endif() if(WATCHMAN_STATE_DIR AND INSTALL_WATCHMAN_STATE_DIR) install(DIRECTORY DESTINATION ${WATCHMAN_STATE_DIR} DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_WRITE GROUP_EXECUTE WORLD_READ WORLD_WRITE WORLD_EXECUTE SETGID) endif() ``` -------------------------------- ### Install fb-watchman with npm Source: https://github.com/facebook/watchman/blob/main/watchman/node/README.md Install the fb-watchman npm package. Ensure Watchman is installed separately before proceeding. ```bash $ npm install fb-watchman ``` -------------------------------- ### BSER Socket Example Source: https://github.com/facebook/watchman/blob/main/watchman/node/bser/README.md Example demonstrating how to read BSER from a socket using BunserBuf and write BSER to a socket. ```APIDOC ## BSER Socket I/O Example ### Description Illustrates reading BSER data from a network socket asynchronously and writing BSER data to a socket. ### Code Example ```javascript var bser = require('bser'); var net = require('net'); // Reading from socket var bunser = new bser.BunserBuf(); bunser.on('value', function(obj) { console.log('data from socket', obj); }); var socket = net.connect('/socket'); socket.on('data', function(buf) { bunser.append(buf); }); // Writing to socket var objToWrite = { message: 'hello' }; socket.write(bser.dumpToBuffer(objToWrite)); ``` ### Parameters None specific to this example, relies on `net` module and `bser` API. ### Response None (demonstrates I/O operations) ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/facebook/watchman/blob/main/website/README.md Run this command to install project dependencies using Yarn. ```bash $ yarn ``` -------------------------------- ### Watchman Interaction Example in Ruby Source: https://github.com/facebook/watchman/blob/main/watchman/ruby/ruby-watchman/README.md This example demonstrates how to interact with a running Watchman process using the RubyWatchman gem. It covers getting the socket name, checking if a path is watched, adding it if necessary, and querying for file names. ```ruby require 'ruby-watchman' require 'socket' require 'pathname' sockname = RubyWatchman.load( %x{watchman --output-encoding=bser get-sockname} )['sockname'] raise unless $?.exitstatus.zero? UNIXSocket.open(sockname) do |socket| root = Pathname.new('.').realpath.to_s roots = RubyWatchman.query(['watch-list'], socket)['roots'] if !roots.include?(root) # this path isn't being watched yet; try to set up watch result = RubyWatchman.query(['watch', root], socket) # root_restrict_files setting may prevent Watchman from working raise if result.has_key?('error') end query = ['query', root, { 'expression' => ['type', 'f'], 'fields' => ['name'], }] paths = RubyWatchman.query(query, socket) # could return error if watch is removed raise if paths.has_key?('error') p paths['files'] end ``` -------------------------------- ### Install Ruby Dependencies for Documentation Source: https://github.com/facebook/watchman/blob/main/website/docs/contributing.md Install Bundler and its dependencies to preview documentation changes. Requires Ruby 2.0.0 or later. ```bash cd website sudo gem install bundler sudo bundler install ``` -------------------------------- ### Install System Dependencies for Watchman Source: https://github.com/facebook/watchman/blob/main/website/docs/install.md Run this script to install necessary system packages for Watchman. Ensure you have sudo privileges. ```bash $ sudo ./install-system-packages.sh ``` -------------------------------- ### Install Watchman via Chocolatey Source: https://github.com/facebook/watchman/blob/main/website/docs/install.md Use this command to install Watchman on Windows using the Chocolatey package manager. Ensure Chocolatey is installed and configured. ```powershell PS C:\> choco install watchman ``` -------------------------------- ### Install Rust Executable Source: https://github.com/facebook/watchman/blob/main/watchman/cli/CMakeLists.txt Installs the compiled 'watchmanctl' Rust executable. This is a standard step for making the executable available after compilation. ```Buck install_rust_executable(watchmanctl) ``` -------------------------------- ### Example CLI Trigger with JSON Input Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/trigger.md This example demonstrates how to define a trigger from the command line using a heredoc. It sets up a trigger named 'assets' that runs 'make' when .js, .css, .c, or .cpp files change. ```bash $ watchman -j <<-EOT ["trigger", "/path/to/root", { "name": "assets", "expression": ["pcre", "\.(js|css|c|cpp)$"], "command": ["make"] }] EOT ``` -------------------------------- ### Install Target Library Source: https://github.com/facebook/watchman/blob/main/watchman/thirdparty/deelevate_binding/CMakeLists.txt Installs the 'libdeelevate' target library. This makes the library available for use by other projects or executables that depend on it. ```cmake install( TARGETS libdeelevate ) ``` -------------------------------- ### Manifest Configuration with Features Source: https://github.com/facebook/watchman/blob/main/build/fbcode_builder/README.md Example of a project manifest file demonstrating how to declare and use features to conditionally enable or disable build components and dependencies. ```ini [features] default = rpc rpc = [cmake.defines.feature_rpc=off] THRIFT_RPC=OFF [dependencies.feature_rpc=on] fizz wangle ``` -------------------------------- ### Install RubyWatchman Gem Source: https://github.com/facebook/watchman/blob/main/watchman/ruby/ruby-watchman/README.md Execute this command to install the ruby-watchman gem after adding it to your Gemfile. ```bash $ bundle ``` -------------------------------- ### Build Watchman from Source Source: https://github.com/facebook/watchman/blob/main/website/docs/contributing.md Clone the repository, set up build dependencies, and compile the project. Ensure you have python, automake, autoconf, cmake, libtool, libpcre, and optionally libfolly and nodejs installed. ```bash git clone https://github.com/facebook/watchman.git cd watchman ./autogen.sh make ``` -------------------------------- ### Install Rust Static Library Source: https://github.com/facebook/watchman/blob/main/watchman/thirdparty/deelevate_binding/CMakeLists.txt Installs the 'rust_deelevate' static library into the 'thirdparty' directory. This makes the Rust library available for other parts of the project. ```cmake install_rust_static_library( rust_deelevate INSTALL_DIR thirdparty ) ``` -------------------------------- ### Serve Watchman Documentation Locally Source: https://github.com/facebook/watchman/blob/main/website/docs/contributing.md Start a local Jekyll server to preview documentation changes. The server will watch for file changes and rebuild automatically. ```bash jekyll serve -w -t ``` -------------------------------- ### Install Watchman via Ubuntu DEB Source: https://github.com/facebook/watchman/blob/main/website/docs/install.md Install Watchman on Ubuntu using a downloaded DEB package. This command installs the package and then attempts to fix any dependency issues. Requires sudo privileges. Avoid Ubuntu's default package. ```bash sudo dpkg -i watchman_$UBUNTU_RELEASE_$VERSION.deb sudo apt-get -f install ``` -------------------------------- ### Watch Project Command Example Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/watch-project.md Use `watch-project` to establish a watch on a directory. Observe the `relative_path` and `watch` elements in the response to correctly construct subsequent queries. ```bash $ watchman watch-project ~/www/some/child/dir { "version": "3.0.1", "watch": "/Users/wez/www", "relative_path": "some/child/dir" } ``` -------------------------------- ### Extract and Install Watchman Binaries Source: https://github.com/facebook/watchman/blob/main/website/docs/install.md Steps to extract prebuilt Watchman binaries and copy them to system directories. This assumes you have downloaded the zip file. ```bash $ unzip watchman-*-linux.zip $ cd watchman-vYYYY.MM.DD.00-linux $ sudo mkdir -p /usr/local/{bin,lib} /usr/local/var/run/watchman $ sudo cp bin/* /usr/local/bin $ sudo cp lib/* /usr/local/lib $ sudo chmod 755 /usr/local/bin/watchman $ sudo chmod 2777 /usr/local/var/run/watchman ``` -------------------------------- ### Project and Dependency Setup Source: https://github.com/facebook/watchman/blob/main/CMakeLists.txt Initializes the project with C++ and C languages and finds necessary modules like GMock and GoogleTest. It also includes custom CMake modules for Thrift, function/include/struct/symbol checks, and Rust static libraries. ```cmake set(PACKAGE_NAME "watchman") set(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}") set(PACKAGE_TARNAME "${PACKAGE_NAME}-${PACKAGE_VERSION}") set(PACKAGE_BUGREPORT "https://github.com/facebook/watchman/issues") project(${PACKAGE_NAME} CXX C) find_package(GMock MODULE REQUIRED) include_directories(${GMOCK_INCLUDEDIR} ${LIBGMOCK_INCLUDE_DIR}) include(GoogleTest) enable_testing() include(FBThriftCppLibrary) include(CheckFunctionExists) include(CheckIncludeFiles) include(CheckStructHasMember) include(CheckSymbolExists) include(RustStaticLibrary) ``` -------------------------------- ### Install Latest Watchman Build via Homebrew Source: https://github.com/facebook/watchman/blob/main/website/docs/install.md Install the latest development build of Watchman from GitHub using Homebrew. Use this if the stable Homebrew package is outdated. ```sh $ brew install --HEAD watchman ``` -------------------------------- ### Install RubyWatchman Gem Manually Source: https://github.com/facebook/watchman/blob/main/watchman/ruby/ruby-watchman/README.md Alternatively, install the ruby-watchman gem directly using this command. ```bash $ gem install ruby-watchman ``` -------------------------------- ### Fetch and Test Watchman Library Source: https://github.com/facebook/watchman/blob/main/watchman/java/README.md Execute these Buck commands to fetch necessary components and run the tests for the Watchman library. Ensure Buck is installed and configured. ```bash buck fetch :watchman-tests buck test :watchman-lib ``` -------------------------------- ### Install Watchman via Homebrew on macOS/Linux Source: https://github.com/facebook/watchman/blob/main/website/docs/install.md Install Watchman using Homebrew. This command updates Homebrew and then installs the Watchman package. It's recommended for macOS and Linux users. ```sh $ brew update $ brew install watchman ``` -------------------------------- ### Watchman flush-subscriptions response example Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/flush-subscriptions.md This is an example of the response received after executing the flush-subscriptions command. It indicates which subscriptions were synced, which needed no synchronization, and which dropped updates. ```json { "clock": "c:1446410081:18462:7:135", "synced": ["sub1"], "no_sync_needed": ["sub2"], "dropped": ["sub3"] } ``` -------------------------------- ### Manual Installation of Watchman Binaries on macOS Source: https://github.com/facebook/watchman/blob/main/website/docs/install.md Manually install Watchman from a downloaded macOS release zip file. This involves extracting the archive and copying binaries to system directories. Requires sudo privileges. ```bash $ unzip watchman-*-macos.zip $ cd watchman-vYYYY.MM.DD.00-macos $ sudo mkdir -p /usr/local/{bin,lib} /usr/local/var/run/watchman $ sudo cp bin/* /usr/local/bin $ sudo cp lib/* /usr/local/lib $ sudo chmod 755 /usr/local/bin/watchman $ sudo chmod 2777 /usr/local/var/run/watchman ``` -------------------------------- ### Check Cargo Version for Building from Source Source: https://github.com/facebook/watchman/blob/main/website/docs/install.md Before building Watchman from source, ensure Cargo is installed by checking its version. This command verifies the Cargo installation. ```bash $ cargo version ``` -------------------------------- ### Install Watchman via Fedora RPM Source: https://github.com/facebook/watchman/blob/main/website/docs/install.md Install Watchman on Fedora using a downloaded RPM package. This command installs the package locally and requires sudo privileges. Avoid Fedora's default package. ```bash sudo dnf localinstall watchman-$VERSION.fc$FEDORA_VERSION.x86_64.rpm ``` -------------------------------- ### Incremental Path Index Update Example Source: https://github.com/facebook/watchman/wiki/File-&-Dir-tracking-data-v2 Illustrates how the paths index is updated incrementally when new files are created within a directory. ```c++ paths["some/dir"] = set("foo"); ``` ```c++ paths["some/dir"] = set("foo", "bar"); ``` -------------------------------- ### Subscribe with Defer VCS Option Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/subscribe.md This command shows how to use the 'defer_vcs' flag to observe the creation of control files at the start of a version control operation. ```bash $ watchman -j -p <<-EOT ["subscribe", "/path/to/root", "mysubscriptionname", { "expression": ["allof", ["type", "f"], ["not", "empty"], ["suffix", "php"] ], "defer_vcs": false, "fields": ["name"] }] EOT ``` -------------------------------- ### Enter State with Custom Sync Timeout Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/state-enter.md This example shows how to specify a custom synchronization timeout in milliseconds for the state-enter command. If synchronization does not complete within this timeout, an error is returned. ```json ["state-enter", "/path/to/root", { "name": "mystate", "sync_timeout": 10000, "metadata": { "foo": "bar" } }] ``` -------------------------------- ### Watchman Source Control Aware Subscription Setup Source: https://github.com/facebook/watchman/blob/main/website/docs/scm-query.md Initiate a source control aware subscription by providing SCM mergebase information in the 'since' field. This implicitly enables deferral of VCS events. ```json ["subscribe", "/path/to/root", "mysubscriptionname", { "fields": ["name"], "since": { "scm": { "mergebase-with": "main" } } }] ``` -------------------------------- ### Enter State with Metadata Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/state-enter.md This example demonstrates passing arbitrary JSON metadata along with the state name. The metadata is propagated to subscribers and not interpreted by the watchman server. ```json ["state-enter", "/path/to/root", { "name": "mystate", "metadata": { "foo": "bar" } }] ``` -------------------------------- ### Example CLI Trigger with Shell Expansion Prevention Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/trigger.md This example demonstrates setting a trigger from the CLI. Single quotes around '*.js' prevent shell expansion, ensuring Watchman receives the pattern literally. ```bash $ watchman -- trigger ~/www jsfiles '*.js' -- ls -l ``` -------------------------------- ### Subscribing with Time Constraints Source: https://github.com/facebook/watchman/blob/main/website/docs/nodejs.md Example of how to create a subscription that only includes changes occurring after a specific point in time, using the 'clock' command. ```APIDOC ## Subscribing only to changed files ### Description This example demonstrates how to establish a subscription to Watchman that is constrained by time. It first queries the current abstract clock of the watchman service and then uses this clock value as the `since` parameter in the subscription command. This ensures that only changes occurring after the clock query are included in the subscription results, avoiding issues with pre-existing files at subscription establishment. ### Method Uses `client.command(['clock', ...])` and `client.command(['subscribe', ...])`. ### Endpoint N/A (Client-side command execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters for `subscribe` command: - **expression** (object) - Defines the criteria for files to be watched. Example: `["allof", ["match", "*.js"]]`. - **fields** (array) - Specifies the data fields to be returned for matching files. Example: `["name", "size", "exists", "type"]`. - **since** (string) - The abstract clock value obtained from a previous `clock` command. This acts as a time constraint. - **relative_root** (string, optional) - Specifies a subdirectory within the watched root to which the subscription should be relative. ### Request Example ```javascript function make_time_constrained_subscription(client, watch, relative_path) { client.command(['clock', watch], function (error, resp) { if (error) { console.error('Failed to query clock:', error); return; } const sub = { expression: ["allof", ["match", "*.js"]], fields: ["name", "size", "exists", "type"], since: resp.clock }; if (relative_path) { sub.relative_root = relative_path; } client.command(['subscribe', watch, 'mysubscription', sub], function (error, resp) { // handle the result here }); }); } ``` ### Response #### Success Response (200) - The response structure depends on the `subscribe` command's outcome and the specified `fields`. It typically includes information about the subscription being established. #### Response Example (Response for the `subscribe` command itself is usually minimal, confirming subscription. Actual file change data comes via subsequent events or queries.) ```json { "subscribe": "mysubscription", "version": "3.8.0" } ``` ``` -------------------------------- ### Configure pkg-config Path for Watchman Client Source: https://github.com/facebook/watchman/blob/main/website/docs/cppclient.md Demonstrates how to set the PKG_CONFIG_PATH environment variable if pkg-config cannot locate the watchmanclient package. This is necessary when Watchman is installed in a non-standard location. ```bash export PKG_CONFIG_PATH=/lib/pkgconfig:$PKG_CONFIG_PATH ``` -------------------------------- ### Subscribe to File Changes in Watchman Source: https://github.com/facebook/watchman/blob/main/website/docs/nodejs.md Establish a subscription to receive notifications for specific file patterns. This example subscribes to all '.js' files in the current directory. ```javascript client.command(['subscribe', process.cwd(), 'mysubscription', { expression: ["match", "*.js"] }], function(error, resp) { if (error) { // Probably an error in the subscription criteria console.log('failed to subscribe: ', error); return; } console.log('subscription ' + resp.subscribe + ' established'); } ); ``` -------------------------------- ### Watch Directory via CLI Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/watch.md Use this command to start watching a directory from the command line. The shell resolves the path, but for JSON protocol, an absolute path is required. ```bash $ watchman watch ~/www ``` -------------------------------- ### Get Configuration for Current Directory Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/get-config.md Retrieves the .watchmanconfig for the current directory. Returns an empty configuration if no file is found. ```bash $ watchman get-config . { "version": "2.9.9", "config": {} } ``` -------------------------------- ### Get Watchman Service Version Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/version.md Use the `watchman version` command to retrieve the version and build information of the running Watchman service. ```bash $ watchman version { "version": "2.9.6", "buildinfo": "git:2727d9a1e47a4a2229c65cbb2f0c7656cbd96270" } ``` -------------------------------- ### BSER Integer Encoding Examples Source: https://github.com/facebook/watchman/blob/main/website/docs/bser.md Integers are transmitted as signed values in host byte order. Different byte prefixes indicate the integer size. ```text 0x03 indicates an int8_t ``` ```text 0x04 indicates an int16_t ``` ```text 0x05 indicates an int32_t ``` ```text 0x06 indicates an int64_t ``` -------------------------------- ### Match any file in a directory or its children Source: https://github.com/facebook/watchman/blob/main/website/docs/expr/dirname.md Use `["dirname", "foo/bar"]` to match any file whose dirname is exactly `foo/bar` or any child directory of `foo/bar`. This is a shortcut for the second example. ```json ["dirname", "foo/bar"] ``` ```json ["dirname", "foo/bar", ["depth", "ge", 0]] ``` -------------------------------- ### Get Configuration for Specific Path Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/get-config.md Retrieves the .watchmanconfig for a specified directory path. This example shows a configuration with an ignore_dirs field. ```bash $ watchman get-config /path/to/root { "version": "2.9.9", "config": { "ignore_dirs": [ "buck-out" ] } } ``` -------------------------------- ### Get Watchman Socket Name Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/get-sockname.md Execute the `get-sockname` command to discover the Watchman socket path. This command will also start the Watchman service if it's not already running. ```bash $ watchman get-sockname { "version": "2.5", "sockname": "/tmp/.watchman.wez" } ``` -------------------------------- ### Initiate a Watch Project Source: https://github.com/facebook/watchman/blob/main/website/docs/nodejs.md Initiate a watch on a directory using the `watch-project` command. This establishes a connection to Watchman for the specified directory and returns the watch root and relative path. ```javascript var watchman = require('fb-watchman'); var client = new watchman.Client(); var dir_of_interest = "/some/path"; client.capabilityCheck({optional:[], required:['relative_root']}, function (error, resp) { if (error) { console.log(error); client.end(); return; } // Initiate the watch client.command(['watch-project', dir_of_interest], function (error, resp) { if (error) { console.error('Error initiating watch:', error); return; } // It is considered to be best practice to show any 'warning' or // 'error' information to the user, as it may suggest steps // for remediation if ('warning' in resp) { console.log('warning: ', resp.warning); } // `watch-project` can consolidate the watch for your // dir_of_interest with another watch at a higher level in the // tree, so it is very important to record the `relative_path` // returned in resp console.log('watch established on ', resp.watch, ' relative_path', resp.relative_path); }); }); ``` -------------------------------- ### Incremental Watchman Query with Previous Clock Source: https://github.com/facebook/watchman/blob/main/website/docs/scm-query.md Feed the previous clock value back into a subsequent query to get incremental changes. This example shows a query after a 'hg pull' operation, where no local files have changed. ```bash $ watchman -j <<-EOT ["query", "/path/to/root", { "since": { "clock": "c:123:123", "scm": { "mergebase": "f12345", "mergebase-with": "main" } }, "expression": ["type", "f"], "fields": ["name"] }] EOT ``` -------------------------------- ### Check Watchman Capabilities Source: https://github.com/facebook/watchman/blob/main/website/docs/nodejs.md Use the `capabilityCheck` method to query the Watchman server's capabilities. This is useful for ensuring the service is installed and supports required features like `relative_root`. ```javascript var watchman = require('fb-watchman'); var client = new watchman.Client(); client.capabilityCheck({optional:[], required:['relative_root']}, function (error, resp) { if (error) { // error will be an Error object if the watchman service is not // installed, or if any of the names listed in the `required` // array are not supported by the server console.error(error); } // resp will be an extended version response: // {'version': '3.8.0', 'capabilities': {'relative_root': true}} console.log(resp); }); ``` -------------------------------- ### Watchman allof Expression Example Source: https://github.com/facebook/watchman/blob/main/website/docs/expr/allof.md Use 'allof' to match files that meet multiple criteria, such as having a specific extension and not being empty. Evaluation stops at the first sub-expression that returns false. ```json ["allof", ["match", "*.txt"], ["not", "empty"]] ``` ```json ["allof", expr1, expr2, ... exprN] ``` -------------------------------- ### Watchman Query with Source Control Awareness Source: https://github.com/facebook/watchman/blob/main/website/docs/scm-query.md Use this query to get incremental results based on SCM mergebase information. Feed the 'clock' from a previous query to ensure correctness. ```bash $ watchman -j <<-EOT ["query", "/path/to/root", { "since": { "clock": "c:123:124", "scm": { "mergebase": "f12345", "mergebase-with": "main" } }, "expression": ["type", "f"], "fields": ["name"] }] EOT ``` -------------------------------- ### Example Watchman Query Response with Default Fields Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/query.md A typical response from a watchman query using the default fields, including version, clock, freshness status, and file details. ```json { "version": "2.9", "clock": "c:80616:59", "is_fresh_instance": false, "files": [ { "exists": true, "mode": 33188, "new": false, "name": "argv.c", "size": 1340, } ] } ``` -------------------------------- ### Fetch and Build Watchman JAR Source: https://github.com/facebook/watchman/blob/main/watchman/java/README.md Use these Buck commands to fetch dependencies and build the Watchman JAR file. The JAR will be located in 'buck-out/gen/watchman.jar'. ```bash buck fetch :watchman buck build :watchman ``` -------------------------------- ### Watchman `not` Expression Example Source: https://github.com/facebook/watchman/blob/main/website/docs/expr/not.md Use the `not` expression to invert the result of a subexpression. This example inverts the `empty` expression. ```json ["not", "empty"] ``` -------------------------------- ### Install Watchman via MacPorts Source: https://github.com/facebook/watchman/blob/main/website/docs/install.md Install Watchman on macOS using the MacPorts package manager. This command requires sudo privileges. ```bash $ sudo port install watchman ``` -------------------------------- ### watchman-make with multiple targets and shared patterns Source: https://github.com/facebook/watchman/blob/main/website/docs/watchman-make.md Executes 'make all integration' if any top-level '*.c' file or test source file is changed. ```bash $ watchman-make -p '*.c' '*.h' 'Makefile*' 'tests/**/*.py' 'tests/**/*.c' -t all integration ``` -------------------------------- ### Example JSON Trigger Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/trigger.md A concrete example of a trigger defined using the JSON protocol. This trigger monitors for JavaScript files and executes 'ls -l' when changes occur. ```json ["trigger", "/home/wez/www", "jsfiles", "*.js", "--", "ls", "-l"] ``` -------------------------------- ### Get Watchman Client Version Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/version.md Use the `watchman -v` command to get the version of the Watchman client. If client and server versions differ, consider restarting the server. ```bash $ watchman -v 2.9.8 ``` -------------------------------- ### Add Python Library to Build Source: https://github.com/facebook/watchman/blob/main/watchman/python/pywatchman/CMakeLists.txt Use this rule to add a Python library to the build. Specify the library name and its source files. ```Buck add_fb_python_library(pywatchman SOURCES __init__.py capabilities.py encoding.py load.py pybser.py windows.py NAMESPACE pywatchman ) ``` -------------------------------- ### watchman-make with multiple targets and patterns Source: https://github.com/facebook/watchman/blob/main/website/docs/watchman-make.md Invokes 'make all' for changes matching '*.c', '*.h', or 'Makefile*', and 'make integration' for changes matching 'tests/**/*.py' or 'tests/**/*.c'. ```bash $ watchman-make -p '**/*.c' '**/*.h' 'Makefile*' -t all -p 'tests/**/*.py' 'tests/**/*.c' -t integration # Relative to /Users/wez/fb/watchman # Changes to files matching **/*.c **/*.h Makefile* will execute `make all` # Changes to files matching tests/**/*.py tests/**/*.c will execute `make integration` # waiting for changes ``` -------------------------------- ### BSER Templated Object Encoding Example Source: https://github.com/facebook/watchman/blob/main/website/docs/bser.md This example demonstrates how a JSON array of objects with repeated keys is serialized using the BSER templated object format. It includes a header for keys and a subsequent array for values, using a skip marker (0x0c) for missing values. ```json [ {"name": "fred", "age": 20}, {"name": "pete", "age": 30}, {"age": 25 }, ] ``` ```text 0b template 00 array -- start prop names 0302 int, 2 -- two prop names 02 string -- first prop "name" 0304 int, 4 6e616d65 "name" 02 string -- 2nd prop "age" 0303 int, 3 616765 "age" 0303 int, 3 -- there are 3 objects 02 string -- object 1, prop 1 name=fred 0304 int, 4 66726564 "fred" 0314 int 0x14 -- object 1, prop 2 age=20 02 string -- object 2, prop 1 name=pete 0304 int 4 70657465 "pete" 031e int, 0x1e -- object 2, prop 2 age=30 0c skip -- object 3, prop 1, not set 0319 int, 0x19 -- object 3, prop 2 age=25 ``` -------------------------------- ### Build Static Website Content Source: https://github.com/facebook/watchman/blob/main/website/README.md Generates static content for the website into the 'build' directory, which can then be hosted. ```bash $ yarn build ``` -------------------------------- ### Add Watchman Wait Executable Source: https://github.com/facebook/watchman/blob/main/watchman/python/CMakeLists.txt Defines the `watchman-wait` Python executable. It depends on the `pywatchman` library and installs the executable. ```cmake add_fb_python_executable(watchman-wait SOURCES bin/watchman-wait=__main__.py DEPENDS pywatchman ) install_fb_python_executable(watchman-wait) ``` -------------------------------- ### Make Time-Constrained Subscription Source: https://github.com/facebook/watchman/blob/main/website/docs/nodejs.md Establishes a subscription to file changes with a logical time constraint. It queries the current clock before setting up the subscription to avoid initial unwanted results. ```javascript function make_time_constrained_subscription(client, watch, relative_path) { client.command(['clock', watch], function (error, resp) { if (error) { console.error('Failed to query clock:', error); return; } sub = { // Match any `.js` file in the dir_of_interest expression: ["allof", ["match", "*.js"]], // Which fields we're interested in fields: ["name", "size", "exists", "type"], // add our time constraint since: resp.clock }; if (relative_path) { sub.relative_root = relative_path; } client.command(['subscribe', watch, 'mysubscription', sub], function (error, resp) { // handle the result here }); }); } ``` -------------------------------- ### Add Watchman Make Executable Source: https://github.com/facebook/watchman/blob/main/watchman/python/CMakeLists.txt Defines the `watchman-make` Python executable. It depends on the `pywatchman` library and installs the executable. ```cmake add_fb_python_executable(watchman-make SOURCES bin/watchman-make=__main__.py DEPENDS pywatchman ) install_fb_python_executable(watchman-make) ``` -------------------------------- ### Add Watchman Diagnostic Executable Source: https://github.com/facebook/watchman/blob/main/watchman/python/CMakeLists.txt Defines the `watchman-diag` Python executable. It depends on the `pywatchman` library and installs the executable. ```cmake add_fb_python_executable(watchman-diag SOURCES bin/watchman-diag=__main__.py DEPENDS pywatchman ) install_fb_python_executable(watchman-diag) ``` -------------------------------- ### Build Watchman Python Client Source: https://github.com/facebook/watchman/blob/main/watchman/python/README.md Use this command to build the Watchman Python client package. ```sh python -m build ``` -------------------------------- ### Add Watchman Replicate Subscription Executable Source: https://github.com/facebook/watchman/blob/main/watchman/python/CMakeLists.txt Defines the `watchman-replicate-subscription` Python executable. It depends on the `pywatchman` library and installs the executable. ```cmake add_fb_python_executable(watchman-replicate-subscription SOURCES bin/watchman-replicate-subscription=__main__.py DEPENDS pywatchman ) install_fb_python_executable(watchman-replicate-subscription) ``` -------------------------------- ### Include Dotfiles in Match Source: https://github.com/facebook/watchman/blob/main/website/docs/expr/match.md Include files or directories starting with a dot (`.`) in the match results by setting the `includedotfiles` flag to `true`. ```json ["match", "*.txt", "basename", {"includedotfiles": true}] ``` -------------------------------- ### Basic CLI Trigger Syntax Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/trigger.md Use this syntax to set up a trigger from the command line. The first '--' separates Watchman options from trigger arguments, and the second '--' separates trigger patterns from the command to execute. ```bash $ watchman -- trigger /path/to/dir triggername [patterns] -- [cmd] ``` -------------------------------- ### JSON Expression Term Example Source: https://github.com/facebook/watchman/blob/main/website/docs/file-query.md Canonical representation of a Watchman expression term as a JSON array, where the first element is the term name. ```json ["termname", arg1, arg2] ``` -------------------------------- ### List existing subscriptions Source: https://github.com/facebook/watchman/blob/main/website/docs/watchman-replicate-subscription.md Retrieve details of existing subscriptions for a watched root to identify the source subscription for replication. ```bash $ watchman-replicate-subscription PATH --list ``` -------------------------------- ### Basic Watchman CLI Command Source: https://github.com/facebook/watchman/blob/main/website/docs/cli-options.md Invokes the watchman CLI to set up a watch on a directory. ```bash $ watchman watch /path/to/dir ``` -------------------------------- ### Glob Test Modules Source: https://github.com/facebook/watchman/blob/main/watchman/integration/CMakeLists.txt Finds all Python files starting with 'test_' in the current directory. This is used to dynamically include test files in the build. ```cmake file(GLOB TEST_MODULES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "test_*.py") ``` -------------------------------- ### All Files Index Composition Source: https://github.com/facebook/watchman/wiki/File-&-Dir-tracking-data-v2 Demonstrates how to construct the set of all known file identifiers by iterating through the 'members' set of each segment in the index chain. This provides a comprehensive view of all tracked files. ```c++ set all_files; for (index = head; index; index = index->prior) { for (fileid in index->members) { all_files.insert(fileid); } } ``` -------------------------------- ### Enable Debug Logging with Watchman Source: https://github.com/facebook/watchman/blob/main/website/docs/nodejs.md To receive 'log' events, send a 'log-level' command to the Watchman service. This example sets the log level to 'debug'. ```javascript client.command(['log-level', 'debug']); ``` -------------------------------- ### Enable BSER Protocol Source: https://github.com/facebook/watchman/blob/main/website/docs/bser.md To use the binary protocol, the client must first send this specific byte sequence to the watchman daemon. ```text \x00x\x01 ``` -------------------------------- ### Vacate a named state with metadata Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/state-leave.md This example demonstrates passing metadata to subscribers when vacating a state. The 'metadata' field is propagated and not interpreted by the watchman server. ```json ["state-leave", "/path/to/root", { "name": "mystate", "metadata": { "foo": "bar" } }] ``` -------------------------------- ### Vacate a named state Source: https://github.com/facebook/watchman/blob/main/website/docs/cmd/state-leave.md This is the simplest example of vacating a state named 'mystate'. It causes subscribers to receive a unilateral subscription PDU from the watchman server. ```json ["state-leave", "/path/to/root", "mystate"] ``` -------------------------------- ### client.command(args [, done]) Source: https://github.com/facebook/watchman/blob/main/website/docs/nodejs.md Sends a command to the watchman service. Commands are queued and dispatched asynchronously in FIFO order. Handles warnings from the watchman service. ```APIDOC ## client.command(args [, done]) ### Description Sends a command to the watchman service. `args` is an array that specifies the command name and any optional arguments. The command is queued and dispatched asynchronously. You may queue multiple commands to the service; they will be dispatched in FIFO order once the client connection is established. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters for `args` array: - **command_name** (string) - The name of the watchman command to execute. - **...arguments** - Any optional arguments required by the command. ### Callback Function (`done`) - **error** (Error) - An error object if the command fails. - **result** (object) - The result of the command execution. May contain a `warning` field. ### Request Example ```javascript client.command(['watch-project', process.cwd()], function(error, resp) { if (error) { console.log('watch failed: ', error); return; } if ('warning' in resp) { console.log('warning: ', resp.warning); } if ('relative_path' in resp) { console.log('watching project ', resp.watch, ' relative path to cwd is ', resp.relative_path); } else { console.log('watching ', resp.watch); } }); ``` ### Response #### Success Response (200) - **watch** (string) - The root path being watched. - **relative_path** (string, optional) - The relative path from the watch root to the current working directory. - **warning** (string, optional) - A warning message from the watchman service. #### Response Example ```json { "watch": "/path/to/project", "relative_path": "src" } ``` ``` -------------------------------- ### Set Project Root Files to .watchmanconfig Source: https://github.com/facebook/watchman/blob/main/website/docs/config.md This JSON configuration snippet specifies that only '.watchmanconfig' should be considered a project root file. This is useful for custom project structures. ```json { "root_files": [".watchmanconfig"] } ``` -------------------------------- ### Encode value to BSER buffer Source: https://github.com/facebook/watchman/blob/main/watchman/node/bser/README.md Use bser.dumpToBuffer to synchronously encode a JavaScript value into a BSER-formatted buffer. This example demonstrates encoding and then decoding to verify. ```javascript var encoded = bser.dumpToBuffer(['hello']); console.log(bser.loadFromBuffer(encoded)); // ['hello'] ``` -------------------------------- ### Find and Link fmt Library Source: https://github.com/facebook/watchman/blob/main/CMakeLists.txt Locates the 'fmt' configuration package, a C++ formatting library. This is used for consistent and efficient string formatting within the project. ```cmake find_package(fmt CONFIG REQUIRED) ```