├── .github └── workflows │ ├── check.yml │ └── integration.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── action.yaml └── src ├── app.rs ├── main.rs └── parser.rs /.github/workflows/check.yml: -------------------------------------------------------------------------------- 1 | name: Check 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: {} 8 | 9 | jobs: 10 | check: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: Swatinem/rust-cache@v2 15 | - run: | 16 | cargo fmt --check 17 | cargo clippy --all-targets --all-features -- -D warnings 18 | cargo test --all-targets --all-features 19 | ci_pass: 20 | if: always() 21 | runs-on: ubuntu-latest 22 | needs: [ check ] 23 | steps: 24 | - uses: re-actors/alls-green@release/v1 25 | with: 26 | jobs: ${{ toJSON(needs) }} 27 | 28 | -------------------------------------------------------------------------------- /.github/workflows/integration.yml: -------------------------------------------------------------------------------- 1 | name: Integration 2 | 3 | on: 4 | push: 5 | tags: [ v1 ] 6 | 7 | jobs: 8 | integration: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | - uses: cachix/install-nix-action@v30 13 | - uses: cachix/cachix-action@v15 14 | with: 15 | name: holochain-ci 16 | - name: Test 17 | uses: ./ 18 | with: 19 | derivation: github:holochain/holonix?ref=main-0.4#devShells.x86_64-linux.default 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 4 4 | 5 | [[package]] 6 | name = "anyhow" 7 | version = "1.0.95" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04" 10 | 11 | [[package]] 12 | name = "memchr" 13 | version = "2.7.4" 14 | source = "registry+https://github.com/rust-lang/crates.io-index" 15 | checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" 16 | 17 | [[package]] 18 | name = "minimal-lexical" 19 | version = "0.2.1" 20 | source = "registry+https://github.com/rust-lang/crates.io-index" 21 | checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" 22 | 23 | [[package]] 24 | name = "nix-cache-check" 25 | version = "0.1.0" 26 | dependencies = [ 27 | "anyhow", 28 | "nom", 29 | ] 30 | 31 | [[package]] 32 | name = "nom" 33 | version = "7.1.3" 34 | source = "registry+https://github.com/rust-lang/crates.io-index" 35 | checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" 36 | dependencies = [ 37 | "memchr", 38 | "minimal-lexical", 39 | ] 40 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "nix-cache-check" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | anyhow = "1.0.75" 8 | nom = "7.1.3" 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nix-cache-check 2 | 3 | [![Integration](https://github.com/holochain/nix-cache-check/actions/workflows/integration.yml/badge.svg)](https://github.com/holochain/nix-cache-check/actions/workflows/integration.yml) 4 | 5 | A GitHub action to check whether a Nix flake is properly cached. It builds 6 | a derivation and fails if anything needs building rather than fetching 7 | from a remote cache. You can permit some derivations to be built using the 8 | `permit_build_derivations` option. 9 | 10 | _Health warning_: This action is scanning the output of `nix build`. 11 | 12 | ### Example usage 13 | 14 | ``` 15 | jobs: 16 | check: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@v4 20 | - uses: cachix/install-nix-action@v22 21 | - uses: cachix/cachix-action@v12 22 | with: 23 | name: my-cache 24 | - name: Check the cache 25 | uses: holochain/nix-cache-check@v1 26 | with: 27 | derivation: .#my-derivation 28 | ``` 29 | 30 | There is also a working example (as long as the build is currently passing!) in the [integration test](https://github.com/holochain/nix-cache-check/blob/main/.github/workflows/integration.yml) for this action. 31 | -------------------------------------------------------------------------------- /action.yaml: -------------------------------------------------------------------------------- 1 | name: nix-cache-check 2 | description: Check that the contents of a Nix cache or remote store is up-to-date 3 | inputs: 4 | derivation: 5 | description: 'The derivation to build such as "github:holochain/holochain#devShells.x86_64-darwin.holonix"' 6 | required: true 7 | extra_build_args: 8 | description: 'Extra args to pass to `nix build`' 9 | required: false 10 | default: '' 11 | permit_build_derivations: 12 | description: "The comma-separated names of derivations which are permitted to be built rather than fetched from the cache" 13 | required: false 14 | default: '' 15 | runs: 16 | using: 'composite' 17 | steps: 18 | - name: Check 19 | shell: bash 20 | run: | 21 | cargo install --locked --git https://github.com/holochain/nix-cache-check.git --tag v1 22 | nix-cache-check 23 | env: 24 | DERIVATION: ${{ inputs.derivation }} 25 | EXTRA_BUILD_ARG: ${{ inputs.extra_build_args }} 26 | PERMIT_BUILD_DERIVATIONS: ${{ inputs.permit_build_derivations }} 27 | 28 | branding: 29 | icon: arrow-down-circle 30 | color: green 31 | -------------------------------------------------------------------------------- /src/app.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::HashSet, 3 | io::{stdout, Write}, 4 | process::{exit, Stdio}, 5 | }; 6 | 7 | use anyhow::anyhow; 8 | 9 | use crate::parser::{parse_log, CacheInfo}; 10 | 11 | fn from_csv(input: &str) -> anyhow::Result> { 12 | Ok(input 13 | .split(",") 14 | .filter_map(|v| { 15 | let x = v.trim().to_owned(); 16 | if !x.is_empty() { 17 | Some(x) 18 | } else { 19 | None 20 | } 21 | }) 22 | .collect()) 23 | } 24 | 25 | pub fn run_app() -> anyhow::Result<()> { 26 | let mut cmd = std::process::Command::new("nix"); 27 | cmd.stderr(Stdio::piped()) 28 | .arg("build") 29 | .arg("--dry-run") 30 | .arg("-v") 31 | .arg("--log-format") 32 | .arg("raw"); 33 | 34 | if let Ok(build_args) = std::env::var("EXTRA_BUILD_ARG") { 35 | for arg in build_args.split(" ") { 36 | if !arg.trim().is_empty() { 37 | cmd.arg(arg); 38 | } 39 | } 40 | } 41 | 42 | cmd.arg(std::env::var("DERIVATION")?); 43 | 44 | println!("Starting Nix build"); 45 | stdout().flush()?; 46 | 47 | let output = cmd 48 | .output() 49 | .map_err(|e| anyhow!("Failed to spawn the Nix build: {:?}", e))?; 50 | 51 | println!("Finished Nix build"); 52 | stdout().flush()?; 53 | 54 | if !output.status.success() { 55 | println!("Nix build command failed, dumping its logs"); 56 | stdout().write_all(&output.stderr)?; 57 | exit(1); 58 | } 59 | 60 | let stderr = String::from_utf8(output.stderr)?; 61 | 62 | let cache_info = match parse_log(stderr.as_str()) { 63 | Ok(ci) => ci, 64 | Err(e) => { 65 | eprintln!("There was a problem parsing the input: {}", e); 66 | eprintln!("The original input was: {}", stderr); 67 | exit(1); 68 | } 69 | }; 70 | 71 | println!( 72 | "Found [{}] to derivations build and [{}] to fetch", 73 | cache_info.get_derivations_to_build().len(), 74 | cache_info.get_derivations_to_fetch().len() 75 | ); 76 | stdout().flush()?; 77 | 78 | if validate( 79 | from_csv( 80 | std::env::var("PERMIT_BUILD_DERIVATIONS") 81 | .unwrap_or_else(|_| "".to_string()) 82 | .as_str(), 83 | )?, 84 | &cache_info, 85 | )? { 86 | println!("Validation passed!"); 87 | } else { 88 | eprintln!("Validation failed!"); 89 | eprintln!( 90 | "To build: \n\t{}", 91 | cache_info.get_derivations_to_build().join("\n\t") 92 | ); 93 | eprintln!( 94 | "To fetch: \n\t{}", 95 | cache_info.get_derivations_to_fetch().join("\n\t") 96 | ); 97 | return Err(anyhow!("Validation failed")); 98 | } 99 | 100 | Ok(()) 101 | } 102 | 103 | pub fn validate( 104 | permit_build_derivations: HashSet, 105 | cache_info: &CacheInfo, 106 | ) -> anyhow::Result { 107 | let mut all_passed = true; 108 | 109 | let mut permits_used = HashSet::new(); 110 | 111 | for to_build in cache_info.get_derivations_to_build() { 112 | let to_build_name: String = to_build 113 | .strip_suffix(".drv") 114 | .ok_or(anyhow!("Not a derivation? {}", to_build))? 115 | .split("-") 116 | .skip(1) 117 | .collect::>() 118 | .join("-"); 119 | 120 | if permit_build_derivations.contains(to_build_name.as_str()) { 121 | println!("Permitting [{}] to be built", to_build); 122 | permits_used.insert(to_build_name); 123 | continue; 124 | } 125 | 126 | eprintln!( 127 | "Found [{}] which requires building but is not in the permitted set", 128 | to_build 129 | ); 130 | all_passed = false; 131 | } 132 | 133 | for unused in permit_build_derivations.difference(&permits_used) { 134 | println!("Warning: You have marked {} as permitted to be built but it is either cached or no longer part of this derivation", unused); 135 | } 136 | 137 | Ok(all_passed) 138 | } 139 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use app::run_app; 2 | 3 | mod app; 4 | mod parser; 5 | 6 | fn main() -> anyhow::Result<()> { 7 | run_app() 8 | } 9 | -------------------------------------------------------------------------------- /src/parser.rs: -------------------------------------------------------------------------------- 1 | use nom::{ 2 | bytes::complete::{take, take_till, take_until}, 3 | character::{ 4 | complete::{newline, space1}, 5 | is_newline, 6 | }, 7 | combinator::opt, 8 | error::{context, convert_error, ContextError}, 9 | multi::fold_many1, 10 | sequence::{preceded, tuple}, 11 | Finish, IResult, 12 | }; 13 | 14 | #[derive(Debug)] 15 | pub struct CacheInfo { 16 | derivations_to_build: Vec, 17 | derivations_to_fetch: Vec, 18 | } 19 | 20 | impl CacheInfo { 21 | pub fn get_derivations_to_build(&self) -> &[String] { 22 | &self.derivations_to_build 23 | } 24 | 25 | pub fn get_derivations_to_fetch(&self) -> &[String] { 26 | &self.derivations_to_fetch 27 | } 28 | } 29 | 30 | pub fn parse_log(log: &str) -> anyhow::Result { 31 | let (_, info) = match do_parse(log).finish() { 32 | Ok(r) => r, 33 | Err(e) => { 34 | return Err(anyhow::anyhow!( 35 | "Failed to parse: {}", 36 | convert_error(log, e) 37 | )); 38 | } 39 | }; 40 | 41 | Ok(info) 42 | } 43 | 44 | fn do_parse<'a, E>(input: &'a str) -> IResult<&'a str, CacheInfo, E> 45 | where 46 | E: nom::error::ParseError<&'a str> + ContextError<&'a str>, 47 | { 48 | match tuple(( 49 | opt(preceded( 50 | context( 51 | "start-of-built-derivations", 52 | tuple(( 53 | take_until("these"), 54 | take(5usize), 55 | take_until("built:"), 56 | take(6usize), 57 | newline, 58 | )), 59 | ), 60 | fold_many1( 61 | context("build-derivation-line", parse_line::), 62 | Vec::new, 63 | |mut acc, line| { 64 | acc.push(line); 65 | acc 66 | }, 67 | ), 68 | )), 69 | opt(preceded( 70 | context( 71 | "start-of-fetched-derivations", 72 | tuple(( 73 | take_until("these "), 74 | take(6usize), 75 | take_until("fetched"), 76 | take(7usize), 77 | take_until(":"), 78 | take(1usize), 79 | newline, 80 | )), 81 | ), 82 | fold_many1( 83 | context("fetch-derivation-line", parse_line::), 84 | Vec::new, 85 | |mut acc, line| { 86 | acc.push(line); 87 | acc 88 | }, 89 | ), 90 | )), 91 | ))(input) 92 | { 93 | Ok((rest, (to_build, to_fetch))) => Ok(( 94 | rest, 95 | CacheInfo { 96 | derivations_to_build: to_build.unwrap_or_else(Vec::new), 97 | derivations_to_fetch: to_fetch.unwrap_or_else(Vec::new), 98 | }, 99 | )), 100 | Err(e) => Err(e), 101 | } 102 | } 103 | 104 | fn parse_line<'a, E>(input: &'a str) -> IResult<&'a str, String, E> 105 | where 106 | E: nom::error::ParseError<&'a str>, 107 | { 108 | match tuple((space1, take_till(|c| is_newline(c as u8)), newline))(input) { 109 | Ok((rest, (_sp, derivation, _newline))) => Ok((rest, derivation.to_string())), 110 | Err(e) => Err(e), 111 | } 112 | } 113 | --------------------------------------------------------------------------------