Skip to content

Commit 03f8979

Browse files
committed
Added upgrading, fixed current keyword bug
1 parent a15496a commit 03f8979

File tree

3 files changed

+157
-25
lines changed

3 files changed

+157
-25
lines changed

CHANGELOG.md

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,30 @@
11
# Changelog
22

3+
## 2.2.0
4+
5+
Features Added:
6+
7+
- We can now upgrade ourselves! You can do this using the `-u` parameter.
8+
9+
Bug Fixes:
10+
11+
- Using the `current` keyword when selecting the build no longer fails.
12+
13+
Other Fixes:
14+
15+
- Added section to readme describing the update process.
16+
317
## 2.1.0
418

519
Features Added:
620

7-
- Added a new keyword, `current`, which will automatically select the current version/build to install
21+
- Added a new keyword, `current`, which will automatically select the current version/build to install.
822

923
Bug Fixes:
1024

1125
- Removed some junk debugging messages that would appear even if we are quieted.
1226

13-
other Fixes:
27+
Other Fixes:
1428

1529
- Added section to the readme that describes how to use keywords.
1630

README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,9 @@ Copies the old file to a new location before the installation process:
180180
Displays stats on the selected version and build:
181181
>-s, --stats
182182
183+
Checks GitHub for a new version of this script, and upgrades if necessary:
184+
>-u, --upgrade
185+
183186
## Special Keywords
184187

185188
The `-v`, `-b`, and interactive menu have special keywords
@@ -204,6 +207,22 @@ You can also use these keywords for selecting the build,
204207
although using the `current` keyword for build selection is not recommended!
205208

206209

210+
## Upgrading the Script
211+
212+
This script has the ability to upgrade itself!
213+
You can do this by providing the `-u` parameter.
214+
215+
We do this by checking GitHub for any version changes.
216+
If there is a change, then we download the new file
217+
and replace the currently running script with the new one.
218+
If we are upgrading, then we will immediately exit after the operation,
219+
and no other actions will be done.
220+
221+
Please note, this upgrade operation is not compatible
222+
with prebuilt binaries!
223+
If you attempt to upgrade a pre-built binary,
224+
then the script will print a warning and exit.
225+
207226
## Deprecated Command Line Options
208227

209228
The following command line options are deprecated. They are still included for backwards compatibility,
@@ -341,6 +360,9 @@ Copy the old file to a new location before the installation process:
341360
Select the currently installed version as the version to install:
342361
>python server_update.py -v current [PATH]
343362
363+
Upgrades the script if necessary:
364+
>python server_upgrade.py -u
365+
344366
# Notes on Deprecated Features
345367

346368
In earlier versions of PaperMC-Update, the script would keep a config file in the users home directory

server_update.py

Lines changed: 119 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
1-
from sys import version_info, stdout
1+
from __future__ import annotations
2+
3+
import sys
24

35
# Before we do ANYTHING, we check to make sure python is the correct version!
46

5-
if version_info < (3,6,0):
7+
if sys.version_info < (3,6,0):
68

7-
stdout.write("\n--== [ Invalid python version! ] ==--\n")
8-
stdout.write("Current version: {}\n".format(version_info))
9-
stdout.write("Expected version: 3.6+\n")
10-
stdout.write("\nPlease install the correct version of python before continuing!\n")
9+
sys.stdout.write("\n--== [ Invalid python version! ] ==--\n")
10+
sys.stdout.write("Current version: {}\n".format(version_info))
11+
sys.stdout.write("Expected version: 3.6+\n")
12+
sys.stdout.write("\nPlease install the correct version of python before continuing!\n")
1113

12-
exit()
14+
sys.exit()
1315

1416
import tempfile
1517
import urllib.request
@@ -31,7 +33,13 @@
3133
A Set of tools to automate the server update process.
3234
"""
3335

34-
__version__ = '2.1.0'
36+
__version__ = '2.2.0'
37+
38+
# These variables contain links for the script updating process.
39+
40+
GITHUB = 'https://github.com/Owen-Cochell/PaperMC-Update'
41+
GITHUB_RELEASE = 'https://api.github.com/repos/Owen-Cochell/PaperMC-Update/releases/latest'
42+
GITHUB_RAW = 'https://raw.githubusercontent.com/Owen-Cochell/PaperMC-Update/master/server_update.py'
3543

3644

3745
def load_config(config: str) -> Tuple[str, int]:
@@ -74,6 +82,78 @@ def load_config(config: str) -> Tuple[str, int]:
7482
return version, build
7583

7684

85+
def upgrade_script(serv: ServerUpdater):
86+
"""
87+
Upgrades this script.
88+
89+
We do this by checking github for any new releases,
90+
comparing them to our version,
91+
and then updating if necessary.
92+
93+
We use the ServerUpdater to do this operation for us,
94+
so you will need to provide it for this function
95+
to work correctly.
96+
97+
:param serv: ServerUpdater to use
98+
:type serv: ServerUpdater
99+
"""
100+
101+
output("# Checking for update ...")
102+
103+
# Creating request here:
104+
105+
req = urllib.request.Request(GITHUB_RELEASE, headers={'Accept': 'application/vnd.github.v3+json'})
106+
107+
# Getting data:
108+
109+
data = json.loads(urllib.request.urlopen(req).read())
110+
111+
# Checking if the version is new:
112+
113+
if data['tag_name'] == __version__:
114+
115+
# No update necessary, lets log and exit:
116+
117+
output("# No update necessary!\n")
118+
119+
return
120+
121+
output("# New version available!")
122+
123+
url = GITHUB_RAW
124+
path = os.path.realpath(__file__)
125+
126+
# Determine if we are working in a frozen environment:
127+
128+
if getattr(sys, 'frozen', False):
129+
130+
print("# Can't upgrade frozen files!")
131+
132+
return
133+
134+
# Getting data:
135+
136+
data = urllib.request.urlopen(urllib.request.Request(url))
137+
138+
# Write the data:
139+
140+
serv.fileutil.create_temp_dir()
141+
142+
temp_path = os.path.realpath(serv.fileutil.temp.name + '/temp')
143+
144+
file = open(temp_path, mode='wb')
145+
146+
file.write(data.read())
147+
148+
# Install the new script:
149+
150+
serv.fileutil.install(temp_path, path)
151+
152+
# We are done!
153+
154+
output("# Script update complete!\n")
155+
156+
77157
def output(text: str):
78158

79159
"""
@@ -173,14 +253,14 @@ def progress_bar(length: int, stepsize: int, total_steps: int, step: int, prefix
173253

174254
if not args.quiet:
175255

176-
stdout.write("{}[{}{}] {}/{}\r".format(prefix, prog_char*x, empty_char*(size-x),
256+
sys.stdout.write("{}[{}{}] {}/{}\r".format(prefix, prog_char*x, empty_char*(size-x),
177257
(step*stepsize if step < total_steps - 1 else length), length))
178-
stdout.flush()
258+
sys.stdout.flush()
179259

180260
if not args.quiet and step >= total_steps - 1 :
181261

182-
stdout.write("\n")
183-
stdout.flush()
262+
sys.stdout.write("\n")
263+
sys.stdout.flush()
184264

185265

186266
class Update:
@@ -342,7 +422,7 @@ def download_response(self, version: str, build_num:int) -> HTTPResponse:
342422

343423
def download_file(self, path: str, version: str, build_num:int, check:bool=True, call: Callable=None, args: List=None, blocksize: int=4608) -> str:
344424
"""
345-
Donloads the content to the given external file.
425+
Downloads the content to the given external file.
346426
We handle all file operations,
347427
and automatically work with the URLResponse objects
348428
to write the file contents to an external file.
@@ -910,22 +990,19 @@ def __init__(self, path, config_file: str='', version='0', build=-1, config=True
910990
self.integrity = integrity # Boolean determining if we should run an integrity check
911991
self.version_install = None # Version to install
912992
self.build_install = None # Build to install
913-
914-
# Starting object
915-
916-
self._start(config)
993+
self.config = config
917994

918995
self.update = Update() # Updater Instance
919996

920-
def _start(self, config):
997+
def start(self):
921998
"""
922999
Starts the object, loads configuration.
9231000
"""
9241001

9251002
temp_version = '0'
9261003
temp_build = 0
9271004

928-
if config:
1005+
if self.config:
9291006

9301007
# Allowed to use configuration file
9311008

@@ -1483,9 +1560,15 @@ def _select(self, val: Any, choice: Sequence[Any], default: str, name: str, prin
14831560

14841561
if val == 'current':
14851562

1486-
# User wants currently installed version:
1563+
if name == 'version':
14871564

1488-
val = self.version
1565+
# User wants currently installed version:
1566+
1567+
val = self.version
1568+
1569+
elif name == 'build':
1570+
1571+
val = self.buildnum
14891572

14901573
if val not in choice:
14911574

@@ -1529,15 +1612,15 @@ def _url_report(self, point: str):
15291612
epilog="Please check the github page for more info: "
15301613
"https://github.com/Owen-Cochell/PaperMC-Update.")
15311614

1532-
parser.add_argument('path', help='Path to paper jar file')
1615+
parser.add_argument('path', help='Path to paper jar file', default=os.path.dirname(__file__) + '/', nargs='?')
15331616

15341617
version = parser.add_argument_group('Version Options', 'Arguments for selecting and altering server version information')
15351618

15361619
# +===========================================+
15371620
# Server version arguments:
15381621

15391622
version.add_argument('-v', '--version', help='Server version to install(Sets default value)', default='latest', type=str)
1540-
version.add_argument('-b', '--build', help='Server build to install(Sets default value)', default=-1, type=int)
1623+
version.add_argument('-b', '--build', help='Server build to install(Sets default value)', default=-1, type=str)
15411624
version.add_argument('-iv', help='Sets the currently installed server version, ignores config', default='0', type=str)
15421625
version.add_argument('-ib', help='Sets the currently installed server build, ignores config', default=0, type=int)
15431626
version.add_argument('-sv', '--server-version', help="Displays server version from configuration file and exits", action='store_true')
@@ -1568,6 +1651,7 @@ def _url_report(self, point: str):
15681651
action='store_true')
15691652
parser.add_argument('-s', '--stats', help='Displays statistics on the selected version and build', action='store_true')
15701653
parser.add_argument('-V', '--script-version', help='Displays script version', version=__version__, action='version')
1654+
parser.add_argument('-u', '--upgrade', help='Upgrades this script to a new version if necessary, and exits', action='store_true')
15711655

15721656
# Deprecated arguments - Included for compatibility, but do nothing
15731657

@@ -1595,6 +1679,18 @@ def _url_report(self, point: str):
15951679

15961680
update_available = True
15971681

1682+
# Determine if we should upgrade:
1683+
1684+
if args.upgrade:
1685+
1686+
upgrade_script(serv)
1687+
1688+
sys.exit()
1689+
1690+
# Start the server updater
1691+
1692+
serv.start()
1693+
15981694
# Figure out the output name:
15991695

16001696
name = None

0 commit comments

Comments
 (0)