Skip to content

Commit a1a00ef

Browse files
authored
Merge pull request #231 from sommersoft/fix_output_file
Fix Output File Generation For Reports
2 parents bf03aa8 + 127d623 commit a1a00ef

File tree

4 files changed

+165
-141
lines changed

4 files changed

+165
-141
lines changed

adabot/arduino_libraries.py

+35-37
Original file line numberDiff line numberDiff line change
@@ -19,25 +19,32 @@
1919
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
2121
# THE SOFTWARE.
22+
23+
import argparse
2224
import datetime
25+
import logging
2326
import sys
24-
import argparse
2527
import traceback
2628

2729
import requests
2830

2931
from adabot import github_requests as github
3032

33+
logger = logging.getLogger(__name__)
34+
ch = logging.StreamHandler(stream=sys.stdout)
35+
logging.basicConfig(
36+
level=logging.INFO,
37+
format='%(message)s',
38+
handlers=[ch]
39+
)
40+
3141
# Setup ArgumentParser
3242
cmd_line_parser = argparse.ArgumentParser(description="Adabot utility for Arduino Libraries.",
3343
prog="Adabot Arduino Libraries Utility")
3444
cmd_line_parser.add_argument("-o", "--output_file", help="Output log to the filename provided.",
3545
metavar="<OUTPUT FILENAME>", dest="output_file")
3646
cmd_line_parser.add_argument("-v", "--verbose", help="Set the level of verbosity printed to the command prompt."
3747
" Zero is off; One is on (default).", type=int, default=1, dest="verbose", choices=[0,1])
38-
output_filename = None
39-
verbosity = 1
40-
file_data = []
4148

4249
all_libraries = []
4350
adafruit_library_index = []
@@ -72,20 +79,13 @@ def is_arduino_library(repo):
7279

7380
def print_list_output(title, coll):
7481
""
75-
output_handler()
76-
output_handler(title.format(len(coll)-2))
82+
logger.info("")
83+
logger.info(title.format(len(coll)-2))
7784
long_col = [(max([len(str(row[i])) for row in coll]) + 3)
7885
for i in range(len(coll[0]))]
7986
row_format = "".join(["{:<" + str(this_col) + "}" for this_col in long_col])
8087
for lib in coll:
81-
output_handler(row_format.format(*lib))
82-
83-
def output_handler(message="", quiet=False):
84-
"""Handles message output to prompt/file for print_*() functions."""
85-
if output_filename is not None:
86-
file_data.append(message)
87-
if verbosity and not quiet:
88-
print(message)
88+
logger.info(row_format.format(*lib))
8989

9090
def validate_library_properties(repo):
9191
""" Checks if the latest GitHub Release Tag and version in the library_properties
@@ -132,7 +132,7 @@ def validate_release_state(repo):
132132

133133
compare_tags = github.get("/repos/" + repo["full_name"] + "/compare/master..." + repo['tag_name'])
134134
if not compare_tags.ok:
135-
output_handler("Error: failed to compare {0} 'master' to tag '{1}'".format(repo["name"], repo['tag_name']))
135+
logger.error("Error: failed to compare {0} 'master' to tag '{1}'".format(repo["name"], repo['tag_name']))
136136
return
137137
compare_tags_json = compare_tags.json()
138138
if "status" in compare_tags_json:
@@ -142,7 +142,7 @@ def validate_release_state(repo):
142142
# compare_tags_json["behind_by"], compare_tags_json["total_commits"], repo["full_name"]))
143143
return [repo['tag_name'], compare_tags_json["behind_by"]]
144144
elif "errors" in compare_tags_json:
145-
output_handler("Error: comparing latest release to 'master' failed on '{0}'. Error Message: {1}".format(
145+
logger.error("Error: comparing latest release to 'master' failed on '{0}'. Error Message: {1}".format(
146146
repo["name"], compare_tags_json["message"]))
147147

148148
return
@@ -166,11 +166,11 @@ def validate_example(repo):
166166
return repo_has_ino.ok and len(repo_has_ino.json())
167167

168168
def run_arduino_lib_checks():
169-
output_handler("Running Arduino Library Checks")
170-
output_handler("Getting list of libraries to check...")
169+
logger.info("Running Arduino Library Checks")
170+
logger.info("Getting list of libraries to check...")
171171

172172
repo_list = list_repos()
173-
output_handler("Found {} Arduino libraries to check\n".format(len(repo_list)))
173+
logger.info("Found {} Arduino libraries to check\n".format(len(repo_list)))
174174
failed_lib_prop = [[" Repo", "Release Tag", "library.properties Version"], [" ----", "-----------", "--------------------------"]]
175175
needs_release_list = [[" Repo", "Latest Release", "Commits Behind"], [" ----", "--------------", "--------------"]]
176176
needs_registration_list = [[" Repo"], [" ----"]]
@@ -218,7 +218,7 @@ def run_arduino_lib_checks():
218218
all_libraries.append(entry)
219219

220220
for entry in all_libraries:
221-
print(entry)
221+
logging.info(entry)
222222

223223
if len(failed_lib_prop) > 2:
224224
print_list_output("Libraries Have Mismatched Release Tag and library.properties Version: ({})", failed_lib_prop)
@@ -236,40 +236,38 @@ def run_arduino_lib_checks():
236236
print_list_output("Libraries that is missing library.properties file: ({})", missing_library_properties_list)
237237

238238

239-
def main(verbosity=1, output_filename=None):
239+
def main(verbosity=1, output_file=None):
240+
241+
if output_file:
242+
fh = logging.FileHandler(output_file)
243+
logger.addHandler(fh)
240244

241245
try:
242246
reply = requests.get("http://downloads.arduino.cc/libraries/library_index.json")
243247
if not reply.ok:
244-
print("Could not fetch http://downloads.arduino.cc/libraries/library_index.json")
248+
logging.error("Could not fetch http://downloads.arduino.cc/libraries/library_index.json")
245249
exit()
246250
arduino_library_index = reply.json()
247251
for lib in arduino_library_index['libraries']:
248252
if 'adafruit' in lib['url']:
249253
adafruit_library_index.append(lib)
250254
run_arduino_lib_checks()
251255
except:
252-
if output_filename is not None:
253-
exc_type, exc_val, exc_tb = sys.exc_info()
254-
output_handler("Exception Occurred!", quiet=True)
255-
output_handler(("-"*60), quiet=True)
256-
output_handler("Traceback (most recent call last):", quiet=True)
257-
tb = traceback.format_tb(exc_tb)
258-
for line in tb:
259-
output_handler(line, quiet=True)
260-
output_handler(exc_val, quiet=True)
256+
exc_type, exc_val, exc_tb = sys.exc_info()
257+
logger.error("Exception Occurred!", quiet=True)
258+
logger.error(("-"*60), quiet=True)
259+
logger.error("Traceback (most recent call last):")
260+
tb = traceback.format_tb(exc_tb)
261+
for line in tb:
262+
logger.error(line)
263+
logger.error(exc_val)
261264

262265
raise
263-
finally:
264-
if output_filename is not None:
265-
with open(output_filename, 'w') as f:
266-
for line in file_data:
267-
f.write(str(line) + "\n")
268266

269267
if __name__ == "__main__":
270268
cmd_line_args = cmd_line_parser.parse_args()
271269
main(
272270
verbosity=cmd_line_args.verbose,
273-
output_filename=cmd_line_args.output_file
271+
output_file=cmd_line_args.output_file
274272
)
275273

0 commit comments

Comments
 (0)