Repository: raiyanyahya/freshenv Branch: master Commit: 08ce41c72bdc Files: 35 Total size: 66.8 KB Directory structure: gitextract_yjxp32md/ ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ └── feature_request.md │ ├── dependabot.yml │ └── workflows/ │ ├── Build-Test.yml │ ├── Integration-Tests.yml │ ├── Package-Release.yml │ └── codeql-analysis.yml ├── .gitignore ├── .version ├── LICENSE ├── MANIFEST.in ├── README.md ├── changelog.md ├── contributing.md ├── freshenv/ │ ├── __init__.py │ ├── build.py │ ├── check.py │ ├── clean.py │ ├── cli.py │ ├── cloud/ │ │ ├── __init__.py │ │ ├── cloud.py │ │ ├── config.py │ │ ├── fetch.py │ │ ├── ls.py │ │ └── push.py │ ├── console.py │ ├── flavours.py │ ├── provision.py │ ├── remove.py │ ├── start.py │ ├── util.py │ └── view.py ├── setup.py ├── snap/ │ └── snapcraft.yaml └── tox.ini ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: raiyanyahya ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: "pip" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "daily" ================================================ FILE: .github/workflows/Build-Test.yml ================================================ name: Build Test on: pull_request: branches: [ master ] push: branches: [ master ] workflow_dispatch: jobs: Build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: setup python uses: actions/setup-python@v2 with: python-version: 3.8 - name: build run: python3 setup.py install Test: needs: [Build] runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: setup python uses: actions/setup-python@v2 with: python-version: 3.8 - name: test run: | pip3 install tox tox -r ================================================ FILE: .github/workflows/Integration-Tests.yml ================================================ name: Integration Tests on: pull_request: branches: [ master ] workflow_dispatch: jobs: integrations-tests: strategy: matrix: os: [macos-latest, ubuntu-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - name: setup python uses: actions/setup-python@v2 with: python-version: 3.8 - uses: docker-practice/actions-setup-docker@master - run: | set -x docker version python3 -m pip install --upgrade pip pip3 install setuptools wheel twine pip3 install . fr check fr provision -c ls fr view fr remove freshenv_1 fr clean fr flavours fr build testenv echo "[testenv]" >> ~/.freshenv/freshenv echo "base=ubuntu" >> ~/.freshenv/freshenv echo "install=apt update -y && apt upgrade -y && apt install snapd -y" >> ~/.freshenv/freshenv echo "cmd=bash" >> ~/.freshenv/freshenv fr build testenv fr cloud config ================================================ FILE: .github/workflows/Package-Release.yml ================================================ name: Package Release on: workflow_dispatch: jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: setup python uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install dependencies run: | python3 -m pip install --upgrade pip pip3 install setuptools wheel twine sudo snap install snapcraft --classic sudo snap install multipass - name: Build and publish env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }} SNAP_TOKEN: ${{ secrets.SNAPCRAFT_SECRET }} SNAPCRAFT_BUILD_ENVIRONMENT: host run: | echo "$SNAP_TOKEN" | snapcraft login --with - snapcraft snapcraft upload --release=stable *.snap python3 setup.py sdist bdist_wheel twine upload dist/* ================================================ FILE: .github/workflows/codeql-analysis.yml ================================================ name: "CodeQL" on: push: branches: [ master ] pull_request: branches: [ master ] jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ 'python' ] steps: - name: Checkout repository uses: actions/checkout@v2 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v1 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v1 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language #- run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v1 ================================================ FILE: .gitignore ================================================ # Created by .ignore support plugin (hsz.mobi) ### Python template # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # snap freshenv_* # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ *.tar # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ .idea env.bak/ venv.bak/ .idea/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ ================================================ FILE: .version ================================================ 3.0.4 ================================================ FILE: LICENSE ================================================ Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. ================================================ FILE: MANIFEST.in ================================================ include .version exclude snap exclude snap/snapcraft.yml ================================================ FILE: README.md ================================================ [![Actions Status](https://github.com/raiyanyahya/freshenv/workflows/Build%20Test/badge.svg)](https://github.com/raiyanyahya/freshenv/actions) [![Actions Status](https://github.com/raiyanyahya/freshenv/workflows/Package%20Release/badge.svg)](https://github.com/raiyanyahya/freshenv/actions) [![Actions Status](https://github.com/raiyanyahya/freshenv/workflows/Integration%20Tests/badge.svg)](https://github.com/raiyanyahya/freshenv/actions) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=raiyanyahya_freshenv&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=raiyanyahya_freshenv) [![CodeQL](https://github.com/raiyanyahya/freshenv/workflows/CodeQL/badge.svg)](https://github.com/raiyanyahya/freshenv/actions?query=workflow%3ACodeQL) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/786fd03c3cc5450c8ad6cf7c00302a94)](https://www.codacy.com/gh/raiyanyahya/freshenv/dashboard?utm_source=github.com&utm_medium=referral&utm_content=raiyanyahya/freshenv&utm_campaign=Badge_Grade) [![](https://img.shields.io/badge/python-3.6+-blue.svg)] [![freshenv](https://snapcraft.io/freshenv/badge.svg)](https://snapcraft.io/freshenv) [![PyPI version](https://badge.fury.io/py/freshenv.svg)](https://badge.fury.io/py/freshenv) [![PyPI download month](https://img.shields.io/pypi/dm/freshenv.svg)](https://pypi.python.org/pypi/freshenv/) # Freshenv 🥗 ```freshenv``` is a command line application to provision and manage local developer environments. Build and develop your projects in completely isolated environments. Save, switch and restart your environments. Push and fetch developer environments from the cloud. Choose from a wide variety of flavours to get the developer tools you need.\ \ [![download-17adc07640182f121.gif](https://s10.gifyu.com/images/download-17adc07640182f121.gif)](https://gifyu.com/image/Sbsim) ## The Story This is a solution to a problem I have always had. I like my system to be clean, minimal and structured. It gets quite tricky to manage multiple projects on my on machine, projects tend to gather and are placed everywhere. Overtime managing system wide dependencies becomes a problem. It is quite easy to mess up a system setting or to keep track of a package I wont need tomorrow. This is why I built ```freshenv```. It is a command line application which helps developers in running and managing completely isolated developer environments locally. It fetches and lets you run environment flavours in the form of docker containers which are preconfigured with tools and packages developer needs everyday. Read about the usage below. I imagine it would help developers like me. I hope you like it. ## Flavours ```freshenv flavours``` are different configurations for freshenv environments. You choose a flavour and provision it as an environment. A flavour can be a combination of operating systems, language packs, tools and application bundles. By default freshenv provisions you with a ```base``` flavour which runs ubuntu 18.04 and has packages like ```wget git python3-pip curl zsh wget nano zsh``` and more. The base flavour is a 260mb environment when provisioned. There are bigger flavours like ```devenv``` which runs on the latest ubuntu and has been loaded and configured with ```docker (run docker inside your freshenv environment), golang, python, node, java, a vscode server, build-essential automake make cmake sudo g++ wget git python3-pip curl zsh wget nano nodejs npm fonts-powerline``` and more. This environment is around 1.6gb large. Freshenv also gives you the option to provision a language based environment which contains necessary developer tools for that language. Checkout the usage section below on the flavours command to see a list of flavours available. ## Custom Environments Freshenv lets developers build and provision custom environments. A custom flavour is a configuration of the base operating system, packages to install and the command to run when your environment is provisioned. Custom flavours are configured in a config file placed under $HOME/.freshenv/freshenv. This file will be automatically created once you run ```freshenv build config```. Below is an example of a custom flavour. ```yml [MyEnv] base=ubuntu install=apt update -y && apt upgrade -y && apt install arandr cmd=bash ``` ## Cloud Environments Freshenv cloud introduces cloud capabilities to the developer environments. It lets developers ```push``` and ```fetch``` custom environments to the cloud. It currently supports personal clouds and a freshenv hosting plan is being worked on. To use the cloud features of freshenv you have to configure freshenv with the cloud provider and the bucket name. A sample of the config is present below. It currently supports aws s3 as a provider and more providers are being worked on. Please run ```fr cloud --help``` for more information. ```yml [cloud.personal] provider=aws bucket=myenvironments aws_profile=default ``` ## Installation Linux I recommend using the snap package manager to install freshenv. ```console snap install freshenv # give it access to the docker interface snap connect freshenv:docker docker:docker-daemon ``` If you dont have or use snap, install the freshenv python package from pypi. ```console pip install freshenv ``` I would recommend using pipx instead of pip to install cli applications on you machine. ## Installation MacOS I am trying to get freshenv on homebrew-core but I need more stars on the repository for them to accept my pull request. The self hosted tap is available on the repo raiyanyahya/homebrew-freshenv. Install the freshenv python package from a self hosted homebrew tap. ```console brew tap raiyanyahya/freshenv brew install freshenv ``` ## Usage ```console Usage: fr [OPTIONS] COMMAND [ARGS]... A cli to provision and manage local developer environments. Options: --version Show the version and exit. --help Show this message and exit. Commands: build Build a custom freshenv flavour. check Check system compatibility for running freshenv. clean Remove all freshenv flavours and environments. cloud Save and share your custom environments on the cloud. flavours Show all available flavours for provisioning. provision Provision a developer environment. remove Remove a freshenv environment. start Resume working in an environment. view View local freshenv managed environments ``` ### Commands and Options **```flavours```** ```console Usage: fr flavours [OPTIONS] Show all available flavours for provisioning. Options: --help Show this message and exit. ``` **```provision```** ```console Usage: fr provision [OPTIONS] Provision a developer environment. Options: -f, --flavour TEXT The flavour of the environment. [default: base] -c, --command TEXT The command to execute at startup of environment. -p, --ports INTEGER List of ports to forward. [default: 3000] -n, --name TEXT Name of your environment. --help Show this message and exit. ``` **```start```** ```console Usage: fr start [OPTIONS] NAME Resume working in an environment. Options: --help Show this message and exit. ``` **```remove```** ```console Usage: fr remove [OPTIONS] NAME Remove a freshenv environment. Options: -f, --force Force remove an environment. --help Show this message and exit. ``` **```view```** ```console Usage: fr view [OPTIONS] View local freshenv managed environments. Options: --help Show this message and exit. ``` **```check```** ```console Usage: fr check [OPTIONS] Check system compatibility for running freshenv. Options: --help Show this message and exit. ``` **```clean```** ```console Usage: fr clean [OPTIONS] Remove all freshenv flavours and environments. Options: -f, --force Force remove freshenv flavours and environments. --help Show this message and exit. ``` **```build```** ```console Usage: fr build [OPTIONS] FLAVOUR Build a custom freshenv flavour. Options: -l, --logs Show build logs. --help Show this message and exit ``` **```cloud```** ```console Usage: fr cloud [OPTIONS] COMMAND [ARGS]... Save and share your custom environments on the cloud. Options: --help Show this message and exit. Commands: config View personal and freshenv cloud configurations. fetch Download an environment from the cloud. ls List cloud environments. push Upload an environment to the cloud. ``` ## License Freshenv is a free for open-source projects, however, if you are using the library for business and commercial projects you could choose to buy me a coffee. ## Contributing Contributions are always welcome! See `contributing.md` for ways to get started. Please adhere to this project's `code of conduct`. ## Contact Contact me through email at contact@freshenv.io ================================================ FILE: changelog.md ================================================ # Changelog All notable changes to this project will be documented in this file. ## [3.0.4] October 13, 2023 - Bumping dependecies ## [3.0.1] September 06, 2022 - Bumping dependecies and adding timeout to the request get function in provision.py ## [3.0.0] August 09, 2022 - Released the open source cloud features for freshenv. Developers can now push and fetch environments from personal aws s3 accounts. ## [2.0.0] July 12, 2022 - Moving to a different license. All cloud features will also be published under this new license. ## [1.2.4] - May 23, 2022 - Fixed issue with the build command since Jinja2 was escaping && and the install command wasnt working. ## [1.1.4] - May 23, 2022 - Removed the template folder and started fetching the templates from github. - Moved all flavours to one new repo called freshenv-flavours. - Exception handling in the build command. ## [1.1.2] - May 23, 2022 - fixed the manifest file to add the template/simple dockerfile. ## [1.1.1] - May 23, 2022 - fixed the manifest file to add the template/simple dockerfile. ## [1.1.0] - May 21, 2022 - Enabled custom flavours by adding build command. - removed the default value "zsh" to the --command/-c option to the provision command. - An empty freshenv config file will be automatically created if no config is found when running the build command. - Users can check build logs by passing the --logs/-l flag. - Created a simple dockerfile template for custom flavours. - Added new dependencies configparser and jinja2. - Updated readme and versions. ## [1.0.3] - May 6, 2022 ### Added - Released on producthunt - Added snap support - This is the main version ================================================ FILE: contributing.md ================================================ # Contributing When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change. Please note we have a code of conduct, please follow it in all your interactions with the project. ## Pull Request Process 1. Ensure any install or build dependencies are removed before the end of the layer when doing a build. 2. Update the README.md with details of changes to the interface, this includes new environment variables, exposed ports, useful file locations and container parameters. 3. Increase the version numbers in any examples files and the README.md to the new version that this Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). 4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you do not have permission to do that, you may request the second reviewer to merge it for you. ## Code of Conduct ### Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ### Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ### Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ### Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ### Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [INSERT EMAIL ADDRESS]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ### Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ ================================================ FILE: freshenv/__init__.py ================================================ __version__ = "1.0.0" ================================================ FILE: freshenv/build.py ================================================ from io import BytesIO from os import makedirs, path from configparser import ConfigParser, SectionProxy from rich import print from jinja2 import Environment import click from docker import APIClient, errors from freshenv.console import console from freshenv.provision import get_dockerfile_path from requests import exceptions homedir = path.expanduser("~") freshenv_config_location = homedir + "/.freshenv/freshenv" def create_dockerfile(base: str, install: str, cmd: str) -> str: contents = get_dockerfile_path("simple") template = Environment(autoescape=True).from_string(str(contents.decode("utf-8"))) build_template = template.render(base=base, install=install, cmd=cmd) return build_template def config_exists() -> bool: if not path.isfile(freshenv_config_location): return False return True def get_key_values_from_config(key: str) -> SectionProxy: config = ConfigParser() config.read(freshenv_config_location) return config[key] def key_exists(flavour: str) -> bool: config = ConfigParser() config.read(freshenv_config_location) if flavour not in config.sections(): return False return True def mandatory_keys_exists(flavour: str) -> bool: config = ConfigParser() config.read(freshenv_config_location) if "base" not in config[flavour]: return False if "install" not in config[flavour]: return False if "cmd" not in config[flavour]: return False return True def create_file(location: str) -> None: makedirs(path.dirname(location), exist_ok=True) open(location, "w", encoding="utf8").close() def run_checks(flavour: str) -> bool: if not config_exists(): print(f":card_index: No config file found. Creating an empty config at {freshenv_config_location}.") create_file(freshenv_config_location) return False if not key_exists(flavour): print(f":exclamation_mark:configuration for custom flavour {flavour} does not exist.") return False if not mandatory_keys_exists(flavour): print(":exclamation_mark: missing mandatory keys in configuration for custom environment {flavour}.") return False return True @click.command("build") @click.argument("flavour") @click.option('--logs', '-l', is_flag=True, help="Show build logs") def build(flavour: str, logs: bool) -> None: """Build a custom freshenv flavour.""" if not run_checks(flavour): return flavour_config = get_key_values_from_config(flavour) flavour_dockerfile = create_dockerfile(flavour_config["base"], flavour_config["install"], flavour_config["cmd"]) try: client = APIClient(base_url="unix://var/run/docker.sock") with console.status("Building custom flavour...", spinner="point"): for line in client.build(fileobj=BytesIO(flavour_dockerfile.encode("utf-8")), tag=f"raiyanyahya/freshenv-flavours/{flavour}", rm=True, pull=True, decode=True): if "errorDetail" in line: raise Exception(line["errorDetail"]["message"]) if logs: print(line) print(f":party_popper: Successfully built custom flavour {flavour}. You can provision it by running [bold]freshenv provision -f {flavour}[/bold].") except (errors.APIError, exceptions.HTTPError): print(":x: Custom flavour could not be built. Try again after cleaning up with [bold]fr clean --force [/bold]") except Exception as e: print(f":x: Custom flavour could not be built due to the error: {e}.") ================================================ FILE: freshenv/check.py ================================================ import click from docker import APIClient, errors from rich import print from freshenv.provision import build_environment, create_environment import dockerpty from requests import exceptions import os from sys import exit freshenv_test_image = "raiyanyahya/freshenv-flavours/freshenv-busybox" def check_docker(): try: client = APIClient(base_url="unix://var/run/docker.sock") print(":heavy_check_mark: Docker installed and running.") return client except Exception: print(":cross_mark_button: Docker not installed or running. ") exit(1) def remove_old_tests(client: APIClient): try: client.remove_container(container="freshenv_system_test",force=True) client.remove_image(image=freshenv_test_image, force=True) print(":heavy_check_mark: Test images removed.") except errors.APIError as e: if e.status_code == 404: print(":heavy_check_mark: No test images found. Moving on...") except Exception: print(":cross_mark_button: Could not remove freshenv test image. A freshenv test environment maybe still running.") exit(1) def run_test_environment(client: APIClient): try: container = create_environment(flavour="freshenv-busybox", command="ls", ports=["3000","4000"],name="system_test", client=client) dockerpty.start(client, container, stdout=open(os.devnull, "w", encoding="utf-8")) print(":heavy_check_mark: Succesfully provisioned test environment.") except (exceptions.HTTPError, errors.NotFound): build_environment(flavour="freshenv-busybox", command="ls", ports=["3000","4000"], name="system_test", client=client) print(":heavy_check_mark: Succesfully provisioned test environment.") except Exception: print(":cross_mark_button: Could not provision test environment.") exit(1) @click.command("check") def check() -> None: """Check system compatibility for running freshenv.""" client = check_docker() remove_old_tests(client) run_test_environment(client) remove_old_tests(client) print(":sunrise: All test passed. Everything looks good.") ================================================ FILE: freshenv/clean.py ================================================ import click from docker import APIClient, errors from rich import print @click.command("clean") @click.option('--force', '-f', is_flag=True, help="Force remove freshenv flavours and environments.") def clean(force: bool) -> None: """Remove all freshenv flavours and environments.""" try: client = APIClient(base_url="unix://var/run/docker.sock") freshenv_containers = client.containers(all=True, filters={"name": "freshenv_*"}) for container in freshenv_containers: client.remove_container(container=container['Id'], force=force) images_list = client.images(filters={"label": "maintainer=Raiyan Yahya "}) for image in images_list: client.remove_image(image=image['Id'], force=force) custom_images = client.images(filters={"label": "maintainer=Custom Environment"}) for custom_image in custom_images: client.remove_image(image=custom_image['Id'], force=force) print(":boom: freshenv flavours and environments removed.") except errors.APIError as e: if e.status_code == 409: print(":runner: Found a [bold green]running[/bold green] environment or a referenced flavour. Close the session first or use the [bold blue]--force[/bold blue] flag.") else: raise Exception(e) except errors.DockerException: print(":cross_mark_button: Docker not installed or running. ") except Exception as e: print(f"Unknown exception: {e}") ================================================ FILE: freshenv/cli.py ================================================ import click from freshenv import provision, view, start, remove, check, clean, flavours, build from freshenv.cloud import cloud @click.group() @click.version_option() def cli() -> None: """A cli to provision and manage local developer environments.""" cli.add_command(provision.provision) cli.add_command(view.view) cli.add_command(start.start) cli.add_command(remove.remove) cli.add_command(check.check) cli.add_command(clean.clean) cli.add_command(flavours.flavours) cli.add_command(build.build) cli.add_command(cloud.cloud) ================================================ FILE: freshenv/cloud/__init__.py ================================================ __version__ = "1.0.0" ================================================ FILE: freshenv/cloud/cloud.py ================================================ import click from freshenv.cloud.config import view_config from freshenv.cloud.fetch import fetch_environment from freshenv.cloud.ls import list_environments from freshenv.cloud.push import push_environment @click.group(name="cloud") def cloud() -> None: """Save and share your custom environments on the cloud.""" @cloud.command("ls") @click.argument("plan", default="personal", type=click.Choice(["freshenv", "personal"]), metavar="plan") def ls(plan: str) -> None: """List cloud environments.""" list_environments(plan) @cloud.command("push") @click.argument("environment_name") @click.argument("plan", default="personal",type=click.Choice(["freshenv", "personal"]), metavar="plan") def push(environment_name: str, plan: str) -> None: """Upload an environment to the cloud.""" push_environment(environment_name, plan) @cloud.command("fetch") @click.argument("environment_name") @click.argument("plan", default="personal",type=click.Choice(["freshenv", "personal"]), metavar="plan") def fetch(environment_name: str, plan: str) -> None: """Download an environment from the cloud.""" fetch_environment(environment_name, plan) @cloud.command("config") @click.argument("plan", default="personal", type=click.Choice(["freshenv", "personal"]), metavar="plan") def config(plan: str) -> None: """View personal and freshenv cloud configurations.""" view_config("cloud."+plan) ================================================ FILE: freshenv/cloud/config.py ================================================ from configparser import ConfigParser from os import path from typing import Dict from rich import pretty, print from freshenv.build import config_exists, create_file, key_exists, get_key_values_from_config homedir = path.expanduser("~") freshenv_config_location = homedir + "/.freshenv/freshenv" def check_run(config_type: str) -> bool: """Check if cloud configuration is valid.""" if not config_exists(): print(f":card_index: No config file found. Creating an empty config at {freshenv_config_location}.") create_file(freshenv_config_location) return False if not key_exists(config_type): print(f":exclamation_mark: A [bold]{config_type}[/bold] cloud has not been configured.") return False if not mandatory_keys_exists(config_type): print(f":exclamation_mark: missing mandatory keys in {config_type} configuration for cloud.") return False return True def mandatory_keys_exists(config_type: str) -> bool: config = ConfigParser() config.read(freshenv_config_location) if "personal" in config_type: if "provider" not in config[config_type]: return False if "aws_profile" not in config[config_type]: return False if "bucket" not in config[config_type]: return False elif "freshenv" in config_type: if "apikey" not in config[config_type]: return False else: return False return True def get_config(config_type: str) -> Dict[str, str]: if not check_run(config_type): return {} cloud_config = dict(get_key_values_from_config(config_type)) return cloud_config def view_config(config_type: str) -> None: """View personal and freshenv cloud configurations.""" cloud_config = get_config(config_type) if not cloud_config: return pretty.pprint(cloud_config) ================================================ FILE: freshenv/cloud/fetch.py ================================================ from docker import APIClient, errors from botocore import exceptions import boto3 from os import remove from freshenv.cloud.config import get_config from freshenv.start import start def fetch_environment_from_aws(environment_name: str, config_obj: dict) -> None: try: session = boto3.session.Session(profile_name=config_obj["aws_profile"]) s3_client = session.client('s3') s3_client.head_bucket(Bucket=config_obj["bucket"]) print(":link: Downloading environment from the cloud.") s3_client.download_file(config_obj["bucket"], environment_name + ".tar", environment_name + ".tar") print(":white_check_mark: Environment downloaded successfully.") except exceptions.ClientError as client_error: if client_error.response['Error']['Code'] == 'NoSuchBucket': print(":person_shrugging: Bucket does not exist.") except exceptions.ProfileNotFound: print(":person_shrugging: config profile does not exist.") except Exception as e: print(f"Unknown exception: {e}") def import_container(environment_name: str) -> None: try: client = APIClient(base_url="unix://var/run/docker.sock") client.import_image(environment_name + ".tar", environment_name) print(":white_check_mark: Environment imported successfully.") remove(environment_name + ".tar") except errors.APIError: print(":cold_sweat: Could not import environment. Please contact the developer or report an issue. :ticket:") except errors.DockerException: print(":cross_mark_button: Docker not installed or running. ") except Exception as e: print(f"Unknown exception: {e}") def fetch_environment(environment_name: str, plan: str) -> None: """Fetch a custom environment from the cloud.""" if plan == "personal": config_obj = get_config(f"cloud.{plan}") if not config_obj: return if config_obj and config_obj["provider"]: provider = config_obj["provider"] if provider == "aws": fetch_environment_from_aws(environment_name, config_obj) import_container(environment_name) start(environment_name) else: print(f":building_construction: {provider} provider not supported.") else: print(":person_facepalming: No provider configured.") else: print(":white_sun_with_small_cloud: The freshenv cloud plan is coming soon. Please visit the website for more information.") ================================================ FILE: freshenv/cloud/ls.py ================================================ import boto3 from botocore import exceptions from rich import print from rich.tree import Tree from freshenv.cloud.config import get_config def list_environments_from_aws(config_obj: dict) -> None: """List your custom cloud environments from AWS.""" try: session = boto3.session.Session(profile_name=config_obj["aws_profile"]) s3_client = session.client('s3') bucket_objs = s3_client.list_objects_v2(Bucket=config_obj["bucket"]) print(":link: Listing your cloud environments.") tree = Tree("Cloud Environments") if "Contents" in bucket_objs and len(bucket_objs["Contents"]) > 0: for obj in bucket_objs["Contents"]: tree.add(obj["Key"]) else: tree.add("No cloud environments found.") print(tree) except exceptions.ClientError as client_error: if client_error.response['Error']['Code'] == 'NoSuchBucket': print(":person_shrugging: Bucket does not exist.") except exceptions.ProfileNotFound: print(":person_shrugging: config profile does not exist.") def list_environments(plan: str) -> None: """List your custom cloud environments.""" if plan == "personal": config_obj = get_config(f"cloud.{plan}") if not config_obj: return if config_obj and config_obj["provider"]: provider = config_obj["provider"] if provider == "aws": list_environments_from_aws(config_obj) else: print(f":building_construction: {provider} provider not supported.") else: print(":person_facepalming: No provider configured.") else: print(":white_sun_with_small_cloud: The freshenv cloud plan is coming soon. Please visit the website for more information.") ================================================ FILE: freshenv/cloud/push.py ================================================ from docker import APIClient, errors from rich import print import boto3 from os import remove from botocore import exceptions from freshenv.cloud.config import get_config def export_environment(environment_name: str) -> str: try: client = APIClient(base_url="unix://var/run/docker.sock") exported_container = client.export(container=environment_name) with open(environment_name + ".tar", "wb") as f: for chunk in exported_container: f.write(chunk) return f.name except errors.NotFound: print(" :man_shrugging: Environment not found. Please check if the environment exists.") except errors.APIError: print(":cold_sweat: Could not export environment. Please contact the developer or report an issue. :ticket:") except errors.DockerException: print(":cross_mark_button: Docker not installed or running. ") except Exception as e: print(f"Unknown exception: {e}") return "" def remove_tar_file(file_name: str) -> None: remove(file_name) def push_environment_to_aws(environment_name: str, config_obj: dict) -> None: try: session = boto3.session.Session(profile_name=config_obj["aws_profile"]) s3_client = session.client('s3') s3_client.head_bucket(Bucket=config_obj["bucket"]) print(":link: Uploading environment to the cloud.") file_name = export_environment(environment_name) if file_name == "": return s3_client.upload_file(file_name, config_obj["bucket"], file_name) print(":white_check_mark: Environment uploaded successfully.") remove_tar_file(file_name) except exceptions.ClientError as client_error: if client_error.response['Error']['Code'] == 'NoSuchBucket': print(":person_shrugging: Bucket does not exist.") except exceptions.ProfileNotFound: print(":person_shrugging: config profile does not exist.") def push_environment(environment_name: str, plan: str) -> None: """Upload a custom environment to the cloud.""" if plan == "personal": config_obj = get_config(f"cloud.{plan}") if not config_obj: return if config_obj and config_obj["provider"]: provider = config_obj["provider"] if provider == "aws": push_environment_to_aws(environment_name, config_obj) else: print( f":building_construction: {provider} provider not supported.") else: print(":person_facepalming: No provider configured.") else: print(":white_sun_with_small_cloud: The freshenv cloud plan is coming soon. Please visit the website for more information.") ================================================ FILE: freshenv/console.py ================================================ from rich.console import Console console = Console() ================================================ FILE: freshenv/flavours.py ================================================ import click from rich import pretty, print from urllib.request import urlopen from json import loads from sys import exit @click.command("flavours") def flavours() -> None: """Show all available flavours for provisioning.""" gist_reponse = urlopen("https://api.github.com/gists/c4709c540a7c29616c771ab642ed2b8b") if gist_reponse.getcode() == 200: gist_data = loads(gist_reponse.read().decode("utf-8")) flavour_dict = loads(gist_data["files"]["fr-flavours.json"]["content"]) print(f":mag: Found {len(flavour_dict['fr-flavours'])} flavours:") pretty.pprint(flavour_dict["fr-flavours"]) else: print(":heavy_exclamation_mark: Could not fetch flavours.") exit(1) ================================================ FILE: freshenv/provision.py ================================================ from io import BytesIO from typing import Dict, List import click from docker import APIClient, errors import dockerpty from freshenv.util import PythonLiteralOption from freshenv.view import count_environents from freshenv.console import console from requests import exceptions, get from os import getcwd, path from rich import print client: APIClient = None current_directory = getcwd() folder = path.basename(current_directory) local_mount_binds = [f"{current_directory}:/home/{folder}:delegated"] google_dns = ["8.8.8.8"] def get_port_bindings(ports: List[str]) -> Dict: port_bindings = {} for port in ports: port_bindings[port] = port return port_bindings def create_environment(flavour: str, command: str, ports: List[str], name: str, client: APIClient, tty: bool=True, stdin_open: bool=True) -> Dict: if name == "index": name = str(count_environents() + 1) container = client.create_container( name=f"freshenv_{name}", image=f"raiyanyahya/freshenv-flavours/{flavour}", stdin_open=stdin_open, tty=tty, command=command, volumes=["/home"], ports=ports, use_config_proxy=True, host_config=client.create_host_config(port_bindings=get_port_bindings(ports),userns_mode="host",privileged=True,dns=google_dns,binds=local_mount_binds)) return container def pull_and_try_again(flavour: str, command: str, ports: List[str], name: str, client: APIClient): try: with console.status("Flavour doesnt exist locally. Fetching flavour...", spinner="dots8Bit"): client.pull(f"ghcr.io/raiyanyahya/{flavour}/{flavour}") container = create_environment(flavour, command, ports, name, client) dockerpty.start(client, container) except (errors.ImageNotFound, exceptions.HTTPError): print(":x: flavour doesnt exist") def get_dockerfile_path(flavour: str) -> bytes: req = get(f"https://raw.githubusercontent.com/raiyanyahya/freshenv-flavours/master/{flavour}", timeout=60) return req.text.encode('utf-8') def build_environment(flavour: str, command: str, ports: List[str], name: str, client: APIClient): try: with console.status("Flavour doesnt exist locally. Building flavour...", spinner="dots8Bit"): [line for line in client.build(fileobj=BytesIO(get_dockerfile_path(flavour=flavour)), tag=f"raiyanyahya/freshenv-flavours/{flavour}", rm=True, pull=True, decode=True)] # pylint: disable=expression-not-assigned container = create_environment(flavour, command, ports, name, client) dockerpty.start(client, container) except (errors.APIError, exceptions.HTTPError): print(":x: Flavour could not be built or found.") @click.command("provision") @click.option("--flavour","-f",default="base", help="The flavour of the environment.",show_default=True) @click.option("--command","-c", help="The command to execute at startup of environment.") @click.option("--ports","-p", default='["3000","4000"]', cls=PythonLiteralOption, help="String list of ports to forward.", show_default=True) @click.option("--name","-n", default="index", help="Name of your environment.", show_default=False) def provision(flavour: str, command: str, ports: List[str], name: str) -> None: """Provision a developer environment.""" try: client = APIClient(base_url="unix://var/run/docker.sock") container = create_environment(flavour, command, ports, name, client) dockerpty.start(client, container) except (errors.ImageNotFound,exceptions.HTTPError, errors.NotFound): build_environment(flavour, command, ports, name,client) #pull_and_try_again(flavour, command, ports, name,client) to be implemented in the cloud version except errors.DockerException: print(":cross_mark_button: Docker not installed or running. ") except Exception as e: print(f"Unknown exception: {e}") ================================================ FILE: freshenv/remove.py ================================================ import click from docker import APIClient, errors from rich import print @click.command("remove") @click.argument("name") @click.option('--force', '-f', is_flag=True, help="Force remove an environment.") def remove(name: str, force: bool) -> None: """Remove a freshenv environment.""" try: client = APIClient(base_url="unix://var/run/docker.sock") client.remove_container(container=name, force=force) print(f":boom: {name} environment removed.") except errors.NotFound: print(f":ghost: No freshenv environment called [bold]{name}[/bold] found.") except errors.APIError as e: if e.status_code == 409: print(f":runner: {name} is a [bold green]running[/bold green] environment. Close the session first or use the [bold blue]--force[/bold blue] flag.") else: raise Exception(e) except errors.DockerException: print(":cross_mark_button: Docker not installed or running. ") except Exception as e: print(f"Unknown exception: {e}") ================================================ FILE: freshenv/start.py ================================================ import click from docker import APIClient, errors import dockerpty from rich import print @click.command("start") @click.argument("name") def start(name: str) -> None: """Resume working in an environment.""" try: client = APIClient(base_url="unix://var/run/docker.sock") containers = client.containers(all=True, filters={"name": name}) if containers: dockerpty.start(client, containers[0]) else: print(f":ghost: No freshenv environment called [bold]{name}[/bold] found.") except errors.DockerException: print(":cross_mark_button: Docker not installed or running. ") except Exception as e: print(f"Unknown exception: {e}") ================================================ FILE: freshenv/util.py ================================================ from click import Option, BadParameter from ast import literal_eval class PythonLiteralOption(Option): """A utility class to convert a string to a python literal.""" def type_cast_value(self, ctx, value): try: return literal_eval(value) except BadParameter: raise BadParameter(value) ================================================ FILE: freshenv/view.py ================================================ from typing import Dict, List import click from docker import APIClient, errors from rich import print client: APIClient = None def count_environents() -> int: return len(get_list_environments()) def get_list_environments() -> List[Dict]: environment_list = [] client = APIClient(base_url="unix://var/run/docker.sock") environment_list = client.containers(all=True,filters={"label": "maintainer=Raiyan Yahya "}) custom_environment_list = client.containers(all=True,filters={"label": "maintainer=Custom Environment"}) environment_list = environment_list + custom_environment_list return environment_list @click.command("view") def view() -> None: """View local freshenv managed environments.""" try: container_list = get_list_environments() if not container_list: print(":computer: No freshenv environments found.") for container in container_list: if "Exited" in container.get("Status"): # type: ignore img = ":arrow_down: " else: img = ":arrow_forward: " print( img, "Name: [bold blue]" + container.get("Names")[0] + "[/bold blue]", # type: ignore "| Flavour: [bold blue]" + container.get("Image").split("/")[-1] + "[/bold blue]", # type: ignore "| State: [bold blue]" + container.get("Status") + "[/bold blue]", # type: ignore ) except errors.DockerException: print(":cross_mark_button: Docker not installed or running. ") except Exception as e: print(f"Unknown exception: {e}") ================================================ FILE: setup.py ================================================ from os.path import abspath, dirname, join, isfile from os import environ from setuptools import find_packages, setup import sys version_f = ".version" this_dir = abspath(dirname(__file__)) with open(join(this_dir, "README.md"), encoding="utf-8") as file: long_description = file.read() def get_version(): if isfile(version_f): with open(version_f) as version_file: version = version_file.read().strip() return version elif ( "build" in sys.argv or "egg_info" in sys.argv or "sdist" in sys.argv or "bdist_wheel" in sys.argv ): version = environ.get("VERSION", "0.0") # Avoid PEP 440 warning if "-SNAPSHOT" in version: version = version.replace("-SNAPSHOT", ".0") with open(version_f, "w+") as version_file: version_file.write(version) return version setup( name="freshenv", python_requires=">3.5", options={"bdist_wheel": {"universal": "1"}}, version=get_version(), description="A cli to provision and manage local developer environments.", long_description=long_description, long_description_content_type='text/markdown', url="https://github.com/raiyanyahya/freshenv", author="Raiyan Yahya", license="Mozilla Public License 2.0", author_email="raiyanyahyadeveloper@gmail.com", keywords=["cli","developer tools","productivity", "tools"], packages=find_packages(), install_requires=["click==8.1.3", "docker==7.0.0", "rich==13.3.1", "dockerpty==0.4.1", "urllib3==1.26.19", "configparser==5.3.0", "Jinja2==3.1.2", "boto3==1.26.83"], entry_points={"console_scripts": ["freshenv=freshenv.cli:cli","fr=freshenv.cli:cli"]}, ) ================================================ FILE: snap/snapcraft.yaml ================================================ name: freshenv version: 3.0.4 summary: A cli to provision and manage local developer environments. description: | A command line application to provision and manage local developer environments. Build and develop your projects in completely isolated environments. Save, switch and restart your environments. Choose from a wide variety of flavours to get the developer tools you need. base: core20 contact: contact@freshenv.io website: https://freshenv.io source-code: https://github.com/raiyanyahya/freshenv issues: https://github.com/raiyanyahya/freshenv/issues architectures: - build-on: [arm64, armhf, amd64] grade: stable confinement: strict plugs: docker-executables: content: docker-executables default-provider: docker interface: content target: docker-env apps: freshenv: command: bin/freshenv plugs: [network, docker,docker-executables] parts: freshenv: plugin: python source: . ================================================ FILE: tox.ini ================================================ [tox] envlist = py38,mypy [testenv] deps = pylint commands = pylint freshenv --disable=C0301,C0114,C0116,C0103,W0603,W0622,C0411,C0304,W0707,R0801,W0703,R1721,W0621,R1732,R0913,W0719 [testenv:mypy] skip_install = true basepython = python3.8 deps = mypy types-requests commands = mypy --exclude build --ignore-missing-imports --pretty .