source: install/bootstrap.py @ 2866

Last change on this file since 2866 was 2866, checked in by toby, 4 years ago

update bootstrap.py to perform 'svn switch'

File size: 9.9 KB
Line 
1#!/usr/bin/env python
2# Installs GSAS-II from network using subversion and creates platform-specific shortcuts.
3# works for Mac & Linux & Windows
4import os, stat, sys, platform, subprocess
5home = 'https://subversion.xray.aps.anl.gov/pyGSAS/'
6print 70*'*'
7#testing for incorrect locale code'
8try:
9    import locale
10    locale.getdefaultlocale()
11except ValueError:
12    print 'Your location is not set properly. This causes problems for matplotlib'
13    print '  (see https://github.com/matplotlib/matplotlib/issues/5420.)'
14    print 'Will try to bypass problem by setting LC_ALL to en_US.UTF-8 (US English)'
15    os.environ['LC_ALL'] = 'en_US.UTF-8'
16    locale.getdefaultlocale()
17print 'Preloading matplotlib to build fonts...'
18try:
19    import matplotlib
20except:
21    pass
22print 'Checking python packages...',
23missing = []
24for pkg in ['numpy','scipy','matplotlib','wx',]:
25    try:
26        exec('import '+pkg)
27    except:
28        missing.append(pkg)
29
30if missing:
31    print """Sorry, this version of Python cannot be used
32for GSAS-II. It is missing the following package(s):
33\t""",
34    for pkg in missing: print " ",pkg,
35    print "\nPlease install these package(s) and try running this again."
36    print "Showing first error: "
37    for pkg in ['numpy','scipy','matplotlib','wx',]:
38        exec('import '+pkg)
39    sys.exit()
40try:
41    import OpenGL
42    install_with_easyinstall = None 
43except:
44    try:                 
45            from setuptools.command import easy_install                 
46    except ImportError:
47        print 'You are missing the OpenGL Python package. This can be '
48        print 'installed by this script if the setuptools package is installed'
49        print 'Please install either OpenGL (pyopengl) or setuptools'
50        print "package and try running this again."
51        sys.exit()
52    print "Missing the OpenGL Python package. Will attempt to install this later."
53    def install_with_easyinstall(package):               
54        try:             
55            print "trying system-wide ",                 
56            easy_install.main(['-f',os.path.split(__file__)[0],package])                 
57            return               
58        except:                 
59            pass                 
60        try:             
61            print "trying user level ",                 
62            easy_install.main(['-f',os.path.split(__file__)[0],'--user',package])               
63            return               
64        except:                 
65            print "\nInstall of "+package+" failed. Error traceback follows:"           
66            import traceback             
67            print traceback.format_exc()                 
68            sys.exit() 
69# path to where this script is located
70gsaspath = os.path.split(sys.argv[0])[0]
71if not gsaspath: gsaspath = os.path.curdir
72gsaspath = os.path.abspath(os.path.expanduser(gsaspath))
73
74print '\nChecking for subversion...',
75if sys.platform.startswith('win'):
76    pathlist = os.environ['PATH'].split(';')
77    if os.path.exists(os.path.join(gsaspath,'svn')):
78        pathlist.append(os.path.join(gsaspath,'svn','bin'))
79else:
80    pathlist = os.environ['PATH'].split(':')
81    # add the standard location for wandisco svn to the path
82    pathlist.append('/opt/subversion/bin')
83if sys.platform.startswith('win'):
84    svn = 'svn.exe'
85else:
86    svn = 'svn'
87# use svn installed via conda 1st (mac)
88if os.path.exists(os.path.join(os.path.split(sys.executable)[0],svn)):
89    pathlist.insert(0,os.path.split(sys.executable)[0])
90# use svn installed via conda 1st (Windows)
91if os.path.exists(os.path.join(os.path.split(sys.executable)[0],'Library','bin',svn)):
92    pathlist.insert(0,os.path.join(os.path.split(sys.executable)[0],'Library','bin'))
93
94for path in pathlist:
95    svn = os.path.join(path,'svn')
96    try:
97        p = subprocess.Popen([svn,'help'],stdout=subprocess.PIPE)
98        res = p.stdout.read()
99        p.communicate()
100        break
101    except:
102        pass
103else:
104    print "Sorry, subversion (svn) could not be found on your system."
105    print "Please install this or place in path and rerun this."
106    #raise Exception('Subversion (svn) not found')
107    sys.exit()
108print ' found svn image: '+svn
109
110if install_with_easyinstall:             
111    print '\nInstalling PyOpenGL. Lots of warnings will follow... ',             
112    install_with_easyinstall('PyOpenGl')                 
113    print 'done.'
114   
115print 'Ready to bootstrap GSAS-II from repository\n\t',home,'\nto '+gsaspath
116proxycmds = []
117if os.path.exists("proxyinfo.txt"):
118    fp = open("proxyinfo.txt",'r')
119    os.remove("proxyinfo.txt")
120print(70*"=")
121ans = raw_input("Enter the proxy address [none needed]: ")
122if ans.strip() != "":
123    proxycmds.append('--config-option')
124    proxycmds.append('servers:global:http-proxy-host='+ans.strip())
125    fp = open("proxyinfo.txt",'w')
126    fp.write(ans.strip()+'\n')
127    ans = raw_input("Enter the proxy port [8080]: ")
128    if ans.strip() == "": ans="8080"
129    proxycmds.append('--config-option')
130    proxycmds.append('servers:global:http-proxy-port='+ans.strip())
131    fp.write(ans.strip()+'\n')
132    fp.close()
133
134print 'Determining system type...',
135if sys.platform.startswith('linux'):
136    #if platform.processor().find('86') <= -1:
137    #    ans = raw_input("Note, GSAS requires an Intel-compatible processor and 32-bit"
138    #                    "libraries.\nAre you sure want to continue? [Yes]/no: ")
139    #    if ans.lower().find('no') > -1: sys.exit()
140    repos = 'linux'
141    print 'Linux, assuming Intel-compatible'
142elif sys.platform == "darwin" and platform.processor() == 'i386':
143    repos = 'osxi86'
144    print 'Mac OS X, Intel-compatible'
145elif sys.platform == "darwin":
146    repos = 'osxppc'
147    print 'Mac OS X, PowerPC -- you will need to run scons on fsource files'
148elif sys.platform.startswith('win'):
149    repos = 'win'
150    print 'Windows'
151else:
152    print 'Unidentifed platform -- you probably will need to run scons to compile the fsource files'
153
154cmd = [svn, 'info']
155p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
156res,err = p.communicate()
157if '.xor.' in res:
158    print('Switching previous install with .xor. download location to\n\thttps://subversion.xray.aps.anl.gov/pyGSAS')
159    cmd = [svn, 'switch','--relocate','https://subversion.xor.aps.anl.gov/pyGSAS',
160           'https://subversion.xray.aps.anl.gov/pyGSAS']
161    p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
162    res,err = p.communicate()
163    if err:
164        print('Please report this error to toby@anl.gov:')
165        print(err)
166        print(res)
167       
168cmd = [svn, 'co', home+ 'trunk/', gsaspath, '--non-interactive', '--trust-server-cert']
169if proxycmds: cmd += proxycmds
170msg = 'Now preparing to install GSAS-II'
171print('\n'+75*'*')
172print(msg + u' from ' + cmd[2])
173print('  *** If GSAS-II fails to be installed, you likely have a network access')
174print('  *** problem, most commonly because you need to use a network proxy. Please')
175print('  *** check with a network administrator or use http://www.whatismyproxy.com/\n')
176print 'svn load command:'
177for item in cmd: print item,
178print ""
179p = subprocess.call(cmd)
180if p:
181    print 'subversion returned an error; Retrying with command for older version...'
182    cmd = [svn, 'co', home+ 'trunk/', gsaspath]
183    if proxycmds: cmd += proxycmds
184    for item in cmd: print item,
185    print ""
186    p = subprocess.call(cmd)
187
188#===========================================================================
189# test if the compiled files load correctly
190#===========================================================================
191script = """
192try:
193    import GSASIIpath
194    import pyspg
195    import histogram2d
196    import polymask
197    import pypowder
198    import pytexture
199    pyspg.sgforpy('P -1')
200    print('==OK==')
201except:
202    pass
203"""
204p = subprocess.Popen([sys.executable,'-c',script],stdout=subprocess.PIPE,cwd=gsaspath)
205res,err = p.communicate()
206if '==OK==' not in res or p.returncode != 0:
207    print('\n'+75*'=')
208    print('Failed when testing the GSAS-II compiled files. GSAS-II will not run without')
209    print('correcting this. Attempting to open a web page on compiling GSAS-II...')
210    print('(https://subversion.xray.aps.anl.gov/trac/pyGSAS/wiki/CompileGSASII)')
211    print(75*'=')
212    print('\n')
213    import webbrowser
214    webbrowser.open_new('https://subversion.xray.aps.anl.gov/trac/pyGSAS/wiki/CompileGSASII')
215    sys.exit()
216else:
217    print 'Successfully tested compiled routines'
218#===========================================================================
219# import all .py files so that .pyc files get created
220print 'Byte-compiling all .py files...',
221import compileall
222compileall.compile_dir(gsaspath,quiet=True)
223print 'done'
224#===========================================================================
225# platform-dependent stuff
226#===========================================================================
227# on Windows, make a batch file with Python and GSAS-II location hard-coded
228if sys.platform.startswith('win') and os.path.exists(
229    os.path.join(gsaspath,"makeBat.py")):
230    execfile(os.path.join(gsaspath,"makeBat.py"))
231#===========================================================================
232# on a Mac, make an applescript
233elif sys.platform.startswith('darwin') and os.path.exists(
234    os.path.join(gsaspath,"makeMacApp.py")):
235    print('running '+os.path.join(gsaspath,"makeMacApp.py"))
236    execfile(os.path.join(gsaspath,"makeMacApp.py"))
237#===========================================================================
238# On linux, make desktop icon
239elif sys.platform.startswith('linux'):
240    desktop_template = """
241[Desktop Entry]
242Encoding=UTF-8
243Version=1.0
244Type=Application
245Terminal=false
246Exec=xterm -hold -e %s
247Name=GSAS-II
248Icon=%s
249"""
250    loc = '~/Desktop/'
251    eloc = os.path.expanduser(loc)
252    dfile = os.path.join(eloc,'GSASII.desktop')
253    icon = os.path.join(gsaspath, 'gsas2.png')
254    script = os.path.join(gsaspath, 'GSASII.py')
255    os.chmod(script, # make the .py file executable and readable
256             stat.S_IXUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IXOTH)
257    if os.path.exists(eloc):
258        open(dfile,'w').write(desktop_template % (script,icon))
259        os.chmod(
260            dfile,
261            stat.S_IWUSR | stat.S_IXUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IXOTH)
262        print("created GNOME desktop shortcut "+dfile) 
263
Note: See TracBrowser for help on using the repository browser.