Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
eugenesvk committed Mar 4, 2021
0 parents commit 6a0ccb8
Show file tree
Hide file tree
Showing 9 changed files with 356 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.xsh text linguist-language=Python
31 changes: 31 additions & 0 deletions .github/workflows/python-publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# This workflow will upload a Python Package using Twine when a release is created
# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries

name: Upload Python Package

on:
release:
types: [published] # allows publishing of releases converted from the draft ones

jobs:
deploy:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine
- name: Build and publish
env:
TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
run: |
python setup.py sdist bdist_wheel
twine upload dist/*
129 changes: 129 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# 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
*.py,cover
.hypothesis/
.pytest_cache/

# 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

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/
21 changes: 21 additions & 0 deletions License
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021, Evgeny

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions Manifest.in
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
include License
47 changes: 47 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<p align="center">
Add Homebrew's shell environment to <a href="https://xon.sh">xonsh shell</a> on Linux
<br/>
(alternative to <a href="https://docs.brew.sh/Homebrew-on-Linux">shellenv</a>)
</p>

<p align="center">
If you like the idea, ask Homebrew to implement it natively as my <a href="https://github.com/Homebrew/brew/pull/10757">fix</a> was rejected because “xonsh is far too niche”
</p>

## Introduction

Homebrew has a `shellenv` command to add __Homebrew__ environment to your shell: it adds a few
environment variables (`HOMEBREW_` `PREFIX`/`CELLAR`/`REPOSITORY`) and updates a few paths (`MAN`/`INFO`/ `PATH`). Unfortunately it doesn't support __xonsh__ shell, and the devs are not yet willing to [fix it](https://github.com/Homebrew/brew/pull/10757), requiring adding the environment variables manually...

Or using this xontrib, which automatically translates the default __bash__ output of `shellenv` into __xonsh__

## Installation

To install use pip:

```bash
xpip install xontrib-linuxbrew
# or: xpip install -U git+https://github.com/eugenesvk/xontrib-linuxbrew
```

## Usage

Add this to your xonsh shell profile script at `~/.xonshrc` or `~/.config/rc.xsh`
```bash
xontrib load linuxbrew
```

Set level of verbosity via `$XONTRIB_LINUXBREW_LOGLEVEL` to __0–3__:

- 0 print nothing (fail silently)
- 1 (default) print errors (e.g. can't find brew at default locations)
- 2 print warnings (e.g parsing errors)
- 3 print more verbose messages

## Known issues

- Only default installation paths (`~/.linuxbrew` and `/home/linuxbrew/.linuxbrew`) are supported

## Credits

This package was created with [xontrib cookiecutter template](https://github.com/xonsh/xontrib-cookiecutter).
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
xonsh
42 changes: 42 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#!/usr/bin/env python
import setuptools

try:
with open('ReadMe.md', 'r', encoding='utf-8') as fh:
long_description = fh.read()
except (IOError, OSError):
long_description = ''

setuptools.setup(
name = 'xontrib-linuxbrew',
version = '0.1.0',
license = 'MIT',
author = 'Evgeny',
author_email = '',
description = "Add Homebrew's shell environment to xonsh on Linux",
long_description = long_description,
long_description_content_type = 'text/markdown',
python_requires = '>=3.6',
install_requires = ['xonsh'],
packages = ['xontrib'],
package_dir = {'xontrib': 'xontrib'},
package_data = {'xontrib': ['*.xsh']},
platforms = 'any',
url = 'https://github.com/eugenesvk/xontrib-linuxbrew',
project_urls = {
"Documentation" : "https://github.com/eugenesvk/xontrib-linuxbrew/blob/master/ReadMe.md",
"Code" : "https://github.com/eugenesvk/xontrib-linuxbrew",
"Issue tracker" : "https://github.com/eugenesvk/xontrib-linuxbrew/issues",
},
classifiers=[
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: System :: Shells",
"Topic :: System :: System Shells",
"Topic :: Terminals",
]
)
83 changes: 83 additions & 0 deletions xontrib/linuxbrew.xsh
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
from xonsh import platform
from os import path

__all__ = ()

_log = __xonsh__.env.get('XONTRIB_LINUXBREW_LOGLEVEL', 1) # 0 none, 1 error, 2 warning, 3 extra

def _SetBrewEnv():
if not platform.ON_LINUX:
if _log >= 3:
print("xontrib-LinuxBrew: not Linux, exiting")
return
if 'HOMEBREW_PREFIX' in ${...}: # don't overwrite existing env var
if _log >= 3:
print("xontrib-LinuxBrew: HOMEBREW_PREFIX already set, exiting")
return
LBS = ''
if p'/home/linuxbrew/.linuxbrew/bin/brew'.exists():
LBS = $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)
elif pf'{path.join(path.expanduser("~"), ".linuxbrew/bin/brew")}'.exists():
LBS = $(pf'{path.join(path.expanduser("~"), ".linuxbrew/bin/brew")}' shellenv)
else:
if _log >= 1:
print("xontrib-LinuxBrew: ERROR: Can't find 'brew' in neither '/home/linuxbrew/.linuxbrew/bin/' nor in '~/.linuxbrew/bin/'")
return
""" we get the default bash shellenv output like this
export HOMEBREW_PREFIX="/home/linuxbrew/.linuxbrew";
export HOMEBREW_CELLAR="/home/linuxbrew/.linuxbrew/Cellar";
export HOMEBREW_REPOSITORY="/home/linuxbrew/.linuxbrew/Homebrew";
export PATH="/home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin${PATH+:$PATH}";
export MANPATH="/home/linuxbrew/.linuxbrew/share/man${MANPATH+:$MANPATH}:";
export INFOPATH="/home/linuxbrew/.linuxbrew/share/info:${INFOPATH:-}";
"""
# 1. Remove bashisms
LBS = LBS.replace(r'export ' , '')\
.replace(r'${PATH+:$PATH}' , '')\
.replace(r'${MANPATH+:$MANPATH}:' , '')\
.replace(r':${INFOPATH:-}' , '')\
.split(';\n')
if LBS[-1] == '': # remove the last (empty) line
del LBS[-1]
if len(LBS) != 6:
if _log >= 2:
print("xontrib-LinuxBrew: WARNING: expected 6 variables from shellenv output, but instead got " + str(len(LBS)))

# 2. Create empty env vars if they don't already exist
if 'PATH' not in ${...}:
$PATH = ''
if 'MANPATH' not in ${...}:
$MANPATH = ''
if 'INFOPATH' not in ${...}:
$INFOPATH = ''

# 3. Test whether each line wants to assign a Location var or add a value to some PATH
startLoc = 'HOMEBREW_' # '_PREFIX', '_CELLAR', '_REPOSITORY'
startPath = ['PATH', 'MANPATH', 'INFOPATH']
matches = []

for i, cmd in enumerate(LBS):
if cmd.startswith(startLoc): # Location vars can be executed as is
execx('$'+LBS[i]) # assigns env var '$HOMEBREW_X="VALUE"'
matches.append(i)
elif cmd.startswith(tuple(startPath)): # PATH vars need to be appended to PATH lists
if cmd.find('=') == -1: # something is wrong, '=' not found after 'PATH'
break
else:
matches.append(i)
cmdSplit = cmd.split('=',1) # split 'PATH="path1:path2"'
cmdVar = cmdSplit[0] # 'PATH'
cmdVal = cmdSplit[1].replace('"','').split(':') # split "path1:path2"
for path in reversed(cmdVal):
${cmdVar}.add(path, front=True, replace=True) # env lookup 'PATH' and add each path
if len(matches) != 6:
if _log >= 2:
print("xontrib-LinuxBrew: WARNING: expected to successfully parse 6 variables from shellenv output, but only managed to parse " + str(len(matches)))
if _log >= 3:
for i in sorted(matches, reverse=True):
del LBS[i]
print("Remaining items:")
print(LBS)
return

_SetBrewEnv()

0 comments on commit 6a0ccb8

Please sign in to comment.