Skip to content

Commit 5c8ef54

Browse files
Merge pull request #5224 from adbridge/master
Fix branch updates and make Linux compatible
2 parents 2f25744 + 31407a1 commit 5c8ef54

File tree

1 file changed

+80
-78
lines changed

1 file changed

+80
-78
lines changed

tools/test/examples/update.py

Lines changed: 80 additions & 78 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,25 +272,34 @@ 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.
271-
cmd = ['git', 'branch']
278+
# We can use the 'git branch -r' command. This returns all the remote branches for
279+
# the current repo.
280+
# The output consists of a list of lines of the form:
281+
# origin/<branch>
282+
# From these we need to extract just the branch names to a list and then check if
283+
# the specified dst exists in that list
284+
branches = []
285+
cmd = "git branch -r"
272286
_, output = run_cmd_with_output(cmd, exit_on_failure=True)
273287

274-
if not dst in output:
288+
branches = [line.split('/')[1] for line in output.split('\n') if 'origin' in line and not '->' in line]
289+
290+
if not dst in branches:
275291

276292
# OOB branch does not exist thus create it, first ensuring we are on
277293
# the src branch and then check it out
278294

279-
for cmd in [['git', 'checkout', src],
280-
['git', 'checkout', '-b', dst],
281-
['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)]:
282298

283299
run_cmd(cmd, exit_on_failure=True)
284300

285301
else:
286-
cmd = ['git', 'checkout', dst]
302+
cmd = "git checkout " + str(dst)
287303
run_cmd(cmd, exit_on_failure=True)
288304

289305
def upgrade_example(github, example, tag, ref, user, src, dst, template):
@@ -321,18 +337,18 @@ def upgrade_example(github, example, tag, ref, user, src, dst, template):
321337
user = 'ARMmbed'
322338

323339
ret = False
324-
update_log.info("Updating example '%s'", example['name'])
325-
update_log.debug("User: %s", user)
326-
update_log.debug("Src branch: %s", (src or "None"))
327-
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"))
328344

329345
cwd = os.getcwd()
330346

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

334350
# Clone the example repo
335-
clone_cmd = ['git', 'clone', update_repo]
351+
clone_cmd = "git clone " + str(update_repo)
336352
return_code = run_cmd(clone_cmd)
337353

338354
if not return_code:
@@ -353,30 +369,27 @@ def upgrade_example(github, example, tag, ref, user, src, dst, template):
353369
os.chdir(cwd)
354370
return False
355371

356-
# Setup the default commit message
357-
commit_message = 'Updating mbed-os to ' + tag
358-
359372
# Setup and run the commit command
360-
commit_cmd = ['git', 'commit', '-m', commit_message]
373+
commit_cmd = "git commit -m \"Updating mbed-os to " + tag + "\""
361374
return_code = run_cmd(commit_cmd)
362375
if not return_code:
363376

364377
# Setup and run the push command
365-
push_cmd = ['git', 'push', 'origin']
378+
push_cmd = "git push origin"
366379
return_code = run_cmd(push_cmd)
367380

368381
if not return_code:
369382
# If the user is not ARMmbed then a fork is being used
370383
if user != 'ARMmbed':
371384

372385
upstream_repo = 'ARMmbed/'+ example['name']
373-
update_log.debug("Upstream repository: %s", upstream_repo)
386+
userlog.debug("Upstream repository: %s", upstream_repo)
374387
# Check access to mbed-os repo
375388
try:
376389
repo = github.get_repo(upstream_repo, False)
377390

378391
except:
379-
update_log.error("Upstream repo: %s, does not exist - skipping", upstream_repo)
392+
userlog.error("Upstream repo: %s, does not exist - skipping", upstream_repo)
380393
return False
381394

382395
jinja_loader = FileSystemLoader(template)
@@ -391,15 +404,15 @@ def upgrade_example(github, example, tag, ref, user, src, dst, template):
391404
ret = True
392405
except GithubException as e:
393406
# Default to False
394-
update_log.error("Pull request creation failed with error: %s", e)
407+
userlog.error("Pull request creation failed with error: %s", e)
395408
else:
396409
ret = True
397410
else:
398-
update_log.error("Git push command failed.")
411+
userlog.error("Git push command failed.")
399412
else:
400-
update_log.error("Git commit command failed.")
413+
userlog.error("Git commit command failed.")
401414
else:
402-
update_log.error("Git clone %s failed", update_repo)
415+
userlog.error("Git clone %s failed", update_repo)
403416

404417
os.chdir(cwd)
405418
return ret
@@ -413,7 +426,7 @@ def create_work_directory(path):
413426
414427
"""
415428
if os.path.exists(path):
416-
update_log.info("'%s' directory already exists. Deleting...", path)
429+
userlog.info("'%s' directory already exists. Deleting...", path)
417430
rmtree_readonly(path)
418431

419432
os.makedirs(path)
@@ -424,28 +437,17 @@ def create_work_directory(path):
424437
formatter_class=argparse.RawDescriptionHelpFormatter)
425438
parser.add_argument('-c', '--config_file', help="Path to the configuration file (default is 'examples.json')", default='examples.json')
426439
parser.add_argument('-T', '--github_token', help="GitHub token for secure access")
427-
parser.add_argument('-l', '--log-level',
428-
help="Level for providing logging output",
429-
default='INFO')
430440

431441
exclusive = parser.add_mutually_exclusive_group(required=True)
432442
exclusive.add_argument('-f', '--fork', help="Update a fork", action='store_true')
433443
exclusive.add_argument('-b', '--branch', help="Update a branch", action='store_true')
434444

435445
args = parser.parse_args()
436446

437-
default = getattr(logging, 'INFO')
438-
level = getattr(logging, args.log_level.upper(), default)
439-
440-
# Set logging level
441-
logging.basicConfig(level=level)
442-
443-
update_log = logging.getLogger("Update")
444-
445447
# Load the config file
446448
with open(os.path.join(os.path.dirname(__file__), args.config_file)) as config:
447449
if not config:
448-
update_log.error("Failed to load config file '%s'", args.config_file)
450+
userlog.error("Failed to load config file '%s'", args.config_file)
449451
sys.exit(1)
450452
json_data = json.load(config)
451453

@@ -470,11 +472,11 @@ def create_work_directory(path):
470472
exit(1)
471473

472474
# Get the github sha corresponding to the specified mbed-os tag
473-
cmd = ['git', 'rev-list', '-1', tag]
475+
cmd = "git rev-list -1 " + tag
474476
return_code, ref = run_cmd_with_output(cmd)
475477

476478
if return_code:
477-
update_log.error("Could not obtain SHA for tag: %s", tag)
479+
userlog.error("Could not obtain SHA for tag: %s", tag)
478480
sys.exit(1)
479481

480482
# Loop through the examples
@@ -499,11 +501,11 @@ def create_work_directory(path):
499501
os.chdir('../')
500502

501503
# Finish the script and report the results
502-
update_log.info("Finished updating examples")
504+
userlog.info("Finished updating examples")
503505
if successes:
504506
for success in successes:
505-
update_log.info(" SUCCEEDED: %s", success)
507+
userlog.info(" SUCCEEDED: %s", success)
506508

507509
if failures:
508510
for fail in failures:
509-
update_log.info(" FAILED: %s", fail)
511+
userlog.info(" FAILED: %s", fail)

0 commit comments

Comments
 (0)