Skip to content

Instantly share code, notes, and snippets.

@fleger
Created February 20, 2011 16:58
Show Gist options
  • Save fleger/836101 to your computer and use it in GitHub Desktop.
Save fleger/836101 to your computer and use it in GitHub Desktop.
Really basic tree walking library written in bash
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details.
# Private API
# treewalker.__walk head preCallback postCallback
treewalker.__walk() {
local head="$1"
if ! treewalker.in "$head" "${excludeList[@]}"; then
excludeList+=("$head")
local preCallback="$2"
local postCallback="$3"
[ -z "$preCallback" ] || $head.$preCallback
local child
for child in ${TREEWALKER_TREE[$head]}; do
treewalker.__walk "$child" "$preCallback" "$postCallback"
done
[ -z "$postCallback" ] || $head.$postCallback
fi
}
# treewalker.__reversedwalk head preCallback postCallback
treewalker.__reversedwalk() {
local head="$1"
if ! treewalker.in "$head" "${excludeList[@]}"; then
excludeList+=("$head")
local preCallback="$2"
local postCallback="$3"
[ -z "$preCallback" ] || $head.$preCallback
local child
for child in ${reversedTree[$head]}; do
treewalker.__reversedwalk "$child" "$preCallback" "$postCallback"
done
[ -z "$postCallback" ] || $head.$postCallback
fi
}
# Public API
# treewalker.in value [items...]
treewalker.in() {
local val="$1"
local item
shift
for item in "$@"; do
[[ x"$val" = x"$item" ]] && return 0
done
return 1
}
# treewalker.walk head preCallback postCallback
treewalker.walk() {
local -a excludeList=()
treewalker.__walk "$1" "$2" "$3"
}
# treewalker.reversedwalk head preCallback postCallback
treewalker.reversedwalk() {
local -A reversedTree
local k
local v
local child
for k in "${!TREEWALKER_TREE[@]}"; do
for v in ${TREEWALKER_TREE[$k]}; do
reversedTree[$v]+=" $k"
done
done
local -a excludeList=()
treewalker.__reversedwalk "$1" "$2" "$3"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment