1- #!/usr/bin/env python2
1+ #!/usr/bin/env python
22
33# Copyright (c) 2016 ARM Limited, All Rights Reserved
44# SPDX-License-Identifier: Apache-2.0
1818# pylint: disable=too-many-nested-blocks, too-many-public-methods, too-many-instance-attributes, too-many-statements
1919# pylint: disable=invalid-name, missing-docstring, bad-continuation
2020
21+ from __future__ import print_function
22+ from future .builtins .iterators import zip
23+ from past .builtins import basestring
24+
25+ try :
26+ from urllib .parse import urlparse , quote
27+ from urllib .request import urlopen
28+ except ImportError :
29+ from urlparse import urlparse
30+ from urllib2 import urlopen
31+ from urllib import quote
32+
2133import traceback
2234import sys
2335import re
2840import stat
2941import errno
3042import ctypes
31- from itertools import chain , izip , repeat
32- from urlparse import urlparse
33- import urllib
34- import urllib2
35- import zipfile
43+ from itertools import chain , repeat
3644import argparse
3745import tempfile
46+ import zipfile
3847
3948
4049# Application version
@@ -184,7 +193,7 @@ def progress_cursor():
184193progress_spinner = progress_cursor ()
185194
186195def progress ():
187- sys .stdout .write (progress_spinner . next ())
196+ sys .stdout .write (next (progress_spinner ))
188197 sys .stdout .flush ()
189198 sys .stdout .write ('\b ' )
190199
@@ -211,10 +220,10 @@ def popen(command, stdin=None, **kwargs):
211220 try :
212221 proc = subprocess .Popen (command , ** kwargs )
213222 except OSError as e :
214- if e [0 ] == errno .ENOENT :
223+ if e . args [0 ] == errno .ENOENT :
215224 error (
216225 "Could not execute \" %s\" .\n "
217- "Please verify that it's installed and accessible from your current path by executing \" %s\" .\n " % (command [0 ], command [0 ]), e [0 ])
226+ "Please verify that it's installed and accessible from your current path by executing \" %s\" .\n " % (command [0 ], command [0 ]), e . args [0 ])
218227 else :
219228 raise e
220229
@@ -227,10 +236,10 @@ def pquery(command, output_callback=None, stdin=None, **kwargs):
227236 try :
228237 proc = subprocess .Popen (command , bufsize = 0 , stdout = subprocess .PIPE , stderr = subprocess .PIPE , ** kwargs )
229238 except OSError as e :
230- if e [0 ] == errno .ENOENT :
239+ if e . args [0 ] == errno .ENOENT :
231240 error (
232241 "Could not execute \" %s\" .\n "
233- "Please verify that it's installed and accessible from your current path by executing \" %s\" .\n " % (command [0 ], command [0 ]), e [0 ])
242+ "Please verify that it's installed and accessible from your current path by executing \" %s\" .\n " % (command [0 ], command [0 ]), e . args [0 ])
234243 else :
235244 raise e
236245
@@ -251,12 +260,12 @@ def pquery(command, output_callback=None, stdin=None, **kwargs):
251260 stdout , _ = proc .communicate (stdin )
252261
253262 if very_verbose :
254- log (str ( stdout ).strip ()+ "\n " )
263+ log (stdout . decode ( "utf-8" ).strip () + "\n " )
255264
256265 if proc .returncode != 0 :
257266 raise ProcessException (proc .returncode , command [0 ], ' ' .join (command ), getcwd ())
258267
259- return stdout
268+ return stdout . decode ( "utf-8" )
260269
261270def rmtree_readonly (directory ):
262271 if os .path .islink (directory ):
@@ -346,15 +355,15 @@ def clone(url, path=None, depth=None, protocol=None):
346355 except Exception as e :
347356 if os .path .isdir (path ):
348357 rmtree_readonly (path )
349- error (e [1 ], e [0 ])
358+ error (e . args [1 ], e . args [0 ])
350359
351360 def fetch_rev (url , rev ):
352361 rev_file = os .path .join ('.' + Bld .name , '.rev-' + rev + '.zip' )
353362 try :
354363 if not os .path .exists (rev_file ):
355364 action ("Downloading library build \" %s\" (might take a minute)" % rev )
356365 outfd = open (rev_file , 'wb' )
357- inurl = urllib2 . urlopen (url )
366+ inurl = urlopen (url )
358367 outfd .write (inurl .read ())
359368 outfd .close ()
360369 except :
@@ -393,7 +402,7 @@ def checkout(rev, clean=False):
393402 Bld .unpack_rev (rev )
394403 Bld .seturl (url + '/' + rev )
395404 except Exception as e :
396- error (e [1 ], e [0 ])
405+ error (e . args [1 ], e . args [0 ])
397406
398407 def update (rev = None , clean = False , clean_files = False , is_local = False ):
399408 return Bld .checkout (rev , clean )
@@ -513,7 +522,7 @@ def outgoing():
513522 pquery ([hg_cmd , 'outgoing' ])
514523 return 1
515524 except ProcessException as e :
516- if e [0 ] != 1 :
525+ if e . args [0 ] != 1 :
517526 raise e
518527 return 0
519528
@@ -567,8 +576,9 @@ def geturl():
567576
568577 def getrev ():
569578 if os .path .isfile (os .path .join ('.hg' , 'dirstate' )):
579+ from io import open
570580 with open (os .path .join ('.hg' , 'dirstate' ), 'rb' ) as f :
571- return '' .join ('% 02x' % ord ( i ) for i in f .read (6 ))
581+ return "" .join ('{: 02x}' . format ( x ) for x in bytearray ( f .read (6 ) ))
572582 else :
573583 return ""
574584
@@ -1282,7 +1292,7 @@ def write(self):
12821292
12831293 ref = url .rstrip ('/' ) + '/' + (('' if self .is_build else '#' ) + self .rev if self .rev else '' )
12841294 action ("Updating reference \" %s\" -> \" %s\" " % (relpath (cwd_root , self .path ) if cwd_root != self .path else self .name , ref ))
1285- with open (self .lib , 'wb ' ) as f :
1295+ with open (self .lib , 'w ' ) as f :
12861296 f .write (ref + "\n " )
12871297
12881298 def rm_untracked (self ):
@@ -1295,7 +1305,7 @@ def rm_untracked(self):
12951305 def url2cachedir (self , url ):
12961306 up = urlparse (formaturl (url , 'https' ))
12971307 if self .cache and up and up .netloc :
1298- return os .path .join (self .cache , urllib . quote (up .netloc ), urllib . quote (re .sub (r'^/' , '' , up .path )))
1308+ return os .path .join (self .cache , quote (up .netloc ), quote (re .sub (r'^/' , '' , up .path )))
12991309
13001310 def get_cache (self , url , scm ):
13011311 cpath = self .url2cachedir (url )
@@ -1992,7 +2002,7 @@ def import_(url, path=None, ignore=False, depth=None, protocol=None, insecure=Fa
19922002 if ignore :
19932003 warning (err )
19942004 else :
1995- error (err , e [0 ])
2005+ error (err , e . args [0 ])
19962006 else :
19972007 err = "Unable to clone repository (%s)" % url
19982008 if ignore :
@@ -2142,7 +2152,7 @@ def publish(all_refs=None, msg=None, top=True):
21422152 if top :
21432153 action ("Nothing to publish to the remote repository (the source tree is unmodified)" )
21442154 except ProcessException as e :
2145- if e [0 ] != 1 :
2155+ if e . args [0 ] != 1 :
21462156 raise e
21472157
21482158
@@ -2209,7 +2219,7 @@ def update(rev=None, clean=False, clean_files=False, clean_deps=False, ignore=Fa
22092219 if ignore :
22102220 warning (err )
22112221 else :
2212- error (err , e [0 ])
2222+ error (err , e . args [0 ])
22132223
22142224 repo .rm_untracked ()
22152225 if top and cwd_type == 'library' :
@@ -2341,7 +2351,7 @@ def sync(recursive=True, keep_refs=False, top=True):
23412351def list_ (detailed = False , prefix = '' , p_path = None , ignore = False ):
23422352 repo = Repo .fromrepo ()
23432353
2344- print "%s (%s)" % (prefix + (relpath (p_path , repo .path ) if p_path else repo .name ), ((repo .url + ('#' + str (repo .rev )[:12 ] if repo .rev else '' ) if detailed else repo .revtype (repo .rev , fmt = 6 )) or 'no revision' ))
2354+ print ( "%s (%s)" % (prefix + (relpath (p_path , repo .path ) if p_path else repo .name ), ((repo .url + ('#' + str (repo .rev )[:12 ] if repo .rev else '' ) if detailed else repo .revtype (repo .rev , fmt = 6 )) or 'no revision' ) ))
23452355
23462356 for i , lib in enumerate (sorted (repo .libs , key = lambda l : l .path )):
23472357 nprefix = (prefix [:- 3 ] + ('| ' if prefix [- 3 ] == '|' else ' ' )) if prefix else ''
@@ -2374,16 +2384,16 @@ def releases_(detailed=False, unstable=False, recursive=False, prefix='', p_path
23742384 rels .append (tag [1 ] + " %s%s" % ('#' + tag [0 ] if detailed else "" , " <- current" if tag [1 ] in revtags else "" ))
23752385
23762386 # Print header
2377- print "%s (%s)" % (prefix + (relpath (p_path , repo .path ) if p_path else repo .name ), ((repo .url + ('#' + str (repo .rev )[:12 ] if repo .rev else '' ) if detailed else repo .revtype (repo .rev , fmt = 6 )) or 'no revision' ))
2387+ print ( "%s (%s)" % (prefix + (relpath (p_path , repo .path ) if p_path else repo .name ), ((repo .url + ('#' + str (repo .rev )[:12 ] if repo .rev else '' ) if detailed else repo .revtype (repo .rev , fmt = 6 )) or 'no revision' ) ))
23782388
23792389 # Print list of tags
23802390 rprefix = (prefix [:- 3 ] + ('| ' if prefix [- 3 ] == '|' else ' ' )) if recursive and prefix else ''
23812391 rprefix += '| ' if recursive and len (repo .libs ) > 1 else ' '
23822392 if len (rels ):
23832393 for rel in rels :
2384- print rprefix + '* ' + rel
2394+ print ( rprefix + '* ' + rel )
23852395 else :
2386- print rprefix + 'No release tags detected'
2396+ print ( rprefix + 'No release tags detected' )
23872397
23882398 if recursive :
23892399 for i , lib in enumerate (sorted (repo .libs , key = lambda l : l .path )):
@@ -2466,8 +2476,8 @@ def compile_(toolchain=None, target=None, profile=False, compile_library=False,
24662476 # Compile configuration
24672477 popen ([python_cmd , os .path .join (tools_dir , 'get_config.py' )]
24682478 + ['-t' , tchain , '-m' , target ]
2469- + list (chain .from_iterable (izip (repeat ('--profile' ), profile or [])))
2470- + list (chain .from_iterable (izip (repeat ('--source' ), source )))
2479+ + list (chain .from_iterable (zip (repeat ('--profile' ), profile or [])))
2480+ + list (chain .from_iterable (zip (repeat ('--source' ), source )))
24712481 + (['-v' ] if verbose else [])
24722482 + (list (chain .from_iterable (izip (repeat ('--prefix' ), config_prefix ))) if config_prefix else []),
24732483 env = env )
@@ -2484,10 +2494,10 @@ def compile_(toolchain=None, target=None, profile=False, compile_library=False,
24842494 build_path = os .path .join (os .path .relpath (program .path , orig_path ), program .build_dir , 'libraries' , os .path .basename (orig_path ), target , tchain )
24852495
24862496 popen ([python_cmd , '-u' , os .path .join (tools_dir , 'build.py' )]
2487- + list (chain .from_iterable (izip (repeat ('-D' ), macros )))
2497+ + list (chain .from_iterable (zip (repeat ('-D' ), macros )))
24882498 + ['-t' , tchain , '-m' , target ]
2489- + list (chain .from_iterable (izip (repeat ('--profile' ), profile or [])))
2490- + list (chain .from_iterable (izip (repeat ('--source' ), source )))
2499+ + list (chain .from_iterable (zip (repeat ('--profile' ), profile or [])))
2500+ + list (chain .from_iterable (zip (repeat ('--source' ), source )))
24912501 + ['--build' , build_path ]
24922502 + (['-c' ] if clean else [])
24932503 + (['--artifact-name' , artifact_name ] if artifact_name else [])
@@ -2500,10 +2510,10 @@ def compile_(toolchain=None, target=None, profile=False, compile_library=False,
25002510 build_path = os .path .join (os .path .relpath (program .path , orig_path ), program .build_dir , target , tchain )
25012511
25022512 popen ([python_cmd , '-u' , os .path .join (tools_dir , 'make.py' )]
2503- + list (chain .from_iterable (izip (repeat ('-D' ), macros )))
2513+ + list (chain .from_iterable (zip (repeat ('-D' ), macros )))
25042514 + ['-t' , tchain , '-m' , target ]
2505- + list (chain .from_iterable (izip (repeat ('--profile' ), profile or [])))
2506- + list (chain .from_iterable (izip (repeat ('--source' ), source )))
2515+ + list (chain .from_iterable (zip (repeat ('--profile' ), profile or [])))
2516+ + list (chain .from_iterable (zip (repeat ('--source' ), source )))
25072517 + ['--build' , build_path ]
25082518 + (['-c' ] if clean else [])
25092519 + (['--artifact-name' , artifact_name ] if artifact_name else [])
@@ -2590,9 +2600,9 @@ def test_(toolchain=None, target=None, compile_list=False, run_list=False, compi
25902600
25912601 if compile_list :
25922602 popen ([python_cmd , '-u' , os .path .join (tools_dir , 'test.py' ), '--list' ]
2593- + list (chain .from_iterable (izip (repeat ('--profile' ), profile or [])))
2603+ + list (chain .from_iterable (list ( izip (repeat ('--profile' ), profile or []) )))
25942604 + ['-t' , tchain , '-m' , target ]
2595- + list (chain .from_iterable (izip (repeat ('--source' ), source )))
2605+ + list (chain .from_iterable (zip (repeat ('--source' ), source )))
25962606 + (['-n' , tests_by_name ] if tests_by_name else [])
25972607 + (['-v' ] if verbose else [])
25982608 + (['--app-config' , app_config ] if app_config else [])
@@ -2606,11 +2616,11 @@ def test_(toolchain=None, target=None, compile_list=False, run_list=False, compi
26062616 program .ignore_build_dir ()
26072617
26082618 popen ([python_cmd , '-u' , os .path .join (tools_dir , 'test.py' )]
2609- + list (chain .from_iterable (izip (repeat ('-D' ), macros )))
2610- + list (chain .from_iterable (izip (repeat ('--profile' ), profile or [])))
2619+ + list (chain .from_iterable (zip (repeat ('-D' ), macros )))
2620+ + list (chain .from_iterable (zip (repeat ('--profile' ), profile or [])))
26112621 + ['-t' , tchain , '-m' , target ]
26122622 + (['-c' ] if clean else [])
2613- + list (chain .from_iterable (izip (repeat ('--source' ), source )))
2623+ + list (chain .from_iterable (zip (repeat ('--source' ), source )))
26142624 + ['--build' , build_path ]
26152625 + ['--test-spec' , test_spec ]
26162626 + (['-n' , tests_by_name ] if tests_by_name else [])
@@ -2947,7 +2957,7 @@ def get_size_(path):
29472957 action ("Repository cache is %s." % str (cfg ['cache' ]).upper ())
29482958 action ("Cache location \" %s\" " % cfg ['cache_dir' ])
29492959 else :
2950- print cmd
2960+ print ( cmd )
29512961 error ("Invalid cache command. Please see \" mbed cache --help\" for valid commands." )
29522962
29532963
@@ -2963,11 +2973,6 @@ def main():
29632973 # Help messages adapt based on current dir
29642974 cwd_root = getcwd ()
29652975
2966- if sys .version_info [0 ] != 2 or sys .version_info [1 ] < 7 :
2967- error (
2968- "mbed CLI is compatible with Python version >= 2.7 and < 3.0\n "
2969- "Please refer to the online guide available at https://github.com/ARMmbed/mbed-cli" )
2970-
29712976 # Parse/run command
29722977 if len (sys .argv ) <= 1 :
29732978 help_ ()
@@ -2988,14 +2993,14 @@ def main():
29882993 except ProcessException as e :
29892994 error (
29902995 "\" %s\" returned error code %d.\n "
2991- "Command \" %s\" in \" %s\" " % (e [1 ], e [0 ], e [2 ], e [3 ]), e [0 ])
2996+ "Command \" %s\" in \" %s\" " % (e . args [1 ], e . args [0 ], e . args [2 ], e . args [3 ]), e . args [0 ])
29922997 except OSError as e :
2993- if e [0 ] == errno .ENOENT :
2998+ if e . args [0 ] == errno .ENOENT :
29942999 error (
29953000 "Could not detect one of the command-line tools.\n "
2996- "You could retry the last command with \" -v\" flag for verbose output\n " , e [0 ])
3001+ "You could retry the last command with \" -v\" flag for verbose output\n " , e . args [0 ])
29973002 else :
2998- error ('OS Error: %s' % e [1 ], e [0 ])
3003+ error ('OS Error: %s' % e . args [1 ], e . args [0 ])
29993004 except KeyboardInterrupt :
30003005 info ('User aborted!' , - 1 )
30013006 sys .exit (255 )
0 commit comments