├── .gitignore ├── LICENSE ├── README.md ├── bin └── publish.sh ├── examples └── npm-install │ └── instaclone.yml ├── images └── clone-140.jpg ├── instaclone ├── __init__.py ├── archives.py ├── configs.py ├── instaclone.py ├── log_calls.py └── main.py ├── setup.py └── tests ├── .gitignore ├── run.sh ├── tests.sh └── work-dir ├── instaclone.yml ├── test-dir ├── file-a ├── file-b ├── subdir │ ├── file-c │ └── symlink-file-b ├── symlink-file-a └── symlink-symlink-file-a ├── test-file1 ├── test-file2 └── test-file2-hashable /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *.cover 45 | *.log 46 | 47 | # Translations 48 | *.mo 49 | *.pot 50 | 51 | # Sphinx documentation 52 | docs/_build/ 53 | 54 | # PyBuilder 55 | target/ 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Instaclone 2 | 3 | [![Boink](images/clone-140.jpg)](http://www.gocomics.com/calvinandhobbes/1990/01/10) 4 | 5 | Instaclone is a simple, configurable command-line tool to publish and later install snapshots of files or directories in S3 (or another store). 6 | It keeps a local cache of downloaded snapshots so switching between previously cached snapshots is almost instant -- just a symlink or local copy from the cache. 7 | 8 | It works nicely when you might want to save things in Git, but can't, due to files or directories being large or sensitive, or because you have multiple variations of files for one Git revision (for example, Mac and Linux). 9 | You can git-ignore the original files, publish them with Instaclone, and instead check in the Instaclone configuration file that references them. 10 | 11 | Note that if all you want is to do is put big files in Git, [LFS](https://git-lfs.github.com/) may be what you want. 12 | Instaclone is more flexible about backend storage and versioning schemes, and offers a local cache. 13 | 14 | ## Basic idea 15 | 16 | Every item (a file or directory) can be published as an immutable snapshot. 17 | A snapshot has a local path name, a published location (such as an S3 prefix), and a _version string_. 18 | You can assign a version string yourself and reference it directly, or -- and this is where it's more useful -- assign it implicitly from other sources, such as the hash of another file, the platform, or the output of an arbitrary command. 19 | The snapshot is then published with that version string. 20 | 21 | Another client can then install that snapshot whenever it requires the same version of the item. 22 | Installing the first time on a new client requires a download. 23 | Subsequent installs use the local cache. 24 | 25 | ## Exact, cached node_modules snapshots 26 | 27 | This tool isn't only for use with Node, but this is a good motivating use case. 28 | 29 | If you `instaclone publish` after you `npm install` and `npm shrinkwrap`, you can switch back and forth between Git branches and run `instaclone install` instantly instead of `npm install` and waiting around minutes for npm to download, copy dependencies, etc. 30 | Your colleagues can do this too -- after you publish, they can run `instaclone install` and get a byte-for-byte exact copy of your `node_modules` on their machines, more quickly and reliably than if they had done the `npm install` themselves. 31 | Finally, your CI builds will speed up most of the time -- possibly by a lot! 32 | 33 | [See below](#why-you-should-instaclone-node_modules) for more info on this. 34 | 35 | ## Features 36 | 37 | - **Scales to large directories.** Works with large directories containing many (100,000+) files. Uses rsync to make file copying and deletion very fast. 38 | - **Configurable storage.** Upload/download is via configurable shell commands, using whatever backing storage system desired, so you don't have to worry about configuring credentials just for this tool, and can publish to S3 or elsewhere. 39 | - **High bandwidth upload/download.** While not a feature of Instaclone, I recommend using [`s4cmd`](https://github.com/bloomreach/s4cmd) for high-performance multi-connection access to S3. 40 | - **Configurable versioning.** Version strings can be explicit or specified indirectly: 41 | - Explicit (you just say what version to use in the config file); 42 | - SHA1 of a file (you say another file that is hashed to get a unique string); or 43 | - Command (you have Instaclone execute an arbitrary command, like `uname`, which means you automatically publish different versions per platform) 44 | - **Good hygiene.** All files, directories, and archives are created atomically, so that interruptions exceptions never leave files in a partially complete state. 45 | - **Read-only or writeable installs.** You can install items as symlinks to the read-only cache (usually what you want), or fully copy all the files (in case you want to modify them). In the latter case, we use rsync for faster copying and to speed up repeat installs of large directories that haven't changed a lot in content. 46 | - **Simple internals.** The format for the cache and published storage is dead simple. 47 | - The files are uploaded under unique paths with the version string as a suffix. 48 | - Files are cached locallyin `~/.instaclone`, but you can set the `INSTACLONE_DIR` environment variable to set this directory to something else. 49 | - The file cache just merges the published paths, so is just a file tree that you can look at. (Currently, clean-up is not automated, but you can delete it any time.) 50 | - **Symlink details.** Symlink installs and directories containing symlinks work pretty well: 51 | - The file permissions on items in the cache is read-only, so that if you inadvertently try to modify the contents of the cache by following the symlink and changing a file, it will fail. 52 | - The target of the symlink (in the cache) has the same name as the source, so installed symlinks will play nice paths like `../target/foo` (where `target` is the symlink). 53 | - Internally within an archive, relative symlinks are preserved. But instaclone is smart enough to check for and abort if it sees symlinks to absolute paths or to relative paths outside the source directory (which would usually be a mistake). 54 | 55 | ## Installation 56 | 57 | Requires Python 2.7+ on Mac or Linux. (Windows untested and probably broken.) 58 | Then (with sudo if desired): 59 | 60 | ``` 61 | pip install instaclone 62 | ``` 63 | 64 | It requires `rsync` for faster file operations, as well as `s3cmd`, `aws`, `s4cmd`, 65 | or any similar tool you put into your `upload_command` and `download_command` settings. 66 | These must be in your path. 67 | 68 | ## Configuration 69 | 70 | Instaclone requires two things to run: 71 | - A config file, which can be called `instaclone.yml` or `instaclone.json` in the current directory. (YAML or JSON syntax is fine.) This configuration file says how resources will be published and installed. 72 | - A main directory to store the cache in, which defaults to `$HOME/.instaclone` but can be overridden by the `INSTACLONE_DIR` environment variable. If you want, you can put a global `instaclone.{yml,json}` file there instead. 73 | 74 | As an example, here is a marginally self-explanatory `instaclone.yml` configuration, which you would drop anywhere you want and probably should check into Git. You'd create as many files like this as desired in different directories, taking care you give them distinct `remote_path`s are unique. 75 | 76 | ```yml 77 | --- 78 | # You can have as many items as you like and all will be installed. 79 | # You'll want to git-ignore the local_paths below. 80 | items: 81 | # A big file lives in this directory. It takes a while to generate, so we're going to 82 | # reference it in this file by version, instaclone publish, and anyone can 83 | # instaclone install it. We update the version string manually when we regenerate it. 84 | - local_path: my-big-and-occasionally-generated-resource.bin 85 | remote_prefix: s3://my-bucket/instaclone-resources 86 | remote_path: some/big-resources 87 | upload_command: s4cmd put -f $LOCAL $REMOTE 88 | download_command: s4cmd get $REMOTE $LOCAL 89 | # This is an explicitly set version of the file. It can be any string. 90 | version_string: 42a 91 | 92 | - local_path: node_modules 93 | remote_prefix: s3://my-bucket/instaclone-resources 94 | remote_path: my-app/node-stuff 95 | upload_command: s4cmd put -f $LOCAL $REMOTE 96 | download_command: s4cmd get $REMOTE $LOCAL 97 | # We generate the version string as a hash of the npm-shrinkwrap.json plus the architecture we're on: 98 | version_hashable: npm-shrinkwrap.json 99 | version_command: uname 100 | ``` 101 | 102 | See below for more on the `node_modules` one. 103 | 104 | ## Usage 105 | 106 | Once Instaclone is configured, run: 107 | 108 | - `instaclone publish`: upload configured items (and add to cache) 109 | - `instaclone install`: download configured items (and add to cache) 110 | - `instaclone configs`: sanity check configuration 111 | - `instaclone purge`: delete entire cache (published resources are never deleted) 112 | - `instaclone remote`: prints the current remote location to standard output (good for sanity checking config or version string) 113 | 114 | Run `instaclone --help` for a complete list of flags and settings. 115 | 116 | If you have multiple items defined in the `instaclone.yml` file, you can list them as arguments to 117 | `instaclone publish` or `instaclone install`, e.g. `instaclone install node_modules`. 118 | 119 | Finally, note that by default, installations are done with a symlink, 120 | but this can be customized in the config file to copy files. 121 | As a shortcut, if you run `instaclone install --copy`, 122 | it will perform a fast rsync-based copy of the files. 123 | You should use the `--copy` option if you plan to modify the files after installation. 124 | 125 | ## Why you should Instaclone node_modules 126 | 127 | This use case deserves a little more explanation. 128 | 129 | While npm is amazingly convenient during development, managing the workflow around `npm install` can be a pain point in terms of speed, reliability, and reproducibility as you scale out builds and in production: 130 | 131 | - As [we](http://blog.nodejs.org/2012/02/27/managing-node-js-dependencies-with-shrinkwrap/) 132 | [all](http://javascript.tutorialhorizon.com/2015/03/21/what-is-npm-shrinkwrap-and-when-is-it-needed/) 133 | [know](http://tilomitra.com/why-you-should-use-npm-shrinkwrap/), 134 | the state of the `node_modules` is not inherently reproducible from the `package.json` file, so you should use [`npm shrinkwrap`](https://docs.npmjs.com/cli/shrinkwrap). 135 | - While `npm shrinkwrap` mostly locks down exact package versions, even this *doesn't guarantee byte-for-byte repeatable installations*. Think about it: Reliability requires controlling change. If you change some single piece of code somewhere unrelated to your dependencies, and your build system reruns `npm install`, what if one of your hundreds of packages was unpublished, or you have an issue connecting to npmjs.org? In addition, shrinkwrap [doesn't prevent churn in peer dependencies](https://github.com/npm/npm/issues/5135). It's impossible to ensure exact repeatability unless you just make an exact copy and use it everywhere. 136 | - Operationally, you also want a more scalable solution to distributing packages than hitting npmjs.org every time. You don't want lots of servers or build machines doing this continuously. 137 | - You can set up a [local npm repository](https://www.npmjs.com/package/sinopia) or a [local npm cache server](https://github.com/mixu/npm_lazy) to help, but this is more infrastructure for devops to maintain and scale. And incidentally, it also is likely to be a single point of failure: Not being able to push new builds reliably is a Bad Thing (precisely when you don't need it). Plus, if you use [private modules](https://www.npmjs.com/private-modules) and pay npm, Inc. to host private code for you, you probably don't otherwise need another local repository. 138 | - Finally, downloading from the global server and even installing from the local cache, take a lot of time, e.g if you want to do rapid CI builds from a clean install. With all these solutions, `npm install` still takes minutes for large projects *even when you haven't changed anything*. 139 | 140 | A simpler and more scalable solution to this is to archive the entire `node_modules` directory, and put it somewhere reliable, like S3. But it can be large and slow to manage if it's always published and then fetched every time you need it. It's also a headache to script, especially in a continuous integration environment, where you want to re-install fresh on builds on all branches, every few minutes, and reinstall *only* when the checked-in `npm-shrinkwrap.json` file changes. Oh, and also the builds are platform-dependent, so you need to publish separately on MacOS and Linux. 141 | 142 | Instaclone does all this for you. If you already have an `npm shrinkwrap` workflow, it's pretty easy. It lets you specify where to store your `node_modules` in S3, and version that entire tree by the SHA1 hash of the `npm-shrinkwrap.json` file togetehr with the architecture. You can then work on multiple branches and swap them in and out -- a bit like how `nvm` caches Node installations. 143 | 144 | Copy and edit [the example config file](examples/npm-install/instaclone.yml) to try it. On your CI system, you might want to have some sort of automation that tries to reuse pre-published versions, but if not, publishes automatically: 145 | ```sh 146 | echo "Running instaclone install or publish..." 147 | instaclone install || (rm -rf ./node_modules && npm install && instaclone publish) 148 | ``` 149 | 150 | Note that in normal scenarios, the installed files are symlinked to the read-only cache. 151 | If you want to `npm install` after doing an `instaclone install`, use 152 | `instaclone install --copy` instead, and all files will be copied instead. 153 | 154 | ## Maturity 155 | 156 | Mostly a one-day hack, but it should now be fairly workable. 157 | It performs well in at least one continuous build environment with quite large directories synced regularly on Mac and Linux. 158 | 159 | ## Caveats 160 | 161 | - There is no `unpublish` functionality -- if you publish something by mistake, go find it in S3 (or wherever you put it) and delete it. 162 | - You have to clean up the cache manually by running `instaclone purge` or deleting files in `~/.instaclone/cache` -- there's no automated process for this yet, so if you publish a lot it will begin to accumulate. 163 | - If you are obsessed with Node, you'll somehow have to accept that this is written in Python. 164 | - See [issues](issues) and [the TODOs list](instaclone/instaclone.py) for further work. 165 | 166 | ## Running tests 167 | 168 | Tests require `s4cmd`: 169 | 170 | ``` 171 | $ TEST_BUCKET=my-s3-bucket tests/run.sh 172 | ``` 173 | 174 | This is a bash-based harness that runs the test script at `tests/tests.sh`. Its output can then be `git diff`ed with the previous output. 175 | 176 | ## Contributing 177 | 178 | Yes, please! File issues for bugs or general discussion. PRs welcome as well -- just figure out how to run the tests and document any other testing that's been done. 179 | 180 | ## License 181 | 182 | Apache 2. 183 | -------------------------------------------------------------------------------- /bin/publish.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -euo pipefail 4 | 5 | confirm_release=${1:?Usage: $0 tag-name 6 | Publish release. Be sure to git push first. 7 | Type the tag name to ensure it matches. 8 | } 9 | 10 | release=$(python -c "from instaclone import main; print main.VERSION") 11 | 12 | if [[ "$release" != "$confirm_release" ]]; then 13 | echo "error: Confirming release failed: Didn't match expected: $release" 14 | exit 1 15 | fi 16 | 17 | if [[ "$(git status -s -uno | wc -l | xargs)" != "0" ]]; then 18 | echo "error: Uncomitted changes!" 19 | exit 1 20 | fi 21 | 22 | base=$(dirname $0)/.. 23 | 24 | set -x 25 | 26 | ghizmo create-release -a name=$release -a tag_name=$release -a prerelease=true 27 | python $base/setup.py sdist upload -r pypi 28 | -------------------------------------------------------------------------------- /examples/npm-install/instaclone.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # Sample configuration for Instacloning node_modules. 3 | # Just copy this file next to your Node project root, modify it as desired, and check it into Git. 4 | # You need to "pip install s4cmd" and configure ~/.s3cfg with your credentials for S3 for this to work. 5 | # Thereafter, anyone can "instaclone publish" or "instaclone install" from that directory. 6 | # With this config, the final files will be in S3 at locations like: 7 | # s3://my-s3-bucket/instaclone/my-project/my-app/node_modules.$xxxx-yyyy$/node_modules.zip 8 | # (where xxxx is a SHA1 hash and yyyy is the platform). 9 | items: 10 | - local_path: node_modules 11 | remote_path: my-app 12 | remote_prefix: s3://my-s3-bucket/instaclone/my-project 13 | # These commands are called to upload and download the archived directory: 14 | upload_command: s4cmd put -f $LOCAL $REMOTE 15 | download_command: s4cmd get $REMOTE $LOCAL 16 | # The "version" is a hash of the shrinkwrap file followed by the platform we're on 17 | # (e.g. Linux or Darwin, which we determine by calling "uname"). 18 | version_hashable: npm-shrinkwrap.json 19 | version_command: uname 20 | -------------------------------------------------------------------------------- /images/clone-140.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vivlabs/instaclone/4d68afabb657e2468c63df0af31b9464c4a0a599/images/clone-140.jpg -------------------------------------------------------------------------------- /instaclone/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Fast, cached installation of versioned files 3 | 4 | For further documentation, see: https://github.com/jlevy/instaclone 5 | """ 6 | 7 | __author__ = 'jlevy' 8 | -------------------------------------------------------------------------------- /instaclone/archives.py: -------------------------------------------------------------------------------- 1 | """ 2 | Libraries for making archives. 3 | """ 4 | 5 | from __future__ import print_function 6 | 7 | __author__ = 'jlevy' 8 | 9 | import sys 10 | import os 11 | import tarfile 12 | import tempfile 13 | import itertools 14 | import logging as log 15 | from collections import namedtuple 16 | 17 | from functools32 import lru_cache # functools32 pip 18 | 19 | # The subprocess module has known threading issues, so prefer subprocess32. 20 | try: 21 | import subprocess32 as subprocess 22 | except ImportError: 23 | import subprocess 24 | 25 | from strif import shell_expand_to_popen, DEV_NULL 26 | 27 | SHELL_OUTPUT = sys.stderr 28 | 29 | 30 | class ArchiveError(RuntimeError): 31 | pass 32 | 33 | 34 | _Archiver = namedtuple("_Archiver", "suffix archive unarchive") 35 | 36 | 37 | def followlink(path, max_follows=10): 38 | """ 39 | Dereference a symlink repeatedly to get a non-symlink (up to max_follows times, 40 | to avoid cycles). 41 | """ 42 | orig_path = path 43 | count = 0 44 | if not os.path.exists(path): 45 | raise ValueError("Not found: %r" % path) 46 | while os.path.islink(path): 47 | # Note path.join handles it correctly if the second arg is an absolute path. 48 | path = os.path.normpath(os.path.join(os.path.dirname(path), os.readlink(path))) 49 | count += 1 50 | if count > max_follows: 51 | raise ValueError("Too many symlinks: %r" % orig_path) 52 | 53 | return path 54 | 55 | 56 | def targz_dir(source_dir, target_archive, dereference_ext_symlinks=True): 57 | norm_source_dir = os.path.normpath(source_dir) 58 | total = itertools.count() 59 | symlinks = itertools.count() 60 | symlinks_followed = itertools.count() 61 | 62 | def tarinfo_filter(tarinfo): 63 | total.next() 64 | log.debug("adding: %s", tarinfo.__dict__) 65 | if tarinfo.linkname: 66 | symlinks.next() 67 | target = followlink(os.path.join(norm_source_dir, tarinfo.name)) 68 | # If it's a relative symlink, and its target is inside our source dir, leave it as is. 69 | # If it's absolute or outside our source dir, resolve it or error. 70 | if os.path.isabs(target) \ 71 | or not os.path.normpath(os.path.join(norm_source_dir, target)).startswith(norm_source_dir): 72 | if dereference_ext_symlinks: 73 | if not os.path.exists(target): 74 | raise ArchiveError("Symlink target not found: %r -> %r" % (tarinfo.name, target)) 75 | tarinfo = tarinfo.tarfile.gettarinfo(target) 76 | symlinks_followed.next() 77 | else: 78 | raise ArchiveError("Absolute path in symlink target not supported: %r -> %r" % (tarinfo.name, target)) 79 | return tarinfo 80 | 81 | with tarfile.open(target_archive, "w:gz") as tf: 82 | log.info("creating archive: %s -> %s", source_dir, target_archive) 83 | tf.add(source_dir, arcname=".", filter=tarinfo_filter) 84 | 85 | log.info("added %s items to archive (%s were symlinks, %s followed)", 86 | total.next(), symlinks.next(), symlinks_followed.next()) 87 | 88 | 89 | def untargz_dir(source_archive, target_dir): 90 | with tarfile.open(source_archive, "r:gz") as tf: 91 | tf.extractall(path=target_dir) 92 | 93 | 94 | TarGzArchiver = _Archiver(".tar.gz", targz_dir, untargz_dir) 95 | 96 | 97 | # Old code: 98 | # We tried zip for a while but found it less satisfactory. 99 | # We use command-line standard zip/unzip instead of Python zip, since it is a bit more performant 100 | # than the Python native alternatives. 101 | 102 | @lru_cache() 103 | def _autodetect_zip_command(): 104 | try: 105 | zip_output = subprocess.check_output(["zip", "-v"]) 106 | zip_cmd = "zip -q -r $ARCHIVE $DIR" 107 | except subprocess.CalledProcessError as e: 108 | raise ArchiveError("Archive handling requires 'zip' in path: %s" % e) 109 | 110 | if zip_output.find("ZIP64_SUPPORT") < 0: 111 | log.warn("installed 'zip' doesn't have Zip64 support so will fail for large archives") 112 | log.debug("zip command: %s", zip_cmd) 113 | return zip_cmd 114 | 115 | 116 | @lru_cache() 117 | def _autodetect_unzip_command(): 118 | unzip_cmd = None 119 | unzip_output = None 120 | try: 121 | unzip_output = subprocess.check_output(["unzip", "-v"]) 122 | unzip_cmd = "unzip -q $ARCHIVE" 123 | except subprocess.CalledProcessError as e: 124 | pass 125 | 126 | # On MacOS Yosemite, unzip does not support Zip64, but ditto is available. 127 | # See: https://github.com/vivlabs/instaclone/issues/1 128 | if not unzip_cmd or not unzip_output or unzip_output.find("ZIP64_SUPPORT") < 0: 129 | log.debug("did not find 'unzip' with Zip64 support; trying ditto") 130 | try: 131 | # ditto has no simple flag to check its version and exit with 0 status code. 132 | subprocess.check_call(["ditto", "-c", "/dev/null", tempfile.mktemp()]) 133 | unzip_cmd = "ditto -x -k $ARCHIVE ." 134 | except subprocess.CalledProcessError as e: 135 | log.debug("did not find ditto") 136 | 137 | if not unzip_cmd: 138 | raise ArchiveError("Archive handling requires 'unzip' or 'ditto' in path") 139 | 140 | log.debug("unzip command: %s", unzip_cmd) 141 | return unzip_cmd 142 | 143 | 144 | def zip_dir(source_dir, target_archive): 145 | popenargs = shell_expand_to_popen(_autodetect_zip_command(), {"ARCHIVE": target_archive, "DIR": "."}) 146 | cd_to = source_dir 147 | log.debug("using cwd: %s", cd_to) 148 | log.info("compress: %s", " ".join(popenargs)) 149 | subprocess.check_call(popenargs, cwd=cd_to, stdout=SHELL_OUTPUT, stderr=SHELL_OUTPUT, stdin=DEV_NULL) 150 | 151 | 152 | def unzip_dir(source_archive, target_dir): 153 | popenargs = shell_expand_to_popen(_autodetect_unzip_command(), {"ARCHIVE": source_archive, "DIR": target_dir}) 154 | cd_to = target_dir 155 | log.debug("using cwd: %s", cd_to) 156 | log.info("decompress: %s", " ".join(popenargs)) 157 | subprocess.check_call(popenargs, cwd=cd_to, stdout=SHELL_OUTPUT, stderr=SHELL_OUTPUT, stdin=DEV_NULL) 158 | 159 | 160 | ZipArchiver = _Archiver(".zip", zip_dir, unzip_dir) 161 | -------------------------------------------------------------------------------- /instaclone/configs.py: -------------------------------------------------------------------------------- 1 | """ 2 | Instaclone configuration handling. 3 | """ 4 | 5 | __author__ = 'jlevy' 6 | 7 | import logging as log 8 | import os 9 | import re 10 | import sys 11 | from collections import namedtuple, OrderedDict 12 | 13 | from enum import Enum # enum34 pip 14 | import yaml # PyYAML pip 15 | from functools32 import lru_cache # functools32 pip 16 | import strif 17 | 18 | from log_calls import log_calls 19 | 20 | _NAME_FIELD = "name" 21 | _required_fields = "local_path remote_path remote_prefix install_method upload_command download_command" 22 | _other_fields = "make_backup version_string version_hashable version_command" 23 | 24 | ConfigBase = namedtuple("ConfigBase", _NAME_FIELD + " " + _other_fields + " " + _required_fields) 25 | 26 | CONFIGS_REQUIRED = _required_fields.split() 27 | CONFIG_DEFAULTS = { 28 | "install_method": "symlink" 29 | } 30 | CONFIG_DESCRIPTIONS = { 31 | "download_command": "shell command template to download file", 32 | "install_method": "the way to install files (symlink, copy, fastcopy, hardlink)", 33 | "local_path": "the local target path to sync to, relative to current dir", 34 | "make_backup": "make a backup (applies only to publish command)", 35 | "remote_path": "remote path (in backing store such as S3) to sync to", 36 | "remote_prefix": "remote path prefix (such as s3://my-bucket/instaclone) to sync to", 37 | "upload_command": "shell command template to upload file", 38 | "version_command": "a shell command that should be run to get a version string", 39 | "version_hashable": "a file path that should be SHA1 hashed to get a version string", 40 | "version_string": "explicit version string to use", 41 | } 42 | # For now, allow anything to be overridden. 43 | CONFIG_OVERRIDABLE = CONFIG_DESCRIPTIONS.keys() 44 | 45 | _CONFIG_VERSION_RE = re.compile("^[\\w.-]+$") 46 | 47 | 48 | def _stringify_config_field(value): 49 | return value.name if isinstance(value, Enum) else str(value) 50 | 51 | 52 | class Config(ConfigBase): 53 | """Configuration for a single item.""" 54 | 55 | def as_string_dict(self): 56 | d = dict(self._asdict()) 57 | return {k: _stringify_config_field(v) for (k, v) in d.iteritems() if v is not None and k != _NAME_FIELD} 58 | 59 | 60 | CONFIG_NAME = "instaclone" 61 | CONFIG_DIR_ENV = "INSTACLONE_DIR" 62 | CONFIG_HOME_DIR = ".instaclone" 63 | 64 | DEFAULT_ITEM_NAME = "default" 65 | 66 | 67 | class ConfigError(RuntimeError): 68 | pass 69 | 70 | 71 | InstallMethod = Enum("InstallMethod", "symlink hardlink copy fastcopy") 72 | 73 | 74 | @lru_cache(maxsize=None) 75 | def _locate_config_dir(): 76 | """Check for which config directory to use.""" 77 | if CONFIG_DIR_ENV in os.environ: 78 | config_dir = os.environ[CONFIG_DIR_ENV] 79 | else: 80 | config_dir = os.path.join(os.environ["HOME"], CONFIG_HOME_DIR) 81 | return config_dir 82 | 83 | 84 | def _locate_config_file(search_dirs): 85 | """Look in common locations for config file.""" 86 | tried = [] 87 | for base in search_dirs: 88 | for path in [os.path.join(base, CONFIG_NAME + suffix) for suffix in ".yml", ".json"]: 89 | log.debug("searching for config file: %s", path) 90 | tried.append(path) 91 | if os.path.isfile(path): 92 | log.info("using config file: %s", path) 93 | return path 94 | raise ConfigError("no config file found in: %s" % ", ".join(tried)) 95 | 96 | 97 | @log_calls 98 | def _load_raw_configs(override_path, defaults, overrides): 99 | """ 100 | Merge defaults, configs from a file, and overrides. 101 | Uses first config file in override_path (if set) or finds it in current dir or config dir. 102 | """ 103 | if override_path: 104 | path = override_path 105 | else: 106 | search_dirs = [".", _locate_config_dir()] 107 | path = _locate_config_file(search_dirs) 108 | 109 | with open(path) as f: 110 | parsed_configs = yaml.safe_load(f) 111 | 112 | out = [] 113 | try: 114 | items = parsed_configs["items"] 115 | for config_dict in items: 116 | # Legacy fix for renamed key. TODO: Remove this after a while. 117 | if "copy_type" in config_dict: 118 | config_dict["install_method"] = config_dict["copy_type"] 119 | del config_dict["copy_type"] 120 | 121 | # Name this config (since we may override the local_path). 122 | config_dict["name"] = config_dict["local_path"] 123 | 124 | nones = {key: None for key in Config._fields} 125 | combined = strif.dict_merge(nones, defaults, config_dict, overrides) 126 | log.debug("raw, combined config: %r", combined) 127 | 128 | try: 129 | out.append(combined) 130 | except TypeError as e: 131 | raise ConfigError("error in config value: %s: %s" % (e, config_dict)) 132 | except ValueError as e: 133 | raise ConfigError("error reading config file: %s" % e) 134 | 135 | return out 136 | 137 | 138 | def _parse_and_validate(raw_config_list): 139 | """ 140 | Parse and validate settings. Merge settings from config files, global defaults, and command-line overrides. 141 | """ 142 | items = [] 143 | for raw in raw_config_list: 144 | 145 | # Validation. 146 | for key in CONFIGS_REQUIRED: 147 | if key not in raw or raw[key] is None: 148 | raise ConfigError("must specify '%s' in item config: %s" % (key, raw)) 149 | 150 | if "version_string" in raw and not _CONFIG_VERSION_RE.match(str(raw["version_string"])): 151 | raise ConfigError("invalid version string: '%s'" % raw["version_string"]) 152 | if "version_string" not in raw and "version_hashable" not in raw and "version_command" not in raw: 153 | raise ConfigError("must specify 'version_string', 'version_hashable', or 'version_command' in item config: %s" % raw) 154 | 155 | # Validate shell templates. 156 | # For these, we don't expand environment variables here, but instead do it at once at call time. 157 | for key in "upload_command", "download_command": 158 | try: 159 | strif.shell_expand_to_popen(raw[key], {"REMOTE": "dummy", "LOCAL": "dummy"}) 160 | except ValueError as e: 161 | raise ConfigError("invalid command in config value for %s: %s" % (key, e)) 162 | 163 | # Normalize and expand environment variables. 164 | for key in "local_path", "remote_prefix", "remote_path": 165 | if key.startswith("/"): 166 | raise ConfigError("currently only support relative paths for local_path and remote_path: %s" % key) 167 | raw[key] = raw[key].rstrip("/") 168 | 169 | try: 170 | raw[key] = strif.expand_variables(raw[key], os.environ) 171 | except ValueError as e: 172 | raise ConfigError("invalid command in config value for %s: %s" % (key, e)) 173 | 174 | # Parse enums. 175 | try: 176 | raw["install_method"] = InstallMethod[raw["install_method"]] 177 | except KeyError: 178 | raise ConfigError("invalid install_method: %s" % raw["install_method"]) 179 | 180 | # Parse booleans. Values True and False may already be converted. 181 | try: 182 | if (type(raw["make_backup"]) is str): 183 | raw["make_backup"] = raw["make_backup"].lower() in ("on", "t", "true", "y", "yes") 184 | except KeyError: 185 | raise ConfigError("invalid make_backup: %s" % raw["make_backup"]) 186 | 187 | items.append(Config(**raw)) 188 | 189 | log.debug("final configs: %s", items) 190 | return items 191 | 192 | 193 | @log_calls 194 | def set_up_cache_dir(): 195 | config_dir = _locate_config_dir() 196 | cache_dir = os.path.join(config_dir, "cache") 197 | if not os.path.exists(cache_dir): 198 | log.info("cache dir not found, so creating: %s", cache_dir) 199 | strif.make_all_dirs(cache_dir) 200 | return cache_dir 201 | 202 | 203 | def load(override_path=None, overrides=None): 204 | """ 205 | Load all configs from a single file. Use override_path or the first one found in standard locations. 206 | If overrides are present, these override all settings. 207 | """ 208 | if not overrides: 209 | overrides = {} 210 | return _parse_and_validate(_load_raw_configs(override_path, CONFIG_DEFAULTS, overrides)) 211 | 212 | 213 | def print_configs(configs, stream=sys.stdout): 214 | yaml.dump({"items": [config.as_string_dict() for config in configs]}, 215 | stream=stream, default_flow_style=False) 216 | 217 | 218 | def _yaml_ordering_support(): 219 | """ 220 | Get yaml lib to handle OrderedDicts. 221 | See http://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts 222 | """ 223 | _mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG 224 | 225 | def dict_representer(dumper, data): 226 | return dumper.represent_dict(data.iteritems()) 227 | 228 | def dict_constructor(loader, node): 229 | return OrderedDict(loader.construct_pairs(node)) 230 | 231 | yaml.add_representer(OrderedDict, dict_representer) 232 | yaml.add_constructor(_mapping_tag, dict_constructor) 233 | 234 | 235 | _yaml_ordering_support() 236 | -------------------------------------------------------------------------------- /instaclone/instaclone.py: -------------------------------------------------------------------------------- 1 | """ 2 | Instaclone main library. 3 | """ 4 | 5 | from __future__ import print_function 6 | 7 | __author__ = 'jlevy' 8 | 9 | import logging as log 10 | import re 11 | import sys 12 | import os 13 | 14 | from enum import Enum # enum34 15 | 16 | 17 | # The subprocess module has known threading issues, so prefer subprocess32. 18 | try: 19 | import subprocess32 as subprocess 20 | except ImportError: 21 | import subprocess 22 | 23 | from strif import (atomic_output_file, temp_output_dir, write_string_to_file, 24 | DEV_NULL, move_to_backup, movefile, 25 | copyfile_atomic, copytree_atomic, file_sha1, 26 | make_all_dirs, make_parent_dirs, chmod_native, 27 | shell_expand_to_popen, 28 | dict_merge) 29 | 30 | import archives 31 | import configs 32 | 33 | from log_calls import log_calls 34 | 35 | SHELL_OUTPUT = sys.stderr 36 | 37 | # We only support one archive format currently. 38 | ARCHIVER = archives.TarGzArchiver 39 | 40 | # Suffix to use when making backups. 41 | BACKUP_SUFFIX = ".bak" 42 | 43 | 44 | class AppError(RuntimeError): 45 | pass 46 | 47 | 48 | @log_calls 49 | def _make_readonly(path, silent=False): 50 | if silent and not os.path.exists(path): 51 | return 52 | return chmod_native(path, "ugo-w", recursive=True) 53 | 54 | 55 | @log_calls 56 | def _make_writable(path, silent=False): 57 | if silent and not os.path.exists(path): 58 | return 59 | return chmod_native(path, "u+w", recursive=True) 60 | 61 | 62 | def _upload_file(command_template, local_path, remote_loc): 63 | popenargs = shell_expand_to_popen(command_template, 64 | dict_merge(os.environ, 65 | {"REMOTE": remote_loc, 66 | "LOCAL": local_path})) 67 | log.info("uploading: %s", " ".join(popenargs)) 68 | # TODO: Find a way to support force here (e.g. add or remove -f to s4cmd) 69 | subprocess.check_call(popenargs, stdout=SHELL_OUTPUT, stderr=SHELL_OUTPUT, 70 | stdin=DEV_NULL) 71 | 72 | 73 | def _download_file(command_template, remote_loc, local_path): 74 | with atomic_output_file(local_path, make_parents=True) as temp_target: 75 | popenargs = shell_expand_to_popen(command_template, 76 | dict_merge(os.environ, 77 | {"REMOTE": remote_loc, 78 | "LOCAL": temp_target})) 79 | log.info("downloading: %s", " ".join(popenargs)) 80 | # TODO: Find a way to support force here. 81 | subprocess.check_call(popenargs, stdout=SHELL_OUTPUT, stderr=SHELL_OUTPUT, 82 | stdin=DEV_NULL) 83 | 84 | 85 | def _compress_dir(local_dir, archive_path, force=False): 86 | if os.path.exists(archive_path): 87 | if force: 88 | log.info("deleting previous archive: %s", archive_path) 89 | os.unlink(archive_path) 90 | else: 91 | raise AppError("Archive already in cache (has version changed?): %r" % 92 | archive_path) 93 | with atomic_output_file(archive_path) as temp_archive: 94 | make_parent_dirs(temp_archive) 95 | ARCHIVER.archive(local_dir, temp_archive) 96 | 97 | 98 | def _decompress_dir(archive_path, target_path, force=False): 99 | if os.path.exists(target_path): 100 | if force: 101 | log.info("deleting previous dir: %s", target_path) 102 | _rmtree_fast(target_path) 103 | else: 104 | raise AppError("Target already exists: %r" % target_path) 105 | with atomic_output_file(target_path) as temp_dir: 106 | make_all_dirs(temp_dir) 107 | ARCHIVER.unarchive(archive_path, temp_dir) 108 | 109 | 110 | def _rsync_dir(source_dir, target_dir, chmod=None): 111 | """ 112 | Use rsync to clone source_dir to target_dir. 113 | Preserves the original owners and permissions. 114 | As an optimization, rsync also allows perms to be partly modified 115 | as files are synced. 116 | """ 117 | popenargs = ["rsync", "-a", "--delete"] 118 | if chmod: 119 | popenargs.append("--chmod=%s" % chmod) 120 | popenargs.append(source_dir.rstrip('/') + '/') 121 | popenargs.append(target_dir) 122 | log.info("using rsync for faster copy") 123 | log.debug("rsync: %r" % popenargs) 124 | subprocess.check_call(popenargs) 125 | 126 | 127 | def _rmtree_fast(path, ignore_errors=False): 128 | """ 129 | Delete a file or directory. Uses rsync to delete directories, which 130 | is among the fastest ways possible to delete large numbers of 131 | files. Note it can remove some read-only files. 132 | 133 | slashroot.in/which-is-the-fastest-method-to-delete-files-in-linux 134 | """ 135 | if ignore_errors and not os.path.exists(path): 136 | return 137 | if os.path.isdir(path) and not os.path.islink(path): 138 | with temp_output_dir("empty.", always_clean=True) as empty_dir: 139 | popenargs = ["rsync", "-r", "--delete", empty_dir + '/', path] 140 | subprocess.check_call(popenargs) 141 | os.rmdir(path) 142 | else: 143 | os.unlink(path) 144 | 145 | 146 | @log_calls 147 | def _install_from_cache(cache_path, target_path, install_method, 148 | force=False, make_backup=False): 149 | """ 150 | Install a file or directory from cache, either symlinking, 151 | hardlinking, or copying. 152 | """ 153 | 154 | def clear_symlink(): 155 | # Never backup links (they are probably previous installs). 156 | if os.path.islink(target_path): 157 | os.unlink(target_path) 158 | 159 | def checked_remove(): 160 | clear_symlink() 161 | if os.path.exists(target_path): 162 | if force: 163 | if make_backup: 164 | _rmtree_fast(target_path + BACKUP_SUFFIX, ignore_errors=True) 165 | move_to_backup(target_path, backup_suffix=BACKUP_SUFFIX) 166 | else: 167 | _rmtree_fast(target_path) 168 | else: 169 | raise AppError("Target already exists: %r" % target_path) 170 | 171 | if not os.path.exists(cache_path): 172 | raise AssertionError("Cached file missing: %r" % cache_path) 173 | log.debug("using install method %s", install_method.name) 174 | if install_method == configs.InstallMethod.symlink: 175 | checked_remove() 176 | os.symlink(cache_path, target_path) 177 | elif install_method == configs.InstallMethod.hardlink: 178 | if os.path.isdir(cache_path): 179 | raise AppError("Can't hardlink a directory: %r" % cache_path) 180 | checked_remove() 181 | os.link(cache_path, target_path) 182 | elif install_method == configs.InstallMethod.copy: 183 | checked_remove() 184 | copytree_atomic(cache_path, target_path) 185 | elif install_method == configs.InstallMethod.fastcopy: 186 | if os.path.isdir(cache_path): 187 | # Try it and see if rsync is available. 188 | try: 189 | clear_symlink() 190 | # Ensure we add write perms since the cache has read-only perms. 191 | # Other perms will be preserved. 192 | _rsync_dir(cache_path, target_path, chmod="u+w") 193 | except OSError as err: 194 | log.info("rsync not found, will copy instead: %s", err) 195 | checked_remove() 196 | copytree_atomic(cache_path, target_path) 197 | else: 198 | checked_remove() 199 | copyfile_atomic(cache_path, target_path) 200 | else: 201 | raise AssertionError("Invalid install_method: %r" % install_method) 202 | 203 | 204 | VERSION_SEP = ".$" 205 | VERSION_END = "$" 206 | 207 | 208 | class FileCache(object): 209 | """ 210 | Manage uploading and downloading files to/from the cloud using a 211 | local cache to maintain copies. Also seamlessly support directories 212 | by archiving them as compressed files. The cache is not bounded and 213 | must be managed/cleaned up manually. 214 | """ 215 | 216 | version = "1" 217 | 218 | def __init__(self, root_path): 219 | self.root_path = root_path.rstrip("/") 220 | self.contents_path = os.path.join(root_path, "contents") 221 | self.version_path = os.path.join(root_path, "version") 222 | self.setup_done = False 223 | assert os.path.exists(self.root_path) 224 | 225 | def setup(self): 226 | """Lazy initialize file cache post instantiation.""" 227 | if not self.setup_done: 228 | if os.path.exists(self.version_path): 229 | log.info("using cache: %s", self.root_path) 230 | else: 231 | log.info("initializing new cache: %s", self.root_path) 232 | make_all_dirs(self.contents_path) 233 | write_string_to_file(self.version_path, FileCache.version + "\n") 234 | self.setup_done = True 235 | 236 | def __str__(self): 237 | return "FileCache@%s" % self.root_path 238 | 239 | def __repr__(self): 240 | return self.__str__() 241 | 242 | @staticmethod 243 | def versioned_path(config, version, suffix=""): 244 | return os.path.join(config.remote_path, 245 | "%s%s%s%s" % 246 | (config.name, VERSION_SEP, version, VERSION_END), 247 | "%s%s" % 248 | (os.path.basename(config.name), suffix)) 249 | 250 | @staticmethod 251 | def pathify_remote_loc(remote_loc): 252 | return os.path.join(*re.findall("[a-zA-Z0-9_.-]+", remote_loc)) 253 | 254 | def cache_path(self, config, version, suffix=""): 255 | return os.path.join(self.contents_path, 256 | self.pathify_remote_loc(config.remote_prefix), 257 | self.versioned_path(config, version, suffix)) 258 | 259 | def remote_loc(self, config, version, suffix=""): 260 | return os.path.join(config.remote_prefix, 261 | self.versioned_path(config, version, suffix)) 262 | 263 | def _upload(self, config, cached_path, version): 264 | _upload_file(config.upload_command, cached_path, 265 | self.remote_loc(config, version)) 266 | 267 | @log_calls 268 | def publish(self, config, version, force=False): 269 | # As precaution for users, we keep unarchived items in cache 270 | # that may be symlinked to as read-only. 271 | cached_path = self.cache_path(config, version) 272 | try: 273 | _make_writable(cached_path, silent=True) 274 | self._publish_writable(config, version, make_backup=config.make_backup, 275 | force=force) 276 | finally: 277 | _make_readonly(cached_path, silent=True) 278 | 279 | def _publish_writable_local_file(self, config, version, 280 | local_path, cached_path, 281 | make_backup=False): 282 | remote_loc = self.remote_loc(config, version) 283 | 284 | log.debug("installing to cache: %s -> %s", local_path, cached_path) 285 | # For speed on large files, move it rather than copy. 286 | # Also make it read-only, just as it will be after install. 287 | movefile(local_path, cached_path, make_parents=True) 288 | _upload_file(config.upload_command, cached_path, remote_loc) 289 | log.info("installed to cache: %s -> %s", local_path, cached_path) 290 | _install_from_cache(cached_path, local_path, config.install_method, 291 | force=False, make_backup=make_backup) 292 | log.info("published file: %s", remote_loc) 293 | 294 | def _publish_writable_local_dir(self, config, version, 295 | local_path, cached_path, 296 | force=False, make_backup=True): 297 | cached_archive = self.cache_path(config, version, suffix=ARCHIVER.suffix) 298 | remote_loc = self.remote_loc(config, version, suffix=ARCHIVER.suffix) 299 | 300 | # We archive and then unarchive, to make sure we expand symlinks 301 | # exactly the way a future installation would. 302 | # TODO: This is usually what we want (think of relative symlinks 303 | # like ../../foo), but we could make it an option. 304 | log.debug("installing to cache: %s -> %s", local_path, cached_path) 305 | _compress_dir(local_path, cached_archive, force=force) 306 | _upload_file(config.upload_command, cached_archive, remote_loc) 307 | _decompress_dir(cached_archive, cached_path, force=force) 308 | # If everything has succeeded, we can safely delete the archive 309 | # to save space. 310 | os.unlink(cached_archive) 311 | # Leave the previous version of the tree as a backup. 312 | log.info("installed to cache: %s -> %s", local_path, cached_path) 313 | _install_from_cache(cached_path, local_path, config.install_method, 314 | force=True, make_backup=make_backup) 315 | log.info("published archive: %s", remote_loc) 316 | 317 | def _publish_writable(self, config, version, make_backup, force=False): 318 | local_path = config.local_path 319 | cached_path = self.cache_path(config, version) 320 | 321 | if os.path.islink(local_path): 322 | raise AppError("Cannot publish symlinks (path already published?): %r" % 323 | local_path) 324 | 325 | self.setup() 326 | 327 | # Directories are archived. Files are published as is. 328 | if os.path.isdir(local_path): 329 | self._publish_writable_local_dir(config, version, 330 | local_path, cached_path, 331 | force, make_backup) 332 | elif os.path.isfile(local_path): 333 | self._publish_writable_local_file(config, version, 334 | local_path, cached_path, 335 | make_backup) 336 | elif os.path.exists(local_path): 337 | # Not a file, dir, or symlink! 338 | raise ValueError("Only files or directories can be published: %r" % 339 | local_path) 340 | else: 341 | raise ValueError("File not found: %r" % local_path) 342 | 343 | @log_calls 344 | def install(self, config, version, force=False): 345 | self.setup() 346 | cached_path = self.cache_path(config, version) 347 | if os.path.exists(cached_path): 348 | # It's a cached file or a cached directory and we've already unpacked it. 349 | _install_from_cache(cached_path, config.local_path, 350 | config.install_method, force=force) 351 | log.info("installed from cache (%s): %s -> %s", 352 | config.install_method.name, config.local_path, cached_path) 353 | else: 354 | # First try it as a directory/archive. 355 | remote_archive_loc = self.remote_loc( 356 | config, version, suffix=ARCHIVER.suffix) 357 | cached_archive_path = self.cache_path( 358 | config, version, suffix=ARCHIVER.suffix) 359 | is_dir = True 360 | # This could be cleaner, but it's nice to be data-driven and not 361 | # require a config saying it's a dir or file. 362 | log.debug("checking for directory by seeing if archive suffix exists") 363 | try: 364 | _download_file( 365 | config.download_command, remote_archive_loc, cached_archive_path) 366 | except subprocess.CalledProcessError: 367 | log.debug("doesn't look like an archived directory: treating as file") 368 | is_dir = False 369 | if is_dir: 370 | log.info("downloaded published archive: %s", remote_archive_loc) 371 | _decompress_dir(cached_archive_path, cached_path, force=force) 372 | # If everything has succeeded, we can safely delete the 373 | # archive to save space. 374 | os.unlink(cached_archive_path) 375 | log.info("installed directory: %s -> %s", 376 | config.local_path, cached_path) 377 | else: 378 | remote_loc = self.remote_loc(config, version) 379 | _download_file(config.download_command, remote_loc, cached_path) 380 | log.info("downloaded published file: %s", remote_loc) 381 | log.info("installed file: %s -> %s", config.local_path, cached_path) 382 | 383 | _make_readonly(cached_path) 384 | _install_from_cache(cached_path, config.local_path, 385 | config.install_method, force=force) 386 | 387 | @log_calls 388 | def purge(self): 389 | log.info("purging cache: %s", self.root_path) 390 | _make_writable(self.root_path, silent=True) 391 | _rmtree_fast(self.root_path) 392 | 393 | 394 | def version_for(config): 395 | """ 396 | The version for an item is either the explicit version specified by 397 | the user, or the SHA1 hash of hashable file. 398 | """ 399 | bits = [] 400 | if config.version_string: 401 | bits.append(str(config.version_string)) 402 | if config.version_hashable: 403 | log.debug("computing sha1 of: %s", config.version_hashable) 404 | bits.append(file_sha1(config.version_hashable)) 405 | if config.version_command: 406 | log.debug("version command: %s", config.version_command) 407 | popenargs = shell_expand_to_popen(config.version_command, os.environ) 408 | output = subprocess.check_output( 409 | popenargs, stderr=SHELL_OUTPUT, stdin=DEV_NULL).strip() 410 | if not configs._CONFIG_VERSION_RE.match(output): 411 | raise configs.ConfigError( 412 | "Invalid version output from version command: %r" % output) 413 | bits.append(output) 414 | 415 | return "-".join(bits) 416 | 417 | 418 | # 419 | # ---- Command line ---- 420 | 421 | Command = Enum("Command", "publish install purge configs remote") 422 | _command_list = [c.name for c in Command] 423 | 424 | 425 | def select_configs(config_list, items): 426 | """Select configs by name, or all configs if none specified.""" 427 | if items: 428 | log.debug("selecting configs for items: %s", items) 429 | new_config_list = [] 430 | for item in items: 431 | matches = filter(lambda config: config.name == item, config_list) 432 | if len(matches) < 1: 433 | raise ValueError("Could not find config for item: %s" % item) 434 | new_config_list.append(matches[0]) 435 | config_list = new_config_list 436 | return config_list 437 | 438 | 439 | def run_command(command, override_path=None, overrides=None, 440 | force=False, items=None): 441 | # Nondestructive commands that don't require cache. 442 | if command == Command.configs: 443 | config_list = select_configs( 444 | configs.load(override_path=override_path, overrides=overrides), 445 | items) 446 | configs.print_configs(config_list) 447 | 448 | # Destructive commands that require cache but not configs. 449 | elif command == Command.purge: 450 | file_cache = FileCache(configs.set_up_cache_dir()) 451 | file_cache.purge() 452 | 453 | # Commands that require cache and configs. 454 | else: 455 | config_list = select_configs( 456 | configs.load(override_path=override_path, overrides=overrides), 457 | items) 458 | 459 | file_cache = FileCache(configs.set_up_cache_dir()) 460 | 461 | if command == Command.publish: 462 | for config in config_list: 463 | file_cache.publish(config, version_for(config), force=force) 464 | 465 | elif command == Command.install: 466 | for config in config_list: 467 | file_cache.install(config, version_for(config), force=force) 468 | 469 | elif command == Command.remote: 470 | for config in config_list: 471 | loc = file_cache.remote_loc(config, version_for(config)) 472 | print(loc) 473 | 474 | else: 475 | raise AssertionError("unknown command: " + command) 476 | 477 | # TODO: 478 | # - "clean" command that deletes local resources (requiring -f if not in cache) 479 | # - "unpublish" command that deletes a remote resource (and purges from cache) 480 | # - --no-cache option that just downloads 481 | # - consider new feature: 482 | # failover_command that is executed if install fails, 483 | # and a flag failover_publish indicating whether to publish 484 | # - command to unpublish all but most recent n versions of a resource? 485 | # - support compressing files as well as archives 486 | # - consider pax-based hardlink tree copy option (more cross platform than cp) 487 | # - init command to generate a config 488 | # - "--offline" mode for install (i.e. will fail if it has to download) 489 | # - test out more custom transport commands (s3cmd, awscli, wget, etc.) 490 | # - for the custom transport like curl, figure out handling of shell redirects? 491 | # (perhaps better just to require a bash wrapper) 492 | -------------------------------------------------------------------------------- /instaclone/log_calls.py: -------------------------------------------------------------------------------- 1 | """ 2 | A simple utility to log calls to functions, for debugging. 3 | """ 4 | 5 | __author__ = 'jlevy' 6 | 7 | import functools 8 | import logging 9 | from logging import log 10 | 11 | 12 | def log_calls_with(severity): 13 | """Create a decorator to log calls and return values of any function, for debugging.""" 14 | 15 | def decorator(fn): 16 | @functools.wraps(fn) 17 | def wrap(*params, **kwargs): 18 | call_str = "%s(%s)" % ( 19 | fn.__name__, ", ".join([repr(p) for p in params] + ["%s=%s" % (k, repr(v)) for (k, v) in kwargs.items()])) 20 | # TODO: Extract line number from caller and use that in logging. 21 | log(severity, ">> %s", call_str) 22 | ret = fn(*params, **kwargs) 23 | # TODO: Add a way to make return short or omitted. 24 | log(severity, "<< %s: %s", call_str, repr(ret)) 25 | return ret 26 | 27 | return wrap 28 | 29 | return decorator 30 | 31 | # Convenience decorators for logging. 32 | log_calls_info = log_calls_with(logging.INFO) 33 | log_calls = log_calls_with(logging.DEBUG) 34 | -------------------------------------------------------------------------------- /instaclone/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Instaclone is usually run from a directory where a instaclone.{yml,json} 4 | settings file resides. It will then install to and publish from that 5 | directory, based on settings in that file. 6 | 7 | Settings may be overridden with corresponding command-line args. 8 | 9 | The install method determines how items are installed from cache: 10 | - symlink: Symlink to read-only cache (the default) 11 | - copy: A slow, full copy of the file or directory 12 | - fastcopy: A faster copy using rsync (preferred over copy) 13 | - hardlink: A hard link (files only) 14 | 15 | For further documentation, see: https://github.com/vivlabs/instaclone 16 | """ 17 | 18 | from __future__ import print_function 19 | 20 | import logging as log 21 | import argparse 22 | import sys 23 | 24 | NAME = "instaclone" 25 | VERSION = "0.3.4" 26 | DESCRIPTION = "instaclone: Fast, cached file installation" 27 | LONG_DESCRIPTION = __doc__ 28 | 29 | LOG_STREAM = sys.stderr 30 | 31 | 32 | def log_setup(level): 33 | if level == log.DEBUG: 34 | log.basicConfig(format="%(levelname).1s %(filename)16s:%(lineno)-4d %(message)s", level=level, 35 | stream=LOG_STREAM) 36 | else: 37 | log.basicConfig(format="%(message)s", level=level, stream=LOG_STREAM) 38 | 39 | def brief_excepthook(exctype, value, traceback): 40 | print("error: %s" % value, file=sys.stderr) 41 | print("(run with --debug for traceback info)", file=sys.stderr) 42 | sys.exit(2) 43 | 44 | sys.excepthook = brief_excepthook 45 | 46 | 47 | def main(): 48 | import instaclone 49 | import configs 50 | 51 | config_docs = "Setting file keys:\n\n%s\n" % ( 52 | "\n".join([" %s: %s" % (k, v) for (k, v) in configs.CONFIG_DESCRIPTIONS.iteritems()])) 53 | 54 | parser = argparse.ArgumentParser(description=DESCRIPTION, version=VERSION, epilog="\n" + config_docs + __doc__, 55 | formatter_class=argparse.RawTextHelpFormatter) 56 | parser.add_argument("command", help="%s command" % NAME, choices=instaclone._command_list) 57 | parser.add_argument("items", help="optional subset of local paths to install", nargs="*") 58 | parser.add_argument("--config", help="YAML or JSON file to use (overrides usual search path)") 59 | parser.add_argument("-f", "--force", 60 | help="force operation, clobbering any existing cached or local targets (use with care)", 61 | action="store_true") 62 | parser.add_argument("--copy", 63 | help="override: use install_method=fastcopy for all items", 64 | action="store_true") 65 | parser.add_argument("--debug", help="enable debugging output", action="store_true") 66 | 67 | # XXX Unfortunately the setting "version" conflicts with argparse's --version. 68 | for (key, desc) in configs.CONFIG_DESCRIPTIONS.iteritems(): 69 | parser.add_argument("--" + key.replace("_", "-"), metavar="S", help="setting override (single item)") 70 | 71 | args = parser.parse_args() 72 | 73 | overrides = {} 74 | for key in configs.CONFIG_OVERRIDABLE: 75 | value = args.__dict__.get(key) 76 | if value is not None: 77 | if len(args.items) == 1: 78 | overrides[key.replace("-", "_")] = value 79 | else: 80 | raise ValueError("Must specify just one item when using override '%s'" % key) 81 | 82 | # These overrides can be applied to _all_ items. 83 | if args.copy: 84 | overrides["install_method"] = "fastcopy" 85 | 86 | log_setup(log.DEBUG if args.debug else log.INFO) 87 | 88 | log.debug("command-line overrides: %r", overrides) 89 | 90 | instaclone.run_command(instaclone.Command[args.command], override_path=args.config, overrides=overrides, 91 | force=args.force, items=args.items) 92 | 93 | 94 | if __name__ == '__main__': 95 | main() 96 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env 2 | 3 | from setuptools import setup, find_packages 4 | from instaclone import main 5 | 6 | setup( 7 | name="instaclone", 8 | version=main.VERSION, 9 | packages=find_packages(), 10 | author="Joshua Levy", 11 | license="Apache 2", 12 | url="https://github.com/vivlabs/instaclone", 13 | install_requires=["strif>=0.1.2", "enum34>=1.0.4", "PyYAML>=3.11", "subprocess32>=3.2.6", "functools32>=3.2.3"], 14 | description=main.DESCRIPTION, 15 | long_description=main.LONG_DESCRIPTION, 16 | classifiers=[ 17 | 'Development Status :: 4 - Beta', 18 | 'Environment :: Console', 19 | 'Intended Audience :: End Users/Desktop', 20 | 'Intended Audience :: System Administrators', 21 | 'Intended Audience :: Developers', 22 | 'License :: OSI Approved :: Apache Software License', 23 | 'Operating System :: MacOS :: MacOS X', 24 | 'Operating System :: POSIX', 25 | 'Operating System :: Unix', 26 | 'Programming Language :: Python :: 2.7', 27 | 'Topic :: Utilities', 28 | 'Topic :: Software Development' 29 | ], 30 | entry_points={ 31 | "console_scripts": [ 32 | "instaclone = instaclone.main:main", 33 | ], 34 | }, 35 | ) 36 | -------------------------------------------------------------------------------- /tests/.gitignore: -------------------------------------------------------------------------------- 1 | # We don't want to check in the run directory or the full, un-cleaned logs. 2 | tmp-dir 3 | tests-full.log 4 | -------------------------------------------------------------------------------- /tests/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Primitive but effective test harness for running command-line regression tests. 4 | # This is all rather ugly but once this harness works, you only need to look at the 5 | # tests file and occasionally edit the cleanup patterns below. 6 | 7 | set -euo pipefail 8 | trap "echo && echo 'Tests failed! See failure above.'" ERR 9 | 10 | dir="$(cd `dirname $0`; pwd)" 11 | prog_name=exporter 12 | 13 | full_log=${1:-$dir/tests-full.log} 14 | clean_log=${2:-$dir/tests-clean.log} 15 | 16 | 17 | echo Cleaning up... 18 | 19 | test_bucket=${TEST_BUCKET:?error: must specify an S3 bucket for tests, in the TEST_BUCKET env variable} 20 | s4cmd del -r s3://$test_bucket/tmp/instaclone-tests 21 | 22 | rm -rf "$dir/tmp-dir" 23 | cp -a $dir/work-dir $dir/tmp-dir 24 | cd $dir/tmp-dir 25 | 26 | echo "Running..." 27 | 28 | # Hackity hack: 29 | # Remove per-run and per-platform details to allow easy comparison. 30 | # Update these patterns as appropriate. 31 | # Note we use perl not sed, so it works on Mac and Linux. 32 | # The $|=1; is just for the impatient and ensures line buffering. 33 | # We also use the cat trick below so it's possible to view the full log as it 34 | # runs on stderr while writing to both logs. 35 | $dir/tests.sh 2>&1 \ 36 | | tee $full_log \ 37 | | tee >(cat 1>&2) \ 38 | | perl -pe '$|=1; s/([a-zA-Z0-9._]+.py):[0-9]+/\1:xx/g' \ 39 | | perl -pe '$|=1; s/File ".*\/([a-zA-Z0-9._]+.py)", line [0-9]*,/File "...\/\1", line __X,/g' \ 40 | | perl -pe '$|=1; s/, line [0-9]*,/, line __X,/g' \ 41 | | perl -pe '$|=1; s/partial.[a-z0-9]*/partial.__X/g' \ 42 | | perl -pe '$|=1; s/ at 0x[0-9a-f]*/ at 0x__X/g' \ 43 | | perl -pe '$|=1; s/[0-9.:T-]*Z/__TIMESTAMP/g' \ 44 | | perl -pe '$|=1; s|s3://[a-zA-Z0-9_-]+/|s3://__BUCKET/|g' \ 45 | | perl -pe '$|=1; s|/s3/[a-zA-Z0-9_-]+/|/s3/__BUCKET/|g' \ 46 | | perl -pe '$|=1; s|/private/tmp/|/tmp/|g' \ 47 | | perl -pe '$|=1; s|/\S+/.instaclone/|__DIR/.instaclone/|g' \ 48 | > $clean_log 49 | 50 | echo "Tests done." 51 | echo 52 | echo "Full log: $full_log" 53 | echo "Clean log: $clean_log" 54 | echo 55 | echo "Validation is manual. To compare regression test results with previously correct output, run:" 56 | echo "git diff $clean_log" 57 | -------------------------------------------------------------------------------- /tests/tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Test script. Output of this script can be saved and compared to test for regressions. 4 | # Double-spacing between commands here makes the script output easier to read. 5 | 6 | # We turn on exit on error, so that any status code changes cause a test failure. 7 | set -e -o pipefail 8 | 9 | prog_name=instaclone 10 | base_dir=`dirname $0` 11 | config=$base_dir/instaclone.yml 12 | prog=$base_dir/../${prog_name}/main.py 13 | 14 | args= 15 | #args=--debug 16 | 17 | # Run harness to set test config externally. 18 | run() { 19 | $prog $args "$@" 20 | } 21 | 22 | # A trick to test for error conditions. 23 | expect_error() { 24 | echo "(got expected error: status $?)" 25 | } 26 | 27 | # A trick to do ls portably, showing just permissions, file types, and symlinks. 28 | ls_portable() { 29 | ls -lF "$@" | tail +2 | awk '{print $1, $9, $10, $11}' 30 | } 31 | 32 | # This will echo all commands as they are read. Bash commands plus their 33 | # outputs will be used for validating regression tests pass (set -x is similar 34 | # but less readable and sometimes not deterministic). 35 | set -v 36 | 37 | # --- Start of tests --- 38 | 39 | unset INSTACLONE_DIR 40 | 41 | # Platform and Python version we're using to run tests. 42 | uname 43 | 44 | python -V 45 | 46 | run purge 47 | 48 | # Error invocations. 49 | run bad_command || expect_error 50 | 51 | run configs 52 | 53 | run configs test-dir 54 | 55 | # Check contents before. 56 | ls_portable 57 | 58 | ls_portable test-dir/ 59 | 60 | ls_portable test-dir/subdir/ 61 | 62 | head -10 test-dir/file-* test-file{1,2} 63 | 64 | run install || expect_error 65 | 66 | run publish 67 | 68 | # Check for results of publish. 69 | ls_portable 70 | 71 | ls_portable test-dir/ 72 | 73 | head -10 test-dir/file-* test-file{1,2} 74 | 75 | # Publish again. 76 | run publish || expect_error 77 | 78 | run install -f 79 | 80 | find $HOME/.instaclone/cache -type f 81 | 82 | # Try cleaning cache again and re-installing. 83 | 84 | run purge 85 | 86 | # This should fail since we installed before. 87 | run install || expect_error 88 | 89 | run install -f 90 | 91 | # Check contents once more. 92 | ls_portable 93 | 94 | ls_portable test-dir/ 95 | 96 | # Try a copy installation. 97 | rm test-file1 test-file2 test-dir 98 | rm -rf *.bak 99 | 100 | run install --copy 101 | 102 | ls_portable 103 | 104 | ls_portable test-dir/ 105 | 106 | # Test installation of a single item, as well as command line override. 107 | run install test-dir --local-path alt-test-dir 108 | 109 | ls_portable 110 | 111 | diff -r test-dir alt-test-dir 112 | 113 | # Try non-default instaclone cache directory. 114 | export INSTACLONE_DIR=/tmp/instaclone-dir 115 | chmod -R +w $INSTACLONE_DIR || true 116 | rm -rf $INSTACLONE_DIR 117 | 118 | run install -f 119 | 120 | # Leave files installed in case it's helpful to debug anything. 121 | 122 | # --- End of tests --- 123 | -------------------------------------------------------------------------------- /tests/work-dir/instaclone.yml: -------------------------------------------------------------------------------- 1 | --- 2 | items: 3 | - local_path: test-file1 4 | remote_path: another-folder 5 | remote_prefix: s3://$TEST_BUCKET/tmp/instaclone-tests 6 | version_string: v11 7 | upload_command: s4cmd put -f $LOCAL $REMOTE 8 | download_command: s4cmd get $REMOTE $LOCAL 9 | 10 | - local_path: test-file2 11 | remote_path: another-folder 12 | remote_prefix: s3://$TEST_BUCKET/tmp/instaclone-tests 13 | version_string: v22 14 | upload_command: s4cmd put -f $LOCAL $REMOTE 15 | download_command: s4cmd get $REMOTE $LOCAL 16 | install_method: fastcopy 17 | 18 | - local_path: test-dir 19 | remote_path: some/remote/folder 20 | remote_prefix: s3://$TEST_BUCKET/instaclone/tmp-tests 21 | version_hashable: test-file2-hashable 22 | version_command: echo testver 23 | upload_command: s4cmd put -f $LOCAL $REMOTE 24 | download_command: s4cmd get $REMOTE $LOCAL 25 | -------------------------------------------------------------------------------- /tests/work-dir/test-dir/file-a: -------------------------------------------------------------------------------- 1 | contents a 2 | -------------------------------------------------------------------------------- /tests/work-dir/test-dir/file-b: -------------------------------------------------------------------------------- 1 | contents b 2 | -------------------------------------------------------------------------------- /tests/work-dir/test-dir/subdir/file-c: -------------------------------------------------------------------------------- 1 | contents c 2 | -------------------------------------------------------------------------------- /tests/work-dir/test-dir/subdir/symlink-file-b: -------------------------------------------------------------------------------- 1 | ../file-b -------------------------------------------------------------------------------- /tests/work-dir/test-dir/symlink-file-a: -------------------------------------------------------------------------------- 1 | file-a -------------------------------------------------------------------------------- /tests/work-dir/test-dir/symlink-symlink-file-a: -------------------------------------------------------------------------------- 1 | symlink-file-a -------------------------------------------------------------------------------- /tests/work-dir/test-file1: -------------------------------------------------------------------------------- 1 | some 2 | contents 3 | -------------------------------------------------------------------------------- /tests/work-dir/test-file2: -------------------------------------------------------------------------------- 1 | some 2 | more 3 | contents 4 | -------------------------------------------------------------------------------- /tests/work-dir/test-file2-hashable: -------------------------------------------------------------------------------- 1 | hashme 2 | --------------------------------------------------------------------------------