|
| 1 | +# Swift BazelRunfiles library |
| 2 | + |
| 3 | +This is a Bazel Runfiles lookup library for Bazel-built Swift binaries and tests. |
| 4 | + |
| 5 | +Learn about runfiles: read [Runfiles guide](https://bazel.build/extending/rules#runfiles) |
| 6 | +or watch [Fabian's BazelCon talk](https://www.youtube.com/watch?v=5NbgUMH1OGo). |
| 7 | + |
| 8 | +## Usage |
| 9 | + |
| 10 | +1. Depend on this runfiles library from your build rule: |
| 11 | + |
| 12 | +```python |
| 13 | +swift_binary( |
| 14 | + name = "my_binary", |
| 15 | + ... |
| 16 | + data = ["//path/to/my/data.txt"], |
| 17 | + deps = ["@build_bazel_rules_swift//swift/runfiles"], |
| 18 | +) |
| 19 | +``` |
| 20 | + |
| 21 | +2. Include the runfiles library: |
| 22 | + |
| 23 | +```swift |
| 24 | +import BazelRunfiles |
| 25 | +``` |
| 26 | + |
| 27 | +3. Create a Runfiles instance and use `rlocation` to look up runfile urls: |
| 28 | + |
| 29 | +```swift |
| 30 | +import BazelRunfiles |
| 31 | + |
| 32 | +do { |
| 33 | + let runfiles = try Runfiles.create() |
| 34 | + let fileURL = try runfiles.rlocation("my_workspace/path/to/my/data.txt") |
| 35 | + print("file: \(fileURL)") |
| 36 | +} catch { |
| 37 | + print("runfiles error: \(error)") |
| 38 | +} |
| 39 | +``` |
| 40 | + |
| 41 | +The code above: |
| 42 | + |
| 43 | +- Creates a manifest- or directory-based implementation based on |
| 44 | + the environment variables in `Process.processInfo.environment`. |
| 45 | + See `Runfiles.create()` for more info. |
| 46 | +- The `Runfiles.create` function uses the runfiles manifest and the runfiles |
| 47 | + directory from the `RUNFILES_MANIFEST_FILE` and `RUNFILES_DIR` environment |
| 48 | + variables. If not present, the function looks for the manifest and directory |
| 49 | + near `CommandLine.arguments.first` (e.g. `argv[0]` the path of the main program). |
| 50 | + |
| 51 | +If you want to start subprocesses, the runfiles library helps you set the required environment variables for them to find their runfiles: |
| 52 | + |
| 53 | +```swift |
| 54 | +import BazelRunfiles |
| 55 | +import Foundation |
| 56 | + |
| 57 | +do { |
| 58 | + |
| 59 | + let runfiles = try Runfiles.create() |
| 60 | + let executableURL = try runfiles.rlocation("my_workspace/path/to/binary") |
| 61 | + |
| 62 | + let process = Process() |
| 63 | + process.executableURL = executableURL |
| 64 | + process.environment = runfiles.envVars() |
| 65 | + |
| 66 | + do { |
| 67 | + // Launch the process |
| 68 | + try process.run() |
| 69 | + process.waitUntilExit() |
| 70 | + } catch { |
| 71 | + // ... |
| 72 | + } |
| 73 | +} catch { |
| 74 | + fatalError("runfiles error: \(error)") |
| 75 | +} |
| 76 | +``` |
0 commit comments