Skip to content

Commit 31407a1

Browse files
committed
Move to using command strings rather than command lists.
Previously the script used cmd =['git','checkout', branch] syntax. This does not work well cross platform. The solution it to actually use strings. E.g. cmd = "git checkout " + branch
1 parent d2d2b68 commit 31407a1

File tree

1 file changed

+69
-76
lines changed

1 file changed

+69
-76
lines changed

tools/test/examples/update.py

Lines changed: 69 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,6 @@
4242
# -c <config file> - Optional path to an examples file.
4343
# If not proved the default is 'examples.json'
4444
# -T <github_token> - GitHub token for secure access (required)
45-
# -l <logging level> - Optional Level for providing logging output. Can be one of,
46-
# CRITICAL, ERROR, WARNING, INFO, DEBUG
47-
# If not provided the default is 'INFO'
4845
# -f - Update forked repos. This will use the 'github-user' parameter in
4946
# the 'via-fork' section.
5047
# -b - Update branched repos. This will use the "src-branch" and
@@ -75,66 +72,76 @@
7572
import examples_lib as lib
7673
from examples_lib import SUPPORTED_TOOLCHAINS
7774

75+
userlog = logging.getLogger("Update")
76+
77+
# Set logging level
78+
userlog.setLevel(logging.DEBUG)
79+
80+
# Everything is output to the log file
81+
logfile = os.path.join(os.getcwd(), 'update.log')
82+
fh = logging.FileHandler(logfile)
83+
fh.setLevel(logging.DEBUG)
84+
85+
# create console handler with a higher log level
86+
ch = logging.StreamHandler()
87+
ch.setLevel(logging.INFO)
88+
89+
formatter = logging.Formatter('%(name)s: %(levelname)s - %(message)s')
90+
ch.setFormatter(formatter)
91+
fh.setFormatter(formatter)
92+
93+
# add the handlers to the logger
94+
userlog.addHandler(fh)
95+
userlog.addHandler(ch)
96+
7897
def run_cmd(command, exit_on_failure=False):
79-
""" Run a system command and return the result status
98+
""" Run a system command returning a status result
8099
81-
Description:
100+
This is just a wrapper for the run_cmd_with_output() function, but
101+
only returns the status of the call.
82102
83-
Passes a command to the system and returns a True/False result, once the
84-
command has been executed, indicating success/failure. Commands are passed
85-
as a list of tokens.
86-
E.g. The command 'git remote -v' would be passed in as ['git', 'remote', '-v']
87-
88103
Args:
89104
command - system command as a list of tokens
90105
exit_on_failure - If True exit the program on failure (default = False)
91106
92107
Returns:
93108
return_code - True/False indicating the success/failure of the command
94109
"""
95-
update_log.debug('[Exec] %s', ' '.join(command))
96-
return_code = subprocess.call(command, shell=True)
97-
98-
if return_code:
99-
update_log.warning("Command '%s' failed with return code: %s",
100-
' '.join(command), return_code)
101-
if exit_on_failure:
102-
sys.exit(1)
103-
110+
return_code, _ = run_cmd_with_output(command, exit_on_failure)
104111
return return_code
105112

106113
def run_cmd_with_output(command, exit_on_failure=False):
107-
""" Run a system command and return the result status plus output
114+
""" Run a system command returning a status result and any command output
108115
109-
Description:
110-
111116
Passes a command to the system and returns a True/False result once the
112117
command has been executed, indicating success/failure. If the command was
113118
successful then the output from the command is returned to the caller.
114-
Commands are passed as a list of tokens.
115-
E.g. The command 'git remote -v' would be passed in as ['git', 'remote', '-v']
119+
Commands are passed as a string.
120+
E.g. The command 'git remote -v' would be passed in as "git remote -v"
116121
117122
Args:
118-
command - system command as a list of tokens
123+
command - system command as a string
119124
exit_on_failure - If True exit the program on failure (default = False)
120125
121126
Returns:
122-
returncode - True/False indicating the success/failure of the command
127+
return_code - True/False indicating the success/failure of the command
123128
output - The output of the command if it was successful, else empty string
124129
"""
125-
update_log.debug('[Exec] %s', ' '.join(command))
130+
text = '[Exec] ' + command
131+
userlog.debug(text)
126132
returncode = 0
127133
output = ""
128134
try:
129135
output = subprocess.check_output(command, shell=True)
130136
except subprocess.CalledProcessError as e:
131-
update_log.warning("Command '%s' failed with return code: %s",
132-
' '.join(command), e.returncode)
137+
text = "The command " + str(command) + "failed with return code: " + str(e.returncode)
138+
userlog.warning(text)
133139
returncode = e.returncode
134140
if exit_on_failure:
135141
sys.exit(1)
136142
return returncode, output
137143

144+
138145
def rmtree_readonly(directory):
139146
""" Deletes a readonly directory tree.
140147
@@ -198,7 +205,7 @@ def upgrade_single_example(example, tag, directory, ref):
198205

199206
os.rename("mbed-os.lib", "mbed-os.lib_bak")
200207
else:
201-
update_log.error("Failed to backup mbed-os.lib prior to updating.")
208+
userlog.error("Failed to backup mbed-os.lib prior to updating.")
202209
return False
203210

204211
# mbed-os.lib file contains one line with the following format
@@ -221,7 +228,7 @@ def upgrade_single_example(example, tag, directory, ref):
221228

222229
if updated:
223230
# Setup and run the git add command
224-
cmd = ['git', 'add', 'mbed-os.lib']
231+
cmd = "git add mbed-os.lib"
225232
return_code = run_cmd(cmd)
226233

227234
os.chdir(cwd)
@@ -242,12 +249,12 @@ def prepare_fork(arm_example):
242249
"""
243250

244251
logstr = "In: " + os.getcwd()
245-
update_log.debug(logstr)
252+
userlog.debug(logstr)
246253

247-
for cmd in [['git', 'remote', 'add', 'armmbed', arm_example],
248-
['git', 'fetch', 'armmbed'],
249-
['git', 'reset', '--hard', 'armmbed/master'],
250-
['git', 'push', '-f', 'origin']]:
254+
for cmd in ["git remote add armmbed " + str(arm_example),
255+
"git fetch armmbed",
256+
"git reset --hard armmbed/master",
257+
"git push -f origin"]:
251258
run_cmd(cmd, exit_on_failure=True)
252259

253260
def prepare_branch(src, dst):
@@ -265,7 +272,7 @@ def prepare_branch(src, dst):
265272
266273
"""
267274

268-
update_log.debug("Preparing branch: %s", dst)
275+
userlog.debug("Preparing branch: %s", dst)
269276

270277
# Check if branch already exists or not.
271278
# We can use the 'git branch -r' command. This returns all the remote branches for
@@ -285,14 +292,14 @@ def prepare_branch(src, dst):
285292
# OOB branch does not exist thus create it, first ensuring we are on
286293
# the src branch and then check it out
287294

288-
for cmd in [['git', 'checkout', src],
289-
['git', 'checkout', '-b', dst],
290-
['git', 'push', '-u', 'origin', dst]]:
295+
for cmd in ["git checkout " + str(src),
296+
"git checkout -b " + str(dst),
297+
"git push -u origin " + str(dst)]:
291298

292299
run_cmd(cmd, exit_on_failure=True)
293300

294301
else:
295-
cmd = ['git', 'checkout', dst]
302+
cmd = "git checkout " + str(dst)
296303
run_cmd(cmd, exit_on_failure=True)
297304

298305
def upgrade_example(github, example, tag, ref, user, src, dst, template):
@@ -330,18 +337,18 @@ def upgrade_example(github, example, tag, ref, user, src, dst, template):
330337
user = 'ARMmbed'
331338

332339
ret = False
333-
update_log.info("Updating example '%s'", example['name'])
334-
update_log.debug("User: %s", user)
335-
update_log.debug("Src branch: %s", (src or "None"))
336-
update_log.debug("Dst branch: %s", (dst or "None"))
340+
userlog.info("Updating example '%s'", example['name'])
341+
userlog.debug("User: %s", user)
342+
userlog.debug("Src branch: %s", (src or "None"))
343+
userlog.debug("Dst branch: %s", (dst or "None"))
337344

338345
cwd = os.getcwd()
339346

340347
update_repo = "https://github.com/" + user + '/' + example['name']
341-
update_log.debug("Update repository: %s", update_repo)
348+
userlog.debug("Update repository: %s", update_repo)
342349

343350
# Clone the example repo
344-
clone_cmd = ['git', 'clone', update_repo]
351+
clone_cmd = "git clone " + str(update_repo)
345352
return_code = run_cmd(clone_cmd)
346353

347354
if not return_code:
@@ -362,30 +369,27 @@ def upgrade_example(github, example, tag, ref, user, src, dst, template):
362369
os.chdir(cwd)
363370
return False
364371

365-
# Setup the default commit message
366-
commit_message = 'Updating mbed-os to ' + tag
367-
368372
# Setup and run the commit command
369-
commit_cmd = ['git', 'commit', '-m', commit_message]
373+
commit_cmd = "git commit -m \"Updating mbed-os to " + tag + "\""
370374
return_code = run_cmd(commit_cmd)
371375
if not return_code:
372376

373377
# Setup and run the push command
374-
push_cmd = ['git', 'push', 'origin']
378+
push_cmd = "git push origin"
375379
return_code = run_cmd(push_cmd)
376380

377381
if not return_code:
378382
# If the user is not ARMmbed then a fork is being used
379383
if user != 'ARMmbed':
380384

381385
upstream_repo = 'ARMmbed/'+ example['name']
382-
update_log.debug("Upstream repository: %s", upstream_repo)
386+
userlog.debug("Upstream repository: %s", upstream_repo)
383387
# Check access to mbed-os repo
384388
try:
385389
repo = github.get_repo(upstream_repo, False)
386390

387391
except:
388-
update_log.error("Upstream repo: %s, does not exist - skipping", upstream_repo)
392+
userlog.error("Upstream repo: %s, does not exist - skipping", upstream_repo)
389393
return False
390394

391395
jinja_loader = FileSystemLoader(template)
@@ -400,15 +404,15 @@ def upgrade_example(github, example, tag, ref, user, src, dst, template):
400404
ret = True
401405
except GithubException as e:
402406
# Default to False
403-
update_log.error("Pull request creation failed with error: %s", e)
407+
userlog.error("Pull request creation failed with error: %s", e)
404408
else:
405409
ret = True
406410
else:
407-
update_log.error("Git push command failed.")
411+
userlog.error("Git push command failed.")
408412
else:
409-
update_log.error("Git commit command failed.")
413+
userlog.error("Git commit command failed.")
410414
else:
411-
update_log.error("Git clone %s failed", update_repo)
415+
userlog.error("Git clone %s failed", update_repo)
412416

413417
os.chdir(cwd)
414418
return ret
@@ -422,7 +426,7 @@ def create_work_directory(path):
422426
423427
"""
424428
if os.path.exists(path):
425-
update_log.info("'%s' directory already exists. Deleting...", path)
429+
userlog.info("'%s' directory already exists. Deleting...", path)
426430
rmtree_readonly(path)
427431

428432
os.makedirs(path)
@@ -433,28 +437,17 @@ def create_work_directory(path):
433437
formatter_class=argparse.RawDescriptionHelpFormatter)
434438
parser.add_argument('-c', '--config_file', help="Path to the configuration file (default is 'examples.json')", default='examples.json')
435439
parser.add_argument('-T', '--github_token', help="GitHub token for secure access")
436-
parser.add_argument('-l', '--log-level',
437-
help="Level for providing logging output",
438-
default='INFO')
439440

440441
exclusive = parser.add_mutually_exclusive_group(required=True)
441442
exclusive.add_argument('-f', '--fork', help="Update a fork", action='store_true')
442443
exclusive.add_argument('-b', '--branch', help="Update a branch", action='store_true')
443444

444445
args = parser.parse_args()
445446

446-
default = getattr(logging, 'INFO')
447-
level = getattr(logging, args.log_level.upper(), default)
448-
449-
# Set logging level
450-
logging.basicConfig(level=level)
451-
452-
update_log = logging.getLogger("Update")
453-
454447
# Load the config file
455448
with open(os.path.join(os.path.dirname(__file__), args.config_file)) as config:
456449
if not config:
457-
update_log.error("Failed to load config file '%s'", args.config_file)
450+
userlog.error("Failed to load config file '%s'", args.config_file)
458451
sys.exit(1)
459452
json_data = json.load(config)
460453

@@ -479,11 +472,11 @@ def create_work_directory(path):
479472
exit(1)
480473

481474
# Get the github sha corresponding to the specified mbed-os tag
482-
cmd = ['git', 'rev-list', '-1', tag]
475+
cmd = "git rev-list -1 " + tag
483476
return_code, ref = run_cmd_with_output(cmd)
484477

485478
if return_code:
486-
update_log.error("Could not obtain SHA for tag: %s", tag)
479+
userlog.error("Could not obtain SHA for tag: %s", tag)
487480
sys.exit(1)
488481

489482
# Loop through the examples
@@ -508,11 +501,11 @@ def create_work_directory(path):
508501
os.chdir('../')
509502

510503
# Finish the script and report the results
511-
update_log.info("Finished updating examples")
504+
userlog.info("Finished updating examples")
512505
if successes:
513506
for success in successes:
514-
update_log.info(" SUCCEEDED: %s", success)
507+
userlog.info(" SUCCEEDED: %s", success)
515508

516509
if failures:
517510
for fail in failures:
518-
update_log.info(" FAILED: %s", fail)
511+
userlog.info(" FAILED: %s", fail)

0 commit comments

Comments
 (0)