summary refs log tree commit diff
path: root/third_party
diff options
context:
space:
mode:
authorVincent Ambo <tazjin@google.com>2019-07-04T10·18+0100
committerVincent Ambo <tazjin@google.com>2019-07-04T10·18+0100
commit64275e446e442c9a0a860969501158ed93058441 (patch)
tree482821738cbc68fb1e7c263bc80a2cea4a946a66 /third_party
parentf723b8b878a3c4a4687b9e337a875500bebb39b1 (diff)
feat(third_party/bazel): Check in rules_nixpkgs from Tweag r/18
Diffstat (limited to 'third_party')
-rw-r--r--third_party/bazel/rules_nixpkgs/.circleci/config.yml17
-rw-r--r--third_party/bazel/rules_nixpkgs/.gitignore5
-rw-r--r--third_party/bazel/rules_nixpkgs/AUTHORS9
-rw-r--r--third_party/bazel/rules_nixpkgs/BUILD0
-rw-r--r--third_party/bazel/rules_nixpkgs/CHANGELOG.md97
-rw-r--r--third_party/bazel/rules_nixpkgs/CONTRIBUTING.md36
-rw-r--r--third_party/bazel/rules_nixpkgs/CONTRIBUTORS13
-rw-r--r--third_party/bazel/rules_nixpkgs/LICENSE201
-rw-r--r--third_party/bazel/rules_nixpkgs/README.md402
-rw-r--r--third_party/bazel/rules_nixpkgs/WORKSPACE99
-rw-r--r--third_party/bazel/rules_nixpkgs/nixpkgs.nix9
-rw-r--r--third_party/bazel/rules_nixpkgs/nixpkgs/BUILD5
-rw-r--r--third_party/bazel/rules_nixpkgs/nixpkgs/BUILD.pkg16
-rw-r--r--third_party/bazel/rules_nixpkgs/nixpkgs/nixpkgs.bzl355
-rw-r--r--third_party/bazel/rules_nixpkgs/shell.nix11
-rw-r--r--third_party/bazel/rules_nixpkgs/tests/BUILD58
-rw-r--r--third_party/bazel/rules_nixpkgs/tests/cc-test.cc1
-rw-r--r--third_party/bazel/rules_nixpkgs/tests/hello.nix3
-rw-r--r--third_party/bazel/rules_nixpkgs/tests/nixpkgs.nix1
-rw-r--r--third_party/bazel/rules_nixpkgs/tests/output.nix13
-rw-r--r--third_party/bazel/rules_nixpkgs/tests/pkgname.nix1
-rwxr-xr-xthird_party/bazel/rules_nixpkgs/tests/test_bin.sh4
-rwxr-xr-xthird_party/bazel/rules_nixpkgs/tests/test_output.sh15
23 files changed, 1371 insertions, 0 deletions
diff --git a/third_party/bazel/rules_nixpkgs/.circleci/config.yml b/third_party/bazel/rules_nixpkgs/.circleci/config.yml
new file mode 100644
index 000000000000..27ab177030d6
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/.circleci/config.yml
@@ -0,0 +1,17 @@
+version: 2
+
+jobs:
+  build:
+    docker:
+      - image: nixos/nix
+    working_directory: ~/rules_nixpkgs
+    steps:
+      - checkout
+      - run:
+          name: System dependencies
+          command: |
+            apk update --no-progress && apk --no-progress add bash ca-certificates
+      - run:
+          name: Run tests
+          command: |
+            nix-shell --pure --run 'bazel test --test_output errors //...'
diff --git a/third_party/bazel/rules_nixpkgs/.gitignore b/third_party/bazel/rules_nixpkgs/.gitignore
new file mode 100644
index 000000000000..4e18ce1aecf6
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/.gitignore
@@ -0,0 +1,5 @@
+/bazel-bin
+/bazel-genfiles
+/bazel-out
+/bazel-rules_nixpkgs
+/bazel-testlogs
diff --git a/third_party/bazel/rules_nixpkgs/AUTHORS b/third_party/bazel/rules_nixpkgs/AUTHORS
new file mode 100644
index 000000000000..928d70d23151
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/AUTHORS
@@ -0,0 +1,9 @@
+# This is the official list of Bazel authors for copyright purposes.
+# This file is distinct from the CONTRIBUTORS files.
+# See the latter for an explanation.
+
+# Names should be added to this file as:
+# Name or Organization <email address>
+# The email address is not required for organizations.
+
+Tweag I/O Limited
diff --git a/third_party/bazel/rules_nixpkgs/BUILD b/third_party/bazel/rules_nixpkgs/BUILD
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/BUILD
diff --git a/third_party/bazel/rules_nixpkgs/CHANGELOG.md b/third_party/bazel/rules_nixpkgs/CHANGELOG.md
new file mode 100644
index 000000000000..91eb1811838a
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/CHANGELOG.md
@@ -0,0 +1,97 @@
+# Change Log
+
+All notable changes to this project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/).
+
+## [0.5.2]
+
+### Added
+- `nixpkgs_package` now has a new optional argument `fail_not_supported`
+  allowing the rule to _not_ fail on Windows (when set to `False`)
+- `nixpkgs_cc_configure` now has a new optional argument `nixopts` which
+  propagates extra arguments to the `nix-build` calls.
+
+### Fixed
+- The `nixpkgs_package` is now a no-op on non nixpkgs-supported platforms
+  instead of throwing an error.
+
+## [0.5.1] - 2018-12-18
+
+### Changed
+
+- `nixpkgs_package` now has a new optional argument `nixopts`
+  allowing to pass extra arguments to the `nix-build` calls
+
+### Fixed
+
+- The various `nix_*` rules are now only triggered when one of their dependency
+  has changed and not each time the `WORKSPACE` is modified
+- The `nixpkgs_cc_configure` macro is now much faster
+- `nixpkgs_cc_configure` is now a no-op on non nixpkgs-supported platforms
+  instead of throwing an error
+- The `lib` filegroup provided in the default `BUILD` file for
+  `nixpkgs_package` now also works on MacOS
+
+## [0.4.1] - 2018-11-17
+
+### Added
+
+* `nixpkgs_cc_configure` rule to tell Bazel to configure a toolchain
+  from tools found in the given Nixpkgs repository, instead of from
+  tools found in the ambient environment.
+* `nixpkgs_local_repository` rule. Works like `nixpkgs_git_repository`
+  but takes a checked-in Nix file or Nix expression as input.
+
+### Changed
+
+* The `repository` attribute is no longer deprecated. Most rules
+  support both `repository` and `repositories` as attributes.
+
+### Fixed
+
+* Short repository labels work again. That is, you can say `repository
+  = "@nixpkgs"` as a short form for `repository =
+  "@nixpkgs//:default.nix"`.
+
+## [0.3.1] - 2018-10-24
+
+### Fixed
+
+* `repositories` is no longer a required argument to `nixpkgs_package`.
+
+## [0.3] - 2018-10-23
+
+### Added
+
+* `nixpkgks_package` now supports referencing arbitrarily named nix
+  files. A bug previously only made it possible to reference
+  `default.nix` files.
+
+### Removed
+
+* The `path` attribute has been removed. See `Migration` section
+  in `README.md` for instructions.
+
+### Changed
+
+* `nixpkgs_packages` does not accept implicit `<nixpkgs>` version. See
+   [#25](https://github.com/tweag/rules_nixpkgs/pull/25).
+
+## [0.2.3] - 2018-07-01
+
+### Added
+
+* `sha256` attribute to `nixpkgs_git_repository`.
+* Ability to point to a Nixpkgs fork via the new `remote` attribute to
+  `nixpkgs_git_repository`.
+
+## [0.2.2] - 2018-04-30
+
+## [0.2.1] - 2018-03-18
+
+## [0.2] - 2018-03-18
+
+## [0.1] - 2018-02-21
+
+## [0.1.1] - 2017-12-27
diff --git a/third_party/bazel/rules_nixpkgs/CONTRIBUTING.md b/third_party/bazel/rules_nixpkgs/CONTRIBUTING.md
new file mode 100644
index 000000000000..f98c3ab184a4
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/CONTRIBUTING.md
@@ -0,0 +1,36 @@
+# Contributing to Bazel
+
+## Contributor License Agreement
+
+Contributions to this project must be accompanied by a Contributor License
+Agreement. You (or your employer) retain the copyright to your contribution,
+this simply gives us permission to use and redistribute your contributions as
+part of the project. Head over to <https://cla.developers.google.com/> to see
+your current agreements on file or to sign a new one.
+
+You generally only need to submit a CLA once, so if you've already submitted one
+(even if it was for a different project), you probably don't need to do it
+again.
+
+## Contribution process
+
+1. Explain your idea and discuss your plan with members of the team.
+   The best way to do this is to create an [issue][issue-tracker] or
+   comment on an existing issue.
+1. Prepare a git commit with your change. Don't forget to
+   add [tests][tests]. Run the existing tests with `bazel test //...`.
+   Update [README.md](./README.md) if appropriate.
+1. [Create a pull request](https://help.github.com/articles/creating-a-pull-request/).
+   This will start the code review process. **All submissions,
+   including submissions by project members, require review.**
+1. You may be asked to make some changes. You'll also need to sign the
+   CLA at this point, if you haven't done so already. Our continuous
+   integration bots will test your change automatically on supported
+   platforms. Once everything looks good, your change will be merged.
+
+[issue-tracker]: https://github.com/tweag/rules_nixpkgs/issues
+[tests]: https://github.com/tweag/rules_nixpkgs/tree/master/tests
+
+## Setting up your development environment
+
+Read how to [set up your development environment](https://bazel.build/contributing.html)
diff --git a/third_party/bazel/rules_nixpkgs/CONTRIBUTORS b/third_party/bazel/rules_nixpkgs/CONTRIBUTORS
new file mode 100644
index 000000000000..4b3b9890ee6e
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/CONTRIBUTORS
@@ -0,0 +1,13 @@
+# People who have agreed to one of the CLAs and can contribute patches.
+# The AUTHORS file lists the copyright holders; this file
+# lists people.  For example, Google employees are listed here
+# but not in AUTHORS, because Google holds the copyright.
+#
+# https://developers.google.com/open-source/cla/individual
+# https://developers.google.com/open-source/cla/corporate
+#
+# Names should be added to this file as:
+#     Name <email address>
+
+Mathieu Boespflug <m@tweag.io>
+Mateusz Kowalczyk <mateusz.kowalczyk@tweag.io>
diff --git a/third_party/bazel/rules_nixpkgs/LICENSE b/third_party/bazel/rules_nixpkgs/LICENSE
new file mode 100644
index 000000000000..261eeb9e9f8b
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/LICENSE
@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/third_party/bazel/rules_nixpkgs/README.md b/third_party/bazel/rules_nixpkgs/README.md
new file mode 100644
index 000000000000..6e967babdfc8
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/README.md
@@ -0,0 +1,402 @@
+# rules_nixpkgs
+
+[![CircleCI](https://circleci.com/gh/tweag/rules_nixpkgs.svg?style=svg)](https://circleci.com/gh/tweag/rules_nixpkgs)
+
+Rules for importing Nixpkgs packages into Bazel.
+
+## Rules
+
+* [nixpkgs_git_repository](#nixpkgs_git_repository)
+* [nixpkgs_package](#nixpkgs_package)
+
+## Setup
+
+Add the following to your `WORKSPACE` file, and select a `$COMMIT` accordingly.
+
+```bzl
+http_archive(
+    name = "io_tweag_rules_nixpkgs",
+    strip_prefix = "rules_nixpkgs-$COMMIT",
+    urls = ["https://github.com/tweag/rules_nixpkgs/archive/$COMMIT.tar.gz"],
+)
+
+load("@io_tweag_rules_nixpkgs//nixpkgs:nixpkgs.bzl", "nixpkgs_git_repository", "nixpkgs_package")
+```
+
+## Example
+
+```bzl
+nixpkgs_git_repository(
+    name = "nixpkgs",
+    revision = "17.09", # Any tag or commit hash
+    sha256 = "" # optional sha to verify package integrity!
+)
+
+nixpkgs_package(
+    name = "hello",
+    repositories = { "nixpkgs": "@nixpkgs//:default.nix" }
+)
+```
+
+## Rules
+
+### nixpkgs_git_repository
+
+Name a specific revision of Nixpkgs on GitHub or a local checkout.
+
+```bzl
+nixpkgs_git_repository(name, revision, sha256)
+```
+
+<table class="table table-condensed table-bordered table-params">
+  <colgroup>
+    <col class="col-param" />
+    <col class="param-description" />
+  </colgroup>
+  <thead>
+    <tr>
+      <th colspan="2">Attributes</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td><code>name</code></td>
+      <td>
+        <p><code>Name; required</code></p>
+        <p>A unique name for this repository.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>revision</code></td>
+      <td>
+        <p><code>String; required</code></p>
+        <p>Git commit hash or tag identifying the version of Nixpkgs
+           to use.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>remote</code></td>
+      <td>
+        <p><code>String; optional</code></p>
+        <p>The URI of the remote Git repository. This must be a HTTP
+           URL. There is currently no support for authentication.
+           Defaults to <a href="https://github.com/NixOS/nixpkgs">
+           upstream nixpkgs.</a></p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>sha256</code></td>
+      <td>
+        <p><code>String; optional</code></p>
+        <p>The SHA256 used to verify the integrity of the repository.</p>
+      </td>
+    </tr>
+  </tbody>
+</table>
+
+### nixpkgs_local_repository
+
+Create an external repository representing the content of Nixpkgs,
+based on a Nix expression stored locally or provided inline. One of
+`nix_file` or `nix_file_content` must be provided.
+
+```bzl
+nixpkgs_local_repository(name, nix_file, nix_file_deps, nix_file_content)
+```
+
+<table class="table table-condensed table-bordered table-params">
+  <colgroup>
+    <col class="col-param" />
+    <col class="param-description" />
+  </colgroup>
+  <thead>
+    <tr>
+      <th colspan="2">Attributes</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td><code>name</code></td>
+      <td>
+        <p><code>Name; required</code></p>
+        <p>A unique name for this repository.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>nix_file</code></td>
+      <td>
+        <p><code>String; optional</code></p>
+        <p>A file containing an expression for a Nix derivation.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>nix_file_deps</code></td>
+      <td>
+        <p><code>List of labels; optional</code></p>
+        <p>Dependencies of `nix_file` if any.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>nix_file_content</code></td>
+      <td>
+        <p><code>String; optional</code></p>
+        <p>An expression for a Nix derivation.</p>
+      </td>
+    </tr>
+  </tbody>
+</table>
+
+### nixpkgs_package
+
+Make the content of a Nixpkgs package available in the Bazel workspace.
+
+```bzl
+nixpkgs_package(
+    name, attribute_path, nix_file, nix_file_deps, nix_file_content,
+    repository, repositories, build_file, build_file_content, nixopts,
+    fail_not_supported,
+)
+```
+
+If `repositories` is not specified, you must provide a
+nixpkgs clone in `nix_file` or `nix_file_content`.
+
+<table class="table table-condensed table-bordered table-params">
+  <colgroup>
+    <col class="col-param" />
+    <col class="param-description" />
+  </colgroup>
+  <thead>
+    <tr>
+      <th colspan="2">Attributes</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td><code>name</code></td>
+      <td>
+        <p><code>Name; required</code></p>
+        <p>A unique name for this target</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>attribute_path</code></td>
+      <td>
+        <p><code>String; optional</code></p>
+        <p>Select an attribute from the top-level Nix expression being
+           evaluated. The attribute path is a sequence of attribute
+           names separated by dots.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>nix_file</code></td>
+      <td>
+        <p><code>String; optional</code></p>
+        <p>A file containing an expression for a Nix derivation.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>nix_file_deps</code></td>
+      <td>
+        <p><code>List of labels; optional</code></p>
+        <p>Dependencies of `nix_file` if any.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>nix_file_content</code></td>
+      <td>
+        <p><code>String; optional</code></p>
+        <p>An expression for a Nix derivation.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>repository</code></td>
+      <td>
+        <p><code>Label; optional</code></p>
+        <p>A repository label identifying which Nixpkgs to use.
+           Equivalent to `repositories = { "nixpkgs": ...}`</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>repositories</code></td>
+      <td>
+        <p><code>String-keyed label dict; optional</code></p>
+        <p>A dictionary mapping `NIX_PATH` entries to repository labels.</p>
+        <p>Setting it to
+           <pre><code>repositories = { "myrepo" : "//:myrepo" }</code></pre>
+           for example would replace all instances
+           of <code>&lt;myrepo&gt;</code> in the called nix code by the
+           path to the target <code>"//:myrepo"</code>. See the
+           <a href="https://nixos.org/nix/manual/#env-NIX_PATH">relevant
+           section in the nix manual</a> for more information.</p>
+        <p>Specify one of `path` or `repositories`.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>build_file</code></td>
+      <td>
+        <p><code>Label; optional</code></p>
+        <p>The file to use as the BUILD file for this repository.
+           Its contents are copied copied into the file
+           <code>BUILD</code> in root of the nix output folder.
+           The Label does not need to be named BUILD, but can be.
+        </p>
+        <p>For common use cases we provide filegroups that expose
+           certain files as targets:
+          <dl>
+            <dt><code>:bin</code></dt>
+            <dd>Everything in the <code>bin/</code> directory.</dd>
+            <dt><code>:lib</code></dt>
+            <dd>All <code>.so</code> and <code>.a</code> files
+              that can be found in subdirectories of
+              <code>lib/</code>.</dd>
+            <dt><code>:include</code></dt>
+            <dd>All <code>.h</code> files
+              that can be found in subdirectories of
+              <code>bin/</code>.</dd>
+          </dl>
+        </p>
+        <p>If you need different files from the nix package,
+          you can reference them like this: <pre><code>package(default_visibility = [ "//visibility:public" ])
+filegroup(
+  name = "our-docs",
+  srcs = glob(["share/doc/ourpackage/**/*"]),
+)</code></pre>
+          See the bazel documentation of
+          <a href="https://docs.bazel.build/versions/master/be/general.html#filegroup">filegroup</a>
+          and
+          <a href="https://docs.bazel.build/versions/master/be/functions.html#glob">glob</a>.
+        </p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>build_file_content</code></td>
+      <td>
+        <p><code>String; optional</code></p>
+        <p>Like <code>build_file</code>, but a string of the contents
+          instead of a file name.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>nixopts</code></td>
+      <td>
+        <p><code>String list; optional</code></p>
+        <p>Extra flags to pass when calling Nix.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>fail_not_supported</code></td>
+      <td>
+        <p><code>Boolean; optional; default = True</code></p>
+        <p>
+            If set to <code>True</code> (default) this rule will fail on
+            platforms which do not support Nix (e.g. Windows). If set to
+            <code>False</code> calling this rule will succeed but no output
+            will be generated.
+        </p>
+      </td>
+    </tr>
+  </tbody>
+</table>
+
+### nixpkgs_cc_configure
+
+Tells Bazel to use compilers and linkers from Nixpkgs for the CC
+toolchain. By default, Bazel autodetects a toolchain on the current
+`PATH`. Overriding this autodetection makes builds more hermetic and
+is considered a best practice.
+
+Example:
+
+```bzl
+nixpkgs_cc_configure(repository = "@nixpkgs//:default.nix")
+```
+
+<table class="table table-condensed table-bordered table-params">
+  <colgroup>
+    <col class="col-param" />
+    <col class="param-description" />
+  </colgroup>
+  <thead>
+    <tr>
+      <th colspan="2">Attributes</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td><code>nix_file</code></td>
+      <td>
+        <p><code>String; optional</code></p>
+        <p>An expression for a Nix environment derivation. The
+           environment should expose all the commands that make up
+           a CC toolchain (`cc`, `ld` etc). Exposes all commands in
+           `stdenv.cc` and `binutils` by default.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>nix_file_deps</code></td>
+      <td>
+        <p><code>List of labels; optional</code></p>
+        <p>Dependencies of `nix_file` if any.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>nix_file_content</code></td>
+      <td>
+        <p><code>String; optional</code></p>
+        <p>An expression for a Nix environment derivation.</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>repository</code></td>
+      <td>
+        <p><code>Label; optional</code></p>
+        <p>A repository label identifying which Nixpkgs to use.
+           Equivalent to `repositories = { "nixpkgs": ...}`</p>
+      </td>
+    </tr>
+    <tr>
+      <td><code>repositories</code></td>
+      <td>
+        <p><code>String-keyed label dict; optional</code></p>
+        <p>A dictionary mapping `NIX_PATH` entries to repository labels.</p>
+        <p>Setting it to
+           <pre><code>repositories = { "myrepo" : "//:myrepo" }</code></pre>
+           for example would replace all instances
+           of <code>&lt;myrepo&gt;</code> in the called nix code by the
+           path to the target <code>"//:myrepo"</code>. See the
+           <a href="https://nixos.org/nix/manual/#env-NIX_PATH">relevant
+           section in the nix manual</a> for more information.</p>
+        <p>Specify one of `path` or `repositories`.</p>
+      </td>
+    </tr>
+  </tbody>
+</table>
+
+## Migration
+
+### `path` Attribute
+
+`path` was an attribute from the early days of `rules_nixpkgs`, and
+its ability to reference arbitrary paths a danger to build hermeticity.
+
+Replace it with either `nixpkgs_git_repository` if you need
+a specific version of `nixpkgs`. If you absolutely *must* depend on a
+local folder, use bazel’s
+[`local_repository` workspace rule](https://docs.bazel.build/versions/master/be/workspace.html#local_repository).
+Both approaches work well with the `repositories` attribute of `nixpkgs_package`.
+
+```bzl
+local_repository(
+  name = "local-nixpkgs",
+  path = "/path/to/nixpkgs",
+)
+
+nixpkgs_package(
+  name = "somepackage",
+  repositories = {
+    "nixpkgs": "@local-nixpkgs//:default.nix",
+  },
+  …
+)
+```
diff --git a/third_party/bazel/rules_nixpkgs/WORKSPACE b/third_party/bazel/rules_nixpkgs/WORKSPACE
new file mode 100644
index 000000000000..02db25031108
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/WORKSPACE
@@ -0,0 +1,99 @@
+workspace(name = "io_tweag_rules_nixpkgs")
+
+load(
+    "//nixpkgs:nixpkgs.bzl",
+    "nixpkgs_cc_configure",
+    "nixpkgs_git_repository",
+    "nixpkgs_local_repository",
+    "nixpkgs_package",
+)
+
+# For tests
+
+nixpkgs_git_repository(
+    name = "remote_nixpkgs",
+    remote = "https://github.com/NixOS/nixpkgs",
+    revision = "18.09",
+    sha256 = "6451af4083485e13daa427f745cbf859bc23cb8b70454c017887c006a13bd65e",
+)
+
+nixpkgs_local_repository(
+    name = "nixpkgs",
+    nix_file = "//:nixpkgs.nix",
+)
+
+nixpkgs_package(
+    name = "nixpkgs-git-repository-test",
+    attribute_path = "hello",
+    repositories = {"nixpkgs": "@remote_nixpkgs"},
+)
+
+nixpkgs_package(
+    name = "hello",
+    # Deliberately not repository, to test whether repositories works.
+    repositories = {"nixpkgs": "@nixpkgs"},
+)
+
+nixpkgs_package(
+    name = "expr-test",
+    nix_file_content = "let pkgs = import <nixpkgs> {}; in pkgs.hello",
+    # Deliberately not @nixpkgs, to test whether explict file works.
+    repositories = {"nixpkgs": "//:nixpkgs.nix"},
+)
+
+nixpkgs_package(
+    name = "attribute-test",
+    attribute_path = "hello",
+    repository = "@nixpkgs",
+)
+
+nixpkgs_package(
+    name = "expr-attribute-test",
+    attribute_path = "hello",
+    nix_file_content = "import <nixpkgs> {}",
+    repository = "@nixpkgs",
+)
+
+nixpkgs_package(
+    name = "nix-file-test",
+    attribute_path = "hello",
+    nix_file = "//tests:nixpkgs.nix",
+    repository = "@nixpkgs",
+)
+
+nixpkgs_package(
+    name = "nix-file-deps-test",
+    nix_file = "//tests:hello.nix",
+    nix_file_deps = ["//tests:pkgname.nix"],
+    repository = "@nixpkgs",
+)
+
+nixpkgs_package(
+    name = "output-filegroup-test",
+    nix_file = "//tests:output.nix",
+    repository = "@nixpkgs",
+)
+
+nixpkgs_package(
+    name = "extra-args-test",
+    nix_file_content = """
+{ packagePath }: (import <nixpkgs> {}).${packagePath}
+    """,
+    repository = "@nixpkgs",
+    nixopts = ["--argstr", "packagePath", "hello"],
+)
+
+nixpkgs_package(
+    name = "output-filegroup-manual-test",
+    build_file_content = """
+package(default_visibility = [ "//visibility:public" ])
+filegroup(
+    name = "manual-filegroup",
+    srcs = glob(["hi-i-exist", "hi-i-exist-too", "bin/*"]),
+)
+""",
+    nix_file = "//tests:output.nix",
+    repository = "@nixpkgs",
+)
+
+nixpkgs_cc_configure(repository = "@remote_nixpkgs")
diff --git a/third_party/bazel/rules_nixpkgs/nixpkgs.nix b/third_party/bazel/rules_nixpkgs/nixpkgs.nix
new file mode 100644
index 000000000000..4da4ebde4a66
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/nixpkgs.nix
@@ -0,0 +1,9 @@
+let
+  nixpkgsRev = "75942f96b3f7136cdc9cc7d9704824f17fabec02";
+  nixpkgsSha256 = "0ay4v4n856xl79ilym4w6vbp6pxzmn8l31j1ch98wa1lj7l71lgi";
+  nixpkgs = fetchTarball {
+    url = "https://github.com/nixos/nixpkgs/archive/${nixpkgsRev}.tar.gz";
+    sha256 = nixpkgsSha256;
+  };
+in
+import nixpkgs
diff --git a/third_party/bazel/rules_nixpkgs/nixpkgs/BUILD b/third_party/bazel/rules_nixpkgs/nixpkgs/BUILD
new file mode 100644
index 000000000000..00d87a19eaf0
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/nixpkgs/BUILD
@@ -0,0 +1,5 @@
+package(default_visibility = ["//visibility:public"])
+
+exports_files([
+    "nixpkgs.bzl",
+])
diff --git a/third_party/bazel/rules_nixpkgs/nixpkgs/BUILD.pkg b/third_party/bazel/rules_nixpkgs/nixpkgs/BUILD.pkg
new file mode 100644
index 000000000000..10809ee106fb
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/nixpkgs/BUILD.pkg
@@ -0,0 +1,16 @@
+package(default_visibility = ["//visibility:public"])
+
+filegroup(
+    name = "bin",
+    srcs = glob(["bin/*"]),
+)
+
+filegroup(
+    name = "lib",
+    srcs = glob(["lib/**/*.so*", "lib/**/*.dylib", "lib/**/*.a"]),
+)
+
+filegroup(
+    name = "include",
+    srcs = glob(["include/**/*.h"]),
+)
diff --git a/third_party/bazel/rules_nixpkgs/nixpkgs/nixpkgs.bzl b/third_party/bazel/rules_nixpkgs/nixpkgs/nixpkgs.bzl
new file mode 100644
index 000000000000..4396fb9c993a
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/nixpkgs/nixpkgs.bzl
@@ -0,0 +1,355 @@
+"""Rules for importing Nixpkgs packages."""
+
+load("@bazel_tools//tools/cpp:cc_configure.bzl", "cc_autoconf_impl")
+load("@bazel_tools//tools/cpp:lib_cc_configure.bzl", "get_cpu_value")
+
+def _nixpkgs_git_repository_impl(repository_ctx):
+    repository_ctx.file("BUILD")
+
+    # Make "@nixpkgs" (syntactic sugar for "@nixpkgs//:nixpkgs") a valid
+    # label for default.nix.
+    repository_ctx.symlink("default.nix", repository_ctx.name)
+
+    repository_ctx.download_and_extract(
+        url = "%s/archive/%s.tar.gz" % (repository_ctx.attr.remote, repository_ctx.attr.revision),
+        stripPrefix = "nixpkgs-" + repository_ctx.attr.revision,
+        sha256 = repository_ctx.attr.sha256,
+    )
+
+nixpkgs_git_repository = repository_rule(
+    implementation = _nixpkgs_git_repository_impl,
+    attrs = {
+        "revision": attr.string(mandatory = True),
+        "remote": attr.string(default = "https://github.com/NixOS/nixpkgs"),
+        "sha256": attr.string(),
+    },
+)
+
+def _nixpkgs_local_repository_impl(repository_ctx):
+    repository_ctx.file("BUILD")
+    if not bool(repository_ctx.attr.nix_file) != \
+       bool(repository_ctx.attr.nix_file_content):
+        fail("Specify one of 'nix_file' or 'nix_file_content' (but not both).")
+    if repository_ctx.attr.nix_file_content:
+        repository_ctx.file(
+            path = "default.nix",
+            content = repository_ctx.attr.nix_file_content,
+            executable = False,
+        )
+        target = repository_ctx.path("default.nix")
+    else:
+        target = repository_ctx.path(repository_ctx.attr.nix_file)
+        repository_ctx.symlink(target, target.basename)
+
+    # Make "@nixpkgs" (syntactic sugar for "@nixpkgs//:nixpkgs") a valid
+    # label for the target Nix file.
+    repository_ctx.symlink(target.basename, repository_ctx.name)
+
+    _symlink_nix_file_deps(repository_ctx, repository_ctx.attr.nix_file_deps)
+
+nixpkgs_local_repository = repository_rule(
+    implementation = _nixpkgs_local_repository_impl,
+    attrs = {
+        "nix_file": attr.label(allow_single_file = [".nix"]),
+        "nix_file_deps": attr.label_list(),
+        "nix_file_content": attr.string(),
+    },
+)
+
+def _is_supported_platform(repository_ctx):
+    return repository_ctx.which("nix-build") != None
+
+def _nixpkgs_package_impl(repository_ctx):
+    repository = repository_ctx.attr.repository
+    repositories = repository_ctx.attr.repositories
+
+    # Is nix supported on this platform?
+    not_supported = not _is_supported_platform(repository_ctx)
+    # Should we fail if Nix is not supported?
+    fail_not_supported = repository_ctx.attr.fail_not_supported
+
+    if repository and repositories or not repository and not repositories:
+        fail("Specify one of 'repository' or 'repositories' (but not both).")
+    elif repository:
+        repositories = {repository_ctx.attr.repository: "nixpkgs"}
+
+    if repository_ctx.attr.build_file and repository_ctx.attr.build_file_content:
+        fail("Specify one of 'build_file' or 'build_file_content', but not both.")
+    elif repository_ctx.attr.build_file:
+        repository_ctx.symlink(repository_ctx.attr.build_file, "BUILD")
+    elif repository_ctx.attr.build_file_content:
+        repository_ctx.file("BUILD", content = repository_ctx.attr.build_file_content)
+    else:
+        repository_ctx.template("BUILD", Label("@io_tweag_rules_nixpkgs//nixpkgs:BUILD.pkg"))
+
+    strFailureImplicitNixpkgs = (
+        "One of 'repositories', 'nix_file' or 'nix_file_content' must be provided. " +
+        "The NIX_PATH environment variable is not inherited."
+    )
+
+    expr_args = []
+    if repository_ctx.attr.nix_file and repository_ctx.attr.nix_file_content:
+        fail("Specify one of 'nix_file' or 'nix_file_content', but not both.")
+    elif repository_ctx.attr.nix_file:
+        repository_ctx.symlink(repository_ctx.attr.nix_file, "default.nix")
+    elif repository_ctx.attr.nix_file_content:
+        expr_args = ["-E", repository_ctx.attr.nix_file_content]
+    elif not repositories:
+        fail(strFailureImplicitNixpkgs)
+    else:
+        expr_args = ["-E", "import <nixpkgs> {}"]
+
+    _symlink_nix_file_deps(repository_ctx, repository_ctx.attr.nix_file_deps)
+
+    expr_args.extend([
+        "-A",
+        repository_ctx.attr.attribute_path if repository_ctx.attr.nix_file or repository_ctx.attr.nix_file_content else repository_ctx.attr.attribute_path or repository_ctx.attr.name,
+        # Creating an out link prevents nix from garbage collecting the store path.
+        # nixpkgs uses `nix-support/` for such house-keeping files, so we mirror them
+        # and use `bazel-support/`, under the assumption that no nix package has
+        # a file named `bazel-support` in its root.
+        # A `bazel clean` deletes the symlink and thus nix is free to garbage collect
+        # the store path.
+        "--out-link",
+        "bazel-support/nix-out-link",
+    ])
+
+    expr_args.extend(repository_ctx.attr.nixopts)
+
+    # If repositories is not set, leave empty so nix will fail
+    # unless a pinned nixpkgs is set in the `nix_file` attribute.
+    nix_path = ""
+    if repositories:
+        nix_path = ":".join(
+            [
+                (path_name + "=" + str(repository_ctx.path(target)))
+                for (target, path_name) in repositories.items()
+            ],
+        )
+    elif not (repository_ctx.attr.nix_file or repository_ctx.attr.nix_file_content):
+        fail(strFailureImplicitNixpkgs)
+
+
+    if not_supported and fail_not_supported:
+        fail("Platform is not supported (see 'fail_not_supported')")
+    elif not_supported:
+        return
+    else:
+        nix_build_path = _executable_path(
+            repository_ctx,
+            "nix-build",
+            extra_msg = "See: https://nixos.org/nix/",
+        )
+        nix_build = [nix_build_path] + expr_args
+
+        # Large enough integer that Bazel can still parse. We don't have
+        # access to MAX_INT and 0 is not a valid timeout so this is as good
+        # as we can do.
+        timeout = 1073741824
+        exec_result = _execute_or_fail(
+            repository_ctx,
+            nix_build,
+            failure_message = "Cannot build Nix attribute '{}'.".format(
+                repository_ctx.attr.attribute_path,
+            ),
+            quiet = False,
+            timeout = timeout,
+            environment = dict(NIX_PATH = nix_path),
+        )
+        output_path = exec_result.stdout.splitlines()[-1]
+
+        # Build a forest of symlinks (like new_local_package() does) to the
+        # Nix store.
+        for target in _find_children(repository_ctx, output_path):
+            basename = target.rpartition("/")[-1]
+            repository_ctx.symlink(target, basename)
+
+_nixpkgs_package = repository_rule(
+    implementation = _nixpkgs_package_impl,
+    attrs = {
+        "attribute_path": attr.string(),
+        "nix_file": attr.label(allow_single_file = [".nix"]),
+        "nix_file_deps": attr.label_list(),
+        "nix_file_content": attr.string(),
+        "repositories": attr.label_keyed_string_dict(),
+        "repository": attr.label(),
+        "build_file": attr.label(),
+        "build_file_content": attr.string(),
+        "nixopts": attr.string_list(),
+        "fail_not_supported": attr.bool(default = True, doc = """
+            If set to True (default) this rule will fail on platforms which do not support Nix (e.g. Windows). If set to False calling this rule will succeed but no output will be generated.
+                                        """),
+    },
+)
+
+def nixpkgs_package(*args, **kwargs):
+    # Because of https://github.com/bazelbuild/bazel/issues/5356 we can't
+    # directly pass a dict from strings to labels to the rule (which we'd like
+    # for the `repositories` arguments), but we can pass a dict from labels to
+    # strings. So we swap the keys and the values (assuming they all are
+    # distinct).
+    if "repositories" in kwargs:
+        inversed_repositories = {value: key for (key, value) in kwargs["repositories"].items()}
+        kwargs.pop("repositories")
+        _nixpkgs_package(
+            repositories = inversed_repositories,
+            *args,
+            **kwargs
+        )
+    else:
+        _nixpkgs_package(*args, **kwargs)
+
+def nixpkgs_cc_autoconf_impl(repository_ctx):
+    cpu_value = get_cpu_value(repository_ctx)
+    if not _is_supported_platform(repository_ctx):
+        cc_autoconf_impl(repository_ctx)
+        return
+
+    # Calling repository_ctx.path() on anything but a regular file
+    # fails. So the roundabout way to do the same thing is to find
+    # a regular file we know is in the workspace (i.e. the WORKSPACE
+    # file itself) and then use dirname to get the path of the workspace
+    # root.
+    workspace_file_path = repository_ctx.path(
+        Label("@nixpkgs_cc_toolchain//:WORKSPACE"),
+    )
+    workspace_root = _execute_or_fail(
+        repository_ctx,
+        ["dirname", workspace_file_path],
+    ).stdout.rstrip()
+
+    # Make a list of all available tools in the Nix derivation. Override
+    # the Bazel autoconfiguration with the tools we found.
+    bin_contents = _find_children(repository_ctx, workspace_root + "/bin")
+    overriden_tools = {
+        tool: entry
+        for entry in bin_contents
+        for tool in [entry.rpartition("/")[-1]]  # Compute basename
+    }
+    cc_autoconf_impl(repository_ctx, overriden_tools = overriden_tools)
+
+nixpkgs_cc_autoconf = repository_rule(
+    implementation = nixpkgs_cc_autoconf_impl,
+    # Copied from
+    # https://github.com/bazelbuild/bazel/blob/master/tools/cpp/cc_configure.bzl.
+    # Keep in sync.
+    environ = [
+        "ABI_LIBC_VERSION",
+        "ABI_VERSION",
+        "BAZEL_COMPILER",
+        "BAZEL_HOST_SYSTEM",
+        "BAZEL_LINKOPTS",
+        "BAZEL_PYTHON",
+        "BAZEL_SH",
+        "BAZEL_TARGET_CPU",
+        "BAZEL_TARGET_LIBC",
+        "BAZEL_TARGET_SYSTEM",
+        "BAZEL_USE_CPP_ONLY_TOOLCHAIN",
+        "BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN",
+        "BAZEL_USE_LLVM_NATIVE_COVERAGE",
+        "BAZEL_VC",
+        "BAZEL_VS",
+        "BAZEL_LLVM",
+        "USE_CLANG_CL",
+        "CC",
+        "CC_CONFIGURE_DEBUG",
+        "CC_TOOLCHAIN_NAME",
+        "CPLUS_INCLUDE_PATH",
+        "GCOV",
+        "HOMEBREW_RUBY_PATH",
+        "SYSTEMROOT",
+        "VS90COMNTOOLS",
+        "VS100COMNTOOLS",
+        "VS110COMNTOOLS",
+        "VS120COMNTOOLS",
+        "VS140COMNTOOLS",
+    ],
+)
+
+def nixpkgs_cc_configure(
+        repository = None,
+        repositories = {},
+        nix_file = None,
+        nix_file_deps = None,
+        nix_file_content = None,
+        nixopts = []):
+    """Use a CC toolchain from Nixpkgs. No-op if not a nix-based platform.
+
+    By default, Bazel auto-configures a CC toolchain from commands (e.g.
+    `gcc`) available in the environment. To make builds more hermetic, use
+    this rule to specific explicitly which commands the toolchain should
+    use.
+    """
+    if not nix_file and not nix_file_content:
+        nix_file_content = """
+          with import <nixpkgs> {}; buildEnv {
+            name = "bazel-cc-toolchain";
+            paths = [ stdenv.cc binutils ];
+          }
+        """
+    nixpkgs_package(
+        name = "nixpkgs_cc_toolchain",
+        repository = repository,
+        repositories = repositories,
+        nix_file = nix_file,
+        nix_file_deps = nix_file_deps,
+        nix_file_content = nix_file_content,
+        build_file_content = """exports_files(glob(["bin/*"]))""",
+        nixopts = nixopts,
+    )
+
+    # Following lines should match
+    # https://github.com/bazelbuild/bazel/blob/master/tools/cpp/cc_configure.bzl#L93.
+    nixpkgs_cc_autoconf(name = "local_config_cc")
+    native.bind(name = "cc_toolchain", actual = "@local_config_cc//:toolchain")
+    native.register_toolchains("@local_config_cc//:all")
+
+def _execute_or_fail(repository_ctx, arguments, failure_message = "", *args, **kwargs):
+    """Call repository_ctx.execute() and fail if non-zero return code."""
+    result = repository_ctx.execute(arguments, *args, **kwargs)
+    if result.return_code:
+        outputs = dict(
+            failure_message = failure_message,
+            arguments = arguments,
+            return_code = result.return_code,
+            stderr = result.stderr,
+        )
+        fail("""
+{failure_message}
+Command: {arguments}
+Return code: {return_code}
+Error output:
+{stderr}
+""".format(**outputs))
+    return result
+
+def _find_children(repository_ctx, target_dir):
+    find_args = [
+        _executable_path(repository_ctx, "find"),
+        "-L",
+        target_dir,
+        "-maxdepth",
+        "1",
+        # otherwise the directory is printed as well
+        "-mindepth",
+        "1",
+        # filenames can contain \n
+        "-print0",
+    ]
+    exec_result = _execute_or_fail(repository_ctx, find_args)
+    return exec_result.stdout.rstrip("\0").split("\0")
+
+def _executable_path(repository_ctx, exe_name, extra_msg = ""):
+    """Try to find the executable, fail with an error."""
+    path = repository_ctx.which(exe_name)
+    if path == None:
+        fail("Could not find the `{}` executable in PATH.{}\n"
+            .format(exe_name, " " + extra_msg if extra_msg else ""))
+    return path
+
+def _symlink_nix_file_deps(repository_ctx, deps):
+    """Introduce an artificial dependency with a bogus name on each input."""
+    for dep in deps:
+        components = [c for c in [dep.workspace_root, dep.package, dep.name] if c]
+        link = "/".join(components).replace("_", "_U").replace("/", "_S")
+        repository_ctx.symlink(dep, link)
diff --git a/third_party/bazel/rules_nixpkgs/shell.nix b/third_party/bazel/rules_nixpkgs/shell.nix
new file mode 100644
index 000000000000..23b3e10da143
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/shell.nix
@@ -0,0 +1,11 @@
+{ pkgs ? import ./nixpkgs.nix {} }:
+
+with pkgs;
+
+mkShell {
+  buildInputs = [
+    bazel
+    gcc
+    nix
+  ];
+}
diff --git a/third_party/bazel/rules_nixpkgs/tests/BUILD b/third_party/bazel/rules_nixpkgs/tests/BUILD
new file mode 100644
index 000000000000..68e4f4c58079
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/tests/BUILD
@@ -0,0 +1,58 @@
+package(default_testonly = 1)
+
+[
+    # All of these tests use the "hello" binary to see
+    # whether different invocations of `nixpkgs_package`
+    # produce a valid bazel repository.
+    sh_test(
+        name = "run-{0}".format(test),
+        timeout = "short",
+        srcs = ["test_bin.sh"],
+        args = ["$(location @{0}//:bin)".format(test)],
+        data = ["@{0}//:bin".format(test)],
+    )
+    for test in [
+        "hello",
+        "expr-test",
+        "attribute-test",
+        "expr-attribute-test",
+        "nix-file-test",
+        "nix-file-deps-test",
+        "nixpkgs-git-repository-test",
+    ]
+] + [
+    # These tests use the nix package generated by ./output.nix
+
+    # Checks whether the `:include` filegroup of `nixpkgs_package`
+    # repositories works as intended
+    # (that the expected number of files are inside the target)
+    sh_test(
+        name = "run-test-include",
+        timeout = "short",
+        srcs = ["test_output.sh"],
+        args = [
+            "2",
+            "$(locations @output-filegroup-test//:include)",
+        ],
+        data = ["@output-filegroup-test//:include"],
+    ),
+
+    # Checks whether specifying a manual filegroup in the
+    # `nixpkgs_package` BUILD file works as well.
+    sh_test(
+        name = "run-test-manual-filegroup",
+        timeout = "short",
+        srcs = ["test_output.sh"],
+        args = [
+            "3",
+            "$(locations @output-filegroup-manual-test//:manual-filegroup)",
+        ],
+        data = ["@output-filegroup-manual-test//:manual-filegroup"],
+    ),
+]
+
+# Test nixpkgs_cc_configure() by building some CC code.
+cc_binary(
+    name = "cc-test",
+    srcs = ["cc-test.cc"],
+)
diff --git a/third_party/bazel/rules_nixpkgs/tests/cc-test.cc b/third_party/bazel/rules_nixpkgs/tests/cc-test.cc
new file mode 100644
index 000000000000..76e8197013aa
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/tests/cc-test.cc
@@ -0,0 +1 @@
+int main() { return 0; }
diff --git a/third_party/bazel/rules_nixpkgs/tests/hello.nix b/third_party/bazel/rules_nixpkgs/tests/hello.nix
new file mode 100644
index 000000000000..285e93f7e803
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/tests/hello.nix
@@ -0,0 +1,3 @@
+with import ./pkgname.nix;
+let pkgs = import <nixpkgs> {}; in builtins.getAttr pkgname pkgs
+
diff --git a/third_party/bazel/rules_nixpkgs/tests/nixpkgs.nix b/third_party/bazel/rules_nixpkgs/tests/nixpkgs.nix
new file mode 100644
index 000000000000..cdd1f58f0ea5
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/tests/nixpkgs.nix
@@ -0,0 +1 @@
+import <nixpkgs> {}
diff --git a/third_party/bazel/rules_nixpkgs/tests/output.nix b/third_party/bazel/rules_nixpkgs/tests/output.nix
new file mode 100644
index 000000000000..a0269adb6679
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/tests/output.nix
@@ -0,0 +1,13 @@
+with import <nixpkgs> {};
+
+runCommand "some-output" {
+  preferLocalBuild = true;
+  allowSubstitutes = false;
+} ''
+  mkdir -p $out/{bin,include/mylib}
+  touch $out/hi-i-exist
+  touch $out/hi-i-exist-too
+  touch $out/bin/im-a-binary
+  touch $out/include/mylib/im-a-header.h
+  touch $out/include/mylib/im-also-a-header.h
+''
diff --git a/third_party/bazel/rules_nixpkgs/tests/pkgname.nix b/third_party/bazel/rules_nixpkgs/tests/pkgname.nix
new file mode 100644
index 000000000000..9a4e13899786
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/tests/pkgname.nix
@@ -0,0 +1 @@
+{ pkgname = "hello"; }
diff --git a/third_party/bazel/rules_nixpkgs/tests/test_bin.sh b/third_party/bazel/rules_nixpkgs/tests/test_bin.sh
new file mode 100755
index 000000000000..f4df0931b987
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/tests/test_bin.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+
+echo "Executing: " $@
+$@
diff --git a/third_party/bazel/rules_nixpkgs/tests/test_output.sh b/third_party/bazel/rules_nixpkgs/tests/test_output.sh
new file mode 100755
index 000000000000..29f2735cf4ca
--- /dev/null
+++ b/third_party/bazel/rules_nixpkgs/tests/test_output.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+# first param is the expected number of files given by `locations`
+expected_length="$1"
+
+# rest of the arguments are files
+shift
+no_of_files=$#
+
+if [ "$no_of_files" -ne "$expected_length" ]; then
+    echo "Should have received $expected_length files, but got $no_of_files:"
+    for f in "$@"; do
+        echo "$f"
+    done
+    exit 1
+fi