Skip to content

Commit 393ee02

Browse files
authored
Merge pull request #105 from fosslight/develop
Be available to download yocto url
2 parents d4787a0 + 0d5940b commit 393ee02

File tree

3 files changed

+108
-50
lines changed

3 files changed

+108
-50
lines changed

src/fosslight_util/download.py

Lines changed: 85 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,14 @@
88
import tarfile
99
import zipfile
1010
import logging
11-
import getopt
11+
import argparse
1212
import shutil
1313
import pygit2 as git
1414
import bz2
1515
from datetime import datetime
1616
from pathlib import Path
17-
from ._get_downloadable_url import get_downloadable_url
17+
from fosslight_util._get_downloadable_url import get_downloadable_url
18+
from fosslight_util.help import print_help_msg_download
1819
import fosslight_util.constant as constant
1920
from fosslight_util.set_log import init_log
2021
import signal
@@ -48,37 +49,59 @@ def alarm_handler(signum, frame):
4849
raise TimeOutException()
4950

5051

51-
def print_help_msg():
52-
print("* Required : -s link_to_download")
53-
print("* Optional : -t target_directory")
54-
print("* Optional : -d log_file_directory")
55-
sys.exit(0)
52+
def change_src_link_to_https(src_link):
53+
src_link = src_link.replace("git://", "https://")
54+
if src_link.endswith(".git"):
55+
src_link = src_link.replace('.git', '')
56+
return src_link
57+
58+
59+
def parse_src_link(src_link):
60+
src_info = {}
61+
src_link_changed = ""
62+
if src_link.startswith("git://") or src_link.startswith("https://") or src_link.startswith("http://"):
63+
src_link_split = src_link.split(';')
64+
if src_link.startswith("git://github.com/"):
65+
src_link_changed = change_src_link_to_https(src_link_split[0])
66+
else:
67+
src_link_changed = src_link_split[0]
68+
69+
branch_info = [s for s in src_link_split if s.startswith('branch')]
70+
tag_info = [s for s in src_link_split if s.startswith('tag')]
71+
72+
src_info["url"] = src_link_changed
73+
src_info["branch"] = branch_info
74+
src_info["tag"] = tag_info
75+
return src_info
5676

5777

5878
def main():
79+
parser = argparse.ArgumentParser(description='FOSSLight Downloader', prog='fosslight_download', add_help=False)
80+
parser.add_argument('-h', '--help', help='Print help message', action='store_true', dest='help')
81+
parser.add_argument('-s', '--source', help='Source link to download', type=str, dest='source')
82+
parser.add_argument('-t', '--target_dir', help='Target directory', type=str, dest='target_dir', default="")
83+
parser.add_argument('-d', '--log_dir', help='Directory to save log file', type=str, dest='log_dir', default="")
5984

6085
src_link = ""
6186
target_dir = os.getcwd()
6287
log_dir = os.getcwd()
6388

6489
try:
65-
argv = sys.argv[1:]
66-
opts, args = getopt.getopt(argv, 'hs:t:d:')
67-
except getopt.GetoptError:
68-
print_help_msg()
69-
70-
for opt, arg in opts:
71-
if opt == "-h":
72-
print_help_msg()
73-
elif opt == "-s":
74-
src_link = arg
75-
elif opt == "-t":
76-
target_dir = arg
77-
elif opt == "-d":
78-
log_dir = arg
90+
args = parser.parse_args()
91+
except SystemExit:
92+
sys.exit(0)
93+
94+
if args.help:
95+
print_help_msg_download()
96+
if args.source:
97+
src_link = args.source
98+
if args.target_dir:
99+
target_dir = args.target_dir
100+
if args.log_dir:
101+
log_dir = args.log_dir
79102

80103
if src_link == "":
81-
print_help_msg()
104+
print_help_msg_download()
82105
else:
83106
cli_download_and_extract(src_link, target_dir, log_dir)
84107

@@ -98,9 +121,14 @@ def cli_download_and_extract(link, target_dir, log_dir, checkout_to="", compress
98121
msg = "Need a link to download."
99122
elif os.path.isfile(target_dir):
100123
success = False
101-
msg = "The target directory exists as a file.:"+target_dir
124+
msg = f"The target directory exists as a file.: {target_dir}"
102125
else:
103-
if not download_git_clone(link, target_dir, checkout_to):
126+
src_info = parse_src_link(link)
127+
link = src_info.get("url", "")
128+
tag = ''.join(src_info.get("tag", "")).split('=')[-1]
129+
branch = ''.join(src_info.get("branch", "")).split('=')[-1]
130+
131+
if not download_git_clone(link, target_dir, checkout_to, tag, branch):
104132
if os.path.isfile(target_dir):
105133
shutil.rmtree(target_dir)
106134

@@ -111,7 +139,7 @@ def cli_download_and_extract(link, target_dir, log_dir, checkout_to="", compress
111139
success = False
112140
msg = str(error)
113141

114-
logger.info("* FOSSLight Downloader - Result :"+str(success)+"\n"+msg)
142+
logger.info(f"\n* FOSSLight Downloader - Result: {success}\n {msg}")
115143
return success, msg
116144

117145

@@ -131,11 +159,24 @@ def get_ref_to_checkout(checkout_to, ref_list):
131159
ref_to_checkout = next(
132160
x for x in ref_list if x.endswith(checkout_to))
133161
except Exception as error:
134-
logger.warning("git find ref - failed:"+str(error))
162+
logger.warning(f"git find ref - failed: {error}")
163+
return ref_to_checkout
164+
165+
166+
def decide_checkout(checkout_to="", tag="", branch=""):
167+
if checkout_to != "":
168+
ref_to_checkout = checkout_to
169+
else:
170+
if branch != "":
171+
ref_to_checkout = branch
172+
else:
173+
ref_to_checkout = tag
135174
return ref_to_checkout
136175

137176

138-
def download_git_clone(git_url, target_dir, checkout_to=""):
177+
def download_git_clone(git_url, target_dir, checkout_to="", tag="", branch=""):
178+
ref_to_checkout = decide_checkout(checkout_to, tag, branch)
179+
139180
if platform.system() != "Windows":
140181
signal.signal(signal.SIGALRM, alarm_handler)
141182
signal.alarm(SIGNAL_TIMEOUT)
@@ -152,18 +193,16 @@ def download_git_clone(git_url, target_dir, checkout_to=""):
152193
else:
153194
del alarm
154195
except Exception as error:
155-
logger.warning("git clone - failed:"+str(error))
196+
logger.warning(f"git clone - failed: {error}")
156197
return False
157198
try:
158-
ref_to_checkout = checkout_to
159-
if checkout_to != "":
199+
if ref_to_checkout != "":
160200
ref_list = [x for x in repo.references]
161-
ref_to_checkout = get_ref_to_checkout(checkout_to, ref_list)
162-
logger.info("git checkout :"+ref_to_checkout)
201+
ref_to_checkout = get_ref_to_checkout(ref_to_checkout, ref_list)
202+
logger.info(f"git checkout: {ref_to_checkout}")
163203
repo.checkout(ref_to_checkout)
164204
except Exception as error:
165-
logger.warning("git checkout to "+ref_to_checkout +
166-
" - failed:"+str(error))
205+
logger.warning(f"git checkout to {ref_to_checkout} - failed: {error}")
167206
return True
168207

169208

@@ -194,33 +233,31 @@ def download_wget(link, target_dir, compressed_only):
194233
if not success:
195234
raise Exception('Not supported compression type (link:{0})'.format(link))
196235

197-
logger.info("wget:"+link)
198-
downloaded_file = wget.download(link)
236+
logger.info(f"wget: {link}")
237+
downloaded_file = wget.download(link, target_dir)
199238
if platform.system() != "Windows":
200239
signal.alarm(0)
201240
else:
202241
del alarm
203242

204-
shutil.move(downloaded_file, target_dir)
205-
downloaded_file = os.path.join(target_dir, downloaded_file)
206243
if downloaded_file != "":
207244
success = True
208-
logger.debug("wget - downloaded:"+downloaded_file)
245+
logger.debug(f"wget - downloaded: {downloaded_file}")
209246
except Exception as error:
210247
success = False
211-
logger.warning("wget - failed:"+str(error))
248+
logger.warning(f"wget - failed: {error}")
212249

213250
return success, downloaded_file
214251

215252

216253
def extract_compressed_dir(src_dir, target_dir, remove_after_extract=True):
217-
logger.debug("Extract Dir:"+src_dir)
254+
logger.debug(f"Extract Dir: {src_dir}")
218255
try:
219256
files_path = [os.path.join(src_dir, x) for x in os.listdir(src_dir)]
220257
for fname in files_path:
221258
extract_compressed_file(fname, target_dir, remove_after_extract)
222259
except Exception as error:
223-
logger.debug("Extract files in dir - failed:"+str(error))
260+
logger.debug(f"Extract files in dir - failed: {error}")
224261
return False
225262
return True
226263

@@ -248,15 +285,15 @@ def extract_compressed_file(fname, extract_path, remove_after_extract=True):
248285
decompress_bz2(fname, extract_path)
249286
else:
250287
is_compressed_file = False
251-
logger.warning("Unsupported file extension:"+fname)
288+
logger.warning(f"Unsupported file extension: {fname}")
252289

253290
if remove_after_extract and is_compressed_file:
254-
logger.debug("Remove - extracted file :"+fname)
291+
logger.debug(f"Remove - extracted file: {fname}")
255292
os.remove(fname)
256293
else:
257-
logger.warning("Not a file:"+fname)
294+
logger.warning(f"Not a file: {fname}")
258295
except Exception as error:
259-
logger.error("Extract - failed:"+str(error))
296+
logger.error(f"Extract - failed: {error}")
260297
return False
261298
return True
262299

@@ -268,7 +305,7 @@ def decompress_bz2(source_file, dest_path):
268305
open(os.path.splitext(source_file)[0], 'wb').write(data) # write a uncompressed file
269306

270307
except Exception as error:
271-
logger.error("Decompress bz2 - failed:"+str(error))
308+
logger.error(f"Decompress bz2 - failed: {error}")
272309
return False
273310
return True
274311

@@ -280,7 +317,7 @@ def unzip(source_file, dest_path):
280317
fzip.extract(filename, dest_path)
281318
fzip.close()
282319
except Exception as error:
283-
logger.error("Unzip - failed:"+str(error))
320+
logger.error(f"Unzip - failed: {error}")
284321
return False
285322
return True
286323

src/fosslight_util/help.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,21 @@
1919
"""
2020

2121

22+
_HELP_MESSAGE_DOWNLOAD = """
23+
FOSSLight Downloader is a tool to download the package via input URL
24+
25+
Usage: fosslight_download [option1] <arg1> [options2] <arg2>
26+
ex) fosslight_download -s http://github.com/fosslight/fosslight -t output_dir -d log_dir
27+
28+
Required:
29+
-s\t\t URL of the package to be downloaded
30+
31+
Optional:
32+
-h\t\t Print help message
33+
-t\t\t Output path name
34+
-d\t\t Directory name to save the log file"""
35+
36+
2237
class PrintHelpMsg():
2338
message_suffix = ""
2439

@@ -41,3 +56,8 @@ def print_package_version(pkg_name, msg="", exitopt=True):
4156

4257
if exitopt:
4358
sys.exit(0)
59+
60+
61+
def print_help_msg_download(exitOpt=True):
62+
helpMsg = PrintHelpMsg(_HELP_MESSAGE_DOWNLOAD)
63+
helpMsg.print_help_msg(exitOpt)

src/fosslight_util/parsing_yaml.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ def find_sbom_yaml_files(path_to_find):
9292
return oss_pkg_files
9393

9494

95-
def set_value_switch(oss, key, value, yaml_file):
95+
def set_value_switch(oss, key, value, yaml_file=""):
9696
if key in ['oss name', 'name']:
9797
oss.name = value
9898
elif key in ['oss version', 'version']:
@@ -116,4 +116,5 @@ def set_value_switch(oss, key, value, yaml_file):
116116
elif key == 'yocto_recipe':
117117
oss.yocto_recipe = value
118118
else:
119-
_logger.debug(f"file:{yaml_file} - key:{key} cannot be parsed")
119+
if yaml_file != "":
120+
_logger.debug(f"file:{yaml_file} - key:{key} cannot be parsed")

0 commit comments

Comments
 (0)