11#!/usr/bin/python3
2- import platform
3- from .lua_runtime import LuaRuntime
42import sys
5- from pathlib import Path
3+
4+ for i in [
5+ "jinja2_easy.generator" ,
6+ "luadata.luatable" ,
7+ "requests_file" ,
8+ "requests_glob" ,
9+ "requests_stdin" ,
10+ "requests_text" ,
11+ ]:
12+ submodule = __name__ + ".bundled." + i .split ("." )[0 ] + "." + i
13+ try :
14+ sys .modules [i ] = __import__ (submodule )
15+ except ImportError :
16+ pass
17+
18+
19+ from .lua_runtime import LuaRuntime
620import argparse
7- from .osdeps_utils import lua_code as os_specific_lua_code , generate_args as os_specific_generate_args , mount_adapter
8- from os .path import isdir , isfile , join , relpath , isdir , abspath
9- from os import chdir , walk , path , listdir , getcwd
21+ from .osdeps_utils import (
22+ lua_code as os_specific_lua_code ,
23+ generate_args as os_specific_generate_args ,
24+ mount_adapter ,
25+ )
26+ from os .path import join , isdir
27+ from os import chdir , listdir , getcwd
1028from .osdeps import DeclareLuaMapping as LuaMapping , is_enabled , store_flag
11- from jinja2_easy .generator import Generator
1229
13- import platformdirs
30+ try :
31+ from jinja2_easy .generator import Generator
32+ except ImportError :
33+ from .bundled .jinja2_easy .jinja2_easy .generator import Generator
34+
1435import subprocess
1536import tempfile
16- import shutil
1737import sys
1838import tarfile
1939
2040from requests import Session
2141from requests .exceptions import RequestException
22- from requests_glob import FileAdapter
23- from requests_text import TextAdapter
24- from requests_stdin import StdinAdapter
42+
43+ try :
44+ from requests_glob import FileAdapter
45+ except ImportError :
46+ from .bundled .requests_glob .requests_glob import FileAdapter
47+
48+ try :
49+ from requests_text import TextAdapter
50+ except ImportError :
51+ from .bundled .requests_text .requests_text import TextAdapter
52+
53+ try :
54+ from requests_stdin import StdinAdapter
55+ except ImportError :
56+ from .bundled .requests_stdin .requests_stdin import StdinAdapter
57+
2558
2659class GetCwd :
2760 def __repr__ (self ):
2861 return getcwd ()
2962
63+
3064def fetch (args ):
3165 # Step 1: Create a temporary directory
3266 outdir = args .outdir
3367 with tempfile .TemporaryDirectory () as temp_dir :
3468 # set output directory
3569 tmp = args .outdir = str (temp_dir )
3670
37- if ( is_enabled (args , ' tostdout' ) ):
71+ if is_enabled (args , " tostdout" ):
3872 resultdir = tmp
3973 elif not outdir :
4074 resultdir = getcwd ()
4175 else :
4276 resultdir = outdir
4377 # set template to rock.rockspec
44- args .template = ' rock.rockspec'
78+ args .template = " rock.rockspec"
4579 # Generate rockspec file in temporary directory
4680 generator (args )
4781 # Find the generated rockspec file
48- rockspec_files = [f for f in listdir (temp_dir ) if f .endswith (' .rockspec' )]
82+ rockspec_files = [f for f in listdir (temp_dir ) if f .endswith (" .rockspec" )]
4983 if not rockspec_files :
5084 raise Exception ("No .rockspec files found in the temporary directory." )
5185 return
5286 rockspec_file = join (tmp , rockspec_files [0 ])
5387 # Run luarocks pack in the temporary directory
54- if subprocess .run (
55- ["luarocks" , "pack" , rockspec_file ],
56- cwd = temp_dir ,
57- check = True
58- ).returncode == 0 :
88+ if (subprocess .run (["luarocks" , "pack" , rockspec_file ], cwd = temp_dir , check = True ).returncode == 0 ):
5989 print (f"Successfully packed { rockspec_file } in { tmp } " )
6090 else :
61- print (f "Error while packing" )
91+ print ("Error while packing" )
6292 # Find the generated .src.rock file
63- rock_files = [f for f in listdir (temp_dir ) if f .endswith (' .src.rock' )]
93+ rock_files = [f for f in listdir (temp_dir ) if f .endswith (" .src.rock" )]
6494 if not rock_files :
6595 raise Exception ("No .src.rock files found in the temporary directory." )
6696 return
6797 # Unpack the first .src.rock file found
6898 rock_prefix = rock_files [0 ]
6999 rock_file = join (tmp , rock_prefix )
70- if subprocess .run (
71- ["luarocks" , "unpack" , rock_file ],
72- cwd = temp_dir ,
73- check = True
74- ).returncode == 0 :
100+ if (subprocess .run (["luarocks" , "unpack" , rock_file ], cwd = temp_dir , check = True ).returncode == 0 ):
75101 print (f"Successfully unpacked { rock_file } in { tmp } " )
76102 else :
77- print (f "Error while unpacking" )
103+ print ("Error while unpacking" )
78104 # Get prefix of unpacked directory
79- rock_prefix = rock_prefix [0 : - len (' .src.rock' )]
105+ rock_prefix = rock_prefix [0 : - len (" .src.rock" )]
80106 # Get directory
81107 rock_dir = join (temp_dir , rock_prefix )
82108 # Find directories in rock_dir
@@ -85,13 +111,14 @@ def fetch(args):
85111 raise Exception (f"No inner dir at path { rock_dir } " )
86112 # Archive the first directory found
87113 inner_dir = join (rock_dir , inner_dirs [0 ])
88- outfile = join (resultdir , rock_prefix + ".tar.gz" )
89- # create_tar_gz_with_prefix(inner_dir, rock_prefix, outfile)
114+ outfile = join (resultdir , rock_prefix + ".tar.gz" )
115+ # create_tar_gz_with_prefix(inner_dir, rock_prefix, outfile)
90116 with tarfile .open (outfile , "w:gz" ) as tar :
91117 tar .add (inner_dir , arcname = rock_prefix )
92118 print (f"Successfully created { outfile } " )
93119 args .outdir = outdir
94120
121+
95122class generate_rockspec (Generator ):
96123 def __init__ (self , * args , current_directory = GetCwd (), ** kwargs ):
97124 super ().__init__ (* args , ** kwargs )
@@ -101,33 +128,34 @@ def __init__(self, *args, current_directory=GetCwd(), **kwargs):
101128
102129 # setup requests session
103130 def get_session (self ):
104- self .session .mount ('file://' , FileAdapter (netloc_paths = {'.' :self .current_directory }))
105- self .session .mount ('text://' , TextAdapter ())
106- self .session .mount ('stdin://' ,StdinAdapter ())
131+ self .session .mount (
132+ "file://" , FileAdapter (netloc_paths = {"." : self .current_directory })
133+ )
134+ self .session .mount ("text://" , TextAdapter ())
135+ self .session .mount ("stdin://" , StdinAdapter ())
107136 mount_adapter (self )
108137
109138 # read rockspec file
110139 def read_rockspec_file (self , path_or_url ):
111140 try :
112141 return self .session .get (path_or_url ).text
113142 except RequestException :
114- return open (path_or_url , 'r' ).read ()
143+ return open (path_or_url , "r" ).read ()
115144
116145 # function used for generating rockspec specification
117146 def rockspec (generator , args ):
118147 # get rockspec path
119148 rockspec_path = args .rockspec
120149 luacode = args .luacode or []
121150 defines = args .define or []
122- cache = {}
123- session = generator .session
124- newline = "\n "
151+ cache = {}
152+ newline = "\n "
125153 # generate lua code (luarocks rockspec contains an lua compatible code)
126- luaprog = f'''
154+ luaprog = f"""
127155{ newline .join (generator .read_rockspec_file (rockspec_path_i ) for rockspec_path_i in rockspec_path )}
128156{ os_specific_lua_code (args )}
129157{ newline .join ([cache [a ] for a in duplicates if custom_dependency (args , a , cache )] + luacode + [a [0 ] + '=' + a [1 ] for a in defines if len (a ) > 1 ])}
130- '''
158+ """
131159 # create lua runtime
132160 lua = LuaRuntime ()
133161 # execute code
@@ -139,12 +167,12 @@ def rockspec(generator, args):
139167 def __call__ (generator , args ):
140168 rockspec = generator .rockspec (args )
141169 template = args .template or rockspec .template
142- filename = args .filename or rockspec .filename or generator .default_file_output (rockspec .name , template )
170+ filename = ( args .filename or rockspec .filename or generator .default_file_output (rockspec .name , template ) )
143171 outdir = args .outdir or rockspec .outdir
144172 if outdir and isdir (outdir ):
145173 chdir (outdir )
146174 mp = LuaMapping (rockspec )
147- if ( is_enabled (args , ' tostdout' ) ):
175+ if is_enabled (args , " tostdout" ):
148176 generator .render (mp , template )
149177 else :
150178 generator .write_template (mp , template , filename )
@@ -157,79 +185,146 @@ def custom_dependency(args, name, cache):
157185 return False
158186 except AttributeError :
159187 return False
160- if not name in cache :
161- cache [name ] = name + '={' + ',' .join (map (repr , array ))+ '}'
188+ if name not in cache :
189+ cache [name ] = name + "={" + "," .join (map (repr , array )) + "}"
162190 return True
163191
192+
164193# Create requirement duplicates
165- duplicates = (lambda array , array2 : ['add_' + i for i in array + array2 ] + ['add_luarocks_' + i for i in array ]) ((* map (lambda a : a + "_requires" , ('build' , 'check' , 'preun' , 'pre' , 'postun' , 'post' , 'pretrans' , 'posttrans' )), 'requires' , 'provides' , 'recommends' , 'conflicts' , 'obsoletes' ), ('patch' ,'source' ,'macro' ,'text' ))
194+ duplicates = (
195+ lambda array , array2 : ["add_" + i for i in array + array2 ] + ["add_luarocks_" + i for i in array ]
196+ )(
197+ (
198+ * map (
199+ lambda a : a + "_requires" ,
200+ (
201+ "build" ,
202+ "check" ,
203+ "preun" ,
204+ "pre" ,
205+ "postun" ,
206+ "post" ,
207+ "pretrans" ,
208+ "posttrans" ,
209+ ),
210+ ),
211+ "requires" ,
212+ "provides" ,
213+ "recommends" ,
214+ "conflicts" ,
215+ "obsoletes" ,
216+ ),
217+ ("patch" , "source" , "macro" , "text" ),
218+ )
166219
167220# Define generator's template environment
168- generator = generate_rockspec ('lua2pack' , __path__ [0 ])
221+ generator = generate_rockspec ("lua2pack" , __path__ [0 ])
222+
169223
170224def Munch (args ):
171225 import collections
226+
172227 d = collections .defaultdict (lambda : None )
173228 d .update (args )
174- return type ('Munch' , tuple (), {
175- "__getattr__" : d .__getitem__ ,
176- "__setattr__" : d .__setitem__ ,
177- "__getitem__" : d .__getitem__ ,
178- "__setitem__" : d .__setitem__ ,
179- "__contains__" : d .__contains__ })()
229+ return type (
230+ "Munch" ,
231+ tuple (),
232+ {
233+ "__getattr__" : d .__getitem__ ,
234+ "__setattr__" : d .__setitem__ ,
235+ "__getitem__" : d .__getitem__ ,
236+ "__setitem__" : d .__setitem__ ,
237+ "__contains__" : d .__contains__ ,
238+ },
239+ )()
240+
180241
181242def main (args = None ):
182243 # Create the parser
183- mainparser = argparse .ArgumentParser (description = "A Python script that generates a rockspec file" )
244+ mainparser = argparse .ArgumentParser (
245+ description = "A Python script that generates a rockspec file"
246+ )
184247 # set defaults
185248 mainparser .set_defaults (func = lambda * a : mainparser .print_help ())
186249 # add noop operation
187- store_flag (mainparser , ' noop' )
250+ store_flag (mainparser , " noop" )
188251 # add subparsers
189- subparsers = mainparser .add_subparsers (title = ' commands' )
252+ subparsers = mainparser .add_subparsers (title = " commands" )
190253 # add generate command
191- parser = subparsers .add_parser ('generate' , help = "generate RPM spec or DEB dsc file for a rockspec specification" )
254+ parser = subparsers .add_parser (
255+ "generate" ,
256+ help = "generate RPM spec or DEB dsc file for a rockspec specification" ,
257+ )
192258 # add generate command
193- fetcher = subparsers .add_parser ('fetch' , help = "fetch sources for a rockspec specification" )
259+ fetcher = subparsers .add_parser (
260+ "fetch" , help = "fetch sources for a rockspec specification"
261+ )
194262 # add noop operation
195- store_flag (parser , ' noop' )
196- store_flag (fetcher , ' noop' )
263+ store_flag (parser , " noop" )
264+ store_flag (fetcher , " noop" )
197265 # add tostdout flag
198- store_flag (parser , ' tostdout' )
199- store_flag (fetcher , ' tostdout' )
266+ store_flag (parser , " tostdout" )
267+ store_flag (fetcher , " tostdout" )
200268 # Define the command-line arguments
201269 # Rockspec file
202- parser .add_argument ("--rockspec" , help = "Path to the rockspec file or URI" , type = str , action = 'append' )
203- fetcher .add_argument ("--rockspec" , help = "Path to the rockspec file or URI" , type = str , action = 'append' )
270+ parser .add_argument (
271+ "--rockspec" , help = "Path to the rockspec file or URI" , type = str , action = "append"
272+ )
273+ fetcher .add_argument (
274+ "--rockspec" , help = "Path to the rockspec file or URI" , type = str , action = "append"
275+ )
204276 # Define lua parameters
205- parser .add_argument ("--define" , help = "Override some lua parameters" , type = str , action = 'append' , nargs = '*' )
206- fetcher .add_argument ("--define" , help = "Override some lua parameters" , type = str , action = 'append' , nargs = '*' )
277+ parser .add_argument (
278+ "--define" ,
279+ help = "Override some lua parameters" ,
280+ type = str ,
281+ action = "append" ,
282+ nargs = "*" ,
283+ )
284+ fetcher .add_argument (
285+ "--define" ,
286+ help = "Override some lua parameters" ,
287+ type = str ,
288+ action = "append" ,
289+ nargs = "*" ,
290+ )
207291 # Add specific lua code
208- parser .add_argument ("--luacode" , help = "Override some lua codes" , type = str , action = 'append' )
209- fetcher .add_argument ("--luacode" , help = "Override some lua codes" , type = str , action = 'append' )
292+ parser .add_argument (
293+ "--luacode" , help = "Override some lua codes" , type = str , action = "append"
294+ )
295+ fetcher .add_argument (
296+ "--luacode" , help = "Override some lua codes" , type = str , action = "append"
297+ )
210298 # Add duplicates
211299 for i in duplicates :
212- parser .add_argument ('--' + i .replace ('_' , '-' ), help = f"Additional { i .replace ('_' , ' ' )[1 :]} to be added" , type = str , action = 'append' )
300+ parser .add_argument (
301+ "--" + i .replace ("_" , "-" ),
302+ help = f"Additional { i .replace ('_' , ' ' )[1 :]} to be added" ,
303+ type = str ,
304+ action = "append" ,
305+ )
213306 os_specific_generate_args (parser )
214307
215308 # Template file for generate command
216- parser .add_argument ('-t' , '--template' , choices = generator .file_template_list (), help = 'file template' )
309+ parser .add_argument (
310+ "-t" , "--template" , choices = generator .file_template_list (), help = "file template"
311+ )
217312 # Template output filename for generate command
218- parser .add_argument ('-f' , ' --filename' , help = ' output filename (optional)' )
313+ parser .add_argument ("-f" , " --filename" , help = " output filename (optional)" )
219314 # Template output directory for generate command
220- parser .add_argument (' --outdir' , help = ' out directory (used by obs service)' )
221- fetcher .add_argument (' --outdir' , help = ' out directory (used by obs service)' )
315+ parser .add_argument (" --outdir" , help = " out directory (used by obs service)" )
316+ fetcher .add_argument (" --outdir" , help = " out directory (used by obs service)" )
222317 # Function for generate command
223318 parser .set_defaults (func = generator )
224319 fetcher .set_defaults (func = fetch )
225320 # Parse arguments
226321 args = Munch (mainparser .parse_args (args ).__dict__ )
227322 # Check if noop is enabled, if yes, then exit
228- if is_enabled (args , ' noop' ):
229- return
323+ if is_enabled (args , " noop" ):
324+ return
230325 # Execute function
231326 args .func (args )
232327
328+
233329if __name__ == "__main__" :
234330 main ()
235-
0 commit comments