55from pathlib import Path
66import argparse
77from .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
9- from os import chdir
8+ from os .path import isdir , isfile , join , relpath , isdir , abspath
9+ from os import chdir , walk , path , listdir , getcwd
1010from .osdeps import DeclareLuaMapping as LuaMapping , is_enabled , store_flag
11- from os import path , listdir , getcwd
1211from jinja2_easy .generator import Generator
12+
1313import platformdirs
14+ import subprocess
15+ import tempfile
16+ import shutil
17+ import sys
18+ import tarfile
1419
1520from requests import Session
1621from requests .exceptions import RequestException
@@ -22,6 +27,71 @@ class GetCwd:
2227 def __repr__ (self ):
2328 return getcwd ()
2429
30+ def fetch (args ):
31+ # Step 1: Create a temporary directory
32+ outdir = args .outdir
33+ with tempfile .TemporaryDirectory () as temp_dir :
34+ # set output directory
35+ tmp = args .outdir = str (temp_dir )
36+
37+ if (is_enabled (args , 'tostdout' )):
38+ resultdir = tmp
39+ elif not outdir :
40+ resultdir = getcwd ()
41+ else :
42+ resultdir = outdir
43+ # set template to rock.rockspec
44+ args .template = 'rock.rockspec'
45+ # Generate rockspec file in temporary directory
46+ generator (args )
47+ # Find the generated rockspec file
48+ rockspec_files = [f for f in listdir (temp_dir ) if f .endswith ('.rockspec' )]
49+ if not rockspec_files :
50+ raise Exception ("No .rockspec files found in the temporary directory." )
51+ return
52+ rockspec_file = join (tmp , rockspec_files [0 ])
53+ # 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 :
59+ print (f"Successfully packed { rockspec_file } in { tmp } " )
60+ else :
61+ print (f"Error while packing" )
62+ # Find the generated .src.rock file
63+ rock_files = [f for f in listdir (temp_dir ) if f .endswith ('.src.rock' )]
64+ if not rock_files :
65+ raise Exception ("No .src.rock files found in the temporary directory." )
66+ return
67+ # Unpack the first .src.rock file found
68+ rock_prefix = rock_files [0 ]
69+ 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 :
75+ print (f"Successfully unpacked { rock_file } in { tmp } " )
76+ else :
77+ print (f"Error while unpacking" )
78+ # Get prefix of unpacked directory
79+ rock_prefix = rock_prefix [0 :- len ('.src.rock' )]
80+ # Get directory
81+ rock_dir = join (temp_dir , rock_prefix )
82+ # Find directories in rock_dir
83+ inner_dirs = [f for f in listdir (rock_dir ) if isdir (join (rock_dir , f ))]
84+ if not inner_dirs :
85+ raise Exception (f"No inner dir at path { rock_dir } " )
86+ # Archive the first directory found
87+ 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)
90+ with tarfile .open (outfile , "w:gz" ) as tar :
91+ tar .add (inner_dir , arcname = rock_prefix )
92+ print (f"Successfully created { outfile } " )
93+ args .outdir = outdir
94+
2595class generate_rockspec (Generator ):
2696 def __init__ (self , * args , current_directory = GetCwd (), ** kwargs ):
2797 super ().__init__ (* args , ** kwargs )
@@ -97,6 +167,17 @@ def custom_dependency(args, name, cache):
97167# Define generator's template environment
98168generator = generate_rockspec ('lua2pack' , __path__ [0 ])
99169
170+ def Munch (args ):
171+ import collections
172+ d = collections .defaultdict (lambda : None )
173+ 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__ })()
180+
100181def main (args = None ):
101182 # Create the parser
102183 mainparser = argparse .ArgumentParser (description = "A Python script that generates a rockspec file" )
@@ -108,17 +189,24 @@ def main(args=None):
108189 subparsers = mainparser .add_subparsers (title = 'commands' )
109190 # add generate command
110191 parser = subparsers .add_parser ('generate' , help = "generate RPM spec or DEB dsc file for a rockspec specification" )
192+ # add generate command
193+ fetcher = subparsers .add_parser ('fetch' , help = "fetch sources for a rockspec specification" )
111194 # add noop operation
112195 store_flag (parser , 'noop' )
196+ store_flag (fetcher , 'noop' )
113197 # add tostdout flag
114198 store_flag (parser , 'tostdout' )
199+ store_flag (fetcher , 'tostdout' )
115200 # Define the command-line arguments
116201 # Rockspec file
117202 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' )
118204 # Define lua parameters
119205 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 = '*' )
120207 # Add specific lua code
121208 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' )
122210 # Add duplicates
123211 for i in duplicates :
124212 parser .add_argument ('--' + i .replace ('_' , '-' ), help = f"Additional { i .replace ('_' , ' ' )[1 :]} to be added" , type = str , action = 'append' )
@@ -130,10 +218,12 @@ def main(args=None):
130218 parser .add_argument ('-f' , '--filename' , help = 'output filename (optional)' )
131219 # Template output directory for generate command
132220 parser .add_argument ('--outdir' , help = 'out directory (used by obs service)' )
221+ fetcher .add_argument ('--outdir' , help = 'out directory (used by obs service)' )
133222 # Function for generate command
134223 parser .set_defaults (func = generator )
224+ fetcher .set_defaults (func = fetch )
135225 # Parse arguments
136- args = mainparser .parse_args (args )
226+ args = Munch ( mainparser .parse_args (args ). __dict__ )
137227 # Check if noop is enabled, if yes, then exit
138228 if is_enabled (args , 'noop' ):
139229 return
0 commit comments