Skip to content

Commit 5bb3084

Browse files
committed
add code to report latest version # even when G2 is not installed w/git
1 parent dea8eb9 commit 5bb3084

File tree

1 file changed

+98
-6
lines changed

1 file changed

+98
-6
lines changed

GSASII/GSASIIpath.py

Lines changed: 98 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -322,16 +322,67 @@ def getG2VersionInfo():
322322
msg += f"\n\tThis GSAS-II version is ~{len(rc)} updates behind current."
323323
return f" GSAS-II: {commit.hexsha[:8]}, {ctim} ({age:.1f} days old). {gversion}{msg}"
324324
elif gv is not None:
325+
vt = ''
326+
cvt = ''
327+
try:
328+
if gv.git_versiontag:
329+
vt = gv.git_versiontag
330+
cvt,cvn = getGitHubVersion()
331+
except:
332+
pass
333+
325334
for item in gv.git_tags+gv.git_prevtags:
326335
if item.isnumeric():
327-
return f"GSAS-II version: Git: {gv.git_version[:8]}, #{item} (installed without update capability)"
328-
# Failed to get version info, fallback on old version number routine
336+
tags = item
337+
if vt:
338+
tags += f', {vt}'
339+
msg = f"GSAS-II version: Git: {gv.git_version[:8]}, #{tags} (reinstall to update)"
340+
if vt != cvt and cvt is not None:
341+
msg += f'\n\tNote that the current GSAS-II version is {cvt}'
342+
return msg
343+
# Failed to get version info, fallback on old version number routine; should not happen anymore
329344
return f"GSAS-II installed without git, last tag: #{GetVersionNumber()}, {GetVersionTag()}"
330345

331346
#==============================================================================
332347
#==============================================================================
333-
# routines to interface with git.
348+
# routines to interface with GitHub.
349+
def saveGitHubVersion():
350+
'''Get the latest GSAS-II version tags from the GitHub site
351+
and place them into the config.ini file. This is always done in
352+
background so that app startup time is minimally delayed.
353+
354+
:returns: Returns a Popen object (see subprocess).
355+
'''
356+
try:
357+
import requests
358+
except:
359+
print('Unable to use requests module')
360+
return
361+
return subprocess.Popen([sys.executable, __file__, '--github-tags'])
362+
if GetConfigValue('debug'): print('Updates fetched')
363+
364+
def getGitHubVersion():
365+
'''Get the latest git version info when not accessible from git
366+
as saved by saveGitHubVersion
367+
'''
368+
import configparser
369+
cfgfile = os.path.expanduser(os.path.normpath('~/.GSASII/config.ini'))
370+
if not os.path.exists(cfgfile):
371+
if GetConfigValue('debug'): print(f"{cfgfile} not found")
372+
return None,None
373+
try:
374+
cfg = configparser.ConfigParser()
375+
# Read the configuration file
376+
cfg.read(cfgfile)
377+
except Exception as err:
378+
if GetConfigValue('debug'): print(f"Error reading {cfgfile}\n",err)
379+
return None,None
380+
if 'version info' not in cfg:
381+
if GetConfigValue('debug'): print(f"no saved version number in {cfgfile}")
382+
return None,None
383+
return cfg['version info'].get('lastVersionTag'),cfg['version info'].get('lastVersionNumber')
334384

385+
# routines to interface with git.
335386
BASE_HEADER = {'Accept': 'application/vnd.github+json',
336387
'X-GitHub-Api-Version': '2022-11-28'}
337388

@@ -828,13 +879,16 @@ def InstallGitBinary(tarURL, instDir, nameByVersion=False, verbose=True):
828879
os.unlink(tar.name)
829880

830881
def GetRepoUpdatesInBackground():
831-
'''Wrapper to make sure that :func:`gitGetUpdate` is called only
882+
'''Get the latest GSAS-II version info.
883+
This serves to make sure that :func:`gitGetUpdate` is called only
832884
if git has been used to install GSAS-II.
833885
834886
:returns: returns a Popen object (see subprocess)
835887
'''
836888
if HowIsG2Installed().startswith('git'):
837889
return gitGetUpdate(mode='Background')
890+
else:
891+
return saveGitHubVersion()
838892

839893
def gitStartUpdate(cmdopts):
840894
'''Update GSAS-II in a separate process, by running this script with the
@@ -1222,6 +1276,8 @@ def WriteConfig(configDict):
12221276
return True
12231277
cfgfile = os.path.join(localdir,'config.ini')
12241278
cfgP = configparser.ConfigParser()
1279+
if os.path.exists(cfgfile):
1280+
cfgP.read(cfgfile) # read previous file so other sections are retained
12251281
cfgP['GUI settings'] = configDict
12261282

12271283
# Write the configuration file
@@ -1270,8 +1326,11 @@ def XferConfigIni():
12701326
try:
12711327
from . import config_example
12721328
except ImportError as err:
1273-
print("Error importing config_example.py file\n",err)
1274-
return
1329+
try:
1330+
import GSASII.config_example as config_example
1331+
except ImportError as err:
1332+
print("Error importing config_example.py file\n",err)
1333+
return
12751334

12761335
# get the original capitalization (lost by configparser)
12771336
capsDict = {key.lower():key for key in config_example.__dict__ if not key.startswith('__')}
@@ -1818,6 +1877,12 @@ def postURL(URL,postdict,getcookie=None,usecookie=None,
18181877
help = True
18191878
break
18201879
updateType = 'fetch'
1880+
elif '--github-tags' in arg: # gets latest tags from github
1881+
if preupdateType or updateType or gitUpdate:
1882+
print(f'previous option conflicts with {arg}')
1883+
help = True
1884+
break
1885+
updateType = 'tags'
18211886
elif '--git-reset' in arg: # restores locally changed GSAS-II files to distributed versions also updates
18221887
gitUpdate = True
18231888
if preupdateType:
@@ -1902,16 +1967,43 @@ def postURL(URL,postdict,getcookie=None,usecookie=None,
19021967
19031968
--git-regress=version
19041969
1970+
--github-tags saves most recent tag info from GitHub
1971+
19051972
and where <project> is an optional path reference to a .gpx file
19061973
19071974
Note: --git-reset and --git-stash cannot be used together. Likewise
19081975
--git-update and --git-regress cannot be used together.
19091976
However either --git-reset or --git-stash can be used
19101977
with either --git-update or --git-regress.
1978+
19111979
--git-fetch cannot be used with any other options.
1980+
--github-tags cannot be used with any other options.
19121981
''')
19131982
sys.exit()
19141983

1984+
if updateType == 'tags':
1985+
# get the most recent tag numbers from the GitHub site. Do this
1986+
# via GitHub when git access is not available. Use here
1987+
# allows this to be done in the background.
1988+
import requests
1989+
url='https://github.com/AdvancedPhotonSource/GSAS-II/tags'
1990+
releases = requests.get(url=url)
1991+
taglist = [tag.split('"')[0] for tag in releases.text.split('AdvancedPhotonSource/GSAS-II/releases/tag/')[1:]]
1992+
lastver = sorted([t for t in taglist if 'v' in t])[-1]
1993+
lastnum = sorted([t for t in taglist if 'v' not in t],key=int)[-1]
1994+
#print('tags=',lastver,lastnum)
1995+
# add tag info to config file
1996+
import configparser
1997+
cfgfile = os.path.expanduser(os.path.normpath('~/.GSASII/config.ini'))
1998+
cfg = configparser.ConfigParser()
1999+
cfg.read(cfgfile)
2000+
if 'version info' not in cfg:
2001+
cfg.add_section('version info')
2002+
cfg['version info'].update(
2003+
{'lastVersionTag':lastver,'lastVersionNumber':lastnum})
2004+
with open(cfgfile, 'w') as configfile:
2005+
cfg.write(configfile)
2006+
sys.exit()
19152007

19162008
if updateType == 'fetch':
19172009
# download the latest updates from GitHub to the local repository

0 commit comments

Comments
 (0)