...
[iramuteq] / checkinstall.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008 Pierre Ratinaud
5 #License: GNU/GPL
6
7 import os
8 import sys
9 import shutil
10 from chemins import ConstructConfigPath, ConstructDicoPath
11 from functions import exec_rcode, exec_RCMD
12 import wx
13 import tempfile
14 from ConfigParser import *
15 from time import sleep
16 import logging
17
18 log = logging.getLogger('iramuteq.checkinstall')
19
20 def IsNew(self):
21     version_glob = self.ConfigGlob.get('DEFAULT', 'version_nb').split('.')
22     try :
23         version_user = self.pref.get('iramuteq','version_nb').split('.')
24     except NoOptionError :
25         return True
26     if version_user :
27         version_user[0] = int(version_user[0])
28         version_user[1] = int(version_user[1])
29         version_glob[0] = int(version_glob[0])
30         version_glob[1] = int(version_glob[1])
31         if len(version_user) == len(version_glob) :
32             if version_glob > version_user :
33                 return True
34             else :
35                 return False
36         if len(version_glob) == 2 :
37             if version_glob[:2] >= version_user[:2] :
38                 return True
39             else :
40                 return False
41         elif len(version_glob) == 3 :
42             if version_glob[:2] <= version_user[:2] :
43                 return False
44             else :
45                 return True
46
47 def UpgradeConf(self) :
48     log.info('upgrade conf')
49     dictuser = self.ConfigPath
50     dictappli = ConstructConfigPath(self.AppliPath, user = False)
51     for item,filein in dictuser.iteritems():
52         if not item == u'global' and not item == u'history':
53             shutil.copyfile(dictappli[item], filein)
54     dicoUser = self.DictPath
55     dicoAppli = ConstructDicoPath(self.AppliPath)
56     for fi in dicoUser :
57         if not os.path.exists(dicoUser[fi]) and os.path.exists(dicoAppli[fi]):
58             shutil.copyfile(dicoAppli[fi], dicoUser[fi])
59
60 def CreateIraDirectory(UserConfigPath,AppliPath):
61     if not os.path.exists(UserConfigPath):
62         os.mkdir(UserConfigPath)
63     if not os.path.exists(os.path.join(UserConfigPath, 'dictionnaires')) :
64         os.mkdir(os.path.join(UserConfigPath, 'dictionnaires'))
65
66 def CopyConf(self) :
67     DictUser = self.ConfigPath
68     DictAppli = ConstructConfigPath(self.AppliPath,user=False)
69     for item, filein in DictUser.iteritems():
70         if not item == u'global' and not item == u'path' and not item == u'preferences' and not item == u'history' :
71             shutil.copyfile(DictAppli[item],filein)
72         if item == u'path':
73             if not os.path.exists(filein):
74                 shutil.copyfile(DictAppli[item],filein)
75         if item == u'preferences' :
76             if not os.path.exists(filein) :
77                 shutil.copyfile(DictAppli[item],filein)
78     dicoUser = self.DictPath
79     dicoAppli = ConstructDicoPath(self.AppliPath)
80     for fi in dicoUser :
81         if not os.path.exists(dicoUser[fi]) and os.path.exists(dicoAppli[fi]):
82             shutil.copyfile(dicoAppli[fi], dicoUser[fi])
83
84 def CheckRPath(PathPath):
85     if not os.path.exists(PathPath.get('PATHS','rpath')):
86         return False
87     else :
88         return True
89         
90 def FindRPAthWin32():
91     BestPath=False
92     progpaths=[]
93     if 'ProgramFiles' in os.environ :
94         progpaths.append(os.environ['ProgramFiles'])
95     if 'ProgramFiles(x86)' in os.environ :
96         progpaths.append(os.environ['ProgramFiles(x86)'])
97     if 'ProgramW6432' in os.environ :
98         progpaths.append(os.environ['ProgramW6432'])
99     progpaths = list(set(progpaths))
100     if progpaths != [] :
101         for progpath in progpaths :
102             rpath = os.path.join(progpath, "R")
103             if os.path.exists(rpath) :
104                 for maj in range(2,4) :
105                     for i in range(0,30):
106                         for j in range(0,20):
107                             for poss in ['', 'i386', 'x64'] :
108                                 path=os.path.join(rpath,"R-%i.%i.%i" % (maj, i, j),'bin',poss,'R.exe')
109                                 print path
110                                 if os.path.exists(path):
111                                     BestPath=path
112     return BestPath
113
114 def FindRPathNix():
115     BestPath=False
116     if os.path.exists('/usr/bin/R'):
117         BestPath='/usr/bin/R'
118     elif os.path.exists('/usr/local/bin/R'):
119         BestPath='/usr/local/bin/R'
120     return BestPath
121
122 def RLibsAreInstalled(self) :
123     rlibs = self.pref.get('iramuteq', 'rlibs')
124     if rlibs == 'false' or rlibs == 'False' :
125         return False
126     else :
127         return True
128
129 def CheckRPackages(self):
130     listdep = ['ca', 'rgl', 'gee', 'ape', 'igraph','proxy', 'wordcloud', 'irlba', 'textometry']
131     nolib = []
132     i=0
133     dlg = wx.ProgressDialog("Test des librairies de R", "test en cours...", maximum = len(listdep), parent=self, style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME | wx.PD_CAN_ABORT)
134     for bib in listdep :
135         dlg.Center()
136         i+=1
137         dlg.Update(i, "test de %s" % bib)
138         txt = """library("%s")""" % bib
139         tmpscript = tempfile.mktemp(dir=self.TEMPDIR)
140         with open(tmpscript, 'w') as f :
141             f.write(txt)
142         test = exec_rcode(self.RPath, tmpscript, wait = True)
143         if test :
144             log.info('packages %s : NOT INSTALLED' % bib)
145             nolib.append(bib)
146         else :
147             log.info('packages %s : OK' % bib)
148     dlg.Update(len(listdep),'fini')
149     dlg.Destroy()
150     if nolib != [] :
151         txt = '\n'.join(nolib)
152         msg = u"""Les bibliothèques de R suivantes sont manquantes :
153 %s
154
155 Sans ces bibliothèques, IRamuteq ne fonctionnera pas.
156     
157 - Vous pouvez installer ces bibliothèques manuellement :
158         Cliquez sur Annuler
159         Lancez R
160         Tapez install.packages('nom de la bibiothèque')
161         
162 - ou laisser IRamuteq les installer automatiquement en cliquant sur VALIDER .
163         Les bibliothèques seront téléchargées depuis le site miroir de R %s.
164         """ % (txt, self.pref.get('iramuteq','rmirror'))
165         dial = wx.MessageDialog(self, msg, u"Installation incomplète", wx.OK | wx.CANCEL | wx.ICON_WARNING)
166         dial.CenterOnParent()
167         val = dial.ShowModal()
168         if val == wx.ID_OK :
169             dlg = wx.ProgressDialog("Installation",
170                                        "Veuillez patientez...",
171                                        maximum=len(nolib) + 1,
172                                        parent=self,
173                                        style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME | wx.PD_CAN_ABORT
174                                        )
175             dlg.Center()
176             dlg.Update(1, u"installation...") 
177             compt = 0
178
179             for bib in nolib :
180                 compt += 1
181                 dlg.Update(compt, u"installation librairie %s" % bib)
182                 txt = """
183                 userdir <- unlist(strsplit(Sys.getenv("R_LIBS_USER"), .Platform$path.sep))[1]
184                 if (!file.exists(userdir)) {
185                     if (!dir.create(userdir, recursive = TRUE)) 
186                         print('pas possible')
187                     lib <- userdir
188                     .libPaths(c(userdir, .libPaths()))
189                 }
190                 print(userdir)
191                 .libPaths
192                 """
193                 txt += """
194                 install.packages("%s", repos = "%s")
195                 """ % (bib, self.pref.get('iramuteq','rmirror'))
196                 tmpscript = tempfile.mktemp(dir=self.TEMPDIR)
197                 with open(tmpscript, 'w') as f :
198                     f.write(txt)
199                 test = exec_rcode(self.RPath, tmpscript, wait = False)
200                 while test.poll() == None :
201                     dlg.Pulse(u"installation librairie %s" % bib)
202                     sleep(0.2)
203             dlg.Update(len(nolib) + 1, 'fin')
204             dlg.Destroy()
205         dial.Destroy()
206     if nolib == [] : 
207         #self.pref.set('iramuteq', 'rlibs', True)
208         with open(self.ConfigPath['preferences'], 'w') as f :
209             self.pref.write(f)
210         return True