/
steamsh
executable file
·173 lines (143 loc) · 5.27 KB
/
steamsh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/python2
# SteamCMD wrapper w/ readline support
# Copyright (C) 2013 Dirk Dankhoff <bluthund23@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import atexit
import os
import re
import readline
import select
import subprocess
import sys
PS1 = os.environ.get("PS1") or "Steam> "
def read_all(p, prnt=True):
"""
Read and echo all output from SteamCMD subprocess p.
With prnt=True (the default) output from SteamCMD is echoed directly to
stdout. The prompt from SteamCMD is omitted.
This function raises a ValueError if the prompt is not matched at the end
of the output to prevent changes on SteamCMD's end causing undefined
behavior on our side.
"""
output_end_delim = "\x1b[1m\n" # last line before prompt in steamcmd
out = list()
l = ""
rl, wl, xl = select.select([p.stdout], [], [])
if rl:
while not l.endswith(output_end_delim):
l = p.stdout.readline()
if l != output_end_delim:
if prnt:
print l,
out.append(l)
end = p.stdout.read(10)
if end != "Steam>\x1b[0m":
raise ValueError("ERROR: found wrong prompt %s" % repr(end))
return out
def input_loop(p):
"""Input loop: Read input, send it to SteamCMD and print its response."""
def wait_and_exit(p):
sys.exit(p.wait())
while True:
print "\x1b[0m" # reset formatting in case steamcmd didn't do it
try:
user_input = raw_input(PS1)
except EOFError:
p.stdin.write("quit\n")
p.stdin.flush()
print # move shell prompt to next line on exit via <C-d>
wait_and_exit(p)
try:
p.stdin.write(user_input + "\n")
p.stdin.flush()
except IOError:
print "Error: Could not write to pipe."
p.poll()
if p.returncode is not None:
print "Error: steamcmd exited with %d." % p.returncode
sys.exit(p.returncode)
else:
if user_input in ['exit', 'quit']:
wait_and_exit(p)
else:
read_all(p)
class SteamCmdCompleter(object):
"""Class providing readline completion functionality for SteamCMD."""
def __init__(self, steamcmd):
self.steam = steamcmd
self.options = sorted(self._harvest_find())
def complete(self, text, state):
"""Readline completion function."""
# TODO add context aware completion
if state == 0:
if text:
self.matches = [s for s in self.options if
s and s.startswith(text)]
else:
self.matches = self.options[:]
try:
return self.matches[state]
except IndexError:
return None
line_fmt = (r'^\x1b\[0m\x1b\[1m\s+' # beginning of line
r'([^\x1b]+)\x1b\[0m' # convar/cmd
r'(?: = "([^"]*)")?\s*: (.*)$') # default value + help
find_re = re.compile(line_fmt)
def _harvest_find(self):
"""Harvest ConVars and Commands from SteamCMD's find command."""
options = list()
def append_options(c):
"""Find and append options having c in them."""
self.steam.stdin.write('find %s\n' % c)
self.steam.stdin.flush()
outl = read_all(self.steam, False)
for l in outl:
m = self.find_re.match(l)
try:
option = m.group(1)
options.append(option)
except AttributeError:
pass
alphabet = [chr(c) for c in xrange(97, 123)]
# explicitly merge convars
append_options('@')
for char in alphabet:
append_options(char)
return list(set(options))
# start steamcmd as subprocess
steamcmd = subprocess.Popen("./steamcmd.sh", shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
bufsize=0)
# get all startup output
read_all(steamcmd)
# setup readline history
histfile = os.path.join(os.path.expanduser("~"), ".history_steamsh")
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
# setup readline completion
# Dear VALVe: Why would you use @-symbols in your convars?
completer_delims = readline.get_completer_delims().replace('@', '')
readline.set_completer_delims(completer_delims)
readline.set_completer(SteamCmdCompleter(steamcmd).complete)
# repl
try:
input_loop(steamcmd)
except KeyboardInterrupt:
steamcmd.send_signal(subprocess.signal.SIGINT)
sys.exit(steamcmd.wait())