...
[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                                 if os.path.exists(path):
110                                     BestPath=path
111     return BestPath
112
113 def FindRPathNix():
114     BestPath=False
115     if os.path.exists('/usr/bin/R'):
116         BestPath='/usr/bin/R'
117     elif os.path.exists('/usr/local/bin/R'):
118         BestPath='/usr/local/bin/R'
119     return BestPath
120
121 def RLibsAreInstalled(self) :
122     rlibs = self.pref.get('iramuteq', 'rlibs')
123     if rlibs == 'false' or rlibs == 'False' :
124         return False
125     else :
126         return True
127
128 def CheckRPackages(self):
129     listdep = ['ca', 'rgl', 'gee', 'ape', 'igraph','proxy', 'wordcloud', 'irlba', 'textometry']
130     nolib = []
131     i=0
132     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)
133     for bib in listdep :
134         dlg.Center()
135         i+=1
136         dlg.Update(i, "test de %s" % bib)
137         txt = """library("%s")""" % bib
138         tmpscript = tempfile.mktemp(dir=self.TEMPDIR)
139         with open(tmpscript, 'w') as f :
140             f.write(txt)
141         test = exec_rcode(self.RPath, tmpscript, wait = True)
142         if test :
143             log.info('packages %s : NOT INSTALLED' % bib)
144             nolib.append(bib)
145         else :
146             log.info('packages %s : OK' % bib)
147     dlg.Update(len(listdep),'fini')
148     dlg.Destroy()
149     if nolib != [] :
150         txt = '\n'.join(nolib)
151         msg = u"""Les bibliothèques de R suivantes sont manquantes :
152 %s
153
154 Sans ces bibliothèques, IRamuteq ne fonctionnera pas.
155     
156 - Vous pouvez installer ces bibliothèques manuellement :
157         Cliquez sur Annuler
158         Lancez R
159         Tapez install.packages('nom de la bibiothèque')
160         
161 - ou laisser IRamuteq les installer automatiquement en cliquant sur VALIDER .
162         Les bibliothèques seront téléchargées depuis le site miroir de R %s.
163         """ % (txt, self.pref.get('iramuteq','rmirror'))
164         dial = wx.MessageDialog(self, msg, u"Installation incomplète", wx.OK | wx.CANCEL | wx.ICON_WARNING)
165         dial.CenterOnParent()
166         val = dial.ShowModal()
167         if val == wx.ID_OK :
168             dlg = wx.ProgressDialog("Installation",
169                                        "Veuillez patientez...",
170                                        maximum=len(nolib) + 1,
171                                        parent=self,
172                                        style=wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME | wx.PD_CAN_ABORT
173                                        )
174             dlg.Center()
175             dlg.Update(1, u"installation...") 
176             compt = 0
177
178             for bib in nolib :
179                 compt += 1
180                 dlg.Update(compt, u"installation librairie %s" % bib)
181                 txt = """
182                 userdir <- unlist(strsplit(Sys.getenv("R_LIBS_USER"), .Platform$path.sep))[1]
183                 if (!file.exists(userdir)) {
184                     if (!dir.create(userdir, recursive = TRUE)) 
185                         print('pas possible')
186                     lib <- userdir
187                     .libPaths(c(userdir, .libPaths()))
188                 }
189                 print(userdir)
190                 .libPaths
191                 """
192                 txt += """
193                 install.packages("%s", repos = "%s")
194                 """ % (bib, self.pref.get('iramuteq','rmirror'))
195                 tmpscript = tempfile.mktemp(dir=self.TEMPDIR)
196                 with open(tmpscript, 'w') as f :
197                     f.write(txt)
198                 test = exec_rcode(self.RPath, tmpscript, wait = False)
199                 while test.poll() == None :
200                     dlg.Pulse(u"installation librairie %s" % bib)
201                     sleep(0.2)
202             dlg.Update(len(nolib) + 1, 'fin')
203             dlg.Destroy()
204         dial.Destroy()
205     if nolib == [] : 
206         self.pref.set('iramuteq', 'rlibs', True)
207         with open(self.ConfigPath['preferences'], 'w') as f :
208             self.pref.write(f)
209         return True