* [PATCH 01/17] wic: use ext4 in canned .wks files
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 02/17] wic: get rid of scripts/lib/image Ed Bartosh
` (15 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Latest kernel doesn't have ext3 compiled in. Wic images produced
from canned .wks can't boot because of that. Switching to ext4
fixes this issue.
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
scripts/lib/image/canned-wks/directdisk-gpt.wks | 4 ++--
scripts/lib/image/canned-wks/directdisk-multi-rootfs.wks | 6 +++---
scripts/lib/image/canned-wks/directdisk.wks | 4 ++--
scripts/lib/image/canned-wks/mkefidisk.wks | 4 ++--
scripts/lib/image/canned-wks/mkgummidisk.wks | 4 ++--
scripts/lib/image/canned-wks/mkhybridiso.wks | 2 +-
6 files changed, 12 insertions(+), 12 deletions(-)
diff --git a/scripts/lib/image/canned-wks/directdisk-gpt.wks b/scripts/lib/image/canned-wks/directdisk-gpt.wks
index 2355259..ea01cf3 100644
--- a/scripts/lib/image/canned-wks/directdisk-gpt.wks
+++ b/scripts/lib/image/canned-wks/directdisk-gpt.wks
@@ -4,7 +4,7 @@
part /boot --source bootimg-pcbios --ondisk sda --label boot --active --align 1024
-part / --source rootfs --ondisk sda --fstype=ext3 --label platform --align 1024 --use-uuid
+part / --source rootfs --ondisk sda --fstype=ext4 --label platform --align 1024 --use-uuid
-bootloader --ptable gpt --timeout=0 --append="rootwait rootfstype=ext3 video=vesafb vga=0x318 console=tty0"
+bootloader --ptable gpt --timeout=0 --append="rootwait rootfstype=ext4 video=vesafb vga=0x318 console=tty0"
diff --git a/scripts/lib/image/canned-wks/directdisk-multi-rootfs.wks b/scripts/lib/image/canned-wks/directdisk-multi-rootfs.wks
index f3c6df5..8a81f8f 100644
--- a/scripts/lib/image/canned-wks/directdisk-multi-rootfs.wks
+++ b/scripts/lib/image/canned-wks/directdisk-multi-rootfs.wks
@@ -16,8 +16,8 @@
# - or any combinations of -r and --rootfs command line options
part /boot --source bootimg-pcbios --ondisk sda --label boot --active --align 1024
-part / --source rootfs --rootfs-dir=rootfs1 --ondisk sda --fstype=ext3 --label platform --align 1024
-part /rescue --source rootfs --rootfs-dir=rootfs2 --ondisk sda --fstype=ext3 --label secondary --align 1024
+part / --source rootfs --rootfs-dir=rootfs1 --ondisk sda --fstype=ext4 --label platform --align 1024
+part /rescue --source rootfs --rootfs-dir=rootfs2 --ondisk sda --fstype=ext4 --label secondary --align 1024
-bootloader --timeout=0 --append="rootwait rootfstype=ext3 video=vesafb vga=0x318 console=tty0"
+bootloader --timeout=0 --append="rootwait rootfstype=ext4 video=vesafb vga=0x318 console=tty0"
diff --git a/scripts/lib/image/canned-wks/directdisk.wks b/scripts/lib/image/canned-wks/directdisk.wks
index 62dcab1..af4c9ea 100644
--- a/scripts/lib/image/canned-wks/directdisk.wks
+++ b/scripts/lib/image/canned-wks/directdisk.wks
@@ -4,7 +4,7 @@
part /boot --source bootimg-pcbios --ondisk sda --label boot --active --align 1024
-part / --source rootfs --ondisk sda --fstype=ext3 --label platform --align 1024
+part / --source rootfs --ondisk sda --fstype=ext4 --label platform --align 1024
-bootloader --timeout=0 --append="rootwait rootfstype=ext3 video=vesafb vga=0x318 console=tty0"
+bootloader --timeout=0 --append="rootwait rootfstype=ext4 video=vesafb vga=0x318 console=tty0"
diff --git a/scripts/lib/image/canned-wks/mkefidisk.wks b/scripts/lib/image/canned-wks/mkefidisk.wks
index 58d42e6..696e94e 100644
--- a/scripts/lib/image/canned-wks/mkefidisk.wks
+++ b/scripts/lib/image/canned-wks/mkefidisk.wks
@@ -4,8 +4,8 @@
part /boot --source bootimg-efi --sourceparams="loader=grub-efi" --ondisk sda --label msdos --active --align 1024
-part / --source rootfs --ondisk sda --fstype=ext3 --label platform --align 1024
+part / --source rootfs --ondisk sda --fstype=ext4 --label platform --align 1024
part swap --ondisk sda --size 44 --label swap1 --fstype=swap
-bootloader --timeout=10 --append="rootwait rootfstype=ext3 console=ttyPCH0,115200 console=tty0 vmalloc=256MB snd-hda-intel.enable_msi=0"
+bootloader --timeout=10 --append="rootwait rootfstype=ext4 console=ttyPCH0,115200 console=tty0 vmalloc=256MB snd-hda-intel.enable_msi=0"
diff --git a/scripts/lib/image/canned-wks/mkgummidisk.wks b/scripts/lib/image/canned-wks/mkgummidisk.wks
index f81cbdf..66a22f6 100644
--- a/scripts/lib/image/canned-wks/mkgummidisk.wks
+++ b/scripts/lib/image/canned-wks/mkgummidisk.wks
@@ -4,8 +4,8 @@
part /boot --source bootimg-efi --sourceparams="loader=gummiboot" --ondisk sda --label msdos --active --align 1024
-part / --source rootfs --ondisk sda --fstype=ext3 --label platform --align 1024
+part / --source rootfs --ondisk sda --fstype=ext4 --label platform --align 1024
part swap --ondisk sda --size 44 --label swap1 --fstype=swap
-bootloader --timeout=10 --append="rootwait rootfstype=ext3 console=ttyPCH0,115200 console=tty0 vmalloc=256MB snd-hda-intel.enable_msi=0"
+bootloader --timeout=10 --append="rootwait rootfstype=ext4 console=ttyPCH0,115200 console=tty0 vmalloc=256MB snd-hda-intel.enable_msi=0"
diff --git a/scripts/lib/image/canned-wks/mkhybridiso.wks b/scripts/lib/image/canned-wks/mkhybridiso.wks
index b443c15..9d34e9b 100644
--- a/scripts/lib/image/canned-wks/mkhybridiso.wks
+++ b/scripts/lib/image/canned-wks/mkhybridiso.wks
@@ -2,6 +2,6 @@
# long-description: Creates an EFI and legacy bootable hybrid ISO image
# which can be used on optical media as well as USB media.
-part /boot --source isoimage-isohybrid --sourceparams="loader=grub-efi,image_name=HYBRID_ISO_IMG" --ondisk cd --label HYBRIDISO --fstype=ext3
+part /boot --source isoimage-isohybrid --sourceparams="loader=grub-efi,image_name=HYBRID_ISO_IMG" --ondisk cd --label HYBRIDISO --fstype=ext4
bootloader --timeout=15 --append=""
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 02/17] wic: get rid of scripts/lib/image
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
2015-09-02 10:58 ` [PATCH 01/17] wic: use ext4 in canned .wks files Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 03/17] oe-selftest: wic: configure a build Ed Bartosh
` (14 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Moved content of scripts/lib/image/ to scripts/lib/wic as
one directory with the same name as a tool is self-explanatory
and less confusing than two.
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
scripts/lib/image/__init__.py | 22 ----------------------
.../{image => wic}/canned-wks/directdisk-gpt.wks | 0
.../canned-wks/directdisk-multi-rootfs.wks | 0
.../lib/{image => wic}/canned-wks/directdisk.wks | 0
.../lib/{image => wic}/canned-wks/mkefidisk.wks | 0
.../lib/{image => wic}/canned-wks/mkgummidisk.wks | 0
.../lib/{image => wic}/canned-wks/mkhybridiso.wks | 0
.../canned-wks/qemux86-directdisk.wks | 0
.../{image => wic}/canned-wks/sdimage-bootpart.wks | 0
scripts/lib/{image => wic}/config/wic.conf | 0
scripts/lib/{image => wic}/engine.py | 2 +-
scripts/lib/{image => wic}/help.py | 4 ++--
scripts/wic | 4 ++--
13 files changed, 5 insertions(+), 27 deletions(-)
delete mode 100644 scripts/lib/image/__init__.py
rename scripts/lib/{image => wic}/canned-wks/directdisk-gpt.wks (100%)
rename scripts/lib/{image => wic}/canned-wks/directdisk-multi-rootfs.wks (100%)
rename scripts/lib/{image => wic}/canned-wks/directdisk.wks (100%)
rename scripts/lib/{image => wic}/canned-wks/mkefidisk.wks (100%)
rename scripts/lib/{image => wic}/canned-wks/mkgummidisk.wks (100%)
rename scripts/lib/{image => wic}/canned-wks/mkhybridiso.wks (100%)
rename scripts/lib/{image => wic}/canned-wks/qemux86-directdisk.wks (100%)
rename scripts/lib/{image => wic}/canned-wks/sdimage-bootpart.wks (100%)
rename scripts/lib/{image => wic}/config/wic.conf (100%)
rename scripts/lib/{image => wic}/engine.py (99%)
rename scripts/lib/{image => wic}/help.py (99%)
diff --git a/scripts/lib/image/__init__.py b/scripts/lib/image/__init__.py
deleted file mode 100644
index 1ff814e..0000000
--- a/scripts/lib/image/__init__.py
+++ /dev/null
@@ -1,22 +0,0 @@
-#
-# OpenEmbedded Image tools library
-#
-# Copyright (c) 2013, Intel Corporation.
-# All rights reserved.
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License along
-# with this program; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# AUTHORS
-# Tom Zanussi <tom.zanussi (at] linux.intel.com>
-#
diff --git a/scripts/lib/image/canned-wks/directdisk-gpt.wks b/scripts/lib/wic/canned-wks/directdisk-gpt.wks
similarity index 100%
rename from scripts/lib/image/canned-wks/directdisk-gpt.wks
rename to scripts/lib/wic/canned-wks/directdisk-gpt.wks
diff --git a/scripts/lib/image/canned-wks/directdisk-multi-rootfs.wks b/scripts/lib/wic/canned-wks/directdisk-multi-rootfs.wks
similarity index 100%
rename from scripts/lib/image/canned-wks/directdisk-multi-rootfs.wks
rename to scripts/lib/wic/canned-wks/directdisk-multi-rootfs.wks
diff --git a/scripts/lib/image/canned-wks/directdisk.wks b/scripts/lib/wic/canned-wks/directdisk.wks
similarity index 100%
rename from scripts/lib/image/canned-wks/directdisk.wks
rename to scripts/lib/wic/canned-wks/directdisk.wks
diff --git a/scripts/lib/image/canned-wks/mkefidisk.wks b/scripts/lib/wic/canned-wks/mkefidisk.wks
similarity index 100%
rename from scripts/lib/image/canned-wks/mkefidisk.wks
rename to scripts/lib/wic/canned-wks/mkefidisk.wks
diff --git a/scripts/lib/image/canned-wks/mkgummidisk.wks b/scripts/lib/wic/canned-wks/mkgummidisk.wks
similarity index 100%
rename from scripts/lib/image/canned-wks/mkgummidisk.wks
rename to scripts/lib/wic/canned-wks/mkgummidisk.wks
diff --git a/scripts/lib/image/canned-wks/mkhybridiso.wks b/scripts/lib/wic/canned-wks/mkhybridiso.wks
similarity index 100%
rename from scripts/lib/image/canned-wks/mkhybridiso.wks
rename to scripts/lib/wic/canned-wks/mkhybridiso.wks
diff --git a/scripts/lib/image/canned-wks/qemux86-directdisk.wks b/scripts/lib/wic/canned-wks/qemux86-directdisk.wks
similarity index 100%
rename from scripts/lib/image/canned-wks/qemux86-directdisk.wks
rename to scripts/lib/wic/canned-wks/qemux86-directdisk.wks
diff --git a/scripts/lib/image/canned-wks/sdimage-bootpart.wks b/scripts/lib/wic/canned-wks/sdimage-bootpart.wks
similarity index 100%
rename from scripts/lib/image/canned-wks/sdimage-bootpart.wks
rename to scripts/lib/wic/canned-wks/sdimage-bootpart.wks
diff --git a/scripts/lib/image/config/wic.conf b/scripts/lib/wic/config/wic.conf
similarity index 100%
rename from scripts/lib/image/config/wic.conf
rename to scripts/lib/wic/config/wic.conf
diff --git a/scripts/lib/image/engine.py b/scripts/lib/wic/engine.py
similarity index 99%
rename from scripts/lib/image/engine.py
rename to scripts/lib/wic/engine.py
index 73e8f8b..a034841 100644
--- a/scripts/lib/image/engine.py
+++ b/scripts/lib/wic/engine.py
@@ -52,7 +52,7 @@ def verify_build_env():
return True
-CANNED_IMAGE_DIR = "lib/image/canned-wks" # relative to scripts
+CANNED_IMAGE_DIR = "lib/wic/canned-wks" # relative to scripts
SCRIPTS_CANNED_IMAGE_DIR = "scripts/" + CANNED_IMAGE_DIR
def build_canned_image_list(dl):
diff --git a/scripts/lib/image/help.py b/scripts/lib/wic/help.py
similarity index 99%
rename from scripts/lib/image/help.py
rename to scripts/lib/wic/help.py
index 717d847..cd2176d 100644
--- a/scripts/lib/image/help.py
+++ b/scripts/lib/wic/help.py
@@ -288,7 +288,7 @@ DESCRIPTION
The first form enumerates all the available 'canned' images.
These are actually just the set of .wks files that have been moved
- into the /scripts/lib/image/canned-wks directory).
+ into the /scripts/lib/wic/canned-wks directory).
The second form lists the detailed help information for a specific
'canned' image.
@@ -591,7 +591,7 @@ DESCRIPTION
NATIVE_SYSROOT: ...
The image(s) were created using OE kickstart file:
- .../scripts/lib/image/canned-wks/directdisk.wks
+ .../scripts/lib/wic/canned-wks/directdisk.wks
The output shows the name and location of the image created, and
so that you know exactly what was used to generate the image, each
diff --git a/scripts/wic b/scripts/wic
index 25b0d67..94028e2 100755
--- a/scripts/wic
+++ b/scripts/wic
@@ -54,8 +54,8 @@ else:
from wic.utils.oe.misc import get_bitbake_var, BB_VARS
from wic.utils.errors import WicError
-from image import engine
-from image import help as hlp
+from wic import engine
+from wic import help as hlp
def rootfs_dir_to_args(krootfs_dir):
"""
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 03/17] oe-selftest: wic: configure a build
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
2015-09-02 10:58 ` [PATCH 01/17] wic: use ext4 in canned .wks files Ed Bartosh
2015-09-02 10:58 ` [PATCH 02/17] wic: get rid of scripts/lib/image Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 04/17] wic: add test cases for 3 images Ed Bartosh
` (13 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Added MACHINE_FEATURES and IMAGE_FSTYPES variables to the build config
to ensure that bootimg and efi artifacts are built. This is needed to
build canned wic images that are using those artifacts.
Introduced class variable Wic.image_is_ready to avoid building image
more than once. It would be better to build image in setUpClass, which
is called only once, but add_config method can't be called in class method,
so we have to use this trick with class variable in setUp method.
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
meta/lib/oeqa/selftest/wic.py | 13 +++++++++++--
1 file changed, 11 insertions(+), 2 deletions(-)
diff --git a/meta/lib/oeqa/selftest/wic.py b/meta/lib/oeqa/selftest/wic.py
index 6bc4b60..817a820 100644
--- a/meta/lib/oeqa/selftest/wic.py
+++ b/meta/lib/oeqa/selftest/wic.py
@@ -39,12 +39,21 @@ class Wic(oeSelfTest):
@classmethod
def setUpClass(cls):
- """Build wic runtime dependencies and images used in the tests."""
+ """Build wic runtime dependencies."""
bitbake('syslinux syslinux-native parted-native gptfdisk-native '
- 'dosfstools-native mtools-native core-image-minimal')
+ 'dosfstools-native mtools-native')
+ Wic.image_is_ready = False
def setUp(self):
"""This code is executed before each test method."""
+ if not Wic.image_is_ready:
+ # build core-image-minimal with required features
+ features = 'IMAGE_FSTYPES += " hddimg"\nMACHINE_FEATURES_append = " efi"\n'
+ self.append_config(features)
+ bitbake('core-image-minimal')
+ # set this class variable to avoid buiding image many times
+ Wic.image_is_ready = True
+
rmtree(self.resultdir, ignore_errors=True)
def test01_help(self):
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 04/17] wic: add test cases for 3 images
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (2 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 03/17] oe-selftest: wic: configure a build Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 05/17] wic: fix typo Ed Bartosh
` (12 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Added test cases to build qemux86_directdisk, mkgummidisk and
mkefdisk images.
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
meta/lib/oeqa/selftest/wic.py | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
diff --git a/meta/lib/oeqa/selftest/wic.py b/meta/lib/oeqa/selftest/wic.py
index 817a820..3dc54a4 100644
--- a/meta/lib/oeqa/selftest/wic.py
+++ b/meta/lib/oeqa/selftest/wic.py
@@ -213,3 +213,24 @@ class Wic(oeSelfTest):
path = prefix + suffix
self.assertTrue(os.path.islink(path))
self.assertTrue(os.path.isfile(os.path.realpath(path)))
+
+ def test21_qemux86_directdisk(self):
+ """Test creation of qemux-86-directdisk image"""
+ image = "qemux86-directdisk"
+ self.assertEqual(0, runCmd("wic create %s -e core-image-minimal" \
+ % image).status)
+ self.assertEqual(1, len(glob(self.resultdir + "%s-*direct" % image)))
+
+ def test22_mkgummidisk(self):
+ """Test creation of mkgummidisk image"""
+ image = "mkgummidisk"
+ self.assertEqual(0, runCmd("wic create %s -e core-image-minimal" \
+ % image).status)
+ self.assertEqual(1, len(glob(self.resultdir + "%s-*direct" % image)))
+
+ def test23_mkefidisk(self):
+ """Test creation of mkefidisk image"""
+ image = "mkefidisk"
+ self.assertEqual(0, runCmd("wic create %s -e core-image-minimal" \
+ % image).status)
+ self.assertEqual(1, len(glob(self.resultdir + "%s-*direct" % image)))
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 05/17] wic: fix typo
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (3 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 04/17] wic: add test cases for 3 images Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 06/17] wic: remove micpartition.py Ed Bartosh
` (11 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Fixed typo in tool name: mkswqp -> mkswap.
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
scripts/lib/wic/utils/oe/misc.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/scripts/lib/wic/utils/oe/misc.py b/scripts/lib/wic/utils/oe/misc.py
index 0a8f3f1..7370d93 100644
--- a/scripts/lib/wic/utils/oe/misc.py
+++ b/scripts/lib/wic/utils/oe/misc.py
@@ -41,7 +41,7 @@ NATIVE_RECIPES = {"mcopy": "mtools",
"mkfs.ext4": "e2fsprogs",
"mkfs.vfat": "dosfstools",
"mksquashfs": "squashfs-tools",
- "mkswqp": "util-linux",
+ "mkswap": "util-linux",
"parted": "parted",
"sgdisk": "gptfdisk",
"syslinux": "syslinux"
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 06/17] wic: remove micpartition.py
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (4 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 05/17] wic: fix typo Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 07/17] wic: remove micboot.py Ed Bartosh
` (10 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Moved functionality of Mic_Partition and Mic_PartData classes
from micpartition.py to Wic_Partition and Wic_PartData classes
of partition.py module.
Reduced level of inheritance.
Removed confusing mic legacy names.
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
.../lib/wic/kickstart/custom_commands/__init__.py | 4 --
.../wic/kickstart/custom_commands/micpartition.py | 57 ----------------------
.../lib/wic/kickstart/custom_commands/partition.py | 41 +++++++++++-----
3 files changed, 30 insertions(+), 72 deletions(-)
delete mode 100644 scripts/lib/wic/kickstart/custom_commands/micpartition.py
diff --git a/scripts/lib/wic/kickstart/custom_commands/__init__.py b/scripts/lib/wic/kickstart/custom_commands/__init__.py
index b4e613d..e4ae406 100644
--- a/scripts/lib/wic/kickstart/custom_commands/__init__.py
+++ b/scripts/lib/wic/kickstart/custom_commands/__init__.py
@@ -1,11 +1,7 @@
-from micpartition import Mic_Partition
-from micpartition import Mic_PartData
from partition import Wic_Partition
from partition import Wic_PartData
__all__ = (
- "Mic_Partition",
- "Mic_PartData",
"Wic_Partition",
"Wic_PartData",
)
diff --git a/scripts/lib/wic/kickstart/custom_commands/micpartition.py b/scripts/lib/wic/kickstart/custom_commands/micpartition.py
deleted file mode 100644
index d6be008..0000000
--- a/scripts/lib/wic/kickstart/custom_commands/micpartition.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/env python -tt
-#
-# Marko Saukko <marko.saukko@cybercom.com>
-#
-# Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
-#
-# This copyrighted material is made available to anyone wishing to use, modify,
-# copy, or redistribute it subject to the terms and conditions of the GNU
-# General Public License v.2. This program is distributed in the hope that it
-# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
-# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License along with
-# this program; if not, write to the Free Software Foundation, Inc., 51
-# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-
-from pykickstart.commands.partition import *
-
-class Mic_PartData(FC4_PartData):
- removedKeywords = FC4_PartData.removedKeywords
- removedAttrs = FC4_PartData.removedAttrs
-
- def __init__(self, *args, **kwargs):
- FC4_PartData.__init__(self, *args, **kwargs)
- self.deleteRemovedAttrs()
- self.align = kwargs.get("align", None)
- self.extopts = kwargs.get("extopts", None)
- self.part_type = kwargs.get("part_type", None)
-
- def _getArgsAsStr(self):
- retval = FC4_PartData._getArgsAsStr(self)
-
- if self.align:
- retval += " --align=%d" % self.align
- if self.extopts:
- retval += " --extoptions=%s" % self.extopts
- if self.part_type:
- retval += " --part-type=%s" % self.part_type
-
- return retval
-
-class Mic_Partition(FC4_Partition):
- removedKeywords = FC4_Partition.removedKeywords
- removedAttrs = FC4_Partition.removedAttrs
-
- def _getParser(self):
- op = FC4_Partition._getParser(self)
- # The alignment value is given in kBytes. e.g., value 8 means that
- # the partition is aligned to start from 8096 byte boundary.
- op.add_option("--align", type="int", action="store", dest="align",
- default=None)
- op.add_option("--extoptions", type="string", action="store", dest="extopts",
- default=None)
- op.add_option("--part-type", type="string", action="store", dest="part_type",
- default=None)
- return op
diff --git a/scripts/lib/wic/kickstart/custom_commands/partition.py b/scripts/lib/wic/kickstart/custom_commands/partition.py
index 045b290..dd6edd2 100644
--- a/scripts/lib/wic/kickstart/custom_commands/partition.py
+++ b/scripts/lib/wic/kickstart/custom_commands/partition.py
@@ -28,7 +28,7 @@ import os
import tempfile
import uuid
-from pykickstart.commands.partition import *
+from pykickstart.commands.partition import FC4_PartData, FC4_Partition
from wic.utils.oe.misc import *
from wic.kickstart.custom_commands import *
from wic.plugin import pluginmgr
@@ -39,13 +39,16 @@ partition_methods = {
"do_configure_partition":None,
}
-class Wic_PartData(Mic_PartData):
- removedKeywords = Mic_PartData.removedKeywords
- removedAttrs = Mic_PartData.removedAttrs
+class Wic_PartData(FC4_PartData):
+ removedKeywords = FC4_PartData.removedKeywords
+ removedAttrs = FC4_PartData.removedAttrs
def __init__(self, *args, **kwargs):
- Mic_PartData.__init__(self, *args, **kwargs)
+ FC4_PartData.__init__(self, *args, **kwargs)
self.deleteRemovedAttrs()
+ self.align = kwargs.get("align", None)
+ self.extopts = kwargs.get("extopts", None)
+ self.part_type = kwargs.get("part_type", None)
self.source = kwargs.get("source", None)
self.sourceparams = kwargs.get("sourceparams", None)
self.rootfs = kwargs.get("rootfs-dir", None)
@@ -59,8 +62,14 @@ class Wic_PartData(Mic_PartData):
self.size = 0
def _getArgsAsStr(self):
- retval = Mic_PartData._getArgsAsStr(self)
-
+ retval = FC4_PartData._getArgsAsStr(self)
+
+ if self.align:
+ retval += " --align=%d" % self.align
+ if self.extopts:
+ retval += " --extoptions=%s" % self.extopts
+ if self.part_type:
+ retval += " --part-type=%s" % self.part_type
if self.source:
retval += " --source=%s" % self.source
if self.sourceparams:
@@ -468,9 +477,10 @@ class Wic_PartData(Mic_PartData):
mkswap_cmd = "mkswap %s -U %s %s" % (label_str, str(uuid.uuid1()), fs)
exec_native_cmd(mkswap_cmd, native_sysroot)
-class Wic_Partition(Mic_Partition):
- removedKeywords = Mic_Partition.removedKeywords
- removedAttrs = Mic_Partition.removedAttrs
+
+class Wic_Partition(FC4_Partition):
+ removedKeywords = FC4_Partition.removedKeywords
+ removedAttrs = FC4_Partition.removedAttrs
def _getParser(self):
def overhead_cb(option, opt_str, value, parser):
@@ -479,7 +489,16 @@ class Wic_Partition(Mic_Partition):
(option, value))
setattr(parser.values, option.dest, value)
- op = Mic_Partition._getParser(self)
+ op = FC4_Partition._getParser(self)
+
+ # The alignment value is given in kBytes. e.g., value 8 means that
+ # the partition is aligned to start from 8096 byte boundary.
+ op.add_option("--align", type="int", action="store", dest="align",
+ default=None)
+ op.add_option("--extoptions", type="string", action="store", dest="extopts",
+ default=None)
+ op.add_option("--part-type", type="string", action="store", dest="part_type",
+ default=None)
# use specified source file to fill the partition
# and calculate partition size
op.add_option("--source", type="string", action="store",
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 07/17] wic: remove micboot.py
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (5 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 06/17] wic: remove micpartition.py Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 08/17] wic: fix errors in partition.py module Ed Bartosh
` (9 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Moved functionaly of micboot.py Mic_Bootloader class to
Wic_Bootloader class of wicboot.py module.
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
.../lib/wic/kickstart/custom_commands/micboot.py | 50 ----------------------
.../lib/wic/kickstart/custom_commands/wicboot.py | 23 ++++++----
2 files changed, 15 insertions(+), 58 deletions(-)
delete mode 100644 scripts/lib/wic/kickstart/custom_commands/micboot.py
diff --git a/scripts/lib/wic/kickstart/custom_commands/micboot.py b/scripts/lib/wic/kickstart/custom_commands/micboot.py
deleted file mode 100644
index 1fa282b..0000000
--- a/scripts/lib/wic/kickstart/custom_commands/micboot.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/env python -tt
-#
-# Copyright (c) 2008, 2009, 2010 Intel, Inc.
-#
-# Anas Nashif
-#
-# This program is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License as published by the Free
-# Software Foundation; version 2 of the License
-#
-# This program is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
-# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
-# for more details.
-#
-# You should have received a copy of the GNU General Public License along
-# with this program; if not, write to the Free Software Foundation, Inc., 59
-# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
-from pykickstart.base import *
-from pykickstart.errors import *
-from pykickstart.options import *
-from pykickstart.commands.bootloader import *
-
-class Mic_Bootloader(F8_Bootloader):
- def __init__(self, writePriority=10, appendLine="", driveorder=None,
- forceLBA=False, location="", md5pass="", password="",
- upgrade=False, menus=""):
- F8_Bootloader.__init__(self, writePriority, appendLine, driveorder,
- forceLBA, location, md5pass, password, upgrade)
-
- self.menus = ""
- self.ptable = "msdos"
-
- def _getArgsAsStr(self):
- ret = F8_Bootloader._getArgsAsStr(self)
-
- if self.menus == "":
- ret += " --menus=%s" %(self.menus,)
- if self.ptable:
- ret += " --ptable=\"%s\"" %(self.ptable,)
- return ret
-
- def _getParser(self):
- op = F8_Bootloader._getParser(self)
- op.add_option("--menus", dest="menus")
- op.add_option("--ptable", dest="ptable", choices=("msdos", "gpt"),
- default="msdos")
- return op
-
diff --git a/scripts/lib/wic/kickstart/custom_commands/wicboot.py b/scripts/lib/wic/kickstart/custom_commands/wicboot.py
index f191416..eefd574 100644
--- a/scripts/lib/wic/kickstart/custom_commands/wicboot.py
+++ b/scripts/lib/wic/kickstart/custom_commands/wicboot.py
@@ -27,29 +27,36 @@
from pykickstart.base import *
from pykickstart.errors import *
from pykickstart.options import *
-from pykickstart.commands.bootloader import *
+from pykickstart.commands.bootloader import F8_Bootloader
-from wic.kickstart.custom_commands.micboot import *
-
-class Wic_Bootloader(Mic_Bootloader):
+class Wic_Bootloader(F8_Bootloader):
def __init__(self, writePriority=10, appendLine="", driveorder=None,
forceLBA=False, location="", md5pass="", password="",
upgrade=False, menus=""):
- Mic_Bootloader.__init__(self, writePriority, appendLine, driveorder,
- forceLBA, location, md5pass, password, upgrade)
+ F8_Bootloader.__init__(self, writePriority, appendLine, driveorder,
+ forceLBA, location, md5pass, password, upgrade)
+ self.menus = ""
+ self.ptable = "msdos"
self.source = ""
def _getArgsAsStr(self):
- retval = Mic_Bootloader._getArgsAsStr(self)
+ retval = F8_Bootloader._getArgsAsStr(self)
+ if self.menus == "":
+ retval += " --menus=%s" %(self.menus,)
+ if self.ptable:
+ retval += " --ptable=\"%s\"" %(self.ptable,)
if self.source:
retval += " --source=%s" % self.source
return retval
def _getParser(self):
- op = Mic_Bootloader._getParser(self)
+ op = F8_Bootloader._getParser(self)
+ op.add_option("--menus", dest="menus")
+ op.add_option("--ptable", dest="ptable", choices=("msdos", "gpt"),
+ default="msdos")
# use specified source plugin to implement bootloader-specific methods
op.add_option("--source", type="string", action="store",
dest="source", default=None)
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 08/17] wic: fix errors in partition.py module
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (6 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 07/17] wic: remove micboot.py Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 09/17] wic: get rid of wildcard imports Ed Bartosh
` (8 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Fixed the followring errors found by pylint in partition.py:
E: 42, 0: class already defined line 33 (function-redefined)
E:429,63: Undefined variable 'fs' (undefined-variable)
E:432,37: Undefined variable 'fs' (undefined-variable)
E:481, 0: class already defined line 33 (function-redefined)
E:488,22: Undefined variable 'OptionValueError' (undefined-variable)
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
scripts/lib/wic/kickstart/custom_commands/partition.py | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/scripts/lib/wic/kickstart/custom_commands/partition.py b/scripts/lib/wic/kickstart/custom_commands/partition.py
index dd6edd2..6defc99 100644
--- a/scripts/lib/wic/kickstart/custom_commands/partition.py
+++ b/scripts/lib/wic/kickstart/custom_commands/partition.py
@@ -27,10 +27,10 @@
import os
import tempfile
import uuid
+from optparse import OptionValueError
from pykickstart.commands.partition import FC4_PartData, FC4_Partition
from wic.utils.oe.misc import *
-from wic.kickstart.custom_commands import *
from wic.plugin import pluginmgr
partition_methods = {
@@ -426,10 +426,10 @@ class Wic_PartData(FC4_PartData):
if self.label:
label_str = "-n %s" % self.label
- dosfs_cmd = "mkdosfs %s -S 512 -C %s %d" % (label_str, fs, blocks)
+ dosfs_cmd = "mkdosfs %s -S 512 -C %s %d" % (label_str, rootfs, blocks)
exec_native_cmd(dosfs_cmd, native_sysroot)
- chmod_cmd = "chmod 644 %s" % fs
+ chmod_cmd = "chmod 644 %s" % rootfs
exec_cmd(chmod_cmd)
def prepare_empty_partition_squashfs(self, cr_workdir, oe_builddir,
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 09/17] wic: get rid of wildcard imports
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (7 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 08/17] wic: fix errors in partition.py module Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 10/17] wic: fix pylint warning multiple-statements Ed Bartosh
` (7 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Used explicit imports in partitions.py and wicboot.py
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
scripts/lib/wic/kickstart/custom_commands/partition.py | 3 ++-
scripts/lib/wic/kickstart/custom_commands/wicboot.py | 4 ----
2 files changed, 2 insertions(+), 5 deletions(-)
diff --git a/scripts/lib/wic/kickstart/custom_commands/partition.py b/scripts/lib/wic/kickstart/custom_commands/partition.py
index 6defc99..bac2067 100644
--- a/scripts/lib/wic/kickstart/custom_commands/partition.py
+++ b/scripts/lib/wic/kickstart/custom_commands/partition.py
@@ -30,7 +30,8 @@ import uuid
from optparse import OptionValueError
from pykickstart.commands.partition import FC4_PartData, FC4_Partition
-from wic.utils.oe.misc import *
+from wic.utils.oe.misc import msger, parse_sourceparams
+from wic.utils.oe.misc import exec_cmd, exec_native_cmd
from wic.plugin import pluginmgr
partition_methods = {
diff --git a/scripts/lib/wic/kickstart/custom_commands/wicboot.py b/scripts/lib/wic/kickstart/custom_commands/wicboot.py
index eefd574..0230df2 100644
--- a/scripts/lib/wic/kickstart/custom_commands/wicboot.py
+++ b/scripts/lib/wic/kickstart/custom_commands/wicboot.py
@@ -23,10 +23,6 @@
# AUTHORS
# Tom Zanussi <tom.zanussi (at] linux.intel.com>
#
-
-from pykickstart.base import *
-from pykickstart.errors import *
-from pykickstart.options import *
from pykickstart.commands.bootloader import F8_Bootloader
class Wic_Bootloader(F8_Bootloader):
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 10/17] wic: fix pylint warning multiple-statements
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (8 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 09/17] wic: get rid of wildcard imports Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 11/17] wic: use optparse instead of cmdln Ed Bartosh
` (6 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Fixed pylint warning:
More than one statement on a single line (multiple-statements)
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
scripts/lib/wic/plugin.py | 3 ++-
scripts/lib/wic/utils/cmdln.py | 57 +++++++++++++++++++++++++++--------------
scripts/lib/wic/utils/runner.py | 3 ++-
3 files changed, 42 insertions(+), 21 deletions(-)
diff --git a/scripts/lib/wic/plugin.py b/scripts/lib/wic/plugin.py
index d714b6d..e901f80 100644
--- a/scripts/lib/wic/plugin.py
+++ b/scripts/lib/wic/plugin.py
@@ -82,7 +82,8 @@ class PluginMgr(object):
def _load_all(self):
for (pdir, loaded) in self.plugin_dirs.iteritems():
- if loaded: continue
+ if loaded:
+ continue
sys.path.insert(0, pdir)
for mod in [x[:-3] for x in os.listdir(pdir) if x.endswith(".py")]:
diff --git a/scripts/lib/wic/utils/cmdln.py b/scripts/lib/wic/utils/cmdln.py
index d8f1c05..47654b9 100644
--- a/scripts/lib/wic/utils/cmdln.py
+++ b/scripts/lib/wic/utils/cmdln.py
@@ -443,7 +443,8 @@ class RawCmdln(cmd.Cmd):
elif line[0] == '?':
line = 'help ' + line[1:]
i, n = 0, len(line)
- while i < n and line[i] in self.identchars: i = i+1
+ while i < n and line[i] in self.identchars:
+ i = i+1
cmd, arg = line[:i], line[i:].strip()
return cmd, arg, line
@@ -499,8 +500,10 @@ class RawCmdln(cmd.Cmd):
doc = self.__class__.__doc__ # try class docstring
if doc is None:
# Try to provide some reasonable useful default help.
- if self.cmdlooping: prefix = ""
- else: prefix = self.name+' '
+ if self.cmdlooping:
+ prefix = ""
+ else:
+ prefix = self.name+' '
doc = """Usage:
%sCOMMAND [ARGS...]
%shelp [COMMAND]
@@ -629,7 +632,8 @@ class RawCmdln(cmd.Cmd):
token2canonical = self._get_canonical_map()
aliases = {}
for token, cmdname in token2canonical.items():
- if token == cmdname: continue
+ if token == cmdname:
+ continue
aliases.setdefault(cmdname, []).append(token)
# Get the list of (non-hidden) commands and their
@@ -697,7 +701,8 @@ class RawCmdln(cmd.Cmd):
helpnames = {}
token2cmdname = self._get_canonical_map()
for attrname, attr in self._gen_names_and_attrs():
- if not attrname.startswith("help_"): continue
+ if not attrname.startswith("help_"):
+ continue
helpname = attrname[5:]
if helpname not in token2cmdname:
helpnames[helpname] = attr
@@ -757,8 +762,10 @@ class RawCmdln(cmd.Cmd):
# Adjust argcount for possible *args and **kwargs arguments.
argcount = co_argcount
- if co_flags & CO_FLAGS_ARGS: argcount += 1
- if co_flags & CO_FLAGS_KWARGS: argcount += 1
+ if co_flags & CO_FLAGS_ARGS:
+ argcount += 1
+ if co_flags & CO_FLAGS_KWARGS:
+ argcount += 1
# Determine the usage string.
usage = "%s %s" % (self.name, cmdname)
@@ -838,8 +845,10 @@ class RawCmdln(cmd.Cmd):
token2canonical = {}
cmd2funcname = {} # use a dict to strip duplicates
for attr in self.get_names():
- if attr.startswith("do_"): cmdname = attr[3:]
- elif attr.startswith("_do_"): cmdname = attr[4:]
+ if attr.startswith("do_"):
+ cmdname = attr[3:]
+ elif attr.startswith("_do_"):
+ cmdname = attr[4:]
else:
continue
cmd2funcname[cmdname] = attr
@@ -1280,12 +1289,14 @@ def line2argv(line):
i = -1
while 1:
i += 1
- if i >= len(line): break
+ if i >= len(line):
+ break
ch = line[i]
if ch == "\\" and i+1 < len(line):
# escaped char always added to arg, regardless of state
- if arg is None: arg = ""
+ if arg is None:
+ arg = ""
if (sys.platform == "win32"
or state in ("double-quoted", "single-quoted")
) and line[i+1] not in tuple('"\''):
@@ -1306,17 +1317,20 @@ def line2argv(line):
arg += ch
elif state == "default":
if ch == '"':
- if arg is None: arg = ""
+ if arg is None:
+ arg = ""
state = "double-quoted"
elif ch == "'":
- if arg is None: arg = ""
+ if arg is None:
+ arg = ""
state = "single-quoted"
elif ch in string.whitespace:
if arg is not None:
argv.append(arg)
arg = None
else:
- if arg is None: arg = ""
+ if arg is None:
+ arg = ""
arg += ch
if arg is not None:
argv.append(arg)
@@ -1380,7 +1394,8 @@ def _dedentlines(lines, tabsize=8, skip_first_line=False):
indents = []
margin = None
for i, line in enumerate(lines):
- if i == 0 and skip_first_line: continue
+ if i == 0 and skip_first_line:
+ continue
indent = 0
for ch in line:
if ch == ' ':
@@ -1393,16 +1408,19 @@ def _dedentlines(lines, tabsize=8, skip_first_line=False):
break
else:
continue # skip all-whitespace lines
- if DEBUG: print "dedent: indent=%d: %r" % (indent, line)
+ if DEBUG:
+ print "dedent: indent=%d: %r" % (indent, line)
if margin is None:
margin = indent
else:
margin = min(margin, indent)
- if DEBUG: print "dedent: margin=%r" % margin
+ if DEBUG:
+ print "dedent: margin=%r" % margin
if margin is not None and margin > 0:
for i, line in enumerate(lines):
- if i == 0 and skip_first_line: continue
+ if i == 0 and skip_first_line:
+ continue
removed = 0
for j, ch in enumerate(line):
if ch == ' ':
@@ -1410,7 +1428,8 @@ def _dedentlines(lines, tabsize=8, skip_first_line=False):
elif ch == '\t':
removed += tabsize - (removed % tabsize)
elif ch in '\r\n':
- if DEBUG: print "dedent: %r: EOL -> strip up to EOL" % line
+ if DEBUG:
+ print "dedent: %r: EOL -> strip up to EOL" % line
lines[i] = lines[i][j:]
break
else:
diff --git a/scripts/lib/wic/utils/runner.py b/scripts/lib/wic/utils/runner.py
index 8d48f68..f6a1d08 100644
--- a/scripts/lib/wic/utils/runner.py
+++ b/scripts/lib/wic/utils/runner.py
@@ -90,7 +90,8 @@ def show(cmdln_or_args):
cmd = cmdln_or_args
msg = 'running command: "%s"' % cmd
- if out: out = out.strip()
+ if out:
+ out = out.strip()
if out:
msg += ', with output::'
msg += '\n +----------------'
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 11/17] wic: use optparse instead of cmdln
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (9 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 10/17] wic: fix pylint warning multiple-statements Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 12/17] wic: fix pylint warning no-member Ed Bartosh
` (5 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
cmdln.py https://pypi.python.org/pypi/cmdln was used in
creator.py to parse image plugin options and arguments.
There is no need in such a sofisticated API to do this
simple task. Standard option parser optparse.OptionParser
can do it just fine.
Modified Creator class to work with option parser.
Removed cmdln.py from the wic codebase.
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
scripts/lib/wic/creator.py | 115 +-
scripts/lib/wic/plugins/imager/direct_plugin.py | 2 +-
scripts/lib/wic/utils/cmdln.py | 1604 -----------------------
3 files changed, 27 insertions(+), 1694 deletions(-)
delete mode 100644 scripts/lib/wic/utils/cmdln.py
diff --git a/scripts/lib/wic/creator.py b/scripts/lib/wic/creator.py
index 760848f..5231297 100644
--- a/scripts/lib/wic/creator.py
+++ b/scripts/lib/wic/creator.py
@@ -16,15 +16,15 @@
# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
import os, sys
-from optparse import SUPPRESS_HELP
+from optparse import OptionParser, SUPPRESS_HELP
from wic import msger
-from wic.utils import cmdln, errors
+from wic.utils import errors
from wic.conf import configmgr
from wic.plugin import pluginmgr
-class Creator(cmdln.Cmdln):
+class Creator(object):
"""${name}: create an image
Usage:
@@ -37,8 +37,7 @@ class Creator(cmdln.Cmdln):
name = 'wic create(cr)'
def __init__(self, *args, **kwargs):
- cmdln.Cmdln.__init__(self, *args, **kwargs)
- self._subcmds = []
+ self._subcmds = {}
# get cmds from pluginmgr
# mix-in do_subcmd interface
@@ -48,11 +47,10 @@ class Creator(cmdln.Cmdln):
continue
func = getattr(klass, 'do_create')
- setattr(self.__class__, "do_"+subcmd, func)
- self._subcmds.append(subcmd)
+ self._subcmds[subcmd] = func
def get_optparser(self):
- optparser = cmdln.CmdlnOptionParser(self)
+ optparser = OptionParser()
optparser.add_option('-d', '--debug', action='store_true',
dest='debug',
help=SUPPRESS_HELP)
@@ -73,69 +71,31 @@ class Creator(cmdln.Cmdln):
' feature, use it if you have more than 4G memory')
return optparser
- def preoptparse(self, argv):
- optparser = self.get_optparser()
-
- largs = []
- rargs = []
- while argv:
- arg = argv.pop(0)
-
- if arg in ('-h', '--help'):
- rargs.append(arg)
-
- elif optparser.has_option(arg):
- largs.append(arg)
-
- if optparser.get_option(arg).takes_value():
- try:
- largs.append(argv.pop(0))
- except IndexError:
- raise errors.Usage("option %s requires arguments" % arg)
-
- else:
- if arg.startswith("--"):
- if "=" in arg:
- opt = arg.split("=")[0]
- else:
- opt = None
- elif arg.startswith("-") and len(arg) > 2:
- opt = arg[0:2]
- else:
- opt = None
-
- if opt and optparser.has_option(opt):
- largs.append(arg)
- else:
- rargs.append(arg)
-
- return largs + rargs
-
- def postoptparse(self):
+ def postoptparse(self, options):
abspath = lambda pth: os.path.abspath(os.path.expanduser(pth))
- if self.options.verbose:
+ if options.verbose:
msger.set_loglevel('verbose')
- if self.options.debug:
+ if options.debug:
msger.set_loglevel('debug')
- if self.options.logfile:
- logfile_abs_path = abspath(self.options.logfile)
+ if options.logfile:
+ logfile_abs_path = abspath(options.logfile)
if os.path.isdir(logfile_abs_path):
raise errors.Usage("logfile's path %s should be file"
- % self.options.logfile)
+ % options.logfile)
if not os.path.exists(os.path.dirname(logfile_abs_path)):
os.makedirs(os.path.dirname(logfile_abs_path))
msger.set_interactive(False)
msger.set_logfile(logfile_abs_path)
- configmgr.create['logfile'] = self.options.logfile
+ configmgr.create['logfile'] = options.logfile
- if self.options.config:
+ if options.config:
configmgr.reset()
- configmgr._siteconf = self.options.config
+ configmgr._siteconf = options.config
- if self.options.outdir is not None:
- configmgr.create['outdir'] = abspath(self.options.outdir)
+ if options.outdir is not None:
+ configmgr.create['outdir'] = abspath(options.outdir)
cdir = 'outdir'
if os.path.exists(configmgr.create[cdir]) \
@@ -143,8 +103,8 @@ class Creator(cmdln.Cmdln):
msger.error('Invalid directory specified: %s' \
% configmgr.create[cdir])
- if self.options.enabletmpfs:
- configmgr.create['enabletmpfs'] = self.options.enabletmpfs
+ if options.enabletmpfs:
+ configmgr.create['enabletmpfs'] = options.enabletmpfs
def main(self, argv=None):
if argv is None:
@@ -152,36 +112,13 @@ class Creator(cmdln.Cmdln):
else:
argv = argv[:] # don't modify caller's list
- self.optparser = self.get_optparser()
- if self.optparser:
- try:
- argv = self.preoptparse(argv)
- self.options, args = self.optparser.parse_args(argv)
-
- except cmdln.CmdlnUserError, ex:
- msg = "%s: %s\nTry '%s help' for info.\n"\
- % (self.name, ex, self.name)
- msger.error(msg)
-
- except cmdln.StopOptionProcessing, ex:
- return 0
- else:
- # optparser=None means no process for opts
- self.options, args = None, argv[1:]
-
- if not args:
- return self.emptyline()
-
- self.postoptparse()
-
- return self.cmd(args)
+ pname = argv[0]
+ if pname not in self._subcmds:
+ msger.error('Unknown plugin: %s' % pname)
- def precmd(self, argv): # check help before cmd
-
- if '-h' in argv or '?' in argv or '--help' in argv or 'help' in argv:
- return argv
+ optparser = self.get_optparser()
+ options, args = optparser.parse_args(argv)
- if len(argv) == 1:
- return ['help', argv[0]]
+ self.postoptparse(options)
- return argv
+ return self._subcmds[pname](options, *args[1:])
diff --git a/scripts/lib/wic/plugins/imager/direct_plugin.py b/scripts/lib/wic/plugins/imager/direct_plugin.py
index eb17e8d..e9672fe 100644
--- a/scripts/lib/wic/plugins/imager/direct_plugin.py
+++ b/scripts/lib/wic/plugins/imager/direct_plugin.py
@@ -56,7 +56,7 @@ class DirectPlugin(ImagerPlugin):
return krootfs_dir
@classmethod
- def do_create(cls, subcmd, opts, *args):
+ def do_create(cls, opts, *args):
"""
Create direct image, called from creator as 'direct' cmd
"""
diff --git a/scripts/lib/wic/utils/cmdln.py b/scripts/lib/wic/utils/cmdln.py
deleted file mode 100644
index 47654b9..0000000
--- a/scripts/lib/wic/utils/cmdln.py
+++ /dev/null
@@ -1,1604 +0,0 @@
-#!/usr/bin/env python
-# Copyright (c) 2002-2007 ActiveState Software Inc.
-# License: MIT (see LICENSE.txt for license details)
-# Author: Trent Mick
-# Home: http://trentm.com/projects/cmdln/
-
-"""An improvement on Python's standard cmd.py module.
-
-As with cmd.py, this module provides "a simple framework for writing
-line-oriented command intepreters." This module provides a 'RawCmdln'
-class that fixes some design flaws in cmd.Cmd, making it more scalable
-and nicer to use for good 'cvs'- or 'svn'-style command line interfaces
-or simple shells. And it provides a 'Cmdln' class that add
-optparse-based option processing. Basically you use it like this:
-
- import cmdln
-
- class MySVN(cmdln.Cmdln):
- name = "svn"
-
- @cmdln.alias('stat', 'st')
- @cmdln.option('-v', '--verbose', action='store_true'
- help='print verbose information')
- def do_status(self, subcmd, opts, *paths):
- print "handle 'svn status' command"
-
- #...
-
- if __name__ == "__main__":
- shell = MySVN()
- retval = shell.main()
- sys.exit(retval)
-
-See the README.txt or <http://trentm.com/projects/cmdln/> for more
-details.
-"""
-
-__version_info__ = (1, 1, 2)
-__version__ = '.'.join(map(str, __version_info__))
-
-import os
-import sys
-import re
-import cmd
-import optparse
-import sys
-
-
-
-
-#---- globals
-
-LOOP_ALWAYS, LOOP_NEVER, LOOP_IF_EMPTY = range(3)
-
-# An unspecified optional argument when None is a meaningful value.
-_NOT_SPECIFIED = ("Not", "Specified")
-
-# Pattern to match a TypeError message from a call that
-# failed because of incorrect number of arguments (see
-# Python/getargs.c).
-_INCORRECT_NUM_ARGS_RE = re.compile(
- r"(takes [\w ]+ )(\d+)( arguments? \()(\d+)( given\))")
-
-
-
-#---- exceptions
-
-class CmdlnError(Exception):
- """A cmdln.py usage error."""
- def __init__(self, msg):
- self.msg = msg
- def __str__(self):
- return self.msg
-
-class CmdlnUserError(Exception):
- """An error by a user of a cmdln-based tool/shell."""
- pass
-
-
-
-#---- public methods and classes
-
-def alias(*aliases):
- """Decorator to add aliases for Cmdln.do_* command handlers.
-
- Example:
- class MyShell(cmdln.Cmdln):
- @cmdln.alias("!", "sh")
- def do_shell(self, argv):
- #...implement 'shell' command
- """
- def decorate(f):
- if not hasattr(f, "aliases"):
- f.aliases = []
- f.aliases += aliases
- return f
- return decorate
-
-
-class RawCmdln(cmd.Cmd):
- """An improved (on cmd.Cmd) framework for building multi-subcommand
- scripts (think "svn" & "cvs") and simple shells (think "pdb" and
- "gdb").
-
- A simple example:
-
- import cmdln
-
- class MySVN(cmdln.RawCmdln):
- name = "svn"
-
- @cmdln.aliases('stat', 'st')
- def do_status(self, argv):
- print "handle 'svn status' command"
-
- if __name__ == "__main__":
- shell = MySVN()
- retval = shell.main()
- sys.exit(retval)
-
- See <http://trentm.com/projects/cmdln> for more information.
- """
- name = None # if unset, defaults basename(sys.argv[0])
- prompt = None # if unset, defaults to self.name+"> "
- version = None # if set, default top-level options include --version
-
- # Default messages for some 'help' command error cases.
- # They are interpolated with one arg: the command.
- nohelp = "no help on '%s'"
- unknowncmd = "unknown command: '%s'"
-
- helpindent = '' # string with which to indent help output
-
- def __init__(self, completekey='tab',
- stdin=None, stdout=None, stderr=None):
- """Cmdln(completekey='tab', stdin=None, stdout=None, stderr=None)
-
- The optional argument 'completekey' is the readline name of a
- completion key; it defaults to the Tab key. If completekey is
- not None and the readline module is available, command completion
- is done automatically.
-
- The optional arguments 'stdin', 'stdout' and 'stderr' specify
- alternate input, output and error output file objects; if not
- specified, sys.* are used.
-
- If 'stdout' but not 'stderr' is specified, stdout is used for
- error output. This is to provide least surprise for users used
- to only the 'stdin' and 'stdout' options with cmd.Cmd.
- """
- import sys
- if self.name is None:
- self.name = os.path.basename(sys.argv[0])
- if self.prompt is None:
- self.prompt = self.name+"> "
- self._name_str = self._str(self.name)
- self._prompt_str = self._str(self.prompt)
- if stdin is not None:
- self.stdin = stdin
- else:
- self.stdin = sys.stdin
- if stdout is not None:
- self.stdout = stdout
- else:
- self.stdout = sys.stdout
- if stderr is not None:
- self.stderr = stderr
- elif stdout is not None:
- self.stderr = stdout
- else:
- self.stderr = sys.stderr
- self.cmdqueue = []
- self.completekey = completekey
- self.cmdlooping = False
-
- def get_optparser(self):
- """Hook for subclasses to set the option parser for the
- top-level command/shell.
-
- This option parser is used retrieved and used by `.main()' to
- handle top-level options.
-
- The default implements a single '-h|--help' option. Sub-classes
- can return None to have no options at the top-level. Typically
- an instance of CmdlnOptionParser should be returned.
- """
- version = (self.version is not None
- and "%s %s" % (self._name_str, self.version)
- or None)
- return CmdlnOptionParser(self, version=version)
-
- def postoptparse(self):
- """Hook method executed just after `.main()' parses top-level
- options.
-
- When called `self.options' holds the results of the option parse.
- """
- pass
-
- def main(self, argv=None, loop=LOOP_NEVER):
- """A possible mainline handler for a script, like so:
-
- import cmdln
- class MyCmd(cmdln.Cmdln):
- name = "mycmd"
- ...
-
- if __name__ == "__main__":
- MyCmd().main()
-
- By default this will use sys.argv to issue a single command to
- 'MyCmd', then exit. The 'loop' argument can be use to control
- interactive shell behaviour.
-
- Arguments:
- "argv" (optional, default sys.argv) is the command to run.
- It must be a sequence, where the first element is the
- command name and subsequent elements the args for that
- command.
- "loop" (optional, default LOOP_NEVER) is a constant
- indicating if a command loop should be started (i.e. an
- interactive shell). Valid values (constants on this module):
- LOOP_ALWAYS start loop and run "argv", if any
- LOOP_NEVER run "argv" (or .emptyline()) and exit
- LOOP_IF_EMPTY run "argv", if given, and exit;
- otherwise, start loop
- """
- if argv is None:
- import sys
- argv = sys.argv
- else:
- argv = argv[:] # don't modify caller's list
-
- self.optparser = self.get_optparser()
- if self.optparser: # i.e. optparser=None means don't process for opts
- try:
- self.options, args = self.optparser.parse_args(argv[1:])
- except CmdlnUserError, ex:
- msg = "%s: %s\nTry '%s help' for info.\n"\
- % (self.name, ex, self.name)
- self.stderr.write(self._str(msg))
- self.stderr.flush()
- return 1
- except StopOptionProcessing, ex:
- return 0
- else:
- self.options, args = None, argv[1:]
- self.postoptparse()
-
- if loop == LOOP_ALWAYS:
- if args:
- self.cmdqueue.append(args)
- return self.cmdloop()
- elif loop == LOOP_NEVER:
- if args:
- return self.cmd(args)
- else:
- return self.emptyline()
- elif loop == LOOP_IF_EMPTY:
- if args:
- return self.cmd(args)
- else:
- return self.cmdloop()
-
- def cmd(self, argv):
- """Run one command and exit.
-
- "argv" is the arglist for the command to run. argv[0] is the
- command to run. If argv is an empty list then the
- 'emptyline' handler is run.
-
- Returns the return value from the command handler.
- """
- assert isinstance(argv, (list, tuple)), \
- "'argv' is not a sequence: %r" % argv
- retval = None
- try:
- argv = self.precmd(argv)
- retval = self.onecmd(argv)
- self.postcmd(argv)
- except:
- if not self.cmdexc(argv):
- raise
- retval = 1
- return retval
-
- def _str(self, s):
- """Safely convert the given str/unicode to a string for printing."""
- try:
- return str(s)
- except UnicodeError:
- #XXX What is the proper encoding to use here? 'utf-8' seems
- # to work better than "getdefaultencoding" (usually
- # 'ascii'), on OS X at least.
- #import sys
- #return s.encode(sys.getdefaultencoding(), "replace")
- return s.encode("utf-8", "replace")
-
- def cmdloop(self, intro=None):
- """Repeatedly issue a prompt, accept input, parse into an argv, and
- dispatch (via .precmd(), .onecmd() and .postcmd()), passing them
- the argv. In other words, start a shell.
-
- "intro" (optional) is a introductory message to print when
- starting the command loop. This overrides the class
- "intro" attribute, if any.
- """
- self.cmdlooping = True
- self.preloop()
- if self.use_rawinput and self.completekey:
- try:
- import readline
- self.old_completer = readline.get_completer()
- readline.set_completer(self.complete)
- readline.parse_and_bind(self.completekey+": complete")
- except ImportError:
- pass
- try:
- if intro is None:
- intro = self.intro
- if intro:
- intro_str = self._str(intro)
- self.stdout.write(intro_str+'\n')
- self.stop = False
- retval = None
- while not self.stop:
- if self.cmdqueue:
- argv = self.cmdqueue.pop(0)
- assert isinstance(argv, (list, tuple)), \
- "item on 'cmdqueue' is not a sequence: %r" % argv
- else:
- if self.use_rawinput:
- try:
- line = raw_input(self._prompt_str)
- except EOFError:
- line = 'EOF'
- else:
- self.stdout.write(self._prompt_str)
- self.stdout.flush()
- line = self.stdin.readline()
- if not len(line):
- line = 'EOF'
- else:
- line = line[:-1] # chop '\n'
- argv = line2argv(line)
- try:
- argv = self.precmd(argv)
- retval = self.onecmd(argv)
- self.postcmd(argv)
- except:
- if not self.cmdexc(argv):
- raise
- retval = 1
- self.lastretval = retval
- self.postloop()
- finally:
- if self.use_rawinput and self.completekey:
- try:
- import readline
- readline.set_completer(self.old_completer)
- except ImportError:
- pass
- self.cmdlooping = False
- return retval
-
- def precmd(self, argv):
- """Hook method executed just before the command argv is
- interpreted, but after the input prompt is generated and issued.
-
- "argv" is the cmd to run.
-
- Returns an argv to run (i.e. this method can modify the command
- to run).
- """
- return argv
-
- def postcmd(self, argv):
- """Hook method executed just after a command dispatch is finished.
-
- "argv" is the command that was run.
- """
- pass
-
- def cmdexc(self, argv):
- """Called if an exception is raised in any of precmd(), onecmd(),
- or postcmd(). If True is returned, the exception is deemed to have
- been dealt with. Otherwise, the exception is re-raised.
-
- The default implementation handles CmdlnUserError's, which
- typically correspond to user error in calling commands (as
- opposed to programmer error in the design of the script using
- cmdln.py).
- """
- import sys
- type, exc, traceback = sys.exc_info()
- if isinstance(exc, CmdlnUserError):
- msg = "%s %s: %s\nTry '%s help %s' for info.\n"\
- % (self.name, argv[0], exc, self.name, argv[0])
- self.stderr.write(self._str(msg))
- self.stderr.flush()
- return True
-
- def onecmd(self, argv):
- if not argv:
- return self.emptyline()
- self.lastcmd = argv
- cmdname = self._get_canonical_cmd_name(argv[0])
- if cmdname:
- handler = self._get_cmd_handler(cmdname)
- if handler:
- return self._dispatch_cmd(handler, argv)
- return self.default(argv)
-
- def _dispatch_cmd(self, handler, argv):
- return handler(argv)
-
- def default(self, argv):
- """Hook called to handle a command for which there is no handler.
-
- "argv" is the command and arguments to run.
-
- The default implementation writes and error message to stderr
- and returns an error exit status.
-
- Returns a numeric command exit status.
- """
- errmsg = self._str(self.unknowncmd % (argv[0],))
- if self.cmdlooping:
- self.stderr.write(errmsg+"\n")
- else:
- self.stderr.write("%s: %s\nTry '%s help' for info.\n"
- % (self._name_str, errmsg, self._name_str))
- self.stderr.flush()
- return 1
-
- def parseline(self, line):
- # This is used by Cmd.complete (readline completer function) to
- # massage the current line buffer before completion processing.
- # We override to drop special '!' handling.
- line = line.strip()
- if not line:
- return None, None, line
- elif line[0] == '?':
- line = 'help ' + line[1:]
- i, n = 0, len(line)
- while i < n and line[i] in self.identchars:
- i = i+1
- cmd, arg = line[:i], line[i:].strip()
- return cmd, arg, line
-
- def helpdefault(self, cmd, known):
- """Hook called to handle help on a command for which there is no
- help handler.
-
- "cmd" is the command name on which help was requested.
- "known" is a boolean indicating if this command is known
- (i.e. if there is a handler for it).
-
- Returns a return code.
- """
- if known:
- msg = self._str(self.nohelp % (cmd,))
- if self.cmdlooping:
- self.stderr.write(msg + '\n')
- else:
- self.stderr.write("%s: %s\n" % (self.name, msg))
- else:
- msg = self.unknowncmd % (cmd,)
- if self.cmdlooping:
- self.stderr.write(msg + '\n')
- else:
- self.stderr.write("%s: %s\n"
- "Try '%s help' for info.\n"
- % (self.name, msg, self.name))
- self.stderr.flush()
- return 1
-
- def do_help(self, argv):
- """${cmd_name}: give detailed help on a specific sub-command
-
- Usage:
- ${name} help [COMMAND]
- """
- if len(argv) > 1: # asking for help on a particular command
- doc = None
- cmdname = self._get_canonical_cmd_name(argv[1]) or argv[1]
- if not cmdname:
- return self.helpdefault(argv[1], False)
- else:
- helpfunc = getattr(self, "help_"+cmdname, None)
- if helpfunc:
- doc = helpfunc()
- else:
- handler = self._get_cmd_handler(cmdname)
- if handler:
- doc = handler.__doc__
- if doc is None:
- return self.helpdefault(argv[1], handler != None)
- else: # bare "help" command
- doc = self.__class__.__doc__ # try class docstring
- if doc is None:
- # Try to provide some reasonable useful default help.
- if self.cmdlooping:
- prefix = ""
- else:
- prefix = self.name+' '
- doc = """Usage:
- %sCOMMAND [ARGS...]
- %shelp [COMMAND]
-
- ${option_list}
- ${command_list}
- ${help_list}
- """ % (prefix, prefix)
- cmdname = None
-
- if doc: # *do* have help content, massage and print that
- doc = self._help_reindent(doc)
- doc = self._help_preprocess(doc, cmdname)
- doc = doc.rstrip() + '\n' # trim down trailing space
- self.stdout.write(self._str(doc))
- self.stdout.flush()
- do_help.aliases = ["?"]
-
- def _help_reindent(self, help, indent=None):
- """Hook to re-indent help strings before writing to stdout.
-
- "help" is the help content to re-indent
- "indent" is a string with which to indent each line of the
- help content after normalizing. If unspecified or None
- then the default is use: the 'self.helpindent' class
- attribute. By default this is the empty string, i.e.
- no indentation.
-
- By default, all common leading whitespace is removed and then
- the lot is indented by 'self.helpindent'. When calculating the
- common leading whitespace the first line is ignored -- hence
- help content for Conan can be written as follows and have the
- expected indentation:
-
- def do_crush(self, ...):
- '''${cmd_name}: crush your enemies, see them driven before you...
-
- c.f. Conan the Barbarian'''
- """
- if indent is None:
- indent = self.helpindent
- lines = help.splitlines(0)
- _dedentlines(lines, skip_first_line=True)
- lines = [(indent+line).rstrip() for line in lines]
- return '\n'.join(lines)
-
- def _help_preprocess(self, help, cmdname):
- """Hook to preprocess a help string before writing to stdout.
-
- "help" is the help string to process.
- "cmdname" is the canonical sub-command name for which help
- is being given, or None if the help is not specific to a
- command.
-
- By default the following template variables are interpolated in
- help content. (Note: these are similar to Python 2.4's
- string.Template interpolation but not quite.)
-
- ${name}
- The tool's/shell's name, i.e. 'self.name'.
- ${option_list}
- A formatted table of options for this shell/tool.
- ${command_list}
- A formatted table of available sub-commands.
- ${help_list}
- A formatted table of additional help topics (i.e. 'help_*'
- methods with no matching 'do_*' method).
- ${cmd_name}
- The name (and aliases) for this sub-command formatted as:
- "NAME (ALIAS1, ALIAS2, ...)".
- ${cmd_usage}
- A formatted usage block inferred from the command function
- signature.
- ${cmd_option_list}
- A formatted table of options for this sub-command. (This is
- only available for commands using the optparse integration,
- i.e. using @cmdln.option decorators or manually setting the
- 'optparser' attribute on the 'do_*' method.)
-
- Returns the processed help.
- """
- preprocessors = {
- "${name}": self._help_preprocess_name,
- "${option_list}": self._help_preprocess_option_list,
- "${command_list}": self._help_preprocess_command_list,
- "${help_list}": self._help_preprocess_help_list,
- "${cmd_name}": self._help_preprocess_cmd_name,
- "${cmd_usage}": self._help_preprocess_cmd_usage,
- "${cmd_option_list}": self._help_preprocess_cmd_option_list,
- }
-
- for marker, preprocessor in preprocessors.items():
- if marker in help:
- help = preprocessor(help, cmdname)
- return help
-
- def _help_preprocess_name(self, help, cmdname=None):
- return help.replace("${name}", self.name)
-
- def _help_preprocess_option_list(self, help, cmdname=None):
- marker = "${option_list}"
- indent, indent_width = _get_indent(marker, help)
- suffix = _get_trailing_whitespace(marker, help)
-
- if self.optparser:
- # Setup formatting options and format.
- # - Indentation of 4 is better than optparse default of 2.
- # C.f. Damian Conway's discussion of this in Perl Best
- # Practices.
- self.optparser.formatter.indent_increment = 4
- self.optparser.formatter.current_indent = indent_width
- block = self.optparser.format_option_help() + '\n'
- else:
- block = ""
-
- help = help.replace(indent+marker+suffix, block, 1)
- return help
-
-
- def _help_preprocess_command_list(self, help, cmdname=None):
- marker = "${command_list}"
- indent, indent_width = _get_indent(marker, help)
- suffix = _get_trailing_whitespace(marker, help)
-
- # Find any aliases for commands.
- token2canonical = self._get_canonical_map()
- aliases = {}
- for token, cmdname in token2canonical.items():
- if token == cmdname:
- continue
- aliases.setdefault(cmdname, []).append(token)
-
- # Get the list of (non-hidden) commands and their
- # documentation, if any.
- cmdnames = {} # use a dict to strip duplicates
- for attr in self.get_names():
- if attr.startswith("do_"):
- cmdnames[attr[3:]] = True
- cmdnames = cmdnames.keys()
- cmdnames.sort()
- linedata = []
- for cmdname in cmdnames:
- if aliases.get(cmdname):
- a = aliases[cmdname]
- a.sort()
- cmdstr = "%s (%s)" % (cmdname, ", ".join(a))
- else:
- cmdstr = cmdname
- doc = None
- try:
- helpfunc = getattr(self, 'help_'+cmdname)
- except AttributeError:
- handler = self._get_cmd_handler(cmdname)
- if handler:
- doc = handler.__doc__
- else:
- doc = helpfunc()
-
- # Strip "${cmd_name}: " from the start of a command's doc. Best
- # practice dictates that command help strings begin with this, but
- # it isn't at all wanted for the command list.
- to_strip = "${cmd_name}:"
- if doc and doc.startswith(to_strip):
- #log.debug("stripping %r from start of %s's help string",
- # to_strip, cmdname)
- doc = doc[len(to_strip):].lstrip()
- linedata.append( (cmdstr, doc) )
-
- if linedata:
- subindent = indent + ' '*4
- lines = _format_linedata(linedata, subindent, indent_width+4)
- block = indent + "Commands:\n" \
- + '\n'.join(lines) + "\n\n"
- help = help.replace(indent+marker+suffix, block, 1)
- return help
-
- def _gen_names_and_attrs(self):
- # Inheritance says we have to look in class and
- # base classes; order is not important.
- names = []
- classes = [self.__class__]
- while classes:
- aclass = classes.pop(0)
- if aclass.__bases__:
- classes = classes + list(aclass.__bases__)
- for name in dir(aclass):
- yield (name, getattr(aclass, name))
-
- def _help_preprocess_help_list(self, help, cmdname=None):
- marker = "${help_list}"
- indent, indent_width = _get_indent(marker, help)
- suffix = _get_trailing_whitespace(marker, help)
-
- # Determine the additional help topics, if any.
- helpnames = {}
- token2cmdname = self._get_canonical_map()
- for attrname, attr in self._gen_names_and_attrs():
- if not attrname.startswith("help_"):
- continue
- helpname = attrname[5:]
- if helpname not in token2cmdname:
- helpnames[helpname] = attr
-
- if helpnames:
- linedata = [(n, a.__doc__ or "") for n, a in helpnames.items()]
- linedata.sort()
-
- subindent = indent + ' '*4
- lines = _format_linedata(linedata, subindent, indent_width+4)
- block = (indent
- + "Additional help topics (run `%s help TOPIC'):\n" % self.name
- + '\n'.join(lines)
- + "\n\n")
- else:
- block = ''
- help = help.replace(indent+marker+suffix, block, 1)
- return help
-
- def _help_preprocess_cmd_name(self, help, cmdname=None):
- marker = "${cmd_name}"
- handler = self._get_cmd_handler(cmdname)
- if not handler:
- raise CmdlnError("cannot preprocess '%s' into help string: "
- "could not find command handler for %r"
- % (marker, cmdname))
- s = cmdname
- if hasattr(handler, "aliases"):
- s += " (%s)" % (", ".join(handler.aliases))
- help = help.replace(marker, s)
- return help
-
- #TODO: this only makes sense as part of the Cmdln class.
- # Add hooks to add help preprocessing template vars and put
- # this one on that class.
- def _help_preprocess_cmd_usage(self, help, cmdname=None):
- marker = "${cmd_usage}"
- handler = self._get_cmd_handler(cmdname)
- if not handler:
- raise CmdlnError("cannot preprocess '%s' into help string: "
- "could not find command handler for %r"
- % (marker, cmdname))
- indent, indent_width = _get_indent(marker, help)
- suffix = _get_trailing_whitespace(marker, help)
-
- # Extract the introspection bits we need.
- func = handler.im_func
- if func.func_defaults:
- func_defaults = list(func.func_defaults)
- else:
- func_defaults = []
- co_argcount = func.func_code.co_argcount
- co_varnames = func.func_code.co_varnames
- co_flags = func.func_code.co_flags
- CO_FLAGS_ARGS = 4
- CO_FLAGS_KWARGS = 8
-
- # Adjust argcount for possible *args and **kwargs arguments.
- argcount = co_argcount
- if co_flags & CO_FLAGS_ARGS:
- argcount += 1
- if co_flags & CO_FLAGS_KWARGS:
- argcount += 1
-
- # Determine the usage string.
- usage = "%s %s" % (self.name, cmdname)
- if argcount <= 2: # handler ::= do_FOO(self, argv)
- usage += " [ARGS...]"
- elif argcount >= 3: # handler ::= do_FOO(self, subcmd, opts, ...)
- argnames = list(co_varnames[3:argcount])
- tail = ""
- if co_flags & CO_FLAGS_KWARGS:
- name = argnames.pop(-1)
- import warnings
- # There is no generally accepted mechanism for passing
- # keyword arguments from the command line. Could
- # *perhaps* consider: arg=value arg2=value2 ...
- warnings.warn("argument '**%s' on '%s.%s' command "
- "handler will never get values"
- % (name, self.__class__.__name__,
- func.func_name))
- if co_flags & CO_FLAGS_ARGS:
- name = argnames.pop(-1)
- tail = "[%s...]" % name.upper()
- while func_defaults:
- func_defaults.pop(-1)
- name = argnames.pop(-1)
- tail = "[%s%s%s]" % (name.upper(), (tail and ' ' or ''), tail)
- while argnames:
- name = argnames.pop(-1)
- tail = "%s %s" % (name.upper(), tail)
- usage += ' ' + tail
-
- block_lines = [
- self.helpindent + "Usage:",
- self.helpindent + ' '*4 + usage
- ]
- block = '\n'.join(block_lines) + '\n\n'
-
- help = help.replace(indent+marker+suffix, block, 1)
- return help
-
- #TODO: this only makes sense as part of the Cmdln class.
- # Add hooks to add help preprocessing template vars and put
- # this one on that class.
- def _help_preprocess_cmd_option_list(self, help, cmdname=None):
- marker = "${cmd_option_list}"
- handler = self._get_cmd_handler(cmdname)
- if not handler:
- raise CmdlnError("cannot preprocess '%s' into help string: "
- "could not find command handler for %r"
- % (marker, cmdname))
- indent, indent_width = _get_indent(marker, help)
- suffix = _get_trailing_whitespace(marker, help)
- if hasattr(handler, "optparser"):
- # Setup formatting options and format.
- # - Indentation of 4 is better than optparse default of 2.
- # C.f. Damian Conway's discussion of this in Perl Best
- # Practices.
- handler.optparser.formatter.indent_increment = 4
- handler.optparser.formatter.current_indent = indent_width
- block = handler.optparser.format_option_help() + '\n'
- else:
- block = ""
-
- help = help.replace(indent+marker+suffix, block, 1)
- return help
-
- def _get_canonical_cmd_name(self, token):
- map = self._get_canonical_map()
- return map.get(token, None)
-
- def _get_canonical_map(self):
- """Return a mapping of available command names and aliases to
- their canonical command name.
- """
- cacheattr = "_token2canonical"
- if not hasattr(self, cacheattr):
- # Get the list of commands and their aliases, if any.
- token2canonical = {}
- cmd2funcname = {} # use a dict to strip duplicates
- for attr in self.get_names():
- if attr.startswith("do_"):
- cmdname = attr[3:]
- elif attr.startswith("_do_"):
- cmdname = attr[4:]
- else:
- continue
- cmd2funcname[cmdname] = attr
- token2canonical[cmdname] = cmdname
- for cmdname, funcname in cmd2funcname.items(): # add aliases
- func = getattr(self, funcname)
- aliases = getattr(func, "aliases", [])
- for alias in aliases:
- if alias in cmd2funcname:
- import warnings
- warnings.warn("'%s' alias for '%s' command conflicts "
- "with '%s' handler"
- % (alias, cmdname, cmd2funcname[alias]))
- continue
- token2canonical[alias] = cmdname
- setattr(self, cacheattr, token2canonical)
- return getattr(self, cacheattr)
-
- def _get_cmd_handler(self, cmdname):
- handler = None
- try:
- handler = getattr(self, 'do_' + cmdname)
- except AttributeError:
- try:
- # Private command handlers begin with "_do_".
- handler = getattr(self, '_do_' + cmdname)
- except AttributeError:
- pass
- return handler
-
- def _do_EOF(self, argv):
- # Default EOF handler
- # Note: an actual EOF is redirected to this command.
- #TODO: separate name for this. Currently it is available from
- # command-line. Is that okay?
- self.stdout.write('\n')
- self.stdout.flush()
- self.stop = True
-
- def emptyline(self):
- # Different from cmd.Cmd: don't repeat the last command for an
- # emptyline.
- if self.cmdlooping:
- pass
- else:
- return self.do_help(["help"])
-
-
-#---- optparse.py extension to fix (IMO) some deficiencies
-#
-# See the class _OptionParserEx docstring for details.
-#
-
-class StopOptionProcessing(Exception):
- """Indicate that option *and argument* processing should stop
- cleanly. This is not an error condition. It is similar in spirit to
- StopIteration. This is raised by _OptionParserEx's default "help"
- and "version" option actions and can be raised by custom option
- callbacks too.
-
- Hence the typical CmdlnOptionParser (a subclass of _OptionParserEx)
- usage is:
-
- parser = CmdlnOptionParser(mycmd)
- parser.add_option("-f", "--force", dest="force")
- ...
- try:
- opts, args = parser.parse_args()
- except StopOptionProcessing:
- # normal termination, "--help" was probably given
- sys.exit(0)
- """
-
-class _OptionParserEx(optparse.OptionParser):
- """An optparse.OptionParser that uses exceptions instead of sys.exit.
-
- This class is an extension of optparse.OptionParser that differs
- as follows:
- - Correct (IMO) the default OptionParser error handling to never
- sys.exit(). Instead OptParseError exceptions are passed through.
- - Add the StopOptionProcessing exception (a la StopIteration) to
- indicate normal termination of option processing.
- See StopOptionProcessing's docstring for details.
-
- I'd also like to see the following in the core optparse.py, perhaps
- as a RawOptionParser which would serve as a base class for the more
- generally used OptionParser (that works as current):
- - Remove the implicit addition of the -h|--help and --version
- options. They can get in the way (e.g. if want '-?' and '-V' for
- these as well) and it is not hard to do:
- optparser.add_option("-h", "--help", action="help")
- optparser.add_option("--version", action="version")
- These are good practices, just not valid defaults if they can
- get in the way.
- """
- def error(self, msg):
- raise optparse.OptParseError(msg)
-
- def exit(self, status=0, msg=None):
- if status == 0:
- raise StopOptionProcessing(msg)
- else:
- #TODO: don't lose status info here
- raise optparse.OptParseError(msg)
-
-
-
-#---- optparse.py-based option processing support
-
-class CmdlnOptionParser(_OptionParserEx):
- """An optparse.OptionParser class more appropriate for top-level
- Cmdln options. For parsing of sub-command options, see
- SubCmdOptionParser.
-
- Changes:
- - disable_interspersed_args() by default, because a Cmdln instance
- has sub-commands which may themselves have options.
- - Redirect print_help() to the Cmdln.do_help() which is better
- equiped to handle the "help" action.
- - error() will raise a CmdlnUserError: OptionParse.error() is meant
- to be called for user errors. Raising a well-known error here can
- make error handling clearer.
- - Also see the changes in _OptionParserEx.
- """
- def __init__(self, cmdln, **kwargs):
- self.cmdln = cmdln
- kwargs["prog"] = self.cmdln.name
- _OptionParserEx.__init__(self, **kwargs)
- self.disable_interspersed_args()
-
- def print_help(self, file=None):
- self.cmdln.onecmd(["help"])
-
- def error(self, msg):
- raise CmdlnUserError(msg)
-
-
-class SubCmdOptionParser(_OptionParserEx):
- def set_cmdln_info(self, cmdln, subcmd):
- """Called by Cmdln to pass relevant info about itself needed
- for print_help().
- """
- self.cmdln = cmdln
- self.subcmd = subcmd
-
- def print_help(self, file=None):
- self.cmdln.onecmd(["help", self.subcmd])
-
- def error(self, msg):
- raise CmdlnUserError(msg)
-
-
-def option(*args, **kwargs):
- """Decorator to add an option to the optparser argument of a Cmdln
- subcommand.
-
- Example:
- class MyShell(cmdln.Cmdln):
- @cmdln.option("-f", "--force", help="force removal")
- def do_remove(self, subcmd, opts, *args):
- #...
- """
- #XXX Is there a possible optimization for many options to not have a
- # large stack depth here?
- def decorate(f):
- if not hasattr(f, "optparser"):
- f.optparser = SubCmdOptionParser()
- f.optparser.add_option(*args, **kwargs)
- return f
- return decorate
-
-
-class Cmdln(RawCmdln):
- """An improved (on cmd.Cmd) framework for building multi-subcommand
- scripts (think "svn" & "cvs") and simple shells (think "pdb" and
- "gdb").
-
- A simple example:
-
- import cmdln
-
- class MySVN(cmdln.Cmdln):
- name = "svn"
-
- @cmdln.aliases('stat', 'st')
- @cmdln.option('-v', '--verbose', action='store_true'
- help='print verbose information')
- def do_status(self, subcmd, opts, *paths):
- print "handle 'svn status' command"
-
- #...
-
- if __name__ == "__main__":
- shell = MySVN()
- retval = shell.main()
- sys.exit(retval)
-
- 'Cmdln' extends 'RawCmdln' by providing optparse option processing
- integration. See this class' _dispatch_cmd() docstring and
- <http://trentm.com/projects/cmdln> for more information.
- """
- def _dispatch_cmd(self, handler, argv):
- """Introspect sub-command handler signature to determine how to
- dispatch the command. The raw handler provided by the base
- 'RawCmdln' class is still supported:
-
- def do_foo(self, argv):
- # 'argv' is the vector of command line args, argv[0] is
- # the command name itself (i.e. "foo" or an alias)
- pass
-
- In addition, if the handler has more than 2 arguments option
- processing is automatically done (using optparse):
-
- @cmdln.option('-v', '--verbose', action='store_true')
- def do_bar(self, subcmd, opts, *args):
- # subcmd = <"bar" or an alias>
- # opts = <an optparse.Values instance>
- if opts.verbose:
- print "lots of debugging output..."
- # args = <tuple of arguments>
- for arg in args:
- bar(arg)
-
- TODO: explain that "*args" can be other signatures as well.
-
- The `cmdln.option` decorator corresponds to an `add_option()`
- method call on an `optparse.OptionParser` instance.
-
- You can declare a specific number of arguments:
-
- @cmdln.option('-v', '--verbose', action='store_true')
- def do_bar2(self, subcmd, opts, bar_one, bar_two):
- #...
-
- and an appropriate error message will be raised/printed if the
- command is called with a different number of args.
- """
- co_argcount = handler.im_func.func_code.co_argcount
- if co_argcount == 2: # handler ::= do_foo(self, argv)
- return handler(argv)
- elif co_argcount >= 3: # handler ::= do_foo(self, subcmd, opts, ...)
- try:
- optparser = handler.optparser
- except AttributeError:
- optparser = handler.im_func.optparser = SubCmdOptionParser()
- assert isinstance(optparser, SubCmdOptionParser)
- optparser.set_cmdln_info(self, argv[0])
- try:
- opts, args = optparser.parse_args(argv[1:])
- except StopOptionProcessing:
- #TODO: this doesn't really fly for a replacement of
- # optparse.py behaviour, does it?
- return 0 # Normal command termination
-
- try:
- return handler(argv[0], opts, *args)
- except TypeError, ex:
- # Some TypeError's are user errors:
- # do_foo() takes at least 4 arguments (3 given)
- # do_foo() takes at most 5 arguments (6 given)
- # do_foo() takes exactly 5 arguments (6 given)
- # Raise CmdlnUserError for these with a suitably
- # massaged error message.
- import sys
- tb = sys.exc_info()[2] # the traceback object
- if tb.tb_next is not None:
- # If the traceback is more than one level deep, then the
- # TypeError do *not* happen on the "handler(...)" call
- # above. In that we don't want to handle it specially
- # here: it would falsely mask deeper code errors.
- raise
- msg = ex.args[0]
- match = _INCORRECT_NUM_ARGS_RE.search(msg)
- if match:
- msg = list(match.groups())
- msg[1] = int(msg[1]) - 3
- if msg[1] == 1:
- msg[2] = msg[2].replace("arguments", "argument")
- msg[3] = int(msg[3]) - 3
- msg = ''.join(map(str, msg))
- raise CmdlnUserError(msg)
- else:
- raise
- else:
- raise CmdlnError("incorrect argcount for %s(): takes %d, must "
- "take 2 for 'argv' signature or 3+ for 'opts' "
- "signature" % (handler.__name__, co_argcount))
-
-
-
-#---- internal support functions
-
-def _format_linedata(linedata, indent, indent_width):
- """Format specific linedata into a pleasant layout.
-
- "linedata" is a list of 2-tuples of the form:
- (<item-display-string>, <item-docstring>)
- "indent" is a string to use for one level of indentation
- "indent_width" is a number of columns by which the
- formatted data will be indented when printed.
-
- The <item-display-string> column is held to 15 columns.
- """
- lines = []
- WIDTH = 78 - indent_width
- SPACING = 2
- NAME_WIDTH_LOWER_BOUND = 13
- NAME_WIDTH_UPPER_BOUND = 16
- NAME_WIDTH = max([len(s) for s,d in linedata])
- if NAME_WIDTH < NAME_WIDTH_LOWER_BOUND:
- NAME_WIDTH = NAME_WIDTH_LOWER_BOUND
- else:
- NAME_WIDTH = NAME_WIDTH_UPPER_BOUND
-
- DOC_WIDTH = WIDTH - NAME_WIDTH - SPACING
- for namestr, doc in linedata:
- line = indent + namestr
- if len(namestr) <= NAME_WIDTH:
- line += ' ' * (NAME_WIDTH + SPACING - len(namestr))
- else:
- lines.append(line)
- line = indent + ' ' * (NAME_WIDTH + SPACING)
- line += _summarize_doc(doc, DOC_WIDTH)
- lines.append(line.rstrip())
- return lines
-
-def _summarize_doc(doc, length=60):
- r"""Parse out a short one line summary from the given doclines.
-
- "doc" is the doc string to summarize.
- "length" is the max length for the summary
-
- >>> _summarize_doc("this function does this")
- 'this function does this'
- >>> _summarize_doc("this function does this", 10)
- 'this fu...'
- >>> _summarize_doc("this function does this\nand that")
- 'this function does this and that'
- >>> _summarize_doc("this function does this\n\nand that")
- 'this function does this'
- """
- import re
- if doc is None:
- return ""
- assert length > 3, "length <= 3 is absurdly short for a doc summary"
- doclines = doc.strip().splitlines(0)
- if not doclines:
- return ""
-
- summlines = []
- for i, line in enumerate(doclines):
- stripped = line.strip()
- if not stripped:
- break
- summlines.append(stripped)
- if len(''.join(summlines)) >= length:
- break
-
- summary = ' '.join(summlines)
- if len(summary) > length:
- summary = summary[:length-3] + "..."
- return summary
-
-
-def line2argv(line):
- r"""Parse the given line into an argument vector.
-
- "line" is the line of input to parse.
-
- This may get niggly when dealing with quoting and escaping. The
- current state of this parsing may not be completely thorough/correct
- in this respect.
-
- >>> from cmdln import line2argv
- >>> line2argv("foo")
- ['foo']
- >>> line2argv("foo bar")
- ['foo', 'bar']
- >>> line2argv("foo bar ")
- ['foo', 'bar']
- >>> line2argv(" foo bar")
- ['foo', 'bar']
-
- Quote handling:
-
- >>> line2argv("'foo bar'")
- ['foo bar']
- >>> line2argv('"foo bar"')
- ['foo bar']
- >>> line2argv(r'"foo\"bar"')
- ['foo"bar']
- >>> line2argv("'foo bar' spam")
- ['foo bar', 'spam']
- >>> line2argv("'foo 'bar spam")
- ['foo bar', 'spam']
-
- >>> line2argv('some\tsimple\ttests')
- ['some', 'simple', 'tests']
- >>> line2argv('a "more complex" test')
- ['a', 'more complex', 'test']
- >>> line2argv('a more="complex test of " quotes')
- ['a', 'more=complex test of ', 'quotes']
- >>> line2argv('a more" complex test of " quotes')
- ['a', 'more complex test of ', 'quotes']
- >>> line2argv('an "embedded \\"quote\\""')
- ['an', 'embedded "quote"']
-
- # Komodo bug 48027
- >>> line2argv('foo bar C:\\')
- ['foo', 'bar', 'C:\\']
-
- # Komodo change 127581
- >>> line2argv(r'"\test\slash" "foo bar" "foo\"bar"')
- ['\\test\\slash', 'foo bar', 'foo"bar']
-
- # Komodo change 127629
- >>> if sys.platform == "win32":
- ... line2argv(r'\foo\bar') == ['\\foo\\bar']
- ... line2argv(r'\\foo\\bar') == ['\\\\foo\\\\bar']
- ... line2argv('"foo') == ['foo']
- ... else:
- ... line2argv(r'\foo\bar') == ['foobar']
- ... line2argv(r'\\foo\\bar') == ['\\foo\\bar']
- ... try:
- ... line2argv('"foo')
- ... except ValueError, ex:
- ... "not terminated" in str(ex)
- True
- True
- True
- """
- import string
- line = line.strip()
- argv = []
- state = "default"
- arg = None # the current argument being parsed
- i = -1
- while 1:
- i += 1
- if i >= len(line):
- break
- ch = line[i]
-
- if ch == "\\" and i+1 < len(line):
- # escaped char always added to arg, regardless of state
- if arg is None:
- arg = ""
- if (sys.platform == "win32"
- or state in ("double-quoted", "single-quoted")
- ) and line[i+1] not in tuple('"\''):
- arg += ch
- i += 1
- arg += line[i]
- continue
-
- if state == "single-quoted":
- if ch == "'":
- state = "default"
- else:
- arg += ch
- elif state == "double-quoted":
- if ch == '"':
- state = "default"
- else:
- arg += ch
- elif state == "default":
- if ch == '"':
- if arg is None:
- arg = ""
- state = "double-quoted"
- elif ch == "'":
- if arg is None:
- arg = ""
- state = "single-quoted"
- elif ch in string.whitespace:
- if arg is not None:
- argv.append(arg)
- arg = None
- else:
- if arg is None:
- arg = ""
- arg += ch
- if arg is not None:
- argv.append(arg)
- if not sys.platform == "win32" and state != "default":
- raise ValueError("command line is not terminated: unfinished %s "
- "segment" % state)
- return argv
-
-
-def argv2line(argv):
- r"""Put together the given argument vector into a command line.
-
- "argv" is the argument vector to process.
-
- >>> from cmdln import argv2line
- >>> argv2line(['foo'])
- 'foo'
- >>> argv2line(['foo', 'bar'])
- 'foo bar'
- >>> argv2line(['foo', 'bar baz'])
- 'foo "bar baz"'
- >>> argv2line(['foo"bar'])
- 'foo"bar'
- >>> print argv2line(['foo" bar'])
- 'foo" bar'
- >>> print argv2line(["foo' bar"])
- "foo' bar"
- >>> argv2line(["foo'bar"])
- "foo'bar"
- """
- escapedArgs = []
- for arg in argv:
- if ' ' in arg and '"' not in arg:
- arg = '"'+arg+'"'
- elif ' ' in arg and "'" not in arg:
- arg = "'"+arg+"'"
- elif ' ' in arg:
- arg = arg.replace('"', r'\"')
- arg = '"'+arg+'"'
- escapedArgs.append(arg)
- return ' '.join(escapedArgs)
-
-
-# Recipe: dedent (0.1) in /Users/trentm/tm/recipes/cookbook
-def _dedentlines(lines, tabsize=8, skip_first_line=False):
- """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines
-
- "lines" is a list of lines to dedent.
- "tabsize" is the tab width to use for indent width calculations.
- "skip_first_line" is a boolean indicating if the first line should
- be skipped for calculating the indent width and for dedenting.
- This is sometimes useful for docstrings and similar.
-
- Same as dedent() except operates on a sequence of lines. Note: the
- lines list is modified **in-place**.
- """
- DEBUG = False
- if DEBUG:
- print "dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\
- % (tabsize, skip_first_line)
- indents = []
- margin = None
- for i, line in enumerate(lines):
- if i == 0 and skip_first_line:
- continue
- indent = 0
- for ch in line:
- if ch == ' ':
- indent += 1
- elif ch == '\t':
- indent += tabsize - (indent % tabsize)
- elif ch in '\r\n':
- continue # skip all-whitespace lines
- else:
- break
- else:
- continue # skip all-whitespace lines
- if DEBUG:
- print "dedent: indent=%d: %r" % (indent, line)
- if margin is None:
- margin = indent
- else:
- margin = min(margin, indent)
- if DEBUG:
- print "dedent: margin=%r" % margin
-
- if margin is not None and margin > 0:
- for i, line in enumerate(lines):
- if i == 0 and skip_first_line:
- continue
- removed = 0
- for j, ch in enumerate(line):
- if ch == ' ':
- removed += 1
- elif ch == '\t':
- removed += tabsize - (removed % tabsize)
- elif ch in '\r\n':
- if DEBUG:
- print "dedent: %r: EOL -> strip up to EOL" % line
- lines[i] = lines[i][j:]
- break
- else:
- raise ValueError("unexpected non-whitespace char %r in "
- "line %r while removing %d-space margin"
- % (ch, line, margin))
- if DEBUG:
- print "dedent: %r: %r -> removed %d/%d"\
- % (line, ch, removed, margin)
- if removed == margin:
- lines[i] = lines[i][j+1:]
- break
- elif removed > margin:
- lines[i] = ' '*(removed-margin) + lines[i][j+1:]
- break
- return lines
-
-def _dedent(text, tabsize=8, skip_first_line=False):
- """_dedent(text, tabsize=8, skip_first_line=False) -> dedented text
-
- "text" is the text to dedent.
- "tabsize" is the tab width to use for indent width calculations.
- "skip_first_line" is a boolean indicating if the first line should
- be skipped for calculating the indent width and for dedenting.
- This is sometimes useful for docstrings and similar.
-
- textwrap.dedent(s), but don't expand tabs to spaces
- """
- lines = text.splitlines(1)
- _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line)
- return ''.join(lines)
-
-
-def _get_indent(marker, s, tab_width=8):
- """_get_indent(marker, s, tab_width=8) ->
- (<indentation-of-'marker'>, <indentation-width>)"""
- # Figure out how much the marker is indented.
- INDENT_CHARS = tuple(' \t')
- start = s.index(marker)
- i = start
- while i > 0:
- if s[i-1] not in INDENT_CHARS:
- break
- i -= 1
- indent = s[i:start]
- indent_width = 0
- for ch in indent:
- if ch == ' ':
- indent_width += 1
- elif ch == '\t':
- indent_width += tab_width - (indent_width % tab_width)
- return indent, indent_width
-
-def _get_trailing_whitespace(marker, s):
- """Return the whitespace content trailing the given 'marker' in string 's',
- up to and including a newline.
- """
- suffix = ''
- start = s.index(marker) + len(marker)
- i = start
- while i < len(s):
- if s[i] in ' \t':
- suffix += s[i]
- elif s[i] in '\r\n':
- suffix += s[i]
- if s[i] == '\r' and i+1 < len(s) and s[i+1] == '\n':
- suffix += s[i+1]
- break
- else:
- break
- i += 1
- return suffix
-
-
-
-#---- bash completion support
-# Note: This is still experimental. I expect to change this
-# significantly.
-#
-# To get Bash completion for a cmdln.Cmdln class, run the following
-# bash command:
-# $ complete -C 'python -m cmdln /path/to/script.py CmdlnClass' cmdname
-# For example:
-# $ complete -C 'python -m cmdln ~/bin/svn.py SVN' svn
-#
-#TODO: Simplify the above so don't have to given path to script (try to
-# find it on PATH, if possible). Could also make class name
-# optional if there is only one in the module (common case).
-
-if __name__ == "__main__" and len(sys.argv) == 6:
- def _log(s):
- return # no-op, comment out for debugging
- from os.path import expanduser
- fout = open(expanduser("~/tmp/bashcpln.log"), 'a')
- fout.write(str(s) + '\n')
- fout.close()
-
- # Recipe: module_from_path (1.0.1+)
- def _module_from_path(path):
- import imp, os, sys
- path = os.path.expanduser(path)
- dir = os.path.dirname(path) or os.curdir
- name = os.path.splitext(os.path.basename(path))[0]
- sys.path.insert(0, dir)
- try:
- iinfo = imp.find_module(name, [dir])
- return imp.load_module(name, *iinfo)
- finally:
- sys.path.remove(dir)
-
- def _get_bash_cplns(script_path, class_name, cmd_name,
- token, preceding_token):
- _log('--')
- _log('get_cplns(%r, %r, %r, %r, %r)'
- % (script_path, class_name, cmd_name, token, preceding_token))
- comp_line = os.environ["COMP_LINE"]
- comp_point = int(os.environ["COMP_POINT"])
- _log("COMP_LINE: %r" % comp_line)
- _log("COMP_POINT: %r" % comp_point)
-
- try:
- script = _module_from_path(script_path)
- except ImportError, ex:
- _log("error importing `%s': %s" % (script_path, ex))
- return []
- shell = getattr(script, class_name)()
- cmd_map = shell._get_canonical_map()
- del cmd_map["EOF"]
-
- # Determine if completing the sub-command name.
- parts = comp_line[:comp_point].split(None, 1)
- _log(parts)
- if len(parts) == 1 or not (' ' in parts[1] or '\t' in parts[1]):
- #TODO: if parts[1].startswith('-'): handle top-level opts
- _log("complete sub-command names")
- matches = {}
- for name, canon_name in cmd_map.items():
- if name.startswith(token):
- matches[name] = canon_name
- if not matches:
- return []
- elif len(matches) == 1:
- return matches.keys()
- elif len(set(matches.values())) == 1:
- return [matches.values()[0]]
- else:
- return matches.keys()
-
- # Otherwise, complete options for the given sub-command.
- #TODO: refine this so it does the right thing with option args
- if token.startswith('-'):
- cmd_name = comp_line.split(None, 2)[1]
- try:
- cmd_canon_name = cmd_map[cmd_name]
- except KeyError:
- return []
- handler = shell._get_cmd_handler(cmd_canon_name)
- optparser = getattr(handler, "optparser", None)
- if optparser is None:
- optparser = SubCmdOptionParser()
- opt_strs = []
- for option in optparser.option_list:
- for opt_str in option._short_opts + option._long_opts:
- if opt_str.startswith(token):
- opt_strs.append(opt_str)
- return opt_strs
-
- return []
-
- for cpln in _get_bash_cplns(*sys.argv[1:]):
- print cpln
-
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 12/17] wic: fix pylint warning no-member
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (10 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 11/17] wic: use optparse instead of cmdln Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 13/17] wic: fix pylint warning unused-variable Ed Bartosh
` (4 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Fixed pylint warning:
Instance of 'ConfigMgr' has no 'create' member (no-member)
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
scripts/lib/wic/conf.py | 1 +
1 file changed, 1 insertion(+)
diff --git a/scripts/lib/wic/conf.py b/scripts/lib/wic/conf.py
index 402ed62..942c0c1 100644
--- a/scripts/lib/wic/conf.py
+++ b/scripts/lib/wic/conf.py
@@ -67,6 +67,7 @@ class ConfigMgr(object):
def reset(self):
self.__ksconf = None
self.__siteconf = None
+ self.create = {}
# initialize the values with defaults
for sec, vals in self.DEFAULTS.iteritems():
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 13/17] wic: fix pylint warning unused-variable
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (11 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 12/17] wic: fix pylint warning no-member Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 14/17] wic: fix pylint warning redefined-builtin Ed Bartosh
` (3 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Removed or reworked code with unused variables.
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
scripts/lib/wic/engine.py | 4 +---
scripts/lib/wic/imager/baseimager.py | 4 ++--
scripts/lib/wic/imager/direct.py | 2 +-
scripts/lib/wic/plugin.py | 7 +------
scripts/lib/wic/plugins/source/bootimg-efi.py | 6 ------
scripts/wic | 2 +-
6 files changed, 6 insertions(+), 19 deletions(-)
diff --git a/scripts/lib/wic/engine.py b/scripts/lib/wic/engine.py
index a034841..30c4fa3 100644
--- a/scripts/lib/wic/engine.py
+++ b/scripts/lib/wic/engine.py
@@ -43,9 +43,7 @@ def verify_build_env():
Returns True if it is, false otherwise
"""
- try:
- builddir = os.environ["BUILDDIR"]
- except KeyError:
+ if not os.environ.get("BUILDDIR"):
print "BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)"
sys.exit(1)
diff --git a/scripts/lib/wic/imager/baseimager.py b/scripts/lib/wic/imager/baseimager.py
index 67a2d01..4abcabc 100644
--- a/scripts/lib/wic/imager/baseimager.py
+++ b/scripts/lib/wic/imager/baseimager.py
@@ -132,9 +132,9 @@ class BaseImageCreator(object):
os.makedirs(self.workdir)
self.__builddir = tempfile.mkdtemp(dir=self.workdir,
prefix="imgcreate-")
- except OSError, (err, msg):
+ except OSError as err:
raise CreatorError("Failed create build directory in %s: %s" %
- (self.tmpdir, msg))
+ (self.tmpdir, err))
def __setup_tmpdir(self):
if not self.enabletmpfs:
diff --git a/scripts/lib/wic/imager/direct.py b/scripts/lib/wic/imager/direct.py
index d68fd2a..74ebbe7 100644
--- a/scripts/lib/wic/imager/direct.py
+++ b/scripts/lib/wic/imager/direct.py
@@ -327,7 +327,7 @@ class DirectImageCreator(BaseImageCreator):
parts = self._get_parts()
- for disk_name, disk in self.__image.disks.items():
+ for disk_name in self.__image.disks:
extension = "direct" + {"gzip": ".gz",
"bzip2": ".bz2",
"xz": ".xz",
diff --git a/scripts/lib/wic/plugin.py b/scripts/lib/wic/plugin.py
index e901f80..7244989 100644
--- a/scripts/lib/wic/plugin.py
+++ b/scripts/lib/wic/plugin.py
@@ -124,12 +124,7 @@ class PluginMgr(object):
self.append_dirs(plugins_dir)
- plugins = []
-
- for _source_name, klass in self.get_plugins('source').iteritems():
- plugins.append(_source_name)
-
- return plugins
+ return self.get_plugins('source')
def get_source_plugin_methods(self, source_name, methods):
diff --git a/scripts/lib/wic/plugins/source/bootimg-efi.py b/scripts/lib/wic/plugins/source/bootimg-efi.py
index 49d5c8a..b48cc83 100644
--- a/scripts/lib/wic/plugins/source/bootimg-efi.py
+++ b/scripts/lib/wic/plugins/source/bootimg-efi.py
@@ -45,12 +45,6 @@ class BootimgEFIPlugin(SourcePlugin):
"""
Create loader-specific (grub-efi) config
"""
- splash = os.path.join(cr_workdir, "/EFI/boot/splash.jpg")
- if os.path.exists(splash):
- splashline = "menu background splash.jpg"
- else:
- splashline = ""
-
options = cr.ks.handler.bootloader.appendLine
grubefi_conf = ""
diff --git a/scripts/wic b/scripts/wic
index 94028e2..c99c504 100755
--- a/scripts/wic
+++ b/scripts/wic
@@ -308,7 +308,7 @@ def main(argv):
parser.disable_interspersed_args()
- (options, args) = parser.parse_args(argv)
+ args = parser.parse_args(argv)[1]
if len(args):
if args[0] == "help":
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 14/17] wic: fix pylint warning redefined-builtin
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (12 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 13/17] wic: fix pylint warning unused-variable Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 15/17] wic: get rid of listing properties Ed Bartosh
` (2 subsequent siblings)
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Renamed variables named as Python builtin functions.
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
scripts/lib/wic/engine.py | 18 +++++++++---------
scripts/lib/wic/imager/baseimager.py | 4 ++--
scripts/lib/wic/imager/direct.py | 6 +++---
scripts/lib/wic/plugins/source/bootimg-pcbios.py | 6 +++---
4 files changed, 17 insertions(+), 17 deletions(-)
diff --git a/scripts/lib/wic/engine.py b/scripts/lib/wic/engine.py
index 30c4fa3..d4a7be6 100644
--- a/scripts/lib/wic/engine.py
+++ b/scripts/lib/wic/engine.py
@@ -77,11 +77,11 @@ def find_canned_image(scripts_path, wks_file):
for canned_wks_dir in layers_canned_wks_dir:
for root, dirs, files in os.walk(canned_wks_dir):
- for file in files:
- if file.endswith("~") or file.endswith("#"):
+ for fname in files:
+ if fname.endswith("~") or fname.endswith("#"):
continue
- if file.endswith(".wks") and wks_file + ".wks" == file:
- fullpath = os.path.join(canned_wks_dir, file)
+ if fname.endswith(".wks") and wks_file + ".wks" == fname:
+ fullpath = os.path.join(canned_wks_dir, fname)
return fullpath
return None
@@ -94,11 +94,11 @@ def list_canned_images(scripts_path):
for canned_wks_dir in layers_canned_wks_dir:
for root, dirs, files in os.walk(canned_wks_dir):
- for file in files:
- if file.endswith("~") or file.endswith("#"):
+ for fname in files:
+ if fname.endswith("~") or fname.endswith("#"):
continue
- if file.endswith(".wks"):
- fullpath = os.path.join(canned_wks_dir, file)
+ if fname.endswith(".wks"):
+ fullpath = os.path.join(canned_wks_dir, fname)
f = open(fullpath, "r")
lines = f.readlines()
for line in lines:
@@ -107,7 +107,7 @@ def list_canned_images(scripts_path):
if idx != -1:
desc = line[idx + len("short-description:"):].strip()
break
- basename = os.path.splitext(file)[0]
+ basename = os.path.splitext(fname)[0]
print " %s\t\t%s" % (basename.ljust(30), desc)
diff --git a/scripts/lib/wic/imager/baseimager.py b/scripts/lib/wic/imager/baseimager.py
index 4abcabc..acbe948 100644
--- a/scripts/lib/wic/imager/baseimager.py
+++ b/scripts/lib/wic/imager/baseimager.py
@@ -186,7 +186,7 @@ class BaseImageCreator(object):
def print_outimage_info(self):
msg = "The new image can be found here:\n"
self.outimage.sort()
- for file in self.outimage:
- msg += ' %s\n' % os.path.abspath(file)
+ for path in self.outimage:
+ msg += ' %s\n' % os.path.abspath(path)
msger.info(msg)
diff --git a/scripts/lib/wic/imager/direct.py b/scripts/lib/wic/imager/direct.py
index 74ebbe7..761e436 100644
--- a/scripts/lib/wic/imager/direct.py
+++ b/scripts/lib/wic/imager/direct.py
@@ -340,10 +340,10 @@ class DirectImageCreator(BaseImageCreator):
if p.get_rootfs() is None:
continue
if p.mountpoint == '/':
- str = ':'
+ suffix = ':'
else:
- str = '["%s"]:' % (p.mountpoint or p.label)
- msg += ' ROOTFS_DIR%s%s\n' % (str.ljust(20), p.get_rootfs())
+ suffix = '["%s"]:' % (p.mountpoint or p.label)
+ msg += ' ROOTFS_DIR%s%s\n' % (suffix.ljust(20), p.get_rootfs())
msg += ' BOOTIMG_DIR: %s\n' % self.bootimg_dir
msg += ' KERNEL_DIR: %s\n' % self.kernel_dir
diff --git a/scripts/lib/wic/plugins/source/bootimg-pcbios.py b/scripts/lib/wic/plugins/source/bootimg-pcbios.py
index 721c524..3c2dbc9 100644
--- a/scripts/lib/wic/plugins/source/bootimg-pcbios.py
+++ b/scripts/lib/wic/plugins/source/bootimg-pcbios.py
@@ -127,9 +127,9 @@ class BootimgPcbiosPlugin(SourcePlugin):
'prepares' the partition to be incorporated into the image.
In this case, prepare content for legacy bios boot partition.
"""
- def _has_syslinux(dir):
- if dir:
- syslinux = "%s/syslinux" % dir
+ def _has_syslinux(dirname):
+ if dirname:
+ syslinux = "%s/syslinux" % dirname
if os.path.exists(syslinux):
return True
return False
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 15/17] wic: get rid of listing properties
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (13 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 14/17] wic: fix pylint warning redefined-builtin Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 16/17] wic: fix short variable names Ed Bartosh
2015-09-02 10:58 ` [PATCH 17/17] image.py: rename _write_env -> _write_wic_env Ed Bartosh
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Functionality of listing and using properties of wic images
does not exist in the wic code. However, there are plenty of
help and usage content about it, which is very confusing.
Removed everything regarding image properties from wic codebase.
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
scripts/lib/wic/engine.py | 55 ++++++++++------------------
scripts/lib/wic/help.py | 93 ++++-------------------------------------------
scripts/wic | 13 ++-----
3 files changed, 30 insertions(+), 131 deletions(-)
diff --git a/scripts/lib/wic/engine.py b/scripts/lib/wic/engine.py
index d4a7be6..ce942ea 100644
--- a/scripts/lib/wic/engine.py
+++ b/scripts/lib/wic/engine.py
@@ -194,46 +194,29 @@ def wic_create(wks_file, rootfs_dir, bootimg_dir, kernel_dir,
print "\nThe image(s) were created using OE kickstart file:\n %s" % wks_file
-def wic_list(args, scripts_path, properties_file):
+def wic_list(args, scripts_path):
"""
- Print the complete list of properties defined by the image, or the
- possible values for a particular image property.
+ Print the list of images or source plugins.
"""
if len(args) < 1:
return False
- if len(args) == 1:
- if args[0] == "images":
- list_canned_images(scripts_path)
- return True
- elif args[0] == "source-plugins":
- list_source_plugins()
- return True
- elif args[0] == "properties":
- return True
- else:
- return False
-
- if len(args) == 2:
- if args[0] == "properties":
- wks_file = args[1]
- print "print properties contained in wks file: %s" % wks_file
- return True
- elif args[0] == "property":
- print "print property values for property: %s" % args[1]
- return True
- elif args[1] == "help":
- wks_file = args[0]
- fullpath = find_canned_image(scripts_path, wks_file)
- if not fullpath:
- print "No image named %s found, exiting. "\
- "(Use 'wic list images' to list available images, or "\
- "specify a fully-qualified OE kickstart (.wks) "\
- "filename)\n" % wks_file
- sys.exit(1)
- list_canned_image_help(scripts_path, fullpath)
- return True
- else:
- return False
+ if args == ["images"]:
+ list_canned_images(scripts_path)
+ return True
+ elif args == ["source-plugins"]:
+ list_source_plugins()
+ return True
+ elif len(args) == 2 and args[1] == "help":
+ wks_file = args[0]
+ fullpath = find_canned_image(scripts_path, wks_file)
+ if not fullpath:
+ print "No image named %s found, exiting. "\
+ "(Use 'wic list images' to list available images, or "\
+ "specify a fully-qualified OE kickstart (.wks) "\
+ "filename)\n" % wks_file
+ sys.exit(1)
+ list_canned_image_help(scripts_path, fullpath)
+ return True
return False
diff --git a/scripts/lib/wic/help.py b/scripts/lib/wic/help.py
index cd2176d..9a778b6 100644
--- a/scripts/lib/wic/help.py
+++ b/scripts/lib/wic/help.py
@@ -108,7 +108,7 @@ wic_usage = """
Current 'wic' commands are:
help Show help for command or one of the topics (see below)
create Create a new OpenEmbedded image
- list List available values for options and image properties
+ list List available canned images and source plugins
Help topics:
overview wic overview - General overview of wic
@@ -221,27 +221,19 @@ DESCRIPTION
The -c option is used to specify compressor utility to compress
an image. gzip, bzip2 and xz compressors are supported.
-
- The set of properties available for a given image type can be
- listed using the 'wic list' command.
"""
wic_list_usage = """
- List available OpenEmbedded image properties and values
+ List available OpenEmbedded images and source plugins
usage: wic list images
wic list <image> help
wic list source-plugins
- wic list properties
- wic list properties <wks file>
- wic list property <property>
- [-o <JSON PROPERTY FILE> | --outfile <JSON PROPERTY_FILE>]
This command enumerates the set of available canned images as well as
- help for those images. It also can be used to enumerate the complete
- set of possible values for a specified option or property needed by
- the image creation process.
+ help for those images. It also can be used to list of available source
+ plugins.
The first form enumerates all the available 'canned' images.
@@ -251,40 +243,23 @@ wic_list_usage = """
The third form enumerates all the available --sources (source
plugins).
- The fourth form enumerates all the possible values that exist and can
- be specified in an OE kickstart (wks) file.
-
- The fifth form enumerates all the possible options that exist for the
- set of properties specified in a given OE kickstart (ks) file.
-
- The final form enumerates all the possible values that exist and can
- be specified for any given OE kickstart (wks) property.
-
See 'wic help list' for more details.
"""
wic_list_help = """
NAME
- wic list - List available OpenEmbedded image properties and values
+ wic list - List available OpenEmbedded images and source plugins
SYNOPSIS
wic list images
wic list <image> help
wic list source-plugins
- wic list properties
- wic list properties <wks file>
- wic list property <property>
- [-o <JSON PROPERTY FILE> | --outfile <JSON PROPERTY_FILE>]
DESCRIPTION
- This command enumerates the complete set of possible values for a
- specified option or property needed by the image creation process.
-
This command enumerates the set of available canned images as well
- as help for those images. It also can be used to enumerate the
- complete set of possible values for a specified option or property
- needed by the image creation process.
+ as help for those images. It also can be used to list available
+ source plugins.
The first form enumerates all the available 'canned' images.
These are actually just the set of .wks files that have been moved
@@ -301,60 +276,6 @@ DESCRIPTION
sources listed by the 'list source-plugins' command. Users can
also add their own source plugins - see 'wic help plugins' for
details.
-
- The third form enumerates all the possible values that exist and
- can be specified in a OE kickstart (wks) file. The output of this
- can be used by the third form to print the description and
- possible values of a specific property.
-
- The fourth form enumerates all the possible options that exist for
- the set of properties specified in a given OE kickstart (wks)
- file. If the -o option is specified, the list of properties, in
- addition to being displayed, will be written to the specified file
- as a JSON object. In this case, the object will consist of the
- set of name:value pairs corresponding to the (possibly nested)
- dictionary of properties defined by the input statements used by
- the image. Some example output for the 'list <wks file>' command:
-
- $ wic list test.ks
- "part" : {
- "mountpoint" : "/"
- "fstype" : "ext3"
- }
- "part" : {
- "mountpoint" : "/home"
- "fstype" : "ext3"
- "offset" : "10000"
- }
- "bootloader" : {
- "type" : "efi"
- }
- .
- .
- .
-
- Each entry in the output consists of the name of the input element
- e.g. "part", followed by the properties defined for that
- element enclosed in braces. This information should provide
- sufficient information to create a complete user interface with.
-
- The final form enumerates all the possible values that exist and
- can be specified for any given OE kickstart (wks) property. If
- the -o option is specified, the list of values for the given
- property, in addition to being displayed, will be written to the
- specified file as a JSON object. In this case, the object will
- consist of the set of name:value pairs corresponding to the array
- of property values associated with the property.
-
- $ wic list property part
- ["mountpoint", "where the partition should be mounted"]
- ["fstype", "filesytem type of the partition"]
- ["ext3"]
- ["ext4"]
- ["btrfs"]
- ["swap"]
- ["offset", "offset of the partition within the image"]
-
"""
wic_plugins_help = """
diff --git a/scripts/wic b/scripts/wic
index c99c504..eb252a2 100755
--- a/scripts/wic
+++ b/scripts/wic
@@ -249,18 +249,13 @@ def wic_create_subcommand(args, usage_str):
def wic_list_subcommand(args, usage_str):
"""
- Command-line handling for listing available image properties and
- values. The real work is done by image.engine.wic_list()
+ Command-line handling for listing available images.
+ The real work is done by image.engine.wic_list()
"""
parser = optparse.OptionParser(usage=usage_str)
+ args = parser.parse_args(args)[1]
- parser.add_option("-o", "--outfile", action="store",
- dest="properties_file",
- help="dump the possible values for image properties to a JSON file")
-
- (options, args) = parser.parse_args(args)
-
- if not engine.wic_list(args, scripts_path, options.properties_file):
+ if not engine.wic_list(args, scripts_path):
logging.error("Bad list arguments, exiting\n")
parser.print_help()
sys.exit(1)
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 16/17] wic: fix short variable names
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (14 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 15/17] wic: get rid of listing properties Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
2015-09-02 10:58 ` [PATCH 17/17] image.py: rename _write_env -> _write_wic_env Ed Bartosh
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Made short variable names longer and more readable.
Fixed pylint warnings "Invalid variable name" and
"Invalid argument name".
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
scripts/lib/wic/conf.py | 4 +-
scripts/lib/wic/engine.py | 62 ++++-----
scripts/lib/wic/imager/direct.py | 70 +++++-----
scripts/lib/wic/kickstart/__init__.py | 66 ++++-----
.../lib/wic/kickstart/custom_commands/partition.py | 72 +++++-----
.../lib/wic/kickstart/custom_commands/wicboot.py | 12 +-
scripts/lib/wic/msger.py | 13 +-
scripts/lib/wic/plugin.py | 4 +-
scripts/lib/wic/pluginbase.py | 14 +-
scripts/lib/wic/plugins/imager/direct_plugin.py | 4 +-
scripts/lib/wic/plugins/source/bootimg-efi.py | 26 ++--
scripts/lib/wic/plugins/source/bootimg-pcbios.py | 28 ++--
.../lib/wic/plugins/source/isoimage-isohybrid.py | 32 ++---
scripts/lib/wic/utils/partitionedfs.py | 154 ++++++++++-----------
scripts/lib/wic/utils/runner.py | 16 +--
scripts/wic | 4 +-
16 files changed, 289 insertions(+), 292 deletions(-)
diff --git a/scripts/lib/wic/conf.py b/scripts/lib/wic/conf.py
index 942c0c1..1d4363a 100644
--- a/scripts/lib/wic/conf.py
+++ b/scripts/lib/wic/conf.py
@@ -87,9 +87,9 @@ class ConfigMgr(object):
if not ksconf:
return
- ks = kickstart.read_kickstart(ksconf)
+ ksobj = kickstart.read_kickstart(ksconf)
- self.create['ks'] = ks
+ self.create['ks'] = ksobj
self.create['name'] = os.path.splitext(os.path.basename(ksconf))[0]
self.create['name'] = misc.build_name(ksconf,
diff --git a/scripts/lib/wic/engine.py b/scripts/lib/wic/engine.py
index ce942ea..76b93e8 100644
--- a/scripts/lib/wic/engine.py
+++ b/scripts/lib/wic/engine.py
@@ -53,17 +53,17 @@ def verify_build_env():
CANNED_IMAGE_DIR = "lib/wic/canned-wks" # relative to scripts
SCRIPTS_CANNED_IMAGE_DIR = "scripts/" + CANNED_IMAGE_DIR
-def build_canned_image_list(dl):
+def build_canned_image_list(path):
layers_path = misc.get_bitbake_var("BBLAYERS")
canned_wks_layer_dirs = []
if layers_path is not None:
for layer_path in layers_path.split():
- path = os.path.join(layer_path, SCRIPTS_CANNED_IMAGE_DIR)
- canned_wks_layer_dirs.append(path)
+ cpath = os.path.join(layer_path, SCRIPTS_CANNED_IMAGE_DIR)
+ canned_wks_layer_dirs.append(cpath)
- path = os.path.join(dl, CANNED_IMAGE_DIR)
- canned_wks_layer_dirs.append(path)
+ cpath = os.path.join(path, CANNED_IMAGE_DIR)
+ canned_wks_layer_dirs.append(cpath)
return canned_wks_layer_dirs
@@ -99,14 +99,13 @@ def list_canned_images(scripts_path):
continue
if fname.endswith(".wks"):
fullpath = os.path.join(canned_wks_dir, fname)
- f = open(fullpath, "r")
- lines = f.readlines()
- for line in lines:
- desc = ""
- idx = line.find("short-description:")
- if idx != -1:
- desc = line[idx + len("short-description:"):].strip()
- break
+ with open(fullpath) as wks:
+ for line in wks:
+ desc = ""
+ idx = line.find("short-description:")
+ if idx != -1:
+ desc = line[idx + len("short-description:"):].strip()
+ break
basename = os.path.splitext(fname)[0]
print " %s\t\t%s" % (basename.ljust(30), desc)
@@ -115,24 +114,23 @@ def list_canned_image_help(scripts_path, fullpath):
"""
List the help and params in the specified canned image.
"""
- f = open(fullpath, "r")
- lines = f.readlines()
found = False
- for line in lines:
- if not found:
- idx = line.find("long-description:")
+ with open(fullpath) as wks:
+ for line in wks:
+ if not found:
+ idx = line.find("long-description:")
+ if idx != -1:
+ print
+ print line[idx + len("long-description:"):].strip()
+ found = True
+ continue
+ if not line.strip():
+ break
+ idx = line.find("#")
if idx != -1:
- print
- print line[idx + len("long-description:"):].strip()
- found = True
- continue
- if not line.strip():
- break
- idx = line.find("#")
- if idx != -1:
- print line[idx + len("#:"):].rstrip()
- else:
- break
+ print line[idx + len("#:"):].rstrip()
+ else:
+ break
def list_source_plugins():
@@ -186,10 +184,10 @@ def wic_create(wks_file, rootfs_dir, bootimg_dir, kernel_dir,
if debug:
msger.set_loglevel('debug')
- cr = creator.Creator()
+ crobj = creator.Creator()
- cr.main(["direct", native_sysroot, kernel_dir, bootimg_dir, rootfs_dir,
- wks_file, image_output_dir, oe_builddir, compressor or ""])
+ crobj.main(["direct", native_sysroot, kernel_dir, bootimg_dir, rootfs_dir,
+ wks_file, image_output_dir, oe_builddir, compressor or ""])
print "\nThe image(s) were created using OE kickstart file:\n %s" % wks_file
diff --git a/scripts/lib/wic/imager/direct.py b/scripts/lib/wic/imager/direct.py
index 761e436..31c0edc 100644
--- a/scripts/lib/wic/imager/direct.py
+++ b/scripts/lib/wic/imager/direct.py
@@ -80,11 +80,11 @@ class DirectImageCreator(BaseImageCreator):
in the partition table and logical partitions
"""
realnum = 0
- for n, p in enumerate(parts, 1):
- if not p.no_table:
+ for pnum, part in enumerate(parts, 1):
+ if not part.no_table:
realnum += 1
- if n == num:
- if p.no_table:
+ if pnum == num:
+ if part.no_table:
return 0
if self.ptable_format == 'msdos' and realnum > 3:
# account for logical partition numbering, ex. sda5..
@@ -154,9 +154,9 @@ class DirectImageCreator(BaseImageCreator):
if not self.ks.handler.partition.partitions:
partstr = "part / --size 1900 --ondisk sda --fstype=ext3"
args = partstr.split()
- pd = self.ks.handler.partition.parse(args[1:])
- if pd not in self.ks.handler.partition.partitions:
- self.ks.handler.partition.partitions.append(pd)
+ part = self.ks.handler.partition.parse(args[1:])
+ if part not in self.ks.handler.partition.partitions:
+ self.ks.handler.partition.partitions.append(part)
# partitions list from kickstart file
return kickstart.get_partitions(self.ks)
@@ -221,19 +221,19 @@ class DirectImageCreator(BaseImageCreator):
self.__image = Image(self.native_sysroot)
- for p in parts:
+ for part in parts:
# as a convenience, set source to the boot partition source
# instead of forcing it to be set via bootloader --source
- if not self.ks.handler.bootloader.source and p.mountpoint == "/boot":
- self.ks.handler.bootloader.source = p.source
+ if not self.ks.handler.bootloader.source and part.mountpoint == "/boot":
+ self.ks.handler.bootloader.source = part.source
fstab_path = self._write_fstab(self.rootfs_dir.get("ROOTFS_DIR"))
- for p in parts:
+ for part in parts:
# get rootfs size from bitbake variable if it's not set in .ks file
- if not p.size:
+ if not part.size:
# and if rootfs name is specified for the partition
- image_name = p.get_rootfs()
+ image_name = part.get_rootfs()
if image_name:
# Bitbake variable ROOTFS_SIZE is calculated in
# Image._get_rootfs_size method from meta/lib/oe/image.py
@@ -242,7 +242,7 @@ class DirectImageCreator(BaseImageCreator):
rsize_bb = get_bitbake_var('ROOTFS_SIZE', image_name)
if rsize_bb:
# convert from Kb to Mb
- p.size = int(rsize_bb) / 1024
+ part.size = int(rsize_bb) / 1024
# need to create the filesystems in order to get their
# sizes before we can add them and do the layout.
# Image.create() actually calls __format_disks() to create
@@ -250,22 +250,22 @@ class DirectImageCreator(BaseImageCreator):
# self.assemble() calls Image.assemble() which calls
# __write_partitition() for each partition to dd the fs
# into the partitions.
- p.prepare(self, self.workdir, self.oe_builddir, self.rootfs_dir,
- self.bootimg_dir, self.kernel_dir, self.native_sysroot)
-
-
- self.__image.add_partition(int(p.size),
- p.disk,
- p.mountpoint,
- p.source_file,
- p.fstype,
- p.label,
- fsopts=p.fsopts,
- boot=p.active,
- align=p.align,
- no_table=p.no_table,
- part_type=p.part_type,
- uuid=p.uuid)
+ part.prepare(self, self.workdir, self.oe_builddir, self.rootfs_dir,
+ self.bootimg_dir, self.kernel_dir, self.native_sysroot)
+
+
+ self.__image.add_partition(int(part.size),
+ part.disk,
+ part.mountpoint,
+ part.source_file,
+ part.fstype,
+ part.label,
+ fsopts=part.fsopts,
+ boot=part.active,
+ align=part.align,
+ no_table=part.no_table,
+ part_type=part.part_type,
+ uuid=part.uuid)
if fstab_path:
shutil.move(fstab_path + ".orig", fstab_path)
@@ -336,14 +336,14 @@ class DirectImageCreator(BaseImageCreator):
msg += ' %s\n\n' % full_path
msg += 'The following build artifacts were used to create the image(s):\n'
- for p in parts:
- if p.get_rootfs() is None:
+ for part in parts:
+ if part.get_rootfs() is None:
continue
- if p.mountpoint == '/':
+ if part.mountpoint == '/':
suffix = ':'
else:
- suffix = '["%s"]:' % (p.mountpoint or p.label)
- msg += ' ROOTFS_DIR%s%s\n' % (suffix.ljust(20), p.get_rootfs())
+ suffix = '["%s"]:' % (part.mountpoint or part.label)
+ msg += ' ROOTFS_DIR%s%s\n' % (suffix.ljust(20), part.get_rootfs())
msg += ' BOOTIMG_DIR: %s\n' % self.bootimg_dir
msg += ' KERNEL_DIR: %s\n' % self.kernel_dir
diff --git a/scripts/lib/wic/kickstart/__init__.py b/scripts/lib/wic/kickstart/__init__.py
index 111723b..c9b0e51 100644
--- a/scripts/lib/wic/kickstart/__init__.py
+++ b/scripts/lib/wic/kickstart/__init__.py
@@ -58,65 +58,65 @@ def read_kickstart(path):
def __init__(self):
superclass.__init__(self, mapping=commandMap[using_version])
- ks = ksparser.KickstartParser(KSHandlers(), errorsAreFatal=True)
+ kickstart = ksparser.KickstartParser(KSHandlers(), errorsAreFatal=True)
try:
- ks.readKickstart(path)
+ kickstart.readKickstart(path)
except (kserrors.KickstartParseError, kserrors.KickstartError), err:
msger.warning("Errors occurred when parsing kickstart file: %s\n" % path)
msger.error("%s" % err)
- return ks
+ return kickstart
-def get_image_size(ks, default=None):
+def get_image_size(kickstart, default=None):
__size = 0
- for p in ks.handler.partition.partitions:
- if p.mountpoint == "/" and p.size:
- __size = p.size
+ for part in kickstart.handler.partition.partitions:
+ if part.mountpoint == "/" and part.size:
+ __size = part.size
if __size > 0:
return int(__size) * 1024L
else:
return default
-def get_image_fstype(ks, default=None):
- for p in ks.handler.partition.partitions:
- if p.mountpoint == "/" and p.fstype:
- return p.fstype
+def get_image_fstype(kickstart, default=None):
+ for part in kickstart.handler.partition.partitions:
+ if part.mountpoint == "/" and part.fstype:
+ return part.fstype
return default
-def get_image_fsopts(ks, default=None):
- for p in ks.handler.partition.partitions:
- if p.mountpoint == "/" and p.fsopts:
- return p.fsopts
+def get_image_fsopts(kickstart, default=None):
+ for part in kickstart.handler.partition.partitions:
+ if part.mountpoint == "/" and part.fsopts:
+ return part.fsopts
return default
-def get_timeout(ks, default=None):
- if not hasattr(ks.handler.bootloader, "timeout"):
+def get_timeout(kickstart, default=None):
+ if not hasattr(kickstart.handler.bootloader, "timeout"):
return default
- if ks.handler.bootloader.timeout is None:
+ if kickstart.handler.bootloader.timeout is None:
return default
- return int(ks.handler.bootloader.timeout)
+ return int(kickstart.handler.bootloader.timeout)
-def get_kernel_args(ks, default="ro rd.live.image"):
- if not hasattr(ks.handler.bootloader, "appendLine"):
+def get_kernel_args(kickstart, default="ro rd.live.image"):
+ if not hasattr(kickstart.handler.bootloader, "appendLine"):
return default
- if ks.handler.bootloader.appendLine is None:
+ if kickstart.handler.bootloader.appendLine is None:
return default
- return "%s %s" %(default, ks.handler.bootloader.appendLine)
+ return "%s %s" %(default, kickstart.handler.bootloader.appendLine)
-def get_menu_args(ks, default=""):
- if not hasattr(ks.handler.bootloader, "menus"):
+def get_menu_args(kickstart, default=""):
+ if not hasattr(kickstart.handler.bootloader, "menus"):
return default
- if ks.handler.bootloader.menus in (None, ""):
+ if kickstart.handler.bootloader.menus in (None, ""):
return default
- return "%s" % ks.handler.bootloader.menus
+ return "%s" % kickstart.handler.bootloader.menus
-def get_default_kernel(ks, default=None):
- if not hasattr(ks.handler.bootloader, "default"):
+def get_default_kernel(kickstart, default=None):
+ if not hasattr(kickstart.handler.bootloader, "default"):
return default
- if not ks.handler.bootloader.default:
+ if not kickstart.handler.bootloader.default:
return default
- return ks.handler.bootloader.default
+ return kickstart.handler.bootloader.default
-def get_partitions(ks):
- return ks.handler.partition.partitions
+def get_partitions(kickstart):
+ return kickstart.handler.partition.partitions
diff --git a/scripts/lib/wic/kickstart/custom_commands/partition.py b/scripts/lib/wic/kickstart/custom_commands/partition.py
index bac2067..eee25a4 100644
--- a/scripts/lib/wic/kickstart/custom_commands/partition.py
+++ b/scripts/lib/wic/kickstart/custom_commands/partition.py
@@ -154,7 +154,7 @@ class Wic_PartData(FC4_PartData):
else:
return 0
- def prepare(self, cr, cr_workdir, oe_builddir, rootfs_dir, bootimg_dir,
+ def prepare(self, creator, cr_workdir, oe_builddir, rootfs_dir, bootimg_dir,
kernel_dir, native_sysroot):
"""
Prepare content for individual partitions, depending on
@@ -199,18 +199,18 @@ class Wic_PartData(FC4_PartData):
self._source_methods = pluginmgr.get_source_plugin_methods(\
self.source, partition_methods)
self._source_methods["do_configure_partition"](self, self.sourceparams_dict,
- cr, cr_workdir,
+ creator, cr_workdir,
oe_builddir,
bootimg_dir,
kernel_dir,
native_sysroot)
self._source_methods["do_stage_partition"](self, self.sourceparams_dict,
- cr, cr_workdir,
+ creator, cr_workdir,
oe_builddir,
bootimg_dir, kernel_dir,
native_sysroot)
self._source_methods["do_prepare_partition"](self, self.sourceparams_dict,
- cr, cr_workdir,
+ creator, cr_workdir,
oe_builddir,
bootimg_dir, kernel_dir, rootfs_dir,
native_sysroot)
@@ -441,21 +441,21 @@ class Wic_PartData(FC4_PartData):
msger.warning("Creating of an empty squashfs %s partition was attempted. " \
"Proceeding as requested." % self.mountpoint)
- fs = "%s/fs_%s.%s" % (cr_workdir, self.label, self.fstype)
- os.path.isfile(fs) and os.remove(fs)
+ path = "%s/fs_%s.%s" % (cr_workdir, self.label, self.fstype)
+ os.path.isfile(path) and os.remove(path)
# it is not possible to create a squashfs without source data,
# thus prepare an empty temp dir that is used as source
tmpdir = tempfile.mkdtemp()
squashfs_cmd = "mksquashfs %s %s -noappend" % \
- (tmpdir, fs)
+ (tmpdir, path)
exec_native_cmd(squashfs_cmd, native_sysroot)
os.rmdir(tmpdir)
# get the rootfs size in the right units for kickstart (kB)
- du_cmd = "du -Lbks %s" % fs
+ du_cmd = "du -Lbks %s" % path
out = exec_cmd(du_cmd)
fs_size = out.split()[0]
@@ -465,17 +465,17 @@ class Wic_PartData(FC4_PartData):
"""
Prepare a swap partition.
"""
- fs = "%s/fs.%s" % (cr_workdir, self.fstype)
+ path = "%s/fs.%s" % (cr_workdir, self.fstype)
dd_cmd = "dd if=/dev/zero of=%s bs=1k seek=%d count=0" % \
- (fs, self.size)
+ (path, self.size)
exec_cmd(dd_cmd)
import uuid
label_str = ""
if self.label:
label_str = "-L %s" % self.label
- mkswap_cmd = "mkswap %s -U %s %s" % (label_str, str(uuid.uuid1()), fs)
+ mkswap_cmd = "mkswap %s -U %s %s" % (label_str, str(uuid.uuid1()), path)
exec_native_cmd(mkswap_cmd, native_sysroot)
@@ -490,37 +490,37 @@ class Wic_Partition(FC4_Partition):
(option, value))
setattr(parser.values, option.dest, value)
- op = FC4_Partition._getParser(self)
+ parser = FC4_Partition._getParser(self)
# The alignment value is given in kBytes. e.g., value 8 means that
# the partition is aligned to start from 8096 byte boundary.
- op.add_option("--align", type="int", action="store", dest="align",
- default=None)
- op.add_option("--extoptions", type="string", action="store", dest="extopts",
- default=None)
- op.add_option("--part-type", type="string", action="store", dest="part_type",
- default=None)
+ parser.add_option("--align", type="int", action="store", dest="align",
+ default=None)
+ parser.add_option("--extoptions", type="string", action="store", dest="extopts",
+ default=None)
+ parser.add_option("--part-type", type="string", action="store", dest="part_type",
+ default=None)
# use specified source file to fill the partition
# and calculate partition size
- op.add_option("--source", type="string", action="store",
- dest="source", default=None)
+ parser.add_option("--source", type="string", action="store",
+ dest="source", default=None)
# comma-separated list of param=value pairs
- op.add_option("--sourceparams", type="string", action="store",
- dest="sourceparams", default=None)
+ parser.add_option("--sourceparams", type="string", action="store",
+ dest="sourceparams", default=None)
# use specified rootfs path to fill the partition
- op.add_option("--rootfs-dir", type="string", action="store",
- dest="rootfs", default=None)
+ parser.add_option("--rootfs-dir", type="string", action="store",
+ dest="rootfs", default=None)
# wether to add the partition in the partition table
- op.add_option("--no-table", dest="no_table", action="store_true",
- default=False)
+ parser.add_option("--no-table", dest="no_table", action="store_true",
+ default=False)
# extra space beyond the partition size
- op.add_option("--extra-space", dest="extra_space", action="store",
- type="size", nargs=1, default="10M")
- op.add_option("--overhead-factor", dest="overhead_factor",
- action="callback", callback=overhead_cb, type="float",
- nargs=1, default=1.3)
- op.add_option("--use-uuid", dest="use_uuid", action="store_true",
- default=False)
- op.add_option("--uuid")
-
- return op
+ parser.add_option("--extra-space", dest="extra_space", action="store",
+ type="size", nargs=1, default="10M")
+ parser.add_option("--overhead-factor", dest="overhead_factor",
+ action="callback", callback=overhead_cb, type="float",
+ nargs=1, default=1.3)
+ parser.add_option("--use-uuid", dest="use_uuid", action="store_true",
+ default=False)
+ parser.add_option("--uuid")
+
+ return parser
diff --git a/scripts/lib/wic/kickstart/custom_commands/wicboot.py b/scripts/lib/wic/kickstart/custom_commands/wicboot.py
index 0230df2..a3e1852 100644
--- a/scripts/lib/wic/kickstart/custom_commands/wicboot.py
+++ b/scripts/lib/wic/kickstart/custom_commands/wicboot.py
@@ -49,12 +49,12 @@ class Wic_Bootloader(F8_Bootloader):
return retval
def _getParser(self):
- op = F8_Bootloader._getParser(self)
- op.add_option("--menus", dest="menus")
- op.add_option("--ptable", dest="ptable", choices=("msdos", "gpt"),
- default="msdos")
+ parser = F8_Bootloader._getParser(self)
+ parser.add_option("--menus", dest="menus")
+ parser.add_option("--ptable", dest="ptable", choices=("msdos", "gpt"),
+ default="msdos")
# use specified source plugin to implement bootloader-specific methods
- op.add_option("--source", type="string", action="store",
+ parser.add_option("--source", type="string", action="store",
dest="source", default=None)
- return op
+ return parser
diff --git a/scripts/lib/wic/msger.py b/scripts/lib/wic/msger.py
index 1b60980..b737554 100644
--- a/scripts/lib/wic/msger.py
+++ b/scripts/lib/wic/msger.py
@@ -151,10 +151,10 @@ def _split_msg(head, msg):
msg = msg.lstrip()
head = '\r' + head
- m = PREFIX_RE.match(msg)
- if m:
- head += ' <%s>' % m.group(1)
- msg = m.group(2)
+ match = PREFIX_RE.match(msg)
+ if match:
+ head += ' <%s>' % match.group(1)
+ msg = match.group(2)
return head, msg
@@ -271,9 +271,8 @@ def set_logfile(fpath):
def _savelogf():
if LOG_FILE_FP:
- fp = open(LOG_FILE_FP, 'w')
- fp.write(LOG_CONTENT)
- fp.close()
+ with open(LOG_FILE_FP, 'w') as log:
+ log.write(LOG_CONTENT)
if LOG_FILE_FP is not None:
warning('duplicate log file configuration')
diff --git a/scripts/lib/wic/plugin.py b/scripts/lib/wic/plugin.py
index 7244989..ccfdfcb 100644
--- a/scripts/lib/wic/plugin.py
+++ b/scripts/lib/wic/plugin.py
@@ -48,7 +48,7 @@ class PluginMgr(object):
self.plugin_dir = scripts_path + PLUGIN_DIR
self.layers_path = None
- def _build_plugin_dir_list(self, dl, ptype):
+ def _build_plugin_dir_list(self, plugin_dir, ptype):
if self.layers_path is None:
self.layers_path = get_bitbake_var("BBLAYERS")
layer_dirs = []
@@ -58,7 +58,7 @@ class PluginMgr(object):
path = os.path.join(layer_path, SCRIPTS_PLUGIN_DIR, ptype)
layer_dirs.append(path)
- path = os.path.join(dl, ptype)
+ path = os.path.join(plugin_dir, ptype)
layer_dirs.append(path)
return layer_dirs
diff --git a/scripts/lib/wic/pluginbase.py b/scripts/lib/wic/pluginbase.py
index 6d96de2..ee8fe95 100644
--- a/scripts/lib/wic/pluginbase.py
+++ b/scripts/lib/wic/pluginbase.py
@@ -51,7 +51,7 @@ class SourcePlugin(_Plugin):
"""
@classmethod
- def do_install_disk(cls, disk, disk_name, cr, workdir, oe_builddir,
+ def do_install_disk(cls, disk, disk_name, creator, workdir, oe_builddir,
bootimg_dir, kernel_dir, native_sysroot):
"""
Called after all partitions have been prepared and assembled into a
@@ -61,7 +61,7 @@ class SourcePlugin(_Plugin):
msger.debug("SourcePlugin: do_install_disk: disk: %s" % disk_name)
@classmethod
- def do_stage_partition(cls, part, source_params, cr, cr_workdir,
+ def do_stage_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
native_sysroot):
"""
@@ -78,7 +78,7 @@ class SourcePlugin(_Plugin):
msger.debug("SourcePlugin: do_stage_partition: part: %s" % part)
@classmethod
- def do_configure_partition(cls, part, source_params, cr, cr_workdir,
+ def do_configure_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
native_sysroot):
"""
@@ -89,7 +89,7 @@ class SourcePlugin(_Plugin):
msger.debug("SourcePlugin: do_configure_partition: part: %s" % part)
@classmethod
- def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
+ def do_prepare_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir, rootfs_dir,
native_sysroot):
"""
@@ -99,9 +99,9 @@ class SourcePlugin(_Plugin):
msger.debug("SourcePlugin: do_prepare_partition: part: %s" % part)
def get_plugins(typen):
- ps = ImagerPlugin.get_plugins()
- if typen in ps:
- return ps[typen]
+ plugins = ImagerPlugin.get_plugins()
+ if typen in plugins:
+ return plugins[typen]
else:
return None
diff --git a/scripts/lib/wic/plugins/imager/direct_plugin.py b/scripts/lib/wic/plugins/imager/direct_plugin.py
index e9672fe..6d3f46c 100644
--- a/scripts/lib/wic/plugins/imager/direct_plugin.py
+++ b/scripts/lib/wic/plugins/imager/direct_plugin.py
@@ -50,8 +50,8 @@ class DirectPlugin(ImagerPlugin):
"""
krootfs_dir = {}
for rootfs_dir in rootfs_dirs.split(' '):
- k, v = rootfs_dir.split('=')
- krootfs_dir[k] = v
+ key, val = rootfs_dir.split('=')
+ krootfs_dir[key] = val
return krootfs_dir
diff --git a/scripts/lib/wic/plugins/source/bootimg-efi.py b/scripts/lib/wic/plugins/source/bootimg-efi.py
index b48cc83..fa63c6a 100644
--- a/scripts/lib/wic/plugins/source/bootimg-efi.py
+++ b/scripts/lib/wic/plugins/source/bootimg-efi.py
@@ -41,16 +41,16 @@ class BootimgEFIPlugin(SourcePlugin):
name = 'bootimg-efi'
@classmethod
- def do_configure_grubefi(cls, hdddir, cr, cr_workdir):
+ def do_configure_grubefi(cls, hdddir, creator, cr_workdir):
"""
Create loader-specific (grub-efi) config
"""
- options = cr.ks.handler.bootloader.appendLine
+ options = creator.ks.handler.bootloader.appendLine
grubefi_conf = ""
grubefi_conf += "serial --unit=0 --speed=115200 --word=8 --parity=no --stop=1\n"
grubefi_conf += "default=boot\n"
- timeout = kickstart.get_timeout(cr.ks)
+ timeout = kickstart.get_timeout(creator.ks)
if not timeout:
timeout = 0
grubefi_conf += "timeout=%s\n" % timeout
@@ -59,7 +59,7 @@ class BootimgEFIPlugin(SourcePlugin):
kernel = "/bzImage"
grubefi_conf += "linux %s root=%s rootwait %s\n" \
- % (kernel, cr.rootdev, options)
+ % (kernel, creator.rootdev, options)
grubefi_conf += "}\n"
msger.debug("Writing grubefi config %s/hdd/boot/EFI/BOOT/grub.cfg" \
@@ -69,7 +69,7 @@ class BootimgEFIPlugin(SourcePlugin):
cfg.close()
@classmethod
- def do_configure_gummiboot(cls, hdddir, cr, cr_workdir):
+ def do_configure_gummiboot(cls, hdddir, creator, cr_workdir):
"""
Create loader-specific (gummiboot) config
"""
@@ -79,9 +79,9 @@ class BootimgEFIPlugin(SourcePlugin):
install_cmd = "install -d %s/loader/entries" % hdddir
exec_cmd(install_cmd)
- options = cr.ks.handler.bootloader.appendLine
+ options = creator.ks.handler.bootloader.appendLine
- timeout = kickstart.get_timeout(cr.ks)
+ timeout = kickstart.get_timeout(creator.ks)
if not timeout:
timeout = 0
@@ -100,7 +100,7 @@ class BootimgEFIPlugin(SourcePlugin):
boot_conf = ""
boot_conf += "title boot\n"
boot_conf += "linux %s\n" % kernel
- boot_conf += "options LABEL=Boot root=%s %s\n" % (cr.rootdev, options)
+ boot_conf += "options LABEL=Boot root=%s %s\n" % (creator.rootdev, options)
msger.debug("Writing gummiboot config %s/hdd/boot/loader/entries/boot.conf" \
% cr_workdir)
@@ -110,7 +110,7 @@ class BootimgEFIPlugin(SourcePlugin):
@classmethod
- def do_configure_partition(cls, part, source_params, cr, cr_workdir,
+ def do_configure_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
native_sysroot):
"""
@@ -125,9 +125,9 @@ class BootimgEFIPlugin(SourcePlugin):
try:
if source_params['loader'] == 'grub-efi':
- cls.do_configure_grubefi(hdddir, cr, cr_workdir)
+ cls.do_configure_grubefi(hdddir, creator, cr_workdir)
elif source_params['loader'] == 'gummiboot':
- cls.do_configure_gummiboot(hdddir, cr, cr_workdir)
+ cls.do_configure_gummiboot(hdddir, creator, cr_workdir)
else:
msger.error("unrecognized bootimg-efi loader: %s" % source_params['loader'])
except KeyError:
@@ -135,7 +135,7 @@ class BootimgEFIPlugin(SourcePlugin):
@classmethod
- def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
+ def do_prepare_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
rootfs_dir, native_sysroot):
"""
@@ -148,7 +148,7 @@ class BootimgEFIPlugin(SourcePlugin):
if not bootimg_dir:
msger.error("Couldn't find HDDDIR, exiting\n")
# just so the result notes display it
- cr.set_bootimg_dir(bootimg_dir)
+ creator.set_bootimg_dir(bootimg_dir)
staging_kernel_dir = kernel_dir
diff --git a/scripts/lib/wic/plugins/source/bootimg-pcbios.py b/scripts/lib/wic/plugins/source/bootimg-pcbios.py
index 3c2dbc9..96ed54d 100644
--- a/scripts/lib/wic/plugins/source/bootimg-pcbios.py
+++ b/scripts/lib/wic/plugins/source/bootimg-pcbios.py
@@ -41,36 +41,36 @@ class BootimgPcbiosPlugin(SourcePlugin):
name = 'bootimg-pcbios'
@classmethod
- def do_install_disk(cls, disk, disk_name, cr, workdir, oe_builddir,
+ def do_install_disk(cls, disk, disk_name, creator, workdir, oe_builddir,
bootimg_dir, kernel_dir, native_sysroot):
"""
Called after all partitions have been prepared and assembled into a
disk image. In this case, we install the MBR.
"""
mbrfile = "%s/syslinux/" % bootimg_dir
- if cr.ptable_format == 'msdos':
+ if creator.ptable_format == 'msdos':
mbrfile += "mbr.bin"
- elif cr.ptable_format == 'gpt':
+ elif creator.ptable_format == 'gpt':
mbrfile += "gptmbr.bin"
else:
- msger.error("Unsupported partition table: %s" % cr.ptable_format)
+ msger.error("Unsupported partition table: %s" % creator.ptable_format)
if not os.path.exists(mbrfile):
msger.error("Couldn't find %s. If using the -e option, do you "
"have the right MACHINE set in local.conf? If not, "
"is the bootimg_dir path correct?" % mbrfile)
- full_path = cr._full_path(workdir, disk_name, "direct")
+ full_path = creator._full_path(workdir, disk_name, "direct")
msger.debug("Installing MBR on disk %s as %s with size %s bytes" \
% (disk_name, full_path, disk['min_size']))
- rc = runner.show(['dd', 'if=%s' % mbrfile,
- 'of=%s' % full_path, 'conv=notrunc'])
- if rc != 0:
+ rcode = runner.show(['dd', 'if=%s' % mbrfile,
+ 'of=%s' % full_path, 'conv=notrunc'])
+ if rcode != 0:
raise ImageError("Unable to set MBR to %s" % full_path)
@classmethod
- def do_configure_partition(cls, part, source_params, cr, cr_workdir,
+ def do_configure_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
native_sysroot):
"""
@@ -89,11 +89,11 @@ class BootimgPcbiosPlugin(SourcePlugin):
else:
splashline = ""
- options = cr.ks.handler.bootloader.appendLine
+ options = creator.ks.handler.bootloader.appendLine
syslinux_conf = ""
syslinux_conf += "PROMPT 0\n"
- timeout = kickstart.get_timeout(cr.ks)
+ timeout = kickstart.get_timeout(creator.ks)
if not timeout:
timeout = 0
syslinux_conf += "TIMEOUT " + str(timeout) + "\n"
@@ -110,7 +110,7 @@ class BootimgPcbiosPlugin(SourcePlugin):
syslinux_conf += "KERNEL " + kernel + "\n"
syslinux_conf += "APPEND label=boot root=%s %s\n" % \
- (cr.rootdev, options)
+ (creator.rootdev, options)
msger.debug("Writing syslinux config %s/hdd/boot/syslinux.cfg" \
% cr_workdir)
@@ -119,7 +119,7 @@ class BootimgPcbiosPlugin(SourcePlugin):
cfg.close()
@classmethod
- def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
+ def do_prepare_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
rootfs_dir, native_sysroot):
"""
@@ -141,7 +141,7 @@ class BootimgPcbiosPlugin(SourcePlugin):
if not _has_syslinux(bootimg_dir):
msger.error("Please build syslinux first\n")
# just so the result notes display it
- cr.set_bootimg_dir(bootimg_dir)
+ creator.set_bootimg_dir(bootimg_dir)
staging_kernel_dir = kernel_dir
diff --git a/scripts/lib/wic/plugins/source/isoimage-isohybrid.py b/scripts/lib/wic/plugins/source/isoimage-isohybrid.py
index 1cee906..9472d8a 100644
--- a/scripts/lib/wic/plugins/source/isoimage-isohybrid.py
+++ b/scripts/lib/wic/plugins/source/isoimage-isohybrid.py
@@ -54,7 +54,7 @@ class IsoImagePlugin(SourcePlugin):
name = 'isoimage-isohybrid'
@classmethod
- def do_configure_syslinux(cls, cr, cr_workdir):
+ def do_configure_syslinux(cls, creator, cr_workdir):
"""
Create loader-specific (syslinux) config
"""
@@ -64,9 +64,9 @@ class IsoImagePlugin(SourcePlugin):
else:
splashline = ""
- options = cr.ks.handler.bootloader.appendLine
+ options = creator.ks.handler.bootloader.appendLine
- timeout = kickstart.get_timeout(cr.ks, 10)
+ timeout = kickstart.get_timeout(creator.ks, 10)
syslinux_conf = ""
syslinux_conf += "PROMPT 0\n"
@@ -90,7 +90,7 @@ class IsoImagePlugin(SourcePlugin):
cfg.write(syslinux_conf)
@classmethod
- def do_configure_grubefi(cls, part, cr, cr_workdir):
+ def do_configure_grubefi(cls, part, creator, cr_workdir):
"""
Create loader-specific (grub-efi) config
"""
@@ -100,13 +100,13 @@ class IsoImagePlugin(SourcePlugin):
else:
splashline = ""
- options = cr.ks.handler.bootloader.appendLine
+ options = creator.ks.handler.bootloader.appendLine
grubefi_conf = ""
grubefi_conf += "serial --unit=0 --speed=115200 --word=8 "
grubefi_conf += "--parity=no --stop=1\n"
grubefi_conf += "default=boot\n"
- timeout = kickstart.get_timeout(cr.ks, 10)
+ timeout = kickstart.get_timeout(creator.ks, 10)
grubefi_conf += "timeout=%s\n" % timeout
grubefi_conf += "\n"
grubefi_conf += "search --set=root --label %s " % part.label
@@ -185,7 +185,7 @@ class IsoImagePlugin(SourcePlugin):
return initrd
@classmethod
- def do_stage_partition(cls, part, source_params, cr, cr_workdir,
+ def do_stage_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
native_sysroot):
"""
@@ -231,7 +231,7 @@ class IsoImagePlugin(SourcePlugin):
exec_cmd("bitbake mtools-native")
@classmethod
- def do_configure_partition(cls, part, source_params, cr, cr_workdir,
+ def do_configure_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
native_sysroot):
"""
@@ -249,11 +249,11 @@ class IsoImagePlugin(SourcePlugin):
msger.debug("%s" % source_params)
if 'image_name' in source_params and \
source_params['image_name'].strip():
- cr.name = source_params['image_name'].strip()
- msger.debug("The name of the image is: %s" % cr.name)
+ creator.name = source_params['image_name'].strip()
+ msger.debug("The name of the image is: %s" % creator.name)
@classmethod
- def do_prepare_partition(cls, part, source_params, cr, cr_workdir,
+ def do_prepare_partition(cls, part, source_params, creator, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
rootfs_dir, native_sysroot):
"""
@@ -353,7 +353,7 @@ class IsoImagePlugin(SourcePlugin):
exec_cmd(install_cmd)
if not os.path.isfile("%s/EFI/BOOT/boot.cfg" % bootimg_dir):
- cls.do_configure_grubefi(part, cr, bootimg_dir)
+ cls.do_configure_grubefi(part, creator, bootimg_dir)
# Builds bootx64.efi/bootia32.efi if ISODIR didn't exist or
# didn't contains it
@@ -463,7 +463,7 @@ class IsoImagePlugin(SourcePlugin):
install_cmd = "install -d %s/isolinux" % isodir
exec_cmd(install_cmd)
- cls.do_configure_syslinux(cr, cr_workdir)
+ cls.do_configure_syslinux(creator, cr_workdir)
install_cmd = "install -m 444 %s/syslinux/ldlinux.sys " % syslinux_dir
install_cmd += "%s/isolinux/ldlinux.sys" % isodir
@@ -508,7 +508,7 @@ class IsoImagePlugin(SourcePlugin):
part.set_source_file(iso_img)
@classmethod
- def do_install_disk(cls, disk, disk_name, cr, workdir, oe_builddir,
+ def do_install_disk(cls, disk, disk_name, creator, workdir, oe_builddir,
bootimg_dir, kernel_dir, native_sysroot):
"""
Called after all partitions have been prepared and assembled into a
@@ -516,9 +516,9 @@ class IsoImagePlugin(SourcePlugin):
utility for booting via BIOS from disk storage devices.
"""
- full_path = cr._full_path(workdir, disk_name, "direct")
+ full_path = creator._full_path(workdir, disk_name, "direct")
iso_img = "%s.p1" % full_path
- full_path_iso = cr._full_path(workdir, disk_name, "iso")
+ full_path_iso = creator._full_path(workdir, disk_name, "iso")
isohybrid_cmd = "isohybrid -u %s" % iso_img
msger.debug("running command: %s" % \
diff --git a/scripts/lib/wic/utils/partitionedfs.py b/scripts/lib/wic/utils/partitionedfs.py
index 2f884a3..5a103bb 100644
--- a/scripts/lib/wic/utils/partitionedfs.py
+++ b/scripts/lib/wic/utils/partitionedfs.py
@@ -129,14 +129,14 @@ class Image(object):
self._partitions_layed_out = True
# Go through partitions in the order they are added in .ks file
- for n in range(len(self.partitions)):
- p = self.partitions[n]
+ for num in range(len(self.partitions)):
+ part = self.partitions[num]
- if not self.disks.has_key(p['disk_name']):
+ if not self.disks.has_key(part['disk_name']):
raise ImageError("No disk %s for partition %s" \
- % (p['disk_name'], p['mountpoint']))
+ % (part['disk_name'], part['mountpoint']))
- if ptable_format == 'msdos' and p['part_type']:
+ if ptable_format == 'msdos' and part['part_type']:
# The --part-type can also be implemented for MBR partitions,
# in which case it would map to the 1-byte "partition type"
# filed at offset 3 of the partition entry.
@@ -144,79 +144,79 @@ class Image(object):
"implemented for msdos partitions")
# Get the disk where the partition is located
- d = self.disks[p['disk_name']]
- d['numpart'] += 1
- if not p['no_table']:
- d['realpart'] += 1
- d['ptable_format'] = ptable_format
+ disk = self.disks[part['disk_name']]
+ disk['numpart'] += 1
+ if not part['no_table']:
+ disk['realpart'] += 1
+ disk['ptable_format'] = ptable_format
- if d['numpart'] == 1:
+ if disk['numpart'] == 1:
if ptable_format == "msdos":
overhead = MBR_OVERHEAD
elif ptable_format == "gpt":
overhead = GPT_OVERHEAD
# Skip one sector required for the partitioning scheme overhead
- d['offset'] += overhead
+ disk['offset'] += overhead
- if d['realpart'] > 3:
+ if disk['realpart'] > 3:
# Reserve a sector for EBR for every logical partition
# before alignment is performed.
if ptable_format == "msdos":
- d['offset'] += 1
+ disk['offset'] += 1
- if p['align']:
+ if part['align']:
# If not first partition and we do have alignment set we need
# to align the partition.
# FIXME: This leaves a empty spaces to the disk. To fill the
# gaps we could enlargea the previous partition?
# Calc how much the alignment is off.
- align_sectors = d['offset'] % (p['align'] * 1024 / self.sector_size)
+ align_sectors = disk['offset'] % (part['align'] * 1024 / self.sector_size)
if align_sectors:
# If partition is not aligned as required, we need
# to move forward to the next alignment point
- align_sectors = (p['align'] * 1024 / self.sector_size) - align_sectors
+ align_sectors = (part['align'] * 1024 / self.sector_size) - align_sectors
msger.debug("Realignment for %s%s with %s sectors, original"
" offset %s, target alignment is %sK." %
- (p['disk_name'], d['numpart'], align_sectors,
- d['offset'], p['align']))
+ (part['disk_name'], disk['numpart'], align_sectors,
+ disk['offset'], part['align']))
# increase the offset so we actually start the partition on right alignment
- d['offset'] += align_sectors
+ disk['offset'] += align_sectors
- p['start'] = d['offset']
- d['offset'] += p['size']
+ part['start'] = disk['offset']
+ disk['offset'] += part['size']
- p['type'] = 'primary'
- if not p['no_table']:
- p['num'] = d['realpart']
+ part['type'] = 'primary'
+ if not part['no_table']:
+ part['num'] = disk['realpart']
else:
- p['num'] = 0
+ part['num'] = 0
- if d['ptable_format'] == "msdos":
- if d['realpart'] > 3:
- p['type'] = 'logical'
- p['num'] = d['realpart'] + 1
+ if disk['ptable_format'] == "msdos":
+ if disk['realpart'] > 3:
+ part['type'] = 'logical'
+ part['num'] = disk['realpart'] + 1
- d['partitions'].append(n)
+ disk['partitions'].append(num)
msger.debug("Assigned %s to %s%d, sectors range %d-%d size %d "
"sectors (%d bytes)." \
- % (p['mountpoint'], p['disk_name'], p['num'],
- p['start'], p['start'] + p['size'] - 1,
- p['size'], p['size'] * self.sector_size))
+ % (part['mountpoint'], part['disk_name'], part['num'],
+ part['start'], part['start'] + part['size'] - 1,
+ part['size'], part['size'] * self.sector_size))
# Once all the partitions have been layed out, we can calculate the
# minumim disk sizes.
- for d in self.disks.values():
- d['min_size'] = d['offset']
- if d['ptable_format'] == "gpt":
- d['min_size'] += GPT_OVERHEAD
+ for disk in self.disks.values():
+ disk['min_size'] = disk['offset']
+ if disk['ptable_format'] == "gpt":
+ disk['min_size'] += GPT_OVERHEAD
- d['min_size'] *= self.sector_size
+ disk['min_size'] *= self.sector_size
def __create_partition(self, device, parttype, fstype, start, size):
""" Create a partition on an image described by the 'device' object. """
@@ -237,21 +237,21 @@ class Image(object):
self.layout_partitions()
for dev in self.disks.keys():
- d = self.disks[dev]
+ disk = self.disks[dev]
msger.debug("Initializing partition table for %s" % \
- (d['disk'].device))
+ (disk['disk'].device))
exec_native_cmd("parted -s %s mklabel %s" % \
- (d['disk'].device, d['ptable_format']),
+ (disk['disk'].device, disk['ptable_format']),
self.native_sysroot)
msger.debug("Creating partitions")
- for p in self.partitions:
- if p['num'] == 0:
+ for part in self.partitions:
+ if part['num'] == 0:
continue
- d = self.disks[p['disk_name']]
- if d['ptable_format'] == "msdos" and p['num'] == 5:
+ disk = self.disks[part['disk_name']]
+ if disk['ptable_format'] == "msdos" and part['num'] == 5:
# Create an extended partition (note: extended
# partition is described in MBR and contains all
# logical partitions). The logical partitions save a
@@ -263,17 +263,17 @@ class Image(object):
# starts a sector before the first logical partition,
# add a sector at the back, so that there is enough
# room for all logical partitions.
- self.__create_partition(d['disk'].device, "extended",
- None, p['start'] - 1,
- d['offset'] - p['start'] + 1)
+ self.__create_partition(disk['disk'].device, "extended",
+ None, part['start'] - 1,
+ disk['offset'] - part['start'] + 1)
- if p['fstype'] == "swap":
+ if part['fstype'] == "swap":
parted_fs_type = "linux-swap"
- elif p['fstype'] == "vfat":
+ elif part['fstype'] == "vfat":
parted_fs_type = "fat32"
- elif p['fstype'] == "msdos":
+ elif part['fstype'] == "msdos":
parted_fs_type = "fat16"
- elif p['fstype'] == "ontrackdm6aux3":
+ elif part['fstype'] == "ontrackdm6aux3":
parted_fs_type = "ontrackdm6aux3"
else:
# Type for ext2/ext3/ext4/btrfs
@@ -281,55 +281,55 @@ class Image(object):
# Boot ROM of OMAP boards require vfat boot partition to have an
# even number of sectors.
- if p['mountpoint'] == "/boot" and p['fstype'] in ["vfat", "msdos"] \
- and p['size'] % 2:
+ if part['mountpoint'] == "/boot" and part['fstype'] in ["vfat", "msdos"] \
+ and part['size'] % 2:
msger.debug("Substracting one sector from '%s' partition to " \
"get even number of sectors for the partition" % \
- p['mountpoint'])
- p['size'] -= 1
+ part['mountpoint'])
+ part['size'] -= 1
- self.__create_partition(d['disk'].device, p['type'],
- parted_fs_type, p['start'], p['size'])
+ self.__create_partition(disk['disk'].device, part['type'],
+ parted_fs_type, part['start'], part['size'])
- if p['part_type']:
+ if part['part_type']:
msger.debug("partition %d: set type UID to %s" % \
- (p['num'], p['part_type']))
+ (part['num'], part['part_type']))
exec_native_cmd("sgdisk --typecode=%d:%s %s" % \
- (p['num'], p['part_type'],
- d['disk'].device), self.native_sysroot)
+ (part['num'], part['part_type'],
+ disk['disk'].device), self.native_sysroot)
- if p['uuid']:
+ if part['uuid']:
msger.debug("partition %d: set UUID to %s" % \
- (p['num'], p['uuid']))
+ (part['num'], part['uuid']))
exec_native_cmd("sgdisk --partition-guid=%d:%s %s" % \
- (p['num'], p['uuid'], d['disk'].device),
+ (part['num'], part['uuid'], disk['disk'].device),
self.native_sysroot)
- if p['boot']:
- flag_name = "legacy_boot" if d['ptable_format'] == 'gpt' else "boot"
+ if part['boot']:
+ flag_name = "legacy_boot" if disk['ptable_format'] == 'gpt' else "boot"
msger.debug("Set '%s' flag for partition '%s' on disk '%s'" % \
- (flag_name, p['num'], d['disk'].device))
+ (flag_name, part['num'], disk['disk'].device))
exec_native_cmd("parted -s %s set %d %s on" % \
- (d['disk'].device, p['num'], flag_name),
+ (disk['disk'].device, part['num'], flag_name),
self.native_sysroot)
# Parted defaults to enabling the lba flag for fat16 partitions,
# which causes compatibility issues with some firmware (and really
# isn't necessary).
if parted_fs_type == "fat16":
- if d['ptable_format'] == 'msdos':
+ if disk['ptable_format'] == 'msdos':
msger.debug("Disable 'lba' flag for partition '%s' on disk '%s'" % \
- (p['num'], d['disk'].device))
+ (part['num'], disk['disk'].device))
exec_native_cmd("parted -s %s set %d lba off" % \
- (d['disk'].device, p['num']),
+ (disk['disk'].device, part['num']),
self.native_sysroot)
def cleanup(self):
if self.disks:
for dev in self.disks:
- d = self.disks[dev]
+ disk = self.disks[dev]
try:
- d['disk'].cleanup()
+ disk['disk'].cleanup()
except:
pass
@@ -354,8 +354,8 @@ class Image(object):
def create(self):
for dev in self.disks.keys():
- d = self.disks[dev]
- d['disk'].create()
+ disk = self.disks[dev]
+ disk['disk'].create()
self.__format_disks()
diff --git a/scripts/lib/wic/utils/runner.py b/scripts/lib/wic/utils/runner.py
index f6a1d08..7431917 100644
--- a/scripts/lib/wic/utils/runner.py
+++ b/scripts/lib/wic/utils/runner.py
@@ -62,13 +62,13 @@ def runtool(cmdln_or_args, catch=1):
serr = subprocess.STDOUT
try:
- p = subprocess.Popen(cmdln_or_args, stdout=sout,
- stderr=serr, shell=shell)
- (sout, serr) = p.communicate()
+ process = subprocess.Popen(cmdln_or_args, stdout=sout,
+ stderr=serr, shell=shell)
+ (sout, serr) = process.communicate()
# combine stdout and stderr, filter None out
out = ''.join(filter(None, [sout, serr]))
- except OSError, e:
- if e.errno == 2:
+ except OSError, err:
+ if err.errno == 2:
# [Errno 2] No such file or directory
msger.error('Cannot run command: %s, lost dependency?' % cmd)
else:
@@ -77,12 +77,12 @@ def runtool(cmdln_or_args, catch=1):
if catch != 3:
os.close(dev_null)
- return (p.returncode, out)
+ return (process.returncode, out)
def show(cmdln_or_args):
# show all the message using msger.verbose
- rc, out = runtool(cmdln_or_args, catch=3)
+ rcode, out = runtool(cmdln_or_args, catch=3)
if isinstance(cmdln_or_args, list):
cmd = ' '.join(cmdln_or_args)
@@ -100,7 +100,7 @@ def show(cmdln_or_args):
msg += '\n +----------------'
msger.verbose(msg)
- return rc
+ return rcode
def outs(cmdln_or_args, catch=1):
# get the outputs of tools
diff --git a/scripts/wic b/scripts/wic
index eb252a2..7ad2b19 100755
--- a/scripts/wic
+++ b/scripts/wic
@@ -62,9 +62,9 @@ def rootfs_dir_to_args(krootfs_dir):
Get a rootfs_dir dict and serialize to string
"""
rootfs_dir = ''
- for k, v in krootfs_dir.items():
+ for key, val in krootfs_dir.items():
rootfs_dir += ' '
- rootfs_dir += '='.join([k, v])
+ rootfs_dir += '='.join([key, val])
return rootfs_dir.strip()
def callback_rootfs_dir(option, opt, value, parser):
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread* [PATCH 17/17] image.py: rename _write_env -> _write_wic_env
2015-09-02 10:58 [PATCH 00/17] wic improvements Ed Bartosh
` (15 preceding siblings ...)
2015-09-02 10:58 ` [PATCH 16/17] wic: fix short variable names Ed Bartosh
@ 2015-09-02 10:58 ` Ed Bartosh
16 siblings, 0 replies; 18+ messages in thread
From: Ed Bartosh @ 2015-09-02 10:58 UTC (permalink / raw)
To: openembedded-core
Renamed this function as it's too generic name for it.
It writes variables, which are used by wic to .env file,
so _write_wic_env is better name for it.
Thanks Christopher Larson for poining out to this.
Signed-off-by: Ed Bartosh <ed.bartosh@linux.intel.com>
---
meta/lib/oe/image.py | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/meta/lib/oe/image.py b/meta/lib/oe/image.py
index 95c62dc..5b77306 100644
--- a/meta/lib/oe/image.py
+++ b/meta/lib/oe/image.py
@@ -326,7 +326,7 @@ class Image(ImageDepGraph):
return image_cmd_groups
- def _write_env(self):
+ def _write_wic_env(self):
"""
Write environment variables used by wic
to tmp/sysroots/<machine>/imgdata/<image>.env
@@ -353,7 +353,7 @@ class Image(ImageDepGraph):
image_cmd_groups = self._get_imagecmds()
- self._write_env()
+ self._write_wic_env()
for image_cmds in image_cmd_groups:
# create the images in parallel
--
2.1.4
^ permalink raw reply related [flat|nested] 18+ messages in thread