From: JF Ding Date: Fri, 19 Aug 2011 07:57:52 +0000 (+0800) Subject: replace most the print with msger module X-Git-Tag: 0.1~191 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=eea9980fa316f7e979dab33cef9bebb79a1f82ea;p=tools%2Fmic.git replace most the print with msger module --- diff --git a/mic/configmgr.py b/mic/configmgr.py index 64e336a..717a755 100644 --- a/mic/configmgr.py +++ b/mic/configmgr.py @@ -171,6 +171,7 @@ class ConfigMgr(object): return self.chroot[key] def dumpAllConfig(self): + # just for debug sys.stdout.write("create options:\n") for key in self.create.keys(): sys.stdout.write("%-8s= %s\n" % (key, self.create[key])) diff --git a/mic/imager/baseimager.py b/mic/imager/baseimager.py index 6281a61..24548f2 100644 --- a/mic/imager/baseimager.py +++ b/mic/imager/baseimager.py @@ -16,10 +16,8 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -import os -import os.path +import os, sys import stat -import sys import tempfile import shutil import logging @@ -35,6 +33,7 @@ from mic.utils.fs_related import * from mic.utils.rpmmisc import * from mic.utils.misc import * from mic.utils import kickstart +from mic import msger class BaseImageCreator(object): """Installs a system to a chroot directory. @@ -140,11 +139,9 @@ class BaseImageCreator(object): vdso_value = vdso_fh.read().strip() vdso_fh.close() if (int)(vdso_value) == 1: - print "\n= WARNING =" - print "vdso is enabled on your host, which might cause problems with arm emulations." - print "You can disable vdso with following command before starting image build:" - print "echo 0 | sudo tee /proc/sys/vm/vdso_enabled" - print "= WARNING =\n" + msger.warning("vdso is enabled on your host, which might cause problems with arm emulations.\n" + + "\tYou can disable vdso with following command before starting image build:\n" + + "\techo 0 | sudo tee /proc/sys/vm/vdso_enabled") return True @@ -849,7 +846,7 @@ class BaseImageCreator(object): pass def __run_post_scripts(self): - print "Running scripts" + msger.info("Running scripts") for s in kickstart.get_post_scripts(self.ks): (fd, path) = tempfile.mkstemp(prefix = "ks-script-", dir = self._instroot + "/tmp") @@ -918,7 +915,7 @@ class BaseImageCreator(object): self.__save_repo_keys(repodata) kickstart.MoblinRepoConfig(self._instroot).apply(ksh.repo, repodata) except: - print "Failed to apply configuration to image" + msger.warning("Failed to apply configuration to image") raise self._create_bootconfig() @@ -932,8 +929,7 @@ class BaseImageCreator(object): """ if launch: - print "Launching shell. Exit to continue." - print "----------------------------------" + msger.info("Launching shell. Exit to continue.") subprocess.call(["/bin/bash"], preexec_fn = self._chroot) def do_genchecksum(self, image_name): @@ -976,12 +972,12 @@ class BaseImageCreator(object): img_location = os.path.join(self._outdir,self._img_name) if self.__img_compression_method == "bz2": bzip2 = find_binary_path('bzip2') - print "Compressing %s with bzip2. Please wait..." % img_location + msger.info("Compressing %s with bzip2. Please wait..." % img_location) rc = subprocess.call([bzip2, "-f", img_location]) if rc: raise CreatorError("Failed to compress image %s with %s." % (img_location, self.__img_compression_method)) for bootimg in glob.glob(os.path.dirname(img_location) + "/*-boot.bin"): - print "Compressing %s with bzip2. Please wait..." % bootimg + msger.info("Compressing %s with bzip2. Please wait..." % bootimg) rc = subprocess.call([bzip2, "-f", bootimg]) if rc: raise CreatorError("Failed to compress image %s with %s." % (bootimg, self.__img_compression_method)) @@ -1020,10 +1016,10 @@ class BaseImageCreator(object): self.package(self.destdir) def print_outimage_info(self): - print "Your new image can be found here:" + msger.info("Your new image can be found here:") self.outimage.sort() for file in self.outimage: - print os.path.abspath(file) + msger.raw(os.path.abspath(file)) def check_depend_tools(self): for tool in self._dep_checks: @@ -1043,11 +1039,11 @@ class BaseImageCreator(object): dst = "%s/%s-%s.tar.%s" % (destdir, self.name, image_format, comp) else: dst = "%s/%s-%s.tar" % (destdir, self.name, image_format) - print "creating %s" % dst + msger.info("creating %s" % dst) tar = tarfile.open(dst, "w:" + comp) for file in self.outimage: - print "adding %s to %s" % (file, dst) + msger.info("adding %s to %s" % (file, dst)) tar.add(file, arcname=os.path.join("%s-%s" % (self.name, image_format), os.path.basename(file))) if os.path.isdir(file): shutil.rmtree(file, ignore_errors = True) diff --git a/mic/imager/liveusb.py b/mic/imager/liveusb.py index b16f969..aee1fb3 100644 --- a/mic/imager/liveusb.py +++ b/mic/imager/liveusb.py @@ -29,6 +29,7 @@ import mic.utils.misc as misc from livecd import LiveCDImageCreator from mic.utils.errors import * from mic.utils.partitionedfs import PartitionedMount +from mic import msger class LiveUSBImageCreator(LiveCDImageCreator): def __init__(self, *args): @@ -149,7 +150,7 @@ class LiveUSBImageCreator(LiveCDImageCreator): text = text.replace("liveimg", "liveimg " + kernelargs) if overlaysizemb > 0: - print "Initializing persistent overlay file" + msger.info("Initializing persistent overlay file") overfile = "overlay" + overlaysuffix if fstype == "vfat": args = [ddcmd, "if=/dev/zero", "of=" + usbmnt + "/LiveOS/" + overfile, "count=%d" % overlaysizemb, "bs=1M"] @@ -162,7 +163,7 @@ class LiveUSBImageCreator(LiveCDImageCreator): text = text.replace(" ro ", " rw ") if swapsizemb > 0: - print "Initializing swap file" + msger.info("Initializing swap file") swapfile = usbmnt + "/LiveOS/" + "swap.img" args = [ddcmd, "if=/dev/zero", "of=" + swapfile, "count=%d" % swapsizemb, "bs=1M"] rc = subprocess.call(args) @@ -174,7 +175,7 @@ class LiveUSBImageCreator(LiveCDImageCreator): raise CreatorError("Can't mkswap on swap file") if homesizemb > 0: - print "Initializing persistent /home" + msger.info("Initializing persistent /home") homefile = usbmnt + "/LiveOS/" + homefile if fstype == "vfat": args = [ddcmd, "if=/dev/zero", "of=" + homefile, "count=%d" % homesizemb, "bs=1M"] @@ -223,7 +224,7 @@ class LiveUSBImageCreator(LiveCDImageCreator): usbloop.cleanup() #Need to do this after image is unmounted and device mapper is closed - print "set MBR" + msger.info("set MBR") mbrfile = "/usr/lib/syslinux/mbr.bin" if not os.path.exists(mbrfile): mbrfile = "/usr/share/syslinux/mbr.bin" diff --git a/mic/kickstart/kickstart.py b/mic/kickstart/kickstart.py index fdc58fc..78a254a 100644 --- a/mic/kickstart/kickstart.py +++ b/mic/kickstart/kickstart.py @@ -26,6 +26,7 @@ import string import errors import misc import fs_related as fs +from mic import msger import pykickstart.commands as kscommands import pykickstart.constants as ksconstants @@ -131,7 +132,7 @@ class KickstartConfig(object): def call(self, args): if not os.path.exists("%s/%s" %(self.instroot, args[0])): - print "%s/%s" %(self.instroot, args[0]) + msger.warning("%s/%s" %(self.instroot, args[0])) raise errors.KickstartError("Unable to run %s!" %(args)) subprocess.call(args, preexec_fn = self.chroot) diff --git a/mic/msger.py b/mic/msger.py index 030d1f0..e1bee0b 100644 --- a/mic/msger.py +++ b/mic/msger.py @@ -26,6 +26,7 @@ INFO_COLOR = 32 # green WARN_COLOR = 33 # yellow ERR_COLOR = 31 # red ASK_COLOR = 34 # blue +NO_COLOR = 0 PREFIX_RE = re.compile('^<(.*?)>\s*(.*)') @@ -34,33 +35,54 @@ INTERACTIVE = True def _color_print(head, color, msg = None, stream = sys.stdout): colored = True - if not stream.isatty(): - colored = False - elif os.getenv('ANSI_COLORS_DISABLED') is not None: + if color == NO_COLOR or \ + not stream.isatty() or \ + os.getenv('ANSI_COLORS_DISABLED') is not None: colored = False + if head.startswith('\r'): + # need not \n at last + newline = False + else: + newline = True + if colored: - head = '\033[%dm%s:\033[0m' %(color, head) + head = '\033[%dm%s:\033[0m ' %(color, head) + if not newline: + # ESC cmd to clear line + head = '\033[2K' + head else: - head += ':' + if head: + head += ': ' if msg: - stream.write('%s %s\n' % (head, msg)) + stream.write('%s%s' % (head, msg)) + if newline: + stream.write('\n') else: stream.write('%s ' % head) + stream.flush() + def _color_perror(head, color, msg): _color_print(head, color, msg, sys.stderr) def _split_msg(head, msg): if msg.startswith('\n'): + # means print \n at first msg = msg.lstrip() head = '\n' + head + elif msg.startswith('\r'): + # means print \r at first + msg = msg.lstrip() + head = '\r' + head + m = PREFIX_RE.match(msg) if m: head += ' <%s>' % m.group(1) msg = m.group(2) + return head, msg def set_mode(interactive): @@ -70,6 +92,10 @@ def set_mode(interactive): else: INTERACTIVE = False +def raw(msg): + head, msg = _split_msg('', msg) + _color_print(head, NO_COLOR, msg) + def info(msg): head, msg = _split_msg('Info', msg) _color_print(head, INFO_COLOR, msg) diff --git a/mic/pluginmgr.py b/mic/pluginmgr.py index 169b1e2..607172f 100644 --- a/mic/pluginmgr.py +++ b/mic/pluginmgr.py @@ -125,6 +125,7 @@ class PluginMgr(object): return self.plugin_sets['hook'] def listAllPlugins(self): + # just for debug for key in self.plugin_sets.keys(): sys.stdout.write("plugin type (%s) :::\n" % key) for item in self.plugin_sets[key]: diff --git a/mic/utils/fs_related.py b/mic/utils/fs_related.py index daa3960..68eea53 100644 --- a/mic/utils/fs_related.py +++ b/mic/utils/fs_related.py @@ -55,24 +55,19 @@ class TextProgress(object): def start(self, filename, url, *args, **kwargs): self.url = url self.termwidth = terminal_width() - if sys.stdout.isatty(): - sys.stdout.write("\r%-*s" % (self.termwidth, " ")) - if self.total is None: - sys.stdout.write("\rRetrieving %s ..." % truncate_url(self.url, self.termwidth - 15)) - else: - sys.stdout.write("\rRetrieving %s [%d/%d] ..." % (truncate_url(self.url, self.termwidth - 25), self.counter, self.total)) + msger.info("\r%-*s" % (self.termwidth, " ")) + if self.total is None: + msger.info("\rRetrieving %s ..." % truncate_url(self.url, self.termwidth - 15)) else: - sys.stdout.write("Retrieving %s ..." % truncate_url(self.url, self.termwidth - 15)) - - sys.stdout.flush() + msger.info("\rRetrieving %s [%d/%d] ..." % (truncate_url(self.url, self.termwidth - 25), self.counter, self.total)) def update(self, *args): pass def end(self, *args): - if self.counter == self.total or not sys.stdout.isatty(): - sys.stdout.write("\n") - sys.stdout.flush() + if self.counter == self.total: + msger.info("\n") + self.counter += 1 def find_binary_path(binary): diff --git a/mic/utils/misc.py b/mic/utils/misc.py index b5e8150..b71c1b2 100644 --- a/mic/utils/misc.py +++ b/mic/utils/misc.py @@ -42,6 +42,8 @@ xmlparse = cElementTree.parse from errors import * from fs_related import * +from mic import msger + def setlocale(): import locale import codecs @@ -479,7 +481,7 @@ def output_siteconf(siteconf): output += "%s=%s\n" % (option, siteconf.get(section, option)) output += "\n\n" - print output + msger.info(output) return output def get_repostrs_from_ks(ks): @@ -657,7 +659,7 @@ def get_metadata_from_repos(repostrs, cachedir): repokey = get_metadata_from_repo(baseurl, proxies, cachedir, reponame, "repodata/repomd.xml.key") except CreatorError: repokey = None - print "Warning: can't get %s/%s" % (baseurl, "repodata/repomd.xml.key") + msger.warning("can't get %s/%s" % (baseurl, "repodata/repomd.xml.key")) my_repo_metadata.append({"name":reponame, "baseurl":baseurl, "repomd":repomd, "primary":primary, "cachedir":cachedir, "proxies":proxies, "patterns":patterns, "comps":comps, "repokey":repokey}) @@ -848,11 +850,12 @@ def get_kickstarts_from_repos(repometadata): return kickstarts def select_ks(ksfiles): - print "Available kickstart files:" + msger.info("Available kickstart files:") i = 0 for ks in ksfiles: i += 1 - print "\t%d. %s (%s)" % (i, ks["description"], os.path.basename(ks["filename"])) + msger.raw("\t%d. %s (%s)" % (i, ks["description"], os.path.basename(ks["filename"]))) + while True: choice = raw_input("Please input your choice and press ENTER. [1..%d] ? " % i) if choice.lower() == "q": @@ -1056,18 +1059,19 @@ def create_release(config, destdir, name, outimages, release): return updated_list def get_local_distro(): - print "Local linux distribution:" + msger.info("Local linux distribution:") for file in glob.glob("/etc/*-release"): fd = open(file, "r") content = fd.read() fd.close() - print content + msger.info(content) if os.path.exists("/etc/issue"): fd = open("/etc/issue", "r") content = fd.read() fd.close() - print content - print "Local Kernel version: " + os.uname()[2] + msger.info(content) + + msger.info("Local Kernel version: " + os.uname()[2]) def check_mic_installation(argv): creator_name = os.path.basename(argv[0]) @@ -1095,7 +1099,7 @@ def SrcpkgsDownload(pkgs, repometadata, instroot, cachedir): src_repometadata = get_source_repometadata(repometadata) if not src_repometadata: - print "No source repo found" + msger.warning("No source repo found") return None src_pkgs = [] @@ -1132,7 +1136,6 @@ def SrcpkgsDownload(pkgs, repometadata, instroot, cachedir): if src_pkg: shutil.copy(src_pkg, destdir) src_pkgs.append(src_pkg) - print '--------------------------------------------------' - print "%d source packages gotten from cache" %cached_count + msger.info("%d source packages gotten from cache" %cached_count) return src_pkgs