[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: raiyanyahya\n\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  - package-ecosystem: \"pip\" # See documentation for possible values\n    directory: \"/\" # Location of package manifests\n    schedule:\n      interval: \"daily\"\n"
  },
  {
    "path": ".github/workflows/Build-Test.yml",
    "content": "\nname: Build Test\non:\n  pull_request:\n    branches: [ master ]\n  push:\n    branches: [ master ]\n  workflow_dispatch:\n\njobs:\n  Build:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2 \n      - name: setup python\n        uses: actions/setup-python@v2\n        with:\n            python-version: 3.8\n\n      - name: build\n        run: python3 setup.py install\n  Test:\n      needs: [Build]\n      runs-on: ubuntu-latest\n      steps:\n        - uses: actions/checkout@v2\n        - name: setup python\n          uses: actions/setup-python@v2\n          with:\n            python-version: 3.8\n        - name: test\n          run: |\n            pip3 install tox\n            tox -r\n"
  },
  {
    "path": ".github/workflows/Integration-Tests.yml",
    "content": "name: Integration Tests\non:\n  pull_request:\n    branches: [ master ]\n  workflow_dispatch:\n\njobs:\n    integrations-tests:\n      strategy:\n        matrix:\n          os: [macos-latest, ubuntu-latest]\n      runs-on: ${{ matrix.os }}\n      steps:\n        - uses: actions/checkout@v2\n        - name: setup python\n          uses: actions/setup-python@v2\n          with:\n            python-version: 3.8\n        - uses: docker-practice/actions-setup-docker@master\n        - run: |\n               set -x\n               docker version\n               python3 -m pip install --upgrade pip\n               pip3 install setuptools wheel twine\n               pip3 install .\n               fr check\n               fr provision -c ls\n               fr view\n               fr remove freshenv_1\n               fr clean\n               fr flavours\n               fr build testenv\n               echo \"[testenv]\" >> ~/.freshenv/freshenv\n               echo \"base=ubuntu\" >> ~/.freshenv/freshenv\n               echo \"install=apt update -y && apt upgrade -y && apt install snapd -y\" >> ~/.freshenv/freshenv\n               echo \"cmd=bash\" >> ~/.freshenv/freshenv\n               fr build testenv\n               fr cloud config\n"
  },
  {
    "path": ".github/workflows/Package-Release.yml",
    "content": "name: Package Release\non:\n  workflow_dispatch:\n\njobs:\n  deploy:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - name: setup python\n        uses: actions/setup-python@v2\n        with:\n          python-version: 3.8\n      - name: Install dependencies\n        run: |\n          python3 -m pip install --upgrade pip\n          pip3 install setuptools wheel twine\n          sudo snap install snapcraft --classic\n          sudo snap install multipass\n      - name: Build and publish\n        env:\n          TWINE_USERNAME: __token__\n          TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}\n          SNAP_TOKEN: ${{ secrets.SNAPCRAFT_SECRET }}\n          SNAPCRAFT_BUILD_ENVIRONMENT: host\n        run: |\n          echo \"$SNAP_TOKEN\" | snapcraft login --with -\n          snapcraft\n          snapcraft upload --release=stable *.snap\n          python3 setup.py sdist bdist_wheel\n          twine upload dist/*\n\n"
  },
  {
    "path": ".github/workflows/codeql-analysis.yml",
    "content": "name: \"CodeQL\"\n\non:\n  push:\n    branches: [ master ]\n  pull_request:\n    branches: [ master ]\n\njobs:\n  analyze:\n    name: Analyze\n    runs-on: ubuntu-latest\n    permissions:\n      actions: read\n      contents: read\n      security-events: write\n\n    strategy:\n      fail-fast: false\n      matrix:\n        language: [ 'python' ]\n\n    steps:\n    - name: Checkout repository\n      uses: actions/checkout@v2\n\n    # Initializes the CodeQL tools for scanning.\n    - name: Initialize CodeQL\n      uses: github/codeql-action/init@v1\n      with:\n        languages: ${{ matrix.language }}\n        # If you wish to specify custom queries, you can do so here or in a config file.\n        # By default, queries listed here will override any specified in a config file.\n        # Prefix the list here with \"+\" to use these queries and those in the config file.\n        # queries: ./path/to/local/query, your-org/your-repo/queries@main\n\n    # Autobuild attempts to build any compiled languages  (C/C++, C#, or Java).\n    # If this step fails, then you should remove it and run the build manually (see below)\n    - name: Autobuild\n      uses: github/codeql-action/autobuild@v1\n\n    # ℹ️ Command-line programs to run using the OS shell.\n    # 📚 https://git.io/JvXDl\n\n    # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines\n    #    and modify them (or add more) to build your code if your project\n    #    uses a compiled language\n\n    #- run: |\n    #   make bootstrap\n    #   make release\n\n    - name: Perform CodeQL Analysis\n      uses: github/codeql-action/analyze@v1\n"
  },
  {
    "path": ".gitignore",
    "content": "# Created by .ignore support plugin (hsz.mobi)\n### Python template\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# snap\nfreshenv_*\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n.pytest_cache/\n*.tar\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\n.idea\nenv.bak/\nvenv.bak/\n.idea/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n"
  },
  {
    "path": ".version",
    "content": "3.0.4\n"
  },
  {
    "path": "LICENSE",
    "content": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\"\n    means each individual or legal entity that creates, contributes to\n    the creation of, or owns Covered Software.\n\n1.2. \"Contributor Version\"\n    means the combination of the Contributions of others (if any) used\n    by a Contributor and that particular Contributor's Contribution.\n\n1.3. \"Contribution\"\n    means Covered Software of a particular Contributor.\n\n1.4. \"Covered Software\"\n    means Source Code Form to which the initial Contributor has attached\n    the notice in Exhibit A, the Executable Form of such Source Code\n    Form, and Modifications of such Source Code Form, in each case\n    including portions thereof.\n\n1.5. \"Incompatible With Secondary Licenses\"\n    means\n\n    (a) that the initial Contributor has attached the notice described\n        in Exhibit B to the Covered Software; or\n\n    (b) that the Covered Software was made available under the terms of\n        version 1.1 or earlier of the License, but not also under the\n        terms of a Secondary License.\n\n1.6. \"Executable Form\"\n    means any form of the work other than Source Code Form.\n\n1.7. \"Larger Work\"\n    means a work that combines Covered Software with other material, in\n    a separate file or files, that is not Covered Software.\n\n1.8. \"License\"\n    means this document.\n\n1.9. \"Licensable\"\n    means having the right to grant, to the maximum extent possible,\n    whether at the time of the initial grant or subsequently, any and\n    all of the rights conveyed by this License.\n\n1.10. \"Modifications\"\n    means any of the following:\n\n    (a) any file in Source Code Form that results from an addition to,\n        deletion from, or modification of the contents of Covered\n        Software; or\n\n    (b) any new file in Source Code Form that contains any Covered\n        Software.\n\n1.11. \"Patent Claims\" of a Contributor\n    means any patent claim(s), including without limitation, method,\n    process, and apparatus claims, in any patent Licensable by such\n    Contributor that would be infringed, but for the grant of the\n    License, by the making, using, selling, offering for sale, having\n    made, import, or transfer of either its Contributions or its\n    Contributor Version.\n\n1.12. \"Secondary License\"\n    means either the GNU General Public License, Version 2.0, the GNU\n    Lesser General Public License, Version 2.1, the GNU Affero General\n    Public License, Version 3.0, or any later versions of those\n    licenses.\n\n1.13. \"Source Code Form\"\n    means the form of the work preferred for making modifications.\n\n1.14. \"You\" (or \"Your\")\n    means an individual or a legal entity exercising rights under this\n    License. For legal entities, \"You\" includes any entity that\n    controls, is controlled by, or is under common control with You. For\n    purposes of this definition, \"control\" means (a) the power, direct\n    or indirect, to cause the direction or management of such entity,\n    whether by contract or otherwise, or (b) ownership of more than\n    fifty percent (50%) of the outstanding shares or beneficial\n    ownership of such entity.\n\n2. License Grants and Conditions\n--------------------------------\n\n2.1. Grants\n\nEach Contributor hereby grants You a world-wide, royalty-free,\nnon-exclusive license:\n\n(a) under intellectual property rights (other than patent or trademark)\n    Licensable by such Contributor to use, reproduce, make available,\n    modify, display, perform, distribute, and otherwise exploit its\n    Contributions, either on an unmodified basis, with Modifications, or\n    as part of a Larger Work; and\n\n(b) under Patent Claims of such Contributor to make, use, sell, offer\n    for sale, have made, import, and otherwise transfer either its\n    Contributions or its Contributor Version.\n\n2.2. Effective Date\n\nThe licenses granted in Section 2.1 with respect to any Contribution\nbecome effective for each Contribution on the date the Contributor first\ndistributes such Contribution.\n\n2.3. Limitations on Grant Scope\n\nThe licenses granted in this Section 2 are the only rights granted under\nthis License. No additional rights or licenses will be implied from the\ndistribution or licensing of Covered Software under this License.\nNotwithstanding Section 2.1(b) above, no patent license is granted by a\nContributor:\n\n(a) for any code that a Contributor has removed from Covered Software;\n    or\n\n(b) for infringements caused by: (i) Your and any other third party's\n    modifications of Covered Software, or (ii) the combination of its\n    Contributions with other software (except as part of its Contributor\n    Version); or\n\n(c) under Patent Claims infringed by Covered Software in the absence of\n    its Contributions.\n\nThis License does not grant any rights in the trademarks, service marks,\nor logos of any Contributor (except as may be necessary to comply with\nthe notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\nNo Contributor makes additional grants as a result of Your choice to\ndistribute the Covered Software under a subsequent version of this\nLicense (see Section 10.2) or under the terms of a Secondary License (if\npermitted under the terms of Section 3.3).\n\n2.5. Representation\n\nEach Contributor represents that the Contributor believes its\nContributions are its original creation(s) or it has sufficient rights\nto grant the rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\nThis License is not intended to limit any rights You have under\napplicable copyright doctrines of fair use, fair dealing, or other\nequivalents.\n\n2.7. Conditions\n\nSections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted\nin Section 2.1.\n\n3. Responsibilities\n-------------------\n\n3.1. Distribution of Source Form\n\nAll distribution of Covered Software in Source Code Form, including any\nModifications that You create or to which You contribute, must be under\nthe terms of this License. You must inform recipients that the Source\nCode Form of the Covered Software is governed by the terms of this\nLicense, and how they can obtain a copy of this License. You may not\nattempt to alter or restrict the recipients' rights in the Source Code\nForm.\n\n3.2. Distribution of Executable Form\n\nIf You distribute Covered Software in Executable Form then:\n\n(a) such Covered Software must also be made available in Source Code\n    Form, as described in Section 3.1, and You must inform recipients of\n    the Executable Form how they can obtain a copy of such Source Code\n    Form by reasonable means in a timely manner, at a charge no more\n    than the cost of distribution to the recipient; and\n\n(b) You may distribute such Executable Form under the terms of this\n    License, or sublicense it under different terms, provided that the\n    license for the Executable Form does not attempt to limit or alter\n    the recipients' rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\nYou may create and distribute a Larger Work under terms of Your choice,\nprovided that You also comply with the requirements of this License for\nthe Covered Software. If the Larger Work is a combination of Covered\nSoftware with a work governed by one or more Secondary Licenses, and the\nCovered Software is not Incompatible With Secondary Licenses, this\nLicense permits You to additionally distribute such Covered Software\nunder the terms of such Secondary License(s), so that the recipient of\nthe Larger Work may, at their option, further distribute the Covered\nSoftware under the terms of either this License or such Secondary\nLicense(s).\n\n3.4. Notices\n\nYou may not remove or alter the substance of any license notices\n(including copyright notices, patent notices, disclaimers of warranty,\nor limitations of liability) contained within the Source Code Form of\nthe Covered Software, except that You may alter any license notices to\nthe extent required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\nYou may choose to offer, and to charge a fee for, warranty, support,\nindemnity or liability obligations to one or more recipients of Covered\nSoftware. However, You may do so only on Your own behalf, and not on\nbehalf of any Contributor. You must make it absolutely clear that any\nsuch warranty, support, indemnity, or liability obligation is offered by\nYou alone, and You hereby agree to indemnify every Contributor for any\nliability incurred by such Contributor as a result of warranty, support,\nindemnity or liability terms You offer. You may include additional\ndisclaimers of warranty and limitations of liability specific to any\njurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n---------------------------------------------------\n\nIf it is impossible for You to comply with any of the terms of this\nLicense with respect to some or all of the Covered Software due to\nstatute, judicial order, or regulation then You must: (a) comply with\nthe terms of this License to the maximum extent possible; and (b)\ndescribe the limitations and the code they affect. Such description must\nbe placed in a text file included with all distributions of the Covered\nSoftware under this License. Except to the extent prohibited by statute\nor regulation, such description must be sufficiently detailed for a\nrecipient of ordinary skill to be able to understand it.\n\n5. Termination\n--------------\n\n5.1. The rights granted under this License will terminate automatically\nif You fail to comply with any of its terms. However, if You become\ncompliant, then the rights granted under this License from a particular\nContributor are reinstated (a) provisionally, unless and until such\nContributor explicitly and finally terminates Your grants, and (b) on an\nongoing basis, if such Contributor fails to notify You of the\nnon-compliance by some reasonable means prior to 60 days after You have\ncome back into compliance. Moreover, Your grants from a particular\nContributor are reinstated on an ongoing basis if such Contributor\nnotifies You of the non-compliance by some reasonable means, this is the\nfirst time You have received notice of non-compliance with this License\nfrom such Contributor, and You become compliant prior to 30 days after\nYour receipt of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\ninfringement claim (excluding declaratory judgment actions,\ncounter-claims, and cross-claims) alleging that a Contributor Version\ndirectly or indirectly infringes any patent, then the rights granted to\nYou by any and all Contributors for the Covered Software under Section\n2.1 of this License shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all\nend user license agreements (excluding distributors and resellers) which\nhave been validly granted by You or Your distributors under this License\nprior to termination shall survive termination.\n\n************************************************************************\n*                                                                      *\n*  6. Disclaimer of Warranty                                           *\n*  -------------------------                                           *\n*                                                                      *\n*  Covered Software is provided under this License on an \"as is\"       *\n*  basis, without warranty of any kind, either expressed, implied, or  *\n*  statutory, including, without limitation, warranties that the       *\n*  Covered Software is free of defects, merchantable, fit for a        *\n*  particular purpose or non-infringing. The entire risk as to the     *\n*  quality and performance of the Covered Software is with You.        *\n*  Should any Covered Software prove defective in any respect, You     *\n*  (not any Contributor) assume the cost of any necessary servicing,   *\n*  repair, or correction. This disclaimer of warranty constitutes an   *\n*  essential part of this License. No use of any Covered Software is   *\n*  authorized under this License except under this disclaimer.         *\n*                                                                      *\n************************************************************************\n\n************************************************************************\n*                                                                      *\n*  7. Limitation of Liability                                          *\n*  --------------------------                                          *\n*                                                                      *\n*  Under no circumstances and under no legal theory, whether tort      *\n*  (including negligence), contract, or otherwise, shall any           *\n*  Contributor, or anyone who distributes Covered Software as          *\n*  permitted above, be liable to You for any direct, indirect,         *\n*  special, incidental, or consequential damages of any character      *\n*  including, without limitation, damages for lost profits, loss of    *\n*  goodwill, work stoppage, computer failure or malfunction, or any    *\n*  and all other commercial damages or losses, even if such party      *\n*  shall have been informed of the possibility of such damages. This   *\n*  limitation of liability shall not apply to liability for death or   *\n*  personal injury resulting from such party's negligence to the       *\n*  extent applicable law prohibits such limitation. Some               *\n*  jurisdictions do not allow the exclusion or limitation of           *\n*  incidental or consequential damages, so this exclusion and          *\n*  limitation may not apply to You.                                    *\n*                                                                      *\n************************************************************************\n\n8. Litigation\n-------------\n\nAny litigation relating to this License may be brought only in the\ncourts of a jurisdiction where the defendant maintains its principal\nplace of business and such litigation shall be governed by laws of that\njurisdiction, without reference to its conflict-of-law provisions.\nNothing in this Section shall prevent a party's ability to bring\ncross-claims or counter-claims.\n\n9. Miscellaneous\n----------------\n\nThis License represents the complete agreement concerning the subject\nmatter hereof. If any provision of this License is held to be\nunenforceable, such provision shall be reformed only to the extent\nnecessary to make it enforceable. Any law or regulation which provides\nthat the language of a contract shall be construed against the drafter\nshall not be used to construe this License against a Contributor.\n\n10. Versions of the License\n---------------------------\n\n10.1. New Versions\n\nMozilla Foundation is the license steward. Except as provided in Section\n10.3, no one other than the license steward has the right to modify or\npublish new versions of this License. Each version will be given a\ndistinguishing version number.\n\n10.2. Effect of New Versions\n\nYou may distribute the Covered Software under the terms of the version\nof the License under which You originally received the Covered Software,\nor under the terms of any subsequent version published by the license\nsteward.\n\n10.3. Modified Versions\n\nIf you create software not governed by this License, and you want to\ncreate a new license for such software, you may create and use a\nmodified version of this License if you rename the license and remove\nany references to the name of the license steward (except to note that\nsuch modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary\nLicenses\n\nIf You choose to distribute Source Code Form that is Incompatible With\nSecondary Licenses under the terms of this version of the License, the\nnotice described in Exhibit B of this License must be attached.\n\nExhibit A - Source Code Form License Notice\n-------------------------------------------\n\n  This Source Code Form is subject to the terms of the Mozilla Public\n  License, v. 2.0. If a copy of the MPL was not distributed with this\n  file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular\nfile, then You may include the notice in a location (such as a LICENSE\nfile in a relevant directory) where a recipient would be likely to look\nfor such a notice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - \"Incompatible With Secondary Licenses\" Notice\n---------------------------------------------------------\n\n  This Source Code Form is \"Incompatible With Secondary Licenses\", as\n  defined by the Mozilla Public License, v. 2.0.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include .version\nexclude snap\nexclude snap/snapcraft.yml"
  },
  {
    "path": "README.md",
    "content": "\n[![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&amp;utm_medium=referral&amp;utm_content=raiyanyahya/freshenv&amp;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)\n [![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/)\n\n\n# Freshenv 🥗\n```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.\\\n\\\n<kbd>\n[![download-17adc07640182f121.gif](https://s10.gifyu.com/images/download-17adc07640182f121.gif)](https://gifyu.com/image/Sbsim)\n</kbd>\n## The Story\n\nThis is a solution to a problem I have always had. I like my system to be clean, minimal and structured. \nIt gets quite tricky to manage multiple projects on my on machine, projects tend to gather and are placed everywhere. \nOvertime managing system wide dependencies becomes a problem. It is quite easy to mess up a system setting or to \nkeep track of a package I wont need tomorrow. This is why I built ```freshenv```. It is a command line application\n which helps developers in running and managing completely isolated developer environments locally. \nIt fetches and lets you run environment flavours in the form of docker containers\nwhich are preconfigured with tools and packages developer needs everyday. Read about the usage below. \nI imagine it would help developers like me. I hope you like it.\n\n## Flavours\n\n```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.\n\n## Custom Environments\n\nFreshenv 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.\n\n```yml\n[MyEnv]\nbase=ubuntu\ninstall=apt update -y && apt upgrade -y && apt install arandr\ncmd=bash\n```\n\n## Cloud Environments\n\nFreshenv 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.\n\n```yml\n[cloud.personal]\nprovider=aws\nbucket=myenvironments\naws_profile=default\n```\n\n\n## Installation Linux\n\nI recommend using the snap package manager to install freshenv. \n\n```console\n  snap install freshenv \n  \n  # give it access to the docker interface\n  snap connect freshenv:docker docker:docker-daemon \n```\n\nIf you dont have or use snap, install the freshenv python package from pypi. \n\n```console\n  pip install freshenv\n```\n\nI would recommend using pipx instead of pip to install cli applications on you machine.\n\n## Installation MacOS\n\nI 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.\n\n```console\n  brew tap raiyanyahya/freshenv\n  brew install freshenv\n```\n\n## Usage\n\n```console\nUsage: fr [OPTIONS] COMMAND [ARGS]...\n\n  A cli to provision and manage local developer environments.\n\nOptions:\n  --version  Show the version and exit.\n  --help     Show this message and exit.\n\nCommands:\n  build      Build a custom freshenv flavour.\n  check      Check system compatibility for running freshenv.\n  clean      Remove all freshenv flavours and environments.\n  cloud      Save and share your custom environments on the cloud.\n  flavours   Show all available flavours for provisioning.\n  provision  Provision a developer environment.\n  remove     Remove a freshenv environment.\n  start      Resume working in an environment.\n  view       View local freshenv managed environments\n```\n\n### Commands and Options\n\n**```flavours```**\n```console\nUsage: fr flavours [OPTIONS]\n\n  Show all available flavours for provisioning.\n\nOptions:\n  --help  Show this message and exit.\n```\n\n\n**```provision```**\n```console\nUsage: fr provision [OPTIONS]\n\n  Provision a developer environment.\n\nOptions:\n  -f, --flavour TEXT   The flavour of the environment.  [default: base]\n  -c, --command TEXT   The command to execute at startup of environment.\n  -p, --ports INTEGER  List of ports to forward.  [default: 3000]\n  -n, --name TEXT      Name of your environment.\n  --help               Show this message and exit.\n```\n\n\n**```start```**\n```console\nUsage: fr start [OPTIONS] NAME\n\n  Resume working in an environment.\n\nOptions:\n  --help  Show this message and exit.\n```\n\n**```remove```**\n```console\nUsage: fr remove [OPTIONS] NAME\n\n  Remove a freshenv environment.\n\nOptions:\n  -f, --force      Force remove an environment.\n  --help           Show this message and exit.\n```\n\n**```view```**\n```console\nUsage: fr view [OPTIONS]\n\n  View local freshenv managed environments.\n\nOptions:\n  --help  Show this message and exit.\n```\n\n**```check```**\n```console\nUsage: fr check [OPTIONS]\n\n  Check system compatibility for running freshenv.\n\nOptions:\n  --help  Show this message and exit.\n```\n\n**```clean```**\n```console\nUsage: fr clean [OPTIONS]\n\n  Remove all freshenv flavours and environments.\n\nOptions:\n  -f, --force  Force remove freshenv flavours and environments.\n  --help       Show this message and exit.\n```\n\n**```build```**\n```console\nUsage: fr build [OPTIONS] FLAVOUR\n\n  Build a custom freshenv flavour.\n\nOptions:\n  -l, --logs  Show build logs.\n  --help      Show this message and exit\n```\n\n**```cloud```**\n```console\nUsage: fr cloud [OPTIONS] COMMAND [ARGS]...\n\n  Save and share your custom environments on the cloud.\n\nOptions:\n  --help  Show this message and exit.\n\nCommands:\n  config  View personal and freshenv cloud configurations.\n  fetch   Download an environment from the cloud.\n  ls      List cloud environments.\n  push    Upload an environment to the cloud.\n```\n\n## License\n\nFreshenv 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.\n\n## Contributing\n\nContributions are always welcome!\n\nSee `contributing.md` for ways to get started. Please adhere to this project's `code of conduct`.\n\n\n## Contact\n\nContact me through email at contact@freshenv.io\n"
  },
  {
    "path": "changelog.md",
    "content": "# Changelog\nAll notable changes to this project will be documented in this file.\n\n\n## [3.0.4] October 13, 2023\n- Bumping dependecies \n\n## [3.0.1] September 06, 2022\n- Bumping dependecies and adding timeout to the request get function in provision.py\n\n## [3.0.0] August 09, 2022\n- Released the open source cloud features for freshenv. Developers can now push and fetch environments from personal aws s3 accounts.\n  \n## [2.0.0] July 12, 2022\n- Moving to a different license. All cloud features will also be published under this new license.\n\n## [1.2.4] - May 23, 2022\n- Fixed issue with the build command since Jinja2 was escaping && and the install command wasnt working.\n\n## [1.1.4] - May 23, 2022\n- Removed the template folder and started fetching the templates from github.\n- Moved all flavours to one new repo called freshenv-flavours.\n- Exception handling in the build command.\n\n## [1.1.2] - May 23, 2022\n- fixed the manifest file to add the template/simple dockerfile.\n\n## [1.1.1] - May 23, 2022\n- fixed the manifest file to add the template/simple dockerfile.\n\n## [1.1.0] - May 21, 2022\n- Enabled custom flavours by adding build command.\n- removed the default value \"zsh\" to the --command/-c option to the provision command.\n- An empty freshenv config file will be automatically created if no config is found when running the build command.\n- Users can check build logs by passing the --logs/-l flag.\n- Created a simple dockerfile template for custom flavours.\n- Added new dependencies configparser and jinja2.\n- Updated readme and versions.\n\n## [1.0.3] - May 6, 2022\n### Added\n- Released on producthunt\n- Added snap support\n- This is the main version\n"
  },
  {
    "path": "contributing.md",
    "content": "# Contributing\n\nWhen contributing to this repository, please first discuss the change you wish to make via issue,\nemail, or any other method with the owners of this repository before making a change. \n\nPlease note we have a code of conduct, please follow it in all your interactions with the project.\n\n## Pull Request Process\n\n1. Ensure any install or build dependencies are removed before the end of the layer when doing a \n   build.\n2. Update the README.md with details of changes to the interface, this includes new environment \n   variables, exposed ports, useful file locations and container parameters.\n3. Increase the version numbers in any examples files and the README.md to the new version that this\n   Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/).\n4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you \n   do not have permission to do that, you may request the second reviewer to merge it for you.\n\n## Code of Conduct\n\n### Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and maintainers pledge to making participation in our project and\nour community a harassment-free experience for everyone, regardless of age, body\nsize, disability, ethnicity, gender identity and expression, level of experience,\nnationality, personal appearance, race, religion, or sexual identity and\norientation.\n\n### Our Standards\n\nExamples of behavior that contributes to creating a positive environment\ninclude:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or\nadvances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic\n  address, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n### Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable\nbehavior and are expected to take appropriate and fair corrective action in\nresponse to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or\nreject comments, commits, code, wiki edits, issues, and other contributions\nthat are not aligned to this Code of Conduct, or to ban temporarily or\npermanently any contributor for other behaviors that they deem inappropriate,\nthreatening, offensive, or harmful.\n\n### Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces\nwhen an individual is representing the project or its community. Examples of\nrepresenting a project or community include using an official project e-mail\naddress, posting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event. Representation of a project may be\nfurther defined and clarified by project maintainers.\n\n### Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported by contacting the project team at [INSERT EMAIL ADDRESS]. All\ncomplaints will be reviewed and investigated and will result in a response that\nis deemed necessary and appropriate to the circumstances. The project team is\nobligated to maintain confidentiality with regard to the reporter of an incident.\nFurther details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good\nfaith may face temporary or permanent repercussions as determined by other\nmembers of the project's leadership.\n\n### Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\navailable at [http://contributor-covenant.org/version/1/4][version]\n\n[homepage]: http://contributor-covenant.org\n[version]: http://contributor-covenant.org/version/1/4/"
  },
  {
    "path": "freshenv/__init__.py",
    "content": "__version__ = \"1.0.0\"\n"
  },
  {
    "path": "freshenv/build.py",
    "content": "from io import BytesIO\nfrom os import makedirs, path\nfrom configparser import ConfigParser, SectionProxy\nfrom rich import print\nfrom jinja2 import Environment\nimport click\nfrom docker import APIClient, errors\nfrom freshenv.console import console\nfrom freshenv.provision import get_dockerfile_path\nfrom requests import exceptions\n\n\nhomedir = path.expanduser(\"~\")\nfreshenv_config_location = homedir + \"/.freshenv/freshenv\"\n\n\ndef create_dockerfile(base: str, install: str, cmd: str) -> str:\n    contents = get_dockerfile_path(\"simple\")\n    template = Environment(autoescape=True).from_string(str(contents.decode(\"utf-8\")))\n    build_template = template.render(base=base, install=install, cmd=cmd)\n    return build_template\n\n\ndef config_exists() -> bool:\n    if not path.isfile(freshenv_config_location):\n        return False\n    return True\n\n\ndef get_key_values_from_config(key: str) -> SectionProxy:\n    config = ConfigParser()\n    config.read(freshenv_config_location)\n    return config[key]\n\n\ndef key_exists(flavour: str) -> bool:\n    config = ConfigParser()\n    config.read(freshenv_config_location)\n    if flavour not in config.sections():\n        return False\n    return True\n\n\ndef mandatory_keys_exists(flavour: str) -> bool:\n    config = ConfigParser()\n    config.read(freshenv_config_location)\n    if \"base\" not in config[flavour]:\n        return False\n    if \"install\" not in config[flavour]:\n        return False\n    if \"cmd\" not in config[flavour]:\n        return False\n    return True\n\n\ndef create_file(location: str) -> None:\n    makedirs(path.dirname(location), exist_ok=True)\n    open(location, \"w\", encoding=\"utf8\").close()\n\n\ndef run_checks(flavour: str) -> bool:\n    if not config_exists():\n        print(f\":card_index: No config file found. Creating an empty config at {freshenv_config_location}.\")\n        create_file(freshenv_config_location)\n        return False\n    if not key_exists(flavour):\n        print(f\":exclamation_mark:configuration for custom flavour {flavour} does not exist.\")\n        return False\n    if not mandatory_keys_exists(flavour):\n        print(\":exclamation_mark: missing mandatory keys in configuration for custom environment {flavour}.\")\n        return False\n    return True\n\n@click.command(\"build\")\n@click.argument(\"flavour\")\n@click.option('--logs', '-l', is_flag=True, help=\"Show build logs\")\ndef build(flavour: str, logs: bool) -> None:\n    \"\"\"Build a custom freshenv flavour.\"\"\"\n    if not run_checks(flavour):\n        return\n\n    flavour_config = get_key_values_from_config(flavour)\n    flavour_dockerfile = create_dockerfile(flavour_config[\"base\"], flavour_config[\"install\"], flavour_config[\"cmd\"])\n    try:\n        client = APIClient(base_url=\"unix://var/run/docker.sock\")\n        with console.status(\"Building custom flavour...\", spinner=\"point\"):\n            for line in client.build(fileobj=BytesIO(flavour_dockerfile.encode(\"utf-8\")), tag=f\"raiyanyahya/freshenv-flavours/{flavour}\", rm=True, pull=True, decode=True):\n                if \"errorDetail\" in line:\n                    raise Exception(line[\"errorDetail\"][\"message\"])\n                if logs:\n                    print(line)\n        print(f\":party_popper: Successfully built custom flavour {flavour}. You can provision it by running [bold]freshenv provision -f {flavour}[/bold].\")\n    except (errors.APIError, exceptions.HTTPError):\n        print(\":x: Custom flavour could not be built. Try again after cleaning up with [bold]fr clean --force [/bold]\")\n    except Exception as e:\n        print(f\":x: Custom flavour could not be built due to the error: {e}.\")"
  },
  {
    "path": "freshenv/check.py",
    "content": "import click\nfrom docker import APIClient, errors\nfrom rich import print\nfrom freshenv.provision import build_environment, create_environment\nimport dockerpty\nfrom requests import exceptions\nimport os\nfrom sys import exit\nfreshenv_test_image = \"raiyanyahya/freshenv-flavours/freshenv-busybox\"\n\ndef check_docker():\n    try:\n        client = APIClient(base_url=\"unix://var/run/docker.sock\")\n        print(\":heavy_check_mark: Docker installed and running.\")\n        return client\n    except Exception:\n        print(\":cross_mark_button: Docker not installed or running. \")\n        exit(1)\n\n\ndef remove_old_tests(client: APIClient):\n    try:\n        client.remove_container(container=\"freshenv_system_test\",force=True)\n        client.remove_image(image=freshenv_test_image, force=True)\n        print(\":heavy_check_mark: Test images removed.\")\n    except errors.APIError as e:\n        if e.status_code == 404:\n            print(\":heavy_check_mark: No test images found. Moving on...\")\n    except Exception:\n        print(\":cross_mark_button: Could not remove freshenv test image. A freshenv test environment maybe still running.\")\n        exit(1)\n\ndef run_test_environment(client: APIClient):\n    try:\n        container = create_environment(flavour=\"freshenv-busybox\", command=\"ls\", ports=[\"3000\",\"4000\"],name=\"system_test\", client=client)\n        dockerpty.start(client, container, stdout=open(os.devnull, \"w\", encoding=\"utf-8\"))\n        print(\":heavy_check_mark: Succesfully provisioned test environment.\")\n    except (exceptions.HTTPError, errors.NotFound):\n        build_environment(flavour=\"freshenv-busybox\", command=\"ls\", ports=[\"3000\",\"4000\"], name=\"system_test\", client=client)\n        print(\":heavy_check_mark: Succesfully provisioned test environment.\")\n    except Exception:\n        print(\":cross_mark_button: Could not provision test environment.\")\n        exit(1)\n\n@click.command(\"check\")\ndef check() -> None:\n    \"\"\"Check system compatibility for running freshenv.\"\"\"\n    client = check_docker()\n    remove_old_tests(client)\n    run_test_environment(client)\n    remove_old_tests(client)\n    print(\":sunrise:  All test passed. Everything looks good.\")\n    "
  },
  {
    "path": "freshenv/clean.py",
    "content": "import click\nfrom docker import APIClient, errors\nfrom rich import print\n\n\n\n\n@click.command(\"clean\")\n@click.option('--force', '-f', is_flag=True, help=\"Force remove freshenv flavours and environments.\")\ndef clean(force: bool) -> None:\n    \"\"\"Remove all freshenv flavours and environments.\"\"\"\n    try:\n        client = APIClient(base_url=\"unix://var/run/docker.sock\")\n        freshenv_containers = client.containers(all=True, filters={\"name\": \"freshenv_*\"})\n        for container in freshenv_containers:\n            client.remove_container(container=container['Id'], force=force)\n        images_list = client.images(filters={\"label\": \"maintainer=Raiyan Yahya <raiyanyahyadeveloper@gmail.com>\"})\n        for image in images_list:\n            client.remove_image(image=image['Id'], force=force)\n        custom_images = client.images(filters={\"label\": \"maintainer=Custom Environment\"})\n        for custom_image in custom_images:\n            client.remove_image(image=custom_image['Id'], force=force)\n        print(\":boom: freshenv flavours and environments removed.\")\n    except errors.APIError as e:\n        if e.status_code == 409:\n            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.\")\n        else:\n            raise Exception(e)\n    except errors.DockerException:\n        print(\":cross_mark_button: Docker not installed or running. \")\n    except Exception as e:\n        print(f\"Unknown exception: {e}\")\n"
  },
  {
    "path": "freshenv/cli.py",
    "content": "import click\nfrom freshenv import provision, view, start, remove, check, clean, flavours, build\nfrom freshenv.cloud import cloud\n\n\n@click.group()\n@click.version_option()\ndef cli() -> None:\n    \"\"\"A cli to provision and manage local developer environments.\"\"\"\n\n\ncli.add_command(provision.provision)\ncli.add_command(view.view)\ncli.add_command(start.start)\ncli.add_command(remove.remove)\ncli.add_command(check.check)\ncli.add_command(clean.clean)\ncli.add_command(flavours.flavours)\ncli.add_command(build.build)\ncli.add_command(cloud.cloud)"
  },
  {
    "path": "freshenv/cloud/__init__.py",
    "content": "__version__ = \"1.0.0\"\n"
  },
  {
    "path": "freshenv/cloud/cloud.py",
    "content": "import click\nfrom freshenv.cloud.config import view_config\nfrom freshenv.cloud.fetch import fetch_environment\nfrom freshenv.cloud.ls import list_environments\nfrom freshenv.cloud.push import push_environment\n\n\n@click.group(name=\"cloud\")\ndef cloud() -> None:\n    \"\"\"Save and share your custom environments on the cloud.\"\"\"\n\n\n@cloud.command(\"ls\")\n@click.argument(\"plan\", default=\"personal\", type=click.Choice([\"freshenv\", \"personal\"]), metavar=\"plan\")\ndef ls(plan: str) -> None:\n    \"\"\"List cloud environments.\"\"\"\n    list_environments(plan)\n\n@cloud.command(\"push\")\n@click.argument(\"environment_name\")\n@click.argument(\"plan\", default=\"personal\",type=click.Choice([\"freshenv\", \"personal\"]),  metavar=\"plan\")\ndef push(environment_name: str, plan: str) -> None:\n    \"\"\"Upload an environment to the cloud.\"\"\"\n    push_environment(environment_name, plan)\n\n@cloud.command(\"fetch\")\n@click.argument(\"environment_name\")\n@click.argument(\"plan\", default=\"personal\",type=click.Choice([\"freshenv\", \"personal\"]),  metavar=\"plan\")\ndef fetch(environment_name: str, plan: str) -> None:\n    \"\"\"Download an environment from the cloud.\"\"\"\n    fetch_environment(environment_name, plan)\n\n@cloud.command(\"config\")\n@click.argument(\"plan\", default=\"personal\", type=click.Choice([\"freshenv\", \"personal\"]),  metavar=\"plan\")\ndef config(plan: str) -> None:\n    \"\"\"View personal and freshenv cloud configurations.\"\"\"\n    view_config(\"cloud.\"+plan)\n"
  },
  {
    "path": "freshenv/cloud/config.py",
    "content": "from configparser import ConfigParser\nfrom os import path\nfrom typing import Dict\nfrom rich import pretty, print\nfrom freshenv.build import config_exists, create_file, key_exists, get_key_values_from_config\n\nhomedir = path.expanduser(\"~\")\nfreshenv_config_location = homedir + \"/.freshenv/freshenv\"\n\n\ndef check_run(config_type: str) -> bool:\n    \"\"\"Check if cloud configuration is valid.\"\"\"\n    if not config_exists():\n        print(f\":card_index: No config file found. Creating an empty config at {freshenv_config_location}.\")\n        create_file(freshenv_config_location)\n        return False\n    if not key_exists(config_type):\n        print(f\":exclamation_mark: A [bold]{config_type}[/bold] cloud has not been configured.\")\n        return False\n    if not mandatory_keys_exists(config_type):\n        print(f\":exclamation_mark: missing mandatory keys in {config_type} configuration for cloud.\")\n        return False\n    return True\n\n\ndef mandatory_keys_exists(config_type: str) -> bool:\n    config = ConfigParser()\n    config.read(freshenv_config_location)\n    if \"personal\" in config_type:\n        if \"provider\" not in config[config_type]:\n            return False\n        if \"aws_profile\" not in config[config_type]:\n            return False\n        if \"bucket\" not in config[config_type]:\n            return False\n    elif \"freshenv\" in config_type:\n        if \"apikey\" not in config[config_type]:\n            return False\n    else:\n        return False\n    return True\n\n\ndef get_config(config_type: str) -> Dict[str, str]:\n    if not check_run(config_type):\n        return {}\n    cloud_config = dict(get_key_values_from_config(config_type))\n    return cloud_config\n\n\ndef view_config(config_type: str) -> None:\n    \"\"\"View personal and freshenv cloud configurations.\"\"\"\n    cloud_config = get_config(config_type)\n    if not cloud_config:\n        return\n    pretty.pprint(cloud_config)\n"
  },
  {
    "path": "freshenv/cloud/fetch.py",
    "content": "\nfrom docker import APIClient, errors\nfrom botocore import exceptions\nimport boto3\nfrom os import remove\nfrom freshenv.cloud.config import get_config\nfrom freshenv.start import start\n\n\ndef fetch_environment_from_aws(environment_name: str, config_obj: dict) -> None:\n    try:\n        session = boto3.session.Session(profile_name=config_obj[\"aws_profile\"])\n        s3_client = session.client('s3')\n        s3_client.head_bucket(Bucket=config_obj[\"bucket\"])\n        print(\":link: Downloading environment from the cloud.\")\n        s3_client.download_file(config_obj[\"bucket\"], environment_name + \".tar\", environment_name + \".tar\")\n        print(\":white_check_mark: Environment downloaded successfully.\")\n    except exceptions.ClientError as client_error:\n        if client_error.response['Error']['Code'] == 'NoSuchBucket':\n            print(\":person_shrugging: Bucket does not exist.\")\n    except exceptions.ProfileNotFound:\n        print(\":person_shrugging: config profile does not exist.\")\n    except Exception as e:\n        print(f\"Unknown exception: {e}\")\n\n\ndef import_container(environment_name: str) -> None:\n    try:\n        client = APIClient(base_url=\"unix://var/run/docker.sock\")\n        client.import_image(environment_name + \".tar\", environment_name)\n        print(\":white_check_mark: Environment imported successfully.\")\n        remove(environment_name + \".tar\")\n    except errors.APIError:\n        print(\":cold_sweat: Could not import environment. Please contact the developer or report an issue. :ticket:\")\n    except errors.DockerException:\n        print(\":cross_mark_button: Docker not installed or running. \")\n    except Exception as e:\n        print(f\"Unknown exception: {e}\")\n\ndef fetch_environment(environment_name: str, plan: str) -> None:\n    \"\"\"Fetch a custom environment from the cloud.\"\"\"\n    if plan == \"personal\":\n        config_obj = get_config(f\"cloud.{plan}\")\n        if not config_obj:\n            return\n        if config_obj and config_obj[\"provider\"]:\n            provider = config_obj[\"provider\"]\n            if provider == \"aws\":\n                fetch_environment_from_aws(environment_name, config_obj)\n                import_container(environment_name)\n                start(environment_name)\n            else:\n                print(f\":building_construction:  {provider} provider not supported.\")\n        else:\n            print(\":person_facepalming: No provider configured.\")\n    else:\n        print(\":white_sun_with_small_cloud:  The freshenv cloud plan is coming soon. Please visit the website for more information.\")\n"
  },
  {
    "path": "freshenv/cloud/ls.py",
    "content": "import boto3\nfrom botocore import exceptions\nfrom rich import print\nfrom rich.tree import Tree\nfrom freshenv.cloud.config import get_config\n\n\ndef list_environments_from_aws(config_obj: dict) -> None:\n    \"\"\"List your custom cloud environments from AWS.\"\"\"\n    try:\n        session = boto3.session.Session(profile_name=config_obj[\"aws_profile\"])\n        s3_client = session.client('s3')\n        bucket_objs = s3_client.list_objects_v2(Bucket=config_obj[\"bucket\"])\n        print(\":link: Listing your cloud environments.\")\n        tree = Tree(\"Cloud Environments\")\n        if \"Contents\" in bucket_objs and len(bucket_objs[\"Contents\"]) > 0:\n            for obj in bucket_objs[\"Contents\"]:\n                tree.add(obj[\"Key\"])\n        else:\n            tree.add(\"No cloud environments found.\")\n        print(tree)\n    except exceptions.ClientError as client_error:\n        if client_error.response['Error']['Code'] == 'NoSuchBucket':\n            print(\":person_shrugging: Bucket does not exist.\")\n    except exceptions.ProfileNotFound:\n        print(\":person_shrugging: config profile does not exist.\")\n\ndef list_environments(plan: str) -> None:\n    \"\"\"List your custom cloud environments.\"\"\"\n    if plan == \"personal\":\n        config_obj = get_config(f\"cloud.{plan}\")\n        if not config_obj:\n            return\n        if config_obj and config_obj[\"provider\"]:\n            provider = config_obj[\"provider\"]\n            if provider == \"aws\":\n                list_environments_from_aws(config_obj)\n            else:\n                print(f\":building_construction: {provider} provider not supported.\")\n        else:\n            print(\":person_facepalming: No provider configured.\")\n    else:\n        print(\":white_sun_with_small_cloud:  The freshenv cloud plan is coming soon. Please visit the website for more information.\")"
  },
  {
    "path": "freshenv/cloud/push.py",
    "content": "from docker import APIClient, errors\nfrom rich import print\nimport boto3\nfrom os import remove\nfrom botocore import exceptions\nfrom freshenv.cloud.config import get_config\n\n\ndef export_environment(environment_name: str) -> str:\n    try:\n        client = APIClient(base_url=\"unix://var/run/docker.sock\")\n        exported_container = client.export(container=environment_name)\n        with open(environment_name + \".tar\", \"wb\") as f:\n            for chunk in exported_container:\n                f.write(chunk)\n        return f.name\n    except errors.NotFound:\n        print(\" :man_shrugging: Environment not found. Please check if the environment exists.\")\n    except errors.APIError:\n        print(\":cold_sweat: Could not export environment. Please contact the developer or report an issue. :ticket:\")\n    except errors.DockerException:\n        print(\":cross_mark_button: Docker not installed or running. \")\n    except Exception as e:\n        print(f\"Unknown exception: {e}\")\n    return \"\"\n\n\ndef remove_tar_file(file_name: str) -> None:\n    remove(file_name)\n\n\ndef push_environment_to_aws(environment_name: str, config_obj: dict) -> None:\n    try:\n        session = boto3.session.Session(profile_name=config_obj[\"aws_profile\"])\n        s3_client = session.client('s3')\n        s3_client.head_bucket(Bucket=config_obj[\"bucket\"])\n        print(\":link: Uploading environment to the cloud.\")\n        file_name = export_environment(environment_name)\n        if file_name == \"\":\n            return\n        s3_client.upload_file(file_name, config_obj[\"bucket\"], file_name)\n        print(\":white_check_mark: Environment uploaded successfully.\")\n        remove_tar_file(file_name)\n    except exceptions.ClientError as client_error:\n        if client_error.response['Error']['Code'] == 'NoSuchBucket':\n            print(\":person_shrugging: Bucket does not exist.\")\n    except exceptions.ProfileNotFound:\n        print(\":person_shrugging: config profile does not exist.\")\n\n\ndef push_environment(environment_name: str, plan: str) -> None:\n    \"\"\"Upload a custom environment to the cloud.\"\"\"\n    if plan == \"personal\":\n        config_obj = get_config(f\"cloud.{plan}\")\n        if not config_obj:\n            return\n        if config_obj and config_obj[\"provider\"]:\n            provider = config_obj[\"provider\"]\n            if provider == \"aws\":\n                push_environment_to_aws(environment_name, config_obj)\n            else:\n                print(\n                    f\":building_construction:  {provider} provider not supported.\")\n        else:\n            print(\":person_facepalming: No provider configured.\")\n    else:\n        print(\":white_sun_with_small_cloud:  The freshenv cloud plan is coming soon. Please visit the website for more information.\")\n"
  },
  {
    "path": "freshenv/console.py",
    "content": "from rich.console import Console\n\nconsole = Console()\n"
  },
  {
    "path": "freshenv/flavours.py",
    "content": "import click\nfrom rich import pretty, print\nfrom urllib.request import urlopen\nfrom json import loads\nfrom sys import exit\n\n\n@click.command(\"flavours\")\ndef flavours() -> None:\n    \"\"\"Show all available flavours for provisioning.\"\"\"\n    gist_reponse = urlopen(\"https://api.github.com/gists/c4709c540a7c29616c771ab642ed2b8b\")\n    if gist_reponse.getcode() == 200:\n        gist_data = loads(gist_reponse.read().decode(\"utf-8\"))\n        flavour_dict = loads(gist_data[\"files\"][\"fr-flavours.json\"][\"content\"])\n        print(f\":mag: Found {len(flavour_dict['fr-flavours'])} flavours:\")\n        pretty.pprint(flavour_dict[\"fr-flavours\"])\n    else:\n        print(\":heavy_exclamation_mark: Could not fetch flavours.\")\n        exit(1)"
  },
  {
    "path": "freshenv/provision.py",
    "content": "from io import BytesIO\nfrom typing import Dict, List\nimport click\nfrom docker import APIClient, errors\nimport dockerpty\nfrom freshenv.util import PythonLiteralOption\nfrom freshenv.view import count_environents\nfrom freshenv.console import console\nfrom requests import exceptions, get\nfrom os import getcwd, path\nfrom rich import print\n\nclient: APIClient = None\ncurrent_directory = getcwd()\nfolder = path.basename(current_directory)\nlocal_mount_binds = [f\"{current_directory}:/home/{folder}:delegated\"]\ngoogle_dns = [\"8.8.8.8\"]\n\ndef get_port_bindings(ports: List[str]) -> Dict:\n    port_bindings = {}\n    for port in ports:\n        port_bindings[port] = port\n    return port_bindings\n\n\ndef create_environment(flavour: str, command: str, ports: List[str], name: str, client: APIClient, tty: bool=True, stdin_open: bool=True) -> Dict:\n    if name == \"index\":\n        name = str(count_environents() + 1)\n    container = client.create_container(\n        name=f\"freshenv_{name}\",\n        image=f\"raiyanyahya/freshenv-flavours/{flavour}\",\n        stdin_open=stdin_open,\n        tty=tty,\n        command=command,\n        volumes=[\"/home\"],\n        ports=ports,\n        use_config_proxy=True,\n        host_config=client.create_host_config(port_bindings=get_port_bindings(ports),userns_mode=\"host\",privileged=True,dns=google_dns,binds=local_mount_binds))\n    return container\n\n\ndef pull_and_try_again(flavour: str, command: str, ports: List[str], name: str, client: APIClient):\n    try:\n        with console.status(\"Flavour doesnt exist locally. Fetching flavour...\", spinner=\"dots8Bit\"):\n            client.pull(f\"ghcr.io/raiyanyahya/{flavour}/{flavour}\")\n        container = create_environment(flavour, command, ports, name, client)\n        dockerpty.start(client, container)\n    except (errors.ImageNotFound, exceptions.HTTPError):\n        print(\":x: flavour doesnt exist\")\n\ndef get_dockerfile_path(flavour: str) -> bytes:\n    req = get(f\"https://raw.githubusercontent.com/raiyanyahya/freshenv-flavours/master/{flavour}\", timeout=60)\n    return req.text.encode('utf-8')\n\ndef build_environment(flavour: str, command: str, ports: List[str], name: str, client: APIClient):\n    try:\n\n        with console.status(\"Flavour doesnt exist locally. Building flavour...\", spinner=\"dots8Bit\"):\n            [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\n        container = create_environment(flavour, command, ports, name, client)\n        dockerpty.start(client, container)\n    except (errors.APIError, exceptions.HTTPError):\n        print(\":x: Flavour could not be built or found.\")\n\n\n@click.command(\"provision\")\n@click.option(\"--flavour\",\"-f\",default=\"base\", help=\"The flavour of the environment.\",show_default=True)\n@click.option(\"--command\",\"-c\", help=\"The command to execute at startup of environment.\")\n@click.option(\"--ports\",\"-p\", default='[\"3000\",\"4000\"]', cls=PythonLiteralOption, help=\"String list of ports to forward.\", show_default=True)\n@click.option(\"--name\",\"-n\", default=\"index\", help=\"Name of your environment.\", show_default=False)\ndef provision(flavour: str, command: str, ports: List[str], name: str) -> None:\n    \"\"\"Provision a developer environment.\"\"\"\n    try:\n        client = APIClient(base_url=\"unix://var/run/docker.sock\")\n        container = create_environment(flavour, command, ports, name, client)\n        dockerpty.start(client, container)\n    except (errors.ImageNotFound,exceptions.HTTPError, errors.NotFound):\n        build_environment(flavour, command, ports, name,client)\n        #pull_and_try_again(flavour, command, ports, name,client) to be implemented in the cloud version\n    except errors.DockerException:\n        print(\":cross_mark_button: Docker not installed or running. \")\n    except Exception as e:\n        print(f\"Unknown exception: {e}\")\n"
  },
  {
    "path": "freshenv/remove.py",
    "content": "import click\nfrom docker import APIClient, errors\nfrom rich import print\n\n\n\n\n@click.command(\"remove\")\n@click.argument(\"name\")\n@click.option('--force', '-f', is_flag=True, help=\"Force remove an environment.\")\ndef remove(name: str, force: bool) -> None:\n    \"\"\"Remove a freshenv environment.\"\"\"\n    try:\n        client = APIClient(base_url=\"unix://var/run/docker.sock\")\n        client.remove_container(container=name, force=force)\n        print(f\":boom: {name} environment removed.\")\n    except errors.NotFound:\n        print(f\":ghost: No freshenv environment called [bold]{name}[/bold] found.\")\n    except errors.APIError as e:\n        if e.status_code == 409:\n            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.\")\n        else:\n            raise Exception(e)\n    except errors.DockerException:\n        print(\":cross_mark_button: Docker not installed or running. \")\n    except Exception as e:\n        print(f\"Unknown exception: {e}\")\n"
  },
  {
    "path": "freshenv/start.py",
    "content": "import click\nfrom docker import APIClient, errors\nimport dockerpty\nfrom rich import print\n\n\n\n\n@click.command(\"start\")\n@click.argument(\"name\")\ndef start(name: str) -> None:\n    \"\"\"Resume working in an environment.\"\"\"\n    try:\n        client = APIClient(base_url=\"unix://var/run/docker.sock\")\n        containers = client.containers(all=True, filters={\"name\": name})\n        if containers:\n            dockerpty.start(client, containers[0])\n        else:\n            print(f\":ghost: No freshenv environment called [bold]{name}[/bold] found.\")\n    except errors.DockerException:\n        print(\":cross_mark_button: Docker not installed or running. \")\n    except Exception as e:\n        print(f\"Unknown exception: {e}\")\n"
  },
  {
    "path": "freshenv/util.py",
    "content": "from click import Option, BadParameter\nfrom ast import literal_eval\n\nclass PythonLiteralOption(Option):\n    \"\"\"A utility class to convert a string to a python literal.\"\"\"\n\n    def type_cast_value(self, ctx, value):\n        try:\n            return literal_eval(value)\n        except BadParameter:\n            raise BadParameter(value)\n"
  },
  {
    "path": "freshenv/view.py",
    "content": "from typing import Dict, List\nimport click\nfrom docker import APIClient, errors\nfrom rich import print\n\n\nclient: APIClient = None\n\n\ndef count_environents() -> int:\n    return len(get_list_environments())\n\n\ndef get_list_environments() -> List[Dict]:\n    environment_list = []\n    client = APIClient(base_url=\"unix://var/run/docker.sock\")\n    environment_list = client.containers(all=True,filters={\"label\": \"maintainer=Raiyan Yahya <raiyanyahyadeveloper@gmail.com>\"})\n    custom_environment_list = client.containers(all=True,filters={\"label\": \"maintainer=Custom Environment\"})\n    environment_list = environment_list + custom_environment_list\n    return environment_list\n\n\n@click.command(\"view\")\ndef view() -> None:\n    \"\"\"View local freshenv managed environments.\"\"\"\n    try:\n        container_list = get_list_environments()\n        if not container_list:\n            print(\":computer: No freshenv environments found.\")\n        for container in container_list:\n            if \"Exited\" in container.get(\"Status\"):  # type: ignore\n                img = \":arrow_down: \"\n            else:\n                img = \":arrow_forward: \"\n            print(\n                img,\n                \"Name: [bold blue]\" + container.get(\"Names\")[0] + \"[/bold blue]\",  # type: ignore\n                \"| Flavour: [bold blue]\" + container.get(\"Image\").split(\"/\")[-1] + \"[/bold blue]\",  # type: ignore\n                \"| State: [bold blue]\" + container.get(\"Status\") + \"[/bold blue]\",  # type: ignore\n            )\n    except errors.DockerException:\n        print(\":cross_mark_button: Docker not installed or running. \")\n    except Exception as e:\n        print(f\"Unknown exception: {e}\")"
  },
  {
    "path": "setup.py",
    "content": "from os.path import abspath, dirname, join, isfile\nfrom os import environ\nfrom setuptools import find_packages, setup\nimport sys\nversion_f = \".version\"\nthis_dir = abspath(dirname(__file__))\nwith open(join(this_dir, \"README.md\"), encoding=\"utf-8\") as file:\n    long_description = file.read()\n\n\ndef get_version():\n    if isfile(version_f):\n        with open(version_f) as version_file:\n            version = version_file.read().strip()\n            return version\n    elif (\n        \"build\" in sys.argv\n        or \"egg_info\" in sys.argv\n        or \"sdist\" in sys.argv\n        or \"bdist_wheel\" in sys.argv\n    ):\n        version = environ.get(\"VERSION\", \"0.0\")  # Avoid PEP 440 warning\n        if \"-SNAPSHOT\" in version:\n            version = version.replace(\"-SNAPSHOT\", \".0\")\n        with open(version_f, \"w+\") as version_file:\n            version_file.write(version)\n        return version\n\n\nsetup(\n    name=\"freshenv\",\n    python_requires=\">3.5\",\n    options={\"bdist_wheel\": {\"universal\": \"1\"}},\n    version=get_version(),\n    description=\"A cli to provision and manage local developer environments.\",\n    long_description=long_description,\n    long_description_content_type='text/markdown',\n    url=\"https://github.com/raiyanyahya/freshenv\",\n    author=\"Raiyan Yahya\",\n    license=\"Mozilla Public License 2.0\",\n    author_email=\"raiyanyahyadeveloper@gmail.com\",\n    keywords=[\"cli\",\"developer tools\",\"productivity\", \"tools\"],\n    packages=find_packages(),\n    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\"],\n    entry_points={\"console_scripts\": [\"freshenv=freshenv.cli:cli\",\"fr=freshenv.cli:cli\"]},\n)\n"
  },
  {
    "path": "snap/snapcraft.yaml",
    "content": "name: freshenv\nversion: 3.0.4\nsummary: A cli to provision and manage local developer environments.\ndescription: |\n          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.\nbase: core20\ncontact: contact@freshenv.io\nwebsite: https://freshenv.io\nsource-code: https://github.com/raiyanyahya/freshenv\nissues: https://github.com/raiyanyahya/freshenv/issues\narchitectures:\n    - build-on: [arm64, armhf, amd64]\ngrade: stable\nconfinement: strict\n\nplugs:\n  docker-executables:\n    content: docker-executables\n    default-provider: docker\n    interface: content\n    target: docker-env\napps:\n  freshenv:\n    command: bin/freshenv\n    plugs: [network, docker,docker-executables]\nparts:\n  freshenv:\n    plugin: python\n    source: .\n"
  },
  {
    "path": "tox.ini",
    "content": "[tox]\nenvlist = py38,mypy\n\n[testenv]\ndeps =\n  pylint\ncommands =\n  pylint freshenv --disable=C0301,C0114,C0116,C0103,W0603,W0622,C0411,C0304,W0707,R0801,W0703,R1721,W0621,R1732,R0913,W0719\n\n[testenv:mypy]\nskip_install = true\nbasepython = python3.8\ndeps =\n  mypy\n  types-requests\ncommands =\n  mypy --exclude build --ignore-missing-imports --pretty .\n"
  }
]