add bash-complete scripts

This commit is contained in:
2023-10-15 23:51:49 +08:00
parent 98fae3427e
commit 6cb42d6b8d
6 changed files with 173 additions and 198 deletions

View File

@@ -13,14 +13,7 @@ if sys.getdefaultencoding() != 'utf-8':
reload(sys)
sys.setdefaultencoding('utf-8')
def ttySize():
try:
(width, heigh) = shutil.get_terminal_size()
except:
width = 80
return width
os.environ['COLUMNS'] = str(ttySize())
os.environ['COLUMNS'] = str(sunhpc.commands.get_help_width())
syslog.openlog('SunhpcCMD', syslog.LOG_PID, syslog.LOG_LOCAL0)
try:

View File

@@ -14,7 +14,6 @@ import socket
import syslog
import struct
import sqlite3
import termios
import argparse
import textwrap
import datetime
@@ -38,10 +37,8 @@ DEFAULT_HELP_WIDTH = 8
def get_help_width():
try:
data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234')
columns = int(struct.unpack('hh', data)[1])
(columns, heigh) = shutil.get_terminal_size()
except (IOError, ValueError) as e:
print ("terminal size detection failed, using default width.")
return DEFAULT_HELP_WIDTH
columns = columns - RIGHT_PADDING
@@ -1255,8 +1252,22 @@ class Command(object):
o.runWrapper(n, args)
return o.getText()
def remove_empty_values(self, input_list):
"""
从列表中删除空值
:param input_list: 输入的列表
:return: 不包含空值的新列表
"""
# 使用列表推导式过滤掉空值
result_list = [value for value in input_list if value is not None and value != ""]
return result_list
def runWrapper(self, name, args):
# 删除所有空值和None.
args = self.remove_empty_values(args)
username = pwd.getpwuid(os.geteuid())[0]
if args:
command = '%s %s' % (name, ' '.join(args))

View File

@@ -25,6 +25,7 @@ class Command(sunhpc.commands.list.command):
def run(self, params, args):
(subdir, cols) = self.fillParams([('subdir', ), ('cols', 80) ], params)
if subdir:
filepath = os.path.join(sunhpc.commands.__path__[0], subdir)
modpath = 'sunhpc.commands.%s' % '.'.join(subdir.split(os.sep))

View File

@@ -0,0 +1,116 @@
#coding:utf-8
import os
import sys
import json
import sunhpc
class Command(sunhpc.commands.report.command):
"""
Output the path prefix for the location of the Rocks distribution.
<example cmd='report distro'>
Output the current path prefix to the distribution.
</example>
"""
def run(self, params, args):
basepath = '/opt/sunhpc/lib'
cmd = args
dotscmd = ''
listcmd = []
module = None
if len(cmd):
s = 'sunhpc.commands.%s' % '.'.join(cmd)
try:
__import__(s)
module, listcmd, dotscmd = eval(s), s.split('.'), '.'.join(cmd)
i = 1
except:
module = None
else:
listcmd = ['sunhpc', 'commands']
if not module:
for i in range(len(args), 0, -1):
s = 'sunhpc.commands.%s' % '.'.join(args[:i])
try:
__import__(s)
module, listcmd, dotscmd = eval(s), s.split('.'), '.'.join(args[:i])
if module:
break
except ImportError:
listcmd = s.split('.')[:-1]
continue
cmdpath = os.path.join(basepath, '/'.join(listcmd))
cmddirs = []
for d in os.listdir(cmdpath):
tmpdirs = os.path.join(cmdpath, d)
if d.startswith('__'):
continue
if not os.path.isdir(tmpdirs):
continue
cmddirs.append(d)
print (' '.join(cmddirs))
try:
o = getattr(module, 'Command')(None)
except AttributeError:
sys.exit(0)
if o.MustBeRoot and not self.isRootUser():
sys.exit(0)
results = []
for arg in o.usage().split():
tmp = arg.split('=', 1)
if len(tmp) != 2:
continue
tmpstr = arg.replace('[', '')
tmpstr = tmpstr.replace(']', '')
tmpstr = tmpstr.split('=')[0] + '='
results.append(tmpstr)
#print (' '.join(results))
#print ('--add-interface= --set-net=')
print ('--envs= prefix=')
RollName = "base"

View File

@@ -51,7 +51,10 @@ class Command(command):
softname = 'autodock'
suffname = 'tar.gz'
dirsname = os.path.join(source, 'hpcsoft', 'AutoDock')
try:
verslist = self.getVersions(key=softname, suffix=suffname, dirs=dirsname)
except FileNotFoundError as e:
self.msg(str(e), 'a')
if len(args):
version = args[0]

View File

@@ -1,198 +1,49 @@
#/usr/bin/env bash
# sunhpc(1) completion
_sunhpc_array_delete_at()
{
eval "local ARRAY=(\"\${$1[@]}\")"
local i
local tmp=()
local lower=$2
local upper=${3:-$lower}
for i in "${!ARRAY[@]}"; do
if [[ "$i" -lt "$2" || "$i" -gt "${3-$2}" ]]; then
tmp=("${tmp[@]}" "${ARRAY[$i]}")
fi
done
eval "$1=(\"\${tmp[@]}\")"
}
_sunhpc()
{
local cur prev words cword split
_init_completion -s || return
local cur prev words cword i output
_init_completion || return
COMPREPLY=()
_get_comp_words_by_ref -n : cur prev words
_sunhpc_array_delete_at words $((cword+1)) ${#words[@]}
_sunhpc_array_delete_at words 0
# Command data: Main commands
cmds='add build check create database list pxelinux repair report run set soft'
# sunhpc add commands
cmds_add='host security'
cmds_add_host='interface security cpus= membership= os= rack= rank= help'
cmds_add_host_interface='ip= mac= name= subnet= help'
cmds_add_host_security='force= help'
cmds_add_security='force= help'
# sunhpc build commands
cmds_build='init initializes'
cmds_build_init='help'
cmds_build_initializes='help'
# sunhpc check commands
cmds_check='services help'
cmds_check_services='help'
# sunhpc create commands
cmds_create='distro pxelinux repos roll rpm security xml help'
cmds_create_distro='arch= dist= md5= rolls= root= version= help'
# sunhpc create pxelinux commands
cmds_create_pxelinux='client efiboot kickstart product squashfs updates vminitrd'
cmds_create_pxelinux_client='basedir= outdir= version= help'
cmds_create_pxelinux_efiboot='basedir= outdir= cdrom= version= help'
cmds_create_pxelinux_kickstart='basedir= outdir= version= help'
cmds_create_pxelinux_product='basedir= outdir= version= help'
cmds_create_pxelinux_squashfs='basedir= outdir= cdrom= version= help'
cmds_create_pxelinux_updates='basedir= outdir= cdrom= version= help'
cmds_create_pxelinux_vminitrd='basedir= outdir= cdrom= version= help'
# sunhpc create repos commands
cmds_create_repos='file= gpk= web= help'
# sunhpc create roll commands
cmds_create_roll='boot= sign= help'
# sunhpc create rpm commands
cmds_create_rpm='arch= name= outdir= prefix= release= source= spec= version= help'
# sunhpc create security commands
cmds_create_security='sshd users keyname= force= help'
cmds_create_security_sshd='help'
cmds_create_security_users=' safedir= help'
# sunhpc create xml commands
cmds_create_xml=' arch= bin= boot= flag= name= os= release= rolls= src= version= help'
# sunhpc database commands
cmds_database='init help'
cmds_database_init='help'
# sunhpc list commands
cmds_list='host license help'
cmds_list_host='interface help'
cmds_list_host_interface='help'
cmds_list_license='help'
# sunhpc pxelinux commands
cmds_pxelinux='build help'
cmds_pxelinux_build='autofs dhcpd httpd nodes tftpd clean= iso= mnt= pxesrv= help'
cmds_pxelinux_build_autofs='quiet= help'
cmds_pxelinux_build_dhcpd='quiet= help'
cmds_pxelinux_build_httpd='pxedir= quiet= help'
cmds_pxelinux_build_nodes='quiet= help'
cmds_pxelinux_build_tftpd='pxedir= quiet= help'
# sunhpc repair commands
cmds_repair='permission users help'
cmds_repair_permission='help'
cmds_repair_users='authorized help'
cmds_repair_users_authorized='all= help'
# sunhpc report commands
cmds_report='distro host kickstart knownhosts nextip yumrepos help'
cmds_report_distro='help'
cmds_report_host='attr dhcpd help'
cmds_report_host_attr='attr= pydict= help'
cmds_report_host_dhcpd='help'
cmds_report_kickstart='help'
cmds_report_knownhosts='help'
cmds_report_nextip='baseip= increment= help'
cmds_report_yumrepos='proto= url= help'
# sunhpc run commands
cmds_run='host help'
cmds_run_host='collate= command= delay= managed= num-threads= stats= timeout= x11= help'
# sunhpc set commands
cmds_set='grub host help'
cmds_set_grub='default= help'
cmds_set_host='boot cpus interface help'
cmds_set_host_boot='action= help'
cmds_set_host_cpus='cpus= help'
cmds_set_host_interface='iface ip mac name subnet help'
cmds_set_host_interface_iface='iface= mac= help'
cmds_set_host_interface_ip='iface= ip= help'
cmds_set_host_interface_mac='iface= mac= help'
cmds_set_host_interface_name='iface= name= help'
cmds_set_host_interface_subnet='iface= subnet= help'
# sunhpc soft commands
cmds_soft='autodock cmake gaussian gromacs mpi ntfs nvidia openmpi schrodinger help'
cmds_soft_autodock='envs= prefix= source= help'
cmds_soft_cmake='envs= prefix= source= help'
cmds_soft_gaussian='envs= prefix= source= help'
cmds_soft_gromacs='envs= prefix= source= help'
cmds_soft_mpi='envs= prefix= source= help'
cmds_soft_ntfs='envs= prefix= source= help'
cmds_soft_nvidia='envs= prefix= source= help'
cmds_soft_openmpi='envs= prefix= source= help'
cmds_soft_schrodinger='envs= prefix= source= help'
# sunhpc sync commands
cmds_sync='config users help'
cmds_sync_config='help'
cmds_sync_users='help'
# sunhpc help commands.
cmds_help='help'
cmd=""
words[0]=""
completed="${cmds}"
for var in "${words[@]:1}"
do
if [[ ${var} == -* ]] ; then
break
fi
if [ -z "${cmd}" ] ; then
proposed="${var}"
else
proposed="${cmd}_${var}"
fi
local i="cmds_${proposed}"
local comp="${!i}"
if [ -z "${comp}" ] ; then
break
fi
if [[ ${comp} == -* ]] ; then
if [[ ${cur} != -* ]] ; then
completed=""
break
fi
fi
cmd="${proposed}"
completed="${comp}"
for i in ${!words[@]}; do
words[i]="$(printf '%s' "${words[i]}" | xargs printf '%s\n' 2>/dev/null || true)"
done
if [ -z "${completed}" ] ; then
COMPREPLY=( $(compgen -f -- "$cur" ) $( compgen -d -- "$cur" ) )
else
COMPREPLY=( $(compgen -W "${completed}" -- "${cur}") )
if [[ "$cur" =~ ^[[:space:]]+ ]]; then
cur=''
fi
# do not append a space to words that end with =
#[[ $COMPREPLY == *= ]] && compopt -o nospace
[[ $COMPREPLY == *= ]] && compopt -o nospace || compopt -o dirnames
output="$(sunhpc report completion ${words[@]} 2>/dev/null)"
#_available_interfaces
if [ $? = 65 ]; then
compopt -o default
COMPREPLY=()
return 0
fi
local IFS=$'\n'
COMPREPLY=( $( compgen -W '$output' -- $cur ) )
} &&
complete -F _sunhpc sunhpc
# ex: ts=4 sw=4 et filetype=sh