Skip to content

Commit

Permalink
Feat/auto upgrade (#3)
Browse files Browse the repository at this point in the history
* rename refactor

* version_check.py support auto update
bump hard coded version to 1.2.1

* wrap color print
version_check.py: remove debug hard coded flag

* add VERSION_CHECK_TIMES constant
  • Loading branch information
zlrs authored Aug 30, 2020
1 parent 3de1b39 commit e3e4503
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 37 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
./test*
test/
.vscode/

Expand Down
30 changes: 15 additions & 15 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,39 +18,39 @@ if [ ! -d "/usr/local/xc" ] # 不存在xc文件夹
then
# clone repo
echo "${Execute}git clone https://github.com/zlrs/xcode-opener.git $repo_folder ${NC}"
git clone https://github.com/zlrs/xcode-opener.git $repo_folder
sudo -S git clone https://github.com/zlrs/xcode-opener.git $repo_folder

# gen symbol link
echo "${Info}Installing xc command to $command_path ${NC}"
# 如果路径上已有文件,则删掉
if [ -f $command_path ]
if [ -f $command_path ]
then
echo "${Execute}rm $command_path ${NC}"
rm $command_path
sudo -S rm $command_path
fi
echo "${Execute}ln -s /usr/local/xc/xc $command_path ${NC}"
ln -s /usr/local/xc/xc $command_path
sudo -S ln -s /usr/local/xc/xc $command_path

echo "${Info}Installation has been completed. ${NC}"
else # 存在 xc 文件夹
if [ -d "/usr/local/xc/.git" ] # 且 xc 文件夹是个git repo
then
echo "${Info}Already installed xc. Updating... ${NC}"

echo "${Execute}cd /usr/local/xc${NC}"
cd /usr/local/xc
cd /usr/local/xc || exit 2

echo "${Execute}git pull${NC}"
git pull
if [ -f $command_path ]
sudo -S git pull

if [ -f $command_path ]
then
echo "${Execute}rm $command_path ${NC}"
rm $command_path
sudo -S rm $command_path
fi

echo "${Execute}ln -s /usr/local/xc/xc $command_path ${NC}"
ln -s /usr/local/xc/xc $command_path
sudo -S ln -s /usr/local/xc/xc $command_path
else
echo "${Error}/usr/local/xc/ exists and is not a git repository. ${NC}"
echo "${Error}No operation is performed. ${NC}"
Expand Down
22 changes: 22 additions & 0 deletions logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# ANSI colors
RED = '\033[0;31m'
GREEN = '\033[0;32m'
PURPLE = '\033[0;35m'
NC = '\033[0m' # No Color

Error = f"{RED}[Error] "
Info = f"{GREEN}[Info] "
Execute = f"{PURPLE}[Execute] "


def printInfo(content):
print(Info + content + NC)


def printError(content):
print(Error + content + NC)


def printExecute(content):
print(Execute + content + NC)

55 changes: 38 additions & 17 deletions version_check.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
import requests
import os
import json
from logger import printInfo, printExecute, printError

VERSION = '1.2.0'
VERSION = '1.2.1'
VERSION_CHECK_TIMES = 7

# ANSI colors
RED = '\033[0;31m'
GREEN = '\033[0;32m'
PURPLE = '\033[0;35m'
NC = '\033[0m' # No Color

class Version:
Error = f"{RED}[Error] "
Info = f"{GREEN}[Info] "
Execute = f"{PURPLE}[Execute] "


class YQVersion:
def __init__(self, version: str):
version.strip()
version.strip("vV")
self.version = version
self.sematic_versions = version.split('.')
self.semantic_versions = version.split('.')
self.digitVersions = []
for sematic_ver in self.sematic_versions:
self.digitVersions.append(int(sematic_ver))
for semantic_ver in self.semantic_versions:
self.digitVersions.append(int(semantic_ver))

def __eq__(self, other):
return tuple(self.digitVersions) == tuple(other.digitVersions)
Expand All @@ -22,11 +34,11 @@ def __lt__(self, other):
return tuple(self.digitVersions) < tuple(other.digitVersions)


def get_latest_version():
def getLatestVersion():
URL = 'https://api.github.com/repos/zlrs/xcode-opener/releases?accept=application/vnd.github.v3+json'
res = requests.get(URL)
if not res.ok:
return '', "error"
return '', f"error: status {res.status_code}" # May be 403: exceeded API rate limit for current IP.

try:
obj = res.json()
Expand All @@ -36,23 +48,32 @@ def get_latest_version():
return '', "error"


def version_check():
latestVersionStr, err = get_latest_version()
def checkVersion():
latest_version_str, err = getLatestVersion()
if not err:
current = Version(VERSION)
latest = Version(latestVersionStr)
current = YQVersion(VERSION)
latest = YQVersion(latest_version_str)
if latest > current:
print('You are using xc %s. The latest version is %s. Please consider upgrade. ' % (current.version, latest.version))
print('https://github.com/zlrs/xcode-opener/releases')
printInfo('You are using xc %s. The latest version is %s. ' % (current.version, latest.version))
res = input(Info + 'Would you like to upgrade now? [y/N]' + NC)
if res == 'y':
install_script = os.path.join(os.path.dirname(__file__), 'install.sh')
install_script = os.path.expanduser(install_script)
printExecute(install_script)
os.execv(install_script, (install_script,))


def shouldCheckVersion():
"""
Check version every several times(VERSION_CHECK_TIMES) the program is called.
:return:Boolean value, whether should program check version.
"""
def initVersionCheck(file_path):
data = {
init_data = {
"version_check_count": 1
}
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(data, f)
json.dump(init_data, f)

folder = os.path.expanduser('~/.xc')
if not os.path.exists(folder):
Expand All @@ -71,14 +92,14 @@ def initVersionCheck(file_path):
except:
initVersionCheck(file_path)

if data["version_check_count"] % 10 == 0:
if data["version_check_count"] % VERSION_CHECK_TIMES == 0:
return True
return False


def run():
if shouldCheckVersion():
version_check()
checkVersion()


if __name__ == '__main__':
Expand Down
13 changes: 8 additions & 5 deletions xc
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import os
import shutil
import click
import version_check
from logger import printInfo, printExecute, printError


def getXCodeProjectOrWorkspaceFilePath(inputPath) -> str:
Expand All @@ -25,8 +26,8 @@ def getXCodeProjectOrWorkspaceFilePath(inputPath) -> str:
index = int(input(prompt))
return files[index - 1]
except (ValueError, IndexError) as e:
print('Invalid Argument: please enter a valid index. ')
print(e)
printError('Invalid Argument: please enter a valid index. ')
printError(e)
exit(1)
return ''

Expand Down Expand Up @@ -58,10 +59,10 @@ def openInXcode(inputPath):
file_path = getXCodeProjectOrWorkspaceFilePath(inputPath)
if file_path:
cmd = 'open "%s"' % file_path
print(cmd)
printExecute(cmd)
os.system(cmd)
else:
print('No .xcodeproj / .xcworkspace file is found. ')
printInfo('No .xcodeproj / .xcworkspace file is found. ')


def removeProjectDerivedData(inputPath, rmAll=False, rmBuild=False, rmIndex=False):
Expand All @@ -70,7 +71,7 @@ def removeProjectDerivedData(inputPath, rmAll=False, rmBuild=False, rmIndex=Fals
"""
def removeDirIfExist(rmDirPath, ignore_errors=False):
if os.path.exists(rmDirPath) and os.path.isdir(rmDirPath):
print('Removing directory: ' + rmDirPath)
printInfo('Removing directory: ' + rmDirPath)
shutil.rmtree(rmDirPath, ignore_errors=ignore_errors)
return rmDirPath
return None
Expand Down Expand Up @@ -149,6 +150,8 @@ def xc(path, rm_all, rm_build, rm_index):
The argument `path` is a path to the directory containing at least 1 `.xcodeproj` or `.xcworkspace` file, default
to the current directory. `.xcworkspace` has higher priority than `.xcodeproj`.
Contribute: https://github.com/zlrs/xcode-opener
"""
abs_path = os.path.expanduser(path)

Expand Down

0 comments on commit e3e4503

Please sign in to comment.