99import tempfile
1010import re
1111import platform
12+ import argparse
1213
13- logging .basicConfig (level = logging .ERROR ) # DEBUG => print ALL msgs
14+ __version__ = "0.0.2"
15+
16+ logging .basicConfig (level = logging .INFO ) # DEBUG => print ALL msgs
17+ log = logging .getLogger ("pyv8unpack" )
1418
1519modified = re .compile ('^(?:M|A)(\s+)(?P<name>.*)' )
1620
1721
1822def get_config_param (param ):
1923 '''
20- parse config file and find in them source dir
24+ parse config file and find in them source dir
2125 '''
22-
26+
2327 curdir = os .curdir
2428 if '__file__' in globals ():
2529 curdir = os .path .dirname (os .path .abspath (__file__ ))
@@ -43,20 +47,20 @@ def get_config_param(param):
4347 if not config is None and config .has_option ("DEFAULT" , param ):
4448 value = config .get ("DEFAULT" , param )
4549 return value
46-
50+
4751
4852 return None
4953
5054
5155def get_path_to_1c ():
5256 """
53- get path to 1c binary.
54- fist env, "PATH1C"
57+ get path to 1c binary.
58+ fist env, "PATH1C"
5559 two env "PROGRAMFILES" on windows
5660 three /opt/1c - only linux
57-
61+
5862 """
59-
63+
6064 cmd = os .getenv ("PATH1C" )
6165 if not cmd is None :
6266 cmd = os .path .join (cmd , "1cv8" )
@@ -67,7 +71,7 @@ def get_path_to_1c():
6771
6872 if not os .path .isfile (cmd ):
6973 raise Exception ("file not found %s" % (cmd ))
70-
74+
7175 return cmd
7276
7377 #read config
@@ -80,14 +84,14 @@ def get_path_to_1c():
8084
8185 onecplatfrorm_config = get_config_param ("onecplatfrorm" )
8286 if not onecplatfrorm_config is None :
83- return onecplatfrorm_config
84-
87+ return onecplatfrorm_config
88+
8589 if platform .system () == "Darwin" :
8690 raise Exception ("MacOS not run 1C" )
8791 elif platform .system () == "Windows" :
8892 program_files = os .getenv ("PROGRAMFILES(X86)" )
8993 if program_files is None :
90- #FIXME: проверить архетиктуру.
94+ #FIXME: проверить архетиктуру.
9195 program_files = os .getenv ("PROGRAMFILES" )
9296 if program_files is None :
9397 raise Exeption ("path to Program files not found" );
@@ -99,11 +103,11 @@ def get_path_to_1c():
99103
100104 if not os .path .isfile (cmd ):
101105 raise Exception ("file not found %s" % (cmd ))
102-
106+
103107 else :
104108 cmd = subprocess .Popen (["which" , "1cv8" ], stdout = PIPE ).communicate ()[0 ].strip ()
105-
106- return cmd
109+
110+ return cmd
107111
108112def get_list_of_comitted_files ():
109113 """
@@ -127,10 +131,10 @@ def get_list_of_comitted_files():
127131
128132 return files
129133
130-
131- def decompile ():
134+ def decompile (list_of_files , source = None , platform = None ):
132135 """
133136 Main functions doing be decompile
137+ возвращает list
134138 """
135139
136140 #list of files to decompile and results decompile
@@ -140,28 +144,27 @@ def decompile():
140144 exit_code = 0
141145
142146 #Find datapocessor files
143- for filename in get_list_of_comitted_files () :
147+ for filename in list_of_files :
144148 #Check the file extensions
145- logging .info ("file to check %s" % filename )
149+ logging .debug ("file to check %s" % filename )
146150 if filename [- 3 :] in ['epf' , 'erf' ]:
147151 dataprocessor_files .append (filename )
148- logging .info ("file %s" % filename )
152+ logging .debug ("file %s" % filename )
149153 continue
150154 if len (dataprocessor_files ) == 0 :
151155 exit (exit_code )
152-
153- source_dir = get_config_param ("source" )
156+
157+ source_dir = source or get_config_param ("source" )
154158 if source_dir is None :
155159 source_dir = "src"
156160
157161 dirsource = os .path .abspath (os .path .join (os .path .curdir , source_dir ))
158162 curabsdirpath = os .path .abspath (os .path .curdir )
159- #pathbin1c = "C:\\Program Files\\1cv82\8.2.17.153\\bin\\1cv8.exe"
160- #pathbin1c = "c:\\Program Files (x86)\\1cv8\\8.3.4.304\\bin\\1cv8.exe"
161- pathbin1c = get_path_to_1c ()
163+ pathbin1c = platform or get_path_to_1c ()
164+ returnlist = []
162165
163166 for filename in dataprocessor_files :
164- print ("file %s" % filename )
167+ logging . info ("file %s" % filename )
165168 #TODO: добавить копирование этих же файлов в каталог src/имяфайла/...
166169 #get file name.
167170 fullpathfile = os .path .abspath (filename )
@@ -174,29 +177,137 @@ def decompile():
174177 os .makedirs (dirsource )
175178 #для каждого файла определим новую папку.
176179 newsourcepath = os .path .join (dirsource , newdirname , basename )
180+ if (os .path .isabs (newdirname )):
181+ newsourcepath = os .path .join (dirsource , basename )
177182 if not os .path .exists (newsourcepath ):
178- logging .info ("create new dir %s" % newsourcepath )
183+ logging .debug ("create new dir %s" % newsourcepath )
179184 os .makedirs (newsourcepath )
180185
181- logging .info ("file to copy %s, new path %s, new file %s" % (filename , newsourcepath ,
182- os .path .join (newsourcepath ,fullbasename )))
186+ logging .debug ("file to copy %s, new path %s, new file %s"
187+ % (filename , newsourcepath , os .path .join (newsourcepath , fullbasename ))
188+ )
183189
184190 formatstring = format ('/C"decompile;pathtocf;%s;pathout;%s;ЗавершитьРаботуПосле;"' % (fullpathfile , newsourcepath ))
185191 base = '/F"' + os .path .join (curabsdirpath ,".git" , "hooks" ,"ibService" )+ '"'
186192 V8Reader = '/execute"' + os .path .join (curabsdirpath ,".git" , "hooks" , "V8Reader.epf" )+ '"'
187193 tempbat = tempfile .mktemp (".bat" )
188- logging .info ("formatstring is %s , base is %s, V8Reader is %s, temp is %s" % (formatstring , base , V8Reader , tempbat ))
194+ logging .debug ("formatstring is %s , base is %s, V8Reader is %s, temp \
195+ is %s" % (formatstring , base , V8Reader , tempbat ))
196+
189197
190198 with open (tempbat , 'w' , encoding = 'cp866' ) as temp :
191199 temp .write ('@echo off\n ' )
192200 temp .write (format ('"%s" %s /DisableStartupMessages %s %s' % (pathbin1c , base , V8Reader , formatstring )))
193201 temp .close ()
194202 result = subprocess .check_call (['cmd.exe' , '/C' , tempbat ])
195- result = subprocess .check_call (['git' , 'add' , '--all' , newsourcepath ])
196203 if not result == 0 :
197- logging .error (result )
198- exit (result )
204+ logging .error (format ("Не удалось разобрать \
205+ обработку %s" % (fullpathfile )))
206+ raise format ("Не удалось разобрать обработку %s" % (fullpathfile ))
207+ returnlist .append (newsourcepath )
208+ logging .info ("Разобран в %s" % (newsourcepath ))
209+
210+ return returnlist
211+
212+ def add_to_git (pathlists ):
213+
214+ for l in pathlists :
215+ result = subprocess .check_call (['git' , 'add' , '--all' , l ])
216+ if not result == 0 :
217+ logging .error (result )
218+ exit (result )
219+
220+ def compile (input , output , ext ):
221+ import codecs
222+ if input is None :
223+ raise "Не указан путь к входящему каталогу"
224+ if output is None :
225+ raise "Не указан путь к исходящему файлу"
226+ extfile = "epf" if ext == "auto" else ext
227+
228+ dirsource = os .path .abspath (os .path .join (os .path .curdir , input ))
229+ if not os .path .exists (dirsource ) or not os .path .isdir (dirsource ):
230+ raise "Не существует входящего каталога"
231+
232+ renamesFile = os .path .join (dirsource , "renames.txt" )
233+ if not os .path .exists (renamesFile ):
234+ raise "Не существует файла {}" .format (renamesFile )
235+ tempPath = tempfile .mkdtemp ()
236+
237+ with codecs .open (renamesFile , "rb" , encoding = 'utf-8' ) as r :
238+ lines = r .read ()
239+ lines = lines .split ('\r \n ' )
240+ for l in lines :
241+ list = l .split ("-->" )
242+ if len (list ) < 2 :
243+ continue
244+ log .error (l )
245+ newPath = os .path .join (tempPath , list [0 ])
246+ dirname = os .path .dirname (newPath )
247+ if not os .path .exists (dirname ):
248+ os .mkdir (dirname )
249+ oldPath = os .path .join (dirsource , list [1 ].replace ("\\ " , os .path .sep ))
250+ if os .path .isdir (oldPath ):
251+ #tempFile = tempfile.mkstemp()
252+ newPath = os .path .join (tempPath , list [0 ])
253+ shutil .copytree (oldPath , newPath )
254+ else :
255+ log .error (oldPath )
256+ shutil .copy (
257+ os .path .normpath (oldPath ),
258+ newPath
259+ )
260+
261+ #вызовем v8unpack, для сборки файла из исходников.
262+ tempFile = tempfile .mktemp ("." + extfile )
263+ log .debug (["UnpackV8.exe" , "-PACK" , '{}{}' .format (tempPath , os .path .sep ), tempFile ])
264+ log .error ('UnpackV8.exe -B "{}" "{}"' .format ('{}{}' .format (tempPath , os .path .sep ), tempFile ))
265+ result = subprocess .check_call (['UnpackV8.exe' , '-PACK' , '{}{}' .format (tempPath , os .path .sep ), tempFile ])
266+ shutil .move (tempFile , output )
267+
268+ def main ():
269+
270+ parser = argparse .ArgumentParser (description = "Утилита \
271+ для автоматической распаковки внешних обработок" )
272+ parser .add_argument ("--version" , action = "version" ,
273+ version = "%(prog)s {}" .format (__version__ ))
274+ parser .add_argument ("-v" , "--verbose" , dest = "verbose_count" ,
275+ action = "count" , default = 0 ,
276+ help = "increases log verbosity for each occurence." )
277+ parser .add_argument ("--index" , action = "store_true" ,
278+ default = False , help = "Добавляем в индекс исходники" )
279+ parser .add_argument ("--g" , action = "store_true" , default = False ,
280+ help = "Запуситить чтение индекса из git и определить\
281+ список файлов для разбора" )
282+ parser .add_argument ("--compile" , action = "store_true" , default = False ,
283+ help = "Собрать внешний файл/обработку" )
284+ parser .add_argument ("--type" , action = "store" , default = "auto" ,
285+ help = "Тип файла для сборки epf, erf. По умолчанию авто epf" )
286+ parser .add_argument ("--platform" , action = "store" , help = "Путь \
287+ к платформе 1С" )
288+ parser .add_argument ("inputPath" , nargs = "?" , help = "Путь к \
289+ файлам необходимым для распаковки" )
290+ parser .add_argument ("output" , nargs = "?" , help = "Путь к \
291+ каталогу, куда распаковывать" )
292+
293+ args = parser .parse_args ()
294+
295+ log .setLevel (max (3 - args .verbose_count , 0 ) * 10 )
296+
297+ if args .g is True :
298+ files = get_list_of_comitted_files ()
299+ indexes = decompile (files , args .output , args .platform )
300+ if args .index is True :
301+ add_to_git (indexes )
302+
303+ if (args .compile ):
304+ compile (args .inputPath , args .output , args .type )
305+ if args .inputPath is not None :
306+ files = [os .path .abspath (
307+ os .path .join (os .path .curdir , args .inputPath ))]
308+ decompile (
309+ files , args .output , args .platform )
199310
200311
201312if __name__ == '__main__' :
202- decompile ( )
313+ sys . exit ( main () )
0 commit comments