Репозиторий Sisyphus
Последнее обновление: 25 сентября 2020 | Пакетов: 17708 | Посещений: 19297069
en ru br
Репозитории ALT
S:2.04-alt1
5.1: 0.5.1-alt2
4.1: 0.5-alt0.M41.1
www.altlinux.org/Changes

Группа :: Разработка/Прочее
Пакет: nish-functions

 Главная   Изменения   Спек   Патчи   Исходники   Загрузить   Gear   Bugs and FR  Repocop 

nish-functions-1.02/000075500000000000000000000000001203751511500144015ustar00rootroot00000000000000nish-functions-1.02/Makefile000064400000000000000000000013301203751511500160360ustar00rootroot00000000000000DESTDIR=
PREFIX=$(DESTDIR)/usr
LIBEXEC=libexec
LIBEXECDIR=$(PREFIX)/$(LIBEXEC)/nish
BINDIR=$(PREFIX)/bin
JUNK= o oo ooo o.* *~
GENERATED=functions.locate.new

all: functions.locate.new README

clean:
rm -rf $(JUNK) $(GENERATED)

README: README.in
sed 's@LIBEXEC@$(LIBEXECDIR)@g' $< > $@
echo | sh ./functions >> $@

functions.locate.new: functions.locate
sed 's@^__LIBEXEC=.*@__LIBEXEC="\$(LIBEXECDIR)"@g' $< > $@

install: all
mkdir -p "$(LIBEXECDIR)" "$(BINDIR)"
install -m755 functions functions.* "$(LIBEXECDIR)"/
rm -f "$(LIBEXECDIR)"/functions.locate*
install -m755 functions.locate.new "$(BINDIR)"/functions.locate

suck:
cd ~ && git pull
rm functions*
cp ~/bin/functions* ./

spit:
install functions* ~/bin/
nish-functions-1.02/README.in000064400000000000000000000001051203751511500156620ustar00rootroot00000000000000Run LIBEXEC/functions itself to get this detailed help on functions:
nish-functions-1.02/functions000075500000000000000000000352541203751511500163500ustar00rootroot00000000000000#!/bin/sh
###########################################################
#
# NameSpace Independent Shell Functions
#
# This is main supplementary functions file
# it is not intended to be called directly
# see functions digest below
#
# Any global variable or function name defined here MUST start with "_"
# to avoid namespace clash (all user-defined names must NOT start with "_")
# Names started with two _'s are internals and should not be used outside
#
#==========================================================
# Variables:

export _Me=`basename "$0"` # script name
test -n "$_GMe" ||
export _GMe="$_Me" # global script name (for set of scripts)
export _FMe=`realpath "$0"` # script fullpath
export _MeDir=`dirname "$_FMe"` # script directory
export _MePID="$$" # PID of current shell
test -n "$_Home" ||
export _Home="$HOME" # base directory
export _AMe=`echo "$_Me" | tr -cd "[:alnum:]"` # script name alphanumeric part (for generating filenames)
test -n "$__RC_SUFFIX" ||
__RC_SUFFIX="rc" # config file suffix
export _RC="$_Home/.$_GMe$__RC_SUFFIX" # config file
export _SYSRC="/etc/$_GMe$__RC_SUFFIX" # system-wide config file
export _RC_HOST="$_Home/.$_GMe$__RC_SUFFIX.`hostname`" # host specific config file
export _Verb=0 # verbosity level
export _Options="" # getopts options (generated!)
export _Usage="" # short help string
export _Help="" # long help string
export _TmpFiles="" # temporary files
export _TmpDirs="" # temporary directories
export _LC_COLLATE=C # LC_COLLATE submissions
export __Version=1.02 # this functions file version
export _Version=0.0 # software version
__CR="
" # see functions.ascii for more
__IsXFlag="" # used while temprarily turnin sh -x off
__Unsafe="" # set this to non-empty to enable unsafe actions
#(like non-/tmp/-directory deleting etc.)
export _OS="`uname -o`" # OS identifier

# LC_COLLATE wrappers (e. g. for [a-z] regexps work properly etc.)
# sed grep sort type
sed() { env LC_COLLATE="$_LC_COLLATE" sed "$@"; }
grep() { env LC_COLLATE="$_LC_COLLATE" grep "$@"; }
sort() { env LC_COLLATE="$_LC_COLLATE" sort "$@"; }

## GNU or BSD sed? (NOTE: -r key is added to BSD sed already)
sed --version 2>/dev/null 1>/dev/null &&
_Esed() { sed -r "$@"; } || _Esed() { sed -E "$@"; }
sed --version 2>/dev/null 1>/dev/null &&
_EsedNL="\n" || _EsedNL="\
"

#==========================================================
# Message displaying and error system

## Internal: display a message
## One may redefine this (e.g. with XDialog) for another displaying method
__Message() { # message [title]
{ test -n "$2" && echo "$2: $1" || echo "$1"; } >&2
}

# Display an error to stderr
# check _Verb if to display message
# exit if errorlevel >0 or "x"
# do not display error type in "Q" (quiet) mode
_Error() { # errormsg [errorlevel|"q" [errorlevel]]
local ER ret
case "${2:-1}" in
[1-9]*) ER="ERROR"; ret="${2:-1}" ;;
[0Ii]*) ER="INFO"; ret=0 ;;
[-WwXx]*) ER="WARNING"; ret=-1 ;;
[Qq]*) ER=""; ret="${3:--1}";;
*) ER="ERROR"; ret=1 ;;
esac
if [ "$_Verb" -ge 1 ] # verbose
then
__Message "$1" "$ER"
elif [ "$_Verb" -ge 0 ] # normal
then
test "$ret" -eq 0 || __Message "$1" "$ER" >&2
else # quiet
test "$ret" -le 0 || __Message "$1" "$ER" >&2
fi
test $ret -le 0 -a "${2:-1}" != "x" || exit $ret
}

# Display a message to stderr
_Msg() { # [message]
_Error "${*:-<STUB>}" q
}

# Display message in verbose mode only
_Debug() { # [message] [verbosity]
local v="${2:-0}"
if [ $_Verb -gt "$v" ]; then _Msg "$1"; fi
}

#==========================================================
# Temporary files and exit handler

# Remove all temporary files and directory
_clean_tmp() {
local F
test -z "$_TmpFiles" || echo "$_TmpFiles" | while read F
do test -z "$F" || rm -f "$F"; done

test -z "$_TmpDirs" || echo "$_TmpDirs" | while read F
do
case "$F" in
*/tmp/?*) # it seems safe to delete this
rm -rf "$F";;
"") ;;
*) _Error "It seems unsafe to delete '$F' directory" w ;;
esac
done
_TmpDirs=""; _TmpFiles=""
}

__cleanup_handler() { # [exit status]
trap - EXIT
_clean_tmp
exit "$1"
}

# Perform actions on exit
_exit_handler() {
__cleanup_handler "$?"
}

# Perform actions on deadly signal and exit
_signal_handler() {
__cleanup_handler 143 # SIGTERM+128
}

trap _exit_handler EXIT
trap _signal_handler HUP INT QUIT PIPE TERM

# create a temporary file and store its name to _TmpFiles
# second parameter means type: [-]d* -- directory, [-]p* -- pipe, other -- file
# (type is also used as "prefix" if later is not set)
# assign filename to "variable"
_TmpFile() { # variable [type [prefix [suffix]]]
local _F _P _Z _N="file" _X="XXXXXXXXXXXX"
case "$1" in
*[!_a-zA-Z0-9]*) _Error "Cannot store valuse to '$1' variable, please user alphanumeric name" ;;
"") _Error "no variable name provided to _TmpFile function" ;;
esac
case "$2" in
*p|p*) _P=""; _N="pipe";;
*d|d*) _P="-d"; _N="directory";;
esac
test -z "$3" || _N="${3##*/}"
_N="$_N.$_X$4"
_F=`mktemp -t $_P "$_AMe.$_N"` || _Error "Cannot create '$_F' temporary $_N"
case "$2" in
*p|p*) # XXX look for race conditions here
_Z="`mktemp XXXXXXXXXXXX`"
mv "$_F" "$_Z"
mkfifo "$_F"
rm -f "$_Z"
;;
esac
case "$2" in
*d|d*) _TmpDirs="$_TmpDirs
$_F" ;;
*) _TmpFiles="$_TmpFiles
$_F" ;;
esac
eval "export $1='$_F'"
}

# create a temporary directory and store its' name to _TmpDirs
# assign filename to "variable"
_TmpDir() { # variable
_TmpFile "$1" directory
}

#==========================================================
# Help system
## TODO long options

# WARNING: this function strongly depends on "case" operator programming style:
# key) # help string
# if help string contains capitalized word, it will be used as parameter name
# E. g.:
# o) # redirect output to FILE
# will produce this help string:
# -o FILE redirect output to FILE
# By default, help strings are searched
# from the first occurance of " getopt[s] " string to the first " esac$" pattern
# so keep a commentary after additional "esac" if it emerges inside
#
# Generted varsiables:
# _Options -- option string in getopts format

# Store a help information
_MakeHelp() { # description [tail_text [additional_help [start_pattern end_pattern]]]
local descr
local selfname
case "$1" in
*--*) selfname="${1%% -- *}"; descr="${1##* -- }" ;;
?*) selfname="$_Me"; descr="$1" ;;
"") _Error "Insufficient parameters in _MakeHelp" ;;
esac
local st="${4:-" getopts? .*_Options"}"
local en="${5:-"[ ]esac[ ]*$"}"
local sedfilter="/$st/,/$en/"
local sedFpattern='^[ ]*([^)]*)\)[ ]*#[ ]*(.*)'
local sedUpattern='^[ ]*([^)]*)\)[ ]*#[ ]*n![ ]*(.*)'
local sedPpattern='^[ ]*([^)]*)\)[ ]*#[ ]*([^!]*[^!A-Z]([A-Z]{3,}).*)'
local genhelp="$(_Esed -n "$sedfilter{
/$sedPpattern/s/$sedPpattern/ -\1 <\3> \2/p
s/([ ])!([A-Z])/\1\2/g
/$sedUpattern/s/$sedUpattern/ -\1 (TODO) \2/p
/$sedFpattern/s/$sedFpattern/ -\1 \2/p
}" "$_FMe")"
_Options=$(_Esed -n "$sedfilter{
/$sedPpattern/s/$sedPpattern/\1:/p
/$sedUpattern/n
/$sedFpattern/s/$sedFpattern/\1/p
}" "$_FMe" | sort | tr -d '\n')
_Usage="$selfname v$_Version -- $descr
Usage: $_Me [-$_Options]${2:+" "}$2"
_Help="
$genhelp${3:+$__CR}$3"
}

# Print error message and usage or usage and help (if no optarg), then exit
_ExitHelp() { # opt optarg [ret]
local msg
local ret="${3:-1}"
case "$1" in
"?") msg="Unknown option";;
":") msg="Option needs an argument";;
*) _Msg "$_Usage$_Help"; exit 0;;
esac
_Error "$msg: -$2
$_Usage
use -h key for long help
" $ret
}

#==========================================================
# Configuration file editing

# Set "Variable=Value" inside Context of File or append it at the start of the Context
_CfgEqSet() { # File Variable Value [Context=0,$]
local Context="${4:-1,\$}"
local N=$(sed -n "$Context{/^[ ]*$2[ ]*=/=}" "$1")
local n
# if Variable=Value exists
test -n "$N" &&
for n in $N
do # Replace
sed -i "$n""s/^\([ ]*$2[ ]*=[ ]*\).*/\1$(_Quote "$3")/" "$1"
done || { # Append
N=$(sed -n "$Context{=;q}" "$1")
test -n "$N" &&
sed -i "$N""a\
$2=$3
" "$1" ||
_Error "No '$Context' context found in $1" -1
}
}

__CfGet() { # File Context Variable Div Value Tail
test -z "$(sed -n "$2{=}" "$1")" &&
_Error "No '$2' context found in $1" -1 || {
local ret=$(sed -n "$2{/$3$4$5$6/{s/$3$4\($5\)$6/\1/p;q}}" "$1")
echo -n $ret
test -n "$ret"
}
}

# Print Value from "Variable=Value" inside Context of File
_CfgEqGet() { # File Variable [Context=1,$]
__CfGet "$1" "${3:-1,\$}" "^[ ]*$2" "[ ]*=[ ]*" ".*" ""
}

# Print Value from "Variable Value" inside Context of File
_CfgBlGet() { # File Variable [Context=1,$]
__CfGet "$1" "${3:-1,\$}" "^[ ]*$2" " *" ".*" ""
}

# Delete all "Variable=" entries inside Context of File
_CfgEqDel() { # File Variable [Context=1,$]
local Context="${3:-1,\$}"
test -z "$(sed -n "$Context{=}" "$1")" &&
_Error "No '$Context' context found in $1" -1 ||
sed -i "$Context{/^[ ]*$2[ ]*=/d}" "$1"
}

# Comment all "Variable=" entries inside Context of File
_CfgEqComm() { # File Variable [Context=1,$]
local Context="${3:-1,\$}"
test -z "$(sed -n "$Context{=}" "$1")" &&
_Error "No '$Context' context found in $1" -1 ||
sed -i "$Context{s/^\([ ]*$2[ ]*=.*\)/#\1/}" "$1"
}

# Uncomment all "#Variable=" entries inside Context of File
_CfgEqUnComm() { # File Variable [Context=1,$]
local Context="${3:-1,\$}"
test -z "$(sed -n "$Context{=}" "$1")" &&
_Error "No '$Context' context found in $1" -1 ||
sed -i "$Context{s/^[ ]*#\([ ]*$2[ ]*=.*\)/\1/}" "$1"
}

#==========================================================
# Parallel execution functions

# To run a number of tasks in parallel:
# first call _II_init <max_number_of_tasks>
# next call _II_run <task> [<parameters...>] for each task
# and last call _II_wait to wait for last task to be done

# Detect number of cores
_II_cores() { #
#N="`ls -d /proc/sys/kernel/sched_domain/cpu* 2>/dev/null | wc -l`" ||
N=`grep vendor_id /proc/cpuinfo 2>/dev/null | wc -l`
test $N != 0 ||
N="`sysctl -n kern.smp.cpus 2>/dev/null`"
test -z "$N" && _Msg "Warning: cannot determine number of CPUs"
echo "$(($N+0))"
}

# Initialize parallel environment for running maxproc tasks at once
_II_init() { # [maxproc]
_TmpFile __II_count # number of processes
_TmpFile __II_sync pipe # pipe for end-of-proc catching
__II_maxproc="${1:-$(_II_cores)}" # parallel slots number
__II_current=0 # tasks already executed
}

__II_done() { wc -l < $__II_count; }

__II_exit() {
trap - EXIT
echo $__II_err >> $__II_count
echo $__II_err > $__II_sync
exit $__II_err
}

__II_next() {
__II_err=0
trap __II_exit EXIT
"$@"
__II_err="$?"
}

__II_pause() { { read __II_err < $__II_sync; } 2>/dev/null || :; }

# Wait for empty slot becomes available, then execute a task
_II_run() { # task [args ...]
test $(($__II_current - $(__II_done) )) -lt $__II_maxproc || __II_pause
(__II_next "$@") &
__II_current=$(($__II_current + 1))
}

# Wait for all tasks to be done
_II_wait() {
while test $(($__II_current - $(__II_done) )) -ne 0
do __II_pause; done
}

#==========================================================
# Misc functions

## TODO: "A_b_c" "D_e" -> "A b c" "D e" call

# print N-th string character (or N-th substring of cell_size length)
_Left() { # String N [cell_size]
# TODO [cell_size]
if [ "$2" = "0" ]; then expr "$1" : "\(.\).*"
else expr "$1" : ".\{$2\}\(.\).*"
fi
}

# print newest/-oldest of version numbers given (via sort -V)
_Newer() { # [-] VersionNumber1 [VersionNumber2 ...]
local keys="-V"
test "$1" != "-" || { keys="-V -r"; shift; }
echo "$@" | tr " " "\n" | sort $keys | tail -1
}

# print pseudo-random 0..Max (32767 if Max undefined)
_Random() { # [Max]
echo $((`dd if=/dev/urandom count=2 bs=1 2>/dev/null | od -An -t u4`%${1:-32768}))
}

# parse "ipcalc Parameters" and get Field value
_IpCalc() { # Parameters Field
local ipc="ipcalc" # dependency avoidance
$ipc $1 | sed -n "/$2/s/$2[ ][ ]*\([^ /]*\).*/\1/p"
}

# print "prefix""N*str""suffix", if any
_NStr() { # N str=" " [prefix [suffix]]
case "$1" in
[1-9]*) printf "$3%$1s$4" '' | sed "s ${2:- }g";;
*) ;;
esac
}

# decode utf-8 output if not utf-8 locale is used
_DeU8() { # [locale]
local l="${1:-$LANG}"
case "$l" in
*[uU][Tt][fF]*8*) cat ;;
*) iconv -f utf-8 -t "${l##*.}" -r. ;;
esac
}

# remove arg from argument_string
_DelArg() { # argument_string arg
local a=" $1 "
a="${a% $2 *} ${a#* $2 }"
a="${a% }"; a="${a# }"
echo "$a"
}

# translate string of format "3-5,12,15" to "3 4 5 12 15"
# and print it using printf formatstring if specified (default is %d)
_ExpandEnum() { # [formatstring] number_list [divider [diapazone_divider]]
case "$1" in
%*) fmt="$1\n"; shift;;
*) fmt="%d\n";;
esac
local lst="$1"
local div="${2:-,}"
local dia="${3:--}"
local d n
for d in $(echo "$lst" | tr "$div" " "); do
case "$d" in
*-*) for n in $(seq $(echo "$d" | tr "-" " ") ); do printf "$fmt" "$n"; done ;;
*) printf "$fmt" "$d" ;;
esac
done
}

# quote Chars_regexp in Str (e. g. /home/dir -> \/home\/dir)
_Quote() { # Str [Chars_regexp=."[/]"]
# Thanks Teemu Likonen for the pattern
local chars="${2:-[]/[\^$.*]}"
printf '%s' "$1" | sed "s$chars\\\&g"
}

# use this to cat the stdin and echo args instead of running filter-like program
_CatEcho() { # [text]
# TODO: prog name or something
tty -s || cat
echo " $@"
}

# Pick file list of <prefix><version>-<timestamp><suffix>
# and generate <prefix><version-=1>-<current_timestamp><suffix>
# VERSION is hexadecimal
_RevFileNames() { # [prefix [suffix [max_version [stamp_format]]]]
local prefix="${1:-file.}"
local suffix="${2:-.log}"
local vers="${3:-FFFF}"
local stamp="$(date "${4:-+%Y-%m.%d-%H:%M}")"

local last="$(ls "$prefix"*[-.:,_]*"$suffix" 2> /dev/null | sort | head -1)"
test -n "$last" || last="$prefix$vers-$stamp$suffix"
local repf="$(_Quote "$prefix")"
local resf="$(_Quote "$suffix")"
local new="$(echo "$last" | _Esed "s/${repf}([[:xdigit:]]+).*/\1/")"
local div="$(echo "$last" | _Esed "s/${repf}[[:xdigit:]]+([^[:digit:]]*).*/\1/")"
echo "$prefix$(printf "%0${#new}X" "$((0x$new-1))")$div$stamp$suffix"
}

# Grep digest from NISH file
_Digest() { # [Name_pattern [filename]]
#egrep "^(#([^#!]|\$|##)|(export +)?_[^_]$1[_a-zA-Z0-9-]+(\(\)|.*# ))" "${2:-$0}" |
local name="${1:-[^_]}"
_Esed -n 's/^#[ *]*$/#/p
/^#([^!#]|.#)/p
s/^(export +)?(_('"$name"')[_a-zA-Z0-9]+)=[^=]*#[ ]*(.*)/\2 # \4/p
s/^(_('"$name"')[_a-zA-Z0-9]+)[ ]*\(\)[ ]*\{([ ]*#[ ]*(.*))?/\1() \4\
/p
' "${2:-0}"
}

case "$_GMe" in
functions|*.functions) # directly called
echo "$_GMe v$__Version" >&2
tty -s && PG=less || PG="cat -s"
_Digest "[^_]" "$_FMe" | $PG
;;
esac
nish-functions-1.02/functions.ascii000075500000000000000000000050441203751511500174310ustar00rootroot00000000000000#!/bin/sh
###########################################################
#
# ASCII and ANSI sequences.
# See the script for variables defined.
#

## WARNING: Now turn -x off for not to display ESC-sequences
case "$-" in
*x*) __IsXFlag="x"; set +x;
esac

## converted from ascii(7)
_ASCII_NUL="$(/bin/echo -en '\000')"
_ASCII_SOH="$(/bin/echo -en '\001')"
_ASCII_STX="$(/bin/echo -en '\002')"
_ASCII_ETX="$(/bin/echo -en '\003')"
_ASCII_EOT="$(/bin/echo -en '\004')"
_ASCII_ENQ="$(/bin/echo -en '\005')"
_ASCII_ACK="$(/bin/echo -en '\006')"
_ASCII_BEL="$(/bin/echo -en '\007')"
_ASCII_BS="$(/bin/echo -en '\010')"
_ASCII_HT="$(/bin/echo -en '\011')"
_ASCII_LF="$(/bin/echo -en '\012')"
_ASCII_VT="$(/bin/echo -en '\013')"
_ASCII_FF="$(/bin/echo -en '\014')"
_ASCII_CR="$(/bin/echo -en '\015')"
_ASCII_SO="$(/bin/echo -en '\016')"
_ASCII_SI="$(/bin/echo -en '\017')"
_ASCII_DLE="$(/bin/echo -en '\020')"
_ASCII_DC1="$(/bin/echo -en '\021')"
_ASCII_DC2="$(/bin/echo -en '\022')"
_ASCII_DC3="$(/bin/echo -en '\023')"
_ASCII_DC4="$(/bin/echo -en '\024')"
_ASCII_NAK="$(/bin/echo -en '\025')"
_ASCII_SYN="$(/bin/echo -en '\026')"
_ASCII_ETB="$(/bin/echo -en '\027')"
_ASCII_CAN="$(/bin/echo -en '\030')"
_ASCII_EM="$(/bin/echo -en '\031')"
_ASCII_SUB="$(/bin/echo -en '\032')"
_ASCII_ESC="$(/bin/echo -en '\033')"
_ASCII_FS="$(/bin/echo -en '\034')"
_ASCII_GS="$(/bin/echo -en '\035')"
_ASCII_RS="$(/bin/echo -en '\036')"
_ASCII_US="$(/bin/echo -en '\037')"
_ASCII_SPACE="$(/bin/echo -en '\040')"
_ASCII_DEL="$(/bin/echo -en '\177')"
## ANSI
_ANSI_CSI="$_ASCII_ESC["
_ANSI_OSC="$_ASCII_ESC]"
_ANSI_ST="$_ASCII_ESC\\"
## aliases
_ASCII_RUBOUT="$_ASCII_DEL"
_ESC="$_ASCII_ESC"
_CSI="$_ANSI_CSI"
_OSC="$_ANSI_OSC"
__ANSI_LOCALFUN=""

## WARNING: Now set -x back on if any
test -z "$__IsXFlag" || set -x;

## Echo some standard-formed sequences
__ANSI_Do() { # control type [parameters [parameter ...]]
local seq="$1"; shift
local typ="$1"; shift
local first=1
local par
echo -n "$seq"
for par; do
test "$first" = 1 && first=0 || echo -n ';'
echo -n "$par"
done
echo -n "$typ"
}

# Emit ansi CSI 'CSIpar1;par2;...;type'
_ANSI_DoCSI() { # type [parameter [parameter ...]]
__ANSI_Do "$_CSI" "$@"
}

# Emit ansi OSC 'OSCpar1;par2;...;BEL'
_ANSI_DoOSC() { # [parameter [parameter ...]]
__ANSI_Do "$_OSC" "$_ASCII_BEL" "$@"
}

if [ -z "$_FMe" ]; then
. "$(functions.locate)" || exit 1
if [ "$(realpath "$0")" = "$(realpath "$_FMe")" ]; then
case "$@" in
"") _Digest "ASCII_|ANSI_" "$_FMe";;
*) __ANSI_LOCALFUN="$1"; shift; "$__ANSI_LOCALFUN" "$@";;
esac
fi
fi
nish-functions-1.02/functions.autobuild000075500000000000000000000133331203751511500203310ustar00rootroot00000000000000#!/bin/sh -e
###########################################################
#
# Autobuild function set.
# Use "<SCRIPTNAME> _AB_Full <STAGENAME>" to perform stage actions
#

## TODO beta versions must be %name-%version-%release.%beta

_AB_Direct=""
test -n "$_Me" || { _AB_Direct=1; . "$(functions.locate)"; } || exit 1
_AB_Local=.gear/autobuild
_AB_WatchFile=""
__AB_Name="*"
__AB_UserAgent="<null>"
_TmpFile __AB_U # uscan file

# Initialize gear environment (must be called first)
_AB_Init() {
# Set name
__AB_Name="$(basename "$(pwd)")"
_AB_Actual="$(git describe)"
# Get gear environment
eval `gear --command env | grep '^gear_'`
# Check there's no errors
test -n "$gear_pkg_version" -a -n "$gear_pkg_name"
# Dirname not always = pkg_name; get it from specfile name
test -d "$gear_pkg_name" && gear_dir_name="$gear_pkg_name" || gear_dir_name="${gear_specfile%%.spec}"
# Determine watchfile, if any
test -r "$gear_pkg_name.watch" && _AB_WatchFile="$gear_pkg_name.watch" || :
test -r "$_AB_Local.watch" && _AB_WatchFile="$_AB_Local.watch" || :
}

## TODO __AB_Call Name -> $_AB_Local.$Name or __AB_$Name

# Check new version/name/URL of upstream
_AB_Uscan() { # [uscan parameters]
local SIH={$SSL_IGNORE_HOSTNAME:-1}
if [ -x "$_AB_Local.uscan" ]; then
SSL_IGNORE_HOSTNAME=$SIH "$_AB_Local.uscan" "$@"
else SSL_IGNORE_HOSTNAME=$SIH __AB_Uscan "$@"
fi
}

# Get upstream environment
_AB_Upstream() {
if [ -r "$_AB_Local.upstream" ]; then . "$_AB_Local.upstream"; else __AB_Upstream; fi
} # sets: new_version new_url

# Based on debian uscan; returns version\nURL as the result of uscan
# When $__AB_DOWNLOAD_PATH is defined, downloads the file
__AB_Uscan() { # [watchfile]
test -r "${1:-$_AB_WatchFile}" || _Error "No '${1:-$_AB_WatchFile}' watch file"
sed "
s/@DIR@/$gear_dir_name/g
s/@PKG@/$gear_pkg_name/g
" < ${1:-$_AB_WatchFile} > $__AB_U
if [ -z "$__AB_DOWNLOAD_PATH" ] ; then
LC_ALL=POSIX uscan --user-agent="$__AB_UserAgent" --watchfile $__AB_U --upstream-version=$gear_pkg_version --package $gear_pkg_name --report-status |
sed -rn 's/Newest version on remote site is ([^ ]+), local version is.*/\1/p
/Newer version .* available on remote site/{
n
s/^[ ]*//p
}'
else
LC_ALL=POSIX uscan --user-agent="$__AB_UserAgent" --watchfile $__AB_U --upstream-version=$gear_pkg_version --package $gear_pkg_name --download --destdir "$__AB_DOWNLOAD_PATH"
fi
}

__AB_Upstream() {
uscan_log="$(_AB_Uscan)"
new_version="$(echo "$uscan_log" | head -1)"
new_url="$(echo "$uscan_log" | sed -n '2p')"
}

# Get upstream source
_AB_Update() {
if [ -r "$_AB_Local.update" ]; then . "$_AB_Local.update"; else __AB_Update; fi
} # NB: sets $new_source

__AB_Update() {
_TmpDir downloads
if [ -x "$_AB_Local.uscan" ]; then
( cd $downloads; wget --user-agent="$__AB_UserAgent" --content-disposition --no-check-certificate "$new_url" )
else
( __AB_DOWNLOAD_PATH="$downloads" __AB_Uscan )
fi
ntarball=`find $downloads -type f | tail -1`
# remove spaces, so RPM doesn't like them
tarball="$(echo -n "$ntarball" | tr '[:blank:]' '_')"
test "$tarball" = "$ntarball" || mv "$ntarball" "$tarball"
if egrep -q 'base=([.]|$| )' .gear/rules; then
gear-update -a $tarball $gear_dir_name
else
gear-update $tarball $gear_dir_name
fi
rm -f $gear_dir_name/.gitignore
new_source=`basename "$tarball" | sed "s/$new_version/%{version}/;s/$gear_pkg_name/%{name}/"`
}

# Update local files (e. g. spec)
_AB_Bump() {
if [ -r "$_AB_Local.bump" ]; then . "$_AB_Local.bump"; else __AB_Bump; fi
}

__AB_Bump() {
# TODO Release.%beta if beta
# TODO rename file when source tarball name sucks
sed -i "/^Version:/c\
Version: $new_version
/^Release:/c\
Release: alt1
/^Source:/c\
Source: $new_source
" $gear_specfile
add_changelog -e "- Autobuild version bump to $new_version" $gear_specfile
cleanup_spec $gear_specfile
}

# Compare local and upstream version
_AB_Compare() { # [message_details]
local details
test -z "$1" && details="$__AB_Name" || details="$1"
test "$new_version" != "$gear_pkg_version" || _Error "$details: same version $new_version" x
test "`_Newer "$new_version" "$gear_pkg_version"`" != "$gear_pkg_version" ||
_Error "$details: upstream version $new_version is older than local $gear_pkg_version" x
}

# Generate a watchfile from given file download URL and watch page
_AB_GenWatch() { # URL [name] [version]
local URL="$1"
local name="${2:-$gear_pkg_name}"
local vers="${3:-$gear_pkg_version}"
local verl="$vers"
local vre d p r
for d in "[[:digit:]] [:digit:]" "[.] ." "[[:alpha:]] [:alpha:]" "_ _"; do
p="${d%% *}"; r="${d##* }";
d="$(echo "${verl}" | tr -d "$p")"
test "$d" = "$verl" || { verl="$d"; vre="$vre$r"; }
done
watch_page="$(echo "$URL" | sed "s/$vers/(\\\d[$vre$verl]+)/g")"
echo "version=3"
echo "$watch_page"
}

# Test build and commit if successful (gear version)
_AB_Testbuild() {
if [ -r "$_AB_Local.testbuild" ]; then . "$_AB_Local.testbuild"; else __AB_Testbuild; fi
}

__AB_Testbuild() {
git add .
if [ -f .gear/tags/list ]; then gear-store-tags -ac; fi &&
gear --commit --hasher -- hsh &&
gear-commit --no-edit -a || # Commit if successful build
{ _Msg "Build $gear_pkg_name FAILED"; git reset --hard "$_AB_Actual"; } # Reset otherwise
}

_AB_Full_Stages="Init Upstream Compare Update Bump Testbuild" # update stages
# _AB_Full_Stages="Init Upstream Compare Update Bump Testbuild"
# Do all the work (or partially up to given stage)
_AB_Full() { # [stage]
local stage
for stage in $_AB_Full_Stages; do
eval _AB_$stage
test $stage != "$1" || break
done
# TODO Notify user
}

case "$_AB_Direct" in
1) case "$1" in
"") _Digest AB_ "$_FMe";;
_*) _AB_Init; "$@" ;;
*) _AB_Init; _AB_GenWatch "$@";;
esac;;
*) ;;
esac
nish-functions-1.02/functions.locate000075500000000000000000000002431203751511500176040ustar00rootroot00000000000000#!/bin/sh
# You can modify this depending on where functions files are stored
__LIBEXEC="$(dirname "$(realpath "$0")")"
echo "$__LIBEXEC/$(basename "$0" .locate)"
nish-functions-1.02/functions.xautomation000075500000000000000000000077711203751511500207220ustar00rootroot00000000000000#!/bin/sh
###########################################################
#
# XAutomation support

test -n "$_Me" || . "$(functions.locate)" || exit 1

_XA_WAIT=0.1 # seconds to sleep between commands

__XA_Wait() {
test -z "$_XA_WAIT" -o "$_XA_WAIT" = 0 || sleep $_XA_WAIT
}

__XA_import() {
if [ "$_Verb" -lt 1 ]; then
import -depth 8 -silent "$@"
else
import -depth 8 "$@"
fi
}

# Select and import selected area to filename
_XA_Import() { # filename [other import keys]
__XA_import -trim "$@"
}

# Import window_id content into filename
_XA_Snap() { # filename window_id [other import keys]
local f="$1" w="$2"
shift; shift
__XA_import -window "${w:-root}" "$f" "$@"
}

# convert PNG_filename image to pat
_XA_Png2Pat() { # PNG_filename [OUT_Filename]
local A=${1:-$(ls [0-9]*png | tail -1)}
local B=${2:-${A%%.png}.pat}
png2pat "$A" > "$B"
}

# Find WindowID(s) of command running using command line pattern
_XA_FindClient() { # Cmdline
xlsclients -l | sed -n '/^Window/{s/.* \(.*\):/\1/;h};/'"$1"'/{g;p}'
}

# Find WindowID(s) of X11 window registered using Title, resource name and class
_XA_FindWindow() { # Title [res_name [res_class]]
xwininfo -root -tree | sed -n "s/[ ]*\(0x[a-z0-9]*\) \"$1\": (\"${2:-.*}\" \"${3:-.*}\").*/\1/p"
}

# Find QEMU "Name" windowID
_XA_QEMUFindWindow() { # Name
_XA_FindWindow "QEMU ($1)" "qemu-.*" "qemu-.*"
}

# Find VirtualBox "Name" windowID
_XA_VBFindWindow() { # Name
_XA_FindWindow "$1 .*" "Qt-subapplication" "VirtualBox"
}

# Find SDL-VirtualBox "Name" windowID
_XA_VBSDLFindWindow() { # Name
_XA_FindWindow "$1 .*" "VBoxSDL" "VBoxSDL"
}

# Cache FILENAME with .FILENAME.ext format
_XA_CacheSnapPatt() { # {Snapshot|-} [Pattern [Pattern]]
local cac tmpppng N
if [ "$1" != "-" ]; then
cac=".$1.png"
if [ ! -r "$cac" -o "$1" -nt "$cac" ]; then
convert -depth 8 "$1" "$cac"
#cp "$1" "$cac"
fi
fi
shift
for N; do
cac=".$N.pat"
if [ ! -r "$cac" -o "$1" -nt "$cac" ]; then
if [ "${N##*.}" != "pat" ]; then
_TmpFile tmppng _XA png
## this makes visgrep empty :(
#convert -depth 8 "$N" "$tmppng"
#_XA_Png2Pat "$tmppng" "$cac"
_XA_Png2Pat "$N" "$cac"
else
cp "$N" "$cac"
fi
fi
done
}

# VisGrep on Snapshot, also cache files with _XA_CacheSnapPatt
# Return X Y
_XA_VisGrep() { # Snapshot Locator
local snap=".$1.png" patt=".$2.pat"
test -r "$1" || _Error "No $1 file found"
test -r "$2" || _Error "No $2 file found"
_XA_CacheSnapPatt "$@"
visgrep "$snap" "$patt" | sed 's/\(.*\),\(.*\) .*/\1 \2/'
}

# Wait 10 seconds for Snapshot containing Locator
_XA_VisWait() { # Snapshot Locator [seconds [window_id]]
local n=${3:-10}
local w=${4:-root}
test $_Verb -lt 1 || _Msg "Waiting for $2 on $1 ($w) for $n seconds"
test -r "$2" || _Error "No $2 file found"
while [ "$n" -gt 0 ];
do
_XA_Snap "$1" $w
test -z "$(_XA_VisGrep "$1" "$2")" || { true && return; }
n="$(($n-1))"
sleep 1
test "$_Verb" -gt 1 && echo -n '.'
done
test $_Verb -lt 1 || _Msg "Cannot locate $2 on $1"
return 1
}

# Click where Locator is found on snapshot
# left align is to click leftmost square fragment of rectangle
_XA_VisClick() { # Snapshot Locator [button_number [align]]
local XY="$(_XA_VisGrep "$@")"
if [ -z "$XY" ]; then
_Error "Cannot locate $2 on $1"
else
xte "mousemove $XY"
local H="$(identify "$2" | sed -n 's/.* PNG [^x]*x\([^x ]*\).*/\1/p')"
local W="$(identify "$2" | sed -n 's/.* PNG \([^x ]*\).*/\1/p')"
case "$4" in
left) xte "mousermove $(($H/2)) $(($H/2))";;
center) xte "mousermove $(($W/2)) $(($H/2))";;
right) xte "mousermove $(($W-$H/2)) $(($H/2))";;
*);;
esac;

__XA_Wait
xte "mousedown ${3:-1}"
__XA_Wait
xte "mouseup ${3:-1}"
#xte "mousemove $XY" "mousedown ${3:-1}" "mouseup ${3:-1}"
fi
}

# Send a sequence of keys with xte
_XA_xteKeys() { # Key1 [Key2 [...]]
test $_Verb -gt 1 || _Msg "Sending keys $@"
for k; do xte "key $k"; done
}

case "$_Me$@" in
*functions.xautomation) _Digest XA "$_FMe";;
*) ;;
esac
nish-functions-1.02/functions.xterm000075500000000000000000000071561203751511500175060ustar00rootroot00000000000000#!/bin/sh
###########################################################
#
# XTerm voodoo spells

test -n "$_Me" || . "$(functions.locate)" || exit 1
test -n "$_ASCII_ESC" || . "$(functions.locate)".ascii || exit 2

## WARNING: Now turn -x off for not to display ESC-sequences
case "$-" in
*x*) __IsXFlag="x"; set +x;
esac

## XTerm stuff
_XTERM_4014="$_CSI?38h"
_XTERM_RAISE="$_CSI""5t"
_XTERM_LOWER="$_CSI""6t"
_XTERM_Cursor() { # {on|off|blink|steady|_blink|_steady}
case "$1" in
on|+) _ANSI_DoCSI h "?25";;
off|-) _ANSI_DoCSI l "?25";;
blink|1) _ANSI_DoCSI " q" 1;;
steady|2) _ANSI_DoCSI " q" 2;;
_blink|3) _ANSI_DoCSI " q" 3;;
_steady|4) _ANSI_DoCSI " q" 4;;
esac
}
## TODO many more

## Tektronix 4014 stuff
_4014_RESET="$_ESC$_ASCII_FF"
_4014_XTERM="$_ESC$_ASCII_ETX"
_4014_FONTL="$_ESC""8"
_4014_FONT2="$_ESC""9"
_4014_FONT3="$_ESC"":"
_4014_FONTS="$_ESC"";"
_4014_SOLID="$_ESC"'`'
_4014_DOTTED="$_ESC""a"
_4014_DOT_DASHED="$_ESC""b"
_4014_SHORT_DASHED="$_ESC""c"
_4014_LONG_DASHED="$_ESC""d"
_4014_GRAPH="$_ASCII_GS"
_4014_POINT="$_ASCII_FS"
_4014_ALPHA="$_ASCII_US"
_4014_GIN="$_ESC$_ASCII_SUB"
## TODO some more

__4014_Hi=' !"#$%&'"'"'()*+,-./0123456789:;<=>?'
__4014_LoX='@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_'
__4014_LoY='`abcdefghijklmnopqrstuvwxyz{|}~'

## WARNING: Now set -x back on if any
test -z "$__IsXFlag" || set -x;

_4014_Width=1024
_4014_Height=780

__4014_Timeout=1000

__XTTTY="/dev/tty" # tty to output and input

# Xterm functions:

# Tackle XTerm to push response on string (e. g. ^[]50;?^G respond with fontname)
# Response must end with response_end (default "t")
# WARNING: this can freeze your terminal to death!
_XTERM_Response() { # string [response_end [response_start [tty]]]
# TODO [tty]
local XT STTY
STTY=`stty -g < "$__XTTTY"`
stty raw -echo < "$__XTTTY"
echo -n "$1" > "$__XTTTY"
XT=`awk -v RS="${2:-t}" '{print; exit; }'`
stty $STTY < "$__XTTTY"
test -z "$3" && echo -n "$XT" || echo -n "${XT#$3}"
}

__XTERM_CSI2t() { # type [par1 par2]
local T="$1"; shift
test "$#" = 0 &&
echo $(_XTERM_Response "$(_ANSI_DoCSI t 1$T)" t "$(_ANSI_DoCSI '' $T '')") | sed 's/\(.*\);\(.*\)/\2 \1/' ||
_ANSI_DoCSI t $T $2 $1
}

__XTERM_CSIt() { # type [par1 par2]
local T="$1"; shift
test "$#" = 0 &&
echo $(_XTERM_Response "$(_ANSI_DoCSI t 1$T)" t "$(_ANSI_DoCSI '' $T '')") | sed 's/\(.*\);\(.*\)/\1 \2/' ||
_ANSI_DoCSI t $T "$@"
}

# Get/set XTerm size in characters
_XTERM_Size() { # [width height]
__XTERM_CSI2t 8 "$@"
}

# Get/set XTerm size in pixels
_XTERM_WH() { # [width height]
__XTERM_CSI2t 4 "$@"
}

# Get/set XTerm position in pixels
_XTERM_Pos() { # [x y]
__XTERM_CSIt 3 "$@"
}

# Get/set current XTerm font
_XTERM_Font() { # [font_to_set]
test -z "$1" &&
_XTERM_Response "$(_ANSI_DoOSC 50 '?')" "$_ASCII_BEL" "$_OSC""50;" ||
_ANSI_DoOSC 50 "$1"
}

# Tektronix 4014 functions:
# convert X and Y to tek character coordinates
_4014_Coord() { # X Y
local LoX LoY HiX HiY
LoX=$(($1%32)); HiX=$(($1/32))
LoY=$(($2%32)); HiY=$(($2/32))
echo -n "$(_Left "$__4014_Hi" $HiY)$(_Left "$__4014_LoY" $LoY)$(_Left "$__4014_Hi" $HiX)$(_Left "$__4014_LoX" $LoX)"
}

_4014_Init() {
echo -n "$_XTERM_4014$_4014_RESET"
}

_4014_Dot() { # X Y
_4014_Line "$1" "$2" "$1" "$2"
}

_4014_Line() { # X1 Y1 X2 Y2 [type]
echo -n "$_4014_GRAPH"
test -z "$5" || echo -n "$_ESC$5"
_4014_Coord $1 $2
_4014_Coord $3 $4
echo -n "$_4014_ALPHA"
}

case "$_GMe$@" in
functions.xterm) _Digest "XTERM|4014" "$_FMe";;
functions.xterm?*)
case "`export LC_ALL=POSIX; type "$1" 2>&1`" in
*" function"*) "$@";;
*) eval echo "\$$@";;
esac
;;
*);;
esac
 
дизайн и разработка: Vladimir Lettiev aka crux © 2004-2005, Andrew Avramenko aka liks © 2007-2008
текущий майнтейнер: Michael Shigorin