• Stars
    star
    669
  • Rank 65,189 (Top 2 %)
  • Language
    Perl
  • Created over 10 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Autoenv for zsh

Build Status

Autoenv for Zsh

zsh-autoenv automatically sources (known/whitelisted) .autoenv.zsh files, typically used in project root directories.

It handles "enter" and leave" events, nesting, and stashing of variables (overwriting and restoring).

Requirements

  • Zsh version 4.3.10 or later.

Features

  • Support for enter and leave events, which can use the same file. By default it uses .autoenv.zsh for entering, and .autoenv_leave.zsh for leaving.
  • Interactively asks for confirmation / authentication before sourcing an unknown .autoenv.zsh file, and remembers whitelisted files by their hashed content.
  • Test suite.
  • Written in/for Zsh.

Variable stashing

You can use autostash in your .autoenv.zsh files to overwrite some variable, e.g. $PATH. When leaving the directory, it will be automatically restored.

% echo 'echo ENTERED; autostash FOO=changed' > project/.autoenv.zsh
% FOO=orig
% cd project
Attempting to load unauthorized env file!
-rw-rw-r-- 1 user user 36 Mai  6 20:38 /tmp/project/.autoenv.zsh

**********************************************

echo ENTERED; autostash FOO=changed

**********************************************

Would you like to authorize it? (type 'yes') yes
ENTERED
project % echo $FOO
changed
% cd ..
% echo $FOO
orig

There is also stash, unstash and autounstash, in case you want to have more control.

The varstash library has been taken from smartcd, and was optimized for Zsh.

Writing your .autoenv.zsh file

autoenv_source_parent()

zsh-autoenv will stop looking for .autoenv.zsh files upwards after the first one has been found, but you can use the function autoenv_source_parent to source the next .autoenv.zsh file upwards the directory tree from there.

The function accepts an optional argument, which allows to stop looking before the file system root is reached:

autoenv_source_parent ../..

Installation

Clone the repository and source it from your ~/.zshrc file:

% git clone https://github.com/Tarrasch/zsh-autoenv ~/.dotfiles/lib/zsh-autoenv
% echo 'source ~/.dotfiles/lib/zsh-autoenv/autoenv.zsh' >> ~/.zshrc

Using antigen

antigen-bundle Tarrasch/zsh-autoenv

Using zgen

Add the following to your .zshrc where you are loading your plugins:

zgen load Tarrasch/zsh-autoenv

Using zplug

Add the following to your .zshrc where you are loading your plugins:

zplug "Tarrasch/zsh-autoenv"

Configuration

You can use the following variables to control zsh-autoenv's behavior. Add them to your ~/.zshrc file, before sourcing/loading zsh-autoenv.

AUTOENV_FILE_ENTER

Name of the file to look for when entering directories.

Default: .autoenv.zsh

AUTOENV_FILE_LEAVE

Name of the file to look for when leaving directories. Requires AUTOENV_HANDLE_LEAVE=1.

Default: .autoenv_leave.zsh

AUTOENV_LOOK_UPWARDS

Look for zsh-autoenv "enter" files in parent dirs?

Default: 1

AUTOENV_HANDLE_LEAVE

Handle leave events when changing away from a subtree, where an "enter" event was handled?

Default: 1

AUTOENV_DISABLED

(Temporarily) disable zsh-autoenv. This gets looked at in the chpwd handler.

Default: 0

AUTOENV_DEBUG

Set debug level. If enabled (> 0) it will print information to stderr.

  • 0: no debug messages
  • 1: generic debug logging
  • 2: more verbose messages
    • messages about adding/removing files on the internal stack
  • 3: everything
    • sets xtrace option (set -x) while sourcing env files

Default: 0

Usage

zsh-autoenv works automatically once installed.

You can use autoenv-edit to edit the nearest/current autoenv files. It will use $AUTOENV_EDITOR, $EDITOR, or vim for editing.

Helper functions

The following helper functions are available:

autoenv_append_path

Appends path(s) to $path ($PATH), if they are not in there already.

autoenv_prepend_path

Prepends path(s) to $path ($PATH), if they are not in there already.

autoenv_remove_path

Removes path(s) from $path ($PATH).

Returns 0 in case $path has changed, 1 otherwise.

Recipes

Automatically activate Python virtualenvs

Given AUTOENV_FILE_ENTER=.autoenv.zsh, AUTOENV_FILE_LEAVE=.autoenv.zsh and AUTOENV_HANDLE_LEAVE=1 the following script will activate Python virtualenvs automatically in all subdirectories (.venv directories get used by pipenv with PIPENV_VENV_IN_PROJECT=1):

# Environment file for all projects.
#  - (de)activates Python virtualenvs (.venv) from pipenv

if [[ $autoenv_event == 'enter' ]]; then
  autoenv_source_parent

  _my_autoenv_venv_chpwd() {
    if [[ -z "$_ZSH_ACTIVATED_VIRTUALENV" && -n "$VIRTUAL_ENV" ]]; then
      return
    fi

    setopt localoptions extendedglob
    local -a venv
    venv=(./(../)#.venv(NY1:A))

    if [[ -n "$_ZSH_ACTIVATED_VIRTUALENV" && -n "$VIRTUAL_ENV" ]]; then
      if ! (( $#venv )) || [[ "$_ZSH_ACTIVATED_VIRTUALENV" != "$venv[1]" ]]; then
        unset _ZSH_ACTIVATED_VIRTUALENV
        echo "De-activating virtualenv: ${(D)VIRTUAL_ENV}" >&2

        # Simulate "deactivate", but handle $PATH better (remove VIRTUAL_ENV).
        if ! autoenv_remove_path $VIRTUAL_ENV/bin; then
          echo "warning: ${VIRTUAL_ENV}/bin not found in \$PATH" >&2
        fi

        # NOTE: does not handle PYTHONHOME/_OLD_VIRTUAL_PYTHONHOME
        unset _OLD_VIRTUAL_PYTHONHOME
        # NOTE: does not handle PS1/_OLD_VIRTUAL_PS1
        unset _OLD_VIRTUAL_PS1
        unset VIRTUAL_ENV
      fi
    fi

    if [[ -z "$VIRTUAL_ENV" ]]; then
      if (( $#venv )); then
        echo "Activating virtualenv: ${(D)venv}" >&2
        export VIRTUAL_ENV=$venv[1]
        autoenv_prepend_path $VIRTUAL_ENV/bin
        _ZSH_ACTIVATED_VIRTUALENV="$venv[1]"
      fi
    fi
  }
  autoload -U add-zsh-hook
  add-zsh-hook chpwd _my_autoenv_venv_chpwd
  _my_autoenv_venv_chpwd
else
  add-zsh-hook -d chpwd _my_autoenv_venv_chpwd
fi

Related projects

History

This started as an optimized version of the bash plugin autoenv but for Zsh, and grew a lot of functionality on top of it (inspired by smartcd).

The code was initially based on @joshuaclayton's dotfiles. In September 2013 @Tarrasch packaged it into a nice antigen-compatible unit with integration tests. Since November 2014, @blueyed took over and added many nice features, mainly inspired by smartcd.

More Repositories

1

zsh-bd

Jump back to a specific directory, without doing `cd ../../..`
Shell
412
star
2

antigen-hs

A fast zsh plugin manager
Haskell
205
star
3

zsh-colors

Imagine a shell where `red ERROR` just works
Shell
42
star
4

zsh-command-not-found

A mirror of oh-my-zsh/plugins/command-not-found in case you don't want all of oh-my-zsh
Shell
22
star
5

dotfiles

My own simple dotfiles (I promise, when i started it was simple ;p)
Vim Script
16
star
6

zsh-mcd

zsh plugin for `mkdir && cd`
Shell
5
star
7

yesod-text-markdown

Yesod support for Text.Markdown
Haskell
5
star
8

vietnamese-stopwords

A relatively big list of vietnamese stopwords
Python
5
star
9

timed-repeating

Repeat haskell IO actions (run background jobs) in a managed way, useful when caching scraping results
Haskell
4
star
10

zsh-i-know

Avoid catastrophes like accidentally running `rm -rf .giit`
Shell
3
star
11

Forarprov-selenium-rb

Check for available test day times for Swedish drivers license
Ruby
3
star
12

Einstein-scraping

A "Restaurant Einstein" online menu scraper in haskell
2
star
13

Matrix-multiplication-in-MIPS

Optimized implementation of gaussian elimination for MIPS assembler
C
2
star
14

authenticate-kerberos

kerberos authentication in Haskell
Haskell
2
star
15

Listify

Managing Spotify playlists using libspotify
C
2
star
16

exjobb

None-code files for my master thesis work
TeX
2
star
17

Huzzle-Bobble

[Abandoned] Puzzle Bobble written in Haskell
Haskell
2
star
18

Cheapest-SJ-Ticket

[Abandoned] SJ.se scraper that could find cheaper train tickets by nontrivial routes
Pascal
2
star
19

LBA-Image-Creator

GUI for modifying in-game images for the Little Big Adventure games
Pascal
2
star
20

Basic-image-Processing

Objective-C
2
star
21

Cyclic-Barrier

2
star
22

room-booker-rb

Book group rooms at Chalmers University of Technology
JavaScript
2
star
23

sokoban-planner

[CS7649] RIP12 project1: Classical Sokoban Planner
Java
2
star
24

Jenkins-home-dir

Repo "backup" of jenkins home dir
Shell
2
star
25

yesod-auth-kerberos

Kerberos support for Yesod Auth
Haskell
2
star
26

Hong

A Pong clone in Haskell with reactive programming
Haskell
2
star
27

Single-lane-Bridge

Getting cars to cross a bridge
2
star
28

Tuplespace

Erlang module which implements a Linda-style tuple space
Erlang
2
star
29

BabuschkaEngine

Babuschka playing engine (also see Babuface)
C++
1
star
30

Cryptography-Course

Coursework repo
1
star
31

Dynamic-Sieves

Sieving out primes with channels created dynamically
1
star
32

shorten-strings

A unified interface for shorten-ellipsis'ing string-like types
1
star
33

Digital-Signature-Algorithm

Digital Signature Algorithm
Haskell
1
star
34

rack-example

Rack example application
Ruby
1
star
35

Advanced-Algorithms

Excercises for the advanced algorithms course on CTH
1
star
36

luigid-basics-jun-2015

Short presentation about luigi central scheduler
JavaScript
1
star
37

Recipe-Site

A small yesod site as described by http://www.yesodweb.com/blog/2011/5/yesod-for-non-haskellers
Haskell
1
star
38

Nollform

A yesod site where university freshmen can register their personality in brief
Haskell
1
star
39

Receiving-in-JR

Receiving multiple messages in JR
Java
1
star
40

Hello-world-in-MIPS

1
star
41

Optimization-of-x2

1
star
42

Maxmargin-classifier

Simple classifier
Objective-C
1
star
43

thunky-lists

[Proof of concept] Lazy lists in java using thunks
Java
1
star
44

Yerbersod

Kerberos + Yesod (temporary repo)
1
star
45

JK-vippa

1
star
46

Synchronus-sequential-design

Laboration in VHDL (= Lab 3)
VHDL
1
star
47

vhpop

[UNOFFICIAL] Mirror of vhpop, just changed to compile
C++
1
star
48

TCP-Client

TCP Client written in java that fetches a website
1
star
49

Water-Tank-Regulator

A control engineering approach to regulate water tanks
1
star
50

Pattern-Recognition

An excercise to recognize patterns in Iris Plants
1
star
51

Flank-Detector

A circuit detecting which signal was last changed
1
star
52

K1K2-MIPS-interrupts

1
star
53

Weighted-Max-Cut

Objective-C
1
star
54

Functional-language-interpreter

An interpreter for a very small untyped functional language
Haskell
1
star
55

Two-Player-Zero-Sum

Objective-C
1
star
56

Dtek-Apache-Conf

Apache2 configuration for dtek.se
1
star
57

Control-of-Satellite

A Control engineering approach using a PD-regulator
1
star
58

my-tetris-solver-hs

Weekend project: Solve Tetris in Haskell
Haskell
1
star
59

MagControl

A control engineering approach to regulating the position of a magnetic ball
MATLAB
1
star
60

motion-planning

[CS7649] RIP12 project2: Motion planning
C++
1
star
61

Hazards

Hazards in combinatorial circuits
1
star
62

stacker

Hello world in elixir
Elixir
1
star
63

Studying-Abroad

1
star
64

Water-demo

We show what github's commenting feature can do
1
star
65

word-numbers-hs

Solving the word numbers problem with help from <http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers1/>
1
star
66

AlphaBiscuit

Analyze alphabet crackers and determine Characters/Words
MATLAB
1
star
67

Basic-image-operation-in-matlab

1
star
68

Babuschkaface

Babuschka game interface (game idea © Alan Newman)
Pascal
1
star
69

Curriculum-Vitae

Repo for my curriculum vitae - a compiled version can be found on my website:
TeX
1
star