Skip to content

Commit

Permalink
release.py
Browse files Browse the repository at this point in the history
  • Loading branch information
yalov committed Sep 26, 2021
1 parent 07f3f86 commit 8aa3954
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 96 deletions.
3 changes: 2 additions & 1 deletion release.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@
"CHANGELOG": "ChangeLog.md",
"DRAFT": false,
"PRERELEASE": false,
"SPACEDOCK_ID": "1935"
"SPACEDOCK_ID": "1935",
"FORUM_ID": "177292"
}
128 changes: 34 additions & 94 deletions release.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""requirements:
Python3
pip install GitPython PyGithub
"""requirements:
Python3.9
pip install pyperclip GitPython PyGithub
./release_spacedock_utils.py
make sure, that ssh is set up
copy private key to ~/.ssh/
Public domain license.
author: flart, version: 15
https://github.com/yalov/SpeedUnitAnnex/blob/master/release.py
version: 21
Script loads release-arhive to github and spacedock
you need to set values in the release.json
Expand All @@ -24,40 +24,27 @@
import json
import os.path
import re
from shutil import copy
from shutil import copy, make_archive
import zipfile
from tkinter import Tk

from git import Repo
from github import Github
from github import GithubException

from release_github import PublishToGithub
from release_spacedock_utils import GetSpacedockKSPVersions
from release_spacedock_utils import GetSpacedockModDetails
from release_spacedock_utils import PublishToSpacedock


def zipdir(path, ziph):
""" recursive archiving path folder to ziph (zipfile handle) """
for root, _, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file))


def archive_to(file):
"""Archive GameData and Extras to .zip"""
if os.path.exists(file):
os.remove(file)

zipf = zipfile.ZipFile(file, 'x', zipfile.ZIP_DEFLATED)
if os.path.exists("GameData"):
zipdir("GameData", zipf)
make_archive(os.path.splitext(file)[0], 'zip', base_dir="GameData")
if os.path.exists("Extras"):
zipdir("Extras", zipf)
zipf.close()
print("{}, files: {}, size: {} byte"
.format("valid ZIP" if zipfile.is_zipfile(file) else "FAIL",
len(zipf.infolist()), os.path.getsize(file)))
make_archive(os.path.splitext(file)[0], 'zip', base_dir="Extras")

print("Size: {} byte"
.format(os.path.getsize(file)))


def get_version(version_file, obj="VERSION", ignore_patch = False):
Expand All @@ -76,14 +63,6 @@ def get_version(version_file, obj="VERSION", ignore_patch = False):
return version


def copy_to_clipboard(text):
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append(text)
r.update() # now it stays on the clipboard after the window is closed
r.destroy()

def get_description(path):
""" Get description of the last version in the changelog """
version = r"(#+ )?(Version )?\d(\d)?\.\d(\d)?\.\d(\d)?(\.\d)?(/\d(\d)?\.\d(\d)?\.\d(\d)?(\.\d)?)?( [(\"\')][^\n]*[)\"\')])?"
Expand All @@ -93,57 +72,6 @@ def get_description(path):
return desc


def publish_to_github(token, mod_name, version, last_change, is_draft, is_prerelease, zip_file):
"""create tag and publish a release"""
sys.stdout.write(" * Github connection...")
github = None
repo = None
user = None

try:
github = Github(token)
user = github.get_user()
except Exception:
print(" failed.")
sys.exit(-1)

try:
repo = user.get_repo(mod_name)
print(" user: {}, repo: {}".format(user.login, repo.name))
except Exception:
print(" failed to get {}".format(mod_name))
sys.exit(-1)

tags = repo.get_tags()
count = tags.totalCount

if count == 0 or (count > 0 and tags[0].name != version):
print(" * getting last commit sha ...")
sha = repo.get_commits()[0].sha

try:
repo.create_git_ref('refs/tags/{}'.format(version), sha)
except GithubException:
print(" * could not create tag on the repo.")
else:
print(" * the tag "+version+" is found, skiping ...")

rel = repo.create_git_release(tag=version, name="Version " + version,
message=last_change,
draft=is_draft, prerelease=is_prerelease)

print(" * uploading asset ...")
rel.upload_asset(path=zip_file, content_type="application/zip")
print(" * git fetch origin ...")
gitrepo = Repo(os.getcwd())
try:
gitrepo.remotes.origin.fetch()
except:
print(" * fetch() failed, check ssh from the cmd")
else:
print(" * success.")


if __name__ == '__main__':

jsn = json.load(open("release.json"))
Expand All @@ -157,6 +85,8 @@ def publish_to_github(token, mod_name, version, last_change, is_draft, is_prerel
DRAFT = jsn["DRAFT"]
PRERELEASE = jsn["PRERELEASE"]
SD_ID = jsn["SPACEDOCK_ID"]
FORUM_ID = jsn["FORUM_ID"]


TOKEN = tkn["GITHUB_TOKEN"]
SD_LOGIN = tkn["SPACEDOCK_LOGIN"]
Expand Down Expand Up @@ -191,9 +121,10 @@ def publish_to_github(token, mod_name, version, last_change, is_draft, is_prerel
print("version: {}\nksp_ver: {}\nksp_min: {}\nksp_max: {}\n"
.format(VERSION, KSP_VER, KSP_MIN, KSP_MAX))
print("draft: {}\nprerelease: {}\n".format(DRAFT, PRERELEASE))
print("parsing "+ CHANGELOG +" ...")
print("parsing "+ CHANGELOG +" ...")
LAST_CHANGE = get_description(CHANGELOG)
copy_to_clipboard(LAST_CHANGE)
import pyperclip
pyperclip.copy("Version " + VERSION + "\n" + LAST_CHANGE)
print("- start of desc ------------")
print(LAST_CHANGE)
print("- end of desc --------------")
Expand All @@ -209,27 +140,29 @@ def publish_to_github(token, mod_name, version, last_change, is_draft, is_prerel
print("Creating "+ ZIPFILE +" ...")
archive_to(ZIPFILE)


print("")
print("GITHUB:")
print("GITHUB:")
print("You already push your changes to a remote repo, don't you?")
print("Create the tag, and publish a {}{} with the asset?".format("DRAFT " if DRAFT else "","PRERELEASE" if PRERELEASE else "RELEASE" ))
if input("[y/N]: ") == 'y':
publish_to_github(TOKEN, MODNAME, VERSION, LAST_CHANGE, DRAFT, PRERELEASE, ZIPFILE)
resp = PublishToGithub(TOKEN, MODNAME, VERSION, LAST_CHANGE, DRAFT, PRERELEASE, ZIPFILE)
if resp == 1:
is_published=True

# ======================================
print("")

print("")
print("SPACEDOCK:")
if not SD_ID:
print("Spacedock number is not found in the json.")
input("Press Enter to exit")
sys.exit(-1)

print("Accessing to Spacedock...")
all_versions = [v['name'] for v in GetSpacedockKSPVersions()]

if not all_versions:
try:
all_versions = [v['name'] for v in GetSpacedockKSPVersions()]
except:
print("Failed. Could not access to Spacedock.")
input("Press Enter to exit")
sys.exit(-1)
Expand Down Expand Up @@ -262,7 +195,14 @@ def publish_to_github(token, mod_name, version, last_change, is_draft, is_prerel

print("Publish {} (KSP {}) to the Spacedock?".format(VERSION, KSP_VER))
if input("[y/N]: ") == 'y':
PublishToSpacedock(SD_ID, ZIPFILE, LAST_CHANGE, VERSION, KSP_VER, SD_LOGIN, SD_PASS)
resp = PublishToSpacedock(SD_ID, ZIPFILE, LAST_CHANGE, VERSION, KSP_VER, SD_LOGIN, SD_PASS)
if not 'error' in resp:
is_published=True

if FORUM_ID and 'is_published' in locals():
import webbrowser
webbrowser.open(f"https://forum.kerbalspaceprogram.com/index.php?/topic/{FORUM_ID}-*", new=2, autoraise=False)
print("The forum page is opened.")

input("Press Enter to exit")
sys.exit(0)
66 changes: 66 additions & 0 deletions release_github.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Public domain license.
# $version: 1

import sys
from git import Repo

import os.path

from github import Github
from github import GithubException

def PublishToGithub(token, mod_name, version, last_change, is_draft, is_prerelease, zip_file):
"""create tag and publish a release,
Returns:
1: succeed
0: failed
"""
sys.stdout.write(" * Github connection...")
github = None
repo = None
user = None

try:
github = Github(token)
user = github.get_user()
except Exception:
print(" failed.")
return 0

try:
repo = user.get_repo(mod_name)
print(" user: {}, repo: {}".format(user.login, repo.name))
except Exception:
print(" failed to get {}".format(mod_name))
return 0

tags = repo.get_tags()
count = tags.totalCount

if count == 0 or (count > 0 and tags[0].name != version):
print(" * getting last commit sha ...")
sha = repo.get_commits()[0].sha

try:
repo.create_git_ref('refs/tags/{}'.format(version), sha)
except GithubException:
print(" * could not create tag on the repo.")
else:
print(" * the tag "+version+" is found, skiping ...")

rel = repo.create_git_release(tag=version, name="Version " + version,
message=last_change,
draft=is_draft, prerelease=is_prerelease)

print(" * uploading asset ...")
rel.upload_asset(path=zip_file, content_type="application/zip")
print(" * git fetch origin ...")
gitrepo = Repo(os.getcwd())
try:
gitrepo.remotes.origin.fetch()
except:
print(" * fetch() failed, check ssh from the cmd")
return 0
else:
print(" * success.")
return 1
1 change: 0 additions & 1 deletion release_spacedock_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
# Public domain license.
# Based on: https://github.com/ihsoft/KSPDev_ReleaseBuilder
# $version: 3
# -*- coding: utf-8 -*-

import json
import urllib.request
Expand Down

0 comments on commit 8aa3954

Please sign in to comment.