├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── USAGE.md ├── all-crate-grep ├── Cargo.toml └── main.rs ├── all-crate-storage ├── Cargo.toml ├── bin │ ├── analyze-all-crates.rs │ ├── create-crate-storage.rs │ ├── create-mb-crate-storage.rs │ ├── diff-all-crates.rs │ ├── diff.rs │ └── download-all-crates.rs ├── blob_crate_storage.rs ├── blob_storage.rs ├── blob_storage_test.rs ├── crate_storage.rs ├── diff.rs ├── hash_ctx.rs ├── lib.rs ├── multi_blob.rs ├── multi_blob_crate_storage.rs ├── reconstruction.rs └── registry │ ├── mod.rs │ ├── registry.rs │ └── statistics.rs ├── cargo-local-serve ├── Cargo.toml ├── code_format.rs ├── escape.rs ├── main.rs ├── markdown_render.rs ├── registry_data.rs ├── site │ ├── static │ │ ├── package-logo.svg │ │ └── style.css │ └── templates │ │ ├── crate.hbs │ │ ├── error.hbs │ │ ├── file-content.hbs │ │ ├── file-listing.hbs │ │ ├── frame.hbs │ │ ├── index.hbs │ │ ├── reverse_dependencies.hbs │ │ ├── search.hbs │ │ └── versions.hbs └── syntect_format.rs └── config.toml.example /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | *swp 4 | crate-archives 5 | crate-constr-archives 6 | /config.toml 7 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["all-crate-storage", "cargo-local-serve", "all-crate-grep"] 3 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Cargo local serve 4 | 5 | Serve a local, offline, clone of `crates.io`. 6 | 7 | DISCLAIMER: this is alpha software. Many features don't work yet 8 | or are only prototyped. 9 | 10 | Uses the crates you have cached locally to display a clone of the `crates.io` interface to users. 11 | 12 | A second (and later) goal of this project is to extend with writeability, aka enabling a local crates.io like service for companies, mars colonists, etc where you can push your crates to, similar to how `crates.io` is working. 13 | 14 | The `crates.io` team has publicly stated that the only goal of the codebase is to drive the site itself and no local clones of it. That's where this project comes in : it is tailored for that use case precisely. Aka, less setup but also only a subset of the features. 15 | 16 | Some little demo for usage: 17 | 18 | 1. clone 19 | 2. do `cargo run -p cargo-local-serve` inside the repo 20 | 3. navigate your browser to some random crate, e.g. `http://localhost:3000/crate/winapi` or `http://localhost:3000/crate/futures` 21 | 22 | ## TODO 23 | 24 | * Proper error handling. Right now we are using unwrap and panics everywhere or cast stuff to Option :) 25 | * Improve compression of the blob storage by a) creating a graph of all blobs in relation to each other. How two blobs relate is an interesting question, the most simple way is to let files with the same name relate to each other iff they are similar b) for each connected component, creating a minimum spanning tree c) splitting up the trees until some okay-ish size per tree is reached (maybe like up to 50 blobs per unit??) d) emitting each such created component into one dedicated superblob that contains the set of blobs 26 | * Implement global scoring of crates by most depended on (directly), most depended on (transitive closure), IDK what else 27 | * Obtain list of mirrored versions of a crate 28 | * Add site for when the given version is not mirrored 29 | * Implement "browse crates" page 30 | * Upload feature 31 | 32 | ## Done 33 | 34 | * Index page that displays a few "top" crates by various scorings 35 | * Implement "versions/cratename" page 36 | * Render the markdown using pulldown-cmark 37 | * Source code formatting inside that rendering using syntect 38 | * Search feature 39 | * Creation of blob crate storage files that can store the entirety of crates.io 40 | 41 | ## Design principles 42 | 43 | The visual design has been heavily lended from the design 44 | of the main `crates.io` website. It is a very beautiful design and well known to the Rust developer community. 45 | 46 | The project is guided by the following principles: 47 | 48 | 1. Any site shoud load fast and be low on resources. 49 | Any argument of the form "but nobody uses dialup any more" is not legitimate: 50 | Instead of being an opportunity for developers to waste stuff, a fast connection should make sites load faster! 51 | 2. While the site may feature Javascript based enhancements, 52 | if a feature can be implemented without Javascript, it should be. 53 | The site's main functionality should work even if no javascript 54 | is available. 55 | 3. In order to have the best developer and setup experience, 56 | no npm or node should be required in developing or running the site. 57 | Additionally, anything that calls itself a Javascript "framework" is disallowed (except for VanillaJs :p), 58 | as these require additional learning and lock you in. 59 | Any Javascript dependencies should be included manually and be small and lean, 60 | but generally Javascript dependencies should be avoided in order to be lean! 61 | 4. Only stable Rust may be used so that the service can be installed and used by a wide audience. 62 | 5. Usage of vendor prefixed features is forbidden. If a feature has been 63 | published as a Recommendation/Standard since, addition of vendor prefixes 64 | for it is tolerated if there is no other way to bring the feature 65 | to a targeted browser without Javascript. 66 | 6. The site should work without any internet available. 67 | Even if internet is available, there should be no requests by the frontend 68 | to any domain but the one the site lives on. 69 | Privacy invading malware like Google analytics is disallowed! 70 | 71 | ## FAQ 72 | 73 | ### Do you want main crates.io to adopt your frontend? 74 | 75 | I definitely encourage `crates.io` maintainers to take a look at my codebase and maybe draw inspiration for some improvements inside their own frontend. This is an open source project, everything is up for the grabs! But the main focus of this project is not to write a new frontend that covers the whole set of features that `crates.io` does. 76 | 77 | ### Do you think Ember is bad? If no, why didn't you use it then? 78 | 79 | Ember is being used by many quite renown companies. If it were bad, they wouldn't be using it. In fact, this project itself is using the `handlebars` technology that has a deep relationship to ember. 80 | 81 | I'm not the maintainer of `crates.io` so I don't want to tell them what to do. But for my project, I have chosen to not adopt ember or any other [single page applications](https://en.wikipedia.org/wiki/Single-page_application) (SPA) based approach. 82 | 83 | The basic idea of designing web sites as single page applications (SPAs) is to *save* on bandwidth by just transporting a *small* json file over the wire. However, for crates I've tested, the json file that ember-powered `crates.io` sends over the network is *larger* than the entire HTML that my frontend sends over the wire. The second thing that SPA is about is having dynamic pages with content that changes over time either from itself (watching a live chat) or through interaction with the user (participating in a live chat). Now this project is about a mostly static site, so we'd get little gain here as well. 84 | 85 | The third reason is a more security oriented one: if your entire interface with the application state is via json, it can be reasoned about by security tools in a much easier fashion. Also, any exploit in the rendering code would not allow you to escalate to a breach. 86 | 87 | The first point is covered here by using handlebars: as handlebars uses json, there is already a json based interface. It is just inside the server! The second point is being approached by using memory-safe Rust everywhere. This obviously doesn't help with exploitable libraries, however they should mostly consist of safe Rust as well. 88 | 89 | `crates.io` would probably see huge improvements in performance by using [ember-fastboot](https://ember-fastboot.com/). However, this project targets to be even leaner than that. 90 | 91 | ### Why did you choose the Iron framework? 92 | 93 | I'm in fact a big fan of the [rocket](https://rocket.rs/) framework: 94 | 95 | * Rocket makes stuff like URL parsing much easier than iron thanks to its macros. In general, the boilerplate is much less. 96 | * Rocket is monolithic. With decentralized frameworks like iron, the documentation is split up, you never know whether crate A is compatible with crate B. This issue only gets worse when you have breaking changes involved: which version of crate A is meant to be used together with which version of crate B? Is crate B even deprecated? Sure, the idea to have crates focussed on small tasks is really great, but when the crates become *too* small, I think it is better to offer a monolithic API to users. You can still have optional features to turn off various components. 97 | * In general, Rocket has much better docs than iron. 98 | 99 | I would really love to use Rocket, but this service isn't just meant to be compiled once by some server inside the cloud (an environment very much under my control). 100 | It is meant to be installed by a wide audience, on local machines, etc. Therefore, I don't want to require nightly, and I can't use Rocket as a consequence. 101 | 102 | The [iron](https://github.com/iron/iron) web framework is mature and well established, compared to e.g. [gotham](https://gotham.rs/). That is why I chose it! 103 | 104 | ## Logo credit 105 | 106 | The logo, under `site/static/package-logo.svg` has been adapted from 107 | [a MIT licensed GitHub artwork](https://www.iconfinder.com/icons/298837/package_icon#size=128). 108 | 109 | ## License 110 | 111 | Licensed under either of 112 | 113 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 114 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 115 | 116 | at your option. 117 | 118 | ### Contributions 119 | 120 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 121 | -------------------------------------------------------------------------------- /USAGE.md: -------------------------------------------------------------------------------- 1 | # Cargo local serve usage notes 2 | 3 | ## config.toml 4 | 5 | cargo local serve itself is configurable. 6 | It per default looks for a `config.toml` 7 | file in its `PATH`. 8 | You can copy `config.toml.example` 9 | and modify it according to your needs. 10 | 11 | ## Managing crate storage 12 | 13 | You need a local copy of all crates.io crates 14 | in order to use cargo-local-serve. 15 | It ships with facilities to obtain such a copy 16 | from crates.io itself. 17 | 18 | ### Downloading the crates (ArchiveTree) 19 | 20 | In order to download all crates that 21 | are stored in the local registry, 22 | just run the command: 23 | ``` 24 | cargo run --release -p all-crate-storage --bin download-all-crates 25 | ``` 26 | It will download all crates to the `crate-archives/` 27 | directory. 28 | 29 | This storage method is referred to as 30 | `ArchiveTree` in config.toml. 31 | 32 | ### Compressing all crates (StorageFile) 33 | 34 | You can create a compressed file 35 | from already locally present .crate files 36 | using this command: 37 | ``` 38 | cargo run --release -p all-crate-storage --bin create-crate-storage 39 | ``` 40 | 41 | This storage method is referred to as 42 | `StorageFile` in config.toml. 43 | 44 | ### Updating 45 | 46 | The downloader to `ArchiveTree` storage 47 | is smart and only downloads things 48 | that are not present on disk. 49 | 50 | Right now, the `StorageFile` compressor 51 | is not really smart. It doesn't update 52 | already present files. 53 | However, it should be easy to add such 54 | a mode if desired. Please contact the 55 | author or try to make a patch yourself. 56 | 57 | ## Making cargo point at it 58 | 59 | One of the use cases that cargo local serve 60 | was built for is the scenario where you lack 61 | internet access yet wish to develop Rust 62 | applications. 63 | 64 | cargo local serve offers a crates.io like API 65 | that cargo understands. 66 | The following steps let you make cargo point at 67 | cargo local serve: 68 | 69 | First, you'll need a clone of the crates.io index. 70 | You can obtain one by doing: 71 | 72 | ``` 73 | git clone https://github.com/rust-lang/crates.io-index 74 | ``` 75 | 76 | Then edit the `config.json` file it contains to read: 77 | 78 | ```json 79 | { 80 | "dl": "http://localhost:3000/api/v1/crates", 81 | "api": "http://localhost:3000/" 82 | } 83 | ``` 84 | 85 | Or to whatever your host/port combination 86 | cargo local serve is listening on. 87 | 88 | Now you only have to tell cargo to use that index. 89 | This can be done by using the replacement mechanism, 90 | setable in `.cargo/config`. 91 | 92 | ```toml 93 | [source.cargo-local-serve] 94 | registry = "file:///path/to/src/crates.io-index/clone" 95 | 96 | [source.crates-io] 97 | replace-with = "cargo-local-serve" 98 | ``` 99 | -------------------------------------------------------------------------------- /all-crate-grep/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "all-crate-grep" 3 | version = "0.1.0" 4 | license = "MIT/Apache-2.0" 5 | authors = ["est31 "] 6 | edition = "2015" 7 | 8 | [[bin]] 9 | name = "all-crate-grep" 10 | path = "main.rs" 11 | 12 | [dependencies] 13 | 14 | all-crate-storage = { path = "../all-crate-storage" } 15 | grep = "0.2" 16 | -------------------------------------------------------------------------------- /all-crate-grep/main.rs: -------------------------------------------------------------------------------- 1 | extern crate all_crate_storage; 2 | extern crate grep; 3 | 4 | use std::env; 5 | use std::path::Path; 6 | use all_crate_storage::registry::registry; 7 | use all_crate_storage::crate_storage::{CrateSource, FileTreeStorage}; 8 | use self::registry::{Registry, AllCratesJson}; 9 | 10 | use std::thread; 11 | use std::sync::mpsc::{sync_channel, SyncSender}; 12 | 13 | use grep::regex::RegexMatcher; 14 | use grep::matcher::Matcher; 15 | 16 | fn run(tx :SyncSender<(usize, usize, String)>, acj :&AllCratesJson, 17 | total_file_count :usize, t :usize, tc :usize, 18 | grepper :&RegexMatcher, storage_base :&Path) { 19 | let mut ctr = 0; 20 | 21 | macro_rules! pln { 22 | ($($v:expr),*) => { 23 | tx.send((ctr, total_file_count, format!($($v),*))).unwrap(); 24 | } 25 | } 26 | 27 | let mut crate_source = FileTreeStorage::new(storage_base); 28 | 29 | for &(ref name, ref versions) in acj.iter() { 30 | 31 | for ref v in versions.iter() { 32 | ctr += 1; 33 | /*if ctr != 21899 { 34 | continue; 35 | }*/ 36 | if ctr % tc != t { 37 | continue; 38 | } 39 | 40 | let fh = match crate_source.get_crate_handle_nv(name.to_owned(), v.version.clone()) { 41 | Some(f) => f, 42 | None => { 43 | pln!("Version {} of crate {} not mirrored", v.version, name); 44 | continue 45 | }, 46 | }; 47 | 48 | let mut match_found = false; 49 | fh.crate_file_handle.map_all_files(|file_path, file| { 50 | if let (Some(file_path), Some(file)) = (file_path, file) { 51 | if let Ok(Some(_)) = grepper.find(&file) { 52 | pln!("Match found in {} v {} file {}", name, v.version, file_path); 53 | match_found = true; 54 | } 55 | } 56 | }); 57 | if !match_found { 58 | pln!("No match in {} v {}", name, v.version); 59 | } 60 | } 61 | } 62 | println!("thread {} done", t); 63 | } 64 | 65 | fn main() { 66 | println!("Loading all crates json..."); 67 | let registry = Registry::from_name("github.com-1ecc6299db9ec823").unwrap(); 68 | let acj :AllCratesJson = registry.get_all_crates_json().unwrap(); 69 | let total_file_count :usize = acj.iter().map(|&(_, ref v)| v.len()).sum(); 70 | 71 | println!("The target is {} files.", total_file_count); 72 | let storage_base = env::current_dir().unwrap().join("crate-archives"); 73 | println!("Using directory {} to load the files from.", 74 | storage_base.to_str().unwrap()); 75 | 76 | let needle = env::args().nth(1).expect("expected search term"); 77 | println!("Search term '{}'", needle); 78 | let grepper = RegexMatcher::new_line_matcher(&needle).unwrap(); 79 | 80 | let (tx, rx) = sync_channel(10); 81 | 82 | let thread_count = 8; 83 | for v in 0..thread_count { 84 | let tx = tx.clone(); 85 | let acj = acj.clone(); 86 | let grepper = grepper.clone(); 87 | let storage_base = storage_base.clone(); 88 | thread::spawn(move || { 89 | run(tx, &acj, total_file_count, v, thread_count, 90 | &grepper, &storage_base); 91 | }); 92 | } 93 | std::mem::drop(tx); 94 | while let Ok((ctr, tc, s)) = rx.recv() { 95 | println!("[{}/{}] {}", ctr, tc, s); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /all-crate-storage/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "all-crate-storage" 3 | version = "0.1.0" 4 | license = "MIT/Apache-2.0" 5 | authors = ["est31 "] 6 | edition = "2015" 7 | 8 | [lib] 9 | path = "lib.rs" 10 | 11 | [[bin]] 12 | name = "analyze-all-crates" 13 | path = "bin/analyze-all-crates.rs" 14 | 15 | [[bin]] 16 | name = "diff-all-crates" 17 | path = "bin/diff-all-crates.rs" 18 | 19 | [[bin]] 20 | name = "download-all-crates" 21 | path = "bin/download-all-crates.rs" 22 | 23 | [[bin]] 24 | name = "create-crate-storage" 25 | path = "bin/create-crate-storage.rs" 26 | 27 | [[bin]] 28 | name = "create-mb-crate-storage" 29 | path = "bin/create-mb-crate-storage.rs" 30 | 31 | [[bin]] 32 | name = "diff" 33 | path = "bin/diff.rs" 34 | 35 | [dependencies] 36 | 37 | try = "1.0.0" 38 | 39 | # Needed by the binaries 40 | pbr = "1.0.0" 41 | reqwest = "0.9" 42 | 43 | # all the other stuff 44 | string-interner = "0.7" 45 | serde = "1.0.0" 46 | serde_json = "1.0.0" 47 | serde_derive = "1.0.0" 48 | flate2 = "1.0" 49 | tar = "0.4" 50 | semver = { version = "0.11", features = ["serde"] } 51 | git2 = "0.13" 52 | failure = "0.1.0" 53 | failure_derive = "0.1.0" 54 | ring = "0.16" 55 | byteorder = "1.0.0" 56 | multiqueue = "0.3" 57 | hex = "0.4.0" 58 | difference = "2.0" 59 | petgraph = "0.5" 60 | -------------------------------------------------------------------------------- /all-crate-storage/bin/analyze-all-crates.rs: -------------------------------------------------------------------------------- 1 | extern crate all_crate_storage; 2 | extern crate flate2; 3 | extern crate tar; 4 | extern crate pbr; 5 | 6 | use std::fs::File; 7 | use std::io; 8 | use std::env; 9 | use std::path::Path; 10 | use all_crate_storage::registry::registry; 11 | use all_crate_storage::hash_ctx::HashCtx; 12 | use self::registry::{Registry, AllCratesJson}; 13 | use flate2::{Compression, GzBuilder}; 14 | use flate2::read::GzDecoder; 15 | use tar::Archive; 16 | 17 | use std::thread; 18 | use std::sync::mpsc::{sync_channel, SyncSender}; 19 | use std::collections::HashMap; 20 | 21 | use pbr::MultiBar; 22 | 23 | // corrupt deflate stream error blacklist 24 | // TODO: does having it make any sense? 25 | // https://github.com/rust-lang/cargo/issues/1465 26 | const BLACKLIST :&[&str] = &[ 27 | /* 28 | "cobs", // v0.1.0 29 | "curl-sys", // v0.1.0 30 | "expat-sys", // v2.1.0 31 | "flate2", // v0.2.2 32 | "libbreakpad-client-sys", // v0.1.0 33 | "ppapi", // v0.0.1 34 | "ruplicity", // v0.1.0 35 | "rustc-serialize", // v0.3.8 36 | */ 37 | ]; 38 | 39 | #[derive(Clone)] 40 | struct Message { 41 | t :usize, 42 | ctr :usize, 43 | total_file_count :usize, 44 | msg :Msg, 45 | } 46 | #[derive(Clone)] 47 | enum Msg { 48 | Text(String), 49 | File(String, String, u64, u64), 50 | Done, 51 | } 52 | 53 | fn run(tx :SyncSender, acj :&AllCratesJson, 54 | total_file_count :usize, t :usize, tc :usize, 55 | storage_base :&Path) { 56 | let mut ctr = 0; 57 | 58 | macro_rules! msg { 59 | ($msg:expr) => { 60 | tx.send(Message { 61 | t, ctr, total_file_count, 62 | msg : $msg, 63 | }).unwrap(); 64 | } 65 | } 66 | macro_rules! pln { 67 | ($($v:expr),*) => { 68 | msg!(Msg::Text(format!($($v),*))); 69 | } 70 | } 71 | 72 | for &(ref name, ref versions) in acj.iter() { 73 | let name_path = storage_base.join(registry::obtain_crate_name_path(name)); 74 | //fs::create_dir_all(&name_c_path).unwrap(); 75 | 76 | if BLACKLIST.contains(&&name[..]) { 77 | ctr += versions.len(); 78 | continue; 79 | } 80 | 81 | for v in versions.iter() { 82 | ctr += 1; 83 | /*if ctr != 21899 { 84 | continue; 85 | }*/ 86 | if ctr % tc != t { 87 | continue; 88 | } 89 | let crate_file_path = name_path 90 | .join(format!("{}-{}.crate", name, v.version)); 91 | match File::open(&crate_file_path) { 92 | Ok(mut f) => { 93 | // verify the checksum 94 | let mut ring_ctx = HashCtx::new(); 95 | io::copy(&mut f, &mut ring_ctx).unwrap(); 96 | let hash_str = ring_ctx.finish_and_get_digest_hex(); 97 | if hash_str == v.checksum { 98 | // everything is fine! 99 | } else { 100 | pln!("Checksum mismatch for {} v{}. \ 101 | expected: '{}' was: '{}'", 102 | name, v.version, v.checksum, hash_str); 103 | // Ignore 104 | continue; 105 | } 106 | }, 107 | Err(_) => { 108 | pln!("File not found for {} v{}", name, v.version); 109 | // Ignore 110 | continue; 111 | }, 112 | } 113 | pln!("Diffing {} v{}", name, v.version); 114 | 115 | // Do the diffing. 116 | let f = File::open(&crate_file_path).unwrap(); 117 | let gz_dec = GzDecoder::new(f); 118 | //pln!("{:?}", gz_dec.header()); 119 | let mut archive = Archive::new(gz_dec); 120 | //gz_dec. 121 | 122 | for entry in archive.entries().expect("no") { 123 | let mut entry = match entry { 124 | Ok(e) => e, 125 | Err(e) => { 126 | pln!("ERROR FOR {} v{}: {:?}", name, v.version, e); 127 | break; 128 | }, 129 | }; 130 | let mut buffer = Vec::::new(); 131 | match io::copy(&mut entry, &mut buffer) { 132 | Ok(_) => (), 133 | Err(e) => pln!("ERROR FOR {} v{}: {:?}", name, v.version, e), 134 | } 135 | let mut ring_ctx = HashCtx::new(); 136 | let mut sl :&[u8] = &buffer; 137 | io::copy(&mut sl, &mut ring_ctx).unwrap(); 138 | let hash_str = ring_ctx.finish_and_get_digest_hex(); 139 | let sl :&[u8] = &buffer; 140 | let mut gz_enc = GzBuilder::new().read(sl, Compression::best()); 141 | let mut buffer_compressed = Vec::::new(); 142 | io::copy(&mut gz_enc, &mut buffer_compressed).unwrap(); 143 | let compressed_size = buffer_compressed.len() as u64; 144 | let path_str = entry.path().unwrap().to_str().unwrap().to_string(); 145 | let size = entry.header().entry_size().unwrap(); 146 | msg!(Msg::File(hash_str, path_str, size, compressed_size)); 147 | } 148 | } 149 | /*if ctr > 10_000 { 150 | pln!("abort"); 151 | break; 152 | }*/ 153 | } 154 | msg!(Msg::Done); 155 | } 156 | 157 | fn main() { 158 | println!("Loading all crates json..."); 159 | let registry = Registry::from_name("github.com-1ecc6299db9ec823").unwrap(); 160 | let acj :AllCratesJson = registry.get_all_crates_json().unwrap(); 161 | let total_file_count :usize = acj.iter().map(|&(_, ref v)| v.len()).sum(); 162 | 163 | println!("The target is {} files.", total_file_count); 164 | let storage_base = env::current_dir().unwrap().join("crate-archives"); 165 | println!("Using directory {} to load the files from.", 166 | storage_base.to_str().unwrap()); 167 | 168 | let (tx, rx) = sync_channel(10); 169 | 170 | let thread_count = 8; 171 | for v in 0..thread_count { 172 | let tx = tx.clone(); 173 | let acj = acj.clone(); 174 | let storage_base = storage_base.clone(); 175 | thread::spawn(move || { 176 | run(tx, &acj, total_file_count, v, thread_count, 177 | &storage_base); 178 | }); 179 | } 180 | std::mem::drop(tx); 181 | let mut h_map = HashMap::new(); 182 | let mut file_count = 0; 183 | let mut threads_running = thread_count; 184 | 185 | let mb = MultiBar::new(); 186 | mb.println("Analyzing all crates"); 187 | let mut p_list = (0..thread_count) 188 | .map(|_| mb.create_bar((total_file_count/thread_count) as _)) 189 | .collect::>(); 190 | 191 | thread::spawn(move || { 192 | mb.listen(); 193 | println!("all bars done!"); 194 | }); 195 | 196 | while let Ok(msg) = rx.recv() { 197 | match msg.msg { 198 | Msg::Text(_s) => { 199 | //println!("[{}/{}] {}", msg.ctr, msg.total_file_count, s), 200 | p_list[msg.t].inc(); 201 | } 202 | Msg::File(h, path, size, size_c) => { 203 | file_count += 1; 204 | let l = h_map.entry(h).or_insert((Vec::new(), size, size_c)); 205 | l.0.push(path); 206 | }, 207 | Msg::Done => { 208 | //println!("Thread {} done", msg.t); 209 | p_list[msg.t].finish(); 210 | threads_running -= 1; 211 | if threads_running == 0 { 212 | break; 213 | } 214 | }, 215 | } 216 | } 217 | let mut hashes = h_map.into_iter().collect::>(); 218 | hashes.sort_by_key(|&(_, ref l)| l.0.len() as u64 * l.1); 219 | hashes.reverse(); 220 | 221 | println!("File count: {}", file_count); 222 | println!("Number of unique file hashes: {}", hashes.len()); 223 | println!("Total size uncompressed: {}", hashes.iter() 224 | .map(|&(_, ref l)| l.0.len() as u64 * l.1).sum::()); 225 | println!("Uncompressed size of unique files: {}", hashes.iter() 226 | .map(|&(_, ref l)| l.1).sum::()); 227 | println!("Compressed size of unique files: {}", hashes.iter() 228 | .map(|&(_, ref l)| l.2).sum::()); 229 | println!("top used hashes: {:?}", 230 | hashes[0..40].iter().map(|&(_, ref l)| (l.0[0].clone(), l.0.len(), 231 | l.1, l.0.len() as u64 * l.1)).collect::>()); 232 | } 233 | -------------------------------------------------------------------------------- /all-crate-storage/bin/create-crate-storage.rs: -------------------------------------------------------------------------------- 1 | extern crate all_crate_storage; 2 | 3 | use std::fs::{self, OpenOptions}; 4 | use std::env; 5 | use all_crate_storage::registry::registry; 6 | use all_crate_storage::blob_crate_storage::BlobCrateStorage; 7 | use all_crate_storage::crate_storage::{FileTreeStorage, CrateStorage}; 8 | use self::registry::{Registry, AllCratesJson}; 9 | 10 | fn main() { 11 | println!("Loading all crates json..."); 12 | let registry = Registry::from_name("github.com-1ecc6299db9ec823").unwrap(); 13 | let acj :AllCratesJson = registry.get_all_crates_json().unwrap(); 14 | let total_file_count :usize = acj.iter().map(|&(_, ref v)| v.len()).sum(); 15 | 16 | println!("The target is {} files.", total_file_count); 17 | let storage_base = env::current_dir().unwrap().join("crate-archives"); 18 | let storage_con_base = env::current_dir().unwrap().join("crate-constr-archives"); 19 | println!("Using directory {} to load the files from.", 20 | storage_base.to_str().unwrap()); 21 | 22 | fs::create_dir_all(&storage_con_base).unwrap(); 23 | 24 | let thread_count = 8; 25 | 26 | let mut fts = FileTreeStorage::new(&storage_base); 27 | let f = OpenOptions::new() 28 | .read(true) 29 | .write(true) 30 | .create(true) 31 | .open(storage_con_base.join("crate_storage")).unwrap(); 32 | let mut cst = BlobCrateStorage::new(f).unwrap(); 33 | cst.fill_crate_storage_from_source(thread_count, &acj, &mut fts, 34 | |n, v| println!("Storing {} v {}", n, v.version)); 35 | 36 | cst.store().unwrap(); 37 | } 38 | -------------------------------------------------------------------------------- /all-crate-storage/bin/create-mb-crate-storage.rs: -------------------------------------------------------------------------------- 1 | extern crate all_crate_storage; 2 | extern crate semver; 3 | 4 | use std::fs::{self, OpenOptions}; 5 | use std::env; 6 | use all_crate_storage::registry::registry; 7 | use all_crate_storage::blob_crate_storage::BlobCrateStorage; 8 | use self::registry::{Registry, AllCratesJson}; 9 | use all_crate_storage::multi_blob_crate_storage::GraphOfBlobs; 10 | 11 | fn main() { 12 | println!("Loading all crates json..."); 13 | let registry = Registry::from_name("github.com-1ecc6299db9ec823").unwrap(); 14 | let acj :AllCratesJson = registry.get_all_crates_json().unwrap(); 15 | let total_file_count :usize = acj.iter().map(|&(_, ref v)| v.len()).sum(); 16 | 17 | println!("The target is {} files.", total_file_count); 18 | let storage_con_base = env::current_dir().unwrap().join("crate-constr-archives"); 19 | 20 | fs::create_dir_all(&storage_con_base).unwrap(); 21 | 22 | let src_f = OpenOptions::new() 23 | .read(true) 24 | .open(storage_con_base.join("crate_storage")).unwrap(); 25 | 26 | let dst_f = OpenOptions::new() 27 | .read(true) 28 | .write(true) 29 | .create(true) 30 | .open(storage_con_base.join("crate_storage_mb")).unwrap(); 31 | let mut src = BlobCrateStorage::new(src_f).unwrap(); 32 | let mut dst = BlobCrateStorage::new(dst_f).unwrap(); 33 | 34 | println!("Obtaining graph..."); 35 | let graph = GraphOfBlobs::from_blob_crate_storage(&acj, &mut src); 36 | println!("root number {}", graph.roots.len()); 37 | dst.store_parallel_mb(&mut src, &graph, 8); 38 | } 39 | -------------------------------------------------------------------------------- /all-crate-storage/bin/diff-all-crates.rs: -------------------------------------------------------------------------------- 1 | extern crate all_crate_storage; 2 | 3 | use std::io; 4 | use std::env; 5 | use std::path::Path; 6 | use all_crate_storage::registry::registry; 7 | use all_crate_storage::reconstruction::{CrateContentBlobs}; 8 | use all_crate_storage::hash_ctx::{HashCtx, get_digest_hex}; 9 | use all_crate_storage::crate_storage::{CrateSource, FileTreeStorage}; 10 | use self::registry::{Registry, AllCratesJson}; 11 | 12 | use std::thread; 13 | use std::sync::mpsc::{sync_channel, SyncSender}; 14 | 15 | // corrupt deflate stream error blacklist 16 | // TODO: does having it make any sense? 17 | // https://github.com/rust-lang/cargo/issues/1465 18 | const BLACKLIST :&[&str] = &[ 19 | /* 20 | "cobs", // v0.1.0 21 | "curl-sys", // v0.1.0 22 | "expat-sys", // v2.1.0 23 | "flate2", // v0.2.2 24 | "libbreakpad-client-sys", // v0.1.0 25 | "ppapi", // v0.0.1 26 | "ruplicity", // v0.1.0 27 | "rustc-serialize", // v0.3.8 28 | */ 29 | ]; 30 | 31 | /* 32 | 33 | [21898/71082] DIFF FAIL for forust v0.1.0! 34 | Diffoscope output: 35 | -00000780: 7080 03fc 42f8 0fbd 883a 3300 2400 00 p...B....:3.$.. 36 | +00000780: 7080 03fc 42f8 0fbd 883a 3300 2400 000a p...B....:3.$... 37 | 38 | [29482/71082] DIFF FAIL for helianto v0.1.0-beta1! 39 | │ -gzip compressed data, was "helianto-0.1.0-beta1.crate", max compression, from Unix 40 | │ +gzip compressed data, was "helianto-0.1.0-beta1.crate", last modified: Wed Jan 13 23:45:28 2016, max compression, from Unix 41 | */ 42 | fn run(tx :SyncSender<(usize, usize, String)>, acj :&AllCratesJson, 43 | total_file_count :usize, t :usize, tc :usize, 44 | storage_base :&Path) { 45 | let mut ctr = 0; 46 | 47 | macro_rules! pln { 48 | ($($v:expr),*) => { 49 | tx.send((ctr, total_file_count, format!($($v),*))).unwrap(); 50 | } 51 | } 52 | 53 | let mut crate_source = FileTreeStorage::new(storage_base); 54 | 55 | for &(ref name, ref versions) in acj.iter() { 56 | 57 | if BLACKLIST.contains(&&name[..]) { 58 | ctr += versions.len(); 59 | continue; 60 | } 61 | 62 | for ref v in versions.iter() { 63 | ctr += 1; 64 | /*if ctr != 21899 { 65 | continue; 66 | }*/ 67 | if ctr % tc != t { 68 | continue; 69 | } 70 | let crate_blob = crate_source.get_crate_nv(name.clone(), v.version.clone()); 71 | let crate_blob = if let Some(crate_blob) = crate_blob { 72 | // verify the checksum 73 | let mut ring_ctx = HashCtx::new(); 74 | io::copy(&mut crate_blob.as_slice(), &mut ring_ctx).unwrap(); 75 | let hash_str = ring_ctx.finish_and_get_digest_hex(); 76 | if hash_str == v.checksum { 77 | // everything is fine! 78 | crate_blob 79 | } else { 80 | pln!("Checksum mismatch for {} v{}. \ 81 | Ignoring. expected: '{}' was: '{}'", 82 | name, v.version, v.checksum, hash_str); 83 | // Ignore 84 | continue; 85 | } 86 | } else { 87 | pln!("Crate not present for {} v{}", name, v.version); 88 | // Ignore 89 | continue; 90 | }; 91 | pln!("Diffing {} v{}", name, v.version); 92 | 93 | // Do the diffing. 94 | 95 | // Create the blobs 96 | let archive_blobs = match CrateContentBlobs::from_archive_file(crate_blob.as_slice()) { 97 | Ok(b) => b, 98 | Err(e) => { 99 | pln!("ERROR FOR {} v{}: {:?}", name, v.version, e); 100 | continue; 101 | }, 102 | }; 103 | 104 | // Reconstruct the file and compute the digest 105 | let digest_reconstructed = archive_blobs.digest_of_reconstructed(); 106 | 107 | // Compare the digest 108 | let hash_str = get_digest_hex(digest_reconstructed); 109 | if hash_str != v.checksum { 110 | pln!("DIFF FAIL for {} v{}!", name, v.version); 111 | } 112 | } 113 | /*if ctr > 100 { 114 | pln!("abort"); 115 | break; 116 | }*/ 117 | } 118 | println!("thread {} done", t); 119 | } 120 | 121 | fn main() { 122 | println!("Loading all crates json..."); 123 | let registry = Registry::from_name("github.com-1ecc6299db9ec823").unwrap(); 124 | let acj :AllCratesJson = registry.get_all_crates_json().unwrap(); 125 | let total_file_count :usize = acj.iter().map(|&(_, ref v)| v.len()).sum(); 126 | 127 | println!("The target is {} files.", total_file_count); 128 | let storage_base = env::current_dir().unwrap().join("crate-archives"); 129 | println!("Using directory {} to load the files from.", 130 | storage_base.to_str().unwrap()); 131 | 132 | let (tx, rx) = sync_channel(10); 133 | 134 | let thread_count = 8; 135 | for v in 0..thread_count { 136 | let tx = tx.clone(); 137 | let acj = acj.clone(); 138 | let storage_base = storage_base.clone(); 139 | thread::spawn(move || { 140 | run(tx, &acj, total_file_count, v, thread_count, 141 | &storage_base); 142 | }); 143 | } 144 | std::mem::drop(tx); 145 | while let Ok((ctr, tc, s)) = rx.recv() { 146 | println!("[{}/{}] {}", ctr, tc, s); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /all-crate-storage/bin/diff.rs: -------------------------------------------------------------------------------- 1 | extern crate all_crate_storage; 2 | extern crate semver; 3 | 4 | use semver::Version; 5 | 6 | use std::fs::{self, OpenOptions}; 7 | use std::env; 8 | use std::str; 9 | use all_crate_storage::registry::registry; 10 | use all_crate_storage::blob_crate_storage::BlobCrateStorage; 11 | use all_crate_storage::crate_storage::{CrateSource}; 12 | use all_crate_storage::diff::Diff; 13 | use self::registry::{Registry, AllCratesJson}; 14 | 15 | fn main() { 16 | println!("Loading all crates json..."); 17 | let registry = Registry::from_name("github.com-1ecc6299db9ec823").unwrap(); 18 | let acj :AllCratesJson = registry.get_all_crates_json().unwrap(); 19 | let total_file_count :usize = acj.iter().map(|&(_, ref v)| v.len()).sum(); 20 | 21 | println!("The target is {} files.", total_file_count); 22 | let storage_base = env::current_dir().unwrap().join("crate-archives"); 23 | let storage_con_base = env::current_dir().unwrap().join("crate-constr-archives"); 24 | println!("Using directory {} to load the files from.", 25 | storage_base.to_str().unwrap()); 26 | 27 | fs::create_dir_all(&storage_con_base).unwrap(); 28 | 29 | let f = OpenOptions::new() 30 | .read(true) 31 | .open(storage_con_base.join("crate_storage")).unwrap(); 32 | let mut cst = BlobCrateStorage::new(f).unwrap(); 33 | 34 | let lib_062 = { 35 | let mut ch = cst.get_crate_handle_nv("lewton".to_owned(), 36 | Version::parse("0.6.2").unwrap()).unwrap(); 37 | ch.get_file("lewton-0.6.2/src/imdct.rs").unwrap() 38 | }; 39 | let lib_062_str = str::from_utf8(&lib_062).unwrap(); 40 | let lib_070 = { 41 | let mut ch = cst.get_crate_handle_nv("lewton".to_owned(), 42 | Version::parse("0.7.0").unwrap()).unwrap(); 43 | ch.get_file("lewton-0.7.0/src/imdct.rs").unwrap() 44 | }; 45 | let lib_070_str = str::from_utf8(&lib_070).unwrap(); 46 | let diff = Diff::from_texts(lib_062_str, 47 | lib_070_str, "\n"); 48 | 49 | let mut v = Vec::new(); 50 | diff.serialize(&mut v).unwrap(); 51 | println!("{:?}", diff); 52 | println!("{} {} {}", lib_062.len(), lib_070.len(), v.len()); 53 | assert_eq!(diff.reconstruct_new(lib_062_str), lib_070_str); 54 | /*for i in diff.inserts() { 55 | println!("{:?}", i); 56 | } 57 | for d in diff.deletes() { 58 | } 59 | println!("{}", lib_062); 60 | println!("{}", lib_070);*/ 61 | } 62 | -------------------------------------------------------------------------------- /all-crate-storage/bin/download-all-crates.rs: -------------------------------------------------------------------------------- 1 | extern crate all_crate_storage; 2 | extern crate reqwest; 3 | 4 | use std::fs::{self, File}; 5 | use std::io; 6 | use std::env; 7 | use reqwest::Client; 8 | use all_crate_storage::registry::registry; 9 | use self::registry::{Registry, AllCratesJson}; 10 | use all_crate_storage::hash_ctx::HashCtx; 11 | 12 | /// This is the URL pattern that we are using to download the .crate 13 | /// files from hosting. 14 | /// 15 | /// At the moment, DNS records for the domain state that 16 | /// it lives in amazon's "global" region. 17 | /// 18 | /// If the URL shouldn't work (any more) for some reason, the more 19 | /// stable URL pattern is this one: 20 | /// 21 | /// ``` 22 | /// https://crates.io/api/v1/crates/{cratename}/{version}/download 23 | /// ``` 24 | /// This URL occurs in the API response by crates.io when you ask 25 | /// the API about a crate via the usual request: 26 | /// https://crates.io/api/v1/crates/{cratename} 27 | /// 28 | /// Also, it is the URL scheme that cargo itself uses to download 29 | /// a crate. 30 | /// 31 | /// But we don't want to fake download statistics, so we directly 32 | /// take the cloudfront URL. 33 | /// The stable URL is simply just a redirect to the cloudfront URL. 34 | macro_rules! download_url_pattern { 35 | () => { 36 | "https://d19xqa3lc3clo8.cloudfront.net/crates/{cratename}/{cratename}-{version}.crate" 37 | }; 38 | } 39 | 40 | // TODO 41 | // * add modes: 42 | // * Download only mode, where we don't delete any corrupt crate files 43 | // * Verification only mode 44 | // * Add a way to change: 45 | // * Registry name/path 46 | // * URL pattern 47 | // * Directory where we download to 48 | // * Experiment with ways to download stuff faster 49 | 50 | fn main() { 51 | println!("Loading all crates json..."); 52 | let registry = Registry::from_name("github.com-1ecc6299db9ec823").unwrap(); 53 | let acj :AllCratesJson = registry.get_all_crates_json().unwrap(); 54 | let total_file_count :usize = acj.iter().map(|&(_, ref v)| v.len()).sum(); 55 | 56 | println!("The target is {} files.", total_file_count); 57 | let storage_base = env::current_dir().unwrap().join("crate-archives"); 58 | println!("Using directory {} to store the files.", 59 | storage_base.to_str().unwrap()); 60 | 61 | let cl = Client::builder().gzip(false).build().unwrap(); 62 | 63 | let mut ctr = 0; 64 | 65 | for &(ref name, ref versions) in acj.iter() { 66 | let name_path = storage_base.join(registry::obtain_crate_name_path(name)); 67 | 68 | fs::create_dir_all(&name_path).unwrap(); 69 | 70 | for ref v in versions.iter() { 71 | ctr += 1; 72 | let crate_file_path = name_path 73 | .join(format!("{}-{}.crate", name, v.version)); 74 | match File::open(&crate_file_path) { 75 | Ok(mut f) => { 76 | // verify the checksum 77 | let mut hash_ctx = HashCtx::new(); 78 | io::copy(&mut f, &mut hash_ctx).unwrap(); 79 | let hash_str = hash_ctx.finish_and_get_digest_hex(); 80 | if hash_str == v.checksum { 81 | println!("[{}/{}] Checksum verified for {} v{}", 82 | ctr, total_file_count, name, v.version); 83 | continue; 84 | } else { 85 | println!("[{}/{}] Checksum mismatch for {} v{}. \ 86 | Deleting. expected: '{}' was: '{}'", 87 | ctr, total_file_count, name, v.version, 88 | v.checksum, hash_str); 89 | fs::remove_file(&crate_file_path).unwrap(); 90 | } 91 | }, 92 | Err(e) => { 93 | // TODO check e and if it is anything else than 94 | // "file not found", make a sad face :) 95 | }, 96 | } 97 | println!("[{}/{}] Downloading {} v{}", 98 | ctr, total_file_count, name, v.version); 99 | let url = format!(download_url_pattern!(), 100 | cratename = name, 101 | version = v.version); 102 | let mut resp = cl.get(&url).send().unwrap(); 103 | if resp.status().is_success() { 104 | let mut f = File::create(crate_file_path).unwrap(); 105 | io::copy(&mut resp, &mut f).unwrap(); 106 | } else { 107 | println!("Got error from server: {}", resp.status()); 108 | } 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /all-crate-storage/blob_crate_storage.rs: -------------------------------------------------------------------------------- 1 | use super::blob_storage::BlobStorage; 2 | use super::hash_ctx::{HashCtx, Digest}; 3 | use super::reconstruction::{CrateContentBlobs, CrateRecMetadata, 4 | CrateRecMetaWithBlobs, hdr_from_ptr}; 5 | use super::crate_storage::{CrateStorage, CrateSpec, CrateSource, 6 | CrateHandle, CrateFileHandle}; 7 | use super::multi_blob::MultiBlob; 8 | use super::diff::Diff; 9 | use super::multi_blob_crate_storage::GraphOfBlobs; 10 | 11 | use semver::Version; 12 | use flate2::{Compression, GzBuilder}; 13 | use flate2::read::GzDecoder; 14 | use std::io::{self, Read, Seek, Write, Result as IoResult}; 15 | use std::collections::HashSet; 16 | 17 | pub struct BlobCrateStorage { 18 | pub(crate) b :BlobStorage, 19 | } 20 | 21 | macro_rules! optry { 22 | ($e:expr) => { 23 | match $e { 24 | Some(d) => d, 25 | None => return None, 26 | } 27 | }; 28 | } 29 | 30 | macro_rules! decompress { 31 | ($e:expr) => {{ 32 | let mut gz_dec = GzDecoder::new($e.as_slice()); 33 | let mut r = Vec::new(); 34 | io::copy(&mut gz_dec, &mut r).unwrap(); 35 | r 36 | }} 37 | } 38 | 39 | impl BlobCrateStorage { 40 | pub fn empty(storage :S) -> Self { 41 | BlobCrateStorage { 42 | b : BlobStorage::empty(storage), 43 | } 44 | } 45 | pub fn new(storage :S) -> IoResult { 46 | Ok(BlobCrateStorage { 47 | b : try!(BlobStorage::new(storage)), 48 | }) 49 | } 50 | pub fn load(storage :S) -> IoResult { 51 | Ok(BlobCrateStorage { 52 | b : try!(BlobStorage::load(storage)), 53 | }) 54 | } 55 | pub(crate) fn get_crate_rec_meta(&mut self, s :&CrateSpec) -> Option { 56 | let meta_d = optry!(self.b.name_index.get(&s.file_name())).clone(); 57 | 58 | let cmeta = optry!(optry!(self.b.get(&meta_d).ok())); 59 | let dmeta = decompress!(cmeta); 60 | let meta = optry!(CrateRecMetadata::deserialize(dmeta.as_slice()).ok()); 61 | Some(meta) 62 | } 63 | } 64 | 65 | impl BlobCrateStorage { 66 | pub fn store(&mut self) -> io::Result<()> { 67 | try!(self.b.write_header_and_index()); 68 | Ok(()) 69 | } 70 | } 71 | 72 | fn get_digest_lists(blob_graph :&GraphOfBlobs) -> Vec> { 73 | let mut res = Vec::with_capacity(blob_graph.roots.len()); 74 | let graph = &blob_graph.graph; 75 | let mut visited = HashSet::new(); 76 | for root in blob_graph.roots.iter() { 77 | let mut mblob_digests = Vec::new(); 78 | let mut to_walk = Vec::new(); 79 | to_walk.push(*root); 80 | // TODO perform in-order traversal 81 | // TODO also actually return a tree not a traversal. 82 | // traversals perform pretty crappily if we have a tree present :). 83 | while let Some(n) = to_walk.pop() { 84 | if !visited.insert(n) { 85 | continue; 86 | } 87 | let digest = graph.node_weight(n).unwrap(); 88 | mblob_digests.push(*digest); 89 | let n = graph.neighbors(n); 90 | for neigh in n { 91 | to_walk.push(neigh); 92 | } 93 | } 94 | res.push(mblob_digests); 95 | } 96 | res 97 | } 98 | 99 | impl BlobCrateStorage { 100 | pub fn store_parallel_mb( 101 | &mut self, src :&mut BlobCrateStorage, 102 | blob_graph :&GraphOfBlobs, thread_count :u16) { 103 | use std::sync::mpsc::{sync_channel, TrySendError}; 104 | use multiqueue::mpmc_queue; 105 | use std::time::Duration; 106 | use std::thread; 107 | 108 | // TODO somehow also store the metadata -- without it we can't provide reading functionality to anyone 109 | 110 | let digest_lists = get_digest_lists(blob_graph); 111 | let mut digests_iter = digest_lists.iter(); 112 | let mut to_go = digest_lists.len(); 113 | 114 | let (bt_tx, bt_rx) = sync_channel(3 * thread_count as usize); 115 | let (pt_tx, pt_rx) = mpmc_queue(3 * thread_count as u64); 116 | for _ in 0 .. thread_count { 117 | let bt_tx = bt_tx.clone(); 118 | let pt_rx = pt_rx.clone(); 119 | thread::spawn(move || { 120 | while let Ok(task) = pt_rx.recv() { 121 | handle_parallel_task(task, |bt| bt_tx.send(bt).unwrap()); 122 | } 123 | }); 124 | } 125 | drop(bt_tx); 126 | pt_rx.unsubscribe(); 127 | let mut par_task_backlog = Vec::new(); 128 | let mut blobs_to_store = HashSet::new(); 129 | loop { 130 | let mut done_something = false; 131 | if let Ok(task) = bt_rx.recv_timeout(Duration::new(0, 50_000)) { 132 | handle_blocking_task(task, &mut self.b, 133 | &mut blobs_to_store, |tsk| par_task_backlog.push(tsk)); 134 | done_something = true; 135 | } 136 | if par_task_backlog.is_empty() { 137 | for digests in (&mut digests_iter).take(10) { 138 | to_go -= 1; 139 | println!("{} {}", to_go, digests.len()); 140 | let blobs = digests.iter() 141 | // TODO don't use unwrap here 142 | // TODO instead of filter_map and skipping report an error or something something 143 | .filter_map(|digest| src.b.get(digest).unwrap().map(|b|(*digest, b))) 144 | .collect::>(); 145 | par_task_backlog.push(ParallelTask::CreateMultiBlob(blobs)); 146 | done_something = true; 147 | } 148 | } 149 | loop { 150 | let mut removed_something = false; 151 | if let Some(t) = par_task_backlog.pop() { 152 | if let Err(e) = pt_tx.try_send(t) { 153 | let t = match e { 154 | TrySendError::Full(t) => t, 155 | TrySendError::Disconnected(t) => t, 156 | }; 157 | par_task_backlog.push(t); 158 | } else { 159 | removed_something = true; 160 | done_something = true; 161 | } 162 | } 163 | if !removed_something { 164 | break; 165 | } 166 | } 167 | if !done_something && par_task_backlog.is_empty() { 168 | break; 169 | } 170 | } 171 | } 172 | } 173 | 174 | impl CrateStorage for BlobCrateStorage { 175 | fn store_parallel_iter, Digest)>>( 176 | &mut self, thread_count :u16, mut crate_iter :I) { 177 | use std::sync::mpsc::{sync_channel, TrySendError}; 178 | use multiqueue::mpmc_queue; 179 | use std::time::Duration; 180 | use std::thread; 181 | 182 | let (bt_tx, bt_rx) = sync_channel(3 * thread_count as usize); 183 | let (pt_tx, pt_rx) = mpmc_queue(3 * thread_count as u64); 184 | for _ in 0 .. thread_count { 185 | let bt_tx = bt_tx.clone(); 186 | let pt_rx = pt_rx.clone(); 187 | thread::spawn(move || { 188 | while let Ok(task) = pt_rx.recv() { 189 | handle_parallel_task(task, |bt| bt_tx.send(bt).unwrap()); 190 | } 191 | }); 192 | } 193 | drop(bt_tx); 194 | pt_rx.unsubscribe(); 195 | let mut par_task_backlog = Vec::new(); 196 | let mut blobs_to_store = HashSet::new(); 197 | loop { 198 | let mut done_something = false; 199 | if let Ok(task) = bt_rx.recv_timeout(Duration::new(0, 50_000)) { 200 | handle_blocking_task(task, &mut self.b, 201 | &mut blobs_to_store, |tsk| par_task_backlog.push(tsk)); 202 | done_something = true; 203 | } 204 | if par_task_backlog.is_empty() { 205 | for (sp, b, d) in (&mut crate_iter).take(10) { 206 | let name = sp.file_name(); 207 | par_task_backlog.push(ParallelTask::ObtainCrateContentBlobs(name, b, d)); 208 | done_something = true; 209 | } 210 | } 211 | loop { 212 | let mut removed_something = false; 213 | if let Some(t) = par_task_backlog.pop() { 214 | if let Err(e) = pt_tx.try_send(t) { 215 | let t = match e { 216 | TrySendError::Full(t) => t, 217 | TrySendError::Disconnected(t) => t, 218 | }; 219 | par_task_backlog.push(t); 220 | } else { 221 | removed_something = true; 222 | done_something = true; 223 | } 224 | } 225 | if !removed_something { 226 | break; 227 | } 228 | } 229 | if !done_something && par_task_backlog.is_empty() { 230 | break; 231 | } 232 | } 233 | } 234 | } 235 | 236 | pub struct StorageFileHandle { 237 | meta :CrateRecMetadata, 238 | } 239 | 240 | impl CrateFileHandle> for StorageFileHandle { 241 | fn get_file_list(&self, _source :&mut BlobCrateStorage) -> Vec { 242 | self.meta.get_file_list() 243 | } 244 | fn get_file(&self, source :&mut BlobCrateStorage, 245 | path :&str) -> Option> { 246 | for &(ref hdr, ref d) in self.meta.entry_metadata.iter() { 247 | let hdr = hdr_from_ptr(hdr); 248 | let p = hdr.path().unwrap(); 249 | let s = p.to_str().unwrap(); 250 | if s != path { 251 | continue; 252 | } 253 | let blob = optry!(optry!(source.b.get(d).ok())); 254 | let decompressed = decompress!(blob); 255 | return Some(decompressed); 256 | } 257 | None 258 | } 259 | } 260 | 261 | impl CrateSource for BlobCrateStorage { 262 | 263 | type CrateHandle = StorageFileHandle; 264 | fn get_crate_handle_nv(&mut self, 265 | name :String, version :Version) -> Option> { 266 | let s = CrateSpec { 267 | name, 268 | version, 269 | }; 270 | let meta = optry!(self.get_crate_rec_meta(&s)); 271 | 272 | Some(CrateHandle { 273 | source : self, 274 | crate_file_handle : StorageFileHandle { 275 | meta 276 | }, 277 | }) 278 | } 279 | fn get_crate(&mut self, s :&CrateSpec) -> Option> { 280 | let meta = optry!(self.get_crate_rec_meta(s)); 281 | let mut blobs = Vec::with_capacity(meta.entry_metadata.len()); 282 | for &(ref _hdr, ref d) in meta.entry_metadata.iter() { 283 | let blob = optry!(optry!(self.b.get(d).ok())); 284 | let decompressed = decompress!(blob); 285 | blobs.push((*d, decompressed)); 286 | } 287 | let crmb = CrateRecMetaWithBlobs { 288 | meta, 289 | blobs 290 | }; 291 | let ccb = CrateContentBlobs::from_meta_with_blobs(crmb); 292 | Some(ccb.to_archive_file()) 293 | } 294 | } 295 | 296 | /// Tasks that can be executed in parallel 297 | enum ParallelTask { 298 | ObtainCrateContentBlobs(String, Vec, Digest), 299 | CompressBlob(Digest, Vec), 300 | CreateMultiBlob(Vec<(Digest, Vec)>), 301 | } 302 | 303 | /// Tasks that need blocking access to the blob storage 304 | enum BlockingTask { 305 | StoreCrateUndeduplicated(String, Vec), 306 | StoreCrateContentBlobs(String, CrateContentBlobs), 307 | StoreBlob(Digest, Vec), 308 | StoreMultiBlob(Digest, Vec, Vec), 309 | } 310 | 311 | fn handle_parallel_task(task :ParallelTask, mut emit_task :ET) { 312 | match task { 313 | ParallelTask::ObtainCrateContentBlobs(crate_file_name, crate_archive_file, digest) => { 314 | match CrateContentBlobs::from_archive_file(&crate_archive_file[..]) { 315 | Ok(ccb) => { 316 | if digest == ccb.digest_of_reconstructed() { 317 | emit_task(BlockingTask::StoreCrateContentBlobs(crate_file_name, ccb)); 318 | } else { 319 | // Digest mismatch 320 | emit_task(BlockingTask::StoreCrateUndeduplicated(crate_file_name, crate_archive_file)); 321 | } 322 | }, 323 | Err(_) => { 324 | // Error during CrateContentBlobs creation... most likely invalid gz file or sth 325 | emit_task(BlockingTask::StoreCrateUndeduplicated(crate_file_name, crate_archive_file)); 326 | }, 327 | }; 328 | }, 329 | ParallelTask::CompressBlob(d, blob) => { 330 | let mut gz_enc = GzBuilder::new().read(blob.as_slice(), Compression::best()); 331 | let mut buffer_compressed = Vec::new(); 332 | io::copy(&mut gz_enc, &mut buffer_compressed).unwrap(); 333 | 334 | emit_task(BlockingTask::StoreBlob(d, buffer_compressed)); 335 | }, 336 | ParallelTask::CreateMultiBlob(blobs) => { 337 | let mut root_blob = None; 338 | let mut diff_list = Vec::new(); 339 | let mut digests = Vec::new(); 340 | let mut last :Option<(Digest, &str)> = None; 341 | for (digest, blob) in blobs.iter() { 342 | if let Ok(s) = ::std::str::from_utf8(&blob) { 343 | digests.push(digest); 344 | if let Some(l) = last.take() { 345 | let diff = Diff::from_texts_nl(&l.1, &s); 346 | diff_list.push((l.0, *digest, diff)); 347 | } else { 348 | root_blob = Some((*digest, s.to_string())); 349 | } 350 | last = Some((*digest, s)); 351 | } else { 352 | // UTF-8 decode error. Skip this one. 353 | // TODO emit a compression parallel task here. one day. 354 | let mut gz_enc = GzBuilder::new().read(blob.as_slice(), Compression::best()); 355 | let mut buffer_compressed = Vec::new(); 356 | io::copy(&mut gz_enc, &mut buffer_compressed).unwrap(); 357 | 358 | emit_task(BlockingTask::StoreBlob(*digest, buffer_compressed)); 359 | } 360 | } 361 | 362 | if digests.len() > 0 { 363 | let mb = MultiBlob { 364 | root_blob : root_blob.unwrap(), 365 | diff_list, 366 | }; 367 | let mut mb_blob = Vec::new(); 368 | mb.serialize(&mut mb_blob).unwrap(); 369 | 370 | let mut hctx = HashCtx::new(); 371 | io::copy(&mut mb_blob.as_slice(), &mut hctx).unwrap(); 372 | let multi_blob_digest = hctx.finish_and_get_digest(); 373 | 374 | let mut gz_enc = GzBuilder::new().read(mb_blob.as_slice(), Compression::best()); 375 | let mut buffer_compressed = Vec::new(); 376 | io::copy(&mut gz_enc, &mut buffer_compressed).unwrap(); 377 | 378 | let digests = blobs.iter() 379 | .map(|(digest, _b)| *digest) 380 | .collect::>(); 381 | 382 | let task = BlockingTask::StoreMultiBlob(multi_blob_digest, digests, buffer_compressed); 383 | emit_task(task); 384 | } 385 | }, 386 | } 387 | } 388 | 389 | fn handle_blocking_task(task :BlockingTask, 390 | blob_store :&mut BlobStorage, blobs_to_store :&mut HashSet, 391 | mut emit_task :ET) { 392 | match task { 393 | BlockingTask::StoreCrateUndeduplicated(crate_file_name, crate_blob) => { 394 | // TODO 395 | }, 396 | BlockingTask::StoreCrateContentBlobs(crate_file_name, ccb) => { 397 | let CrateRecMetaWithBlobs { meta, blobs } = ccb.into_meta_with_blobs(); 398 | for entry in blobs { 399 | let entry_digest = entry.0; 400 | if blobs_to_store.insert(entry_digest) { 401 | emit_task(ParallelTask::CompressBlob(entry_digest, entry.1)); 402 | } 403 | } 404 | // emit a blob for meta as well 405 | let mut meta_blob = Vec::new(); 406 | meta.serialize(&mut meta_blob).unwrap(); 407 | let mut meta_blob_hctx = HashCtx::new(); 408 | io::copy(&mut meta_blob.as_slice(), &mut meta_blob_hctx).unwrap(); 409 | let meta_blob_digest = meta_blob_hctx.finish_and_get_digest(); 410 | // The blob digest may be already present, e.g. if 411 | // we had been writing this particular crate into the 412 | // BlobStorage previously. In order to be on the safe 413 | // side, check for existence before inserting into 414 | // the blob storage. 415 | if blobs_to_store.insert(meta_blob_digest) { 416 | emit_task(ParallelTask::CompressBlob(meta_blob_digest, meta_blob)); 417 | } 418 | // enter the meta blob into the blob storage 419 | blob_store.name_index.insert(crate_file_name, meta_blob_digest); 420 | 421 | }, 422 | BlockingTask::StoreBlob(d, blob) => { 423 | let actually_added = blob_store.insert(d, &blob).unwrap(); 424 | // If the blob is already present, it indicates a bug because 425 | // we are supposed to check for presence before we ask for the 426 | // blob to be compressed. If we would just shrug this off, we'd 427 | // waste cycles spent on compressing the blobs. 428 | assert!(actually_added, "Tried to insert a blob into the storage that was already present"); 429 | }, 430 | BlockingTask::StoreMultiBlob(mblob_digest, digests, buf_compressed) => { 431 | let actually_added = blob_store.insert(mblob_digest, &buf_compressed).unwrap(); 432 | for d in digests.iter() { 433 | blob_store.digest_to_multi_blob.insert(*d, mblob_digest); 434 | } 435 | // If the blob is already present, it indicates a bug because 436 | // we are supposed to check for presence before we ask for the 437 | // blob to be compressed. If we would just shrug this off, we'd 438 | // waste cycles spent on compressing the blobs. 439 | assert!(actually_added, "Tried to insert a blob into the storage that was already present"); 440 | }, 441 | } 442 | } 443 | -------------------------------------------------------------------------------- /all-crate-storage/blob_storage.rs: -------------------------------------------------------------------------------- 1 | 2 | use std::io::{Read, Write, Seek, SeekFrom, Result as IoResult, ErrorKind}; 3 | use std::collections::HashMap; 4 | use std::collections::hash_map::Entry; 5 | use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; 6 | use super::hash_ctx::Digest; 7 | 8 | pub struct BlobStorage { 9 | blob_offsets :HashMap, 10 | /// Index that maps (crate) names to digests 11 | /// 12 | /// Note that not all blobs are present in this index, only those that represent 13 | /// a crate. 14 | pub name_index :HashMap, 15 | pub digest_to_multi_blob :HashMap, 16 | storage :S, 17 | index_offset :u64, 18 | } 19 | 20 | pub(crate) fn write_delim_byte_slice(mut wtr :W, sl :&[u8]) -> IoResult<()> { 21 | try!(wtr.write_u64::(sl.len() as u64)); 22 | try!(wtr.write(sl)); 23 | Ok(()) 24 | } 25 | pub(crate) fn read_delim_byte_slice(mut rdr :R) -> IoResult> { 26 | let len = try!(rdr.read_u64::()); 27 | let mut res = vec![0; len as usize]; 28 | try!(rdr.read_exact(&mut res)); 29 | Ok(res) 30 | } 31 | 32 | impl BlobStorage { 33 | pub fn empty(storage :S) -> Self { 34 | BlobStorage { 35 | name_index : HashMap::new(), 36 | digest_to_multi_blob : HashMap::new(), 37 | blob_offsets : HashMap::new(), 38 | 39 | storage, 40 | // TODO don't hardcode this number somehow (get the length of the header) 41 | index_offset : 64, 42 | } 43 | } 44 | pub fn new(mut storage :S) -> IoResult { 45 | try!(storage.seek(SeekFrom::Start(0))); 46 | match storage.read_u64::() { 47 | Ok(v) if v == BLOB_MAGIC => BlobStorage::load(storage), 48 | Ok(_) => panic!("Invalid header"), 49 | Err(ref e) if e.kind() == ErrorKind::UnexpectedEof => Ok(BlobStorage::empty(storage)), 50 | Err(e) => Err(e), 51 | } 52 | } 53 | pub fn load(mut storage :S) -> IoResult { 54 | try!(storage.seek(SeekFrom::Start(0))); 55 | let index_offset = try!(read_hdr(&mut storage)); 56 | try!(storage.seek(SeekFrom::Start(index_offset))); 57 | let blob_offsets = try!(read_offset_table(&mut storage)); 58 | let name_index = try!(read_name_idx(&mut storage)); 59 | let digest_to_multi_blob = try!(read_digest_to_multi_blob(&mut storage)); 60 | Ok(BlobStorage { 61 | blob_offsets, 62 | name_index, 63 | digest_to_multi_blob, 64 | 65 | storage, 66 | index_offset, 67 | }) 68 | } 69 | 70 | pub fn has(&self, digest :&Digest) -> bool { 71 | self.blob_offsets.get(digest).is_some() 72 | } 73 | pub fn get(&mut self, digest :&Digest) -> IoResult>> { 74 | let blob_offs = match self.blob_offsets.get(digest) { 75 | Some(d) => *d, 76 | None => return Ok(None), 77 | }; 78 | try!(self.storage.seek(SeekFrom::Start(blob_offs))); 79 | let content = try!(read_delim_byte_slice(&mut self.storage)); 80 | Ok(Some(content)) 81 | } 82 | } 83 | 84 | impl BlobStorage { 85 | pub fn insert_named_blob(&mut self, name :Option, digest :Digest, content :&[u8]) -> IoResult<()> { 86 | if let Some(n) = name { 87 | self.name_index.insert(n, digest); 88 | } 89 | try!(self.insert(digest, &content)); 90 | Ok(()) 91 | } 92 | pub fn insert(&mut self, digest :Digest, content :&[u8]) -> IoResult { 93 | let e = self.blob_offsets.entry(digest); 94 | match e { 95 | Entry::Occupied(_) => return Ok(false), 96 | Entry::Vacant(v) => v.insert(self.index_offset), 97 | }; 98 | try!(self.storage.seek(SeekFrom::Start(self.index_offset))); 99 | try!(write_delim_byte_slice(&mut self.storage, content)); 100 | self.index_offset = try!(self.storage.seek(SeekFrom::Current(0))); 101 | Ok(true) 102 | } 103 | pub fn write_header_and_index(&mut self) -> IoResult<()> { 104 | try!(self.storage.seek(SeekFrom::Start(0))); 105 | try!(write_hdr(&mut self.storage, self.index_offset)); 106 | try!(self.storage.seek(SeekFrom::Start(self.index_offset))); 107 | try!(write_offset_table(&mut self.storage, &self.blob_offsets)); 108 | try!(write_name_idx(&mut self.storage, &self.name_index)); 109 | try!(write_digest_to_multi_blob(&mut self.storage, &self.digest_to_multi_blob)); 110 | Ok(()) 111 | } 112 | } 113 | 114 | const BLOB_MAGIC :u64 = 0x42_4C_4F_42_53_54_52_45; 115 | 116 | fn read_hdr(mut rdr :R) -> IoResult { 117 | let magic = try!(rdr.read_u64::()); 118 | // TODO return Err instead of panicing 119 | assert_eq!(magic, BLOB_MAGIC); 120 | let index_offset = try!(rdr.read_u64::()); 121 | Ok(index_offset) 122 | } 123 | fn write_hdr(mut wtr :W, index_offset :u64) -> IoResult<()> { 124 | try!(wtr.write_u64::(BLOB_MAGIC)); 125 | try!(wtr.write_u64::(index_offset)); 126 | Ok(()) 127 | } 128 | fn read_offset_table(mut rdr :R) -> IoResult> { 129 | let len = try!(rdr.read_u64::()); 130 | let mut tbl = HashMap::new(); 131 | for _ in 0 .. len { 132 | let mut d :Digest = [0; 32]; 133 | try!(rdr.read_exact(&mut d)); 134 | let offset = try!(rdr.read_u64::()); 135 | tbl.insert(d, offset); 136 | } 137 | Ok(tbl) 138 | } 139 | fn write_offset_table(mut wtr :W, tbl :&HashMap) -> IoResult<()> { 140 | try!(wtr.write_u64::(tbl.len() as u64)); 141 | for (d, o) in tbl.iter() { 142 | try!(wtr.write(d)); 143 | try!(wtr.write_u64::(*o)); 144 | } 145 | Ok(()) 146 | } 147 | fn read_name_idx(mut rdr :R) -> IoResult> { 148 | let nidx_len = try!(rdr.read_u64::()); 149 | let mut nidx = HashMap::new(); 150 | for _ in 0 .. nidx_len { 151 | let s_bytes = try!(read_delim_byte_slice(&mut rdr)); 152 | let mut d :Digest = [0; 32]; 153 | try!(rdr.read_exact(&mut d)); 154 | let s = String::from_utf8(s_bytes).unwrap(); 155 | // TODO return Err instead of panicing 156 | nidx.insert(s, d); 157 | } 158 | Ok(nidx) 159 | } 160 | fn write_name_idx(mut wtr :W, nidx :&HashMap) -> IoResult<()> { 161 | try!(wtr.write_u64::(nidx.len() as u64)); 162 | for (s,d) in nidx.iter() { 163 | try!(write_delim_byte_slice(&mut wtr, s.as_bytes())); 164 | try!(wtr.write(d)); 165 | } 166 | Ok(()) 167 | } 168 | fn read_digest_to_multi_blob(mut rdr :R) -> IoResult> { 169 | let res_len = try!(rdr.read_u64::()); 170 | let mut res = HashMap::new(); 171 | for _ in 0 .. res_len { 172 | let mut d :Digest = [0; 32]; 173 | let mut d_multi :Digest = [0; 32]; 174 | try!(rdr.read_exact(&mut d)); 175 | try!(rdr.read_exact(&mut d_multi)); 176 | res.insert(d, d_multi); 177 | } 178 | Ok(res) 179 | } 180 | fn write_digest_to_multi_blob(mut wtr :W, nidx :&HashMap) -> IoResult<()> { 181 | try!(wtr.write_u64::(nidx.len() as u64)); 182 | for (d, d_multi) in nidx.iter() { 183 | try!(wtr.write(d)); 184 | try!(wtr.write(d_multi)); 185 | } 186 | Ok(()) 187 | } 188 | -------------------------------------------------------------------------------- /all-crate-storage/blob_storage_test.rs: -------------------------------------------------------------------------------- 1 | use std::io::Cursor; 2 | use super::blob_storage::{BlobStorage}; 3 | 4 | #[test] 5 | fn store_and_load() { 6 | let mut c = Cursor::new(Vec::new()); 7 | let test_data = [ 8 | ([1u8; 32], &vec![1,2,3,4,5,6,7,8]), 9 | ([2; 32], &vec![7,8,9,1,1,1,9,8,7]), 10 | ([3; 32], &vec![8,3,8,3,8,3,8,3,8,3,8,3,8,3,8,3,8,3]), 11 | ]; 12 | { 13 | let mut st = BlobStorage::empty(&mut c); 14 | for &(d, ref s) in test_data.iter() { 15 | st.insert(d, s).unwrap(); 16 | } 17 | st.write_header_and_index().unwrap(); 18 | } 19 | println!("c {:?}", c); 20 | { 21 | let mut st = BlobStorage::load(&mut c).unwrap(); 22 | for &(ref d, s) in test_data.iter() { 23 | assert_eq!(st.get(d).unwrap().as_ref(), Some(s)); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /all-crate-storage/crate_storage.rs: -------------------------------------------------------------------------------- 1 | use semver::Version; 2 | use super::hash_ctx::{HashCtx, Digest}; 3 | use super::registry::registry::{CrateIndexJson, AllCratesJson}; 4 | use super::blob_crate_storage::{BlobCrateStorage, StorageFileHandle}; 5 | use flate2::read::GzDecoder; 6 | use tar::Archive; 7 | use std::path::{Path, PathBuf}; 8 | use std::cell::RefCell; 9 | use std::fs::File; 10 | use std::io::{self, Read, Seek}; 11 | use std::ops::Deref; 12 | use registry::registry::obtain_crate_name_path; 13 | 14 | #[derive(Clone, PartialEq, Eq)] 15 | pub struct CrateSpec { 16 | pub name :String, 17 | pub version :Version, 18 | } 19 | 20 | impl CrateSpec { 21 | pub fn file_name(&self) -> String { 22 | format!("{}-{}.crate", self.name, self.version) 23 | } 24 | } 25 | 26 | pub struct CrateHandle<'a, S :CrateSource + 'a, C :CrateFileHandle> { 27 | pub source :&'a mut S, 28 | pub crate_file_handle :C, 29 | } 30 | 31 | impl<'a, S :CrateSource + 'a, C :CrateFileHandle> CrateHandle<'a, S, C> { 32 | pub fn get_file_list(&mut self) -> Vec { 33 | self.crate_file_handle.get_file_list(&mut self.source) 34 | } 35 | pub fn get_file(&mut self, path :&str) -> Option> { 36 | self.crate_file_handle.get_file(&mut self.source, path) 37 | } 38 | } 39 | 40 | pub trait CrateFileHandle { 41 | fn get_file_list(&self, source :&mut S) -> Vec; 42 | fn get_file(&self, source :&mut S, path :&str) -> Option>; 43 | } 44 | 45 | impl CrateFileHandle for Box> { 46 | fn get_file_list(&self, source :&mut S) -> Vec { 47 | as Deref>::deref(self).get_file_list(source) 48 | } 49 | fn get_file(&self, source :&mut S, path :&str) -> Option> { 50 | as Deref>::deref(self).get_file(source, path) 51 | } 52 | } 53 | 54 | pub trait CrateSource :Sized { 55 | type CrateHandle :CrateFileHandle; 56 | fn get_crate_handle_nv(&mut self, 57 | name :String, version :Version) -> Option>; 58 | // TODO maybe use CrateSpec here? 59 | fn get_crate_nv(&mut self, name :String, version :Version) -> Option> { 60 | self.get_crate(&CrateSpec { 61 | name, 62 | version, 63 | }) 64 | } 65 | fn get_crate(&mut self, spec :&CrateSpec) -> Option>; 66 | } 67 | 68 | pub trait CrateStorage { 69 | fn store_parallel_iter, Digest)>>( 70 | &mut self, thread_count :u16, crate_iter :I); 71 | 72 | fn fill_crate_storage_from_source(&mut self, 73 | thread_count :u16, acj :&AllCratesJson, source :&mut S, 74 | progress_callback :fn(&str, &CrateIndexJson)) { 75 | // Iterators are cool they told me. 76 | // Iterators are idiomatic they told me. 77 | // THEN WHY THE FUCK DO I NEED THIS REFCELL CRAP?!?!?! 78 | // https://stackoverflow.com/a/28521985 79 | let source_cell = RefCell::new(source); 80 | let crate_iter = acj.iter() 81 | .flat_map(|&(ref name, ref versions)| { 82 | let name = name.clone(); 83 | let source_cell = &source_cell; 84 | versions.iter().filter_map(move |v| { 85 | let name = name.clone(); 86 | let mut source = source_cell.borrow_mut(); 87 | progress_callback(&name, &v); 88 | 89 | let spec = CrateSpec { 90 | name : name.to_owned(), 91 | version : v.version.clone(), 92 | }; 93 | let crate_file_buf = match source.get_crate(&spec) { 94 | Some(cfb) => cfb, 95 | None => return None, 96 | }; 97 | 98 | let mut hctx = HashCtx::new(); 99 | io::copy(&mut crate_file_buf.as_slice(), &mut hctx).unwrap(); 100 | let d = hctx.finish_and_get_digest(); 101 | Some((spec, crate_file_buf, d)) 102 | }) 103 | }); 104 | self.store_parallel_iter(thread_count, crate_iter); 105 | } 106 | } 107 | 108 | pub enum DynCrateSource { 109 | FileTreeStorage(FileTreeStorage), 110 | CacheStorage(CacheStorage), 111 | BlobCrateStorage(BlobCrateStorage), 112 | OverlayCrateSource(Box, DynCrateSource>>), 113 | } 114 | 115 | pub enum DynCrateHandle { 116 | BlobCrateHandle(BlobCrateHandle), 117 | StorageFileHandle(StorageFileHandle), 118 | OverlayCrateHandle(Box, DynCrateSource>>), 119 | } 120 | 121 | impl DynCrateHandle { 122 | fn blob(&self) -> Option<&BlobCrateHandle> { 123 | match self { 124 | &DynCrateHandle::BlobCrateHandle(ref h) => Some(h), 125 | _ => None, 126 | } 127 | } 128 | fn storage(&self) -> Option<&StorageFileHandle> { 129 | match self { 130 | &DynCrateHandle::StorageFileHandle(ref h) => Some(h), 131 | _ => None, 132 | } 133 | } 134 | fn overlay(&self) -> Option<&OverlayCrateHandle, DynCrateSource>> { 135 | match self { 136 | &DynCrateHandle::OverlayCrateHandle(ref h) => Some(h), 137 | _ => None, 138 | } 139 | } 140 | } 141 | 142 | impl CrateSource for DynCrateSource { 143 | type CrateHandle = DynCrateHandle; 144 | fn get_crate_handle_nv(&mut self, 145 | name :String, version :Version) -> Option> { 146 | let ch = match self { 147 | &mut DynCrateSource::FileTreeStorage(ref mut s) => { 148 | s.get_crate_handle_nv(name, version) 149 | .map(|h| DynCrateHandle::BlobCrateHandle(h.crate_file_handle)) 150 | }, 151 | &mut DynCrateSource::CacheStorage(ref mut s) => { 152 | s.get_crate_handle_nv(name, version) 153 | .map(|h| DynCrateHandle::BlobCrateHandle(h.crate_file_handle)) 154 | }, 155 | &mut DynCrateSource::BlobCrateStorage(ref mut s) => { 156 | s.get_crate_handle_nv(name, version) 157 | .map(|h| DynCrateHandle::StorageFileHandle(h.crate_file_handle)) 158 | }, 159 | &mut DynCrateSource::OverlayCrateSource(ref mut s) => { 160 | s.get_crate_handle_nv(name, version) 161 | .map(|h| DynCrateHandle::OverlayCrateHandle(Box::new(h.crate_file_handle))) 162 | }, 163 | }; 164 | if let Some(ch) = ch { 165 | Some(CrateHandle { 166 | source : self, 167 | crate_file_handle : ch, 168 | }) 169 | } else { 170 | None 171 | } 172 | } 173 | fn get_crate(&mut self, spec :&CrateSpec) -> Option> { 174 | match self { 175 | &mut DynCrateSource::FileTreeStorage(ref mut s) => { 176 | s.get_crate(spec) 177 | }, 178 | &mut DynCrateSource::CacheStorage(ref mut s) => { 179 | s.get_crate(spec) 180 | }, 181 | &mut DynCrateSource::BlobCrateStorage(ref mut s) => { 182 | s.get_crate(spec) 183 | }, 184 | &mut DynCrateSource::OverlayCrateSource(ref mut s) => { 185 | s.get_crate(spec) 186 | }, 187 | } 188 | } 189 | } 190 | 191 | impl CrateFileHandle> for DynCrateHandle { 192 | fn get_file_list(&self, source :&mut DynCrateSource) -> Vec { 193 | match source { 194 | &mut DynCrateSource::FileTreeStorage(ref mut s) => { 195 | self.blob().unwrap().get_file_list(s) 196 | }, 197 | &mut DynCrateSource::CacheStorage(ref mut s) => { 198 | self.blob().unwrap().get_file_list(s) 199 | }, 200 | &mut DynCrateSource::BlobCrateStorage(ref mut s) => { 201 | self.storage().unwrap().get_file_list(s) 202 | }, 203 | &mut DynCrateSource::OverlayCrateSource(ref mut s) => { 204 | self.overlay().unwrap().get_file_list(s) 205 | }, 206 | } 207 | } 208 | fn get_file(&self, source :&mut DynCrateSource, 209 | path :&str) -> Option> { 210 | match source { 211 | &mut DynCrateSource::FileTreeStorage(ref mut s) => { 212 | self.blob().unwrap().get_file(s, path) 213 | }, 214 | &mut DynCrateSource::CacheStorage(ref mut s) => { 215 | self.blob().unwrap().get_file(s, path) 216 | }, 217 | &mut DynCrateSource::BlobCrateStorage(ref mut s) => { 218 | self.storage().unwrap().get_file(s, path) 219 | }, 220 | &mut DynCrateSource::OverlayCrateSource(ref mut s) => { 221 | self.overlay().unwrap().get_file(s, path) 222 | }, 223 | } 224 | } 225 | } 226 | 227 | pub struct OverlayCrateSource(S, T); 228 | 229 | impl OverlayCrateSource { 230 | pub fn new(default :S, fallback :T) -> Self { 231 | OverlayCrateSource(default, fallback) 232 | } 233 | fn get_overlay_crate_handle_nv(&mut self, 234 | name :String, version :Version) -> Option> { 235 | if let Some(v) = self.0.get_crate_handle_nv(name.clone(), version.clone()) { 236 | return Some(OverlayCrateHandle::DefaultFound(v.crate_file_handle)); 237 | } 238 | if let Some(v) = self.1.get_crate_handle_nv(name, version) { 239 | return Some(OverlayCrateHandle::FallbackFound(v.crate_file_handle)); 240 | } 241 | return None; 242 | } 243 | } 244 | 245 | impl CrateSource for OverlayCrateSource { 246 | type CrateHandle = OverlayCrateHandle; 247 | fn get_crate_handle_nv(&mut self, 248 | name :String, version :Version) -> Option> { 249 | if let Some(ch) = self.get_overlay_crate_handle_nv(name, version) { 250 | Some(CrateHandle { 251 | source : self, 252 | crate_file_handle : ch, 253 | }) 254 | } else { 255 | None 256 | } 257 | } 258 | fn get_crate(&mut self, spec :&CrateSpec) -> Option> { 259 | if let Some(v) = self.0.get_crate(spec) { 260 | return Some(v); 261 | } 262 | return self.1.get_crate(spec); 263 | } 264 | } 265 | 266 | pub enum OverlayCrateHandle { 267 | DefaultFound(D::CrateHandle), 268 | FallbackFound(F::CrateHandle), 269 | } 270 | 271 | impl CrateFileHandle> for OverlayCrateHandle { 272 | fn get_file_list(&self, source :&mut OverlayCrateSource) -> Vec { 273 | match self { 274 | &OverlayCrateHandle::DefaultFound(ref s) => { 275 | s.get_file_list(&mut source.0) 276 | }, 277 | &OverlayCrateHandle::FallbackFound(ref s) => { 278 | s.get_file_list(&mut source.1) 279 | }, 280 | } 281 | } 282 | fn get_file(&self, source :&mut OverlayCrateSource, 283 | path :&str) -> Option> { 284 | match self { 285 | &OverlayCrateHandle::DefaultFound(ref s) => { 286 | s.get_file(&mut source.0, path) 287 | }, 288 | &OverlayCrateHandle::FallbackFound(ref s) => { 289 | s.get_file(&mut source.1, path) 290 | }, 291 | } 292 | } 293 | } 294 | 295 | pub struct FileTreeStorage { 296 | storage_base :PathBuf, 297 | } 298 | 299 | impl FileTreeStorage { 300 | pub fn new(storage_base :&Path) -> Self { 301 | FileTreeStorage { 302 | storage_base : storage_base.to_path_buf(), 303 | } 304 | } 305 | } 306 | 307 | 308 | pub struct BlobCrateHandle { 309 | content :Vec, 310 | } 311 | 312 | impl BlobCrateHandle { 313 | pub fn new(content :Vec) -> Self { 314 | BlobCrateHandle { 315 | content 316 | } 317 | } 318 | pub fn map_all_files, Option>)>(&self, mut f :F) { 319 | let r = self.content.as_slice(); 320 | let decoded = GzDecoder::new(r); 321 | let mut archive = Archive::new(decoded); 322 | for entry in archive.entries().unwrap() { 323 | let mut entry = if let Ok(entry) = entry { 324 | entry 325 | } else { 326 | continue; 327 | }; 328 | let path :Option = entry.path().ok() 329 | .and_then(|s| if let Some(s) = s.to_str() { 330 | Some(s.to_owned()) 331 | } else { 332 | None 333 | }); 334 | let mut v = Vec::new(); 335 | let v = if entry.read_to_end(&mut v).is_ok() { 336 | Some(v) 337 | } else { 338 | None 339 | }; 340 | f(path, v); 341 | } 342 | } 343 | } 344 | 345 | impl CrateFileHandle for BlobCrateHandle { 346 | fn get_file_list(&self, _source :&mut S) -> Vec { 347 | let f = self.content.as_slice(); 348 | let mut l = Vec::new(); 349 | let decoded = GzDecoder::new(f); 350 | let mut archive = Archive::new(decoded); 351 | for entry in archive.entries().unwrap() { 352 | let entry = entry.unwrap(); 353 | let path = entry.path().unwrap(); 354 | let s :String = path.to_str().unwrap().to_owned(); 355 | l.push(s); 356 | } 357 | l 358 | } 359 | fn get_file(&self, _ :&mut S, path :&str) -> Option> { 360 | extract_path_from_gz(self.content.as_slice(), path) 361 | } 362 | } 363 | 364 | macro_rules! otry { 365 | ($v:expr) => {{ 366 | if let Some(v) = $v.ok() { 367 | v 368 | } else { 369 | return None; 370 | } 371 | }}; 372 | } 373 | 374 | fn extract_path_from_gz(r :T, 375 | path_ex :&str) -> Option> { 376 | let decoded = GzDecoder::new(r); 377 | let mut archive = Archive::new(decoded); 378 | for entry in otry!(archive.entries()) { 379 | let mut entry = otry!(entry); 380 | let is_path_ex = if let Some(path) = otry!(entry.path()).to_str() { 381 | path_ex == path 382 | } else { 383 | false 384 | }; 385 | if is_path_ex { 386 | // Extract the file 387 | let mut v = Vec::new(); 388 | otry!(entry.read_to_end(&mut v)); 389 | return Some(v); 390 | } 391 | } 392 | return None; 393 | } 394 | 395 | 396 | impl CrateSource for FileTreeStorage { 397 | type CrateHandle = BlobCrateHandle; 398 | fn get_crate_handle_nv(&mut self, 399 | name :String, version :Version) -> Option> { 400 | if let Some(content) = self.get_crate_nv(name, version) { 401 | Some(CrateHandle { 402 | source : self, 403 | crate_file_handle : BlobCrateHandle::new(content), 404 | }) 405 | } else { 406 | None 407 | } 408 | } 409 | fn get_crate(&mut self, spec :&CrateSpec) -> Option> { 410 | let crate_file_path = self.storage_base 411 | .join(obtain_crate_name_path(&spec.name)) 412 | .join(spec.file_name()); 413 | let mut f = match File::open(&crate_file_path) { 414 | Ok(f) => f, 415 | Err(_) => { 416 | return None; 417 | }, 418 | }; 419 | let mut file_buf = Vec::new(); 420 | io::copy(&mut f, &mut file_buf).unwrap(); 421 | Some(file_buf) 422 | } 423 | } 424 | 425 | pub struct CacheStorage { 426 | storage_base :PathBuf, 427 | } 428 | 429 | impl CacheStorage { 430 | pub fn new(storage_base :&Path) -> Self { 431 | CacheStorage { 432 | storage_base : storage_base.to_path_buf(), 433 | } 434 | } 435 | } 436 | 437 | impl CrateSource for CacheStorage { 438 | type CrateHandle = BlobCrateHandle; 439 | fn get_crate_handle_nv(&mut self, 440 | name :String, version :Version) -> Option> { 441 | if let Some(content) = self.get_crate_nv(name, version) { 442 | Some(CrateHandle { 443 | source : self, 444 | crate_file_handle : BlobCrateHandle::new(content), 445 | }) 446 | } else { 447 | None 448 | } 449 | } 450 | fn get_crate(&mut self, spec :&CrateSpec) -> Option> { 451 | let crate_file_path = self.storage_base 452 | .join(spec.file_name()); 453 | let mut f = match File::open(&crate_file_path) { 454 | Ok(f) => f, 455 | Err(_) => { 456 | return None; 457 | }, 458 | }; 459 | let mut file_buf = Vec::new(); 460 | io::copy(&mut f, &mut file_buf).unwrap(); 461 | Some(file_buf) 462 | } 463 | } 464 | -------------------------------------------------------------------------------- /all-crate-storage/diff.rs: -------------------------------------------------------------------------------- 1 | use std::io::Result as IoResult; 2 | use std::io::{Read, Write}; 3 | use difference::{Difference, Changeset}; 4 | use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; 5 | use super::blob_storage::{write_delim_byte_slice, read_delim_byte_slice}; 6 | use std::str; 7 | 8 | #[derive(Debug)] 9 | pub enum DiffInstruction { 10 | Same(u64), 11 | Addition(String), 12 | Removal(u64), 13 | } 14 | 15 | impl DiffInstruction { 16 | fn from_difference_last(d :Difference) -> Self { 17 | use self::Difference as D; 18 | use self::DiffInstruction as Di; 19 | match d { 20 | D::Same(s) => Di::Same(s.len() as u64), 21 | D::Add(s) => Di::Addition(s), 22 | D::Rem(s) => Di::Removal(s.len() as u64), 23 | } 24 | } 25 | fn from_difference(d :Difference, sep :&str) -> Self { 26 | use self::Difference as D; 27 | use self::DiffInstruction as Di; 28 | 29 | match d { 30 | D::Same(s) => Di::Same((s.len() + sep.len()) as u64), 31 | D::Add(s) => Di::Addition(s + "\n"), 32 | D::Rem(s) => Di::Removal((s.len() + sep.len()) as u64), 33 | } 34 | } 35 | } 36 | 37 | #[derive(Debug)] 38 | pub struct Diff { 39 | instructions :Vec, 40 | } 41 | 42 | impl Diff { 43 | pub fn from_texts_nl(old :&str, new :&str) -> Self { 44 | Diff::from_texts(old, new, "\n") 45 | } 46 | pub fn from_texts(old :&str, new :&str, sep :&str) -> Self { 47 | let cset = Changeset::new(old, new, sep); 48 | let len = cset.diffs.len(); 49 | let instructions = cset.diffs.into_iter() 50 | .enumerate() 51 | .map(|(i, d)| { 52 | println!("{:?}", d); 53 | if i + 1 < len { 54 | DiffInstruction::from_difference(d, sep) 55 | } else { 56 | DiffInstruction::from_difference_last(d) 57 | } 58 | }) 59 | .collect::>(); 60 | Diff { 61 | instructions, 62 | } 63 | } 64 | pub fn reconstruct_new(&self, old :&str) -> String { 65 | let mut res = String::new(); 66 | let mut oldsl = old; 67 | for ins in self.instructions.iter() { 68 | match ins { 69 | &DiffInstruction::Same(l) => { 70 | let adv = l as usize; 71 | res += &oldsl[..adv]; 72 | oldsl = &oldsl[adv..]; 73 | }, 74 | &DiffInstruction::Addition(ref s) => { 75 | res += s; 76 | }, 77 | &DiffInstruction::Removal(l) => { 78 | let adv = l as usize; 79 | oldsl = &oldsl[adv..]; 80 | }, 81 | } 82 | } 83 | res 84 | } 85 | pub fn deserialize(mut rdr :R) -> IoResult { 86 | let len = try!(rdr.read_u64::()); 87 | let mut instructions = Vec::with_capacity(len as usize); 88 | for _ in 0 .. len { 89 | let kind = try!(rdr.read_u8()); 90 | let ins = match kind { 91 | 1 => DiffInstruction::Same(try!(rdr.read_u64::())), 92 | 2 => { 93 | let sl = try!(read_delim_byte_slice(&mut rdr)); 94 | // TODO get rid of unwrap here 95 | let s = str::from_utf8(&sl).unwrap(); 96 | DiffInstruction::Addition(s.to_owned()) 97 | }, 98 | 3 => DiffInstruction::Removal(try!(rdr.read_u64::())), 99 | _ => panic!("Invalid kind {}", kind), 100 | }; 101 | instructions.push(ins); 102 | } 103 | Ok(Diff { 104 | instructions 105 | }) 106 | } 107 | pub fn serialize(&self, mut wtr :W) -> IoResult<()> { 108 | try!(wtr.write_u64::(self.instructions.len() as u64)); 109 | for ins in self.instructions.iter() { 110 | let kind = match ins { 111 | &DiffInstruction::Same(_) => 1, 112 | &DiffInstruction::Addition(_) => 2, 113 | &DiffInstruction::Removal(_) => 3, 114 | }; 115 | try!(wtr.write_u8(kind)); 116 | match ins { 117 | &DiffInstruction::Same(l) => try!(wtr.write_u64::(l)), 118 | &DiffInstruction::Addition(ref s) => { 119 | try!(write_delim_byte_slice(&mut wtr, s.as_bytes())); 120 | }, 121 | &DiffInstruction::Removal(l) => try!(wtr.write_u64::(l)), 122 | } 123 | } 124 | Ok(()) 125 | } 126 | } 127 | 128 | #[cfg(test)] 129 | mod test { 130 | use super::*; 131 | #[test] 132 | fn test_simple() { 133 | let str_a = r#" 134 | Hello, dear 135 | World! 136 | Nice to see you."#; 137 | let str_b = r#" 138 | Hello, dear 139 | Reader! 140 | Nice to see you."#; 141 | let diff = Diff::from_texts_nl(str_a, str_b); 142 | let str_b_reconstructed = diff.reconstruct_new(str_a); 143 | assert_eq!(str_b, str_b_reconstructed); 144 | } 145 | #[test] 146 | fn test_simple_ser_de() { 147 | let str_a = r#" 148 | Hello, dear 149 | World! 150 | Nice to see you."#; 151 | let str_b = r#" 152 | Hello, dear 153 | Reader! 154 | Nice to see you."#; 155 | let diff = Diff::from_texts_nl(str_a, str_b); 156 | let mut v = Vec::new(); 157 | diff.serialize(&mut v).unwrap(); 158 | let diff_reconstructed = Diff::deserialize(v.as_slice()).unwrap(); 159 | let str_b_reconstructed = diff_reconstructed.reconstruct_new(str_a); 160 | assert_eq!(str_b, str_b_reconstructed); 161 | } 162 | #[test] 163 | fn test_another() { 164 | let str_a = r#" 165 | For this test, 166 | we wonder about the first line."#; 167 | let str_b = r#" 168 | For this example, 169 | we wonder about the first line."#; 170 | let diff = Diff::from_texts_nl(str_a, str_b); 171 | let str_b_reconstructed = diff.reconstruct_new(str_a); 172 | assert_eq!(str_b, str_b_reconstructed); 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /all-crate-storage/hash_ctx.rs: -------------------------------------------------------------------------------- 1 | use hex; 2 | use ring::digest::{Context, SHA256}; 3 | use std::io; 4 | 5 | pub type Digest = [u8; 32]; 6 | 7 | pub fn get_digest_hex(digest :Digest) -> String { 8 | hex::encode(&digest) 9 | } 10 | 11 | pub fn digest_from_hex(digest :&str) -> Option { 12 | match hex::decode(&digest) { 13 | Ok(v) => { 14 | let mut res = [0; 32]; 15 | res.copy_from_slice(&v[..32]); 16 | Some(res) 17 | }, 18 | Err(_) => None, 19 | } 20 | } 21 | 22 | /// SHA-256 hash context that impls Write 23 | pub struct HashCtx(Context); 24 | 25 | impl io::Write for HashCtx { 26 | fn write(&mut self, data: &[u8]) -> Result { 27 | self.0.update(data); 28 | Ok(data.len()) 29 | } 30 | fn flush(&mut self) -> Result<(), io::Error> { 31 | Ok(()) 32 | } 33 | } 34 | 35 | impl HashCtx { 36 | pub fn new() -> HashCtx { 37 | HashCtx(Context::new(&SHA256)) 38 | } 39 | pub fn finish_and_get_digest_hex(self) -> String { 40 | let digest = self.finish_and_get_digest(); 41 | get_digest_hex(digest) 42 | } 43 | pub fn finish_and_get_digest(self) -> Digest { 44 | let digest = self.0.finish(); 45 | let mut res = [0; 32]; 46 | res[0 .. 32].clone_from_slice(&digest.as_ref()[0 .. 32]); 47 | res 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /all-crate-storage/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate serde; 2 | extern crate serde_json; 3 | #[macro_use] 4 | extern crate serde_derive; 5 | extern crate semver; 6 | extern crate failure; 7 | #[macro_use] 8 | extern crate failure_derive; 9 | extern crate string_interner; 10 | extern crate git2; 11 | extern crate byteorder; 12 | extern crate ring; 13 | extern crate flate2; 14 | extern crate tar; 15 | extern crate multiqueue; 16 | extern crate hex; 17 | extern crate difference; 18 | extern crate petgraph; 19 | #[macro_use] 20 | extern crate try; 21 | 22 | pub mod registry; 23 | pub mod crate_storage; 24 | pub mod blob_storage; 25 | pub mod blob_crate_storage; 26 | pub mod multi_blob_crate_storage; 27 | pub mod hash_ctx; 28 | pub mod reconstruction; 29 | pub mod diff; 30 | pub mod multi_blob; 31 | 32 | #[cfg(test)] 33 | mod blob_storage_test; 34 | -------------------------------------------------------------------------------- /all-crate-storage/multi_blob.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | Multiblob storage 3 | 4 | This structure stores multiple blobs by storing the 5 | first blob directly, and then expressing the other 6 | blobs via a tree structure, only storing the edges 7 | between the vertices via diffs. 8 | */ 9 | 10 | use hash_ctx::Digest; 11 | use super::diff::Diff; 12 | use std::io::Result as IoResult; 13 | use std::io::{Read, Write}; 14 | use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; 15 | use super::blob_storage::{write_delim_byte_slice, read_delim_byte_slice}; 16 | 17 | pub struct MultiBlob { 18 | pub(crate) root_blob :(Digest, String), 19 | /// The tree expressed in DFS traversal form. 20 | /// 21 | /// In order to get the path to the root, 22 | /// you should traverse this list in a reverse 23 | /// fashion. 24 | pub(crate) diff_list :Vec<(Digest, Digest, Diff)>, 25 | } 26 | 27 | impl MultiBlob { 28 | pub fn get_blob(&self, d :Digest) -> Option { 29 | // Assemble the diffs 30 | let mut needed = d; 31 | let mut diffs = Vec::new(); 32 | for cr in self.diff_list.iter().rev() { 33 | if cr.0 != needed { 34 | continue; 35 | } 36 | needed = cr.1; 37 | diffs.push(&cr.2); 38 | } 39 | // Resolve the diffs 40 | if needed != self.root_blob.0 { 41 | return None; 42 | } 43 | let mut res = self.root_blob.1.clone(); 44 | for diff in diffs.iter() { 45 | res = diff.reconstruct_new(&res); 46 | } 47 | Some(res) 48 | } 49 | pub fn deserialize(mut rdr :R) -> IoResult { 50 | let mut root_digest :Digest = [0; 32]; 51 | try!(rdr.read_exact(&mut root_digest)); 52 | let root_sl = try!(read_delim_byte_slice(&mut rdr)); 53 | // TODO get rid of unwrap here 54 | let root_s = String::from_utf8(root_sl).unwrap(); 55 | let root_blob = (root_digest, root_s); 56 | let len = try!(rdr.read_u64::()); 57 | let mut diff_list = Vec::with_capacity(len as usize); 58 | for _ in 0 .. len { 59 | let mut digest_a :Digest = [0; 32]; 60 | try!(rdr.read_exact(&mut digest_a)); 61 | let mut digest_b :Digest = [0; 32]; 62 | try!(rdr.read_exact(&mut digest_b)); 63 | let diff = try!(Diff::deserialize(&mut rdr)); 64 | diff_list.push((digest_a, digest_b, diff)); 65 | } 66 | Ok(MultiBlob { root_blob, diff_list }) 67 | } 68 | pub fn serialize(&self, mut wtr :W) -> IoResult<()> { 69 | try!(wtr.write(&self.root_blob.0)); 70 | try!(write_delim_byte_slice(&mut wtr, self.root_blob.1.as_bytes())); 71 | try!(wtr.write_u64::(self.diff_list.len() as u64)); 72 | for d in self.diff_list.iter() { 73 | try!(wtr.write(&d.0)); 74 | try!(wtr.write(&d.1)); 75 | try!(d.2.serialize(&mut wtr)); 76 | } 77 | Ok(()) 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /all-crate-storage/multi_blob_crate_storage.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | 3 | Embedding multi blob into blob crate storages 4 | 5 | In the first step, we create a directed graph of blobs. 6 | In the second step, we determine minimum spanning trees 7 | 8 | */ 9 | 10 | use hash_ctx::Digest; 11 | use std::collections::{HashMap, HashSet}; 12 | use std::collections::hash_map::Entry; 13 | use std::io::{self, Read, Seek}; 14 | use semver::Version; 15 | use petgraph::graph::{Graph, NodeIndex}; 16 | use registry::registry::AllCratesJson; 17 | use crate_storage::{CrateSource, CrateSpec}; 18 | use blob_crate_storage::BlobCrateStorage; 19 | 20 | use super::hash_ctx::HashCtx; 21 | 22 | /** 23 | A grah of blobs 24 | 25 | Each node represents a blob. 26 | Edges suggest that the two blobs 27 | might be different versions of the same file, 28 | thus possibly have a small diff. 29 | */ 30 | pub struct GraphOfBlobs { 31 | pub graph :Graph, 32 | pub roots :HashSet, 33 | } 34 | 35 | macro_rules! optry { 36 | ($e:expr) => { 37 | match $e { 38 | Some(d) => d, 39 | None => return None, 40 | } 41 | }; 42 | } 43 | 44 | impl GraphOfBlobs { 45 | pub fn from_func(acj :&AllCratesJson, 46 | mut get_digest_list :impl FnMut(&str, &Version) -> Option>) 47 | -> GraphOfBlobs { 48 | /// Strips the first component of a path 49 | fn strip_path<'a>(path :&'a str, name :&str, version :&Version) -> &'a str { 50 | let ver_display_len = format!("{}", version).len(); 51 | let prefix_len = name.len() + 2 + ver_display_len; 52 | &path[prefix_len..] 53 | } 54 | let mut graph = Graph::new(); 55 | let mut roots = HashSet::new(); 56 | let mut digest_to_node_id = HashMap::new(); 57 | for (_crate_name, crate_versions) in acj { 58 | let mut path_to_digests = HashMap::new(); 59 | let mut digest_to_version = HashMap::new(); 60 | let mut digest_lists = Vec::new(); 61 | for krate in crate_versions { 62 | let digest_list = get_digest_list(&krate.name, &krate.version); 63 | if let Some(digest_list) = digest_list { 64 | for (digest, path) in digest_list.iter() { 65 | // TODO find a way to store these long file names 66 | if path == "././@LongLink" { 67 | continue; 68 | } 69 | let path_stripped = strip_path(path, &krate.name, &krate.version) 70 | .to_owned(); 71 | let digests = path_to_digests.entry(path_stripped) 72 | .or_insert(HashSet::new()); 73 | digests.insert(*digest); 74 | digest_to_version.insert(*digest, krate.version.clone()); 75 | } 76 | digest_lists.push((krate, digest_list)); 77 | } 78 | } 79 | // Add the nodes 80 | for (_krate, digest_list) in digest_lists.iter() { 81 | for (digest, _path) in digest_list.iter() { 82 | match digest_to_node_id.entry(*digest) { 83 | Entry::Occupied(_) => (), 84 | Entry::Vacant(v) => { 85 | let id = graph.add_node(*digest); 86 | roots.insert(id); 87 | v.insert(id); 88 | }, 89 | } 90 | } 91 | } 92 | // Add the edges 93 | for (_path, digests) in path_to_digests.iter() { 94 | let mut ordered_digests = digests.iter().collect::>(); 95 | ordered_digests.sort_by_key(|digest| { 96 | digest_to_version.get(*digest).unwrap() 97 | }); 98 | let mut node_id_prior = None; 99 | for digest in ordered_digests { 100 | let node_id = *digest_to_node_id.get(digest).unwrap(); 101 | if let Some(prior) = node_id_prior { 102 | roots.remove(&node_id); 103 | graph.add_edge(prior, node_id, ()); 104 | } 105 | node_id_prior = Some(node_id); 106 | } 107 | } 108 | } 109 | GraphOfBlobs { 110 | graph, 111 | roots 112 | } 113 | } 114 | 115 | pub fn from_crate_source(acj :&AllCratesJson, src :&mut C) -> GraphOfBlobs { 116 | GraphOfBlobs::from_func(acj, |name :&str, version :&Version| { 117 | println!("name {} v {}", name, version); 118 | // TODO instead of obtaining the blobs, 119 | // extend the CrateSource trait or the CrateHandle trait 120 | // to include a way to obtain this directly. 121 | // Some format store the digests along the metadata. 122 | // TODO don't use unwrap here 123 | let mut handle = optry!(src.get_crate_handle_nv(name.to_string(), version.clone())); 124 | let file_list = handle.get_file_list(); 125 | Some(file_list.into_iter() 126 | .map(|path| { 127 | let file = handle.get_file(&path).unwrap(); 128 | let mut file_rdr = &*file; 129 | let mut hash_ctx = HashCtx::new(); 130 | io::copy(&mut file_rdr, &mut hash_ctx).unwrap(); 131 | let digest = hash_ctx.finish_and_get_digest(); 132 | (digest, path) 133 | }) 134 | .collect::>()) 135 | }) 136 | } 137 | 138 | pub fn from_blob_crate_storage(acj :&AllCratesJson, 139 | src :&mut BlobCrateStorage) -> GraphOfBlobs { 140 | GraphOfBlobs::from_func(acj, |name :&str, version :&Version| { 141 | //println!("name {} v {}", name, version); 142 | let s = CrateSpec { 143 | name : name.to_string(), 144 | version : version.clone(), 145 | }; 146 | // TODO treat LongLink 147 | let meta = optry!(src.get_crate_rec_meta(&s)); 148 | Some(meta.get_file_digest_list()) 149 | }) 150 | } 151 | 152 | } 153 | -------------------------------------------------------------------------------- /all-crate-storage/reconstruction.rs: -------------------------------------------------------------------------------- 1 | 2 | /*! 3 | reconstruction of .crate files 4 | 5 | In order to achieve gains from doing per-file deduplication and diffing, 6 | we need to be able to reconstruct the exact sha-256-hash matching .crate 7 | files. 8 | */ 9 | 10 | use super::hash_ctx::{Digest, HashCtx}; 11 | use flate2::{Compression, GzBuilder}; 12 | use flate2::read::GzDecoder; 13 | use tar::{Archive, Header, Builder as TarBuilder}; 14 | use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; 15 | use std::mem; 16 | use std::u64; 17 | use std::io; 18 | 19 | pub(crate) struct CrateRecMetadata { 20 | pub(crate) gz_file_name :Option>, 21 | pub(crate) gz_os :u8, 22 | pub(crate) entry_metadata :Vec<(Box<[u8; 512]>, Digest)>, 23 | } 24 | 25 | pub(crate) struct CrateRecMetaWithBlobs { 26 | pub(crate) meta :CrateRecMetadata, 27 | pub(crate) blobs :Vec<(Digest, Vec)>, 28 | } 29 | 30 | pub struct CrateContentBlobs { 31 | gz_file_name :Option>, 32 | gz_os :u8, 33 | entries :Vec<(Box<[u8; 512]>, Vec)>, 34 | } 35 | 36 | pub(crate) fn hdr_from_ptr(p :&[u8; 512]) -> &Header { 37 | unsafe { 38 | mem::transmute(p) 39 | } 40 | } 41 | 42 | impl CrateContentBlobs { 43 | /// Creates the CrateContentBlobs structure from a given .crate file 44 | pub fn from_archive_file(archive_rdr :R) -> io::Result { 45 | let gz_dec = GzDecoder::new(archive_rdr); 46 | let gz_file_name = gz_dec.header().unwrap() 47 | .filename().map(|v| v.to_vec()); 48 | let gz_os = gz_dec.header().unwrap().operating_system(); 49 | let mut archive = Archive::new(gz_dec); 50 | let mut entries = Vec::new(); 51 | for entry in archive.entries().unwrap().raw(true) { 52 | let mut entry = try!(entry); 53 | let hdr_box = Box::new(entry.header().as_bytes().clone()); 54 | let mut content = Vec::new(); 55 | try!(io::copy(&mut entry, &mut content)); 56 | entries.push((hdr_box, content)); 57 | } 58 | Ok(CrateContentBlobs { 59 | gz_file_name, 60 | gz_os, 61 | entries, 62 | }) 63 | } 64 | 65 | /// Reconstructs the .crate file from the CrateContentBlobs structure 66 | pub fn to_archive_file(&self) -> Vec { 67 | let mut res = Vec::new(); 68 | let gz_bld = GzBuilder::new() 69 | .operating_system(self.gz_os); 70 | let gz_bld = if let Some(filen) = self.gz_file_name.clone() { 71 | gz_bld.filename(filen) 72 | } else { 73 | gz_bld 74 | }; 75 | { 76 | let mut gz_enc = gz_bld.write(&mut res, Compression::best()); 77 | let mut bld = TarBuilder::new(&mut gz_enc); 78 | for entry in &self.entries { 79 | let hdr_buf = entry.0.clone(); 80 | let hdr = hdr_from_ptr(&hdr_buf); 81 | let content_sl :&[u8] = &entry.1; 82 | bld.append(&hdr, content_sl).unwrap(); 83 | } 84 | } 85 | res 86 | } 87 | 88 | /// Reconstructs the .crate file and obtains its digest 89 | pub fn digest_of_reconstructed(&self) -> Digest { 90 | let mut hash_ctx = HashCtx::new(); 91 | let reconstructed = self.to_archive_file(); 92 | io::copy(&mut reconstructed.as_slice(), &mut hash_ctx).unwrap(); 93 | hash_ctx.finish_and_get_digest() 94 | } 95 | 96 | pub(crate) fn into_meta_with_blobs(self) -> CrateRecMetaWithBlobs { 97 | let mut entry_metadata = Vec::new(); 98 | let mut blobs = Vec::new(); 99 | for entry in self.entries { 100 | let content = entry.1; 101 | let mut hash_ctx = HashCtx::new(); 102 | io::copy(&mut content.as_slice(), &mut hash_ctx).unwrap(); 103 | let digest = hash_ctx.finish_and_get_digest(); 104 | entry_metadata.push((entry.0, digest)); 105 | blobs.push((digest, content)); 106 | } 107 | CrateRecMetaWithBlobs { 108 | meta : CrateRecMetadata { 109 | gz_file_name : self.gz_file_name, 110 | gz_os : self.gz_os, 111 | entry_metadata, 112 | }, 113 | blobs, 114 | } 115 | } 116 | 117 | pub(crate) fn from_meta_with_blobs(m :CrateRecMetaWithBlobs) -> Self { 118 | let entries = m.meta.entry_metadata.into_iter() 119 | .zip(m.blobs.into_iter()) 120 | .map(|((h, _), (_, b))| (h, b)) 121 | .collect::>(); 122 | CrateContentBlobs { 123 | gz_file_name : m.meta.gz_file_name, 124 | gz_os : m.meta.gz_os, 125 | entries, 126 | } 127 | } 128 | } 129 | 130 | impl CrateRecMetadata { 131 | pub fn deserialize(mut rdr :R) -> io::Result { 132 | let gz_file_name_len = try!(rdr.read_u64::()); 133 | let gz_file_name = if gz_file_name_len == u64::MAX { 134 | None 135 | } else { 136 | let mut gfn = vec![0; gz_file_name_len as usize]; 137 | try!(rdr.read_exact(&mut gfn)); 138 | Some(gfn) 139 | }; 140 | let gz_os = try!(rdr.read_u8()); 141 | let entry_count = try!(rdr.read_u64::()) as usize; 142 | let mut entry_metadata = Vec::with_capacity(entry_count); 143 | for _ in 0 .. entry_count { 144 | let mut hdr = Box::new([0; 512]); 145 | { 146 | let hdr_ref :&mut [u8; 512] = &mut hdr; 147 | try!(rdr.read_exact(hdr_ref)); 148 | } 149 | let mut digest = [0; 32]; 150 | try!(rdr.read_exact(&mut digest)); 151 | entry_metadata.push((hdr, digest)); 152 | } 153 | Ok(CrateRecMetadata { 154 | gz_file_name, 155 | gz_os, 156 | entry_metadata, 157 | }) 158 | } 159 | pub fn serialize(&self, mut wtr :W) -> io::Result<()> { 160 | if let Some(ref name) = self.gz_file_name { 161 | try!(wtr.write_u64::(name.len() as u64)); 162 | try!(wtr.write(&name)); 163 | } else { 164 | try!(wtr.write_u64::(u64::MAX)); 165 | } 166 | try!(wtr.write_u8(self.gz_os)); 167 | try!(wtr.write_u64::(self.entry_metadata.len() as u64)); 168 | for entry in self.entry_metadata.iter() { 169 | let hdr_ref :&[u8; 512] = &entry.0; 170 | try!(wtr.write(hdr_ref)); 171 | try!(wtr.write(&entry.1)); 172 | } 173 | Ok(()) 174 | } 175 | pub fn get_file_list(&self) -> Vec { 176 | self.entry_metadata.iter() 177 | .map(|&(ref h, _)| { 178 | let hdr = hdr_from_ptr(h); 179 | let path = hdr.path().unwrap(); 180 | let s :String = path.to_str().unwrap().to_owned(); 181 | s 182 | }) 183 | .collect::>() 184 | } 185 | pub(crate) fn get_file_digest_list(&self) -> Vec<(Digest, String)> { 186 | self.entry_metadata.iter() 187 | .map(|&(ref h, d)| { 188 | let hdr = hdr_from_ptr(h); 189 | let path = hdr.path().unwrap(); 190 | let s :String = path.to_str().unwrap().to_owned(); 191 | (d, s) 192 | }) 193 | .collect::>() 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /all-crate-storage/registry/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod registry; 2 | pub mod statistics; 3 | -------------------------------------------------------------------------------- /all-crate-storage/registry/registry.rs: -------------------------------------------------------------------------------- 1 | use std::{io, env}; 2 | use std::io::BufRead; 3 | use std::path::{Path, PathBuf}; 4 | use semver::VersionReq; 5 | use serde_json::from_str; 6 | use serde::de::{Deserialize, Deserializer}; 7 | use failure::{Context, ResultExt}; 8 | 9 | use semver::Version; 10 | use git2::{self, Repository}; 11 | use super::super::crate_storage::CacheStorage; 12 | 13 | #[derive(Serialize, Debug)] 14 | pub struct Dependency { 15 | name :String, 16 | req :String, 17 | optional :bool, 18 | } 19 | 20 | #[derive(Deserialize, PartialEq, Eq, Hash, Debug, Clone, Copy)] 21 | #[serde(rename_all = "lowercase")] 22 | pub enum DependencyKind { 23 | Normal, 24 | Build, 25 | Dev, 26 | } 27 | 28 | // custom function needed due to https://github.com/serde-rs/serde/issues/1098 29 | // as default + rename_all = "lowercase" does not cover the kind: null case :/ 30 | fn nullable_dep_kind<'de, D :Deserializer<'de>>(deserializer :D) 31 | -> Result { 32 | let opt = try!(Option::deserialize(deserializer)); 33 | Ok(opt.unwrap_or(DependencyKind::Normal)) 34 | } 35 | 36 | fn normal_dep_kind() -> DependencyKind { 37 | DependencyKind::Normal 38 | } 39 | 40 | // TODO tests for dependency kind set to null or non existent. 41 | 42 | #[derive(Deserialize, Clone)] 43 | pub struct CrateDepJson { 44 | pub name :String, 45 | pub features :Vec, 46 | pub default_features :bool, 47 | pub target :Option, 48 | pub req :VersionReq, 49 | pub optional :bool, 50 | // We need to set a default as kind may not always be != null, 51 | // or it may not be existent. 52 | // https://github.com/rust-lang/crates.io/issues/1168 53 | #[serde(default = "normal_dep_kind", deserialize_with = "nullable_dep_kind")] 54 | pub kind :DependencyKind, 55 | } 56 | 57 | impl CrateDepJson { 58 | pub fn to_crate_dep(&self) -> Dependency { 59 | Dependency { 60 | name : self.name.clone(), 61 | req : self.req.to_string(), 62 | optional : self.optional, 63 | } 64 | } 65 | } 66 | 67 | #[derive(Deserialize, Clone)] 68 | pub struct CrateIndexJson { 69 | pub name :String, 70 | #[serde(rename = "vers")] 71 | pub version :Version, 72 | #[serde(rename = "deps")] 73 | pub dependencies :Vec, 74 | #[serde(rename = "cksum")] 75 | pub checksum :String, 76 | // TODO features 77 | pub yanked :bool, 78 | } 79 | 80 | pub struct Registry { 81 | cache_path :PathBuf, 82 | index_path :PathBuf, 83 | } 84 | 85 | pub fn obtain_crate_name_path(name :&str) -> String { 86 | match name.len() { 87 | 1 => format!("1/{}", name), 88 | 2 => format!("2/{}", name), 89 | 3 => format!("3/{}/{}", &name[..1], name), 90 | _ => format!("{}/{}/{}", &name[..2], &name[2..4], name), 91 | } 92 | } 93 | 94 | fn buf_to_index_json(buf :&[u8]) -> io::Result> { 95 | let mut r = Vec::new(); 96 | for l in buf.lines() { 97 | let l = try!(l); 98 | r.push(try!(from_str(&l))); 99 | } 100 | Ok(r) 101 | } 102 | 103 | pub type AllCratesJson = Vec<(String, Vec)>; 104 | 105 | #[derive(Copy, Clone, Eq, PartialEq, Debug, Fail)] 106 | pub enum RegistryErrorKind { 107 | #[fail(display = "Opening Registry failed")] 108 | RegOpen, 109 | #[fail(display = "Index reading failed")] 110 | IndexRepoReading, 111 | #[fail(display = "Index JSON reading failed")] 112 | IndexJsonReading, 113 | #[fail(display = "Index JSON file not found")] 114 | IndexJsonMissing, 115 | } 116 | 117 | pub type RegistryError = Context; 118 | 119 | fn get_repo_head_tree<'a>(repo :&'a Repository) 120 | -> Result, git2::Error> { 121 | let head_id = try!(repo.refname_to_id("refs/remotes/origin/master")); 122 | let head_commit = try!(repo.find_commit(head_id)); 123 | let head_tree = try!(head_commit.tree()); 124 | Ok(head_tree) 125 | } 126 | 127 | impl Registry { 128 | pub fn from_name(name :&str) -> Result { 129 | // The name is the name + hash pair. 130 | // For crates.io it is "github.com-1ecc6299db9ec823" 131 | let home = try!(env::var("HOME")); 132 | let base_path = Path::new(&home).join(".cargo/registry/"); 133 | let cache_path = base_path.join("cache").join(name); 134 | //let cache_path = env::current_dir().unwrap().join("crate-archives"); 135 | let index_path = base_path.join("index").join(name); 136 | Ok(Registry { 137 | cache_path, 138 | index_path, 139 | }) 140 | } 141 | pub fn get_crate_json(&self, crate_name :&str) 142 | -> Result, RegistryError> { 143 | use self::RegistryErrorKind::*; 144 | 145 | let repo = try!(git2::Repository::open(&self.index_path).context(RegOpen)); 146 | let head_tree = try!(get_repo_head_tree(&repo).context(IndexRepoReading)); 147 | 148 | let path_str = obtain_crate_name_path(crate_name); 149 | let entry = try!(head_tree.get_path(&Path::new(&path_str)) 150 | .with_context(|e :&git2::Error| { 151 | if e.code() == git2::ErrorCode::NotFound { 152 | IndexJsonMissing 153 | } else { 154 | IndexJsonReading 155 | } 156 | })); 157 | let obj = try!(entry.to_object(&repo).context(IndexRepoReading)); 158 | let bytes :&[u8] = match obj.as_blob() { 159 | Some(b) => b.content(), 160 | None => try!(Err(IndexRepoReading)), 161 | }; 162 | let json = try!(buf_to_index_json(bytes).context(IndexJsonReading)); 163 | Ok(json) 164 | } 165 | pub fn get_all_crates_json(&self) -> 166 | Result { 167 | use self::RegistryErrorKind::*; 168 | 169 | let repo = try!(git2::Repository::open(&self.index_path).context(RegOpen)); 170 | let head_tree = try!(get_repo_head_tree(&repo).context(IndexRepoReading)); 171 | 172 | fn walk Result<(), RegistryError>>( 173 | t :&git2::Tree, repo :&git2::Repository, 174 | d :bool, f :&mut F) -> Result<(), RegistryError> { 175 | for entry in t.iter() { 176 | let entry_obj = try!(entry.to_object(&repo) 177 | .context(IndexRepoReading)); 178 | if let Some(tree) = entry_obj.as_tree() { 179 | try!(walk(tree, repo, false, f)); 180 | } else if let Some(blob) = entry_obj.as_blob() { 181 | if !d { 182 | let name = match entry.name() { 183 | Some(v) => v, 184 | None => try!(Err(IndexRepoReading)), 185 | }; 186 | try!(f(name, blob.content())); 187 | } 188 | } 189 | } 190 | Ok(()) 191 | } 192 | let mut res = Vec::new(); 193 | try!(walk(&head_tree, &repo, true, &mut |name, blob| { 194 | let json = try!(buf_to_index_json(blob).context(IndexJsonReading)); 195 | let name = if let Some(v) = json.iter().next() { 196 | // This is important as the file name is always in lowercase, 197 | // but the actual name of the crate may have mixed casing. 198 | v.name.to_owned() 199 | } else { 200 | name.to_owned() 201 | }; 202 | res.push((name, json)); 203 | Ok(()) 204 | })); 205 | Ok(res) 206 | } 207 | pub fn get_cache_storage(&self) -> CacheStorage { 208 | CacheStorage::new(&self.cache_path) 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /all-crate-storage/registry/statistics.rs: -------------------------------------------------------------------------------- 1 | use super::registry::AllCratesJson; 2 | use string_interner::StringInterner; 3 | use semver::{Version, VersionReq}; 4 | use std::collections::{HashMap, HashSet}; 5 | 6 | type CrateName = usize; 7 | 8 | pub struct CrateStats { 9 | pub crate_names_interner :StringInterner, 10 | /// Mapping a crate to its latest version 11 | pub latest_crate_versions :HashMap, 12 | /// Mapping a crate to its reverse dependencies 13 | pub reverse_dependencies :HashMap>>, 14 | /// The list of crates ordered by the number of crates directly depending on them. 15 | /// 16 | /// The algorithm doesn't count any reverse dependency where only 17 | /// a past version depended on a crate, but not the latest one. 18 | pub most_directly_depended_on :Vec<(CrateName, usize)>, 19 | /// The list of crates ordered by the number of versions they have. 20 | pub most_versions: Vec<(CrateName, usize)>, 21 | } 22 | 23 | pub fn compute_crate_statistics(acj :&AllCratesJson) -> CrateStats { 24 | let mut names_interner = StringInterner::new(); 25 | 26 | let mut latest_crate_versions = HashMap::new(); 27 | for &(ref name, ref cjv) in acj.iter() { 28 | let name_i = names_interner.get_or_intern(name.clone()); 29 | if let Some(newest_krate) = cjv.iter().max_by_key(|krate| &krate.version) { 30 | latest_crate_versions.insert(name_i, newest_krate.version.clone()); 31 | } 32 | } 33 | 34 | let mut revd = HashMap::new(); 35 | let mut ddon = HashMap::>::new(); 36 | for &(ref name, ref cjv) in acj.iter() { 37 | let name_i = names_interner.get_or_intern(name.clone()); 38 | let latest_version = latest_crate_versions.get(&name_i).unwrap(); 39 | for krate in cjv.iter() { 40 | for dep in krate.dependencies.iter() { 41 | let dname_i = names_interner.get_or_intern(dep.name.clone()); 42 | let e = revd.entry(dname_i).or_insert(HashMap::new()); 43 | let s = e.entry(dep.req.clone()).or_insert(HashSet::new()); 44 | s.insert((name_i, krate.version.clone())); 45 | if &krate.version == latest_version { 46 | let s = ddon.entry(dname_i).or_insert(HashSet::new()); 47 | s.insert(name_i); 48 | } 49 | } 50 | } 51 | } 52 | 53 | let mut most_directly_depended_on = ddon.into_iter() 54 | .map(|(n, s)| (n, s.len())) 55 | .collect::>(); 56 | most_directly_depended_on.sort_by_key(|v| v.1); 57 | 58 | let mut most_versions = acj.iter() 59 | .map(|&(ref n, ref v)| { 60 | let ni = names_interner.get_or_intern(n.clone()); 61 | (ni, v.len()) 62 | }) 63 | .collect::>(); 64 | most_versions.sort_by_key(|v| v.1); 65 | 66 | CrateStats { 67 | crate_names_interner : names_interner, 68 | reverse_dependencies : revd, 69 | latest_crate_versions, 70 | most_directly_depended_on, 71 | most_versions, 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /cargo-local-serve/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cargo-local-serve" 3 | version = "0.1.0" 4 | license = "MIT/Apache-2.0" 5 | authors = ["est31 "] 6 | edition = "2015" 7 | 8 | [[bin]] 9 | name = "cargo-local-serve" 10 | path = "main.rs" 11 | 12 | [dependencies] 13 | 14 | all-crate-storage = { path = "../all-crate-storage" } 15 | 16 | try = "1.0.0" 17 | 18 | #iron related 19 | handlebars-iron = "0.28" 20 | iron = "0.6.0" 21 | staticfile = { version = "0.5", features = ["cache"] } 22 | urlencoded = "0.6" 23 | mount = "0.4" 24 | hyper = "0.10" 25 | 26 | # markdown rendering 27 | pulldown-cmark = { version = "0.8.0", default-features = false } 28 | ammonia = "3.0.0" 29 | syntect = "4.0" 30 | 31 | # all the other stuff 32 | toml = "0.5" 33 | serde = "1.0.0" 34 | serde_json = "1.0.0" 35 | serde_derive = "1.0.0" 36 | env_logger = "0.7" 37 | flate2 = "1.0" 38 | semver = { version = "0.11", features = ["serde"] } 39 | lazy_static = "1.0" 40 | failure = "0.1.0" 41 | -------------------------------------------------------------------------------- /cargo-local-serve/code_format.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{self, Write}; 2 | use syntect::html::IncludeBackground; 3 | use syntect::parsing::{SyntaxReference, SyntaxSet}; 4 | use syntect::easy::HighlightLines; 5 | use syntect::highlighting::{Theme, Style, FontStyle, Color}; 6 | use escape::Escape; 7 | 8 | pub fn highlight_string_snippet(s :&str, syntax :&SyntaxReference, theme :&Theme, syns :&SyntaxSet) 9 | -> String { 10 | let mut output = String::new(); 11 | let mut highlighter = HighlightLines::new(syntax, theme); 12 | let c = theme.settings.background.unwrap_or(Color::WHITE); 13 | write!(output, 14 | "
\n",
 15 | 		c.r,
 16 | 		c.g,
 17 | 		c.b).unwrap();
 18 | 	let mut spcx = StyledPrintCx::new(IncludeBackground::IfDifferent(c));
 19 | 	for line in s.lines() {
 20 | 		let regions = highlighter.highlight(line, syns);
 21 | 		spcx.styles_to_coloured_html(&mut output, ®ions[..]);
 22 | 		output.push('\n');
 23 | 	}
 24 | 	spcx.finish(&mut output);
 25 | 	output.push_str("
\n"); 26 | output 27 | } 28 | 29 | struct SpanBegin<'a>(&'a Style, &'a IncludeBackground); 30 | 31 | impl<'a> fmt::Display for SpanBegin<'a> { 32 | fn fmt(&self, fmt :&mut fmt::Formatter) -> fmt::Result { 33 | let style = self.0; 34 | let bg = self.1; 35 | 36 | try!(write!(fmt, " true, 39 | &IncludeBackground::No => false, 40 | &IncludeBackground::IfDifferent(c) => (style.background != c), 41 | }; 42 | if include_bg { 43 | try!(write!(fmt, "background-color:")); 44 | try!(write_css_color(fmt, style.background)); 45 | try!(write!(fmt, ";")); 46 | } 47 | if style.font_style.contains(FontStyle::UNDERLINE) { 48 | try!(write!(fmt, "text-decoration:underline;")); 49 | } 50 | if style.font_style.contains(FontStyle::BOLD) { 51 | try!(write!(fmt, "font-weight:bold;")); 52 | } 53 | if style.font_style.contains(FontStyle::ITALIC) { 54 | try!(write!(fmt, "font-style:italic;")); 55 | } 56 | try!(write!(fmt, "color:")); 57 | try!(write_css_color(fmt, style.foreground)); 58 | try!(write!(fmt, ";\">")); 59 | 60 | Ok(()) 61 | } 62 | } 63 | 64 | struct StyledPrintCx { 65 | background :IncludeBackground, 66 | prev_style :Option 9 | 11 | 13 | 15 | 17 | 18 | -------------------------------------------------------------------------------- /cargo-local-serve/site/static/style.css: -------------------------------------------------------------------------------- 1 | * { 2 | box-sizing: border-box; 3 | } 4 | 5 | html { 6 | background:radial-gradient(rgba(255,255,255,.1) 10%, transparent 20%) 0 0px, 7 | radial-gradient(rgba(255,255,255,.1) 10%, transparent 20%) 8px 8px; 8 | background-size:16px 16px; 9 | background-color:#3b6837; 10 | } 11 | 12 | body { 13 | font-family: "Helvetica Neue",Helvetica,Helvetica,Arial,sans-serif; 14 | font-size: 16px; 15 | display: flex; 16 | flex-direction: column; 17 | align-items: center; 18 | } 19 | 20 | body, html { 21 | margin: 0; 22 | } 23 | 24 | h1 { 25 | font-size: 2em; 26 | margin: .67em 0; 27 | } 28 | 29 | a { 30 | text-decoration: none; 31 | color: #00ac5b; 32 | } 33 | 34 | a:hover { 35 | color: #007940; 36 | } 37 | 38 | #view { 39 | width: 960px; 40 | color: #383838; 41 | } 42 | 43 | #crates-heading { 44 | background-color: #edebdd; 45 | padding: 20px; 46 | display: flex; 47 | flex-wrap: wrap; 48 | flex-direction: row; 49 | align-items: baseline; 50 | margin-bottom: 20px; 51 | } 52 | 53 | #crates-heading h2 { 54 | color: #858585; 55 | padding-left: 10px; 56 | } 57 | 58 | .wide { 59 | width: 100%; 60 | display: flex; 61 | align-items: baseline; 62 | flex-direction: row; 63 | } 64 | 65 | .wide * { 66 | width: initial; 67 | } 68 | 69 | .crate-links { 70 | font-size: 80%; 71 | display: flex; 72 | flex-direction: row; 73 | padding: 0; 74 | list-style-type: none; 75 | margin: 1em 0 0; 76 | } 77 | 78 | .crate-links li { 79 | margin-right: 1em; 80 | } 81 | 82 | .header { 83 | color: #fff; 84 | align-items: center; 85 | height: 100px; 86 | display: flex; 87 | } 88 | 89 | .header a:hover { 90 | color: #d9d9d9; 91 | } 92 | 93 | .header a { 94 | color: #fff; 95 | } 96 | 97 | .subtitle { 98 | display: block; 99 | font-size: x-small; 100 | } 101 | 102 | #header form.search { 103 | display: flex; 104 | flex-grow: 1; 105 | } 106 | 107 | #header input.search { 108 | width: 100%; 109 | 110 | font-size: 90%; 111 | padding: 5px 5px 5px 25px; 112 | 113 | color: #000; 114 | background-color: #fff; 115 | 116 | border: none; 117 | 118 | margin-left: 16px; 119 | margin-right: 16px; 120 | } 121 | 122 | #header .sep { 123 | margin: 0 10px; 124 | color: #284725; 125 | } 126 | 127 | .content { 128 | border: 5px solid #62865f; 129 | background-color: #f9f7ec; 130 | padding: 15px; 131 | } 132 | 133 | .install { 134 | background-color: #dfdbc2; 135 | padding: 10px; 136 | font-size: 120%; 137 | display: flex; 138 | padding-right: 10px; 139 | } 140 | 141 | .install .action { 142 | flex: 0; 143 | align-self: center; 144 | padding-right: 10px; 145 | } 146 | 147 | .install code { 148 | color: #fff; 149 | flex: 8; 150 | background: #383838; 151 | padding: 20px; 152 | 153 | } 154 | 155 | .copy-btn { 156 | border: none; 157 | width: 60px; 158 | cursor: pointer; 159 | } 160 | 161 | .copy-btn:hover { 162 | background: #edebdd; 163 | 164 | } 165 | 166 | .crate-info { 167 | display: flex; 168 | flex-direction: row; 169 | } 170 | 171 | .docs { 172 | flex: 7; 173 | padding-right: 40px; 174 | max-width: 640px; 175 | } 176 | 177 | .docs pre, .docs code, .file-content pre, .file-content code { 178 | font-family: Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace; 179 | } 180 | 181 | .docs pre, .file-content pre { 182 | color: #fff; 183 | border-radius: .5em; 184 | border: .3em solid #545454; 185 | background: #2b303b; 186 | margin: .5em 0; 187 | overflow: auto; 188 | padding: 1em; 189 | } 190 | 191 | .authorship { 192 | flex: 3; 193 | padding-left: 20px; 194 | border-left: 2px solid #d5d3cb; 195 | } 196 | 197 | .date { 198 | font-weight: 700; 199 | } 200 | 201 | span.small { 202 | font-size: 80%; 203 | } 204 | .small a { 205 | color: #858585; 206 | text-decoration: underline; 207 | } 208 | .small a:hover { 209 | color: #6b6b6b; 210 | } 211 | 212 | .error-display { 213 | font-weight: 700; 214 | font-size: 120%; 215 | background-color: #ffd5d5; 216 | border: 2px solid #e48888; 217 | text-align: center; 218 | margin: 10px 0 10px; 219 | padding: 10px; 220 | border-radius: 5px; 221 | } 222 | 223 | .optional { 224 | font-size: 80%; 225 | } 226 | 227 | .crate-lists { 228 | display: flex; 229 | flex-wrap: wrap; 230 | justify-content: left; 231 | } 232 | 233 | .crate-lists ul { 234 | list-style: none; 235 | padding: 0; 236 | } 237 | 238 | .crate-lists div { 239 | margin: 0; 240 | padding: 0 15px; 241 | width: 33.33%; 242 | } 243 | 244 | .crate-lists h2 { 245 | font-size: 105%; 246 | } 247 | 248 | .crate-lists li { 249 | margin: 8px 0; 250 | } 251 | 252 | .crate-lists li a:hover { 253 | background-color: #e4e1cc; 254 | } 255 | 256 | .crate-lists li a { 257 | width: 100%; 258 | color: #525252; 259 | background-color: #edebdd; 260 | padding: 20px 10px; 261 | font-size: 90%; 262 | display: flex; 263 | } 264 | 265 | .title-header { 266 | border-bottom: 5px solid #d5d3cb; 267 | padding-bottom: 40px; 268 | text-align: center; 269 | } 270 | 271 | .title-header h1 { 272 | font-size: 50px; 273 | } 274 | -------------------------------------------------------------------------------- /cargo-local-serve/site/templates/crate.hbs: -------------------------------------------------------------------------------- 1 | {{#*inline "head-block" }} 2 | {{c.name}} - cargo-local-serve: packages for Rust 3 | 4 | {{/inline}} 5 | {{#> frame}} 6 |
7 |
8 |

{{c.name}}

9 |

{{c.version}}

10 |
11 | 25 |
26 |
27 |
28 |
29 |
Cargo.toml
30 | {{c.name}} = "{{c.version}}" 31 | 34 |
35 | {{#if c.de.readme_html}} 36 |
{{{c.de.readme_html}}}
37 | {{else}} 38 | {{#if c.de.description}} 39 |

About this Package

40 |

{{c.de.description}}

41 | {{/if}} 42 | {{#if c.err_msg}} 43 |
44 |

Error

45 |

{{c.err_msg}}

46 |
47 | {{/if}} 48 | {{/if}} 49 |
50 |
51 |
52 |

Authors

53 |
    54 | {{#each c.de.authors}} 55 | {{#if email}} 56 |
  • {{name}}
  • 57 | {{else}} 58 |
  • {{name}}
  • 59 | {{/if}} 60 | {{/each}} 61 |
62 |
63 | {{#if c.de.license}} 64 |
65 |

License

66 |

67 | {{c.de.license}} 68 |

69 |
70 | {{/if}} 71 |
72 |

Versions

73 |
    74 | {{#each c.versions}} 75 |
  • 76 | {{v}} 77 | {{date}} 78 |
  • 79 | {{/each}} 80 |
81 | {{#if c.versions_limited}} 82 | 83 | Show all {{c.versions_limited}} versions 84 | 85 | {{/if}} 86 |
87 |
88 |

Dependencies

89 |
    90 | {{#each c.dependencies}} 91 |
  • {{name}} {{req}} 92 | {{#if optional}} 93 | optional 94 | {{/if}} 95 |
  • 96 | {{else}} 97 |
  • None
  • 98 | {{/each}} 99 |
100 |
101 | {{#if c.dev_dependencies}} 102 |
103 |

Dev-Dependencies

104 |
    105 | {{#each c.dev_dependencies}} 106 |
  • {{name}} {{req}}
  • 107 | {{/each}} 108 |
109 |
110 | {{/if}} 111 |
112 |
113 | {{/frame}} 114 | -------------------------------------------------------------------------------- /cargo-local-serve/site/templates/error.hbs: -------------------------------------------------------------------------------- 1 | {{#*inline "head-block" }} 2 | Error: cargo-local-serve: packages for Rust 3 | {{/inline}} 4 | {{#> frame}} 5 |

6 | {{error}} 7 |

8 | {{/frame}} 9 | -------------------------------------------------------------------------------- /cargo-local-serve/site/templates/file-content.hbs: -------------------------------------------------------------------------------- 1 | {{#*inline "head-block" }} 2 | cargo-local-serve: packages for Rust 3 | {{/inline}} 4 | {{#> frame}} 5 |
6 |

File content

of {{c.file_path}}

7 |
8 | 9 |
10 | {{{c.content_html}}} 11 |
12 | {{/frame}} 13 | -------------------------------------------------------------------------------- /cargo-local-serve/site/templates/file-listing.hbs: -------------------------------------------------------------------------------- 1 | {{#*inline "head-block" }} 2 | cargo-local-serve: packages for Rust 3 | {{/inline}} 4 | {{#> frame}} 5 |
6 |

File listing

for '{{c.name}}'

7 |
8 | 9 | Displaying {{c.file_count}} children: 10 |
    11 | {{#each c.files}} 12 |
  • {{name}}
  • 13 | {{/each}} 14 | 15 | {{/frame}} 16 | -------------------------------------------------------------------------------- /cargo-local-serve/site/templates/frame.hbs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | {{> head-block}} 12 | 13 | 14 |
    15 | 34 |
    35 | {{> @partial-block}} 36 |
    37 |
    38 | 39 | 40 | -------------------------------------------------------------------------------- /cargo-local-serve/site/templates/index.hbs: -------------------------------------------------------------------------------- 1 | {{#*inline "head-block" }} 2 | cargo-local-serve: packages for Rust 3 | {{/inline}} 4 | {{#> frame}} 5 |
    6 |

    Local crate registry

    7 |
    8 |
    9 |
    10 |

    Most direct reverse deps

    11 | 18 |
    19 |
    20 |

    Most transitive reverse deps

    21 | 28 |
    29 |
    30 |

    Most versions

    31 | 38 |
    39 |
    40 | {{/frame}} 41 | -------------------------------------------------------------------------------- /cargo-local-serve/site/templates/reverse_dependencies.hbs: -------------------------------------------------------------------------------- 1 | {{#*inline "head-block" }} 2 | {{c.name}} - cargo-local-serve: packages for Rust 3 | {{/inline}} 4 | {{#> frame}} 5 | {{#if c.refferer}} 6 | 7 | {{/if}} 8 | All {{c.rev_d_len}} reverse dependencies of {{c.name}} 9 |
      10 | {{#each c.rev_d}} 11 |
    • {{name}} version {{version}} needs {{req}}
    • 12 | {{/each}} 13 | 14 | {{/frame}} 15 | -------------------------------------------------------------------------------- /cargo-local-serve/site/templates/search.hbs: -------------------------------------------------------------------------------- 1 | {{#*inline "head-block" }} 2 | Search results for {{c.search_term}} - cargo-local-serve: packages for Rust 3 | {{/inline}} 4 | {{#> frame}} 5 |
      6 |

      Search results

      for '{{c.search_term}}'

      7 |
      8 | Displaying {{c.results_length}} results: 9 |
        10 | {{#each c.results}} 11 |
      • {{name}}
      • 12 | {{/each}} 13 | 14 | {{/frame}} 15 | 16 | -------------------------------------------------------------------------------- /cargo-local-serve/site/templates/versions.hbs: -------------------------------------------------------------------------------- 1 | {{#*inline "head-block" }} 2 | {{c.name}} - cargo-local-serve: packages for Rust 3 | {{/inline}} 4 | {{#> frame}} 5 | {{#if c.refferer}} 6 | 7 | {{/if}} 8 | All {{c.versions_length}} versions of {{c.name}} : 9 |
          10 | {{#each c.versions}} 11 |
        • {{v}}
        • 12 | {{/each}} 13 | 14 | {{/frame}} 15 | -------------------------------------------------------------------------------- /cargo-local-serve/syntect_format.rs: -------------------------------------------------------------------------------- 1 | use code_format::highlight_string_snippet; 2 | use syntect::parsing::SyntaxSet; 3 | use syntect::highlighting::ThemeSet; 4 | 5 | lazy_static! { 6 | static ref THEME_SET :ThemeSet = ThemeSet::load_defaults(); 7 | } 8 | 9 | pub struct SyntectFormatter<'a> { 10 | token :Option<&'a str>, 11 | extension :Option<&'a str>, 12 | } 13 | 14 | impl<'a> SyntectFormatter<'a> { 15 | pub fn new() -> Self { 16 | SyntectFormatter { 17 | token : None, 18 | extension : None, 19 | } 20 | } 21 | pub fn token(mut self, token :&'a str) -> Self { 22 | self.token = Some(token); 23 | self 24 | } 25 | pub fn extension(mut self, extension :&'a str) -> Self { 26 | self.extension = Some(extension); 27 | self 28 | } 29 | // Note: this is NOT ESCAPED!! 30 | // Do ammonia to sanitize this first!!!! 31 | pub fn highlight_snippet(&self, snippet :&str) -> String { 32 | thread_local!(static SYN_SET :SyntaxSet = SyntaxSet::load_defaults_newlines()); 33 | 34 | let theme = &THEME_SET.themes["base16-ocean.dark"]; 35 | 36 | return SYN_SET.with(|s| { 37 | let mut syntax = self.token.and_then(|tok| s.find_syntax_by_token(tok)); 38 | syntax = syntax.or_else(|| self.extension.and_then(|ext| s.find_syntax_by_extension(ext))); 39 | if let Some(syntax) = syntax { 40 | // TODO find a way to avoid inline css in the syntect formatter 41 | let formatted = highlight_string_snippet(snippet, 42 | &syntax, theme, s); 43 | return formatted; 44 | } else { 45 | let code_block = format!("
          {}
          ", 46 | snippet); 47 | return code_block; 48 | } 49 | }); 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /config.toml.example: -------------------------------------------------------------------------------- 1 | #site_dir = "site" 2 | #listen_host = "localhost" 3 | #listen_port = 3000 4 | 5 | #[source] 6 | #kind = "Cache" 7 | 8 | #[source] 9 | #kind = "ArchiveTree" 10 | #path = "/path/to/ArchiveTree" 11 | 12 | #[source] 13 | #kind = "StorageFile" 14 | #path = "/path/to/StorageFile" 15 | --------------------------------------------------------------------------------